diff --git a/README.md b/README.md index 8e1a159c..55519ab3 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ These are all in the **Mantle** dropdown: | Tool | What it does | Docs | |---|---|---| | **Build a vehicle...** | Makes a drivable vehicle from your own 3D model. | [Vehicles](https://mantleplatform.com/docs/creators/vehicles/) | -| **Build a weapon...** | Turns a 3D model into a gun, bow, blade or other weapon. | [Weapons](https://mantleplatform.com/docs/creators/weapons/) | +| **Build an item...** | Turns a 3D model into an item: a weapon (gun, bow, blade and more), a consumable, or a usable item your script gives a purpose. Consumables and usable items can bring their own animations. | [Weapons](https://mantleplatform.com/docs/creators/weapons/) | | **Cosmetics...** | Publishes avatars, hair, clothing, accessories and emotes. | [Avatars and emotes](https://mantleplatform.com/docs/creators/avatars-emotes/), [Clothing](https://mantleplatform.com/docs/creators/clothing/) | | **Library...** | Finds vehicles, weapons and script packages, yours or other creators' public ones, and adds them to your place. | [Script packages](https://mantleplatform.com/docs/creators/script-packages/) | | **Voxelize selected meshes** | Turns meshes into a block world, or smooth ground, that players can dig and build in. | [Block worlds](https://mantleplatform.com/docs/creators/block-worlds/) | diff --git a/Resources/ScriptApi/mantle.d.luau b/Resources/ScriptApi/mantle.d.luau index e4159b00..42412449 100644 --- a/Resources/ScriptApi/mantle.d.luau +++ b/Resources/ScriptApi/mantle.d.luau @@ -139,7 +139,7 @@ declare extern type Entity with function ApplyAngularImpulse(self, impulse: Vector3): () --- Push a physics entity: impulse is in kg*cm/s along the world axes, so its velocity changes by impulse / Mass. Does nothing while it is Anchored. Errors on an entity with no physics block. (server only) function ApplyImpulse(self, impulse: Vector3): () - --- Stick this entity to target so it follows it wherever it goes: a car, a lift or moving platform, an NPC, or a player's character (player.Character). It is sent to players once and then rides by itself, never lagging behind. options.Offset is where it sits in the target's own space (cm, (0, 0, 0) by default: the target's middle, or the bone's), options.Rotation its turn there as (pitch, yaw, roll) degrees, and options.Bone a bone or socket of the target's skeleton ("hand_r", "head", "spine_03") to follow instead of the whole target; Bone = "HeldItem" follows where the player's held tool or gun sits, so a light attached there points where they aim. Attaching again moves it to the new target or offset. What can be attached: an entity a script may move (a clone, an Assets:Spawn mesh, a light, an effect, a place entity marked "dynamic", a physics entity); a player's character, an NPC or a vehicle can't be (attach things to them instead). A physics entity is held Anchored while attached, and Detach gives it back what Anchored was, so a crate let go off a truck falls. Attached to a player, an NPC, a vehicle or a physics entity it blocks nothing, so it can't push what carries it (overlaps, Touched and raycasts still find it); attached to anything else it keeps its collision, so a floor riding a lift still holds players up. If the target goes (destroyed, or a player's character replaced when they respawn or leave), the attachment ends and the entity stays where it was. Setting its Position or Rotation, or tweening either, detaches it first. On a player's character Offset may be at most 50 cm and the entity at most 2 m across; anywhere else Offset may be up to 100 m. A place holds at most 256 attachments. Errors for an unknown Bone, a target that rides this entity, or past these limits. On the server everyone sees it; on a client only that player does (a physics entity is attached by a server script only). An attached entity can't be cloned. Example, a flashlight: `local light = Lights:Spawn("Spot", Vector3.new(0, 0, 0)) light:AttachTo(player.Character, {Bone = "HeldItem", Offset = Vector3.new(0, 20, 0)})`. + --- Stick this entity to target so it follows it wherever it goes: a car, a lift or moving platform, an NPC, or a player's character (player.Character). It is sent to players once and then rides by itself, never lagging behind. options.Offset is where it sits in the target's own space (cm, (0, 0, 0) by default: the target's middle, or the bone's), options.Rotation its turn there as (pitch, yaw, roll) degrees, and options.Bone a bone or socket of the target's skeleton ("hand_r", "head", "spine_03") to follow instead of the whole target; Bone = "HeldItem" follows where the player's held tool or gun sits, so a light attached there points where they aim. While a usable item or a consumable is in their hand it follows the palm holding it instead, turned as the item is (Offset and Rotation are then along the item mesh's own axes). Attaching again moves it to the new target or offset. What can be attached: an entity a script may move (a clone, an Assets:Spawn mesh, a light, an effect, a place entity marked "dynamic", a physics entity); a player's character, an NPC or a vehicle can't be (attach things to them instead). A physics entity is held Anchored while attached, and Detach gives it back what Anchored was, so a crate let go off a truck falls. Attached to a player, an NPC, a vehicle or a physics entity it blocks nothing, so it can't push what carries it (overlaps, Touched and raycasts still find it); attached to anything else it keeps its collision, so a floor riding a lift still holds players up. If the target goes (destroyed, or a player's character replaced when they respawn or leave), the attachment ends and the entity stays where it was. Setting its Position or Rotation, or tweening either, detaches it first. On a player's character Offset may be at most 50 cm and the entity at most 2 m across; anywhere else Offset may be up to 100 m. A place holds at most 256 attachments. Errors for an unknown Bone, a target that rides this entity, or past these limits. On the server everyone sees it; on a client only that player does (a physics entity is attached by a server script only). An attached entity can't be cloned. Example, a flashlight: `local light = Lights:Spawn("Spot", Vector3.new(0, 0, 0)) light:AttachTo(player.Character, {Bone = "HeldItem", Offset = Vector3.new(0, 20, 0)})`. function AttachTo(self, target: Entity, options: {Offset: Vector3?, Rotation: Vector3?, Bone: string?}?): () --- Remove the outline SetHighlight drew around this entity. On the server it goes for everyone; on a client it removes only that client's own highlight (the server's, if any, shows again). Does nothing when it has none. function ClearHighlight(self): () @@ -248,6 +248,14 @@ declare extern type Player with HealthEnabled: boolean --- The id of the Tool in the player's hands (the id Backpack:GetTools lists); nil with bare hands, and while the player has no character. Readable on the server and on every client. HeldToolId: string? + --- How full the character's hunger pool is, from 0 (empty: it hurts) to MaxHunger (it counts in small steps, and moves only while HungerEnabled is true). nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..MaxHunger: that is how a script feeds the player. Every new character starts full. + Hunger: number? + --- How much health the character loses each second while its Hunger is empty, dealt once a second and tagged "Hunger" (1 unless a script changes it). It goes past Armor and Shield, and nobody is credited for the kill. 0: an empty pool does no harm. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session, through respawns. + HungerDamage: number? + --- How much Hunger the character loses each second while HungerEnabled is true (0.1 unless a script changes it: a full pool of 100 lasts about 17 minutes). 0 holds it where it is. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session, through respawns. + HungerDrain: number? + --- Whether the player gets hungry (false unless a script turns it on, so places that never use it play as before). With it on, Hunger drains by HungerDrain every second, and once it is empty the character takes HungerDamage every second until something fills it again (Died then says "Hunger"): a script setting Hunger, or a consumable whose effect is hunger. Turning it on starts it full. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) lasts for the rest of the session, through respawns. Mantle draws no bar for it: show it with your own UI. + HungerEnabled: boolean? --- Whether the player's own controls move and act for their character (true unless a script changes it); nil while the player has no character. Setting it (server only) to false stops moving, looking around, aiming, jumping, crouching, dodging, climbing, using tools and entering or driving vehicles: the keys and the pad do nothing for the character, and a key held at the time is let go. The menu (Esc, Start), chat, push to talk, the leaderboard and script UI still work, and so do the place's own Input bindings, so a cutscene can still be skipped with a key. Scripts can still move the character (Teleport, Launch; Player:Jump is refused while it is false). A player driving a vehicle can neither drive nor get out while it is false: the controls go to rest. Turning it off (or on) mid-move can cost the player's own machine one round trip of corrected movement, as ToolsEnabled does. It lasts for the rest of the session, through respawns. Use it for cutscenes, stuns and freezes, and intro sequences. InputEnabled: boolean? --- Whether the character is crouched right now (by the key, a slide or ForceCrouch). nil while the player has no character. Read-only. @@ -270,10 +278,14 @@ declare extern type Player with MaxBreath: number? --- The most health the character can have (100 unless a script changes it); nil while the player has no character. Setting it (server only) clamps to 1..10000 and lasts for the rest of the session: every respawn starts with full health at this maximum. Lowering it below Health lowers Health too; raising it does not heal. MaxHealth: number? + --- The full hunger pool (100 unless a script changes it). nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 1..10000 and lasts for the rest of the session, through respawns. Lowering it below Hunger lowers Hunger too; raising it keeps a full pool full. + MaxHunger: number? --- The size of the shield pool (0, no shield, unless a script changes it); nil while the player has no character. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session. A shield above the new size drops to it; raising an existing shield does not fill the pool (set Shield for that), but giving a shield to a player who had none starts it full. MaxShield: number? --- The most stamina the character can have (100 unless a script changes it); nil while the player has no character. Setting it (server only) clamps to 1..10000 and lasts for the rest of the session, through respawns. Lowering it below Stamina lowers Stamina too; raising it does not refill. MaxStamina: number? + --- The full thirst pool (100 unless a script changes it). nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 1..10000 and lasts for the rest of the session, through respawns. Lowering it below Thirst lowers Thirst too; raising it keeps a full pool full. + MaxThirst: number? --- The player's Epic display name. Name: string --- The player's round-trip time to the server in milliseconds, a whole number. Read-only. Works on the server and every client, for any player. It is the average of the last few seconds, updated about once a second; on another player's client it arrives with that player's replication, in 4 ms steps and at most 1020 (about 1100 elsewhere). 0 when there is no network in between (single player, a listen server's own player) or before the first measurement, and when the player has left. Example: label.Text = player.Ping .. " ms" @@ -314,6 +326,14 @@ declare extern type Player with StaminaRegenDelay: number? --- The name of the team the player is on, or nil for none. Setting it (server only) puts the player on that team, which must exist (Teams:Create); set nil to take them off. Fires Teams.PlayerTeamChanged. Team membership replicates, so client scripts can read it, and it lasts while the player is in the session. Team: string? + --- How full the character's thirst pool is, from 0 (empty: it hurts) to MaxThirst (it counts in small steps, and moves only while ThirstEnabled is true). nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..MaxThirst: that is how a script feeds the player. Every new character starts full. + Thirst: number? + --- How much health the character loses each second while its Thirst is empty, dealt once a second and tagged "Thirst" (1 unless a script changes it). It goes past Armor and Shield, and nobody is credited for the kill. 0: an empty pool does no harm. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session, through respawns. + ThirstDamage: number? + --- How much Thirst the character loses each second while ThirstEnabled is true (0.1 unless a script changes it: a full pool of 100 lasts about 17 minutes). 0 holds it where it is. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session, through respawns. + ThirstDrain: number? + --- Whether the player gets thirsty (false unless a script turns it on, so places that never use it play as before). With it on, Thirst drains by ThirstDrain every second, and once it is empty the character takes ThirstDamage every second until something fills it again (Died then says "Thirst"): a script setting Thirst, or a consumable whose effect is thirst. Turning it on starts it full. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) lasts for the rest of the session, through respawns. Mantle draws no bar for it: show it with your own UI. + ThirstEnabled: boolean? --- Whether the player can use their tools (true unless a script changes it); nil while the player has no character. Setting it (server only) to false puts the tool in hand away and leaves the hands empty: no attacking, guarding, firing, reloading, using an item, drawing a tool or switching tools, the built-in fists included. The tools stay in the Backpack, and a tool a script or pickup gives meanwhile goes into the Backpack without coming to hand. Setting it back to true gives back the tool it put away (if the hands are still empty). The dodge is not a tool: DodgeEnabled and CombatEnabled keep it. The fists punch only while both CombatEnabled and ToolsEnabled are true. Use it for safe zones, lobbies and cutscenes. It lasts for the rest of the session, through respawns. ToolsEnabled: boolean? --- Whether the player has their worn top tucked in under their bottoms (their Tuck in switch in the avatar editor, off by default). false when no top is worn or their look has not arrived. A top its creator made untuckable stays out whatever this says. Read-only. (server only) @@ -338,9 +358,9 @@ declare extern type Player with BreathRestored: Signal<(Player)> --- The player has a fresh character, ready for weapons, attributes or a teleport: the first one when they join (or when Player:Spawn gives it), and every one after a death, Player:Respawn or Player:Spawn. character is the same Entity as Player.Character. Fires on the server, the tick after the character appears and after PlayerAdded for a player who just joined. Players:OnCharacter also covers characters that already exist. CharacterAdded: Signal<(Player, Entity)> - --- A clip PlayClip started on the player ended, on the server. clip is the name you gave. reason is "finished" (it played out), "stopped" (StopClip), "replaced" (a new PlayClip, or a change of body: another avatar, or their own again), "moved" (StopOnMove and the player moved), "action" (death, a seat or a knockdown took the body) or "removed" (the player left or their character was replaced). A looping clip never finishes. + --- A clip PlayClip started on the player ended, on the server. clip is the name you gave. reason is "finished" (it played out), "stopped" (StopClip), "replaced" (a new PlayClip, an emote, or a change of body: another avatar, or their own again), "moved" (StopOnMove and the player moved), "action" (death, a seat or a knockdown took the body; an attack, reload or aim; a climb, vault, dodge or hit reaction ended a full-body clip) or "removed" (the player left or their character was replaced). A looping clip never finishes. ClipEnded: Signal<(Player, string, string)> - --- A clip PlayClip started on the player crossed a marker its creator put in it, on the server, at the time the marker was set (a loop fires it every pass). name is the marker: "impact", the moment a swing lands. Only the avatar's own slots and extras carry it (a place clip you name by id fires none). Footstep markers stay on the player's own machine and fire nothing. + --- A clip PlayClip started on the player crossed a marker its creator put in it, on the server, at the time the marker was set (a loop fires it every pass). name is the marker: "impact", the moment a swing lands. A slot, an extra, a place clip or a pack clip fires it when its creator set an "impact" marker in it (a built-in clip has none). Footstep markers stay on the player's own machine and fire nothing. ClipEvent: Signal<(Player, string, string)> --- The character crouched (the key, a slide or ForceCrouch). Fires on the server and on every client. CrouchStarted: Signal<(Player)> @@ -348,6 +368,8 @@ declare extern type Player with CrouchStopped: Signal<(Player)> --- The character was hurt, on the server. amount is what got through Armor (the Shield and health took it between them), so a hit the shield soaked up still counts; a killing hit fires Damaged first and then Died. damageType is the hit's tag ("Bullet", "Melee", "Explosion", ..., or your own) and attacker the player who dealt it, or nil. weapon is the Tool id of the weapon that dealt the hit and round the name of the round loaded on it when it fired (Backpack:SetRound), so a script can tell a fire arrow from a plain one; both nil for a hit that was not a weapon's, round nil for a weapon with none loaded (weapon and round: script API 1.77). bone is the bone the hit struck (a melee swing: the bone nearest where it landed) and region its body part ("Head", "Body" or "Limb"); both nil for a hit that named no bone, such as a blast, a car or a script's (script API 1.113). Not fired for a hit a held guard blocked, friendly fire that was switched off, a hit Players:OnDamaging blocked, or Health set directly. Damaged: Signal<(Player, number, string, Player?, string?, string?, string?, string?)> + --- The character's Thirst reached 0: from now on it takes ThirstDamage every second until something fills it. Fires on the server and on the player's own machine. + Dehydrated: Signal<(Player)> --- The player's character died, on the server and on every client. killer is the player whose damage finished it (a weapon, or TakeDamage with a source); nil for falling out of the world, Kill, Health set to 0, or their own damage. damageType is the tag of the killing hit ("Bullet", "Melee", "Explosion", ..., or your own); "Generic" when nothing named one. Died: Signal<(Player, Player?, string)> --- The player's dimension changed (Player.Dimension, or a vehicle they ride moved with Entity.Dimension). Fires on the server and on every client; old and new are the dimensions. @@ -362,6 +384,8 @@ declare extern type Player with GrabRefused: Signal<(Player, Entity?, string, string)> --- The character's health changed: damage, healing, Health set, or a respawn's refill. Fires on the server and on every client. HealthChanged: Signal<(Player, number, number)> + --- The character's Hunger changed: draining, a script setting it or a consumable filling it. It reports steps of about half a percent of MaxHunger, not every frame. Fires on the server and on the player's own machine. + HungerChanged: Signal<(Player, number, number)> --- The character jumped: the jump key, Player:Jump, a double jump or a wall jump (a Launch is not a jump). Fires on the server and on the player's own client, not on other players' clients. Jumped: Signal<(Player)> --- The character came down onto the ground after being in the air (a jump, a fall, a Launch). fallSpeed is how fast it was falling as it hit, in centimeters per second (FallDamageSpeed is the same measure). Not fired for landing in water. Fires on the server and on the player's own client, not on other players' clients. @@ -390,12 +414,16 @@ declare extern type Player with StaffExtraUsed: Signal<(Player, string)> --- The character's Stamina changed: sprinting, resting, a jump's cost or a script setting it. It reports steps of about half a percent of MaxStamina, not every frame. Fires on the server and on every client while StaminaEnabled is true. StaminaChanged: Signal<(Player, number, number)> + --- The character's Hunger reached 0: from now on it takes HungerDamage every second until something fills it. Fires on the server and on the player's own machine. + Starving: Signal<(Player)> --- The player's stun is over, on the server: it ran out, or a knockdown, a death or putting the weapon away ended it early. StunEnded: Signal<(Player)> --- The player's guard was broken into a stun, on the server: until StunEnded they cannot move, attack or block, but can still look around, and hits still hurt them. A weapon whose stunSeconds is 0, or a hold with no stun animation, breaks the guard without a stun and does not fire this. Stunned: Signal<(Player)> --- The character's head came back out of the water after WentUnderwater (IsUnderwater turned false), or it left the water or sat in a seat while under. Always before LeftWater. Fires on the server and on every client. Surfaced: Signal<(Player)> + --- The character's Thirst changed: draining, a script setting it or a consumable filling it. It reports steps of about half a percent of MaxThirst, not every frame. Fires on the server and on the player's own machine. + ThirstChanged: Signal<(Player, number, number)> --- The swimming character's head went under the surface: IsUnderwater turned true, the moment Breath starts draining when BreathEnabled is on. Always after EnteredWater. Fires on the server and on every client. Use it for an underwater sound, a screen tint or a drowning timer of your own. WentUnderwater: Signal<(Player)> --- Fade this player's screen to a color and back (server only), as Camera:Fade does on their own client: player:FadeScreen({To = 1, Duration = 0.4, Audio = true}), move them, then player:FadeScreen({To = 0}). options: To (how covered the screen ends, 0 clear to 1 solid color, default 1), Duration (seconds, 0 to 60, default 0.5; 0 cuts), Color ("#RRGGBB", default black), Audio (default false: true turns all in-game sound down with the picture, all the way at 1; voice chat is not faded; a later fade back toward clear brings the sound up with the picture) and Hold (default true: the screen stays at To once there; false clears it when the fade ends, for a flash). The fade runs from wherever the screen is now, so a fade back in started halfway through a fade out turns back without a jump, and a new fade replaces the last one, its color at once. A fade ending at 0 clears the screen and the sound. Only the 3D picture fades: the HUD, script UI (labels placed in the world included) and the Esc menu draw over it and stay usable. It is kept through a respawn (so a fade can cover one) and clears at once when the script that made it stops. An unknown option or a value of the wrong type is an error that names it. The player's client scripts can fade too; the last fade wins. Does nothing for a player who has left. (server only) @@ -429,7 +457,7 @@ declare extern type Player with function Launch(self, velocity: Vector3, options: {Override: boolean?, OverrideZ: boolean?}?): boolean --- Call handler with the player's attribute value now and every time it changes. The easy way to keep a HUD or nameplate in sync. function ObserveAttribute(self, name: string, handler: (value: any) -> ()): Connection - --- Play a clip on the player's body, on the server, and tell everyone (a player who joins later sees it in step). For now this works on a player who is a Custom avatar (SetAvatar): clip is one of its slots ("roar", "attack"), "slot:N" (the Nth clip of a slot, from 0), one of its extras by name, or a place clip id (ast_...) made on the avatar's own skeleton. On a player in a human avatar it returns false (clips on human players come with the creator-clips work, #333). Options: Layer "full" (the whole body, the default) or "upper" (from the avatar's upper-body bone up, the legs keep moving; an avatar with no upper-body bone plays it full); Loop (left out: a slot's own rule, so an attack plays once and a walk loops); PlayRate (0.1 to 4, 1 by default); StartOffset (seconds into the clip); BlendIn and BlendOut (seconds, 0 to 2, 0.2 when left out: the fade into the clip and out of it); StopOnMove (stop when the player moves); KeepTool (a Custom avatar holds no tool). The last call wins: a new clip replaces the one that plays (ClipEnded "replaced"). Returns false, and plays nothing, with a reason in the script log, when the clip is unknown, the player is dead, or they are not a Custom avatar. (server only) + --- Play a clip on the player's body, on the server, and tell everyone (a player who joins later sees it in step). On a player in a human avatar, clip is a place clip id (ast_...) made on the UEFN mannequin, or a built-in clip: "pickup", "drink", "use", "sit_bench" (loops), "fidget" or "look_around". On a Custom avatar (SetAvatar), clip is one of its slots ("roar", "attack"), "slot:N" (the Nth clip of a slot, from 0), one of its extras by name, or a place clip id made on the avatar's own skeleton. On either, clip can be "/": the clip named name in the animation pack the place pins under the storage name pack (an avatarStorage entry of kind animPack), made on the body's skeleton. Options: Layer "full" (the whole body, the default) or "upper" (the upper body: from spine_01 up on a human, from the avatar's upper-body bone up on a Custom avatar, which plays it full when it has none; the legs keep moving); Loop (left out: a slot's own rule, so an attack plays once and a walk loops; a place clip plays once); PlayRate (0.1 to 4, 1 by default); StartOffset (seconds into the clip); BlendIn and BlendOut (seconds, 0 to 2, 0.2 when left out: the fade into the clip and out of it); StopOnMove (stop when the player moves or leaves the ground); KeepTool (a full-body clip on a human puts the held tool away unless KeepTool is true; a Custom avatar holds no tool). The clip ends early when the player dies, is knocked down or sits, when they attack, reload or aim, and (a full-body clip) when they climb, vault or dodge or react to a hit; an upper-body clip steps aside for a climb or vault and comes back after it. The last call wins: a new clip replaces the one that plays (ClipEnded "replaced"), an emote replaces the clip and a clip the emote. Returns false, and plays nothing, with a reason in the script log, when the clip is unknown or made on another skeleton (a pack the place does not pin, or a name the pack lacks, is unknown), or the player is dead, knocked down or seated. (server only) function PlayClip(self, clip: string, options: {Layer: string?, Loop: boolean?, PlayRate: number?, StartOffset: number?, BlendIn: number?, BlendOut: number?, StopOnMove: boolean?, KeepTool: boolean?}?): boolean --- Knock the character down: it goes limp for everyone, the player cannot move or act, and when the time is up (or Recover is called) it stands back up where it lies with a get-up animation. seconds is how long to stay down, 0.1 to 300; leave it out to stay down until Recover (at most five minutes). velocity is an optional shove in centimeters per second; without it the character keeps the speed it had. Ragdolled fires now and Recovered when it gets up. Returns false when the player has no character on foot, is dead, is sitting in a vehicle or is already knocked down. (server only) function Ragdoll(self, seconds: number?, velocity: Vector3?): boolean @@ -452,7 +480,7 @@ declare extern type Player with function Spawn(self, position: Vector3?, yaw: number?): boolean --- Stop the clip PlayClip started on the player; ClipEnded fires with "stopped". blendOut (seconds, 0 to 2) is how long the body takes to fade out of the clip; left out, the clip's own BlendOut (0.2 s by default). Returns false when nothing played. (server only) function StopClip(self, blendOut: number?): boolean - --- Hurt the character through the same path weapons use, so the game's damage rules apply: friendly fire, Armor, then Shield, then health. source is the player to credit: if this hit kills, Died names them as the killer. damageType tags the hit for Damaged and Died ("Generic" when left out); use a built-in such as "Bullet", "Melee", "Explosion", "Fall", "Vehicle", "Area", "Magic" or "Drown", or any word of your own up to 32 characters, such as "Poison". Returns false when the player has no character on foot (respawning or driving), is already dead, or nothing got through (friendly fire off, or Armor 100). (server only) + --- Hurt the character through the same path weapons use, so the game's damage rules apply: friendly fire, Armor, then Shield, then health. source is the player to credit: if this hit kills, Died names them as the killer. damageType tags the hit for Damaged and Died ("Generic" when left out); use a built-in such as "Bullet", "Melee", "Explosion", "Fall", "Vehicle", "Area", "Magic", "Drown", "Hunger" or "Thirst", or any word of your own up to 32 characters, such as "Poison". Returns false when the player has no character on foot (respawning or driving), is already dead, or nothing got through (friendly fire off, or Armor 100). (server only) function TakeDamage(self, amount: number, source: Player?, damageType: string?): boolean --- Move the player's character instantly. Always lands exactly at position, even inside solid geometry; returns false only when the player has no character to move right now. (server only) function Teleport(self, position: Vector3): boolean @@ -959,12 +987,14 @@ declare Avatar: AvatarService declare extern type BackpackService with --- One shot or swing of a player's weapon, on the server: each trigger pull of a gun (once for a shotgun's whole spread, once per round of a burst or an automatic), each arrow, spell, launched round or thrown weapon or shield, each swing of a melee weapon, a staff, a bow's bash or the fists, the start of a beam, and a gravity gun's launch. Fires whether or not it hits anything (Entity.Hit, Player.Damaged and NPC.Damaged report what it hit). toolId is the weapon's Tool id in the player's Backpack ("fists" for the fists). origin and direction are where the shot left from and the way it went: a gun's is the player's aim (Player:GetAim, before the spread), a projectile's is where it was launched and its launch direction (a bow's arc included), a swing's or a beam's is the player's aim when it started. Use it for accuracy stats, ammo counters of your own, or an alarm that hears gunshots. Example: `Backpack.Fired:Connect(function(player, toolId) shots[player] = (shots[player] or 0) + 1 end)`. (server only) Fired: Signal<(Player, string, Vector3, Vector3)> - --- A consumable (a potion, a medkit, food: a weapon-builder item with the Consumable hold) was used, on the server, at the moment its effect lands: halfway through its drink or use clip. It fires for every use, whether the item has a built-in effect or not, and never for a use that was canceled (sprinting, jumping or dodging first spends nothing). toolId is the item's Tool id in the player's Backpack, docName the name the creator gave it in the builder, usesLeft how many uses it has left (0: it is gone from the Backpack), and builtInEffect whether its own heal also ran (false for an item whose effect is "none": your script is the whole effect). + --- A consumable (a potion, a medkit, food: a weapon-builder item with the Consumable hold) was used, on the server, at the moment its effect lands: halfway through its drink or use clip. It fires for every use, whether the item has a built-in effect or not, and never for a use that was canceled (sprinting, jumping or dodging first spends nothing). toolId is the item's Tool id in the player's Backpack, docName the name the creator gave it in the builder, usesLeft how many uses it has left (0: it is gone from the Backpack), and builtInEffect whether its own effect also ran: its heal, or its stamina, hunger or thirst while your script has that pool on (false for an item whose effect is "none", where your script is the whole effect, and for a pool that is off). ItemUsed: Signal<(Player, string, string, number, boolean)> --- A weapon's attachments, stat multipliers or light changed: a script call, a pickup that brought a loadout, or the player's light key. Fires on the server, once the change has taken effect. LoadoutChanged: Signal<(Player, string)> --- The local player's Backpack changed: a Tool came or went, a different slot is in the hands, or a consumable's uses changed. Redraw from GetLocal. LocalChanged: Signal<()> + --- One use of anything a player holds, on the server, whatever it is: everything Backpack.Fired counts for a weapon (each shot, launch, swing, beam start and gravity gun launch), each consumable's use as it starts (Backpack.ItemUsed is its effect moment, which a canceled use never reaches), and each use of a usable item (hold "item", which does nothing by itself: this is where your script gives it its behavior). toolId is the Tool's id in the player's Backpack ("fists" for the fists), docName its name. Guarding, aiming, reloading and switching are not uses. Example: `Backpack.ToolUsed:Connect(function(player, toolId, name) if name == "Flashlight" then toggleLamp(player) end end)`. (server only) + ToolUsed: Signal<(Player, string, string)> --- Put a whole loadout on the weapon, all or nothing: the slots it does not name end up empty, the stats it does not name go back to 1, and a loadout with no round key leaves the weapon's round as it is (1.81: ClearRound takes it off). Returns { ok = true }, or { ok = false, error = ... } as SetAttachment does ("not an option" when the loadout names an option the weapon no longer has, for the script to decide what to do). A loadout that is not the right shape errors. (server only) function ApplyLoadout(self, player: Player, toolId: string, loadout: {attachments: {[string]: string}?, stats: {[string]: number}?, color: string?, round: {Name: string, DamageMultiplier: number?, Speed: number?, Color: string?}?}): {ok: boolean, error: string?} --- Empty the player's Backpack, leaving only fists. Returns how many Tools were removed. (server only) diff --git a/Resources/ScriptApi/mantle.d.ts b/Resources/ScriptApi/mantle.d.ts index d033eec7..a859fafd 100644 --- a/Resources/ScriptApi/mantle.d.ts +++ b/Resources/ScriptApi/mantle.d.ts @@ -140,7 +140,7 @@ interface Entity { applyAngularImpulse(impulse: Vector3): void; /** Push a physics entity: impulse is in kg*cm/s along the world axes, so its velocity changes by impulse / Mass. Does nothing while it is Anchored. Errors on an entity with no physics block. (server only) */ applyImpulse(impulse: Vector3): void; - /** Stick this entity to target so it follows it wherever it goes: a car, a lift or moving platform, an NPC, or a player's character (player.Character). It is sent to players once and then rides by itself, never lagging behind. options.Offset is where it sits in the target's own space (cm, (0, 0, 0) by default: the target's middle, or the bone's), options.Rotation its turn there as (pitch, yaw, roll) degrees, and options.Bone a bone or socket of the target's skeleton ("hand_r", "head", "spine_03") to follow instead of the whole target; Bone = "HeldItem" follows where the player's held tool or gun sits, so a light attached there points where they aim. Attaching again moves it to the new target or offset. What can be attached: an entity a script may move (a clone, an Assets:Spawn mesh, a light, an effect, a place entity marked "dynamic", a physics entity); a player's character, an NPC or a vehicle can't be (attach things to them instead). A physics entity is held Anchored while attached, and Detach gives it back what Anchored was, so a crate let go off a truck falls. Attached to a player, an NPC, a vehicle or a physics entity it blocks nothing, so it can't push what carries it (overlaps, Touched and raycasts still find it); attached to anything else it keeps its collision, so a floor riding a lift still holds players up. If the target goes (destroyed, or a player's character replaced when they respawn or leave), the attachment ends and the entity stays where it was. Setting its Position or Rotation, or tweening either, detaches it first. On a player's character Offset may be at most 50 cm and the entity at most 2 m across; anywhere else Offset may be up to 100 m. A place holds at most 256 attachments. Errors for an unknown Bone, a target that rides this entity, or past these limits. On the server everyone sees it; on a client only that player does (a physics entity is attached by a server script only). An attached entity can't be cloned. Example, a flashlight: `local light = Lights:Spawn("Spot", Vector3.new(0, 0, 0)) light:AttachTo(player.Character, {Bone = "HeldItem", Offset = Vector3.new(0, 20, 0)})`. */ + /** Stick this entity to target so it follows it wherever it goes: a car, a lift or moving platform, an NPC, or a player's character (player.Character). It is sent to players once and then rides by itself, never lagging behind. options.Offset is where it sits in the target's own space (cm, (0, 0, 0) by default: the target's middle, or the bone's), options.Rotation its turn there as (pitch, yaw, roll) degrees, and options.Bone a bone or socket of the target's skeleton ("hand_r", "head", "spine_03") to follow instead of the whole target; Bone = "HeldItem" follows where the player's held tool or gun sits, so a light attached there points where they aim. While a usable item or a consumable is in their hand it follows the palm holding it instead, turned as the item is (Offset and Rotation are then along the item mesh's own axes). Attaching again moves it to the new target or offset. What can be attached: an entity a script may move (a clone, an Assets:Spawn mesh, a light, an effect, a place entity marked "dynamic", a physics entity); a player's character, an NPC or a vehicle can't be (attach things to them instead). A physics entity is held Anchored while attached, and Detach gives it back what Anchored was, so a crate let go off a truck falls. Attached to a player, an NPC, a vehicle or a physics entity it blocks nothing, so it can't push what carries it (overlaps, Touched and raycasts still find it); attached to anything else it keeps its collision, so a floor riding a lift still holds players up. If the target goes (destroyed, or a player's character replaced when they respawn or leave), the attachment ends and the entity stays where it was. Setting its Position or Rotation, or tweening either, detaches it first. On a player's character Offset may be at most 50 cm and the entity at most 2 m across; anywhere else Offset may be up to 100 m. A place holds at most 256 attachments. Errors for an unknown Bone, a target that rides this entity, or past these limits. On the server everyone sees it; on a client only that player does (a physics entity is attached by a server script only). An attached entity can't be cloned. Example, a flashlight: `local light = Lights:Spawn("Spot", Vector3.new(0, 0, 0)) light:AttachTo(player.Character, {Bone = "HeldItem", Offset = Vector3.new(0, 20, 0)})`. */ attachTo(target: Entity, options?: { offset?: Vector3 | undefined; rotation?: Vector3 | undefined; bone?: string | undefined }): void; /** Remove the outline SetHighlight drew around this entity. On the server it goes for everyone; on a client it removes only that client's own highlight (the server's, if any, shows again). Does nothing when it has none. */ clearHighlight(): void; @@ -251,6 +251,14 @@ interface Player { healthEnabled: boolean; /** The id of the Tool in the player's hands (the id Backpack:GetTools lists); nil with bare hands, and while the player has no character. Readable on the server and on every client. */ readonly heldToolId: string | undefined; + /** How full the character's hunger pool is, from 0 (empty: it hurts) to MaxHunger (it counts in small steps, and moves only while HungerEnabled is true). nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..MaxHunger: that is how a script feeds the player. Every new character starts full. */ + hunger: number | undefined; + /** How much health the character loses each second while its Hunger is empty, dealt once a second and tagged "Hunger" (1 unless a script changes it). It goes past Armor and Shield, and nobody is credited for the kill. 0: an empty pool does no harm. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session, through respawns. */ + hungerDamage: number | undefined; + /** How much Hunger the character loses each second while HungerEnabled is true (0.1 unless a script changes it: a full pool of 100 lasts about 17 minutes). 0 holds it where it is. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session, through respawns. */ + hungerDrain: number | undefined; + /** Whether the player gets hungry (false unless a script turns it on, so places that never use it play as before). With it on, Hunger drains by HungerDrain every second, and once it is empty the character takes HungerDamage every second until something fills it again (Died then says "Hunger"): a script setting Hunger, or a consumable whose effect is hunger. Turning it on starts it full. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) lasts for the rest of the session, through respawns. Mantle draws no bar for it: show it with your own UI. */ + hungerEnabled: boolean | undefined; /** Whether the player's own controls move and act for their character (true unless a script changes it); nil while the player has no character. Setting it (server only) to false stops moving, looking around, aiming, jumping, crouching, dodging, climbing, using tools and entering or driving vehicles: the keys and the pad do nothing for the character, and a key held at the time is let go. The menu (Esc, Start), chat, push to talk, the leaderboard and script UI still work, and so do the place's own Input bindings, so a cutscene can still be skipped with a key. Scripts can still move the character (Teleport, Launch; Player:Jump is refused while it is false). A player driving a vehicle can neither drive nor get out while it is false: the controls go to rest. Turning it off (or on) mid-move can cost the player's own machine one round trip of corrected movement, as ToolsEnabled does. It lasts for the rest of the session, through respawns. Use it for cutscenes, stuns and freezes, and intro sequences. */ inputEnabled: boolean | undefined; /** Whether the character is crouched right now (by the key, a slide or ForceCrouch). nil while the player has no character. Read-only. */ @@ -273,10 +281,14 @@ interface Player { maxBreath: number | undefined; /** The most health the character can have (100 unless a script changes it); nil while the player has no character. Setting it (server only) clamps to 1..10000 and lasts for the rest of the session: every respawn starts with full health at this maximum. Lowering it below Health lowers Health too; raising it does not heal. */ maxHealth: number | undefined; + /** The full hunger pool (100 unless a script changes it). nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 1..10000 and lasts for the rest of the session, through respawns. Lowering it below Hunger lowers Hunger too; raising it keeps a full pool full. */ + maxHunger: number | undefined; /** The size of the shield pool (0, no shield, unless a script changes it); nil while the player has no character. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session. A shield above the new size drops to it; raising an existing shield does not fill the pool (set Shield for that), but giving a shield to a player who had none starts it full. */ maxShield: number | undefined; /** The most stamina the character can have (100 unless a script changes it); nil while the player has no character. Setting it (server only) clamps to 1..10000 and lasts for the rest of the session, through respawns. Lowering it below Stamina lowers Stamina too; raising it does not refill. */ maxStamina: number | undefined; + /** The full thirst pool (100 unless a script changes it). nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 1..10000 and lasts for the rest of the session, through respawns. Lowering it below Thirst lowers Thirst too; raising it keeps a full pool full. */ + maxThirst: number | undefined; /** The player's Epic display name. */ readonly name: string; /** The player's round-trip time to the server in milliseconds, a whole number. Read-only. Works on the server and every client, for any player. It is the average of the last few seconds, updated about once a second; on another player's client it arrives with that player's replication, in 4 ms steps and at most 1020 (about 1100 elsewhere). 0 when there is no network in between (single player, a listen server's own player) or before the first measurement, and when the player has left. Example: label.Text = player.Ping .. " ms" */ @@ -317,6 +329,14 @@ interface Player { staminaRegenDelay: number | undefined; /** The name of the team the player is on, or nil for none. Setting it (server only) puts the player on that team, which must exist (Teams:Create); set nil to take them off. Fires Teams.PlayerTeamChanged. Team membership replicates, so client scripts can read it, and it lasts while the player is in the session. */ team: string | undefined; + /** How full the character's thirst pool is, from 0 (empty: it hurts) to MaxThirst (it counts in small steps, and moves only while ThirstEnabled is true). nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..MaxThirst: that is how a script feeds the player. Every new character starts full. */ + thirst: number | undefined; + /** How much health the character loses each second while its Thirst is empty, dealt once a second and tagged "Thirst" (1 unless a script changes it). It goes past Armor and Shield, and nobody is credited for the kill. 0: an empty pool does no harm. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session, through respawns. */ + thirstDamage: number | undefined; + /** How much Thirst the character loses each second while ThirstEnabled is true (0.1 unless a script changes it: a full pool of 100 lasts about 17 minutes). 0 holds it where it is. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session, through respawns. */ + thirstDrain: number | undefined; + /** Whether the player gets thirsty (false unless a script turns it on, so places that never use it play as before). With it on, Thirst drains by ThirstDrain every second, and once it is empty the character takes ThirstDamage every second until something fills it again (Died then says "Thirst"): a script setting Thirst, or a consumable whose effect is thirst. Turning it on starts it full. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) lasts for the rest of the session, through respawns. Mantle draws no bar for it: show it with your own UI. */ + thirstEnabled: boolean | undefined; /** Whether the player can use their tools (true unless a script changes it); nil while the player has no character. Setting it (server only) to false puts the tool in hand away and leaves the hands empty: no attacking, guarding, firing, reloading, using an item, drawing a tool or switching tools, the built-in fists included. The tools stay in the Backpack, and a tool a script or pickup gives meanwhile goes into the Backpack without coming to hand. Setting it back to true gives back the tool it put away (if the hands are still empty). The dodge is not a tool: DodgeEnabled and CombatEnabled keep it. The fists punch only while both CombatEnabled and ToolsEnabled are true. Use it for safe zones, lobbies and cutscenes. It lasts for the rest of the session, through respawns. */ toolsEnabled: boolean | undefined; /** Whether the player has their worn top tucked in under their bottoms (their Tuck in switch in the avatar editor, off by default). false when no top is worn or their look has not arrived. A top its creator made untuckable stays out whatever this says. Read-only. (server only) */ @@ -341,9 +361,9 @@ interface Player { readonly breathRestored: Signal<[player: Player]>; /** The player has a fresh character, ready for weapons, attributes or a teleport: the first one when they join (or when Player:Spawn gives it), and every one after a death, Player:Respawn or Player:Spawn. character is the same Entity as Player.Character. Fires on the server, the tick after the character appears and after PlayerAdded for a player who just joined. Players:OnCharacter also covers characters that already exist. */ readonly characterAdded: Signal<[player: Player, character: Entity]>; - /** A clip PlayClip started on the player ended, on the server. clip is the name you gave. reason is "finished" (it played out), "stopped" (StopClip), "replaced" (a new PlayClip, or a change of body: another avatar, or their own again), "moved" (StopOnMove and the player moved), "action" (death, a seat or a knockdown took the body) or "removed" (the player left or their character was replaced). A looping clip never finishes. */ + /** A clip PlayClip started on the player ended, on the server. clip is the name you gave. reason is "finished" (it played out), "stopped" (StopClip), "replaced" (a new PlayClip, an emote, or a change of body: another avatar, or their own again), "moved" (StopOnMove and the player moved), "action" (death, a seat or a knockdown took the body; an attack, reload or aim; a climb, vault, dodge or hit reaction ended a full-body clip) or "removed" (the player left or their character was replaced). A looping clip never finishes. */ readonly clipEnded: Signal<[player: Player, clip: string, reason: string]>; - /** A clip PlayClip started on the player crossed a marker its creator put in it, on the server, at the time the marker was set (a loop fires it every pass). name is the marker: "impact", the moment a swing lands. Only the avatar's own slots and extras carry it (a place clip you name by id fires none). Footstep markers stay on the player's own machine and fire nothing. */ + /** A clip PlayClip started on the player crossed a marker its creator put in it, on the server, at the time the marker was set (a loop fires it every pass). name is the marker: "impact", the moment a swing lands. A slot, an extra, a place clip or a pack clip fires it when its creator set an "impact" marker in it (a built-in clip has none). Footstep markers stay on the player's own machine and fire nothing. */ readonly clipEvent: Signal<[player: Player, clip: string, name: string]>; /** The character crouched (the key, a slide or ForceCrouch). Fires on the server and on every client. */ readonly crouchStarted: Signal<[player: Player]>; @@ -351,6 +371,8 @@ interface Player { readonly crouchStopped: Signal<[player: Player]>; /** The character was hurt, on the server. amount is what got through Armor (the Shield and health took it between them), so a hit the shield soaked up still counts; a killing hit fires Damaged first and then Died. damageType is the hit's tag ("Bullet", "Melee", "Explosion", ..., or your own) and attacker the player who dealt it, or nil. weapon is the Tool id of the weapon that dealt the hit and round the name of the round loaded on it when it fired (Backpack:SetRound), so a script can tell a fire arrow from a plain one; both nil for a hit that was not a weapon's, round nil for a weapon with none loaded (weapon and round: script API 1.77). bone is the bone the hit struck (a melee swing: the bone nearest where it landed) and region its body part ("Head", "Body" or "Limb"); both nil for a hit that named no bone, such as a blast, a car or a script's (script API 1.113). Not fired for a hit a held guard blocked, friendly fire that was switched off, a hit Players:OnDamaging blocked, or Health set directly. */ readonly damaged: Signal<[player: Player, amount: number, damageType: string, attacker: Player | undefined, weapon: string | undefined, round: string | undefined, bone: string | undefined, region: string | undefined]>; + /** The character's Thirst reached 0: from now on it takes ThirstDamage every second until something fills it. Fires on the server and on the player's own machine. */ + readonly dehydrated: Signal<[player: Player]>; /** The player's character died, on the server and on every client. killer is the player whose damage finished it (a weapon, or TakeDamage with a source); nil for falling out of the world, Kill, Health set to 0, or their own damage. damageType is the tag of the killing hit ("Bullet", "Melee", "Explosion", ..., or your own); "Generic" when nothing named one. */ readonly died: Signal<[player: Player, killer: Player | undefined, damageType: string]>; /** The player's dimension changed (Player.Dimension, or a vehicle they ride moved with Entity.Dimension). Fires on the server and on every client; old and new are the dimensions. */ @@ -365,6 +387,8 @@ interface Player { readonly grabRefused: Signal<[player: Player, target: Entity | undefined, reason: string, via: string]>; /** The character's health changed: damage, healing, Health set, or a respawn's refill. Fires on the server and on every client. */ readonly healthChanged: Signal<[player: Player, old: number, new: number]>; + /** The character's Hunger changed: draining, a script setting it or a consumable filling it. It reports steps of about half a percent of MaxHunger, not every frame. Fires on the server and on the player's own machine. */ + readonly hungerChanged: Signal<[player: Player, old: number, new: number]>; /** The character jumped: the jump key, Player:Jump, a double jump or a wall jump (a Launch is not a jump). Fires on the server and on the player's own client, not on other players' clients. */ readonly jumped: Signal<[player: Player]>; /** The character came down onto the ground after being in the air (a jump, a fall, a Launch). fallSpeed is how fast it was falling as it hit, in centimeters per second (FallDamageSpeed is the same measure). Not fired for landing in water. Fires on the server and on the player's own client, not on other players' clients. */ @@ -393,12 +417,16 @@ interface Player { readonly staffExtraUsed: Signal<[player: Player, extra: string]>; /** The character's Stamina changed: sprinting, resting, a jump's cost or a script setting it. It reports steps of about half a percent of MaxStamina, not every frame. Fires on the server and on every client while StaminaEnabled is true. */ readonly staminaChanged: Signal<[player: Player, old: number, new: number]>; + /** The character's Hunger reached 0: from now on it takes HungerDamage every second until something fills it. Fires on the server and on the player's own machine. */ + readonly starving: Signal<[player: Player]>; /** The player's stun is over, on the server: it ran out, or a knockdown, a death or putting the weapon away ended it early. */ readonly stunEnded: Signal<[player: Player]>; /** The player's guard was broken into a stun, on the server: until StunEnded they cannot move, attack or block, but can still look around, and hits still hurt them. A weapon whose stunSeconds is 0, or a hold with no stun animation, breaks the guard without a stun and does not fire this. */ readonly stunned: Signal<[player: Player]>; /** The character's head came back out of the water after WentUnderwater (IsUnderwater turned false), or it left the water or sat in a seat while under. Always before LeftWater. Fires on the server and on every client. */ readonly surfaced: Signal<[player: Player]>; + /** The character's Thirst changed: draining, a script setting it or a consumable filling it. It reports steps of about half a percent of MaxThirst, not every frame. Fires on the server and on the player's own machine. */ + readonly thirstChanged: Signal<[player: Player, old: number, new: number]>; /** The swimming character's head went under the surface: IsUnderwater turned true, the moment Breath starts draining when BreathEnabled is on. Always after EnteredWater. Fires on the server and on every client. Use it for an underwater sound, a screen tint or a drowning timer of your own. */ readonly wentUnderwater: Signal<[player: Player]>; /** Fade this player's screen to a color and back (server only), as Camera:Fade does on their own client: player:FadeScreen({To = 1, Duration = 0.4, Audio = true}), move them, then player:FadeScreen({To = 0}). options: To (how covered the screen ends, 0 clear to 1 solid color, default 1), Duration (seconds, 0 to 60, default 0.5; 0 cuts), Color ("#RRGGBB", default black), Audio (default false: true turns all in-game sound down with the picture, all the way at 1; voice chat is not faded; a later fade back toward clear brings the sound up with the picture) and Hold (default true: the screen stays at To once there; false clears it when the fade ends, for a flash). The fade runs from wherever the screen is now, so a fade back in started halfway through a fade out turns back without a jump, and a new fade replaces the last one, its color at once. A fade ending at 0 clears the screen and the sound. Only the 3D picture fades: the HUD, script UI (labels placed in the world included) and the Esc menu draw over it and stay usable. It is kept through a respawn (so a fade can cover one) and clears at once when the script that made it stops. An unknown option or a value of the wrong type is an error that names it. The player's client scripts can fade too; the last fade wins. Does nothing for a player who has left. (server only) */ @@ -434,7 +462,7 @@ interface Player { launch(velocity: Vector3, options?: { override?: boolean | undefined; overrideZ?: boolean | undefined } | undefined): boolean; /** Call handler with the player's attribute value now and every time it changes. The easy way to keep a HUD or nameplate in sync. */ observeAttribute(name: string, handler: (value: any) => void): Connection; - /** Play a clip on the player's body, on the server, and tell everyone (a player who joins later sees it in step). For now this works on a player who is a Custom avatar (SetAvatar): clip is one of its slots ("roar", "attack"), "slot:N" (the Nth clip of a slot, from 0), one of its extras by name, or a place clip id (ast_...) made on the avatar's own skeleton. On a player in a human avatar it returns false (clips on human players come with the creator-clips work, #333). Options: Layer "full" (the whole body, the default) or "upper" (from the avatar's upper-body bone up, the legs keep moving; an avatar with no upper-body bone plays it full); Loop (left out: a slot's own rule, so an attack plays once and a walk loops); PlayRate (0.1 to 4, 1 by default); StartOffset (seconds into the clip); BlendIn and BlendOut (seconds, 0 to 2, 0.2 when left out: the fade into the clip and out of it); StopOnMove (stop when the player moves); KeepTool (a Custom avatar holds no tool). The last call wins: a new clip replaces the one that plays (ClipEnded "replaced"). Returns false, and plays nothing, with a reason in the script log, when the clip is unknown, the player is dead, or they are not a Custom avatar. (server only) */ + /** Play a clip on the player's body, on the server, and tell everyone (a player who joins later sees it in step). On a player in a human avatar, clip is a place clip id (ast_...) made on the UEFN mannequin, or a built-in clip: "pickup", "drink", "use", "sit_bench" (loops), "fidget" or "look_around". On a Custom avatar (SetAvatar), clip is one of its slots ("roar", "attack"), "slot:N" (the Nth clip of a slot, from 0), one of its extras by name, or a place clip id made on the avatar's own skeleton. On either, clip can be "/": the clip named name in the animation pack the place pins under the storage name pack (an avatarStorage entry of kind animPack), made on the body's skeleton. Options: Layer "full" (the whole body, the default) or "upper" (the upper body: from spine_01 up on a human, from the avatar's upper-body bone up on a Custom avatar, which plays it full when it has none; the legs keep moving); Loop (left out: a slot's own rule, so an attack plays once and a walk loops; a place clip plays once); PlayRate (0.1 to 4, 1 by default); StartOffset (seconds into the clip); BlendIn and BlendOut (seconds, 0 to 2, 0.2 when left out: the fade into the clip and out of it); StopOnMove (stop when the player moves or leaves the ground); KeepTool (a full-body clip on a human puts the held tool away unless KeepTool is true; a Custom avatar holds no tool). The clip ends early when the player dies, is knocked down or sits, when they attack, reload or aim, and (a full-body clip) when they climb, vault or dodge or react to a hit; an upper-body clip steps aside for a climb or vault and comes back after it. The last call wins: a new clip replaces the one that plays (ClipEnded "replaced"), an emote replaces the clip and a clip the emote. Returns false, and plays nothing, with a reason in the script log, when the clip is unknown or made on another skeleton (a pack the place does not pin, or a name the pack lacks, is unknown), or the player is dead, knocked down or seated. (server only) */ playClip(clip: string, options?: { layer?: string | undefined; loop?: boolean | undefined; playRate?: number | undefined; startOffset?: number | undefined; blendIn?: number | undefined; blendOut?: number | undefined; stopOnMove?: boolean | undefined; keepTool?: boolean | undefined }): boolean; /** Knock the character down: it goes limp for everyone, the player cannot move or act, and when the time is up (or Recover is called) it stands back up where it lies with a get-up animation. seconds is how long to stay down, 0.1 to 300; leave it out to stay down until Recover (at most five minutes). velocity is an optional shove in centimeters per second; without it the character keeps the speed it had. Ragdolled fires now and Recovered when it gets up. Returns false when the player has no character on foot, is dead, is sitting in a vehicle or is already knocked down. (server only) */ ragdoll(seconds?: number | undefined, velocity?: Vector3 | undefined): boolean; @@ -459,7 +487,7 @@ interface Player { spawn(position?: Vector3 | undefined, yaw?: number | undefined): boolean; /** Stop the clip PlayClip started on the player; ClipEnded fires with "stopped". blendOut (seconds, 0 to 2) is how long the body takes to fade out of the clip; left out, the clip's own BlendOut (0.2 s by default). Returns false when nothing played. (server only) */ stopClip(blendOut?: number | undefined): boolean; - /** Hurt the character through the same path weapons use, so the game's damage rules apply: friendly fire, Armor, then Shield, then health. source is the player to credit: if this hit kills, Died names them as the killer. damageType tags the hit for Damaged and Died ("Generic" when left out); use a built-in such as "Bullet", "Melee", "Explosion", "Fall", "Vehicle", "Area", "Magic" or "Drown", or any word of your own up to 32 characters, such as "Poison". Returns false when the player has no character on foot (respawning or driving), is already dead, or nothing got through (friendly fire off, or Armor 100). (server only) */ + /** Hurt the character through the same path weapons use, so the game's damage rules apply: friendly fire, Armor, then Shield, then health. source is the player to credit: if this hit kills, Died names them as the killer. damageType tags the hit for Damaged and Died ("Generic" when left out); use a built-in such as "Bullet", "Melee", "Explosion", "Fall", "Vehicle", "Area", "Magic", "Drown", "Hunger" or "Thirst", or any word of your own up to 32 characters, such as "Poison". Returns false when the player has no character on foot (respawning or driving), is already dead, or nothing got through (friendly fire off, or Armor 100). (server only) */ takeDamage(amount: number, source?: Player | undefined, damageType?: string | undefined): boolean; /** Move the player's character instantly. Always lands exactly at position, even inside solid geometry; returns false only when the player has no character to move right now. (server only) */ teleport(position: Vector3): boolean; @@ -966,12 +994,14 @@ const Avatar: AvatarService; interface BackpackService { /** One shot or swing of a player's weapon, on the server: each trigger pull of a gun (once for a shotgun's whole spread, once per round of a burst or an automatic), each arrow, spell, launched round or thrown weapon or shield, each swing of a melee weapon, a staff, a bow's bash or the fists, the start of a beam, and a gravity gun's launch. Fires whether or not it hits anything (Entity.Hit, Player.Damaged and NPC.Damaged report what it hit). toolId is the weapon's Tool id in the player's Backpack ("fists" for the fists). origin and direction are where the shot left from and the way it went: a gun's is the player's aim (Player:GetAim, before the spread), a projectile's is where it was launched and its launch direction (a bow's arc included), a swing's or a beam's is the player's aim when it started. Use it for accuracy stats, ammo counters of your own, or an alarm that hears gunshots. Example: `Backpack.Fired:Connect(function(player, toolId) shots[player] = (shots[player] or 0) + 1 end)`. (server only) */ readonly fired: Signal<[player: Player, toolId: string, origin: Vector3, direction: Vector3]>; - /** A consumable (a potion, a medkit, food: a weapon-builder item with the Consumable hold) was used, on the server, at the moment its effect lands: halfway through its drink or use clip. It fires for every use, whether the item has a built-in effect or not, and never for a use that was canceled (sprinting, jumping or dodging first spends nothing). toolId is the item's Tool id in the player's Backpack, docName the name the creator gave it in the builder, usesLeft how many uses it has left (0: it is gone from the Backpack), and builtInEffect whether its own heal also ran (false for an item whose effect is "none": your script is the whole effect). */ + /** A consumable (a potion, a medkit, food: a weapon-builder item with the Consumable hold) was used, on the server, at the moment its effect lands: halfway through its drink or use clip. It fires for every use, whether the item has a built-in effect or not, and never for a use that was canceled (sprinting, jumping or dodging first spends nothing). toolId is the item's Tool id in the player's Backpack, docName the name the creator gave it in the builder, usesLeft how many uses it has left (0: it is gone from the Backpack), and builtInEffect whether its own effect also ran: its heal, or its stamina, hunger or thirst while your script has that pool on (false for an item whose effect is "none", where your script is the whole effect, and for a pool that is off). */ readonly itemUsed: Signal<[player: Player, toolId: string, docName: string, usesLeft: number, builtInEffect: boolean]>; /** A weapon's attachments, stat multipliers or light changed: a script call, a pickup that brought a loadout, or the player's light key. Fires on the server, once the change has taken effect. */ readonly loadoutChanged: Signal<[player: Player, toolId: string]>; /** The local player's Backpack changed: a Tool came or went, a different slot is in the hands, or a consumable's uses changed. Redraw from GetLocal. */ readonly localChanged: Signal<[]>; + /** One use of anything a player holds, on the server, whatever it is: everything Backpack.Fired counts for a weapon (each shot, launch, swing, beam start and gravity gun launch), each consumable's use as it starts (Backpack.ItemUsed is its effect moment, which a canceled use never reaches), and each use of a usable item (hold "item", which does nothing by itself: this is where your script gives it its behavior). toolId is the Tool's id in the player's Backpack ("fists" for the fists), docName its name. Guarding, aiming, reloading and switching are not uses. Example: `Backpack.ToolUsed:Connect(function(player, toolId, name) if name == "Flashlight" then toggleLamp(player) end end)`. (server only) */ + readonly toolUsed: Signal<[player: Player, toolId: string, docName: string]>; /** Put a whole loadout on the weapon, all or nothing: the slots it does not name end up empty, the stats it does not name go back to 1, and a loadout with no round key leaves the weapon's round as it is (1.81: ClearRound takes it off). Returns { ok = true }, or { ok = false, error = ... } as SetAttachment does ("not an option" when the loadout names an option the weapon no longer has, for the script to decide what to do). A loadout that is not the right shape errors. (server only) */ applyLoadout(player: Player, toolId: string, loadout: { attachments?: Record | undefined; stats?: Record | undefined; color?: string | undefined; round?: { name: string; damageMultiplier?: number | undefined; speed?: number | undefined; color?: string | undefined } | undefined }): { ok: boolean; error?: string | undefined }; /** Empty the player's Backpack, leaving only fists. Returns how many Tools were removed. (server only) */ diff --git a/Resources/ScriptApi/mantle.pyi b/Resources/ScriptApi/mantle.pyi index 60883f13..ab68b403 100644 --- a/Resources/ScriptApi/mantle.pyi +++ b/Resources/ScriptApi/mantle.pyi @@ -101,7 +101,7 @@ class Entity: """Push a physics entity: impulse is in kg*cm/s along the world axes, so its velocity changes by impulse / Mass. Does nothing while it is Anchored. Errors on an entity with no physics block.""" ... def attach_to(self, target: Entity, options: dict[str, Any] = ..., /) -> None: - """Stick this entity to target so it follows it wherever it goes: a car, a lift or moving platform, an NPC, or a player's character (player.Character). It is sent to players once and then rides by itself, never lagging behind. options.Offset is where it sits in the target's own space (cm, (0, 0, 0) by default: the target's middle, or the bone's), options.Rotation its turn there as (pitch, yaw, roll) degrees, and options.Bone a bone or socket of the target's skeleton ('hand_r', 'head', 'spine_03') to follow instead of the whole target; Bone = 'HeldItem' follows where the player's held tool or gun sits, so a light attached there points where they aim. Attaching again moves it to the new target or offset. What can be attached: an entity a script may move (a clone, an Assets:Spawn mesh, a light, an effect, a place entity marked 'dynamic', a physics entity); a player's character, an NPC or a vehicle can't be (attach things to them instead). A physics entity is held Anchored while attached, and Detach gives it back what Anchored was, so a crate let go off a truck falls. Attached to a player, an NPC, a vehicle or a physics entity it blocks nothing, so it can't push what carries it (overlaps, Touched and raycasts still find it); attached to anything else it keeps its collision, so a floor riding a lift still holds players up. If the target goes (destroyed, or a player's character replaced when they respawn or leave), the attachment ends and the entity stays where it was. Setting its Position or Rotation, or tweening either, detaches it first. On a player's character Offset may be at most 50 cm and the entity at most 2 m across; anywhere else Offset may be up to 100 m. A place holds at most 256 attachments. Errors for an unknown Bone, a target that rides this entity, or past these limits. On the server everyone sees it; on a client only that player does (a physics entity is attached by a server script only). An attached entity can't be cloned. Example, a flashlight: `local light = Lights:Spawn('Spot', Vector3.new(0, 0, 0)) light:AttachTo(player.Character, {Bone = 'HeldItem', Offset = Vector3.new(0, 20, 0)})`.""" + """Stick this entity to target so it follows it wherever it goes: a car, a lift or moving platform, an NPC, or a player's character (player.Character). It is sent to players once and then rides by itself, never lagging behind. options.Offset is where it sits in the target's own space (cm, (0, 0, 0) by default: the target's middle, or the bone's), options.Rotation its turn there as (pitch, yaw, roll) degrees, and options.Bone a bone or socket of the target's skeleton ('hand_r', 'head', 'spine_03') to follow instead of the whole target; Bone = 'HeldItem' follows where the player's held tool or gun sits, so a light attached there points where they aim. While a usable item or a consumable is in their hand it follows the palm holding it instead, turned as the item is (Offset and Rotation are then along the item mesh's own axes). Attaching again moves it to the new target or offset. What can be attached: an entity a script may move (a clone, an Assets:Spawn mesh, a light, an effect, a place entity marked 'dynamic', a physics entity); a player's character, an NPC or a vehicle can't be (attach things to them instead). A physics entity is held Anchored while attached, and Detach gives it back what Anchored was, so a crate let go off a truck falls. Attached to a player, an NPC, a vehicle or a physics entity it blocks nothing, so it can't push what carries it (overlaps, Touched and raycasts still find it); attached to anything else it keeps its collision, so a floor riding a lift still holds players up. If the target goes (destroyed, or a player's character replaced when they respawn or leave), the attachment ends and the entity stays where it was. Setting its Position or Rotation, or tweening either, detaches it first. On a player's character Offset may be at most 50 cm and the entity at most 2 m across; anywhere else Offset may be up to 100 m. A place holds at most 256 attachments. Errors for an unknown Bone, a target that rides this entity, or past these limits. On the server everyone sees it; on a client only that player does (a physics entity is attached by a server script only). An attached entity can't be cloned. Example, a flashlight: `local light = Lights:Spawn('Spot', Vector3.new(0, 0, 0)) light:AttachTo(player.Character, {Bone = 'HeldItem', Offset = Vector3.new(0, 20, 0)})`.""" ... def clear_highlight(self) -> None: """Remove the outline SetHighlight drew around this entity. On the server it goes for everyone; on a client it removes only that client's own highlight (the server's, if any, shows again). Does nothing when it has none.""" @@ -213,6 +213,10 @@ class Player: health: Optional[float] health_enabled: bool held_tool_id: Optional[str] + hunger: Optional[float] + hunger_damage: Optional[float] + hunger_drain: Optional[float] + hunger_enabled: Optional[bool] input_enabled: Optional[bool] is_crouched: Optional[bool] is_grounded: Optional[bool] @@ -224,8 +228,10 @@ class Player: jump_stamina_cost: Optional[float] max_breath: Optional[float] max_health: Optional[float] + max_hunger: Optional[float] max_shield: Optional[float] max_stamina: Optional[float] + max_thirst: Optional[float] name: str ping: float place_avatar: Optional[str] @@ -246,6 +252,10 @@ class Player: stamina_regen: Optional[float] stamina_regen_delay: Optional[float] team: Optional[str] + thirst: Optional[float] + thirst_damage: Optional[float] + thirst_drain: Optional[float] + thirst_enabled: Optional[bool] tools_enabled: Optional[bool] top_tucked: bool user_id: str @@ -263,6 +273,7 @@ class Player: crouch_started: Signal crouch_stopped: Signal damaged: Signal + dehydrated: Signal died: Signal dimension_changed: Signal dodged: Signal @@ -270,6 +281,7 @@ class Player: entered_water: Signal grab_refused: Signal health_changed: Signal + hunger_changed: Signal jumped: Signal landed: Signal left_water: Signal @@ -284,9 +296,11 @@ class Player: sprint_stopped: Signal staff_extra_used: Signal stamina_changed: Signal + starving: Signal stun_ended: Signal stunned: Signal surfaced: Signal + thirst_changed: Signal went_underwater: Signal def fade_screen(self, options: Optional[dict[str, Any]] = ..., /) -> None: """Fade this player's screen to a color and back (server only), as Camera:Fade does on their own client: player:FadeScreen({To = 1, Duration = 0.4, Audio = true}), move them, then player:FadeScreen({To = 0}). options: To (how covered the screen ends, 0 clear to 1 solid color, default 1), Duration (seconds, 0 to 60, default 0.5; 0 cuts), Color ('#RRGGBB', default black), Audio (default false: true turns all in-game sound down with the picture, all the way at 1; voice chat is not faded; a later fade back toward clear brings the sound up with the picture) and Hold (default true: the screen stays at To once there; false clears it when the fade ends, for a flash). The fade runs from wherever the screen is now, so a fade back in started halfway through a fade out turns back without a jump, and a new fade replaces the last one, its color at once. A fade ending at 0 clears the screen and the sound. Only the 3D picture fades: the HUD, script UI (labels placed in the world included) and the Esc menu draw over it and stay usable. It is kept through a respawn (so a fade can cover one) and clears at once when the script that made it stops. An unknown option or a value of the wrong type is an error that names it. The player's client scripts can fade too; the last fade wins. Does nothing for a player who has left.""" @@ -335,7 +349,7 @@ Example: player:Launch(Vector3.new(0, 0, 1500), {OverrideZ = true})""" """Call handler with the player's attribute value now and every time it changes. The easy way to keep a HUD or nameplate in sync.""" ... def play_clip(self, clip: str, options: dict[str, Any] = ..., /) -> bool: - """Play a clip on the player's body, on the server, and tell everyone (a player who joins later sees it in step). For now this works on a player who is a Custom avatar (SetAvatar): clip is one of its slots ('roar', 'attack'), 'slot:N' (the Nth clip of a slot, from 0), one of its extras by name, or a place clip id (ast_...) made on the avatar's own skeleton. On a player in a human avatar it returns false (clips on human players come with the creator-clips work, #333). Options: Layer 'full' (the whole body, the default) or 'upper' (from the avatar's upper-body bone up, the legs keep moving; an avatar with no upper-body bone plays it full); Loop (left out: a slot's own rule, so an attack plays once and a walk loops); PlayRate (0.1 to 4, 1 by default); StartOffset (seconds into the clip); BlendIn and BlendOut (seconds, 0 to 2, 0.2 when left out: the fade into the clip and out of it); StopOnMove (stop when the player moves); KeepTool (a Custom avatar holds no tool). The last call wins: a new clip replaces the one that plays (ClipEnded 'replaced'). Returns false, and plays nothing, with a reason in the script log, when the clip is unknown, the player is dead, or they are not a Custom avatar.""" + """Play a clip on the player's body, on the server, and tell everyone (a player who joins later sees it in step). On a player in a human avatar, clip is a place clip id (ast_...) made on the UEFN mannequin, or a built-in clip: 'pickup', 'drink', 'use', 'sit_bench' (loops), 'fidget' or 'look_around'. On a Custom avatar (SetAvatar), clip is one of its slots ('roar', 'attack'), 'slot:N' (the Nth clip of a slot, from 0), one of its extras by name, or a place clip id made on the avatar's own skeleton. On either, clip can be '/': the clip named name in the animation pack the place pins under the storage name pack (an avatarStorage entry of kind animPack), made on the body's skeleton. Options: Layer 'full' (the whole body, the default) or 'upper' (the upper body: from spine_01 up on a human, from the avatar's upper-body bone up on a Custom avatar, which plays it full when it has none; the legs keep moving); Loop (left out: a slot's own rule, so an attack plays once and a walk loops; a place clip plays once); PlayRate (0.1 to 4, 1 by default); StartOffset (seconds into the clip); BlendIn and BlendOut (seconds, 0 to 2, 0.2 when left out: the fade into the clip and out of it); StopOnMove (stop when the player moves or leaves the ground); KeepTool (a full-body clip on a human puts the held tool away unless KeepTool is true; a Custom avatar holds no tool). The clip ends early when the player dies, is knocked down or sits, when they attack, reload or aim, and (a full-body clip) when they climb, vault or dodge or react to a hit; an upper-body clip steps aside for a climb or vault and comes back after it. The last call wins: a new clip replaces the one that plays (ClipEnded 'replaced'), an emote replaces the clip and a clip the emote. Returns false, and plays nothing, with a reason in the script log, when the clip is unknown or made on another skeleton (a pack the place does not pin, or a name the pack lacks, is unknown), or the player is dead, knocked down or seated.""" ... def ragdoll(self, seconds: Optional[float] = ..., velocity: Optional[Vector3] = ..., /) -> bool: """Knock the character down: it goes limp for everyone, the player cannot move or act, and when the time is up (or Recover is called) it stands back up where it lies with a get-up animation. seconds is how long to stay down, 0.1 to 300; leave it out to stay down until Recover (at most five minutes). velocity is an optional shove in centimeters per second; without it the character keeps the speed it had. Ragdolled fires now and Recovered when it gets up. Returns false when the player has no character on foot, is dead, is sitting in a vehicle or is already knocked down.""" @@ -369,7 +383,7 @@ TopDown options: Distance (cm from the character, default 1400), MinDistance and """Stop the clip PlayClip started on the player; ClipEnded fires with 'stopped'. blendOut (seconds, 0 to 2) is how long the body takes to fade out of the clip; left out, the clip's own BlendOut (0.2 s by default). Returns false when nothing played.""" ... def take_damage(self, amount: float, source: Optional[Player] = ..., damageType: Optional[str] = ..., /) -> bool: - """Hurt the character through the same path weapons use, so the game's damage rules apply: friendly fire, Armor, then Shield, then health. source is the player to credit: if this hit kills, Died names them as the killer. damageType tags the hit for Damaged and Died ('Generic' when left out); use a built-in such as 'Bullet', 'Melee', 'Explosion', 'Fall', 'Vehicle', 'Area', 'Magic' or 'Drown', or any word of your own up to 32 characters, such as 'Poison'. Returns false when the player has no character on foot (respawning or driving), is already dead, or nothing got through (friendly fire off, or Armor 100).""" + """Hurt the character through the same path weapons use, so the game's damage rules apply: friendly fire, Armor, then Shield, then health. source is the player to credit: if this hit kills, Died names them as the killer. damageType tags the hit for Damaged and Died ('Generic' when left out); use a built-in such as 'Bullet', 'Melee', 'Explosion', 'Fall', 'Vehicle', 'Area', 'Magic', 'Drown', 'Hunger' or 'Thirst', or any word of your own up to 32 characters, such as 'Poison'. Returns false when the player has no character on foot (respawning or driving), is already dead, or nothing got through (friendly fire off, or Armor 100).""" ... def teleport(self, position: Vector3, /) -> bool: """Move the player's character instantly. Always lands exactly at position, even inside solid geometry; returns false only when the player has no character to move right now.""" @@ -941,6 +955,7 @@ class _BackpackService: item_used: Signal loadout_changed: Signal local_changed: Signal + tool_used: Signal def apply_loadout(self, player: Player, toolId: str, loadout: dict[str, Any], /) -> dict[str, Any]: """Put a whole loadout on the weapon, all or nothing: the slots it does not name end up empty, the stats it does not name go back to 1, and a loadout with no round key leaves the weapon's round as it is (1.81: ClearRound takes it off). Returns { ok = true }, or { ok = false, error = ... } as SetAttachment does ('not an option' when the loadout names an option the weapon no longer has, for the script to decide what to do). A loadout that is not the right shape errors.""" ... diff --git a/Resources/ScriptApi/mantle_api.json b/Resources/ScriptApi/mantle_api.json index 9edf4c62..b2626c3e 100644 --- a/Resources/ScriptApi/mantle_api.json +++ b/Resources/ScriptApi/mantle_api.json @@ -1,9 +1,9 @@ -{"major":1,"minor":115,"classes":[ +{"major":1,"minor":118,"classes":[ {"name":"Entity","service":false,"introducedMinor":0,"doc":"A thing in the world: any actor in the level.", "methods":[{"name":"AddTag","side":"server","params":[{"name":"tag","type":"string","optional":false}],"variadic":false,"returns":"()","kit":false,"doc":"Give the entity a tag (fires World:OnTagged handlers).","deprecated":false,"deprecatedReason":"","introducedMinor":0}, {"name":"ApplyAngularImpulse","side":"server","params":[{"name":"impulse","type":"Vector3","optional":false}],"variadic":false,"returns":"()","kit":false,"doc":"Spin a physics entity: an angular impulse in kg*cm^2/s about the world axes, in degrees. Does nothing while it is Anchored. Errors on an entity with no physics block.","deprecated":false,"deprecatedReason":"","introducedMinor":15}, {"name":"ApplyImpulse","side":"server","params":[{"name":"impulse","type":"Vector3","optional":false}],"variadic":false,"returns":"()","kit":false,"doc":"Push a physics entity: impulse is in kg*cm/s along the world axes, so its velocity changes by impulse / Mass. Does nothing while it is Anchored. Errors on an entity with no physics block.","deprecated":false,"deprecatedReason":"","introducedMinor":15}, -{"name":"AttachTo","side":"both","params":[{"name":"target","type":"Entity","optional":false},{"name":"options","type":"{Offset: Vector3?, Rotation: Vector3?, Bone: string?}","optional":true}],"variadic":false,"returns":"()","kit":false,"doc":"Stick this entity to target so it follows it wherever it goes: a car, a lift or moving platform, an NPC, or a player's character (player.Character). It is sent to players once and then rides by itself, never lagging behind. options.Offset is where it sits in the target's own space (cm, (0, 0, 0) by default: the target's middle, or the bone's), options.Rotation its turn there as (pitch, yaw, roll) degrees, and options.Bone a bone or socket of the target's skeleton (\"hand_r\", \"head\", \"spine_03\") to follow instead of the whole target; Bone = \"HeldItem\" follows where the player's held tool or gun sits, so a light attached there points where they aim. Attaching again moves it to the new target or offset. What can be attached: an entity a script may move (a clone, an Assets:Spawn mesh, a light, an effect, a place entity marked \"dynamic\", a physics entity); a player's character, an NPC or a vehicle can't be (attach things to them instead). A physics entity is held Anchored while attached, and Detach gives it back what Anchored was, so a crate let go off a truck falls. Attached to a player, an NPC, a vehicle or a physics entity it blocks nothing, so it can't push what carries it (overlaps, Touched and raycasts still find it); attached to anything else it keeps its collision, so a floor riding a lift still holds players up. If the target goes (destroyed, or a player's character replaced when they respawn or leave), the attachment ends and the entity stays where it was. Setting its Position or Rotation, or tweening either, detaches it first. On a player's character Offset may be at most 50 cm and the entity at most 2 m across; anywhere else Offset may be up to 100 m. A place holds at most 256 attachments. Errors for an unknown Bone, a target that rides this entity, or past these limits. On the server everyone sees it; on a client only that player does (a physics entity is attached by a server script only). An attached entity can't be cloned. Example, a flashlight: `local light = Lights:Spawn(\"Spot\", Vector3.new(0, 0, 0)) light:AttachTo(player.Character, {Bone = \"HeldItem\", Offset = Vector3.new(0, 20, 0)})`.","deprecated":false,"deprecatedReason":"","introducedMinor":113}, +{"name":"AttachTo","side":"both","params":[{"name":"target","type":"Entity","optional":false},{"name":"options","type":"{Offset: Vector3?, Rotation: Vector3?, Bone: string?}","optional":true}],"variadic":false,"returns":"()","kit":false,"doc":"Stick this entity to target so it follows it wherever it goes: a car, a lift or moving platform, an NPC, or a player's character (player.Character). It is sent to players once and then rides by itself, never lagging behind. options.Offset is where it sits in the target's own space (cm, (0, 0, 0) by default: the target's middle, or the bone's), options.Rotation its turn there as (pitch, yaw, roll) degrees, and options.Bone a bone or socket of the target's skeleton (\"hand_r\", \"head\", \"spine_03\") to follow instead of the whole target; Bone = \"HeldItem\" follows where the player's held tool or gun sits, so a light attached there points where they aim. While a usable item or a consumable is in their hand it follows the palm holding it instead, turned as the item is (Offset and Rotation are then along the item mesh's own axes). Attaching again moves it to the new target or offset. What can be attached: an entity a script may move (a clone, an Assets:Spawn mesh, a light, an effect, a place entity marked \"dynamic\", a physics entity); a player's character, an NPC or a vehicle can't be (attach things to them instead). A physics entity is held Anchored while attached, and Detach gives it back what Anchored was, so a crate let go off a truck falls. Attached to a player, an NPC, a vehicle or a physics entity it blocks nothing, so it can't push what carries it (overlaps, Touched and raycasts still find it); attached to anything else it keeps its collision, so a floor riding a lift still holds players up. If the target goes (destroyed, or a player's character replaced when they respawn or leave), the attachment ends and the entity stays where it was. Setting its Position or Rotation, or tweening either, detaches it first. On a player's character Offset may be at most 50 cm and the entity at most 2 m across; anywhere else Offset may be up to 100 m. A place holds at most 256 attachments. Errors for an unknown Bone, a target that rides this entity, or past these limits. On the server everyone sees it; on a client only that player does (a physics entity is attached by a server script only). An attached entity can't be cloned. Example, a flashlight: `local light = Lights:Spawn(\"Spot\", Vector3.new(0, 0, 0)) light:AttachTo(player.Character, {Bone = \"HeldItem\", Offset = Vector3.new(0, 20, 0)})`.","deprecated":false,"deprecatedReason":"","introducedMinor":113}, {"name":"ClearHighlight","side":"both","params":[],"variadic":false,"returns":"()","kit":false,"doc":"Remove the outline SetHighlight drew around this entity. On the server it goes for everyone; on a client it removes only that client's own highlight (the server's, if any, shows again). Does nothing when it has none.","deprecated":false,"deprecatedReason":"","introducedMinor":113}, {"name":"Clone","side":"both","params":[],"variadic":false,"returns":"Entity","kit":false,"doc":"Make a copy (same look, tags and place). On the server the copy appears for everyone; on a client only for that player. Tip: keep a hidden template and clone it. A physics entity is copied by a server script: the copy has its mass, PhysicsMaterial and Grabbable, starts Anchored or simulating as the original is, at rest, and can be joined with Constraints:Create. It stands exactly where the original does until you move it, and physics only steps after your script, so set its Position right after cloning. A Constraint or an NPC can't be cloned (it errors, and says how to make another), nor can a client script clone a physics entity, and an entity attached with AttachTo can't be cloned until it is detached.","deprecated":false,"deprecatedReason":"","introducedMinor":0}, {"name":"Destroy","side":"both","params":[],"variadic":false,"returns":"()","kit":false,"doc":"Remove the entity. On the server it disappears for everyone; on a client only for that player.","deprecated":false,"deprecatedReason":"","introducedMinor":0}, @@ -92,7 +92,7 @@ {"name":"Kill","side":"server","params":[],"variadic":false,"returns":"boolean","kit":false,"doc":"Kill the character outright: Died fires with no killer, and the place's respawn rules take over as for any other death. Returns false when the player has no character on foot or is already dead. While HealthEnabled is false it does nothing, prints a warning to the script output and returns false.","deprecated":false,"deprecatedReason":"","introducedMinor":9}, {"name":"Launch","side":"server","params":[{"name":"velocity","type":"Vector3","optional":false},{"name":"options","type":"{Override: boolean?, OverrideZ: boolean?}?","optional":true}],"variadic":false,"returns":"boolean","kit":false,"doc":"Send the character flying with velocity (centimeters per second) added to the speed it has, and it stays on its feet: it falls, steers in the air and lands as after a jump, with no knockdown (Ragdoll is the one that knocks it down). options.Override true sets its speed to velocity instead of adding to it, and options.OverrideZ true does that for the up and down part only (a jump pad that always throws to the same height, however fast the player fell onto it). Each part of velocity clamps to -10000..10000. It is a one-off push, not a force to call every frame: two launches before the character next moves add up (an override in the second still replaces its parts). The server decides it and the player's own machine is brought along with its next movement update, about one round trip later. Works while InputEnabled is false. A launch is a fall like any other, so with FallDamage on a high one hurts when it lands: the example below comes down at about 1500 cm/s, 15 health at FallDamage 5 and the default FallDamageSpeed. Returns false when the player has no character on foot, is dead, knocked down, seated, swimming (the water would take them straight back) or in the middle of a vault or climb. Use it for jump pads, launchers, knockback and blasts that push without knocking down.\nExample: player:Launch(Vector3.new(0, 0, 1500), {OverrideZ = true})","deprecated":false,"deprecatedReason":"","introducedMinor":113}, {"name":"ObserveAttribute","side":"both","params":[{"name":"name","type":"string","optional":false},{"name":"handler","type":"(value: any) -> ()","optional":false}],"variadic":false,"returns":"Connection","kit":true,"doc":"Call handler with the player's attribute value now and every time it changes. The easy way to keep a HUD or nameplate in sync.","deprecated":false,"deprecatedReason":"","introducedMinor":113}, -{"name":"PlayClip","side":"server","params":[{"name":"clip","type":"string","optional":false},{"name":"options","type":"{Layer: string?, Loop: boolean?, PlayRate: number?, StartOffset: number?, BlendIn: number?, BlendOut: number?, StopOnMove: boolean?, KeepTool: boolean?}","optional":true}],"variadic":false,"returns":"boolean","kit":false,"doc":"Play a clip on the player's body, on the server, and tell everyone (a player who joins later sees it in step). For now this works on a player who is a Custom avatar (SetAvatar): clip is one of its slots (\"roar\", \"attack\"), \"slot:N\" (the Nth clip of a slot, from 0), one of its extras by name, or a place clip id (ast_...) made on the avatar's own skeleton. On a player in a human avatar it returns false (clips on human players come with the creator-clips work, #333). Options: Layer \"full\" (the whole body, the default) or \"upper\" (from the avatar's upper-body bone up, the legs keep moving; an avatar with no upper-body bone plays it full); Loop (left out: a slot's own rule, so an attack plays once and a walk loops); PlayRate (0.1 to 4, 1 by default); StartOffset (seconds into the clip); BlendIn and BlendOut (seconds, 0 to 2, 0.2 when left out: the fade into the clip and out of it); StopOnMove (stop when the player moves); KeepTool (a Custom avatar holds no tool). The last call wins: a new clip replaces the one that plays (ClipEnded \"replaced\"). Returns false, and plays nothing, with a reason in the script log, when the clip is unknown, the player is dead, or they are not a Custom avatar.","deprecated":false,"deprecatedReason":"","introducedMinor":115}, +{"name":"PlayClip","side":"server","params":[{"name":"clip","type":"string","optional":false},{"name":"options","type":"{Layer: string?, Loop: boolean?, PlayRate: number?, StartOffset: number?, BlendIn: number?, BlendOut: number?, StopOnMove: boolean?, KeepTool: boolean?}","optional":true}],"variadic":false,"returns":"boolean","kit":false,"doc":"Play a clip on the player's body, on the server, and tell everyone (a player who joins later sees it in step). On a player in a human avatar, clip is a place clip id (ast_...) made on the UEFN mannequin, or a built-in clip: \"pickup\", \"drink\", \"use\", \"sit_bench\" (loops), \"fidget\" or \"look_around\". On a Custom avatar (SetAvatar), clip is one of its slots (\"roar\", \"attack\"), \"slot:N\" (the Nth clip of a slot, from 0), one of its extras by name, or a place clip id made on the avatar's own skeleton. On either, clip can be \"/\": the clip named name in the animation pack the place pins under the storage name pack (an avatarStorage entry of kind animPack), made on the body's skeleton. Options: Layer \"full\" (the whole body, the default) or \"upper\" (the upper body: from spine_01 up on a human, from the avatar's upper-body bone up on a Custom avatar, which plays it full when it has none; the legs keep moving); Loop (left out: a slot's own rule, so an attack plays once and a walk loops; a place clip plays once); PlayRate (0.1 to 4, 1 by default); StartOffset (seconds into the clip); BlendIn and BlendOut (seconds, 0 to 2, 0.2 when left out: the fade into the clip and out of it); StopOnMove (stop when the player moves or leaves the ground); KeepTool (a full-body clip on a human puts the held tool away unless KeepTool is true; a Custom avatar holds no tool). The clip ends early when the player dies, is knocked down or sits, when they attack, reload or aim, and (a full-body clip) when they climb, vault or dodge or react to a hit; an upper-body clip steps aside for a climb or vault and comes back after it. The last call wins: a new clip replaces the one that plays (ClipEnded \"replaced\"), an emote replaces the clip and a clip the emote. Returns false, and plays nothing, with a reason in the script log, when the clip is unknown or made on another skeleton (a pack the place does not pin, or a name the pack lacks, is unknown), or the player is dead, knocked down or seated.","deprecated":false,"deprecatedReason":"","introducedMinor":115}, {"name":"Ragdoll","side":"server","params":[{"name":"seconds","type":"number?","optional":true},{"name":"velocity","type":"Vector3?","optional":true}],"variadic":false,"returns":"boolean","kit":false,"doc":"Knock the character down: it goes limp for everyone, the player cannot move or act, and when the time is up (or Recover is called) it stands back up where it lies with a get-up animation. seconds is how long to stay down, 0.1 to 300; leave it out to stay down until Recover (at most five minutes). velocity is an optional shove in centimeters per second; without it the character keeps the speed it had. Ragdolled fires now and Recovered when it gets up. Returns false when the player has no character on foot, is dead, is sitting in a vehicle or is already knocked down.","deprecated":false,"deprecatedReason":"","introducedMinor":40}, {"name":"Recover","side":"server","params":[],"variadic":false,"returns":"boolean","kit":false,"doc":"Stand a knocked-down character back up now, wherever it lies; Recovered fires when it is up. Safe to call at any time. Returns false when the character was not knocked down.","deprecated":false,"deprecatedReason":"","introducedMinor":40}, {"name":"ReleaseCrouch","side":"server","params":[],"variadic":false,"returns":"boolean","kit":false,"doc":"Give the player the crouch key back after ForceCrouch. Returns false when the player has no character on foot.","deprecated":false,"deprecatedReason":"","introducedMinor":40}, @@ -103,7 +103,7 @@ {"name":"SetVisibleFor","side":"server","params":[{"name":"viewer","type":"Player","optional":false},{"name":"visible","type":"boolean","optional":false}],"variadic":false,"returns":"()","kit":false,"doc":"Hide (false) or show again (true) this player's character for one viewer only: the viewer's machine is not sent it (no model, nameplate, held tool or minimap dot), also after a respawn (a body left behind too). A vehicle they drive is the vehicle's own: hide it with Entity:SetVisibleFor as well, or the viewer still sees it (and its dot) move. Everyone else is unchanged, and it can't show a player in another dimension. Their voice is not changed (use Voice:MuteFor), and they stay in the player list. Errors when viewer is the player themselves, past 1024 hidden things at once, or when the server can't keep it apart, changing nothing. Lasts until either player leaves. Example: ghost:SetVisibleFor(hunter, false).","deprecated":false,"deprecatedReason":"","introducedMinor":113}, {"name":"Spawn","side":"server","params":[{"name":"position","type":"Vector3?","optional":true},{"name":"yaw","type":"number?","optional":true}],"variadic":false,"returns":"boolean","kit":false,"doc":"Give a player who has no character one now: at position (facing yaw degrees, else the way the place's spawn point faces) when given, otherwise where Respawn:SetSpawnPicker's picker or the place's spawn points say. Use it with Players.AutoSpawn set false, once the player has picked a character. CharacterAdded fires for it. Returns false when the player already has a character, a corpse or a vehicle (Player:Respawn replaces a character), when called from inside the spawn picker, when position is outside the world (below the place's kill floor or past its edge), or when no character could be spawned. Example: Players.AutoSpawn = false; Players.PlayerAdded:Connect(function(p) menu:Show(p) end); -- later, when they pick: p:Spawn()","deprecated":false,"deprecatedReason":"","introducedMinor":113}, {"name":"StopClip","side":"server","params":[{"name":"blendOut","type":"number?","optional":true}],"variadic":false,"returns":"boolean","kit":false,"doc":"Stop the clip PlayClip started on the player; ClipEnded fires with \"stopped\". blendOut (seconds, 0 to 2) is how long the body takes to fade out of the clip; left out, the clip's own BlendOut (0.2 s by default). Returns false when nothing played.","deprecated":false,"deprecatedReason":"","introducedMinor":115}, -{"name":"TakeDamage","side":"server","params":[{"name":"amount","type":"number","optional":false},{"name":"source","type":"Player?","optional":true},{"name":"damageType","type":"string?","optional":true}],"variadic":false,"returns":"boolean","kit":false,"doc":"Hurt the character through the same path weapons use, so the game's damage rules apply: friendly fire, Armor, then Shield, then health. source is the player to credit: if this hit kills, Died names them as the killer. damageType tags the hit for Damaged and Died (\"Generic\" when left out); use a built-in such as \"Bullet\", \"Melee\", \"Explosion\", \"Fall\", \"Vehicle\", \"Area\", \"Magic\" or \"Drown\", or any word of your own up to 32 characters, such as \"Poison\". Returns false when the player has no character on foot (respawning or driving), is already dead, or nothing got through (friendly fire off, or Armor 100).","deprecated":false,"deprecatedReason":"","introducedMinor":9}, +{"name":"TakeDamage","side":"server","params":[{"name":"amount","type":"number","optional":false},{"name":"source","type":"Player?","optional":true},{"name":"damageType","type":"string?","optional":true}],"variadic":false,"returns":"boolean","kit":false,"doc":"Hurt the character through the same path weapons use, so the game's damage rules apply: friendly fire, Armor, then Shield, then health. source is the player to credit: if this hit kills, Died names them as the killer. damageType tags the hit for Damaged and Died (\"Generic\" when left out); use a built-in such as \"Bullet\", \"Melee\", \"Explosion\", \"Fall\", \"Vehicle\", \"Area\", \"Magic\", \"Drown\", \"Hunger\" or \"Thirst\", or any word of your own up to 32 characters, such as \"Poison\". Returns false when the player has no character on foot (respawning or driving), is already dead, or nothing got through (friendly fire off, or Armor 100).","deprecated":false,"deprecatedReason":"","introducedMinor":9}, {"name":"Teleport","side":"server","params":[{"name":"position","type":"Vector3","optional":false}],"variadic":false,"returns":"boolean","kit":false,"doc":"Move the player's character instantly. Always lands exactly at position, even inside solid geometry; returns false only when the player has no character to move right now.","deprecated":false,"deprecatedReason":"","introducedMinor":0}], "properties":[{"name":"Armor","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"How much of every hit the character shrugs off, as a percent from 0 (none, the default) to 100 (all of it). Armor works before the Shield and health. nil while the player has no character. Setting it (server only) clamps to 0..100 and lasts for the rest of the session, through respawns.","deprecated":false,"deprecatedReason":"","introducedMinor":39}, {"name":"Avatar","type":"string?","getSide":"server","settable":false,"setSide":"server","doc":"The item id of the avatar (body) the player has on, or nil before their look has arrived. Read-only.","deprecated":false,"deprecatedReason":"","introducedMinor":2}, @@ -128,6 +128,10 @@ {"name":"Health","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"The character's health, from 0 to MaxHealth; nil while the player has no character. Weapons and TakeDamage lower this same value. Setting it (server only) clamps to 0..MaxHealth, and 0 kills the character with no killer. Setting it on a dead player, or one driving a vehicle, does nothing: use Respawn to bring a player back. While HealthEnabled is false, setting it to 0 does nothing and prints a warning to the script output.","deprecated":false,"deprecatedReason":"","introducedMinor":9}, {"name":"HealthEnabled","type":"boolean","getSide":"both","settable":true,"setSide":"server","doc":"Whether this player has health: damage, death, and falling out of the map killing them. false unless the place turns it on (settings.health in the place file) or a script does. Setting it (server only) lasts for the rest of the session, through respawns, until the script that set it stops, when the player goes back to the place's setting. Armor and Shield only matter while it is on. While it is off nothing hurts the player (weapons, vehicles, crashes, drowning and TakeDamage do nothing), Kill and setting Health to 0 do nothing and print a warning to the script output, and falling out of the map moves the player to a spawn point with no death. Turning it on mid-game starts the player at full health. Readable on the server and on that player's own client.","deprecated":false,"deprecatedReason":"","introducedMinor":91}, {"name":"HeldToolId","type":"string?","getSide":"both","settable":false,"setSide":"server","doc":"The id of the Tool in the player's hands (the id Backpack:GetTools lists); nil with bare hands, and while the player has no character. Readable on the server and on every client.","deprecated":false,"deprecatedReason":"","introducedMinor":76}, +{"name":"Hunger","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"How full the character's hunger pool is, from 0 (empty: it hurts) to MaxHunger (it counts in small steps, and moves only while HungerEnabled is true). nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..MaxHunger: that is how a script feeds the player. Every new character starts full.","deprecated":false,"deprecatedReason":"","introducedMinor":117}, +{"name":"HungerDamage","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"How much health the character loses each second while its Hunger is empty, dealt once a second and tagged \"Hunger\" (1 unless a script changes it). It goes past Armor and Shield, and nobody is credited for the kill. 0: an empty pool does no harm. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session, through respawns.","deprecated":false,"deprecatedReason":"","introducedMinor":117}, +{"name":"HungerDrain","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"How much Hunger the character loses each second while HungerEnabled is true (0.1 unless a script changes it: a full pool of 100 lasts about 17 minutes). 0 holds it where it is. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session, through respawns.","deprecated":false,"deprecatedReason":"","introducedMinor":117}, +{"name":"HungerEnabled","type":"boolean?","getSide":"both","settable":true,"setSide":"server","doc":"Whether the player gets hungry (false unless a script turns it on, so places that never use it play as before). With it on, Hunger drains by HungerDrain every second, and once it is empty the character takes HungerDamage every second until something fills it again (Died then says \"Hunger\"): a script setting Hunger, or a consumable whose effect is hunger. Turning it on starts it full. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) lasts for the rest of the session, through respawns. Mantle draws no bar for it: show it with your own UI.","deprecated":false,"deprecatedReason":"","introducedMinor":117}, {"name":"InputEnabled","type":"boolean?","getSide":"both","settable":true,"setSide":"server","doc":"Whether the player's own controls move and act for their character (true unless a script changes it); nil while the player has no character. Setting it (server only) to false stops moving, looking around, aiming, jumping, crouching, dodging, climbing, using tools and entering or driving vehicles: the keys and the pad do nothing for the character, and a key held at the time is let go. The menu (Esc, Start), chat, push to talk, the leaderboard and script UI still work, and so do the place's own Input bindings, so a cutscene can still be skipped with a key. Scripts can still move the character (Teleport, Launch; Player:Jump is refused while it is false). A player driving a vehicle can neither drive nor get out while it is false: the controls go to rest. Turning it off (or on) mid-move can cost the player's own machine one round trip of corrected movement, as ToolsEnabled does. It lasts for the rest of the session, through respawns. Use it for cutscenes, stuns and freezes, and intro sequences.","deprecated":false,"deprecatedReason":"","introducedMinor":113}, {"name":"IsCrouched","type":"boolean?","getSide":"both","settable":false,"setSide":"server","doc":"Whether the character is crouched right now (by the key, a slide or ForceCrouch). nil while the player has no character. Read-only.","deprecated":false,"deprecatedReason":"","introducedMinor":40}, {"name":"IsGrounded","type":"boolean?","getSide":"both","settable":false,"setSide":"server","doc":"Whether the character is standing on the ground right now (walking, running or crouched; not in the air, swimming, climbing or seated). nil while the player has no character. Read-only, on the server and every client.","deprecated":false,"deprecatedReason":"","introducedMinor":113}, @@ -139,8 +143,10 @@ {"name":"JumpStaminaCost","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"How much stamina a jump costs (0 unless a script changes it, so jumping is free); with a cost, a character with less stamina than that cannot jump. nil while the player has no character. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session. Only counts while StaminaEnabled is true.","deprecated":false,"deprecatedReason":"","introducedMinor":40}, {"name":"MaxBreath","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"How many seconds the character can stay underwater on a full breath (20 unless a script changes it); nil while the player has no character. Setting it (server only) clamps to 1..3600 and lasts for the rest of the session, through respawns. Lowering it below Breath lowers Breath too; raising it does not refill.","deprecated":false,"deprecatedReason":"","introducedMinor":45}, {"name":"MaxHealth","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"The most health the character can have (100 unless a script changes it); nil while the player has no character. Setting it (server only) clamps to 1..10000 and lasts for the rest of the session: every respawn starts with full health at this maximum. Lowering it below Health lowers Health too; raising it does not heal.","deprecated":false,"deprecatedReason":"","introducedMinor":9}, +{"name":"MaxHunger","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"The full hunger pool (100 unless a script changes it). nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 1..10000 and lasts for the rest of the session, through respawns. Lowering it below Hunger lowers Hunger too; raising it keeps a full pool full.","deprecated":false,"deprecatedReason":"","introducedMinor":117}, {"name":"MaxShield","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"The size of the shield pool (0, no shield, unless a script changes it); nil while the player has no character. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session. A shield above the new size drops to it; raising an existing shield does not fill the pool (set Shield for that), but giving a shield to a player who had none starts it full.","deprecated":false,"deprecatedReason":"","introducedMinor":39}, {"name":"MaxStamina","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"The most stamina the character can have (100 unless a script changes it); nil while the player has no character. Setting it (server only) clamps to 1..10000 and lasts for the rest of the session, through respawns. Lowering it below Stamina lowers Stamina too; raising it does not refill.","deprecated":false,"deprecatedReason":"","introducedMinor":40}, +{"name":"MaxThirst","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"The full thirst pool (100 unless a script changes it). nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 1..10000 and lasts for the rest of the session, through respawns. Lowering it below Thirst lowers Thirst too; raising it keeps a full pool full.","deprecated":false,"deprecatedReason":"","introducedMinor":117}, {"name":"Name","type":"string","getSide":"both","settable":false,"setSide":"server","doc":"The player's Epic display name.","deprecated":false,"deprecatedReason":"","introducedMinor":0}, {"name":"Ping","type":"number","getSide":"both","settable":false,"setSide":"server","doc":"The player's round-trip time to the server in milliseconds, a whole number. Read-only. Works on the server and every client, for any player. It is the average of the last few seconds, updated about once a second; on another player's client it arrives with that player's replication, in 4 ms steps and at most 1020 (about 1100 elsewhere). 0 when there is no network in between (single player, a listen server's own player) or before the first measurement, and when the player has left. Example: label.Text = player.Ping .. \" ms\"","deprecated":false,"deprecatedReason":"","introducedMinor":113}, {"name":"PlaceAvatar","type":"string?","getSide":"both","settable":false,"setSide":"server","doc":"The name, in the place's avatarStorage, of the Custom avatar the player is right now (put on with SetAvatar), or nil when they are their own avatar. Read-only. Readable on the server and on every client.","deprecated":false,"deprecatedReason":"","introducedMinor":115}, @@ -161,6 +167,10 @@ {"name":"StaminaRegen","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"How much stamina comes back each second once the character has rested (15 unless a script changes it); nil while the player has no character. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session.","deprecated":false,"deprecatedReason":"","introducedMinor":40}, {"name":"StaminaRegenDelay","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"How many seconds after sprinting (or a jump that cost stamina) before stamina starts coming back (1 unless a script changes it); nil while the player has no character. Setting it (server only) clamps to 0..60 and lasts for the rest of the session.","deprecated":false,"deprecatedReason":"","introducedMinor":40}, {"name":"Team","type":"string?","getSide":"both","settable":true,"setSide":"server","doc":"The name of the team the player is on, or nil for none. Setting it (server only) puts the player on that team, which must exist (Teams:Create); set nil to take them off. Fires Teams.PlayerTeamChanged. Team membership replicates, so client scripts can read it, and it lasts while the player is in the session.","deprecated":false,"deprecatedReason":"","introducedMinor":39}, +{"name":"Thirst","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"How full the character's thirst pool is, from 0 (empty: it hurts) to MaxThirst (it counts in small steps, and moves only while ThirstEnabled is true). nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..MaxThirst: that is how a script feeds the player. Every new character starts full.","deprecated":false,"deprecatedReason":"","introducedMinor":117}, +{"name":"ThirstDamage","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"How much health the character loses each second while its Thirst is empty, dealt once a second and tagged \"Thirst\" (1 unless a script changes it). It goes past Armor and Shield, and nobody is credited for the kill. 0: an empty pool does no harm. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session, through respawns.","deprecated":false,"deprecatedReason":"","introducedMinor":117}, +{"name":"ThirstDrain","type":"number?","getSide":"both","settable":true,"setSide":"server","doc":"How much Thirst the character loses each second while ThirstEnabled is true (0.1 unless a script changes it: a full pool of 100 lasts about 17 minutes). 0 holds it where it is. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) clamps to 0..10000 and lasts for the rest of the session, through respawns.","deprecated":false,"deprecatedReason":"","introducedMinor":117}, +{"name":"ThirstEnabled","type":"boolean?","getSide":"both","settable":true,"setSide":"server","doc":"Whether the player gets thirsty (false unless a script turns it on, so places that never use it play as before). With it on, Thirst drains by ThirstDrain every second, and once it is empty the character takes ThirstDamage every second until something fills it again (Died then says \"Thirst\"): a script setting Thirst, or a consumable whose effect is thirst. Turning it on starts it full. nil while the player has no character, and on any machine but the server and the player's own. Setting it (server only) lasts for the rest of the session, through respawns. Mantle draws no bar for it: show it with your own UI.","deprecated":false,"deprecatedReason":"","introducedMinor":117}, {"name":"ToolsEnabled","type":"boolean?","getSide":"both","settable":true,"setSide":"server","doc":"Whether the player can use their tools (true unless a script changes it); nil while the player has no character. Setting it (server only) to false puts the tool in hand away and leaves the hands empty: no attacking, guarding, firing, reloading, using an item, drawing a tool or switching tools, the built-in fists included. The tools stay in the Backpack, and a tool a script or pickup gives meanwhile goes into the Backpack without coming to hand. Setting it back to true gives back the tool it put away (if the hands are still empty). The dodge is not a tool: DodgeEnabled and CombatEnabled keep it. The fists punch only while both CombatEnabled and ToolsEnabled are true. Use it for safe zones, lobbies and cutscenes. It lasts for the rest of the session, through respawns.","deprecated":false,"deprecatedReason":"","introducedMinor":113}, {"name":"TopTucked","type":"boolean","getSide":"server","settable":false,"setSide":"server","doc":"Whether the player has their worn top tucked in under their bottoms (their Tuck in switch in the avatar editor, off by default). false when no top is worn or their look has not arrived. A top its creator made untuckable stays out whatever this says. Read-only.","deprecated":false,"deprecatedReason":"","introducedMinor":96}, {"name":"UserId","type":"string","getSide":"both","settable":false,"setSide":"server","doc":"The player's verified Mantle account id (a plain UUID).","deprecated":false,"deprecatedReason":"","introducedMinor":0}, @@ -173,11 +183,12 @@ {"name":"BreathChanged","args":"(player: Player, old: number, new: number)","side":"both","doc":"The character's Breath changed: holding it underwater, getting it back at the surface or a script setting it. It reports steps of about half a percent of MaxBreath, not every frame. Fires on the server and on every client while BreathEnabled is true.","deprecated":false,"deprecatedReason":"","introducedMinor":45}, {"name":"BreathRestored","args":"(player: Player)","side":"both","doc":"The character's Breath is full again after it had used some. Fires on the server and on every client.","deprecated":false,"deprecatedReason":"","introducedMinor":45}, {"name":"CharacterAdded","args":"(player: Player, character: Entity)","side":"server","doc":"The player has a fresh character, ready for weapons, attributes or a teleport: the first one when they join (or when Player:Spawn gives it), and every one after a death, Player:Respawn or Player:Spawn. character is the same Entity as Player.Character. Fires on the server, the tick after the character appears and after PlayerAdded for a player who just joined. Players:OnCharacter also covers characters that already exist.","deprecated":false,"deprecatedReason":"","introducedMinor":113}, -{"name":"ClipEnded","args":"(player: Player, clip: string, reason: string)","side":"server","doc":"A clip PlayClip started on the player ended, on the server. clip is the name you gave. reason is \"finished\" (it played out), \"stopped\" (StopClip), \"replaced\" (a new PlayClip, or a change of body: another avatar, or their own again), \"moved\" (StopOnMove and the player moved), \"action\" (death, a seat or a knockdown took the body) or \"removed\" (the player left or their character was replaced). A looping clip never finishes.","deprecated":false,"deprecatedReason":"","introducedMinor":115}, -{"name":"ClipEvent","args":"(player: Player, clip: string, name: string)","side":"server","doc":"A clip PlayClip started on the player crossed a marker its creator put in it, on the server, at the time the marker was set (a loop fires it every pass). name is the marker: \"impact\", the moment a swing lands. Only the avatar's own slots and extras carry it (a place clip you name by id fires none). Footstep markers stay on the player's own machine and fire nothing.","deprecated":false,"deprecatedReason":"","introducedMinor":115}, +{"name":"ClipEnded","args":"(player: Player, clip: string, reason: string)","side":"server","doc":"A clip PlayClip started on the player ended, on the server. clip is the name you gave. reason is \"finished\" (it played out), \"stopped\" (StopClip), \"replaced\" (a new PlayClip, an emote, or a change of body: another avatar, or their own again), \"moved\" (StopOnMove and the player moved), \"action\" (death, a seat or a knockdown took the body; an attack, reload or aim; a climb, vault, dodge or hit reaction ended a full-body clip) or \"removed\" (the player left or their character was replaced). A looping clip never finishes.","deprecated":false,"deprecatedReason":"","introducedMinor":115}, +{"name":"ClipEvent","args":"(player: Player, clip: string, name: string)","side":"server","doc":"A clip PlayClip started on the player crossed a marker its creator put in it, on the server, at the time the marker was set (a loop fires it every pass). name is the marker: \"impact\", the moment a swing lands. A slot, an extra, a place clip or a pack clip fires it when its creator set an \"impact\" marker in it (a built-in clip has none). Footstep markers stay on the player's own machine and fire nothing.","deprecated":false,"deprecatedReason":"","introducedMinor":115}, {"name":"CrouchStarted","args":"(player: Player)","side":"both","doc":"The character crouched (the key, a slide or ForceCrouch). Fires on the server and on every client.","deprecated":false,"deprecatedReason":"","introducedMinor":40}, {"name":"CrouchStopped","args":"(player: Player)","side":"both","doc":"The character stood up from a crouch. Fires on the server and on every client.","deprecated":false,"deprecatedReason":"","introducedMinor":40}, {"name":"Damaged","args":"(player: Player, amount: number, damageType: string, attacker: Player?, weapon: string?, round: string?, bone: string?, region: string?)","side":"server","doc":"The character was hurt, on the server. amount is what got through Armor (the Shield and health took it between them), so a hit the shield soaked up still counts; a killing hit fires Damaged first and then Died. damageType is the hit's tag (\"Bullet\", \"Melee\", \"Explosion\", ..., or your own) and attacker the player who dealt it, or nil. weapon is the Tool id of the weapon that dealt the hit and round the name of the round loaded on it when it fired (Backpack:SetRound), so a script can tell a fire arrow from a plain one; both nil for a hit that was not a weapon's, round nil for a weapon with none loaded (weapon and round: script API 1.77). bone is the bone the hit struck (a melee swing: the bone nearest where it landed) and region its body part (\"Head\", \"Body\" or \"Limb\"); both nil for a hit that named no bone, such as a blast, a car or a script's (script API 1.113). Not fired for a hit a held guard blocked, friendly fire that was switched off, a hit Players:OnDamaging blocked, or Health set directly.","deprecated":false,"deprecatedReason":"","introducedMinor":39}, +{"name":"Dehydrated","args":"(player: Player)","side":"both","doc":"The character's Thirst reached 0: from now on it takes ThirstDamage every second until something fills it. Fires on the server and on the player's own machine.","deprecated":false,"deprecatedReason":"","introducedMinor":117}, {"name":"Died","args":"(player: Player, killer: Player?, damageType: string)","side":"both","doc":"The player's character died, on the server and on every client. killer is the player whose damage finished it (a weapon, or TakeDamage with a source); nil for falling out of the world, Kill, Health set to 0, or their own damage. damageType is the tag of the killing hit (\"Bullet\", \"Melee\", \"Explosion\", ..., or your own); \"Generic\" when nothing named one.","deprecated":false,"deprecatedReason":"","introducedMinor":9}, {"name":"DimensionChanged","args":"(player: Player, old: number, new: number)","side":"both","doc":"The player's dimension changed (Player.Dimension, or a vehicle they ride moved with Entity.Dimension). Fires on the server and on every client; old and new are the dimensions.","deprecated":false,"deprecatedReason":"","introducedMinor":113}, {"name":"Dodged","args":"(player: Player, roll: boolean)","side":"server","doc":"The player dodged (roll false: one tap of the dodge key) or rolled (roll true: a double tap), on the server, as it starts. For the first half second of it nothing hurts them. DodgeEnabled false stops the key; a firearm, or a weapon with no dodge animation, never dodges.","deprecated":false,"deprecatedReason":"","introducedMinor":53}, @@ -185,6 +196,7 @@ {"name":"EnteredWater","args":"(player: Player)","side":"both","doc":"The character stepped, fell, jumped or swam into water: its feet went in (WaterDepth past 2 cm), wading included, or it started swimming. It fires again only after LeftWater. Getting out of a seat into the water fires it too, and so does a new character that spawns in water. Fires on the server and on every client (each from its own copy of the character, so a client can hear it a moment before or after the server, and rarely an extra EnteredWater and LeftWater pair at the edge of a swim). On a client, another player's signals start over when that player comes into view: one already in the water then fires EnteredWater there, and one that goes out of view fires no LeftWater. Use it for a splash, a wet look or a zone rule.","deprecated":false,"deprecatedReason":"","introducedMinor":113}, {"name":"GrabRefused","args":"(player: Player, target: Entity?, reason: string, via: string)","side":"server","doc":"A grab the player tried was refused, on the server: they pressed to grab (physics mode's left mouse, the gravity gun's, or a staff's Q) and nothing was lifted. target is the Entity the aim was on, nil when there was none (or it has no Entity). reason is \"cooldown\", \"busy\" (another grab of theirs already holds a prop), \"no_target\" (the aim is on nothing in reach), \"no_aim\" (there was no aim to use), \"character\" (a player or an NPC; physics mode and the gun refuse them), \"not_a_prop\" (a vehicle or anything that is not a physics prop), \"anchored\", \"too_heavy\", \"too_far\", \"held\" (another player holds it), \"not_grabbable\" (Entity.Grabbable is false), or the holder's own state, for example \"disabled\", \"dead\", \"stunned\", \"knocked_down\", \"swimming\", \"seated\", \"sliding\" or \"traversing\". via is \"physics_mode\", \"gravity_gun\" or \"telekinesis\". A press that does nothing for another reason (a swing under way, no extra) is not reported.","deprecated":false,"deprecatedReason":"","introducedMinor":87}, {"name":"HealthChanged","args":"(player: Player, old: number, new: number)","side":"both","doc":"The character's health changed: damage, healing, Health set, or a respawn's refill. Fires on the server and on every client.","deprecated":false,"deprecatedReason":"","introducedMinor":9}, +{"name":"HungerChanged","args":"(player: Player, old: number, new: number)","side":"both","doc":"The character's Hunger changed: draining, a script setting it or a consumable filling it. It reports steps of about half a percent of MaxHunger, not every frame. Fires on the server and on the player's own machine.","deprecated":false,"deprecatedReason":"","introducedMinor":117}, {"name":"Jumped","args":"(player: Player)","side":"both","doc":"The character jumped: the jump key, Player:Jump, a double jump or a wall jump (a Launch is not a jump). Fires on the server and on the player's own client, not on other players' clients.","deprecated":false,"deprecatedReason":"","introducedMinor":113}, {"name":"Landed","args":"(player: Player, fallSpeed: number)","side":"both","doc":"The character came down onto the ground after being in the air (a jump, a fall, a Launch). fallSpeed is how fast it was falling as it hit, in centimeters per second (FallDamageSpeed is the same measure). Not fired for landing in water. Fires on the server and on the player's own client, not on other players' clients.","deprecated":false,"deprecatedReason":"","introducedMinor":113}, {"name":"LeftWater","args":"(player: Player)","side":"both","doc":"The character's feet came out of the water (WaterDepth back to 0 and not swimming), or it sat in a seat. A climb or vault out of the water reports it when the character lands on dry ground. A character that dies in the water reports nothing more; its next one starts dry. Fires on the server and on every client.","deprecated":false,"deprecatedReason":"","introducedMinor":113}, @@ -199,9 +211,11 @@ {"name":"SprintStopped","args":"(player: Player)","side":"both","doc":"The character stopped sprinting: the key let go, stamina ran out, SprintEnabled turned off, or it stopped moving. Fires on the server and on every client.","deprecated":false,"deprecatedReason":"","introducedMinor":40}, {"name":"StaffExtraUsed","args":"(player: Player, extra: string)","side":"server","doc":"The player used their staff's extra on Q (gamepad D-pad up), on the server, as it starts. extra is the weapon's extra: \"telekinesis\", \"blink\", \"heal\", \"dash\" or \"levitate\" (a press that ends a float fires nothing). Not fired for a press that did nothing (StaffExtraEnabled false, the cooldown, nothing to lift, nowhere to blink to, full health, stunned, knocked down, swimming, sliding, seated or in a vehicle).","deprecated":false,"deprecatedReason":"","introducedMinor":54}, {"name":"StaminaChanged","args":"(player: Player, old: number, new: number)","side":"both","doc":"The character's Stamina changed: sprinting, resting, a jump's cost or a script setting it. It reports steps of about half a percent of MaxStamina, not every frame. Fires on the server and on every client while StaminaEnabled is true.","deprecated":false,"deprecatedReason":"","introducedMinor":40}, +{"name":"Starving","args":"(player: Player)","side":"both","doc":"The character's Hunger reached 0: from now on it takes HungerDamage every second until something fills it. Fires on the server and on the player's own machine.","deprecated":false,"deprecatedReason":"","introducedMinor":117}, {"name":"StunEnded","args":"(player: Player)","side":"server","doc":"The player's stun is over, on the server: it ran out, or a knockdown, a death or putting the weapon away ended it early.","deprecated":false,"deprecatedReason":"","introducedMinor":53}, {"name":"Stunned","args":"(player: Player)","side":"server","doc":"The player's guard was broken into a stun, on the server: until StunEnded they cannot move, attack or block, but can still look around, and hits still hurt them. A weapon whose stunSeconds is 0, or a hold with no stun animation, breaks the guard without a stun and does not fire this.","deprecated":false,"deprecatedReason":"","introducedMinor":53}, {"name":"Surfaced","args":"(player: Player)","side":"both","doc":"The character's head came back out of the water after WentUnderwater (IsUnderwater turned false), or it left the water or sat in a seat while under. Always before LeftWater. Fires on the server and on every client.","deprecated":false,"deprecatedReason":"","introducedMinor":113}, +{"name":"ThirstChanged","args":"(player: Player, old: number, new: number)","side":"both","doc":"The character's Thirst changed: draining, a script setting it or a consumable filling it. It reports steps of about half a percent of MaxThirst, not every frame. Fires on the server and on the player's own machine.","deprecated":false,"deprecatedReason":"","introducedMinor":117}, {"name":"WentUnderwater","args":"(player: Player)","side":"both","doc":"The swimming character's head went under the surface: IsUnderwater turned true, the moment Breath starts draining when BreathEnabled is on. Always after EnteredWater. Fires on the server and on every client. Use it for an underwater sound, a screen tint or a drowning timer of your own.","deprecated":false,"deprecatedReason":"","introducedMinor":113}]}, {"name":"Signal","service":false,"introducedMinor":0,"doc":"An event you can connect functions to.", "methods":[{"name":"Connect","side":"both","params":[{"name":"handler","type":"(...any) -> ()","optional":false}],"variadic":false,"returns":"Connection","kit":false,"doc":"Call handler every time the signal fires. Each call runs in its own thread, so it may task.wait.","deprecated":false,"deprecatedReason":"","introducedMinor":0}, @@ -289,9 +303,10 @@ {"name":"SetWeaponColor","side":"server","params":[{"name":"player","type":"Player","optional":false},{"name":"toolId","type":"string","optional":false},{"name":"color","type":"string","optional":false}],"variadic":false,"returns":"boolean","kit":false,"doc":"Paint one of the player's weapons: color is \"#RRGGBB\", the same format as Vehicles:SetPaintColor. Every player sees the new color. Returns false when the player does not have that Tool or it is not a weapon.","deprecated":false,"deprecatedReason":"","introducedMinor":0}], "properties":[], "signals":[{"name":"Fired","args":"(player: Player, toolId: string, origin: Vector3, direction: Vector3)","side":"server","doc":"One shot or swing of a player's weapon, on the server: each trigger pull of a gun (once for a shotgun's whole spread, once per round of a burst or an automatic), each arrow, spell, launched round or thrown weapon or shield, each swing of a melee weapon, a staff, a bow's bash or the fists, the start of a beam, and a gravity gun's launch. Fires whether or not it hits anything (Entity.Hit, Player.Damaged and NPC.Damaged report what it hit). toolId is the weapon's Tool id in the player's Backpack (\"fists\" for the fists). origin and direction are where the shot left from and the way it went: a gun's is the player's aim (Player:GetAim, before the spread), a projectile's is where it was launched and its launch direction (a bow's arc included), a swing's or a beam's is the player's aim when it started. Use it for accuracy stats, ammo counters of your own, or an alarm that hears gunshots. Example: `Backpack.Fired:Connect(function(player, toolId) shots[player] = (shots[player] or 0) + 1 end)`. (server only)","deprecated":false,"deprecatedReason":"","introducedMinor":113}, -{"name":"ItemUsed","args":"(player: Player, toolId: string, docName: string, usesLeft: number, builtInEffect: boolean)","side":"server","doc":"A consumable (a potion, a medkit, food: a weapon-builder item with the Consumable hold) was used, on the server, at the moment its effect lands: halfway through its drink or use clip. It fires for every use, whether the item has a built-in effect or not, and never for a use that was canceled (sprinting, jumping or dodging first spends nothing). toolId is the item's Tool id in the player's Backpack, docName the name the creator gave it in the builder, usesLeft how many uses it has left (0: it is gone from the Backpack), and builtInEffect whether its own heal also ran (false for an item whose effect is \"none\": your script is the whole effect).","deprecated":false,"deprecatedReason":"","introducedMinor":49}, +{"name":"ItemUsed","args":"(player: Player, toolId: string, docName: string, usesLeft: number, builtInEffect: boolean)","side":"server","doc":"A consumable (a potion, a medkit, food: a weapon-builder item with the Consumable hold) was used, on the server, at the moment its effect lands: halfway through its drink or use clip. It fires for every use, whether the item has a built-in effect or not, and never for a use that was canceled (sprinting, jumping or dodging first spends nothing). toolId is the item's Tool id in the player's Backpack, docName the name the creator gave it in the builder, usesLeft how many uses it has left (0: it is gone from the Backpack), and builtInEffect whether its own effect also ran: its heal, or its stamina, hunger or thirst while your script has that pool on (false for an item whose effect is \"none\", where your script is the whole effect, and for a pool that is off).","deprecated":false,"deprecatedReason":"","introducedMinor":49}, {"name":"LoadoutChanged","args":"(player: Player, toolId: string)","side":"server","doc":"A weapon's attachments, stat multipliers or light changed: a script call, a pickup that brought a loadout, or the player's light key. Fires on the server, once the change has taken effect.","deprecated":false,"deprecatedReason":"","introducedMinor":76}, -{"name":"LocalChanged","args":"()","side":"client","doc":"The local player's Backpack changed: a Tool came or went, a different slot is in the hands, or a consumable's uses changed. Redraw from GetLocal.","deprecated":false,"deprecatedReason":"","introducedMinor":81}]}, +{"name":"LocalChanged","args":"()","side":"client","doc":"The local player's Backpack changed: a Tool came or went, a different slot is in the hands, or a consumable's uses changed. Redraw from GetLocal.","deprecated":false,"deprecatedReason":"","introducedMinor":81}, +{"name":"ToolUsed","args":"(player: Player, toolId: string, docName: string)","side":"server","doc":"One use of anything a player holds, on the server, whatever it is: everything Backpack.Fired counts for a weapon (each shot, launch, swing, beam start and gravity gun launch), each consumable's use as it starts (Backpack.ItemUsed is its effect moment, which a canceled use never reaches), and each use of a usable item (hold \"item\", which does nothing by itself: this is where your script gives it its behavior). toolId is the Tool's id in the player's Backpack (\"fists\" for the fists), docName its name. Guarding, aiming, reloading and switching are not uses. Example: `Backpack.ToolUsed:Connect(function(player, toolId, name) if name == \"Flashlight\" then toggleLamp(player) end end)`. (server only)","deprecated":false,"deprecatedReason":"","introducedMinor":116}]}, {"name":"Camera","service":true,"introducedMinor":10,"doc":"The local player's view (client only): first person, a fixed camera (cut to or tweened into), a camera following an entity, the field of view and a shake. All of it goes back to Mantle's own camera when the script stops or the player respawns.", "methods":[{"name":"Fade","side":"client","params":[{"name":"options","type":"{To: number?, Duration: number?, Color: string?, Audio: boolean?, Hold: boolean?}?","optional":true}],"variadic":false,"returns":"()","kit":false,"doc":"Fade this player's screen to a color and back, for scene cuts, teleports, death and respawn, or going in and out of a building. Camera:Fade({To = 1, Duration = 0.5}) fades to black, Camera:Fade({To = 0, Duration = 0.5}) back in. options: To (how covered the screen ends, 0 clear to 1 solid color, default 1), Duration (seconds, 0 to 60, default 0.5; 0 cuts), Color (\"#RRGGBB\", default black), Audio (default false: true turns all in-game sound down with the picture, all the way at 1; voice chat is not faded; a later fade back toward clear brings the sound up with the picture) and Hold (default true: the screen stays at To once there; false clears it when the fade ends, for a flash). The fade runs from wherever the screen is now, so a fade back in started halfway through a fade out turns back without a jump, and a new fade replaces the last one, its color at once. A fade ending at 0 clears the screen and the sound. Only the 3D picture fades: the HUD, script UI (labels placed in the world included) and the Esc menu draw over it and stay usable. It is kept through a respawn (so a fade can cover one) and clears at once when the script that made it stops. An unknown option or a value of the wrong type is an error that names it. A server script fades one player's screen with Player:FadeScreen; the last fade from either wins.","deprecated":false,"deprecatedReason":"","introducedMinor":113}, {"name":"Follow","side":"client","params":[{"name":"entity","type":"Entity","optional":false},{"name":"offset","type":"Vector3","optional":false},{"name":"relative","type":"boolean?","optional":true}],"variadic":false,"returns":"()","kit":false,"doc":"Keep the camera at offset from entity, looking at it, wherever it goes (Mode becomes \"Follow\"). offset is in world axes, so Vector3.new(0, -600, 300) keeps the camera 6 m along -Y and 3 m up; with relative true it turns with the entity's heading instead, so Vector3.new(-600, 0, 250) stays behind it. The player still moves their character. When the entity is destroyed the camera goes back to Mantle's; set Mode to \"Default\" or call Reset to give it back sooner.","deprecated":false,"deprecatedReason":"","introducedMinor":22}, diff --git a/Source/MantleEditor/Private/MantleAnimPack.cpp b/Source/MantleEditor/Private/MantleAnimPack.cpp new file mode 100644 index 00000000..cf20a5af --- /dev/null +++ b/Source/MantleEditor/Private/MantleAnimPack.cpp @@ -0,0 +1,119 @@ +// Copyright Joshua Eger. All Rights Reserved. +#include "MantleAnimPack.h" + +#include "MantleCustomAvatar.h" + +#include "Animation/AnimSequence.h" +#include "Engine/SkeletalMesh.h" +#include "Dom/JsonObject.h" +#include "Serialization/JsonSerializer.h" +#include "Serialization/JsonWriter.h" + +bool FMantleAnimPack::ConvertClip(UAnimSequence* Sequence, USkeletalMesh* OwnMesh, FMantleCreatorClip& Out, FString& OutSkeleton, FString& OutError) +{ + OutSkeleton.Reset(); + if (!Sequence) + { + OutError = TEXT("No animation was given."); + return false; + } + if (OwnMesh) + { + if (!FMantleCreatorClips::ConvertOnOwnMesh(Sequence, OwnMesh, Out, OutError)) + { + return false; + } + OutSkeleton = Out.SkeletonHash; + return true; + } + if (!FMantleCreatorClips::ConvertToUefn(Sequence, Out, OutError)) + { + return false; + } + OutSkeleton = TEXT("uefn"); + return true; +} + +bool FMantleAnimPack::IsNameValid(const FString& Name) +{ + if (Name.IsEmpty() || Name.Len() > 64) + { + return false; + } + for (int32 Index = 0; Index < Name.Len(); ++Index) + { + const TCHAR Char = Name[Index]; + const bool bLetter = (Char >= TEXT('a') && Char <= TEXT('z')) || (Char >= TEXT('A') && Char <= TEXT('Z')); + if (!bLetter && (Index == 0 || (!(Char >= TEXT('0') && Char <= TEXT('9')) && Char != TEXT('_')))) + { + return false; + } + } + return true; +} + +FString FMantleAnimPack::NameFrom(const FString& AssetName) +{ + const FString Name = FMantleCustomAvatar::ExtraNameFor(AssetName); + if (Name.IsEmpty()) + { + return TEXT("clip"); + } + return IsNameValid(Name) ? Name : (TEXT("clip_") + Name).Left(64); +} + +TArray FMantleAnimPack::CheckPack(const TConstArrayView Names) +{ + TArray Problems; + if (Names.IsEmpty()) + { + Problems.Add(TEXT("The pack has no clips.")); + return Problems; + } + if (Names.Num() > MaxClips) + { + Problems.Add(FString::Printf(TEXT("The pack has %d clips; a pack may have at most %d."), Names.Num(), MaxClips)); + } + TSet Seen; + for (const FString& Name : Names) + { + if (Name.IsEmpty()) + { + Problems.Add(TEXT("A clip in the pack has no name.")); + continue; + } + if (!IsNameValid(Name)) + { + Problems.Add(FString::Printf(TEXT("The clip name '%s' can't be used: start with a letter, then letters, digits or _, at most 64."), *Name)); + continue; + } + bool bAlready = false; + Seen.Add(Name.ToLower(), &bAlready); + if (bAlready) + { + Problems.Add(FString::Printf(TEXT("Two clips in the pack are named '%s'."), *Name)); + } + } + return Problems; +} + +FString FMantleAnimPack::WriteDocument(const TConstArrayView Entries) +{ + FString Text; + const TSharedRef>> Writer = TJsonWriterFactory>::Create(&Text); + Writer->WriteObjectStart(); + Writer->WriteValue(TEXT("format"), FString(DocumentFormat())); + Writer->WriteArrayStart(TEXT("clips")); + for (const FEntry& Entry : Entries) + { + Writer->WriteObjectStart(); + Writer->WriteValue(TEXT("name"), Entry.Name); + Writer->WriteValue(TEXT("asset"), Entry.AssetId); + Writer->WriteValue(TEXT("skeleton"), Entry.Skeleton); + Writer->WriteObjectEnd(); + } + Writer->WriteArrayEnd(); + Writer->WriteObjectEnd(); + Writer->Close(); + return Text; +} diff --git a/Source/MantleEditor/Private/MantleAnimPack.h b/Source/MantleEditor/Private/MantleAnimPack.h new file mode 100644 index 00000000..3316d54d --- /dev/null +++ b/Source/MantleEditor/Private/MantleAnimPack.h @@ -0,0 +1,53 @@ +// Copyright Joshua Eger. All Rights Reserved. +#pragma once + +#include "CoreMinimal.h" +#include "MantleCreatorClips.h" + +class UAnimSequence; +class USkeletalMesh; + +/** + * mantle #333 G10: an animation pack, a library item of kind animPack that holds named clips for any skeleton (a creator's own + * rig as well as the UEFN mannequin). Its document lists {name, asset, skeleton}: asset is the uploaded animclip id, skeleton is + * "uefn" for a clip converted to the UEFN mannequin, else the skeleton hash of the mesh the clip was sampled over. The clips are the + * item's dependencies (at most MaxDependencies); the same item id takes a new version on republish. Pure editor code, no Slate. + */ +struct FMantleAnimPack +{ + static const TCHAR* DocumentFormat() { return TEXT("mantle.animpack/1"); } + static const TCHAR* LibraryKind() { return TEXT("animPack"); } + /** The asset kind the document is uploaded as (like a Custom avatar's "customavatar"). */ + static const TCHAR* DocumentKind() { return TEXT("animpack"); } + + /** The most clips a pack holds: an item's dependency limit (MaxDependencies). */ + static constexpr int32 MaxClips = 64; + + struct FEntry + { + FString Name; + /** The uploaded animclip id. */ + FString AssetId; + /** "uefn", or a skeleton hash (skel_...). */ + FString Skeleton; + }; + + /** + * One clip of a pack, converted. OwnMesh null: a clip made on the UEFN, MetaHuman, UE5 or UE4 Mannequin skeleton, as an item's clip + * is (FMantleCreatorClips::ConvertToUefn), and Skeleton is "uefn". OwnMesh given: sampled over that mesh's own bones + * (ConvertOnOwnMesh) and Skeleton is the clip's skeleton hash. OutSkeleton is the document's skeleton field. + */ + static bool ConvertClip(UAnimSequence* Sequence, USkeletalMesh* OwnMesh, FMantleCreatorClip& Out, FString& OutSkeleton, FString& OutError); + + /** A clip's name as the backend takes it (and scripts play it): a letter, then letters, digits or _, at most 64. */ + static bool IsNameValid(const FString& Name); + + /** A valid clip name made from an animation's asset name (lower case, other characters as _); "clip" when nothing is left. */ + static FString NameFrom(const FString& AssetName); + + /** Why a pack cannot be published, in plain words, one line each; empty when it can: no clips, over MaxClips, a missing, unusable or repeated name. */ + static TArray CheckPack(TConstArrayView Names); + + /** The document's JSON text (compact), the entries in the order given. */ + static FString WriteDocument(TConstArrayView Entries); +}; diff --git a/Source/MantleEditor/Private/MantleAnimPackPublish.cpp b/Source/MantleEditor/Private/MantleAnimPackPublish.cpp new file mode 100644 index 00000000..e16edcc3 --- /dev/null +++ b/Source/MantleEditor/Private/MantleAnimPackPublish.cpp @@ -0,0 +1,443 @@ +// Copyright Joshua Eger. All Rights Reserved. +#include "MantleAnimPackPublish.h" + +#include "MantleAnimPack.h" +#include "MantleApiClient.h" +#include "MantleAvatarContract.h" +#include "MantleEmoteRetarget.h" +#include "MantleAttribution.h" +#include "MantleCreatorClips.h" +#include "MantleCreatorSignIn.h" +#include "MantlePlaceAssetConverter.h" +#include "MantlePlaceAssets.h" +#include "MantleRuntime.h" +#include "MantleSettings.h" +#include "MantleSha256.h" + +#include "Animation/AnimSequence.h" +#include "AssetRegistry/AssetData.h" +#include "AssetRegistry/IAssetRegistry.h" +#include "Engine/SkeletalMesh.h" +#include "HAL/IConsoleManager.h" +#include "HAL/PlatformMisc.h" +#include "Misc/PackageName.h" + +// Named, not anonymous: MantleEditor builds as a unity build. +namespace MantleAnimPackPublishPrivate +{ + FMantleValidationIssue PackIssue(const EMantleIssueSeverity Severity, const FString& Problem, const FString& Remedy) + { + return FMantleValidationIssue{ Severity, FString(), Problem, Remedy }; + } +} + +// ============================================================================================= +// The input + +FString FMantleAnimPackInput::Problem() const +{ + if (Name.TrimStartAndEnd().IsEmpty()) + { + return TEXT("Name the animation pack."); + } + TArray Names; + for (const FClip& Clip : Clips) + { + Names.Add(Clip.Name); + } + const TArray PackProblems = FMantleAnimPack::CheckPack(Names); + if (PackProblems.Num() > 0) + { + return FString::Join(PackProblems, TEXT(" ")); + } + for (const FClip& Clip : Clips) + { + if (!Clip.Sequence.IsValid()) + { + return FString::Printf(TEXT("The animation for the clip '%s' could not be loaded. Pick it again, then publish."), *Clip.Name); + } + } + return FString(); +} + +// ============================================================================================= +// One animation pack, as a publish source + +FMantleAnimPackPublishSource::FMantleAnimPackPublishSource(FMantleAnimPackInput InInput) + : Input(MoveTemp(InInput)) +{ +} + +bool FMantleAnimPackPublishSource::Prepare(FMantleValidationResult& OutValidation, FString& OutMessage) +{ + OutValidation = FMantleValidationResult(); + const FString Problem = Input.Problem(); + if (!Problem.IsEmpty()) + { + OutMessage = Problem; + return false; + } + // The item is remembered per API and account, as a Custom avatar's is. + FString WhyNot; + LinkApi = FMantleApiClient::BaseUrlResolver(); + if (!FMantleCreatorSignIn::ResolveAccountId(LinkAccount, WhyNot)) + { + OutMessage = WhyNot + TEXT(" Sign in again (Tools > Mantle) and choose Publish again; nothing was uploaded."); + return false; + } + Held.Reset(); + for (const FMantleAnimPackInput::FClip& Clip : Input.Clips) + { + if (UAnimSequence* Sequence = Clip.Sequence.Get()) + { + Held.Add(TStrongObjectPtr(Sequence)); + } + if (USkeletalMesh* Mesh = Clip.OwnMesh.Get()) + { + Held.Add(TStrongObjectPtr(Mesh)); + } + } + return true; +} + +FString FMantleAnimPackPublishSource::ConversionStepName(int32 Step) const +{ + return FString::Printf(TEXT("%s's clips"), *Input.Name); +} + +void FMantleAnimPackPublishSource::Convert(int32 Step, FMantlePlaceAssetSet& Set) +{ + using namespace MantleAnimPackPublishPrivate; + const FMantlePlaceAssetLimits Limits = FMantlePlaceAssetLimits::FromContract(); + + FMantleConvertedAnimPack Pack; + Pack.Path = PathFor(Input.Name); + Pack.Key = KeyFor(Input.Name); + Pack.Name = Input.Name; + + TArray Made; + TMap SkeletonByKey; + bool bRefused = false; + for (const FMantleAnimPackInput::FClip& Entry : Input.Clips) + { + UAnimSequence* Sequence = Entry.Sequence.Get(); + if (!Sequence) + { + Set.Issues.Add(PackIssue(EMantleIssueSeverity::Error, FString::Printf(TEXT("The animation for the clip '%s' of '%s' could not be loaded."), *Entry.Name, *Input.Name), + TEXT("Pick the animation again, then publish again."))); + bRefused = true; + continue; + } + // Two names on the same animation (and the same mesh choice) are converted and uploaded once, and share one asset id. + const USkeletalMesh* OwnMeshForKey = Entry.OwnMesh.Get(); + const FString SharedKey = ClipKeyFor(Sequence->GetPathName(), OwnMeshForKey ? OwnMeshForKey->GetPathName() : FString()); + if (const FString* EarlierSkeleton = SkeletonByKey.Find(SharedKey)) + { + FMantleConvertedAnimPack::FEntry& Shared = Pack.Entries.AddDefaulted_GetRef(); + Shared.Name = Entry.Name; + Shared.ClipKey = SharedKey; + Shared.Skeleton = *EarlierSkeleton; + continue; + } + FMantleCreatorClip Clip; + FString Skeleton; + FString Error; + if (!FMantleAnimPack::ConvertClip(Sequence, Entry.OwnMesh.Get(), Clip, Skeleton, Error)) + { + Set.Issues.Add(PackIssue(EMantleIssueSeverity::Error, FString::Printf(TEXT("The clip '%s' (%s) of '%s' can't be used: %s"), *Entry.Name, *Sequence->GetName(), *Input.Name, *Error), + TEXT("Pick an animation made on the UEFN Mannequin, a MetaHuman, the UE5 Mannequin or the UE4 Mannequin, or choose the mesh it was made for."))); + bRefused = true; + continue; + } + TArray Checked; + if (!FMantleCreatorClips::CheckClip(Sequence->GetName(), Sequence, &Clip, Limits, Checked)) + { + bRefused = true; + } + for (FMantleValidationIssue& Issue : Checked) + { + Set.Issues.Add(MoveTemp(Issue)); + } + + FMantleConvertedClip& Upload = Made.AddDefaulted_GetRef(); + Upload.Key = SharedKey; + SkeletonByKey.Add(SharedKey, Skeleton); + Upload.Name = FString::Printf(TEXT("%s %s"), *Input.Name, *Entry.Name); + Upload.Path = Sequence->GetPathName(); + Upload.Frames = Clip.Frames; + Upload.Tracks = Clip.Tracks; + Upload.SkeletonHash = Clip.SkeletonHash; + Upload.Bytes = MoveTemp(Clip.Bytes); + Upload.Hash = Clip.Hash; + UE_LOG(LogMantle, Log, TEXT("MANTLE_ANIM_PACK clip %s name=%s frames=%d tracks=%d bytes=%d skeleton=%s. %s"), *Input.Name, *Entry.Name, Upload.Frames, Upload.Tracks, + Upload.Bytes.Num(), *Skeleton, *Clip.Note); + + FMantleConvertedAnimPack::FEntry& Item = Pack.Entries.AddDefaulted_GetRef(); + Item.Name = Entry.Name; + Item.ClipKey = Upload.Key; + Item.Skeleton = Skeleton; + } + if (bRefused) + { + return; + } + for (FMantleConvertedClip& Upload : Made) + { + Set.Clips.Add(MoveTemp(Upload)); + } + Set.AnimPacks.Add(MoveTemp(Pack)); +} + +bool FMantleAnimPackPublishSource::CollectScripts(TArray& OutScripts, FString& OutMessage) +{ + OutScripts.Reset(); + return true; +} + +EMantlePlaceExportOutcome FMantleAnimPackPublishSource::Export(const FMantlePlaceAssetSet& Set, const TMap& ScriptSourceIds, + const TMap& ScriptAuthorSourceIds, FString& OutPlaceJson, TArray& OutIssues) +{ + // A library-only source writes no place file; the session never asks. + return EMantlePlaceExportOutcome::Failed; +} + +FString FMantleAnimPackPublishSource::FindLibraryItem(const FString& SourcePath) +{ + return UMantleSettings::Get()->FindLibraryItemForVehicle(LinkApi, LinkAccount, SourcePath); +} + +void FMantleAnimPackPublishSource::RememberLibraryItem(const FString& SourcePath, const FString& ItemId) +{ + UMantleSettings::GetMutable()->RememberLibraryItemForVehicle(LinkApi, LinkAccount, SourcePath, ItemId); +} + +void FMantleAnimPackPublishSource::ForgetLibraryItem(const FString& SourcePath) +{ + UMantleSettings::GetMutable()->ForgetLibraryItemForVehicle(LinkApi, LinkAccount, SourcePath); +} + +int32 FMantleAnimPackPublishSource::LibraryGeneration(const FString& SourcePath) +{ + return UMantleSettings::Get()->FindLibraryGenerationForVehicle(LinkApi, LinkAccount, SourcePath); +} + +FString FMantleAnimPackPublishSource::AttributionFor(const FString& ObjectPath) const +{ + return FMantleAttribution::ForObjectPath(ObjectPath); +} + +// ============================================================================================= +// The Publish button's session + +FMantleAnimPackPublish& FMantleAnimPackPublish::Get() +{ + static FMantleAnimPackPublish Instance; + return Instance; +} + +bool FMantleAnimPackPublish::Start(FMantleAnimPackInput Input, const FMantleVehicleLibraryChoice& Choice, FString& OutError) +{ + if (IsBusy()) + { + OutError = FString::Printf(TEXT("'%s' is still publishing. Wait for it to finish, then try again."), *Name); + return false; + } + if (!Choice.IsReady()) + { + OutError = TEXT("A public animation pack needs the rights declaration: tick it, or choose Private."); + return false; + } + OutError = Input.Problem(); + if (!OutError.IsEmpty()) + { + return false; + } + Name = Input.Name; + Source = MakeShared(MoveTemp(Input)); + // A go-live: the uploads wait for Mantle's approval, which a library item needs. + Session = MakeShared(Source.ToSharedRef(), MakeShared(), /*bGoLive*/ true, FString()); + Session->VehicleChoice = Choice; + UE_LOG(LogMantle, Log, TEXT("MANTLE_ANIM_PACK_PUBLISH started pack=%s visibility=%s"), *Name, Choice.bPublic ? TEXT("public") : TEXT("private")); + Session->Start(); + if (!TickerHandle.IsValid()) + { + TickerHandle = FTSTicker::GetCoreTicker().AddTicker(FTickerDelegate::CreateRaw(this, &FMantleAnimPackPublish::Tick)); + } + return true; +} + +bool FMantleAnimPackPublish::Tick(float DeltaSeconds) +{ + if (Session.IsValid() && !Session->IsFinished()) + { + Session->Tick(); + } + if (!Session.IsValid() || !Session->IsFinished()) + { + return true; + } + if (Session->Succeeded()) + { + UE_LOG(LogMantle, Log, TEXT("MANTLE_ANIM_PACK_PUBLISH_DONE pack=%s %s"), *Name, *Session->GetResult().Message); + } + else + { + UE_LOG(LogMantle, Warning, TEXT("MANTLE_ANIM_PACK_PUBLISH_FAILED pack=%s %s"), *Name, *Session->GetResult().Message); + for (const FMantleValidationIssue& Issue : Session->GetResult().Validation.Issues) + { + UE_LOG(LogMantle, Warning, TEXT("MANTLE_ANIM_PACK_PUBLISH_ISSUE %s %s"), *Issue.Problem, *Issue.Remedy); + } + for (const FMantleValidationIssue& Issue : Session->GetAttention()) + { + UE_LOG(LogMantle, Warning, TEXT("MANTLE_ANIM_PACK_PUBLISH_ISSUE %s %s"), *Issue.Problem, *Issue.Remedy); + } + } + TickerHandle.Reset(); + if (bExitWhenDone) + { + FPlatformMisc::RequestExit(false); + } + return false; +} + +// ============================================================================================= +// The animation pack publish without the panel, for a harness + +namespace MantleAnimPackPublishPrivate +{ + // Mantle.Dev.PublishAnimPack ... name= [public|private] [exit] + FAutoConsoleCommand GMantleDevPublishAnimPackCommand( + TEXT("Mantle.Dev.PublishAnimPack"), + TEXT("Mantle.Dev.PublishAnimPack ... name= [mesh=] [public|private] [exit] -- publishes an animation pack: a folder gives every ") + TEXT("animation under it (named by its asset name, lowercase), an animation path gives that one. A clip made on the UEFN, MetaHuman, UE5 or UE4 Mannequin is converted to UEFN; ") + TEXT("any other clip is sampled over mesh= (all such clips) or, without it, over its animation's preview mesh. Private unless public is given. ") + TEXT("Logs MANTLE_ANIM_PACK_PUBLISH_DONE or MANTLE_ANIM_PACK_PUBLISH_FAILED."), + FConsoleCommandWithArgsDelegate::CreateLambda([](const TArray& AllArgs) + { + auto Fail = [](const FString& Why) { UE_LOG(LogMantle, Error, TEXT("MANTLE_ANIM_PACK_PUBLISH_FAILED %s"), *Why); }; + TArray Paths; + FString PackName; + FString MeshPath; + bool bPublic = false; + bool bExit = false; + for (const FString& Arg : AllArgs) + { + if (Arg.StartsWith(TEXT("name="))) + { + PackName = Arg.Mid(5); + } + else if (Arg.StartsWith(TEXT("mesh="))) + { + MeshPath = Arg.Mid(5); + } + else if (Arg == TEXT("public")) + { + bPublic = true; + } + else if (Arg == TEXT("private")) + { + bPublic = false; + } + else if (Arg == TEXT("exit")) + { + bExit = true; + } + else + { + Paths.Add(Arg); + } + } + if (Paths.IsEmpty() || PackName.IsEmpty()) + { + Fail(TEXT("usage: Mantle.Dev.PublishAnimPack ... name= [mesh=] [public|private] [exit]")); + return; + } + IAssetRegistry* Registry = IAssetRegistry::Get(); + if (!Registry) + { + Fail(TEXT("the asset registry is not available")); + return; + } + Registry->WaitForCompletion(); + USkeletalMesh* ForcedMesh = nullptr; + if (!MeshPath.IsEmpty()) + { + FString Full = MeshPath; + if (!FPackageName::GetShortName(Full).Contains(TEXT("."))) + { + Full += TEXT(".") + FPackageName::GetShortName(Full); + } + ForcedMesh = LoadObject(nullptr, *Full); + if (!ForcedMesh) + { + Fail(FString::Printf(TEXT("%s did not load as a skeletal mesh"), *MeshPath)); + return; + } + } + + // Each path: a package folder (every animation sequence under it) or one animation. + TArray Found; + for (const FString& Path : Paths) + { + FString Folder = Path; + Folder.RemoveFromEnd(TEXT("/")); + TArray Assets; + if (!Folder.Contains(TEXT(".")) && Registry->GetAssetsByPath(FName(*Folder), Assets, /*bRecursive*/ true) && Assets.Num() > 0) + { + Assets.RemoveAll([](const FAssetData& Asset) { return Asset.AssetClassPath != UAnimSequence::StaticClass()->GetClassPathName(); }); + Assets.Sort([](const FAssetData& A, const FAssetData& B) { return A.AssetName.LexicalLess(B.AssetName); }); + for (const FAssetData& Asset : Assets) + { + if (UAnimSequence* Sequence = Cast(Asset.GetAsset())) + { + Found.AddUnique(Sequence); + } + } + continue; + } + FString Full = Path; + if (!FPackageName::GetShortName(Full).Contains(TEXT("."))) + { + Full += TEXT(".") + FPackageName::GetShortName(Full); + } + UAnimSequence* Sequence = LoadObject(nullptr, *Full); + if (!Sequence) + { + Fail(FString::Printf(TEXT("%s is neither a folder with animations nor an animation"), *Path)); + return; + } + Found.AddUnique(Sequence); + } + + FMantleAnimPackInput Input; + Input.Name = PackName; + const FMantleAvatarContract* Contract = FMantleAvatarContract::Get(); + for (UAnimSequence* Sequence : Found) + { + FMantleAnimPackInput::FClip& Clip = Input.Clips.AddDefaulted_GetRef(); + Clip.Name = FMantleAnimPack::NameFrom(Sequence->GetName()); + Clip.Sequence = Sequence; + // The clip's own rig is read as UEFN when the converter accepts it; any other rig needs a mesh to sample over. + const bool bUefn = Contract && !FMantleEmoteRetarget::IdentifySkeleton(Sequence->GetSkeleton(), *Contract).IsEmpty(); + if (!bUefn) + { + Clip.OwnMesh = ForcedMesh ? ForcedMesh : Sequence->GetPreviewMesh(/*bFindIfNotSet*/ false); + } + UE_LOG(LogMantle, Log, TEXT("MANTLE_ANIM_PACK clip %s <- %s (%s)"), *Clip.Name, *Sequence->GetPathName(), + bUefn ? TEXT("UEFN") : Clip.OwnMesh.IsValid() ? *Clip.OwnMesh->GetName() : TEXT("no mesh")); + } + FString Error; + FMantleVehicleLibraryChoice Choice; + Choice.bPublic = bPublic; + Choice.bRightsDeclared = bPublic; + if (!FMantleAnimPackPublish::Get().Start(MoveTemp(Input), Choice, Error)) + { + Fail(Error); + return; + } + if (bExit) + { + FMantleAnimPackPublish::Get().ExitWhenDone(); + } + })); +} diff --git a/Source/MantleEditor/Private/MantleAnimPackPublish.h b/Source/MantleEditor/Private/MantleAnimPackPublish.h new file mode 100644 index 00000000..18f54c5d --- /dev/null +++ b/Source/MantleEditor/Private/MantleAnimPackPublish.h @@ -0,0 +1,110 @@ +// Copyright Joshua Eger. All Rights Reserved. +#pragma once + +#include "CoreMinimal.h" +#include "Containers/Ticker.h" +#include "MantleLibraryPublish.h" +#include "MantlePlacePublishSession.h" +#include "UObject/StrongObjectPtr.h" + +class UAnimSequence; +class USkeletalMesh; + +/** What an animation pack publish is made of (mantle #333 G10): the pack's name and its named clips. */ +struct MANTLEEDITOR_API FMantleAnimPackInput +{ + /** One clip of the pack: its name (what a script plays as "/"), its animation and the mesh it was made for. */ + struct FClip + { + FString Name; + TWeakObjectPtr Sequence; + /** The mesh the clip is sampled over, for a clip made on the creator's own rig. Null: a clip on the UEFN, MetaHuman, UE5 or UE4 Mannequin, converted to the UEFN mannequin. */ + TWeakObjectPtr OwnMesh; + }; + + /** The library item's name and what it is remembered under: /Game/MantleAnimPacks/. */ + FString Name; + + /** The clips, in the order the creator gave them. */ + TArray Clips; + + /** Why this input cannot be published, in plain words; empty when it can (each clip is checked again at conversion). */ + FString Problem() const; +}; + +/** + * One animation pack, published on its own as a library item with no place: each clip is converted (FMantleAnimPack::ConvertClip), checked + * against the place clip limits and uploaded as a place animclip by the place publish session in its library-only mode; then the pack's + * document (FMantleAnimPack::WriteDocument) names their ids and is uploaded as kind animpack; then the pack becomes an item of kind + * animPack. A republish makes a new version of the same item; clips that did not change are not uploaded again. + */ +class MANTLEEDITOR_API FMantleAnimPackPublishSource : public IMantlePlacePublishSource +{ +public: + UE_NONCOPYABLE(FMantleAnimPackPublishSource); + + explicit FMantleAnimPackPublishSource(FMantleAnimPackInput InInput); + + /** What an animation pack named Name is remembered under. */ + static FString PathFor(const FString& Name) { return TEXT("/Game/MantleAnimPacks/") + Name; } + + /** The key its document goes by in a FMantlePlaceAssetSet (FMantleConvertedAnimPack::Key). */ + static FString KeyFor(const FString& Name) { return TEXT("animpack:") + PathFor(Name); } + + /** The key of one clip's upload: the animation plus the mesh it is sampled over ("uefn" for the UEFN conversion), so two names on the same animation share one upload. */ + static FString ClipKeyFor(const FString& SequencePath, const FString& OwnMeshPath) { return TEXT("animpackclip:") + SequencePath + TEXT("|") + (OwnMeshPath.IsEmpty() ? FString(TEXT("uefn")) : OwnMeshPath); } + + virtual FString GetLevelName() const override { return Input.Name; } + virtual bool Prepare(FMantleValidationResult& OutValidation, FString& OutMessage) override; + virtual int32 NumConversionSteps() const override { return 1; } + virtual FString ConversionStepName(int32 Step) const override; + virtual void Convert(int32 Step, FMantlePlaceAssetSet& Set) override; + virtual bool CollectScripts(TArray& OutScripts, FString& OutMessage) override; + virtual EMantlePlaceExportOutcome Export(const FMantlePlaceAssetSet& Set, const TMap& ScriptSourceIds, + const TMap& ScriptAuthorSourceIds, FString& OutPlaceJson, TArray& OutIssues) override; + virtual FString FindPlaceId() override { return FString(); } + virtual void RememberPlaceId(const FString& PlaceId) override {} + virtual void ForgetPlaceId() override {} + virtual FString FindLibraryItem(const FString& SourcePath) override; + virtual void RememberLibraryItem(const FString& SourcePath, const FString& ItemId) override; + virtual void ForgetLibraryItem(const FString& SourcePath) override; + virtual int32 LibraryGeneration(const FString& SourcePath) override; + virtual FString AttributionFor(const FString& ObjectPath) const override; + virtual void ConversionFinished() override { Held.Reset(); } + virtual void EndPublish() override { Held.Reset(); } + virtual bool IsLibraryOnly() const override { return true; } + +private: + FMantleAnimPackInput Input; + /** The sequences and meshes are held here while the conversion runs. */ + TArray> Held; + FString LinkApi; + FString LinkAccount; +}; + +/** One animation pack publish at a time, ticked by the editor, so the creator keeps working. The session is kept after it ends, for its result line, until the next publish. */ +class MANTLEEDITOR_API FMantleAnimPackPublish +{ +public: + static FMantleAnimPackPublish& Get(); + + /** Starts publishing Input with Choice. False, with OutError in plain words, when another publish is running, the choice is not ready or the input cannot be published. */ + bool Start(FMantleAnimPackInput Input, const FMantleVehicleLibraryChoice& Choice, FString& OutError); + + bool IsBusy() const { return Session.IsValid() && !Session->IsFinished(); } + + TSharedPtr GetSession() const { return Session; } + const FString& GetName() const { return Name; } + + /** Quits the editor when the running publish ends (for a harness). */ + void ExitWhenDone() { bExitWhenDone = true; } + +private: + bool Tick(float DeltaSeconds); + + TSharedPtr Session; + TSharedPtr Source; + FString Name; + FTSTicker::FDelegateHandle TickerHandle; + bool bExitWhenDone = false; +}; diff --git a/Source/MantleEditor/Private/MantleBuiltInMannequin.cpp b/Source/MantleEditor/Private/MantleBuiltInMannequin.cpp index e9a2e51b..0fec32d8 100644 --- a/Source/MantleEditor/Private/MantleBuiltInMannequin.cpp +++ b/Source/MantleEditor/Private/MantleBuiltInMannequin.cpp @@ -1,6 +1,7 @@ // Copyright Joshua Eger. All Rights Reserved. #include "MantleBuiltInMannequin.h" +#include "MantleAvatarContract.h" #include "MantleCosmeticExport.h" #include "MantleRuntime.h" #include "MantleRuntimeSkeletalMeshBuilder.h" @@ -82,7 +83,34 @@ USkeletalMesh* FMantleBuiltInMannequin::Get(FString* OutError) const FIKRigSkeleton& Skeleton = Rig->GetSkeleton(); FMantleSkinnedMesh Mesh; FString Error; - if (!MakeMesh(Skeleton.BoneNames, Skeleton.ParentIndices, Skeleton.RefPoseGlobal, Mesh, Error)) + // The rig lacks a few bones the backend's uefn skeleton has (the prop and virtual bones a held item's clip moves). They are added + // last, each at its parent's pose, so a clip's track on one of them is sampled instead of lost (mantle #333). + TArray BoneNames(Skeleton.BoneNames); + TArray ParentIndices(Skeleton.ParentIndices); + TArray RefPoseGlobal(Skeleton.RefPoseGlobal); + if (const FMantleAvatarContract* Contract = FMantleAvatarContract::Get()) + { + if (const FMantleContractSkeleton* Fixture = Contract->FindSkeleton(Contract->EmoteSkeleton)) + { + for (int32 Index = 0; Index < Fixture->Bones.Num(); ++Index) + { + if (BoneNames.Contains(Fixture->Bones[Index]) || Fixture->Parents[Index] == INDEX_NONE) + { + continue; + } + const int32 Parent = BoneNames.IndexOfByKey(Fixture->Bones[Fixture->Parents[Index]]); + if (Parent == INDEX_NONE) + { + continue; + } + BoneNames.Add(Fixture->Bones[Index]); + ParentIndices.Add(Parent); + const FTransform ParentPose = RefPoseGlobal[Parent]; + RefPoseGlobal.Add(ParentPose); + } + } + } + if (!MakeMesh(BoneNames, ParentIndices, RefPoseGlobal, Mesh, Error)) { return Refuse(FString::Printf(TEXT("the Mantle plugin's IK rig %s stores no usable skeleton (%s)"), *Path.GetAssetName(), *Error)); } diff --git a/Source/MantleEditor/Private/MantleConsumableEffect.cpp b/Source/MantleEditor/Private/MantleConsumableEffect.cpp new file mode 100644 index 00000000..edef06b5 --- /dev/null +++ b/Source/MantleEditor/Private/MantleConsumableEffect.cpp @@ -0,0 +1,66 @@ +// Copyright Joshua Eger. All Rights Reserved. +#include "MantleConsumableEffect.h" +#include "MantlePlaceAssets.h" +#include "MantleWeaponSource.h" +#include "Animation/AnimData/IAnimationDataModel.h" +#include "Animation/AnimSequence.h" +#include "Misc/PackageName.h" + +#define LOCTEXT_NAMESPACE "MantleConsumableEffect" + +double FMantleConsumableEffect::ConvertedSeconds(const UAnimSequence& Sequence) +{ + const IAnimationDataModel* Model = Sequence.GetDataModel(); + if (!Model) + { + return 0.0; + } + // As FMantleAnimClipWriter::SampleOnMesh counts the frames. A retargeted copy is within a frame of this, inside the end margin. + const double Rate = FMantlePlaceAssetLimits::ClipFrameRate; + return FMath::Max(0, FMath::FloorToInt32(Model->GetPlayLength() * Rate + 0.5)) / Rate; +} + +TOptional FMantleConsumableEffect::MomentIn(const double ClipSeconds) +{ + if (!(ClipSeconds > 0.0)) + { + return {}; + } + const double Seconds = FMath::Max(0.0, FMath::Min(ClipShare * ClipSeconds, ClipSeconds - EndMarginSeconds)); + return FMath::RoundToDouble(Seconds * 1000.0) / 1000.0; +} + +TOptional FMantleConsumableEffect::DocumentSeconds(const UMantleWeaponSource& Source) +{ + if (Source.Hold != EMantleWeaponHold::Consumable || Source.ClipUse.IsNull()) + { + return {}; + } + // A clip that is gone has no moment (the export refuses it); asking the loader for it would only warn. + const UAnimSequence* Clip = Source.ClipUse.Get(); + if (!Clip && FPackageName::DoesPackageExist(Source.ClipUse.ToSoftObjectPath().GetLongPackageName())) + { + Clip = Source.ClipUse.LoadSynchronous(); + } + return Clip ? MomentIn(ConvertedSeconds(*Clip)) : TOptional(); +} + +FText FMantleConsumableEffect::Line(const UMantleWeaponSource& Source) +{ + const TOptional Moment = DocumentSeconds(Source); + if (!Moment.IsSet()) + { + return FText::GetEmpty(); + } + double Played = Moment.GetValue(); + if (Source.Consumable.bOverrideUseSeconds) + { + Played *= Source.Consumable.UseSeconds / ConvertedSeconds(*Source.ClipUse.Get()); + } + FNumberFormattingOptions Format; + Format.SetMinimumFractionalDigits(1); + Format.SetMaximumFractionalDigits(1); + return FText::Format(LOCTEXT("EffectAt", "The effect happens at {0} s."), FText::AsNumber(Played, &Format)); +} + +#undef LOCTEXT_NAMESPACE diff --git a/Source/MantleEditor/Private/MantleConsumableEffect.h b/Source/MantleEditor/Private/MantleConsumableEffect.h new file mode 100644 index 00000000..4468fdb6 --- /dev/null +++ b/Source/MantleEditor/Private/MantleConsumableEffect.h @@ -0,0 +1,35 @@ +// Copyright Joshua Eger. All Rights Reserved. +#pragma once + +#include "CoreMinimal.h" + +class UAnimSequence; +class UMantleWeaponSource; + +/** + * The moment a consumable's effect lands when the creator brings their own Use clip (mantle #333, the document's hidden + * useEffectSeconds). The creator never types it: it is a fixed share of the clip. Without a Use clip nothing is written and + * the built-in clip's own moment applies. Pure editor code. + */ +struct FMantleConsumableEffect +{ + /** How far through the Use clip the effect lands. */ + static constexpr double ClipShare = 0.6; + /** The effect lands at least this long before the clip ends. */ + static constexpr double EndMarginSeconds = 0.1; + + /** Sequence's length as Mantle's converted clip has it: whole frames at the place clip rate. */ + static double ConvertedSeconds(const UAnimSequence& Sequence); + + /** Seconds into a Use clip of ClipSeconds when the effect lands; unset for a clip with no length (it has no moment before its end). */ + static TOptional MomentIn(double ClipSeconds); + + /** The document's useEffectSeconds for a source: set only for a consumable with a Use clip. Loads the clip. Game thread. */ + static TOptional DocumentSeconds(const UMantleWeaponSource& Source); + + /** + * The line the builder shows beside the Use slot, with the time as it plays: a chosen use time speeds the clip up or slows it + * down, and the moment moves with it. Empty when DocumentSeconds is unset. Loads the clip. Game thread. + */ + static FText Line(const UMantleWeaponSource& Source); +}; diff --git a/Source/MantleEditor/Private/MantleCosmeticPanel.cpp b/Source/MantleEditor/Private/MantleCosmeticPanel.cpp index aa41643e..89348885 100644 --- a/Source/MantleEditor/Private/MantleCosmeticPanel.cpp +++ b/Source/MantleEditor/Private/MantleCosmeticPanel.cpp @@ -18,6 +18,7 @@ #include "MantleUnriggedAsIs.h" #include "SMantleThumbnailSection.h" #include "SMantleCustomAvatarSection.h" +#include "SMantleAnimPackSection.h" #include "IImageWrapper.h" #include "IImageWrapperModule.h" #include "MantleCosmeticUpload.h" @@ -1255,6 +1256,17 @@ void SMantleCosmeticPanel::Construct(const FArguments& InArgs) .GetDraft([this] { return Draft; }) ] ] + // mantle #333 G10: an animation pack, a library item of named clips for any skeleton. + + SVerticalBox::Slot().AutoHeight().Padding(0, 8, 0, 0) + [ + SNew(SExpandableArea) + .InitiallyCollapsed(true) + .AreaTitle(LOCTEXT("AnimPackTitle", "Animation pack")) + .BodyContent() + [ + SNew(SMantleAnimPackSection) + ] + ] + SVerticalBox::Slot().AutoHeight().Padding(0, 8, 0, 0) [ SNew(SExpandableArea) diff --git a/Source/MantleEditor/Private/MantleCosmeticPreviewViewport.cpp b/Source/MantleEditor/Private/MantleCosmeticPreviewViewport.cpp index 6146e29a..5c04be8f 100644 --- a/Source/MantleEditor/Private/MantleCosmeticPreviewViewport.cpp +++ b/Source/MantleEditor/Private/MantleCosmeticPreviewViewport.cpp @@ -3,11 +3,17 @@ #include "MantleAccessoryPlacement.h" #include "MantleAccessorySettings.h" #include "MantleAvatarContract.h" +#include "MantleBuiltInMannequin.h" +#include "MantleEmoteRetarget.h" #include "MantleClipAnimInstance.h" #include "MantleCosmeticPreview.h" #include "MantleCosmeticPreviewRetarget.h" #include "MantleCosmeticThumbnail.h" +#include "Animation/AnimSingleNodeInstance.h" +#include "AnimationRuntime.h" +#include "SceneManagement.h" +#include "Settings/LevelEditorViewportSettings.h" #include "Animation/AnimationAsset.h" #include "Animation/Skeleton.h" #include "Components/SkeletalMeshComponent.h" @@ -55,9 +61,58 @@ namespace MantleCosmeticPreviewViewportPrivate EngineShowFlags.SetGrid(false); } + /** What the camera holds whole. The view's shape is known only once the widget is laid out, so a new size frames it again. */ + void SetFrame(const FBox& Box) + { + FrameBox = Box; + ApplyFrame(); + } + + const FBox& GetFrame() const { return FrameBox; } + + /** The body, drawn as a figure of its bones when it is Mantle's built-in mannequin: that mesh has nothing of its own to show. */ + TWeakObjectPtr Figure; + + using FEditorViewportClient::Draw; + virtual void Draw(const FSceneView* View, FPrimitiveDrawInterface* PDI) override + { + FEditorViewportClient::Draw(View, PDI); + const USkeletalMeshComponent* Body = Figure.Get(); + const USkeletalMesh* Mesh = Body && Body->IsVisible() ? Body->GetSkeletalMeshAsset() : nullptr; + if (!Mesh || !FMantleBuiltInMannequin::Is(Mesh)) + { + return; + } + const FReferenceSkeleton& Skeleton = Mesh->GetRefSkeleton(); + const FLinearColor Color(0.85f, 0.55f, 0.25f); + for (int32 Bone = 0; Bone < Skeleton.GetNum(); ++Bone) + { + const int32 Parent = Skeleton.GetParentIndex(Bone); + const FName Name = Skeleton.GetBoneName(Bone); + if (Parent <= 0 || !FMantleEmoteRetarget::IsBodyBone(Name)) + { + continue; + } + const FVector From = Body->GetBoneTransform(Parent).GetLocation(); + const FVector To = Body->GetBoneTransform(Bone).GetLocation(); + const FString Text = Name.ToString(); + const bool bFinger = Text.StartsWith(TEXT("thumb")) || Text.StartsWith(TEXT("index")) || Text.StartsWith(TEXT("middle")) + || Text.StartsWith(TEXT("ring")) || Text.StartsWith(TEXT("pinky")); + PDI->DrawLine(From, To, Color, SDPG_World, bFinger ? 0.9f : 4.0f); + if (Name == TEXT("head")) + { + DrawWireSphere(PDI, To + (To - From).GetSafeNormal() * 8.0, Color, 10.0, 16, SDPG_World, 1.0f); + } + } + } + virtual void Tick(float DeltaSeconds) override { FEditorViewportClient::Tick(DeltaSeconds); + if (FrameBox.IsValid && Viewport && Viewport->GetSizeXY() != FramedSize) + { + ApplyFrame(); + } if (UWorld* World = Stage.GetWorld()) { World->Tick(LEVELTICK_All, DeltaSeconds); @@ -65,12 +120,35 @@ namespace MantleCosmeticPreviewViewportPrivate } private: + void ApplyFrame() + { + if (!FrameBox.IsValid) + { + return; + } + FramedSize = Viewport ? Viewport->GetSizeXY() : FIntPoint::ZeroValue; + const float Fit = SMantleCosmeticPreviewViewport::FitFieldOfView(ViewFOV, FramedSize, + GetDefault()->AspectRatioAxisConstraint, AspectRatio); + SetViewLocation(FMantleCosmeticThumbnail::FrameCamera(FrameBox, BodyViewRotation(), Fit, FMantleCosmeticThumbnail::FrameMargin)); + SetViewRotation(BodyViewRotation()); + Invalidate(); + } + + static FRotator BodyViewRotation(); + FPreviewScene& Stage; + FBox FrameBox = FBox(ForceInit); + FIntPoint FramedSize = FIntPoint::ZeroValue; }; /** The thumbnail's body view: 20 degrees off the front (meshes face +Y), slightly from above. */ const FRotator BodyView(-4.0f, -70.0f, 0.0f); + FRotator FPreviewViewportClient::BodyViewRotation() + { + return BodyView; + } + USkeletalMeshComponent* MakeComponent(FPreviewScene& Stage) { USkeletalMeshComponent* Component = NewObject(GetTransientPackage(), NAME_None, RF_Transient); @@ -95,10 +173,18 @@ void SMantleCosmeticPreviewViewport::Construct(const FArguments& InArgs) AccessoryComponent->SetCanEverAffectNavigation(false); AccessoryComponent->SetVisibility(false); Scene->AddComponent(AccessoryComponent, FTransform::Identity); + HeldSkeletalComponent = MakeComponent(*Scene); + HeldStaticComponent = NewObject(GetTransientPackage(), NAME_None, RF_Transient); + HeldStaticComponent->SetCollisionProfileName(UCollisionProfile::NoCollision_ProfileName); + HeldStaticComponent->SetGenerateOverlapEvents(false); + HeldStaticComponent->SetCanEverAffectNavigation(false); + HeldStaticComponent->SetVisibility(false); + Scene->AddComponent(HeldStaticComponent, FTransform::Identity); // #283: never drawn, but it animates and refreshes its bones every frame: the avatar's retarget reads them. DriverComponent = MakeComponent(*Scene); DriverComponent->VisibilityBasedAnimTickOption = EVisibilityBasedAnimTickOption::AlwaysTickPoseAndRefreshBones; SEditorViewport::Construct(SEditorViewport::FArguments()); + static_cast(*Client).Figure = BodyComponent; } SMantleCosmeticPreviewViewport::~SMantleCosmeticPreviewViewport() @@ -123,6 +209,8 @@ void SMantleCosmeticPreviewViewport::AddReferencedObjects(FReferenceCollector& C Collector.AddReferencedObject(FaceComponent); Collector.AddReferencedObject(GarmentComponent); Collector.AddReferencedObject(AccessoryComponent); + Collector.AddReferencedObject(HeldStaticComponent); + Collector.AddReferencedObject(HeldSkeletalComponent); Collector.AddReferencedObject(DriverComponent); Collector.AddReferencedObject(Animation); Collector.AddReferencedObject(AvatarRetargeter); @@ -155,6 +243,7 @@ void SMantleCosmeticPreviewViewport::Show(const FMantlePreviewView& View) return; } LeaveAvatarMode(); + SetHeldItem(nullptr, NAME_None, FTransform::Identity); AccessoryComponent->SetVisibility(false); AccessoryComponent->SetStaticMesh(nullptr); BodyComponent->SetSkeletalMeshAsset(View.Body); @@ -393,6 +482,7 @@ void SMantleCosmeticPreviewViewport::LeaveAvatarMode() void SMantleCosmeticPreviewViewport::ClearStage() { LeaveAvatarMode(); + SetHeldItem(nullptr, NAME_None, FTransform::Identity); AccessoryComponent->SetVisibility(false); AccessoryComponent->SetStaticMesh(nullptr); for (USkeletalMeshComponent* Component : { BodyComponent.Get(), FaceComponent.Get(), GarmentComponent.Get(), DriverComponent.Get() }) @@ -440,12 +530,100 @@ void SMantleCosmeticPreviewViewport::Frame(const USkeletalMesh* Body) { return; } - const FBox Bounds = Body->GetImportedBounds().GetBox(); - if (!Bounds.IsValid) + static_cast(*Client).SetFrame(BodyBox(Body)); +} + +FBox SMantleCosmeticPreviewViewport::BodyBox(const USkeletalMesh* Body) +{ + if (!Body) + { + return FBox(ForceInit); + } + if (!FMantleBuiltInMannequin::Is(Body)) { - return; + return Body->GetImportedBounds().GetBox(); + } + // The built-in mannequin's one triangle says nothing about its size: its bones at rest do. + TArray Rest; + FAnimationRuntime::FillUpComponentSpaceTransforms(Body->GetRefSkeleton(), Body->GetRefSkeleton().GetRefBonePose(), Rest); + FBox Box(ForceInit); + for (int32 Bone = 0; Bone < Rest.Num(); ++Bone) + { + if (FMantleEmoteRetarget::IsBodyBone(Body->GetRefSkeleton().GetBoneName(Bone))) + { + Box += Rest[Bone].GetLocation(); + } } - const FRotator View = MantleCosmeticPreviewViewportPrivate::BodyView; - Client->SetViewLocation(FMantleCosmeticThumbnail::FrameCamera(Bounds, View, Client->ViewFOV, FMantleCosmeticThumbnail::FrameMargin)); - Client->SetViewRotation(View); + // The crown above the head bone, and the flesh around the others. + return Box.ExpandBy(FVector(6.0, 6.0, 0.0), FVector(6.0, 6.0, 18.0)); +} + +float SMantleCosmeticPreviewViewport::FitFieldOfView(float ViewFOV, const FIntPoint& Size, int32 AxisConstraint, float CameraAspect) +{ + if (Size.X <= 0 || Size.Y <= 0) + { + return ViewFOV; + } + // FEditorViewportClient::CalcSceneView: which tangent the view's FOV sets, and the other from the widget's shape. + const double Base = FMath::Tan(FMath::DegreesToRadians(static_cast(ViewFOV)) * 0.5); + const double Shape = static_cast(Size.X) / Size.Y; + const bool bMaintainX = AxisConstraint == AspectRatio_MaintainXFOV || (AxisConstraint == AspectRatio_MajorAxisFOV && Size.X > Size.Y); + const double Vertical = bMaintainX ? Base / Shape : (CameraAspect != 0.0f ? Base / CameraAspect : Base); + const double Horizontal = bMaintainX ? Base : Vertical * Shape; + return static_cast(FMath::RadiansToDegrees(FMath::Atan(FMath::Min(Horizontal, Vertical)) * 2.0)); +} + +void SMantleCosmeticPreviewViewport::PoseAt(float Time) +{ + if (BodyComponent && BodyComponent->GetSingleNodeInstance()) + { + BodyComponent->SetPosition(Time, /*bFireNotifies*/ false); + BodyComponent->TickAnimation(0.0f, false); + BodyComponent->RefreshBoneTransforms(); + } +} + +bool SMantleCosmeticPreviewViewport::SetHeldItem(UStreamableRenderAsset* Mesh, FName Socket, const FTransform& Local) +{ + if (!BodyComponent || !HeldStaticComponent || !HeldSkeletalComponent) + { + return false; + } + const bool bFits = Mesh && GetShownBody() && BodyComponent->DoesSocketExist(Socket); + UStaticMesh* Static = bFits ? Cast(Mesh) : nullptr; + USkeletalMesh* Skeletal = bFits ? Cast(Mesh) : nullptr; + HeldStaticComponent->SetStaticMesh(Static); + HeldStaticComponent->SetVisibility(Static != nullptr); + HeldSkeletalComponent->SetSkeletalMeshAsset(Skeletal); + HeldSkeletalComponent->SetVisibility(Skeletal != nullptr); + USceneComponent* Held = GetHeldItem(); + if (Held) + { + Held->AttachToComponent(BodyComponent, FAttachmentTransformRules::KeepRelativeTransform, Socket); + Held->SetRelativeTransform(Local); + } + if (Client.IsValid()) + { + Client->Invalidate(); + } + return Held != nullptr; +} + +USceneComponent* SMantleCosmeticPreviewViewport::GetHeldItem() const +{ + if (HeldStaticComponent && HeldStaticComponent->GetStaticMesh()) + { + return HeldStaticComponent; + } + return HeldSkeletalComponent && HeldSkeletalComponent->GetSkeletalMeshAsset() ? HeldSkeletalComponent.Get() : nullptr; +} + +FTransform SMantleCosmeticPreviewViewport::GetBodySocket(FName Socket) const +{ + return BodyComponent ? BodyComponent->GetSocketTransform(Socket) : FTransform::Identity; +} + +FBox SMantleCosmeticPreviewViewport::GetFrameBox() const +{ + return Client.IsValid() ? static_cast(*Client).GetFrame() : FBox(ForceInit); } diff --git a/Source/MantleEditor/Private/MantleCosmeticPreviewViewport.h b/Source/MantleEditor/Private/MantleCosmeticPreviewViewport.h index 67939434..a29e1018 100644 --- a/Source/MantleEditor/Private/MantleCosmeticPreviewViewport.h +++ b/Source/MantleEditor/Private/MantleCosmeticPreviewViewport.h @@ -10,6 +10,8 @@ class FEditorViewportClient; class UAnimationAsset; class UMaterialInterface; +class USceneComponent; +class UStreamableRenderAsset; class USkeletalMesh; class USkeletalMeshComponent; class UStaticMesh; @@ -79,6 +81,33 @@ class SMantleCosmeticPreviewViewport : public SEditorViewport, public FGCObject /** Loops Animation on the body; null holds the reference pose. Kept but not applied while an avatar shows (its driver plays the idle). */ void SetAnimation(UAnimationAsset* Animation); + /** + * A prop in the shown body's hand (or on any bone or socket of it): a static or skeletal mesh at Local from Socket, + * following the pose. Null shows none. False (and none shown) when there is no body, no such socket or another kind of mesh. + */ + bool SetHeldItem(UStreamableRenderAsset* Mesh, FName Socket, const FTransform& Local); + + /** The held item's component while one shows (tests), else null. */ + USceneComponent* GetHeldItem() const; + + /** Where Socket of the shown body is now, in the stage's world (tests). */ + FTransform GetBodySocket(FName Socket) const; + + /** Poses the playing clip at Time, in seconds (tests). */ + void PoseAt(float Time); + + /** + * The field of view to hand FMantleCosmeticThumbnail::FrameCamera (which assumes a square view) for a viewport of + * Size: the narrower of its two directions. AxisConstraint is an EAspectRatioAxisConstraint. Pure (tested). + */ + static float FitFieldOfView(float ViewFOV, const FIntPoint& Size, int32 AxisConstraint, float CameraAspect); + + /** What the camera holds to show Body whole: the mesh's bounds, or the built-in mannequin's bones (its mesh has no size). */ + static FBox BodyBox(const USkeletalMesh* Body); + + /** What the camera holds (tests). */ + FBox GetFrameBox() const; + /** The body shown, for filtering animations by skeleton; null when nothing is shown. */ USkeletalMesh* GetShownBody() const; @@ -111,6 +140,9 @@ class SMantleCosmeticPreviewViewport : public SEditorViewport, public FGCObject TObjectPtr FaceComponent; TObjectPtr GarmentComponent; TObjectPtr AccessoryComponent; + /** The held item (SetHeldItem): whichever fits the mesh's kind shows. */ + TObjectPtr HeldStaticComponent; + TObjectPtr HeldSkeletalComponent; /** #283: the avatar preview's hidden UEFN driver, whose pose the body's retarget reads. */ TObjectPtr DriverComponent; TObjectPtr Animation; diff --git a/Source/MantleEditor/Private/MantleCreatorClips.cpp b/Source/MantleEditor/Private/MantleCreatorClips.cpp new file mode 100644 index 00000000..6477dea7 --- /dev/null +++ b/Source/MantleEditor/Private/MantleCreatorClips.cpp @@ -0,0 +1,382 @@ +// Copyright Joshua Eger. All Rights Reserved. +// +// Maintainer command: Mantle.Dev.MakeCreatorClip +// Converts one clip exactly as an item's clip is converted at publish, writes the MAN1 bytes and a .json beside them (skeleton +// hash, bones, frames), and logs MANTLE_CREATOR_CLIP. See FMantleCreatorClips (MantleCreatorClips.h). +#include "MantleCreatorClips.h" + +#include "MantleAnimClipWriter.h" +#include "MantleAvatarContract.h" +#include "MantleBuiltInMannequin.h" +#include "MantleEmoteRetarget.h" +#include "MantlePlaceValidator.h" +#include "MantleSha256.h" +#include "MantleSkeletonHash.h" + +#include "Animation/AnimData/IAnimationDataModel.h" +#include "Animation/AnimSequence.h" +#include "Animation/IAnimationSequenceCompiler.h" +#include "Animation/Skeleton.h" +#include "Engine/SkeletalMesh.h" +#include "HAL/IConsoleManager.h" +#include "Misc/FileHelper.h" +#include "Misc/PackageName.h" +#include "Misc/Paths.h" +#include "Misc/ScopeExit.h" +#include "Dom/JsonObject.h" +#include "Serialization/JsonSerializer.h" +#include "Serialization/JsonWriter.h" + +DEFINE_LOG_CATEGORY_STATIC(LogMantleCreatorClips, Log, All); + +// Named, not anonymous: MantleEditor builds as a unity build. +namespace MantleCreatorClipsPrivate +{ + FMantleValidationIssue Issue(const EMantleIssueSeverity Severity, const FString& Problem, const FString& Remedy) + { + return FMantleValidationIssue{ Severity, FString(), Problem, Remedy }; + } + + /** + * Samples Sequence over Mesh's bones and encodes it as a place clip. Fixture, when given (the contract's uefn skeleton): the clip's bone + * table is the fixture's, in the fixture's order, whatever Mesh has (the plugin's built-in mannequin lacks the prop and virtual bones + * that the backend's uefn skeleton carries, and a project's own mannequin may have more), so every UEFN clip hashes the same. Tracks + * bind by bone name, a bone with no track keeps its rest pose, and a track on a bone the fixture does not have is dropped. + */ + bool SampleAndEncode(const UAnimSequence* Sequence, const USkeletalMesh* Mesh, FMantleCreatorClip& Out, FString& OutError, const FMantleContractSkeleton* Fixture = nullptr) + { + FMantleAnimClipData Clip; + if (!FMantleAnimClipWriter::SampleOnMesh(Sequence, Mesh, FMantlePlaceAssetLimits::ClipFrameRate, Clip, OutError)) + { + return false; + } + if (Fixture) + { + TArray Dropped; + for (const FMantleAnimClipTrackData& Track : Clip.Tracks) + { + if (Fixture->Find(Track.Bone) == INDEX_NONE) + { + Dropped.Add(Track.Bone.ToString()); + } + } + Clip.Tracks.RemoveAll([Fixture](const FMantleAnimClipTrackData& Track) { return Fixture->Find(Track.Bone) == INDEX_NONE; }); + if (!Dropped.IsEmpty()) + { + UE_LOG(LogMantleCreatorClips, Log, TEXT("MANTLE_CREATOR_CLIP dropped %d tracks: %s (%s)"), Dropped.Num(), *FString::Join(Dropped, TEXT(", ")), *Sequence->GetName()); + } + // Tracks the sampler never saw: the animation moves a bone the target mesh does not have. A bone the UEFN skeleton does have + // (a prop or virtual bone the in-memory mannequin lacks) is a real loss for a held item, so it is named apart. + TArray Missing; + if (const IAnimationDataModel* Model = Sequence->GetDataModel()) + { + TArray TrackNames; + Model->GetBoneTrackNames(TrackNames); + for (const FName TrackName : TrackNames) + { + if (Mesh->GetRefSkeleton().FindRawBoneIndex(TrackName) == INDEX_NONE && Fixture->Find(TrackName) != INDEX_NONE) + { + Missing.Add(TrackName.ToString()); + } + } + } + if (!Missing.IsEmpty()) + { + UE_LOG(LogMantleCreatorClips, Warning, TEXT("MANTLE_CREATOR_CLIP dropped %d tracks because %s has no such bone: %s (%s)"), Missing.Num(), *Mesh->GetName(), + *FString::Join(Missing, TEXT(", ")), *Sequence->GetName()); + } + if (Clip.Tracks.IsEmpty()) + { + OutError = FString::Printf(TEXT("%s animates no bone of the UEFN skeleton."), *Sequence->GetName()); + return false; + } + Clip.SkeletonBones = Fixture->Bones; + Clip.SkeletonParents = Fixture->Parents; + Clip.SkeletonHash = FMantleSkeletonHash::Compute(Clip.SkeletonBones, Clip.SkeletonParents); + FMantleAnimClipWriter::Canonicalize(Clip); + } + Out.Bytes = FMantleAnimClipWriter::Encode(Clip); + Out.Hash = FMantleSha256::AssetHash(Out.Bytes); + Out.SkeletonHash = Clip.SkeletonHash; + Out.Frames = Clip.FrameCount; + Out.Tracks = Clip.Tracks.Num(); + Out.Bones = Clip.SkeletonBones.Num(); + Out.Seconds = Clip.DurationSeconds(); + return true; + } +} + +UAnimSequence* FMantleCreatorClips::MakePreview(UAnimSequence* Clip, USkeletalMesh*& InOutBody, TStrongObjectPtr& Kept, FString& OutError) +{ + OutError.Reset(); + if (!Clip || !Clip->GetSkeleton()) + { + OutError = TEXT("No animation was chosen."); + return nullptr; + } + const FMantleAvatarContract* Contract = FMantleAvatarContract::Get(&OutError); + if (!Contract) + { + return nullptr; + } + FString Why; + const FString SkeletonId = FMantleEmoteRetarget::IdentifySkeleton(Clip->GetSkeleton(), *Contract, &Why); + if (SkeletonId.IsEmpty()) + { + OutError = FString::Printf(TEXT("%s is not made for a body Mantle can use (%s)."), *Clip->GetName(), *Why); + return nullptr; + } + if (SkeletonId == Contract->EmoteSkeleton) + { + USkeletalMesh* Own = FMantleEmoteRetarget::ChooseSourceMesh(Clip, nullptr); + if (!Own) + { + OutError = FString::Printf(TEXT("No skeletal mesh in this project uses %s's skeleton, so it cannot be shown. Give the skeleton a preview mesh."), *Clip->GetName()); + return nullptr; + } + InOutBody = Own; + return Clip; + } + USkeletalMesh* Target = FMantleBuiltInMannequin::UEFNMannequin(*Contract, &OutError); + if (!Target) + { + return nullptr; + } + TStrongObjectPtr Made; + const bool bOk = FMantleEmoteRetarget::RetargetAndUse(Clip, SkeletonId, FMantleEmoteRetarget::ChooseSourceMesh(Clip, nullptr), Target, *Contract, + [&Made, Target](UAnimSequence& Retargeted, FString& OutUseError) + { + // The retargeted copy is deleted as soon as this returns: a duplicate stays for the preview. Its compression runs + // asynchronously, so let it land first. + UAnimSequence* const Compiling[] = { &Retargeted }; + UE::Anim::IAnimSequenceCompilingManager::FinishCompilation(MakeArrayView(Compiling)); + Made.Reset(DuplicateObject(&Retargeted, GetTransientPackage())); + if (!Made.IsValid()) + { + OutUseError = TEXT("the retargeted animation could not be copied."); + return false; + } + Made->ClearFlags(RF_Public | RF_Standalone); + Made->SetFlags(RF_Transient); + Made->SetPreviewMesh(Target); + return true; + }, OutError); + if (!bOk) + { + return nullptr; + } + Kept = MoveTemp(Made); + InOutBody = Target; + return Kept.Get(); +} + +bool FMantleCreatorClips::ConvertToUefn(UAnimSequence* Sequence, FMantleCreatorClip& Out, FString& OutError, USkeletalMesh* PickedBody) +{ + using namespace MantleCreatorClipsPrivate; + Out = FMantleCreatorClip(); + if (!Sequence || !Sequence->GetSkeleton()) + { + OutError = TEXT("no animation was chosen."); + return false; + } + const FMantleAvatarContract* Contract = FMantleAvatarContract::Get(&OutError); + if (!Contract) + { + return false; + } + FString Why; + const FString SkeletonId = FMantleEmoteRetarget::IdentifySkeleton(Sequence->GetSkeleton(), *Contract, &Why); + if (SkeletonId.IsEmpty()) + { + OutError = FString::Printf(TEXT("%s is not made for a body Mantle can use: its skeleton %s is not the UEFN Mannequin, a MetaHuman, the UE5 Mannequin or the UE4 Mannequin (%s). Retarget it onto one of those and pick the result."), + *Sequence->GetName(), *Sequence->GetSkeleton()->GetName(), *Why); + return false; + } + FString MeshError; + USkeletalMesh* Target = FMantleBuiltInMannequin::UEFNMannequin(*Contract, &MeshError); + if (!Target) + { + OutError = FString::Printf(TEXT("Mantle's UEFN mannequin is not available to play %s on (%s): reinstall the Mantle plugin."), *Sequence->GetName(), *MeshError); + return false; + } + const FMantleContractSkeleton* UefnFixture = Contract->FindSkeleton(Contract->EmoteSkeleton); + if (!UefnFixture) + { + OutError = FString::Printf(TEXT("Mantle's contract has no %s skeleton to write %s against: reinstall the Mantle plugin."), *Contract->EmoteSkeleton, *Sequence->GetName()); + return false; + } + if (SkeletonId == Contract->EmoteSkeleton) + { + if (!SampleAndEncode(Sequence, Target, Out, OutError, UefnFixture)) + { + return false; + } + Out.Note = FString::Printf(TEXT("%s is made on the UEFN Mannequin: sampled as it is over %s."), *Sequence->GetName(), *Target->GetName()); + return true; + } + FString SourceFrom; + USkeletalMesh* Source = FMantleEmoteRetarget::ChooseSourceMesh(Sequence, PickedBody, &SourceFrom); + FString HandsNote; + FMantleCreatorClip Made; + const bool bOk = FMantleEmoteRetarget::RetargetAndUse(Sequence, SkeletonId, Source, Target, *Contract, + [&Made, Sequence, Target, Fixture = UefnFixture](UAnimSequence& Retargeted, FString& OutUseError) + { + FString SampleError; + if (!SampleAndEncode(&Retargeted, Target, Made, SampleError, Fixture)) + { + OutUseError = FString::Printf(TEXT("the retargeted %s could not be read: %s"), *Sequence->GetName(), *SampleError); + return false; + } + return true; + }, OutError, &HandsNote); + if (!bOk) + { + return false; + } + Out = MoveTemp(Made); + UE_LOG(LogMantleCreatorClips, Log, TEXT("MANTLE_CREATOR_CLIP_RETARGETED %s skeleton=%s retargeter=%s"), *Sequence->GetPathName(), *SkeletonId, + *FPackageName::ObjectPathToObjectName(FString(FMantleEmoteRetarget::RetargeterPathFor(SkeletonId)))); + Out.Note = FString::Printf(TEXT("%s retargeted from the %s skeleton (played on %s, %s) onto %s."), *Sequence->GetName(), *SkeletonId, + Source ? *Source->GetName() : TEXT("none"), *SourceFrom, *Target->GetName()); + if (!HandsNote.IsEmpty()) + { + Out.Note += TEXT(" ") + HandsNote; + } + return true; +} + +bool FMantleCreatorClips::ConvertOnOwnMesh(const UAnimSequence* Sequence, const USkeletalMesh* Mesh, FMantleCreatorClip& Out, FString& OutError) +{ + Out = FMantleCreatorClip(); + if (!MantleCreatorClipsPrivate::SampleAndEncode(Sequence, Mesh, Out, OutError)) + { + return false; + } + Out.Note = FString::Printf(TEXT("%s sampled over %s's own bones."), *Sequence->GetName(), *Mesh->GetName()); + return true; +} + +bool FMantleCreatorClips::CheckClip(const FString& Name, const UAnimSequence* Sequence, const FMantleCreatorClip* Converted, + const FMantlePlaceAssetLimits& Limits, TArray& OutIssues) +{ + using namespace MantleCreatorClipsPrivate; + const int32 Before = OutIssues.Num(); + // Its length (and the rest FMantlePlaceAssets checks of a place clip), before anything is converted. + FMantlePlaceAssets::CheckClip(Sequence, FString(), Limits, OutIssues); + if (Converted) + { + if (Converted->Bytes.Num() > Limits.MaxClipCookedBytes) + { + OutIssues.Add(Issue(EMantleIssueSeverity::Error, + FString::Printf(TEXT("Clip '%s' is %.1f MB as a Mantle clip; a clip may be at most %.0f MB."), *Name, + Converted->Bytes.Num() / (1024.0 * 1024.0), Limits.MaxClipCookedBytes / (1024.0 * 1024.0)), + TEXT("Shorten it, or animate fewer bones."))); + } + if (Converted->Bones > Limits.MaxSkeletalBones) + { + OutIssues.Add(Issue(EMantleIssueSeverity::Error, + FString::Printf(TEXT("Clip '%s' is made for a skeleton with %d bones; a clip may have at most %d."), *Name, Converted->Bones, Limits.MaxSkeletalBones), + TEXT("Make it on a skeleton with fewer bones."))); + } + if (!Sequence && Converted->Seconds > Limits.MaxClipSeconds + 1.0e-6) + { + OutIssues.Add(Issue(EMantleIssueSeverity::Error, + FString::Printf(TEXT("Clip '%s' is %.1f s long; a clip may be at most %g s."), *Name, Converted->Seconds, Limits.MaxClipSeconds), + TEXT("Trim the animation, or split it."))); + } + } + for (int32 Index = Before; Index < OutIssues.Num(); ++Index) + { + if (OutIssues[Index].Severity == EMantleIssueSeverity::Error) + { + return false; + } + } + return true; +} + +TConstArrayView FMantleCreatorClips::ItemSlotNames() +{ + static const TCHAR* const Names[] = { TEXT("hold"), TEXT("use"), TEXT("equip"), TEXT("putAway") }; + return TConstArrayView(Names); +} + +bool FMantleCreatorClips::CheckItemTotal(const TConstArrayView Clips, TArray& OutIssues) +{ + int64 Total = 0; + for (const FMantleCreatorClip* Clip : Clips) + { + Total += Clip ? Clip->Bytes.Num() : 0; + } + if (Total <= MaxItemClipBytes) + { + return true; + } + OutIssues.Add(MantleCreatorClipsPrivate::Issue(EMantleIssueSeverity::Error, + FString::Printf(TEXT("This item's clips together are %.1f MB as Mantle clips; they may be at most %.0f MB together."), + Total / (1024.0 * 1024.0), MaxItemClipBytes / (1024.0 * 1024.0)), + TEXT("Shorten the clips, or use fewer of them."))); + return false; +} + +namespace MantleCreatorClipsPrivate +{ + void MakeCreatorClipCommand(const TArray& Args) + { + if (Args.Num() < 2) + { + UE_LOG(LogMantleCreatorClips, Error, TEXT("MANTLE_CREATOR_CLIP usage: Mantle.Dev.MakeCreatorClip ")); + return; + } + UE_LOG(LogMantleCreatorClips, Log, TEXT("MANTLE_CREATOR_CLIP started %s"), *Args[0]); + UAnimSequence* Sequence = LoadObject(nullptr, *Args[0]); + if (!Sequence) + { + UE_LOG(LogMantleCreatorClips, Error, TEXT("MANTLE_CREATOR_CLIP failed: %s did not load as an animation"), *Args[0]); + return; + } + FMantleCreatorClip Clip; + FString Error; + const double Start = FPlatformTime::Seconds(); + if (!FMantleCreatorClips::ConvertToUefn(Sequence, Clip, Error)) + { + UE_LOG(LogMantleCreatorClips, Error, TEXT("MANTLE_CREATOR_CLIP failed %s: %s"), *Args[0], *Error); + return; + } + TArray Issues; + const bool bFits = FMantleCreatorClips::CheckClip(Sequence->GetName(), Sequence, &Clip, FMantlePlaceAssetLimits::FromContract(), Issues); + for (const FMantleValidationIssue& Found : Issues) + { + UE_LOG(LogMantleCreatorClips, Warning, TEXT("MANTLE_CREATOR_CLIP check: %s"), *Found.Problem); + } + const FString OutFile = FPaths::ConvertRelativePathToFull(Args[1]); + if (!FFileHelper::SaveArrayToFile(Clip.Bytes, *OutFile)) + { + UE_LOG(LogMantleCreatorClips, Error, TEXT("MANTLE_CREATOR_CLIP failed: %s could not be written"), *OutFile); + return; + } + TSharedRef Json = MakeShared(); + Json->SetStringField(TEXT("source"), Sequence->GetPathName()); + Json->SetStringField(TEXT("skeletonHash"), Clip.SkeletonHash); + Json->SetNumberField(TEXT("bones"), Clip.Bones); + Json->SetNumberField(TEXT("tracks"), Clip.Tracks); + Json->SetNumberField(TEXT("frames"), Clip.Frames); + Json->SetNumberField(TEXT("seconds"), Clip.Seconds); + Json->SetNumberField(TEXT("bytes"), Clip.Bytes.Num()); + Json->SetStringField(TEXT("assetHash"), Clip.Hash); + Json->SetStringField(TEXT("note"), Clip.Note); + FString JsonText; + TSharedRef> Writer = TJsonWriterFactory<>::Create(&JsonText); + FJsonSerializer::Serialize(Json, Writer); + FFileHelper::SaveStringToFile(JsonText, *(OutFile + TEXT(".json"))); + UE_LOG(LogMantleCreatorClips, Log, TEXT("MANTLE_CREATOR_CLIP done %s -> %s skeleton=%s bones=%d tracks=%d frames=%d bytes=%d fits=%d seconds=%.2f. %s"), + *Sequence->GetPathName(), *OutFile, *Clip.SkeletonHash, Clip.Bones, Clip.Tracks, Clip.Frames, Clip.Bytes.Num(), bFits ? 1 : 0, + FPlatformTime::Seconds() - Start, *Clip.Note); + } + + FAutoConsoleCommand GMantleDevMakeCreatorClipCommand( + TEXT("Mantle.Dev.MakeCreatorClip"), + TEXT("Mantle.Dev.MakeCreatorClip -- converts one clip as an item's clip is converted at publish (retargeted to the UEFN ") + TEXT("mannequin, sampled over its bones) and writes the MAN1 bytes and a .json with the skeleton hash beside them."), + FConsoleCommandWithArgsDelegate::CreateStatic(&MakeCreatorClipCommand)); +} diff --git a/Source/MantleEditor/Private/MantleCreatorClips.h b/Source/MantleEditor/Private/MantleCreatorClips.h new file mode 100644 index 00000000..68bb0f9b --- /dev/null +++ b/Source/MantleEditor/Private/MantleCreatorClips.h @@ -0,0 +1,72 @@ +// Copyright Joshua Eger. All Rights Reserved. +#pragma once + +#include "CoreMinimal.h" +#include "MantlePlaceAssets.h" +#include "UObject/StrongObjectPtr.h" + +class UAnimSequence; +class USkeletalMesh; +struct FMantleValidationIssue; + +/** + * One creator clip as it is uploaded (mantle #333): MAN1 bytes sampled over a mesh's bones (a place clip, with its skeleton + * block), and what the checks and the notes need to say about it. + */ +struct FMantleCreatorClip +{ + TArray Bytes; + /** FMantleSha256::AssetHash of Bytes. */ + FString Hash; + /** FMantleSkeletonHash of the mesh the clip was sampled over (the skeleton block's hash). */ + FString SkeletonHash; + int32 Frames = 0; + int32 Tracks = 0; + int32 Bones = 0; + double Seconds = 0.0; + /** What was done, for the log and the creator's notes ("retargeted from ue5mannequin ..."). */ + FString Note; +}; + +/** + * The shared conversion for a creator's own clips (usable items and consumables, mantle #333 P1; Custom avatars use the + * own-mesh route). Pure editor code, no Slate. + */ +struct FMantleCreatorClips +{ + /** + * A clip made on the UEFN, MetaHuman, UE5 or UE4 Mannequin skeleton, as the UEFN clip Mantle plays on every player: + * a UEFN clip is sampled as it is; the others are retargeted to the UEFN mannequin the way emotes are + * (FMantleEmoteRetarget::RetargetAndUse); either way it is sampled over the UEFN mannequin's bones at the place clip + * rate (FMantleAnimClipWriter::SampleOnMesh) and encoded as a place clip. Any other skeleton is refused with OutError, a + * sentence for the creator. PickedBody: the body a retargeted clip is played on, when its own preview mesh says none. + * Game thread. + */ + static bool ConvertToUefn(UAnimSequence* Sequence, FMantleCreatorClip& Out, FString& OutError, USkeletalMesh* PickedBody = nullptr); + + /** A clip made for Mesh's own skeleton (Custom avatars), sampled over Mesh's bones as a place does. */ + static bool ConvertOnOwnMesh(const UAnimSequence* Sequence, const USkeletalMesh* Mesh, FMantleCreatorClip& Out, FString& OutError); + + /** + * Clip as it plays on every player, for a preview: a UEFN clip on a UEFN body as it is, a MetaHuman, UE5 or UE4 Mannequin clip + * retargeted onto the built-in UEFN mannequin (the copy lives in Kept until the next preview). InOutBody becomes the body it plays on. + * Null with OutError, a sentence for the creator, when it cannot be shown. Game thread. + */ + static UAnimSequence* MakePreview(UAnimSequence* Clip, USkeletalMesh*& InOutBody, TStrongObjectPtr& Kept, FString& OutError); + + /** + * The place clip limits that a clip is checked against before it is converted (its length) and after (its cooked + * size and bone count). Appends to OutIssues; true when no error was added. + */ + static bool CheckClip(const FString& Name, const UAnimSequence* Sequence, const FMantleCreatorClip* Converted, const FMantlePlaceAssetLimits& Limits, + TArray& OutIssues); + + /** All of one item's clips together: at most MaxItemClipBytes cooked. Appends an error to OutIssues when over; true when it fits. */ + static bool CheckItemTotal(TConstArrayView Clips, TArray& OutIssues); + + /** The slots of an item's `clips` block, in the order the Clips control shows them: hold, use, equip, putAway. */ + static TConstArrayView ItemSlotNames(); + + /** mantle #333: all of one item's clips together, cooked. */ + static constexpr int64 MaxItemClipBytes = 8 << 20; +}; diff --git a/Source/MantleEditor/Private/MantleDevClipSlotShot.cpp b/Source/MantleEditor/Private/MantleDevClipSlotShot.cpp new file mode 100644 index 00000000..ec26db39 --- /dev/null +++ b/Source/MantleEditor/Private/MantleDevClipSlotShot.cpp @@ -0,0 +1,218 @@ +// Copyright Joshua Eger. All Rights Reserved. +// +// Maintainer command: Mantle.Dev.ClipSlotShots [Exit] +// Pictures of the shared clip slots (mantle #333 P1) in a window: the Custom section on Clip A's preview mesh (wide, at the size of a small +// window, and narrow), the Animation pack section with the two clips, and a bare clip list holding a cube in its right hand while Clip A plays. +// Each picture is taken 30 frames after its step. Nothing uploads. The editor needs to draw (no -nullrhi). Logs MANTLE_CLIPSLOT_SHOT lines. +#include "MantleCosmeticPreviewViewport.h" +#include "MantlePng.h" +#include "MantleRuntime.h" +#include "SMantleAnimPackSection.h" +#include "SMantleClipSlots.h" +#include "SMantleCustomAvatarSection.h" + +#include "Animation/AnimSequence.h" +#include "AssetCompilingManager.h" +#include "Containers/Ticker.h" +#include "Engine/SkeletalMesh.h" +#include "Engine/StaticMesh.h" +#include "Framework/Application/SlateApplication.h" +#include "HAL/FileManager.h" +#include "HAL/IConsoleManager.h" +#include "Misc/FileHelper.h" +#include "Misc/PackageName.h" +#include "Misc/Paths.h" +#include "Styling/AppStyle.h" +#include "UObject/StrongObjectPtr.h" +#include "Widgets/Layout/SBorder.h" +#include "Widgets/Layout/SScrollBox.h" +#include "Widgets/SWindow.h" + +/** Reaches into the sections for Mantle.Dev.ClipSlotShots (a friend of both). */ +struct FMantleClipSlotShotAccess +{ + /** One thing to do, and the picture to take 30 frames after it (none when Picture is empty). */ + struct FShot + { + FString Picture; + TFunction Do; + }; + + struct FRun + { + TSharedPtr Window; + TSharedPtr Scroll; + TSharedPtr Custom; + TSharedPtr Pack; + TSharedPtr Bare; + TArray Shots; + FString Directory; + int32 Index = 0; + int32 Frames = 0; + bool bExit = false; + }; + + static UObject* Load(FString Path) + { + if (!FPackageName::GetShortName(Path).Contains(TEXT("."))) + { + Path += TEXT(".") + FPackageName::GetShortName(Path); + } + UObject* Object = LoadObject(nullptr, *Path); + if (!Object) + { + UE_LOG(LogMantle, Error, TEXT("MANTLE_CLIPSLOT_SHOT %s did not load"), *Path); + } + return Object; + } + + static void Show(FRun& Run, const TSharedRef& Content, const FVector2D& Size) + { + SAssignNew(Run.Scroll, SScrollBox) + SScrollBox::Slot().Padding(8)[Content]; + Run.Window->Resize(Size); + Run.Window->SetContent(SNew(SBorder).BorderImage(FAppStyle::GetBrush("ToolPanel.GroupBorder"))[Run.Scroll.ToSharedRef()]); + } + + static bool Tick(const TSharedRef& Run) + { + if (!Run->Shots.IsValidIndex(Run->Index)) + { + UE_LOG(LogMantle, Display, TEXT("MANTLE_CLIPSLOT_SHOT done")); + Run->Window->RequestDestroyWindow(); + const bool bExit = Run->bExit; + Run->Shots.Reset(); + Run->Scroll.Reset(); + Run->Custom.Reset(); + Run->Pack.Reset(); + Run->Bare.Reset(); + if (bExit) + { + FPlatformMisc::RequestExit(false); + } + return false; + } + if (Run->Frames == 0) + { + Run->Shots[Run->Index].Do(); + FAssetCompilingManager::Get().FinishAllCompilation(); + } + if (++Run->Frames <= 30) + { + return true; + } + const FString& Picture = Run->Shots[Run->Index].Picture; + if (!Picture.IsEmpty()) + { + TArray Pixels; + FIntVector Size; + const FString File = FPaths::Combine(Run->Directory, Picture + TEXT(".png")); + bool bSaved = FSlateApplication::Get().TakeScreenshot(Run->Window.ToSharedRef(), Pixels, Size); + if (bSaved) + { + for (FColor& Pixel : Pixels) + { + Pixel.A = 255; + } + bSaved = FFileHelper::SaveArrayToFile(FMantlePng::EncodeRGBA8(Size.X, Size.Y, Pixels), *File); + } + UE_LOG(LogMantle, Display, TEXT("MANTLE_CLIPSLOT_SHOT %s %s"), *File, bSaved ? TEXT("saved") : TEXT("NOT saved")); + } + ++Run->Index; + Run->Frames = 0; + return true; + } + + static void Start(const TArray& Args) + { + if (Args.Num() < 3) + { + UE_LOG(LogMantle, Error, TEXT("MANTLE_CLIPSLOT_SHOT usage: Mantle.Dev.ClipSlotShots [Exit]")); + return; + } + UAnimSequence* ClipA = Cast(Load(Args[0])); + UAnimSequence* ClipB = Cast(Load(Args[1])); + USkeletalMesh* Mesh = ClipA ? ClipA->GetPreviewMesh() : nullptr; + UStaticMesh* Cube = Cast(Load(TEXT("/Engine/BasicShapes/Cube"))); + if (!ClipA || !ClipB || !Mesh || !Cube || !FSlateApplication::IsInitialized()) + { + UE_LOG(LogMantle, Error, TEXT("MANTLE_CLIPSLOT_SHOT needs two animations, the first with a preview mesh")); + return; + } + static TArray> Kept; + Kept = { TStrongObjectPtr(ClipA), TStrongObjectPtr(ClipB), TStrongObjectPtr(Mesh), TStrongObjectPtr(Cube) }; + const TSharedRef Run = MakeShared(); + Run->Directory = Args[2]; + Run->bExit = Args.Num() > 3 && Args[3].Equals(TEXT("Exit"), ESearchCase::IgnoreCase); + IFileManager::Get().MakeDirectory(*Run->Directory, true); + Run->Window = SNew(SWindow).Title(INVTEXT("Clip slots")).ClientSize(FVector2D(890.0, 500.0)).SizingRule(ESizingRule::UserSized); + FSlateApplication::Get().AddWindow(Run->Window.ToSharedRef()); + const TWeakPtr Weak = Run; + + Run->Shots.Add({ FString(), [Weak, Mesh] + { + const TSharedPtr Held = Weak.Pin(); + Held->Custom = SNew(SMantleCustomAvatarSection) + .GetSource([Mesh] { return Mesh; }) + .GetConverted([] { return static_cast(nullptr); }) + .GetScale([] { return 1.0; }) + .GetFeetZ([] { return 0.0; }) + .GetName([] { return FString(TEXT("ClipSlotShot")); }); + Held->Custom->SourceChanged(); + Show(*Held, Held->Custom.ToSharedRef(), FVector2D(890.0, 500.0)); + } }); + auto ToClips = [Weak] + { + const TSharedPtr Held = Weak.Pin(); + Held->Scroll->ScrollDescendantIntoView(Held->Custom->ClipSlots, false, EDescendantScrollDestination::TopOrLeft); + }; + Run->Shots.Add({ TEXT("custom_890x500"), ToClips }); + Run->Shots.Add({ TEXT("custom_890x500_playing"), [Weak, ClipA] + { + Weak.Pin()->Custom->ClipSlots->Preview(ClipA); + } }); + Run->Shots.Add({ FString(), [Weak] { Weak.Pin()->Window->Resize(FVector2D(450.0, 800.0)); } }); + Run->Shots.Add({ TEXT("custom_narrow_450x800"), ToClips }); + Run->Shots.Add({ TEXT("pack_890x500"), [Weak, ClipA, ClipB] + { + const TSharedPtr Held = Weak.Pin(); + Held->Pack = SNew(SMantleAnimPackSection); + FMantleClipSlotsModel& Model = *Held->Pack->Clips; + const FName First = Model.Slots[0].Name; + Model.RenameFreeSlot(First, TEXT("drink")); + Model.SetClip(First, 0, FSoftObjectPath(ClipA)); + const FName Second = Model.AddFreeSlot(TEXT("drink_ue4")); + Model.SetClip(Second, 0, FSoftObjectPath(ClipB)); + Held->Pack->ClipSlots->Refresh(); + Show(*Held, Held->Pack.ToSharedRef(), FVector2D(890.0, 500.0)); + } }); + Run->Shots.Add({ TEXT("pack_playing_ue4_890x500"), [Weak, ClipB] + { + Weak.Pin()->Pack->ClipSlots->PlayClip(ClipB); + } }); + Run->Shots.Add({ TEXT("held_item_890x500"), [Weak, Mesh, Cube, ClipA] + { + const TSharedPtr Held = Weak.Pin(); + const TSharedRef Model = MakeShared(); + Model->PreviewMesh = Mesh; + FMantleClipSlotDef& Slot = Model->Slots.AddDefaulted_GetRef(); + Slot.Name = TEXT("hold"); + Slot.Label = INVTEXT("Hold"); + Model->HeldItem.Mesh = Cube; + Model->HeldItem.Socket = TEXT("hand_r"); + Model->HeldItem.Local = FTransform(FQuat::Identity, FVector::ZeroVector, FVector(0.15)); + Held->Bare = SNew(SMantleClipSlots).Model(Model); + Show(*Held, Held->Bare.ToSharedRef(), FVector2D(890.0, 500.0)); + Held->Bare->Preview(ClipA); + } }); + FTSTicker::GetCoreTicker().AddTicker(FTickerDelegate::CreateLambda([Run](float) { return Tick(Run); })); + } +}; + +// Named, not anonymous: MantleEditor builds as a unity build. +namespace MantleDevClipSlotShotPrivate +{ + FAutoConsoleCommand GClipSlotShotsCommand( + TEXT("Mantle.Dev.ClipSlotShots"), + TEXT("Mantle.Dev.ClipSlotShots [Exit] -- pictures of the shared clip slots in the Custom section, the Animation pack section and with a held item. Nothing uploads."), + FConsoleCommandWithArgsDelegate::CreateStatic(&FMantleClipSlotShotAccess::Start)); +} diff --git a/Source/MantleEditor/Private/MantleDevItemBuilderShot.cpp b/Source/MantleEditor/Private/MantleDevItemBuilderShot.cpp new file mode 100644 index 00000000..6f6deb3e --- /dev/null +++ b/Source/MantleEditor/Private/MantleDevItemBuilderShot.cpp @@ -0,0 +1,271 @@ +// Copyright Joshua Eger. All Rights Reserved. +// +// Maintainer command: Mantle.Dev.ItemBuilderShots [Exit] +// Opens Build an item in a window and goes through it three times: a consumable (hunger) with the clip as Use, a usable item with the clip as Hold, +// and a pistol (mantle #333 P2). The type picker, each Animations screen and the usable item's size screen (tipped forward) are photographed into after 30 frames, and the usable item's Animations +// screen once more with its Hold clip playing and the item in the hand; each item is created (so its document is written under +// /Game/MantleWeapons/P2Shot*/), and its clip is played on the Animations screen. Nothing uploads. The editor needs to draw +// (no -nullrhi). Logs MANTLE_ITEM_SHOT lines. +#include "MantlePng.h" +#include "MantleRuntime.h" +#include "MantleWeaponBuilderLogic.h" +#include "MantleWeaponSource.h" +#include "SMantleClipSlots.h" +#include "SMantleWeaponBuilder.h" + +#include "Animation/AnimSequence.h" +#include "AssetCompilingManager.h" +#include "Containers/Ticker.h" +#include "Framework/Application/SlateApplication.h" +#include "HAL/FileManager.h" +#include "HAL/IConsoleManager.h" +#include "Misc/FileHelper.h" +#include "Misc/PackageName.h" +#include "Misc/Paths.h" +#include "Widgets/SWindow.h" + +/** Reaches into the window for Mantle.Dev.ItemBuilderShots (a friend of SMantleWeaponBuilder). */ +struct FMantleItemBuilderShotAccess +{ + /** One thing to do, and the picture to take 30 frames after it (none when Picture is empty). */ + struct FShot + { + FString Picture; + TFunction Do; + }; + + struct FRun + { + TSharedPtr Window; + TSharedPtr Panel; + TArray Shots; + FString Directory; + int32 Index = 0; + int32 Frames = 0; + bool bExit = false; + /** The step just done takes no picture. */ + bool bSkip = false; + }; + + /** The usable item's "Size and direction" screen as it opens and after "Tip forward"; the pistol's as it opens, to compare. */ + static void AddSizeShots(const TSharedRef& Run, const FString& Prefix, const EMantleWeaponHold Hold) + { + using namespace MantleWeaponBuilderLogic; + const TWeakPtr Weak = Run; + const int32 Count = Hold == EMantleWeaponHold::Item ? 2 : 1; + for (int32 Part = 0; Part < Count; ++Part) + { + const TCHAR* const Names[] = { TEXT("_size"), TEXT("_size_tipped") }; + Run->Shots.Add({ Prefix + Names[Part], [Weak, Part] + { + const TSharedPtr Held = Weak.Pin(); + SMantleWeaponBuilder& Panel = *Held->Panel; + if (Part == 0) + { + const TArray& Steps = Panel.Flow->GetSteps(); + for (int32 Step = 0; Step < Steps.Num(); ++Step) + { + if (Steps[Step].Title.ToString() == TEXT("Size and direction")) + { + Panel.Flow->GoTo(Step); + } + } + } + else + { + Panel.TurnFit(QuarterTurn(EQuarterTurn::Forward)); + } + } }); + } + } + + static UObject* Load(FString Path) + { + if (!FPackageName::GetShortName(Path).Contains(TEXT("."))) + { + Path += TEXT(".") + FPackageName::GetShortName(Path); + } + UObject* Object = LoadObject(nullptr, *Path); + if (!Object) + { + UE_LOG(LogMantle, Error, TEXT("MANTLE_ITEM_SHOT %s did not load"), *Path); + } + return Object; + } + + /** The screens of one item, from a new window on the first screen to the created item. */ + static void AddItem(const TSharedRef& Run, const FString& Prefix, const FString& Name, const EMantleWeaponHold Hold, UObject* Model, UAnimSequence* Clip) + { + using namespace MantleWeaponBuilderLogic; + const TWeakPtr Weak = Run; + Run->Shots.Add({ Prefix + TEXT("_0_type"), [Weak, Name, Hold] + { + const TSharedPtr Held = Weak.Pin(); + Held->Panel = SNew(SMantleWeaponBuilder); + Held->Window->SetContent(Held->Panel.ToSharedRef()); + Held->Panel->SetItemType(ItemTypeOf(Hold)); + if (ItemTypeOf(Hold) == EItemType::Weapon) + { + Held->Panel->SetHold(Hold); + } + Held->Panel->Working->DisplayName = Name; + Held->Panel->bNameEdited = true; + if (Hold == EMantleWeaponHold::Consumable) + { + // A hunger consumable, so the written document is one with an effect and its amount (mantle #333 G4). + Held->Panel->Working->Consumable.Effect = EMantleWeaponSourceConsumableEffect::Hunger; + Held->Panel->Working->Consumable.Amount = 40.f; + } + } }); + // The screens' count depends on the type, which the first step picks, so each later step is queued by its place and skipped past the end. + for (int32 Step = 1; Step < 9; ++Step) + { + Run->Shots.Add({ FString::Printf(TEXT("%s_%d"), *Prefix, Step), [Weak, Step, Model, Clip, Hold] + { + const TSharedPtr Held = Weak.Pin(); + SMantleWeaponBuilder& Panel = *Held->Panel; + if (Step >= Panel.Flow->GetSteps().Num()) + { + Held->bSkip = true; + return; + } + const FString Title = Panel.Flow->GetSteps()[Step].Title.ToString(); + // Pictures are of the builder's new screens only: the type picker and the Animations screen (the size screen has its own shots + // after the item is created). The other screens are gone through unphotographed. + Held->bSkip = Title != TEXT("Animations"); + if (Panel.Working->Model.IsNull()) + { + Panel.SetModel(Model); + } + if (Clip && TakesClips(Hold)) + { + TSoftObjectPtr& Field = Hold == EMantleWeaponHold::Item ? Panel.Working->ClipHold : Panel.Working->ClipUse; + Field = Clip; + } + Panel.Flow->GoTo(Step); + UE_LOG(LogMantle, Display, TEXT("MANTLE_ITEM_SHOT screen %d %s"), Step, *Title); + if (Step == Panel.Flow->GetSteps().Num() - 1) + { + Panel.Create(); + UE_LOG(LogMantle, Display, TEXT("MANTLE_ITEM_SHOT created %s %s exported=%d"), *Panel.Working->DisplayName, + *Panel.SourceAssetPath.ToString(), Panel.CreatedSignature.IsEmpty() ? 0 : 1); + } + } }); + } + if (Clip && TakesClips(Hold)) + { + Run->Shots.Add({ Prefix + TEXT("_play"), [Weak, Clip, Hold] + { + const TSharedPtr Held = Weak.Pin(); + SMantleWeaponBuilder& Panel = *Held->Panel; + const TArray& Steps = Panel.Flow->GetSteps(); + for (int32 Step = 0; Step < Steps.Num(); ++Step) + { + if (Steps[Step].Title.ToString() == TEXT("Animations")) + { + Panel.Flow->GoTo(Step); + } + } + // Only the usable item's carry is photographed: its Hold clip with the item in the hand. + Held->bSkip = Hold != EMantleWeaponHold::Item; + if (const TSharedPtr Slots = Panel.ClipsView.Pin()) + { + Slots->PlayClip(Clip); + UE_LOG(LogMantle, Display, TEXT("MANTLE_ITEM_SHOT played %s error=[%s]"), *Clip->GetName(), *Panel.ClipPreviewError); + } + else + { + UE_LOG(LogMantle, Error, TEXT("MANTLE_ITEM_SHOT no Animations screen to play on")); + } + } }); + } + if (Hold != EMantleWeaponHold::Consumable) + { + AddSizeShots(Run, Prefix, Hold); + } + } + + static bool Tick(const TSharedRef& Run) + { + if (!Run->Shots.IsValidIndex(Run->Index)) + { + UE_LOG(LogMantle, Display, TEXT("MANTLE_ITEM_SHOT done")); + Run->Window->RequestDestroyWindow(); + Run->Panel.Reset(); + if (Run->bExit) + { + FPlatformMisc::RequestExit(false); + } + return false; + } + const FShot& Shot = Run->Shots[Run->Index]; + if (Run->Frames == 0) + { + Shot.Do(); + FAssetCompilingManager::Get().FinishAllCompilation(); + if (Run->bSkip) + { + Run->bSkip = false; + ++Run->Index; + return true; + } + } + if (++Run->Frames <= 30) + { + return true; + } + TArray Pixels; + FIntVector Size; + const FString File = FPaths::Combine(Run->Directory, Shot.Picture + TEXT(".png")); + bool bSaved = FSlateApplication::Get().TakeScreenshot(Run->Window.ToSharedRef(), Pixels, Size); + if (bSaved) + { + for (FColor& Pixel : Pixels) + { + Pixel.A = 255; + } + bSaved = FFileHelper::SaveArrayToFile(FMantlePng::EncodeRGBA8(Size.X, Size.Y, Pixels), *File); + } + UE_LOG(LogMantle, Display, TEXT("MANTLE_ITEM_SHOT %s %s"), *File, bSaved ? TEXT("saved") : TEXT("NOT saved")); + ++Run->Index; + Run->Frames = 0; + return true; + } + + static void Start(const TArray& Args) + { + if (Args.Num() < 4) + { + UE_LOG(LogMantle, Error, TEXT("MANTLE_ITEM_SHOT usage: Mantle.Dev.ItemBuilderShots [Exit]")); + return; + } + UObject* Item = Load(Args[0]); + UObject* Gun = Load(Args[1]); + UAnimSequence* Clip = Cast(Load(Args[2])); + if (!Item || !Gun || !Clip || !FSlateApplication::IsInitialized()) + { + return; + } + static TArray> Kept; + Kept = { TStrongObjectPtr(Item), TStrongObjectPtr(Gun), TStrongObjectPtr(Clip) }; + const TSharedRef Run = MakeShared(); + Run->Directory = Args[3]; + Run->bExit = Args.Num() > 4 && Args[4].Equals(TEXT("Exit"), ESearchCase::IgnoreCase); + IFileManager::Get().MakeDirectory(*Run->Directory, true); + Run->Window = SNew(SWindow).Title(INVTEXT("Build an item")).ClientSize(FVector2D(1100.0, 900.0)); + FSlateApplication::Get().AddWindow(Run->Window.ToSharedRef()); + AddItem(Run, TEXT("consumable"), TEXT("P2Shot Potion"), EMantleWeaponHold::Consumable, Item, Clip); + AddItem(Run, TEXT("usable"), TEXT("P2Shot Lantern"), EMantleWeaponHold::Item, Item, Clip); + AddItem(Run, TEXT("gun"), TEXT("P2Shot Pistol"), EMantleWeaponHold::Pistol, Gun, nullptr); + FTSTicker::GetCoreTicker().AddTicker(FTickerDelegate::CreateLambda([Run](float) { return Tick(Run); })); + } +}; + +// Named, not anonymous: MantleEditor builds as a unity build. +namespace MantleDevItemBuilderShotPrivate +{ + FAutoConsoleCommand GItemBuilderShotsCommand( + TEXT("Mantle.Dev.ItemBuilderShots"), + TEXT("Mantle.Dev.ItemBuilderShots [Exit] -- goes through Build an item for a consumable, a usable item and a pistol, photographing the type picker and the Animations screens and creating each item. Nothing uploads."), + FConsoleCommandWithArgsDelegate::CreateStatic(&FMantleItemBuilderShotAccess::Start)); +} diff --git a/Source/MantleEditor/Private/MantleEditor.cpp b/Source/MantleEditor/Private/MantleEditor.cpp index c800b8bc..932e510f 100644 --- a/Source/MantleEditor/Private/MantleEditor.cpp +++ b/Source/MantleEditor/Private/MantleEditor.cpp @@ -211,7 +211,7 @@ namespace { FMessageDialog::Open(EAppMsgType::Ok, LOCTEXT("AddWeaponSpawnNoWeapons", - "Added a weapon spawn.\n\nYou have not built a weapon yet. Use Tools > Mantle > Build a weapon to make one, " + "Added a weapon spawn.\n\nYou have not built a weapon yet. Use Tools > Mantle > Build an item to make one, " "then pick it in this spawn's Weapon list.")); } } @@ -560,7 +560,7 @@ void FMantleEditorModule::StartupModule() SMantleVehicleBuilder::RegisterTab(); // #614 stage 6: Tools > Mantle > Library..., browse vehicles and weapons and add them to the place's storage. SMantleLibraryPanel::RegisterTab(); - // #729: Tools > Mantle > Build a weapon..., the guided weapon builder. + // #729: Tools > Mantle > Build an item..., the guided item builder. FMantleWeaponBuilderPanel::RegisterTab(); // #563 stage 3: the Mantle Preview panel that Test Locally opens. SMantlePreviewPanel::RegisterTab(); @@ -849,8 +849,8 @@ void FillMantleSection(FToolMenuSection& Section) Section.AddMenuEntry( TEXT("MantleBuildWeapon"), - LOCTEXT("BuildWeaponLabel", "Build a weapon..."), - LOCTEXT("BuildWeaponTooltip", "Turn a 3D model into a weapon players can use: a gun, a bow, a blade or another weapon."), + LOCTEXT("BuildItemLabel", "Build an item..."), + LOCTEXT("BuildItemTooltip", "Turn a 3D model into an item players can use: a weapon such as a gun, bow or blade, a consumable, or a usable item."), FSlateIcon(), FUIAction(FExecuteAction::CreateStatic(&FMantleWeaponBuilderPanel::TryInvokeTab))); diff --git a/Source/MantleEditor/Private/MantleEmoteRetarget.cpp b/Source/MantleEditor/Private/MantleEmoteRetarget.cpp index 43bb8a5e..4c72028c 100644 --- a/Source/MantleEditor/Private/MantleEmoteRetarget.cpp +++ b/Source/MantleEditor/Private/MantleEmoteRetarget.cpp @@ -975,8 +975,24 @@ void FMantleEmoteRetarget::ReleaseRestHandsCopy(UObject* Copy) bool FMantleEmoteRetarget::RetargetAndSample(UAnimSequence* Sequence, const FString& SkeletonId, USkeletalMesh* SourceMesh, USkeletalMesh* TargetMesh, const FMantleAvatarContract& Contract, FMantleAnimClipData& OutClip, FString& OutError, FString* OutHandsNote) { - using namespace MantleEmoteRetargetPrivate; OutClip = FMantleAnimClipData(); + return RetargetAndUse(Sequence, SkeletonId, SourceMesh, TargetMesh, Contract, + [&Contract, &OutClip, Sequence](UAnimSequence& Retargeted, FString& OutUseError) + { + FString SampleError; + if (!FMantleAnimClipWriter::Sample(&Retargeted, Contract, OutClip, SampleError)) + { + OutUseError = FString::Printf(TEXT("the retargeted %s could not be read: %s"), *Sequence->GetName(), *SampleError); + return false; + } + return true; + }, OutError, OutHandsNote); +} + +bool FMantleEmoteRetarget::RetargetAndUse(UAnimSequence* Sequence, const FString& SkeletonId, USkeletalMesh* SourceMesh, USkeletalMesh* TargetMesh, + const FMantleAvatarContract& Contract, TFunctionRef Use, FString& OutError, FString* OutHandsNote) +{ + using namespace MantleEmoteRetargetPrivate; const TCHAR* const RetargeterPath = RetargeterPathFor(SkeletonId); if (!Sequence) { @@ -1045,17 +1061,7 @@ bool FMantleEmoteRetarget::RetargetAndSample(UAnimSequence* Sequence, const FStr ReleaseRestHandsCopy(Matched); }; const double Frame = Contract.EmoteFrameRate > 0.0f ? 1.0 / Contract.EmoteFrameRate : 1.0 / 30.0; - return RetargetThrough(Sequence, SourceMesh, TargetMesh, Matched, Frame, - [&Contract, &OutClip, Sequence](UAnimSequence& Retargeted, FString& OutUseError) - { - FString SampleError; - if (!FMantleAnimClipWriter::Sample(&Retargeted, Contract, OutClip, SampleError)) - { - OutUseError = FString::Printf(TEXT("the retargeted %s could not be read: %s"), *Sequence->GetName(), *SampleError); - return false; - } - return true; - }, OutError); + return RetargetThrough(Sequence, SourceMesh, TargetMesh, Matched, Frame, Use, OutError); } bool FMantleEmoteRetarget::RetargetThrough(UAnimSequence* Sequence, USkeletalMesh* SourceMesh, USkeletalMesh* TargetMesh, UObject* Retargeter, diff --git a/Source/MantleEditor/Private/MantleEmoteRetarget.h b/Source/MantleEditor/Private/MantleEmoteRetarget.h index 05c0cadc..4b2076b3 100644 --- a/Source/MantleEditor/Private/MantleEmoteRetarget.h +++ b/Source/MantleEditor/Private/MantleEmoteRetarget.h @@ -123,6 +123,14 @@ struct FMantleEmoteRetarget static bool RetargetAndSample(UAnimSequence* Sequence, const FString& SkeletonId, USkeletalMesh* SourceMesh, USkeletalMesh* TargetMesh, const FMantleAvatarContract& Contract, FMantleAnimClipData& OutClip, FString& OutError, FString* OutHandsNote = nullptr); + /** + * Everything RetargetAndSample does, but hands the retargeted copy to Use instead of sampling it as an emote (mantle #333: creator + * clips sample it over the UEFN mesh as a place clip). RetargetAndSample runs through it. + */ + static bool RetargetAndUse(UAnimSequence* Sequence, const FString& SkeletonId, USkeletalMesh* SourceMesh, USkeletalMesh* TargetMesh, + const FMantleAvatarContract& Contract, TFunctionRef Use, FString& OutError, + FString* OutHandsNote = nullptr); + /** * The retarget itself, through any retargeter: IK Rig's batch retarget of Sequence (played on SourceMesh) onto * TargetMesh through Retargeter into TransientFolder, checked to be one animation on TargetMesh's skeleton whose length diff --git a/Source/MantleEditor/Private/MantleItemClips.cpp b/Source/MantleEditor/Private/MantleItemClips.cpp new file mode 100644 index 00000000..70de3afc --- /dev/null +++ b/Source/MantleEditor/Private/MantleItemClips.cpp @@ -0,0 +1,171 @@ +// Copyright Joshua Eger. All Rights Reserved. +#include "MantleItemClips.h" + +#include "MantleAvatarContract.h" +#include "MantleBuilderPoint.h" +#include "MantleBuiltInMannequin.h" +#include "MantleCreatorClips.h" +#include "MantleEmoteRetarget.h" +#include "MantleHandAttach.h" +#include "MantlePlaceAssets.h" +#include "MantlePlaceValidator.h" +#include "MantleWeaponBuilderKind.h" +#include "MantleWeaponBuilderLogic.h" +#include "MantleWeaponSource.h" +#include "SMantleBuilderViewport.h" + +#include "Animation/AnimSequence.h" +#include "Animation/Skeleton.h" +#include "Engine/SkeletalMesh.h" +#include "Engine/StreamableRenderAsset.h" + +#define LOCTEXT_NAMESPACE "MantleItemClips" + +// Named, not anonymous: MantleEditor builds as a unity build. +namespace MantleItemClipsPrivate +{ + /** The slots in the order of FMantleCreatorClips::ItemSlotNames, and the source field behind each. */ + TSoftObjectPtr UMantleWeaponSource::* const Fields[] = { + &UMantleWeaponSource::ClipHold, &UMantleWeaponSource::ClipUse, &UMantleWeaponSource::ClipEquip, &UMantleWeaponSource::ClipPutAway }; +} + +TSharedRef FMantleItemClips::MakeModel() +{ + TSharedRef Model = MakeShared(); + Model->Conversion = EMantleClipConversion::RetargetToUefn; + const TPair Words[] = { + { LOCTEXT("Hold", "Hold"), LOCTEXT("HoldHint", "How it is carried. Only the upper body plays; the legs keep moving.") }, + { LOCTEXT("Use", "Use"), LOCTEXT("UseHint", "What using it looks like: eat, drink, click.") }, + { LOCTEXT("Equip", "Equip"), LOCTEXT("EquipHint", "Taking it out.") }, + { LOCTEXT("PutAway", "Put away"), LOCTEXT("PutAwayHint", "Putting it away.") }, + }; + const TConstArrayView Names = FMantleCreatorClips::ItemSlotNames(); + for (int32 Index = 0; Index < Names.Num() && Index < UE_ARRAY_COUNT(Words); ++Index) + { + FMantleClipSlotDef& Def = Model->Slots.AddDefaulted_GetRef(); + Def.Name = Names[Index]; + Def.Label = Words[Index].Key; + Def.Hint = Words[Index].Value; + } + if (const FMantleAvatarContract* Contract = FMantleAvatarContract::Get()) + { + Model->PreviewMesh = FMantleBuiltInMannequin::UEFNMannequin(*Contract); + } + return Model; +} + +void FMantleItemClips::ReadSource(FMantleClipSlotsModel& Model, const UMantleWeaponSource& Source) +{ + Model.Clips.Reset(); + for (int32 Index = 0; Index < Model.Slots.Num() && Index < UE_ARRAY_COUNT(MantleItemClipsPrivate::Fields); ++Index) + { + const TSoftObjectPtr& Clip = Source.*MantleItemClipsPrivate::Fields[Index]; + if (!Clip.IsNull()) + { + Model.Clips.Add(Model.Slots[Index].Name, { Clip.ToSoftObjectPath() }); + } + } +} + +void FMantleItemClips::WriteSource(const FMantleClipSlotsModel& Model, UMantleWeaponSource& Source) +{ + for (int32 Index = 0; Index < Model.Slots.Num() && Index < UE_ARRAY_COUNT(MantleItemClipsPrivate::Fields); ++Index) + { + const TArray* Held = Model.Clips.Find(Model.Slots[Index].Name); + Source.*MantleItemClipsPrivate::Fields[Index] = TSoftObjectPtr(Held && Held->Num() > 0 ? (*Held)[0] : FSoftObjectPath()); + } +} + +FString FMantleItemClips::Problems(const FMantleClipSlotsModel& Model) +{ + TArray Lines; + const FMantleAvatarContract* Contract = FMantleAvatarContract::Get(); + const FMantlePlaceAssetLimits Limits = FMantlePlaceAssetLimits::FromContract(); + for (const FMantleClipSlotDef& Def : Model.Slots) + { + if (Model.NumClips(Def.Name) == 0) + { + continue; + } + const UAnimSequence* Sequence = Model.Load(Def.Name, 0); + if (!Sequence) + { + Lines.Add(FString::Printf(TEXT("%s: the animation could not be loaded. Pick it again."), *Def.Label.ToString())); + continue; + } + const USkeleton* Skeleton = Sequence->GetSkeleton(); + if (Contract && (!Skeleton || FMantleEmoteRetarget::IdentifySkeleton(Skeleton, *Contract).IsEmpty())) + { + Lines.Add(FString::Printf(TEXT("%s: %s is not made for the UEFN Mannequin, a MetaHuman, the UE5 Mannequin or the UE4 Mannequin. Retarget it onto one of those and pick the result."), + *Def.Label.ToString(), *Sequence->GetName())); + continue; + } + // Another mannequin's clip is retargeted from a body of its own skeleton, so the project needs one. + if (Contract && FMantleEmoteRetarget::IdentifySkeleton(Skeleton, *Contract) != Contract->EmoteSkeleton + && !FMantleEmoteRetarget::ChooseSourceMesh(const_cast(Sequence), nullptr)) + { + Lines.Add(FString::Printf(TEXT("%s: no skeletal mesh in this project uses %s's skeleton, so it cannot be retargeted. Give the skeleton a preview mesh."), + *Def.Label.ToString(), *Sequence->GetName())); + continue; + } + TArray Issues; + FMantleCreatorClips::CheckClip(Sequence->GetName(), Sequence, nullptr, Limits, Issues); + for (const FMantleValidationIssue& Issue : Issues) + { + if (Issue.Severity == EMantleIssueSeverity::Error) + { + Lines.Add(FString::Printf(TEXT("%s: %s %s"), *Def.Label.ToString(), *Issue.Problem, *Issue.Remedy)); + } + } + } + return FString::Join(Lines, TEXT("\n")); +} + +UAnimSequence* FMantleItemClips::MakePreview(UAnimSequence* Clip, USkeletalMesh*& InOutBody, TStrongObjectPtr& Kept, FString& OutError) +{ + return FMantleCreatorClips::MakePreview(Clip, InOutBody, Kept, OutError); +} + +const FMantleBuilderPoint* FMantleItemClips::PlacedGrip(const TArray& Points) +{ + const int32 Last = Points.FindLastByPredicate([](const FMantleBuilderPoint& Point) { return Point.Role == FName(TEXT("Grip")); }); + return Last != INDEX_NONE && Points[Last].Source == EMantleBuilderPointSource::Creator ? &Points[Last] : nullptr; +} + +FMantlePreviewHeldItem FMantleItemClips::HeldItem(const UMantleWeaponSource& Source, UObject* Model, const USkeletalMesh* Body) +{ + FMantlePreviewHeldItem Held; + UStreamableRenderAsset* Mesh = Cast(Model); + if (!Mesh || !Body) + { + return Held; + } + // The same fit and grip as the export and the game: the creator's, or else the builder's guess, which is the game's default. + FMantleWeaponBuilderKind Kind(MantleWeaponBuilderLogic::ToFitHold(Source.Hold)); + Kind.SetFlipRotation(Source.FlipRotation); + Kind.SetScaleOverride(Source.bScaleOverridden ? Source.FitScale : 0.f); + const TArray Guesses = Kind.GuessPoints(Model); + const FName GripRole(TEXT("Grip")); + const FMantleBuilderPoint* Grip = PlacedGrip(Source.Points); + if (!Grip) + { + Grip = Guesses.FindByPredicate([&GripRole](const FMantleBuilderPoint& Point) { return Point.Role == GripRole; }); + } + FTransform Parent = FTransform::Identity; + if (!Grip || (!Grip->Parent.IsNone() && !MantleBuilderViewportMath::ResolveParent(Model, Grip->Parent, Parent))) + { + return Held; + } + const FTransform InMesh = Grip->Transform * Parent; + const FTransform MeshToWeapon = Kind.GetLastFit().MeshToWeapon; + // The grip as the exported document has it: in the fitted item's space, unscaled. + const FTransform GripInItem(MeshToWeapon.GetRotation() * InMesh.GetRotation(), MeshToWeapon.TransformPosition(InMesh.GetLocation())); + const MantleHandAttach::FPalm Palm = MantleHandAttach::FindPalm(*Body, /*bRightHand*/ false); + Held.Mesh = Mesh; + Held.Socket = Palm.Where; + // The creator's model fitted, then the grip in the palm, then the palm on the attach point. + Held.Local = MeshToWeapon * GripInItem.Inverse() * Palm.Offset; + return Held; +} + +#undef LOCTEXT_NAMESPACE diff --git a/Source/MantleEditor/Private/MantleItemClips.h b/Source/MantleEditor/Private/MantleItemClips.h new file mode 100644 index 00000000..7380fd6c --- /dev/null +++ b/Source/MantleEditor/Private/MantleItemClips.h @@ -0,0 +1,50 @@ +// Copyright Joshua Eger. All Rights Reserved. +#pragma once + +#include "CoreMinimal.h" +#include "SMantleClipSlots.h" +#include "UObject/StrongObjectPtr.h" + +class UAnimSequence; +struct FMantleBuilderPoint; +class UMantleWeaponSource; +class USkeletalMesh; + +/** + * Build an item's Animations screen (mantle #333 P2): the shared Clips control's four slots (Hold, Use, Equip, Put away) bound to the + * source's clip fields, what is wrong with a picked clip, and the preview of a clip as Mantle will play it. + */ +struct FMantleItemClips +{ + /** The four slots, each optional and holding one clip, retargeted to Mantle's character. */ + static TSharedRef MakeModel(); + + /** The model's clips from the source's fields. Does not call OnChanged. */ + static void ReadSource(FMantleClipSlotsModel& Model, const UMantleWeaponSource& Source); + + /** The source's fields from the model's clips. */ + static void WriteSource(const FMantleClipSlotsModel& Model, UMantleWeaponSource& Source); + + /** Why the picked clips cannot be published (a skeleton Mantle cannot retarget, a clip over the limits), one sentence per line; empty when fine. */ + static FString Problems(const FMantleClipSlotsModel& Model); + + /** + * Clip as it plays on every player: a UEFN clip on a UEFN body as it is, a MetaHuman, UE5 or UE4 Mannequin clip retargeted onto the + * built-in UEFN mannequin (the copy lives in Kept until the next preview). InOutBody becomes the body it plays on. Null with OutError, + * a sentence for the creator, when it cannot be shown. Game thread. + */ + static UAnimSequence* MakePreview(UAnimSequence* Clip, USkeletalMesh*& InOutBody, TStrongObjectPtr& Kept, FString& OutError); + + /** + * The grip the creator moved themself, the last of the name; null while it is the builder's guess. A consumable's and a usable item's + * document has a grip only then: without one the game holds the item at its default (MantleHandAttach::DefaultGripInMesh). + */ + static const FMantleBuilderPoint* PlacedGrip(const TArray& Points); + + /** + * The creator's model as Body holds it in the preview: its grip (placed, or the default) in the palm of the left hand, placed as the game places it + * (MantleHandAttach::FindPalm), at the fitted size and direction the export bakes in. Holds nothing without a model, a body or a grip point. + * The model must stay alive while it is held. Game thread. + */ + static FMantlePreviewHeldItem HeldItem(const UMantleWeaponSource& Source, UObject* Model, const USkeletalMesh* Body); +}; diff --git a/Source/MantleEditor/Private/MantleLibraryPanel.cpp b/Source/MantleEditor/Private/MantleLibraryPanel.cpp index 04de5251..830d1404 100644 --- a/Source/MantleEditor/Private/MantleLibraryPanel.cpp +++ b/Source/MantleEditor/Private/MantleLibraryPanel.cpp @@ -330,8 +330,18 @@ FString FMantleLibraryStorage::TakenDownNote() return TEXT("This item was taken down by a Mantle moderator after a complaint, so a place can no longer use it."); } +int32 FMantleLibraryStorage::CountStoredItems(const TArray& Storage) +{ + int32 Count = 0; + for (const FMantleStorageSetting& Entry : Storage) + { + Count += !Entry.Kind.IsEmpty() && !Entry.Kind.Equals(FMantleStorage::KindScript, ESearchCase::CaseSensitive) ? 1 : 0; + } + return Count; +} + FMantleLibraryAddPlan FMantleLibraryStorage::PlanAdd(const TArray& Entries, const FString& ItemId, - const FString& ItemName, const int32 Version, const FString& Status) + const FString& ItemName, const int32 Version, const FString& Status, const FString& Kind, const int32 CountedStored) { FMantleLibraryAddPlan Plan; if (!FMantlePlaceLimits::IsLibraryItemId(ItemId)) @@ -390,6 +400,14 @@ FMantleLibraryAddPlan FMantleLibraryStorage::PlanAdd(const TArray= FMantlePlaceLimits::MaxStoredItems) + { + Plan.Result = EMantleLibraryAdd::Full; + Plan.Message = FString::Printf(TEXT("This place already stores %d vehicles, weapons and wheels, the most it can. Remove one first."), + FMantlePlaceLimits::MaxStoredItems); + return Plan; + } + FMantleStorageEntry Entry; Entry.Name = MakeUniqueName(SanitizeName(ItemName), Entries); Entry.Item = ItemId; @@ -1510,7 +1528,9 @@ bool SMantleLibraryPanel::ApplyAdd(const FMantleLibraryCard& Card, FString& OutM } TArray Entries; AMantlePlaceSettingsActor::ApplyStorageTo(World, Entries); - const FMantleLibraryAddPlan Plan = FMantleLibraryStorage::PlanAdd(Entries, Card.Id, Card.Name, Card.LatestVersion, Card.Status); + const AMantlePlaceSettingsActor* CurrentSettings = AMantlePlaceSettingsActor::Find(World); + const FMantleLibraryAddPlan Plan = FMantleLibraryStorage::PlanAdd(Entries, Card.Id, Card.Name, Card.LatestVersion, Card.Status, Card.Kind, + CurrentSettings ? FMantleLibraryStorage::CountStoredItems(CurrentSettings->Storage) : 0); if (Plan.Result != EMantleLibraryAdd::Added) { OutMessage = Plan.Message; @@ -1658,8 +1678,8 @@ TSharedRef SMantleLibraryPanel::MakeStorageSection() .Font(FAppStyle::GetFontStyle("NormalFontBold")) .Text_Lambda([this] { - return FText::Format(LOCTEXT("StorageHeading", "This place's storage ({0} of {1})"), - FText::AsNumber(StorageSnapshot.Num()), FText::AsNumber(FMantlePlaceLimits::MaxStorageEntries)); + return FText::Format(LOCTEXT("StorageHeadingCounted", "This place's storage: {0} items ({1} of {2} vehicles, weapons and wheels)"), + FText::AsNumber(StorageSnapshot.Num()), FText::AsNumber(StoredItemsSnapshot), FText::AsNumber(FMantlePlaceLimits::MaxStoredItems)); }) ] + SHorizontalBox::Slot().AutoWidth() @@ -1710,8 +1730,10 @@ void SMantleLibraryPanel::RefreshStorageSnapshot() } StorageSnapshot.Reset(); AvatarStorageSnapshot.Reset(); + StoredItemsSnapshot = 0; if (Settings) { + StoredItemsSnapshot = FMantleLibraryStorage::CountStoredItems(Settings->Storage); for (const FMantleStorageSetting& Setting : Settings->Storage) { FMantleStorageEntry Stored; diff --git a/Source/MantleEditor/Private/MantleLibraryPanel.h b/Source/MantleEditor/Private/MantleLibraryPanel.h index 3baac5c1..676e5010 100644 --- a/Source/MantleEditor/Private/MantleLibraryPanel.h +++ b/Source/MantleEditor/Private/MantleLibraryPanel.h @@ -70,10 +70,17 @@ struct FMantleLibraryStorage * Whether {sanitized unique name of ItemName, ItemId, Version} may be appended to Entries. Refuses (and says why): * a bad item id or a version below 1; an item that is already stored, at any version; an item whose Status a place may * not newly add (IsUsableStatus: only an active item is added); a full place - * (the schema's cap); and anything FMantleStorage::CheckEntries would report for the entries with it added. + * (the schema's cap on all entries, or, for an item whose Kind is known and not a script package, CountedStored already at + * FMantlePlaceLimits::MaxStoredItems); and anything FMantleStorage::CheckEntries would report for the entries with it added. */ static FMantleLibraryAddPlan PlanAdd(const TArray& Entries, const FString& ItemId, const FString& ItemName, int32 Version, - const FString& Status); + const FString& Status, const FString& Kind = FString(), int32 CountedStored = 0); + + /** + * How many of the level's storage entries count toward FMantlePlaceLimits::MaxStoredItems: vehicles, weapons and wheels, not + * script packages (#475). An entry typed in by hand has no kind yet and is not counted here; publishing counts it. + */ + static int32 CountStoredItems(const TArray& Storage); /** The index of the entry that stores ItemId (compared case-sensitively), or INDEX_NONE. */ static int32 FindItem(const TArray& Entries, const FString& ItemId); @@ -272,6 +279,8 @@ class SMantleLibraryPanel : public SCompoundWidget /** The level's storage as last read, and its signature: the timer rebuilds what shows it when it changes. */ TArray StorageSnapshot; + /** FMantleLibraryStorage::CountStoredItems of the level's storage, taken with StorageSnapshot. */ + int32 StoredItemsSnapshot = 0; TArray AvatarStorageSnapshot; FString StorageSignature; bool bStorageHasSettings = false; diff --git a/Source/MantleEditor/Private/MantlePlaceAssetConverter.cpp b/Source/MantleEditor/Private/MantlePlaceAssetConverter.cpp index 7abc12b6..450ec1de 100644 --- a/Source/MantleEditor/Private/MantlePlaceAssetConverter.cpp +++ b/Source/MantleEditor/Private/MantlePlaceAssetConverter.cpp @@ -1,6 +1,8 @@ // Copyright Joshua Eger. All Rights Reserved. #include "MantlePlaceAssetConverter.h" #include "MantleAnimClipWriter.h" +#include "MantleCreatorClips.h" +#include "MantleAnimPack.h" #include "MantleCustomAvatar.h" #include "MantleCosmeticExport.h" #include "MantleHeightfieldReader.h" @@ -1332,6 +1334,11 @@ const FMantleConvertedCustomAvatar* FMantlePlaceAssetSet::FindCustomAvatar(const return CustomAvatars.FindByPredicate([&Key](const FMantleConvertedCustomAvatar& Avatar) { return Avatar.Key == Key; }); } +const FMantleConvertedAnimPack* FMantlePlaceAssetSet::FindAnimPack(const FString& Key) const +{ + return AnimPacks.FindByPredicate([&Key](const FMantleConvertedAnimPack& Pack) { return Pack.Key == Key; }); +} + void FMantlePlaceAssetSet::RecordUpload(const FString& Key, const FString& Id, const FString& Hash, int64 Bytes) { FMantlePlaceUploadedRef& Ref = Uploaded.FindOrAdd(Key); @@ -1538,6 +1545,28 @@ bool FMantlePlaceAssetSet::CustomAvatarBytes(const FMantleConvertedCustomAvatar& return true; } +bool FMantlePlaceAssetSet::AnimPackBytes(const FMantleConvertedAnimPack& Pack, TArray& OutBytes, FString& OutError) const +{ + TArray Entries; + for (const FMantleConvertedAnimPack::FEntry& Source : Pack.Entries) + { + const FMantlePlaceUploadedRef* Ref = Uploaded.Find(Source.ClipKey); + if (!Ref || Ref->Id.IsEmpty()) + { + OutError = FString::Printf(TEXT("Animation pack '%s' was not uploaded because its clip '%s' could not be."), *Pack.Name, *Source.Name); + return false; + } + FMantleAnimPack::FEntry& Out = Entries.AddDefaulted_GetRef(); + Out.Name = Source.Name; + Out.AssetId = Ref->Id; + Out.Skeleton = Source.Skeleton; + } + const FTCHARToUTF8 Utf8(*FMantleAnimPack::WriteDocument(Entries)); + OutBytes.SetNumUninitialized(Utf8.Length()); + FMemory::Memcpy(OutBytes.GetData(), Utf8.Get(), Utf8.Length()); + return true; +} + bool FMantlePlaceAssetSet::WheelBytes(const FMantleConvertedWheel& Wheel, TArray& OutBytes, FString& OutError) const { const FMantlePlaceUploadedRef* MeshRef = Uploaded.Find(Wheel.MeshKey); @@ -1686,6 +1715,18 @@ bool FMantlePlaceAssetSet::WeaponBytes(const FMantleConvertedWeapon& Weapon, TAr } (*SoundsBlock)->SetStringField(Sound.Key, SoundRef->Id); } + // mantle #333: the item's own clips by uploaded id. + for (const TPair& Slot : Weapon.ClipKeys) + { + const TSharedPtr* ClipsBlock = nullptr; + const FMantlePlaceUploadedRef* ClipRef = Uploaded.Find(Slot.Value); + if (!Root->TryGetObjectField(TEXT("clips"), ClipsBlock) || !ClipsBlock || !ClipRef || ClipRef->Id.IsEmpty()) + { + OutError = FString::Printf(TEXT("Weapon '%s' was not uploaded because its %s clip could not be."), *Weapon.Name, *Slot.Key); + return false; + } + (*ClipsBlock)->SetStringField(Slot.Key, ClipRef->Id); + } FString Json; const TSharedRef>> Writer = TJsonWriterFactory>::Create(&Json); FJsonSerializer::Serialize(Root.ToSharedRef(), Writer); @@ -1867,6 +1908,23 @@ bool FMantlePlaceAssetSet::TakeUploads(EMantlePlaceUploadStage Stage, TArray& Clips, FMantlePlaceAssetSet& Out, + TArray>& OutSlotKeys) +{ + using namespace MantlePlaceAssetConverterPrivate; + const FMantlePlaceAssetLimits ClipLimits = FMantlePlaceAssetLimits::FromContract(); + TArray Distinct; + TArray Made; + TArray Creator; + Creator.Reserve(Clips.Num()); + TSet Counted; + bool bRefused = false; + for (const TCHAR* SlotName : FMantleCreatorClips::ItemSlotNames()) + { + UAnimSequence* const* Found = Clips.Find(FName(SlotName)); + if (!Found || !*Found) + { + continue; + } + UAnimSequence* Sequence = *Found; + const FString ClipKey = FString::Printf(TEXT("itemclip:%s"), *Sequence->GetPathName()); + OutSlotKeys.Emplace(SlotName, ClipKey); + if (Made.ContainsByPredicate([&ClipKey](const FMantleConvertedClip& Each) { return Each.Key == ClipKey; }) || Counted.Contains(ClipKey)) + { + continue; + } + if (const FMantleConvertedClip* Earlier = Out.FindClip(ClipKey)) + { + // Already converted for another weapon: it still counts toward this item's total. + Counted.Add(ClipKey); + Creator.AddDefaulted_GetRef().Bytes = Earlier->Bytes; + Distinct.Add(&Creator.Last()); + continue; + } + FMantleCreatorClip& Clip = Creator.AddDefaulted_GetRef(); + FString ClipError; + TArray Checked; + if (!FMantleCreatorClips::ConvertToUefn(Sequence, Clip, ClipError)) + { + Out.Issues.Add(ErrorIssue(FString::Printf(TEXT("The %s clip '%s' of weapon '%s' can't be used: %s"), SlotName, *Sequence->GetName(), *WeaponName, *ClipError), + TEXT("Pick an animation made on the UEFN Mannequin, a MetaHuman, the UE5 Mannequin or the UE4 Mannequin."))); + bRefused = true; + continue; + } + if (!FMantleCreatorClips::CheckClip(Sequence->GetName(), Sequence, &Clip, ClipLimits, Checked)) + { + bRefused = true; + } + for (FMantleValidationIssue& Issue : Checked) + { + Out.Issues.Add(MoveTemp(Issue)); + } + Distinct.Add(&Clip); + FMantleConvertedClip& Upload = Made.AddDefaulted_GetRef(); + Upload.Key = ClipKey; + Upload.Name = FString::Printf(TEXT("%s %s"), *WeaponName, SlotName); + Upload.Path = Sequence->GetPathName(); + Upload.Frames = Clip.Frames; + Upload.Tracks = Clip.Tracks; + Upload.SkeletonHash = Clip.SkeletonHash; + Upload.Bytes = Clip.Bytes; + Upload.Hash = Clip.Hash; + UE_LOG(LogMantle, Log, TEXT("MANTLE_ITEM_CLIP %s slot=%s frames=%d tracks=%d bytes=%d skeleton=%s. %s"), *WeaponName, SlotName, Clip.Frames, Clip.Tracks, + Clip.Bytes.Num(), *Clip.SkeletonHash, *Clip.Note); + } + TArray TotalIssues; + if (!FMantleCreatorClips::CheckItemTotal(Distinct, TotalIssues)) + { + bRefused = true; + } + for (FMantleValidationIssue& Issue : TotalIssues) + { + Issue.Problem = FString::Printf(TEXT("Weapon '%s': %s"), *WeaponName, *Issue.Problem); + Out.Issues.Add(MoveTemp(Issue)); + } + if (bRefused) + { + return false; + } + for (FMantleConvertedClip& Upload : Made) + { + Out.Clips.Add(MoveTemp(Upload)); + } + return true; +} + bool FMantlePlaceAssetConverter::ConvertWeapon(const FMantleGatheredWeapon& Weapon, FMantlePlaceAssetSet& Out) { using namespace MantlePlaceAssetConverterPrivate; @@ -3696,7 +3842,7 @@ bool FMantlePlaceAssetConverter::ConvertWeapon(const FMantleGatheredWeapon& Weap if (!Mesh || !FFileHelper::LoadFileToString(Text, *AMantleWeaponSpawnPoint::BuiltDocumentFile(Weapon.Name))) { Out.Issues.Add(ErrorIssue(FString::Printf(TEXT("The weapon '%s' could not be loaded."), *Weapon.Name), - TEXT("Open Tools > Mantle > Build a weapon and press Create weapon again, then publish again."))); + TEXT("Open Tools > Mantle > Build an item and press Create item again, then publish again."))); return false; } FMantleBuiltWeaponParts Parts; @@ -3704,7 +3850,7 @@ bool FMantlePlaceAssetConverter::ConvertWeapon(const FMantleGatheredWeapon& Weap if (!Problem.IsEmpty()) { Out.Issues.Add(ErrorIssue(FString::Printf(TEXT("The weapon '%s' %s."), *Weapon.Name, *Problem), - TEXT("Open Tools > Mantle > Build a weapon and press Create weapon again, then publish again."))); + TEXT("Open Tools > Mantle > Build an item and press Create item again, then publish again."))); return false; } FMantleConvertedWeapon Converted; @@ -3755,7 +3901,12 @@ bool FMantlePlaceAssetConverter::ConvertWeapon(const FMantleGatheredWeapon& Weap ReadPart(Parts.Projectile, Converted.Projectile); Converted.FireSoundKey = Parts.Fire ? FMantlePlaceAssets::SoundKey(Parts.Fire) : FString(); Converted.FireSuppressedSoundKey = Parts.FireSuppressed ? FMantlePlaceAssets::SoundKey(Parts.FireSuppressed) : FString(); - // #124: its library picture, from the creator's choice (the weapon builder's Thumbnail step) or Automatic: the model in the catalog's thumbnail scene. A texture + // mantle #333: an item's own clips, uploaded as animclips before the weapon. + if (!ConvertItemClips(Weapon.Name, Parts.Clips, Out, Converted.ClipKeys)) + { + return false; + } + // #124: its library picture, from the creator's choice (the item builder's Thumbnail step) or Automatic: the model in the catalog's thumbnail scene. A texture // upload beside the weapon's, like a vehicle's, named on its library item. A weapon that cannot get one (no renderer) publishes without, as before. { FMantleThumbnailChoice Choice; @@ -3776,19 +3927,19 @@ bool FMantlePlaceAssetConverter::ConvertWeapon(const FMantleGatheredWeapon& Weap Converted.ThumbnailKey = Out.AddTexture(MoveTemp(Texture)); if (!Picture.Warning.IsEmpty()) { - Out.Issues.Add(WarningIssue(FString::Printf(TEXT("The weapon '%s' thumbnail: %s"), *Weapon.Name, *Picture.Warning), TEXT("Use a bigger picture in the weapon builder's Thumbnail step."))); + Out.Issues.Add(WarningIssue(FString::Printf(TEXT("The weapon '%s' thumbnail: %s"), *Weapon.Name, *Picture.Warning), TEXT("Use a bigger picture in the item builder's Thumbnail step."))); } } else if (Choice.Mode == EMantleThumbnailMode::Custom) { Out.Issues.Add(ErrorIssue(FString::Printf(TEXT("The weapon '%s' thumbnail's custom image could not be used: %s"), *Weapon.Name, *Picture.Error), - TEXT("Open Tools > Mantle > Build a weapon, choose another picture in the Thumbnail step, press Create weapon, then publish again."))); + TEXT("Open Tools > Mantle > Build an item, choose another picture in the Thumbnail step, press Create item, then publish again."))); return false; } else if (FMantleCosmeticThumbnail::CanCapture()) { Out.Issues.Add(WarningIssue(FString::Printf(TEXT("The weapon '%s' thumbnail could not be taken (%s), so its library card has no picture."), *Weapon.Name, *Picture.Error), - TEXT("Publish again; if it keeps happening, choose a Custom image in the weapon builder's Thumbnail step."))); + TEXT("Publish again; if it keeps happening, choose a Custom image in the item builder's Thumbnail step."))); } } Out.Weapons.Add(MoveTemp(Converted)); diff --git a/Source/MantleEditor/Private/MantlePlaceAssets.cpp b/Source/MantleEditor/Private/MantlePlaceAssets.cpp index ddb68de1..c202dd67 100644 --- a/Source/MantleEditor/Private/MantlePlaceAssets.cpp +++ b/Source/MantleEditor/Private/MantlePlaceAssets.cpp @@ -1,5 +1,6 @@ // Copyright Joshua Eger. All Rights Reserved. #include "MantlePlaceAssets.h" +#include "MantleCreatorClips.h" #include "MantlePlacePrefabs.h" #include "MantleWaterBodyExport.h" #include "MantleActorDecompose.h" @@ -3513,6 +3514,26 @@ FString FMantlePlaceAssets::WeaponDocumentProblem(const FString& WeaponName, con *Into = Wave; } } + // mantle #333: an item's own clips, each copied beside the weapon under the local name the file writes; a slot that already names an + // uploaded id (a clip from a pack the creator owns) has nothing to load. + const TSharedPtr* ClipsBlock = nullptr; + if (Root->TryGetObjectField(TEXT("clips"), ClipsBlock) && ClipsBlock) + { + for (const TCHAR* SlotName : FMantleCreatorClips::ItemSlotNames()) + { + FString LocalName; + if (!(*ClipsBlock)->TryGetStringField(SlotName, LocalName) || LocalName.StartsWith(TEXT("ast_"))) + { + continue; + } + UAnimSequence* Sequence = Cast(Load(LocalName)); + if (!Sequence) + { + return FString::Printf(TEXT("has a %s clip '%s' that is missing from its folder"), SlotName, *LocalName); + } + Parts.Clips.Add(FName(SlotName), Sequence); + } + } if (OutParts) { *OutParts = MoveTemp(Parts); @@ -6464,7 +6485,7 @@ void FMantlePlaceAssets::CheckLevel(UWorld* World, TArray Mantle > Build a weapon, press Create weapon again to remake it, then check the place again.") }); + TEXT("Open Tools > Mantle > Build an item, press Create item again to remake it, then check the place again.") }); } } } diff --git a/Source/MantleEditor/Private/MantlePlaceExporter.cpp b/Source/MantleEditor/Private/MantlePlaceExporter.cpp index e61460bd..9020157b 100644 --- a/Source/MantleEditor/Private/MantlePlaceExporter.cpp +++ b/Source/MantleEditor/Private/MantlePlaceExporter.cpp @@ -1554,7 +1554,7 @@ namespace { Errors.Add(FMantleParseError{ Path + TEXT("/properties/weapon"), - FString::Printf(TEXT("'%s' has no weapon; pick one in its Weapon list (make one first with Tools > Mantle > Build a weapon)"), *Entity.Name) }); + FString::Printf(TEXT("'%s' has no weapon; pick one in its Weapon list (make one first with Tools > Mantle > Build an item)"), *Entity.Name) }); } Entity.Props.Set(MoveTemp(Props)); break; diff --git a/Source/MantleEditor/Private/MantlePlacePublishSession.cpp b/Source/MantleEditor/Private/MantlePlacePublishSession.cpp index ae093c62..b6a1003b 100644 --- a/Source/MantleEditor/Private/MantlePlacePublishSession.cpp +++ b/Source/MantleEditor/Private/MantlePlacePublishSession.cpp @@ -1,5 +1,6 @@ // Copyright Joshua Eger. All Rights Reserved. #include "MantlePlacePublishSession.h" +#include "MantleAnimPack.h" #include "MantleCustomAvatar.h" #include "MantlePlaceThumbnail.h" #include "MantleMinimap.h" @@ -1797,6 +1798,23 @@ bool FMantlePlacePublishSession::PrepareCustomAvatar(const FString& Key, FMantle return true; } +bool FMantlePlacePublishSession::PrepareAnimPack(const FString& Key, FMantleQueuedUpload& Item, FString& OutWhyNot) +{ + const FMantleConvertedAnimPack* Pack = Set.FindAnimPack(Key); + if (!Pack) + { + OutWhyNot = FString::Printf(TEXT("Animation pack '%s' was not prepared."), *Item.Name); + return false; + } + // Its document names its clips' ids, which the earlier stage has just recorded. + if (!Set.AnimPackBytes(*Pack, Item.Bytes, OutWhyNot)) + { + return false; + } + Item.Hash = FMantleSha256::AssetHash(Item.Bytes); + return true; +} + void FMantlePlacePublishSession::StartUploads() { // A credit Mantle would refuse is said now, before anything is sent, rather than after the uploads. @@ -1956,6 +1974,21 @@ void FMantlePlacePublishSession::StartUploads() return This.IsValid() && This->PrepareCustomAvatar(Key, Out, OutWhyNot); }; } + // Animation packs (#333 G10), after them: their documents name their clips' ids. + for (const FMantleConvertedAnimPack& Pack : Set.AnimPacks) + { + FMantleQueuedUpload& Item = Items.AddDefaulted_GetRef(); + Item.Key = Pack.Key; + Item.Stage = static_cast(EMantlePlaceUploadStage::AnimPack); + Item.Name = Pack.Name; + Item.Options.Kind = FMantleAnimPack::DocumentKind(); + const FString Key = Pack.Key; + Item.Prepare = [WeakThis, Key](FMantleQueuedUpload& Out, FString& OutWhyNot) + { + const TSharedPtr This = WeakThis.Pin(); + return This.IsValid() && This->PrepareAnimPack(Key, Out, OutWhyNot); + }; + } if (Items.Num() == 0) { EnterScriptsOrLibrary(); @@ -2275,7 +2308,7 @@ void FMantlePlacePublishSession::AfterExport(FString Json) AddLog(Note); } Result.PlaceJson = MoveTemp(Json); - if (Set.Vehicles.Num() > 0 || Set.Weapons.Num() > 0 || Set.Wheels.Num() > 0 || Set.CustomAvatars.Num() > 0 || Packages.Num() > 0) + if (Set.Vehicles.Num() > 0 || Set.Weapons.Num() > 0 || Set.Wheels.Num() > 0 || Set.CustomAvatars.Num() > 0 || Set.AnimPacks.Num() > 0 || Packages.Num() > 0) { if (bGoLive) { @@ -2286,7 +2319,7 @@ void FMantlePlacePublishSession::AfterExport(FString Json) Tick(); return; } - if (Set.Vehicles.Num() > 0 || Set.Weapons.Num() > 0 || Set.Wheels.Num() > 0 || Set.CustomAvatars.Num() > 0) + if (Set.Vehicles.Num() > 0 || Set.Weapons.Num() > 0 || Set.Wheels.Num() > 0 || Set.CustomAvatars.Num() > 0 || Set.AnimPacks.Num() > 0) { AddLog(TEXT("Vehicles and weapons are uploaded and saved in the draft by their upload id; they become library items when you publish")); } @@ -2581,6 +2614,28 @@ void FMantlePlacePublishSession::TickLibrary() Job.ThumbnailId = AvatarPicture->Id; } } + // Animation packs (#333 G10): library only, never named by a place file; no picture of their own. + for (const FMantleConvertedAnimPack& Pack : Set.AnimPacks) + { + const FMantlePlaceUploadedRef* Uploaded = Set.Uploaded.Find(Pack.Key); + if (!Uploaded || !bLibraryOnly) + { + continue; + } + const FString SourcePath = MantlePlacePublishSessionPrivate::ConvertedObjectPath(Pack.Path, Pack.Key); + if (FLibraryJob* Same = FindJobByAsset(Uploaded->Id)) + { + Same->Paths.AddUnique(SourcePath); + continue; + } + FLibraryJob& Job = LibraryJobs.AddDefaulted_GetRef(); + Job.bAnimPack = true; + Job.Name = Pack.Name; + Job.Path = SourcePath; + Job.Paths.Add(SourcePath); + Job.AssetId = Uploaded->Id; + Job.Provenance = FMantleProvenance::Make(SourcePath, FString()); + } // #838: each script package, once all its files are on Mantle; remembered by its folder like a vehicle by its asset. PackageRefs.Reset(); for (int32 PackageIndex = 0; PackageIndex < Packages.Num(); ++PackageIndex) diff --git a/Source/MantleEditor/Private/MantlePlaceValidator.cpp b/Source/MantleEditor/Private/MantlePlaceValidator.cpp index 083e776f..6ab3d53a 100644 --- a/Source/MantleEditor/Private/MantlePlaceValidator.cpp +++ b/Source/MantleEditor/Private/MantlePlaceValidator.cpp @@ -15,6 +15,7 @@ #include "MantlePlaceExporter.h" #include "MantlePlaceLimits.h" #include "MantlePlaceParser.h" +#include "MantleLibraryPanel.h" #include "MantlePlaceSettingsActor.h" #include "MantlePlaceStorage.h" #include "MantlePlaceWorldPartition.h" @@ -842,7 +843,7 @@ namespace EMantleIssueSeverity::Error, LabelOf(Actor), FString::Printf(TEXT("uses the weapon '%s', whose files are not in your project's MantleWeapons folder."), *Spawn->Weapon), - TEXT("Pick a weapon from its Weapon list, or make the weapon again with Tools > Mantle > Build a weapon.") }); + TEXT("Pick a weapon from its Weapon list, or make the weapon again with Tools > Mantle > Build an item.") }); } } else if (!FMantleVehicleConverter::IsUploadedId(Props.Weapon)) @@ -851,7 +852,7 @@ namespace EMantleIssueSeverity::Error, LabelOf(Actor), TEXT("has no weapon to leave."), - TEXT("Pick one in its Weapon list in the Details panel. Make a weapon first with Tools > Mantle > Build a weapon.") }); + TEXT("Pick one in its Weapon list in the Details panel. Make a weapon first with Tools > Mantle > Build an item.") }); } } @@ -2492,7 +2493,8 @@ FMantleValidationResult FMantlePlaceValidator::Validate(UWorld* World) CheckPlaceUIDocuments(World, Result); // #614 stage 4: the storage entries in Mantle Place Settings, by the schema's rules (the parser's and the - // exporter's): at most 32, unique letter-first names, itm_u item ids, versions from 1. + // exporter's): the most entries, unique letter-first names, itm_u item ids, versions from 1; and at most + // MaxStoredItems of them vehicles, weapons and wheels, where the kind is known. if (const AMantlePlaceSettingsActor* PlaceSettings = AMantlePlaceSettingsActor::Find(World)) { TArray StorageEntries; @@ -2505,6 +2507,15 @@ FMantleValidationResult FMantlePlaceValidator::Validate(UWorld* World) FString::Printf(TEXT("has a storage problem at %s: %s."), *Problem.Path, *Problem.Message), TEXT("Fix it under Storage in Mantle Place Settings.") }); } + const int32 Counted = FMantleLibraryStorage::CountStoredItems(PlaceSettings->Storage); + if (Counted > FMantlePlaceLimits::MaxStoredItems) + { + Result.Issues.Add(FMantleValidationIssue{ + EMantleIssueSeverity::Error, + LabelOf(PlaceSettings), + FString::Printf(TEXT("stores %d vehicles, weapons and wheels; a place stores at most %d."), Counted, FMantlePlaceLimits::MaxStoredItems), + TEXT("Remove some under Storage in Mantle Place Settings. Script packages do not count.") }); + } // mantle#296: the avatar items, at most 1,000; a place over that cannot publish, so it is named here first. TArray AvatarEntries; AMantlePlaceSettingsActor::ApplyAvatarStorageTo(World, AvatarEntries); diff --git a/Source/MantleEditor/Private/MantlePreviewExport.cpp b/Source/MantleEditor/Private/MantlePreviewExport.cpp index 825450ae..73122054 100644 --- a/Source/MantleEditor/Private/MantlePreviewExport.cpp +++ b/Source/MantleEditor/Private/MantlePreviewExport.cpp @@ -983,6 +983,8 @@ namespace MantlePreviewExportPrivate USkeletalMesh* Mesh = nullptr; FString DocumentText; FString MeshName; + /** mantle #333: an item's own clips, the settings file's local name to the clip's upload key. */ + TMap ClipKeys; }; TArray LoadedWeapons; if (Options.Weapons.Num() > 0) @@ -999,18 +1001,18 @@ namespace MantlePreviewExportPrivate Loaded.Mesh = LoadObject(nullptr, *Weapon.MeshObjectPath); if (!Loaded.Mesh) { - Result.Errors.Add(FString::Printf(TEXT("The 3D model of your weapon %s was not found. Press Create weapon again, then try Test locally."), *Weapon.Name)); + Result.Errors.Add(FString::Printf(TEXT("The 3D model of your weapon %s was not found. Press Create item again, then try Test locally."), *Weapon.Name)); return false; } if (!FFileHelper::LoadFileToString(Loaded.DocumentText, *Weapon.DocumentFile)) { - Result.Errors.Add(FString::Printf(TEXT("The settings file of your weapon %s was not found. Press Create weapon again, then try Test locally."), *Weapon.Name)); + Result.Errors.Add(FString::Printf(TEXT("The settings file of your weapon %s was not found. Press Create item again, then try Test locally."), *Weapon.Name)); return false; } Loaded.MeshName = FMantlePreviewExport::ReadWeaponMeshName(Loaded.DocumentText); if (Loaded.MeshName.IsEmpty() || !MantlePreviewLaunch::IsBundleRelativePath(Weapon.BundleFile())) { - Result.Errors.Add(FString::Printf(TEXT("The settings file of your weapon %s does not name its 3D model. Press Create weapon again, then try Test locally."), *Weapon.Name)); + Result.Errors.Add(FString::Printf(TEXT("The settings file of your weapon %s does not name its 3D model. Press Create item again, then try Test locally."), *Weapon.Name)); return false; } } @@ -1113,6 +1115,11 @@ namespace MantlePreviewExportPrivate } // The map picture (#167), made as Publish makes it: its tiles cook with the textures and the place names their ids. FMantleMinimap::Convert(World, Converter, Set); + // mantle #333: a consumable's or a usable item's own clips are cooked and bundled with it, as an upload sends them with the item. + for (FLoadedWeapon& Loaded : LoadedWeapons) + { + FMantlePreviewExport::ConvertWeaponClips(*Loaded.Weapon, Loaded.DocumentText, Converter, Set, Loaded.ClipKeys); + } PreviewAddIssueLines(Set.Issues, Result.Errors, Result.Warnings); if (Set.HasErrors()) { @@ -1626,6 +1633,16 @@ namespace MantlePreviewExportPrivate FMantlePreviewBundleWeapon& Entry = BundleWeapons.AddDefaulted_GetRef(); Entry.File = Loaded.Weapon->BundleFile(); Entry.Assets.Add(Loaded.MeshName, MeshId); + for (const TPair& Clip : Loaded.ClipKeys) + { + const FString ClipId = FMantlePlaceAssets::ProvisionalId(Clip.Value); + if (!State.AssetIndexById.Contains(ClipId)) + { + Result.Errors.Add(FString::Printf(TEXT("An animation of your item %s could not be prepared for the test."), *Loaded.Weapon->Name)); + return false; + } + Entry.Assets.Add(Clip.Key, ClipId); + } // The cooked mesh carries no material ids: the slot's own material (else the default surface), as the exporter fills a // SkeletalMesh entity's materials. A library material is not an uploaded asset, so its slot is left alone. const TArray& MeshMaterials = Loaded.Mesh->GetMaterials(); @@ -1830,6 +1847,35 @@ FMantleWeaponToTry FMantleWeaponToTry::FromBuilderName(const FString& SafeName) return Weapon; } +bool FMantlePreviewExport::ConvertWeaponClips(const FMantleWeaponToTry& Weapon, const FString& DocumentText, FMantlePlaceAssetConverter& Converter, + FMantlePlaceAssetSet& Set, TMap& OutClipKeys) +{ + TSharedPtr Root; + const TSharedPtr* ClipsBlock = nullptr; + if (!FJsonSerializer::Deserialize(TJsonReaderFactory<>::Create(DocumentText), Root) || !Root || !Root->TryGetObjectField(TEXT("clips"), ClipsBlock)) + { + return true; + } + FMantleBuiltWeaponParts Parts; + const FString Problem = FMantlePlaceAssets::WeaponDocumentProblem(Weapon.Name, DocumentText, &Parts); + if (!Problem.IsEmpty()) + { + Set.Issues.Add(FMantleValidationIssue{ EMantleIssueSeverity::Error, Weapon.Name, FString::Printf(TEXT("The item '%s' %s."), *Weapon.Name, *Problem), + TEXT("Open Tools > Mantle > Build an item and press Create item again, then try Test locally.") }); + return false; + } + TArray> SlotKeys; + if (!Converter.ConvertItemClips(Weapon.Name, Parts.Clips, Set, SlotKeys)) + { + return false; + } + for (const TPair& Slot : SlotKeys) + { + OutClipKeys.Add((*ClipsBlock)->GetStringField(Slot.Key), Slot.Value); + } + return true; +} + bool FMantlePreviewExport::ClientReadsWeapons(const FMantleTargetFeatures& Features) { return Features.Reads(MantleClientFeatures::WeaponDocument); diff --git a/Source/MantleEditor/Private/MantlePreviewExport.h b/Source/MantleEditor/Private/MantlePreviewExport.h index 7b2943a1..63abb32b 100644 --- a/Source/MantleEditor/Private/MantlePreviewExport.h +++ b/Source/MantleEditor/Private/MantlePreviewExport.h @@ -6,8 +6,10 @@ #include "MantleCoverage.h" #include "MantleTargetFeatures.h" +class FMantlePlaceAssetConverter; class UWorld; struct FMantleCosmeticPackage; +struct FMantlePlaceAssetSet; struct FMantlePlace; class FJsonObject; struct FMantleLocalScriptPackage; @@ -163,6 +165,14 @@ class FMantlePreviewExport /** #729: true when the client these features describe reads a weapon settings file (the weaponDocument feature). */ static bool ClientReadsWeapons(const FMantleTargetFeatures& Features); + /** + * mantle #333: the clips a weapon's settings file names (a consumable's or a usable item's own), converted into Set as the upload + * makes them. OutClipKeys gets the file's local name of each clip and its upload key; nothing for a file without clips. False, + * with the reason in Set.Issues, when one is missing or cannot be used. + */ + static bool ConvertWeaponClips(const FMantleWeaponToTry& Weapon, const FString& DocumentText, FMantlePlaceAssetConverter& Converter, + FMantlePlaceAssetSet& Set, TMap& OutClipKeys); + /** #729: what the creator is told when the Mantle app is too old for a weapon preview, in plain words. */ static FString WeaponsNeedNewerClientMessage(); diff --git a/Source/MantleEditor/Private/MantleWeaponBuilderDev.cpp b/Source/MantleEditor/Private/MantleWeaponBuilderDev.cpp index 54bb16fb..c9278eb3 100644 --- a/Source/MantleEditor/Private/MantleWeaponBuilderDev.cpp +++ b/Source/MantleEditor/Private/MantleWeaponBuilderDev.cpp @@ -4,11 +4,12 @@ #include "MantleWeaponBuilderLogic.h" #include "MantleWeaponSource.h" #include "MantleRuntime.h" +#include "Animation/AnimSequence.h" #include "Engine/SkeletalMesh.h" #include "Engine/StaticMesh.h" #include "HAL/IConsoleManager.h" -// Dev command (#840): `Mantle.Dev.BuildWeapon [MeshPath] [flip] [full] [stick] [pickup] [blast=] [fuse=] [speed=] [linger=] [lingerdps=] [lingerradius=] [charges=] [refill=] [beamdps=] [beamseconds=]` makes a builder weapon without the panel, the way +// Dev command (#840): `Mantle.Dev.BuildWeapon [MeshPath] [flip] [full] [stick] [pickup] [blast=] [fuse=] [speed=] [linger=] [lingerdps=] [lingerradius=] [charges=] [refill=] [beamdps=] [beamseconds=] [holdclip= useclip= equipclip= putawayclip=]` makes a builder weapon without the panel, the way // its Create does: a source with the hold's default tuning and the model, exported to // /Game/MantleWeapons/. flip is the panel's Flip (front and back swapped); full turns on a melee weapon's whole // kit (four-stage combo, charged heavy, block). A staff's choices: charges (how many casts), refill (seconds to get one back), beamdps and beamseconds @@ -155,6 +156,23 @@ namespace MantleWeaponBuilderDev { Source->Projectile.Model = TSoftObjectPtr(FSoftObjectPath(Value)); } + // A consumable's or a usable item's own clips (mantle #333): the Animations screen's four slots. + else if (Key == TEXT("holdclip")) + { + Source->ClipHold = TSoftObjectPtr(FSoftObjectPath(Value)); + } + else if (Key == TEXT("useclip")) + { + Source->ClipUse = TSoftObjectPtr(FSoftObjectPath(Value)); + } + else if (Key == TEXT("equipclip")) + { + Source->ClipEquip = TSoftObjectPtr(FSoftObjectPath(Value)); + } + else if (Key == TEXT("putawayclip")) + { + Source->ClipPutAway = TSoftObjectPtr(FSoftObjectPath(Value)); + } else if (Key == TEXT("element")) { const int64 Style = StaticEnum()->GetValueByNameString(Value); @@ -191,7 +209,7 @@ namespace MantleWeaponBuilderDev static FAutoConsoleCommand GBuildWeaponCommand( TEXT("Mantle.Dev.BuildWeapon"), TEXT("Mantle.Dev.BuildWeapon [MeshPath] [flip] [full] [stick] [pickup] [packframe] -- the weapon builder's Create without the panel (default tuning, auto fit; flip: the panel's Flip; full: combo, charge and block; stick, pickup: a bow's arrows; charges=, refill=, beamdps=, beamseconds=: a staff's casts and beam; packframe: a pack gun mesh turned bore-forward on its own hand and sight sockets; ") - TEXT("#905: delivery=projectile|beam on a gun, speed=, gravity=, blast=, round=, beamradius=, beamrange=, element=), ") + TEXT("#905: delivery=projectile|beam on a gun, speed=, gravity=, blast=, round=, beamradius=, beamrange=, element=; #333: holdclip=, useclip=, equipclip=, putawayclip= on a consumable or a usable item), ") TEXT("exported to /Game/MantleWeapons/. Logs MANTLE_BUILD_WEAPON_OK or MANTLE_BUILD_WEAPON_FAILED."), FConsoleCommandWithArgsDelegate::CreateStatic(&BuildWeapon)); } diff --git a/Source/MantleEditor/Private/MantleWeaponBuilderExport.cpp b/Source/MantleEditor/Private/MantleWeaponBuilderExport.cpp index 75c5cb58..d4cd4ca5 100644 --- a/Source/MantleEditor/Private/MantleWeaponBuilderExport.cpp +++ b/Source/MantleEditor/Private/MantleWeaponBuilderExport.cpp @@ -1,12 +1,15 @@ // Copyright Joshua Eger. All Rights Reserved. #include "MantleWeaponBuilderExport.h" +#include "MantleConsumableEffect.h" #include "AssetRegistry/AssetRegistryModule.h" +#include "Animation/AnimSequence.h" #include "Engine/SkeletalMesh.h" #include "MantlePlaceLimits.h" #include "Engine/StaticMesh.h" #include "HAL/FileManager.h" #include "MantleBuilderPoint.h" +#include "MantleItemClips.h" #include "MantleWeaponBuilderKind.h" #include "MantleWeaponBuilderLogic.h" #include "MantleWeaponDocument.h" @@ -40,6 +43,43 @@ namespace MantleWeaponBuilderExportPrivate bool IsMesh(UObject* Asset) { return Cast(Asset) || Cast(Asset); } + /** The creator clips of a source, in the order the Clips control shows them: hold, use, equip, putAway (mantle #333). */ + TArray*> ClipSlots(const UMantleWeaponSource& Source) + { + return { &Source.ClipHold, &Source.ClipUse, &Source.ClipEquip, &Source.ClipPutAway }; + } + + /** The local name slot Slot's clip goes by in the item's folder; one animation in two slots is copied once, under the first slot's name. */ + FString ClipLocalName(const UMantleWeaponSource& Source, const int32 Slot) + { + const TArray*> Slots = ClipSlots(Source); + int32 First = Slot; + for (int32 Earlier = 0; Earlier < Slot; ++Earlier) + { + if (Slots[Earlier]->ToSoftObjectPath() == Slots[Slot]->ToSoftObjectPath()) + { + First = Earlier; + break; + } + } + return AuxiliaryName(Source, *FString::Printf(TEXT("Clip%d"), First)); + } + + /** Creator clips (mantle #333): the slots name the copies made in the item's folder; the upload swaps the names for uploaded ids. */ + void SetClips(const UMantleWeaponSource& Source, FMantleWeaponDesc& Desc) + { + const TArray*> Slots = ClipSlots(Source); + FString* const Fields[] = { &Desc.ClipHold, &Desc.ClipUse, &Desc.ClipEquip, &Desc.ClipPutAway }; + for (int32 Slot = 0; Slot < Slots.Num(); ++Slot) + { + if (!Slots[Slot]->IsNull()) + { + *Fields[Slot] = ClipLocalName(Source, Slot); + Desc.bClips = true; + } + } + } + /** The extra's cooldown, written only when the creator chose one that is not the kind's own (below 0 = never chosen). */ void SetExtraCooldownIfChosen(FMantleWeaponDocExtra& Extra, const float Seconds) { @@ -219,7 +259,7 @@ bool FMantleWeaponBuilderExport::BuildDocument(const UMantleWeaponSource& Source using namespace MantleWeaponBuilderExportPrivate; using namespace MantleWeaponBuilderLogic; Out = FMantleWeaponDesc(); - if (Source.Hold >= EMantleWeaponHold::Count || Source.Delivery > EMantleWeaponSourceDelivery::Use || Source.Resource > EMantleWeaponSourceResource::None) + if (Source.Hold >= EMantleWeaponHold::Count || Source.Delivery > EMantleWeaponSourceDelivery::Signal || Source.Resource > EMantleWeaponSourceResource::None) { OutMessages.Add(LOCTEXT("InvalidChoice", "Pick a supported hold, delivery and resource for your weapon.")); return false; @@ -367,52 +407,81 @@ bool FMantleWeaponBuilderExport::BuildDocument(const UMantleWeaponSource& Source } } } - if (Desc.GetHold() == EMantleWeaponDocHold::Consumable) + if (FMantleWeaponDocument::IsUsedNotFired(Desc.GetDelivery())) { - // #1025: a consumable is used up, never fired: no attack, spread, recoil, parts, attachments or sounds, just its own block. - const FMantleWeaponSourceConsumable& C = Source.Consumable; - const bool bHeals = C.Effect == EMantleWeaponSourceConsumableEffect::Heal; - if (bHeals && (!FMath::IsFinite(C.Heal) || C.Heal < 1.f || C.Heal > 1000.f || !FMath::IsFinite(C.HealSeconds) || C.HealSeconds < 0.f || C.HealSeconds > 60.f)) + // #1025, #333: a consumable and a usable item are used, never fired: no attack, spread, recoil, parts, attachments or sounds. A + // consumable has its own block; what using a usable item does is the place's script's. + if (Desc.GetHold() == EMantleWeaponDocHold::Consumable) { - OutMessages.Add(LOCTEXT("BadHeal", "Set the health between 1 and 1000, and the time to spread it over between 0 and 60 seconds.")); - return false; - } - if (C.Uses < 1 || C.Uses > 100) - { - OutMessages.Add(LOCTEXT("BadUses", "Set the uses between 1 and 100.")); - return false; - } - if (C.bOverrideUseSeconds && (!FMath::IsFinite(C.UseSeconds) || C.UseSeconds < 0.5f || C.UseSeconds > 10.f)) - { - OutMessages.Add(LOCTEXT("BadUseSeconds", "Set the use time between 0.5 and 10 seconds.")); - return false; - } - if (!FMath::IsFinite(C.CooldownSeconds) || C.CooldownSeconds < 0.f || C.CooldownSeconds > 600.f) - { - OutMessages.Add(LOCTEXT("BadCooldown", "Set the wait between uses between 0 and 600 seconds.")); - return false; - } - FMantleWeaponDocConsumable Consumable; - Consumable.Style = C.Style == EMantleWeaponSourceUseStyle::EatDrink ? EMantleWeaponDocUseStyle::EatDrink : EMantleWeaponDocUseStyle::Use; - if (bHeals) - { - Consumable.Heal.Set(C.Heal); - Consumable.HealSeconds.Set(C.HealSeconds); - } - else - { - // The document refuses heal and healSeconds beside effect none. - Consumable.Effect.Set(EMantleWeaponDocConsumableEffect::None); + const FMantleWeaponSourceConsumable& C = Source.Consumable; + const bool bHeals = C.Effect == EMantleWeaponSourceConsumableEffect::Heal; + if (bHeals && (!FMath::IsFinite(C.Heal) || C.Heal < 1.f || C.Heal > 1000.f || !FMath::IsFinite(C.HealSeconds) || C.HealSeconds < 0.f || C.HealSeconds > 60.f)) + { + OutMessages.Add(LOCTEXT("BadHeal", "Set the health between 1 and 1000, and the time to spread it over between 0 and 60 seconds.")); + return false; + } + const bool bAmount = !bHeals && C.Effect != EMantleWeaponSourceConsumableEffect::None; + if (bAmount && (!FMath::IsFinite(C.Amount) || C.Amount < 1.f || C.Amount > 10000.f)) + { + OutMessages.Add(LOCTEXT("BadAmount", "Set the amount between 1 and 10000.")); + return false; + } + if (C.Uses < 1 || C.Uses > 100) + { + OutMessages.Add(LOCTEXT("BadUses", "Set the uses between 1 and 100.")); + return false; + } + if (C.bOverrideUseSeconds && (!FMath::IsFinite(C.UseSeconds) || C.UseSeconds < 0.5f || C.UseSeconds > 10.f)) + { + OutMessages.Add(LOCTEXT("BadUseSeconds", "Set the use time between 0.5 and 10 seconds.")); + return false; + } + if (!FMath::IsFinite(C.CooldownSeconds) || C.CooldownSeconds < 0.f || C.CooldownSeconds > 600.f) + { + OutMessages.Add(LOCTEXT("BadCooldown", "Set the wait between uses between 0 and 600 seconds.")); + return false; + } + FMantleWeaponDocConsumable Consumable; + Consumable.Style = C.Style == EMantleWeaponSourceUseStyle::EatDrink ? EMantleWeaponDocUseStyle::EatDrink : EMantleWeaponDocUseStyle::Use; + switch (C.Effect) + { + case EMantleWeaponSourceConsumableEffect::Heal: + Consumable.Heal.Set(C.Heal); + Consumable.HealSeconds.Set(C.HealSeconds); + break; + // The document takes each amount only beside its own effect. + case EMantleWeaponSourceConsumableEffect::Stamina: + Consumable.Effect.Set(EMantleWeaponDocConsumableEffect::Stamina); + Consumable.Stamina.Set(C.Amount); + break; + case EMantleWeaponSourceConsumableEffect::Hunger: + Consumable.Effect.Set(EMantleWeaponDocConsumableEffect::Hunger); + Consumable.Hunger.Set(C.Amount); + break; + case EMantleWeaponSourceConsumableEffect::Thirst: + Consumable.Effect.Set(EMantleWeaponDocConsumableEffect::Thirst); + Consumable.Thirst.Set(C.Amount); + break; + case EMantleWeaponSourceConsumableEffect::None: + Consumable.Effect.Set(EMantleWeaponDocConsumableEffect::None); + break; + } + Consumable.Uses.Set(C.Uses); + if (C.bOverrideUseSeconds) Consumable.UseSeconds.Set(C.UseSeconds); + Consumable.CooldownSeconds.Set(C.CooldownSeconds); + Consumable.bMoveWhileUsing.Set(C.bMoveWhileUsing); + Desc.Consumable.Set(Consumable); + // #333: with the creator's own Use clip, the hidden effect moment goes with it. + if (const TOptional Moment = FMantleConsumableEffect::DocumentSeconds(Source)) + { + Desc.UseEffectSeconds.Set(Moment.GetValue()); + } } - Consumable.Uses.Set(C.Uses); - if (C.bOverrideUseSeconds) Consumable.UseSeconds.Set(C.UseSeconds); - Consumable.CooldownSeconds.Set(C.CooldownSeconds); - Consumable.bMoveWhileUsing.Set(C.bMoveWhileUsing); - Desc.Consumable.Set(Consumable); - TArray ConsumableErrors; - if (!FMantleWeaponDocument::Validate(Desc, ConsumableErrors)) + SetClips(Source, Desc); + TArray UseErrors; + if (!FMantleWeaponDocument::Validate(Desc, UseErrors)) { - for (const auto& Error : ConsumableErrors) + for (const auto& Error : UseErrors) { OutMessages.Add(FText::FromString(Error.ToString())); UE_LOG(LogMantleWeaponBuilderExport, Warning, TEXT("Weapon '%s' settings refused: %s"), *Desc.Name, *Error.ToString()); @@ -748,6 +817,7 @@ bool FMantleWeaponBuilderExport::BuildDocument(const UMantleWeaponSource& Source if (!Source.FireSoundTrigger.IsEmpty()) Sounds.Trigger.Set(Source.FireSoundTrigger); Desc.Sounds.Set(Sounds); } + SetClips(Source, Desc); TArray Errors; if (!FMantleWeaponDocument::Validate(Desc, Errors)) { @@ -826,6 +896,11 @@ bool FMantleWeaponBuilderExport::Export(const UMantleWeaponSource& Source, TArra }; for (const auto& Point : Guesses) if (!AddPoint(Point)) return false; for (const auto& Point : Source.Points) if (!AddPoint(Point)) return false; + // A consumable's and a usable item's grip is written only once the creator moves it: without one the game holds the item at its default. + if ((Source.Hold == EMantleWeaponHold::Consumable || Source.Hold == EMantleWeaponHold::Item) && !FMantleItemClips::PlacedGrip(Source.Points)) + { + InMesh.Remove(TEXT("Grip")); + } TMap InWeapon; for (const auto& Point : InMesh) { @@ -851,7 +926,9 @@ bool FMantleWeaponBuilderExport::Export(const UMantleWeaponSource& Source, TArra if (const auto* Point = InMesh.Find(SocketRole(Socket))) MeshInput.Sockets.Add(SocketRole(Socket), *Point); } } - for (const auto& Section : Source.MagazineSections) + // A consumable and a usable item are the model alone: parts left over from a gun are not baked into it (they would move its default grip). + const bool bModelAlone = Source.Hold == EMantleWeaponHold::Consumable || Source.Hold == EMantleWeaponHold::Item; + for (const auto& Section : bModelAlone ? TArray>() : Source.MagazineSections) { UObject* Asset = Section.LoadSynchronous(); if (!CheckAsset(Asset, true, FString())) return false; @@ -861,7 +938,7 @@ bool FMantleWeaponBuilderExport::Export(const UMantleWeaponSource& Source, TArra if (!MeshInput.Magazine.IsSet()) MeshInput.Magazine = Part; // Only the first magazine section is used; further sections are validated but not exported. } - for (const auto& In : Source.Parts) + for (const auto& In : bModelAlone ? TArray() : Source.Parts) { if (!In.InBody.IsValid() || In.InBody.GetScale3D().GetAbsMin() <= UE_SMALL_NUMBER) { @@ -891,6 +968,33 @@ bool FMantleWeaponBuilderExport::Export(const UMantleWeaponSource& Source, TArra } if (!Source.FireSound.IsNull() && !CheckAsset(Source.FireSound.LoadSynchronous(), false, AuxiliaryName(Source, TEXT("Fire")))) return false; if (!Source.FireSuppressedSound.IsNull() && !CheckAsset(Source.FireSuppressedSound.LoadSynchronous(), false, AuxiliaryName(Source, TEXT("FireSuppressed")))) return false; + { + // Creator clips: each is an animation (a skeleton the upload accepts is checked when the item is converted), kept outside the output folder like the models. + const TArray*> Slots = ClipSlots(Source); + for (int32 Slot = 0; Slot < Slots.Num(); ++Slot) + { + if (Slots[Slot]->IsNull()) + { + continue; + } + UAnimSequence* Clip = Slots[Slot]->LoadSynchronous(); + if (!Clip) + { + OutMessages.Add(LOCTEXT("BadClip", "A clip needs an animation sequence.")); + return false; + } + if (Clip->GetOutermost()->GetName().StartsWith(PackageFolder + TEXT("/"), ESearchCase::IgnoreCase)) + { + OutMessages.Add(LOCTEXT("ClipInOutput", "Keep the original clips outside this item's output folder, then try again.")); + return false; + } + const FString LocalName = ClipLocalName(Source, Slot); + if (!Auxiliary.ContainsByPredicate([&LocalName](const TPair& Each) { return Each.Value == LocalName; })) + { + Auxiliary.Emplace(Clip, LocalName); + } + } + } FOutputBackup Backup(Name, OutMessages); if (!Backup.bReady) return false; // Keep the existing firearm eye placement; non-firearm framing comes from its hold library. diff --git a/Source/MantleEditor/Private/MantleWeaponBuilderKind.cpp b/Source/MantleEditor/Private/MantleWeaponBuilderKind.cpp index e19ac616..0edeec91 100644 --- a/Source/MantleEditor/Private/MantleWeaponBuilderKind.cpp +++ b/Source/MantleEditor/Private/MantleWeaponBuilderKind.cpp @@ -3,6 +3,7 @@ #include "MantleWeaponBuilderExport.h" #include "MantleWeaponBuilderLogic.h" +#include "MantleHandAttach.h" #include "Engine/SkeletalMesh.h" #include "Engine/StaticMesh.h" #include "MeshDescription.h" @@ -368,7 +369,9 @@ TArray FMantleWeaponBuilderKind::GetRoles() const { const FName Name = MantleWeaponBuilderLogic::SocketRole(Socket); const bool bHand = Socket == EMantleWeaponDocSocket::GripR || Socket == EMantleWeaponDocSocket::GripL || Socket == EMantleWeaponDocSocket::Grip; - const FText Help = bHand ? LOCTEXT("HeldGripHelp", "The middle of the hand's palm on the handle. Check its position and orientation.") + const bool bHeldAtDefault = Socket == EMantleWeaponDocSocket::Grip && (Hold == EMantleWeaponFitHold::Consumable || Hold == EMantleWeaponFitHold::Item); + const FText Help = bHeldAtDefault ? LOCTEXT("ItemGripHelp", "Where the palm holds the item. Left where it is, the hand holds the item upright at its bottom; move it to hold it somewhere else.") + : bHand ? LOCTEXT("HeldGripHelp", "The middle of the hand's palm on the handle. Check its position and orientation.") : LOCTEXT("HeldContactHelp", "The weapon's contact or launch point. The arrow points along the edge, cast, arrow or shield face."); Roles.Add(MakeRole(*Name.ToString(), FText::FromName(Name), Help, bHand ? EMantleBuilderPointShape::Hand : EMantleBuilderPointShape::Arrow, bRequired, true)); }; @@ -448,6 +451,21 @@ TArray FMantleWeaponBuilderKind::GuessPointsFromPositions(c LastFit.ScaleReason = TEXT("You set the size yourself."); } + // A consumable and a usable item: no grip is written until the creator moves it, so the guess is where the game then holds it + // (in whichever hand; the left's turn here), measured on the item as the export bakes it, after the creator's turn and size. + if (Hold == EMantleWeaponFitHold::Consumable || Hold == EMantleWeaponFitHold::Item) + { + FBox Bounds(ForceInit); + for (const FVector3f& Position : Positions) + { + Bounds += LastFit.MeshToWeapon.TransformPosition(FVector(Position)); + } + if (FTransform* Grip = LastFit.Points.Find(FName(TEXT("Grip"))); Grip && Bounds.IsValid) + { + *Grip = MantleHandAttach::DefaultGripInMesh(Bounds, /*bRightHand*/ false); + } + } + // The surface, sampled about 1 cm apart in the weapon frame's units, for the hand and sight checks. { const double Scale = FMath::Max(double(LastFit.MeshToWeapon.GetScale3D().X), 1.0e-6); @@ -608,7 +626,7 @@ namespace MantleWeaponBuilderKindHeld { return { FVector(0.0, 1.0, 0.0), FVector(-1.0, 0.0, 0.0), FVector(0.0, 0.0, 1.0) }; } - if (Hold < EMantleWeaponFitHold::Melee1h || Hold == EMantleWeaponFitHold::Shield || Hold == EMantleWeaponFitHold::Consumable) + if (Hold < EMantleWeaponFitHold::Melee1h || Hold == EMantleWeaponFitHold::Shield || Hold == EMantleWeaponFitHold::Consumable || Hold == EMantleWeaponFitHold::Item) { return { FVector(1.0, 0.0, 0.0), FVector(0.0, 1.0, 0.0), FVector(0.0, 0.0, 1.0) }; } @@ -724,8 +742,8 @@ namespace MantleWeaponBuilderKindHeld AddBody(Out, Frame, Palm, HandL.GetValue(), Right, Left, 0.15); return; } - // A shield and a consumable are each one item in the left hand (the bow's clips use the right, but the ghost only needs a hand there). - if (Hold == EMantleWeaponFitHold::Shield || Hold == EMantleWeaponFitHold::Consumable) + // A shield, a consumable and a usable item are each one item in the left hand (the bow's clips use the right, but the ghost only needs a hand there). + if (Hold == EMantleWeaponFitHold::Shield || Hold == EMantleWeaponFitHold::Consumable || Hold == EMantleWeaponFitHold::Item) { if (!HandL.IsSet()) { @@ -1128,7 +1146,7 @@ const FMantleWeaponBuilderKind::FContactCache& FMantleWeaponBuilderKind::Contact return A.IsSet() == B.IsSet() && (!A.IsSet() || A.GetValue() == B.GetValue()); }; const TOptional HandR = ToWeapon(GripR); - const TOptional HandL = ToWeapon(Hold == EMantleWeaponFitHold::Shield || Hold == EMantleWeaponFitHold::Consumable ? FName(TEXT("Grip")) : GripL); + const TOptional HandL = ToWeapon(Hold == EMantleWeaponFitHold::Shield || Hold == EMantleWeaponFitHold::Consumable || Hold == EMantleWeaponFitHold::Item ? FName(TEXT("Grip")) : GripL); const TOptional SightLoc = ToWeapon(Sight); if (Cache.bValid && Cache.Hold == Hold && Cache.MeshToWeapon.Equals(MeshToWeapon, 0.f) && Same(Cache.HandR, HandR) && Same(Cache.HandL, HandL) && Same(Cache.Sight, SightLoc)) { diff --git a/Source/MantleEditor/Private/MantleWeaponBuilderLogic.cpp b/Source/MantleEditor/Private/MantleWeaponBuilderLogic.cpp index eea941b9..6118dbb6 100644 --- a/Source/MantleEditor/Private/MantleWeaponBuilderLogic.cpp +++ b/Source/MantleEditor/Private/MantleWeaponBuilderLogic.cpp @@ -52,6 +52,10 @@ namespace MantleWeaponBuilderLogicPrivate for (const auto& Attachment : Source.Attachments) Add(Attachment.Model.ToSoftObjectPath()); Add(Source.FireSound.ToSoftObjectPath()); Add(Source.FireSuppressedSound.ToSoftObjectPath()); + Add(Source.ClipHold.ToSoftObjectPath()); + Add(Source.ClipUse.ToSoftObjectPath()); + Add(Source.ClipEquip.ToSoftObjectPath()); + Add(Source.ClipPutAway.ToSoftObjectPath()); Packages.Sort(); for (FString& Package : Packages) { @@ -84,7 +88,9 @@ static_assert(static_cast(EMantleWeaponHold::Lmg) == static_cast(E static_assert(static_cast(EMantleWeaponHold::Count) == static_cast(EMantleWeaponFitHold::Count), "hold count"); static_assert(static_cast(EMantleWeaponHold::Throwable) == static_cast(EMantleWeaponDocHold::Throwable), "document hold order"); static_assert(static_cast(EMantleWeaponHold::Consumable) == static_cast(EMantleWeaponDocHold::Consumable), "document hold order"); -static_assert(static_cast(EMantleWeaponHold::Consumable) + 1 == static_cast(EMantleWeaponDocHold::Count), "document hold count"); +static_assert(static_cast(EMantleWeaponHold::Item) == static_cast(EMantleWeaponDocHold::Item), "document hold order"); +static_assert(static_cast(EMantleWeaponHold::Item) + 1 == static_cast(EMantleWeaponDocHold::Count), "document hold count"); +static_assert(static_cast(EMantleWeaponSourceDelivery::Signal) == static_cast(EMantleWeaponDocDelivery::Signal) + 1, "delivery order"); static_assert(static_cast(EMantleWeaponHold::Shield) == static_cast(EMantleWeaponDocHold::Shield), "document hold order"); static_assert(static_cast(EMantleWeaponSourceAction::Release) == static_cast(EMantleWeaponDocAction::Release), "action order"); @@ -146,6 +152,27 @@ EMantleWeaponHold MantleWeaponBuilderLogic::FromFitHold(EMantleWeaponFitHold Hol return static_cast(static_cast(Hold)); } +MantleWeaponBuilderLogic::EItemType MantleWeaponBuilderLogic::ItemTypeOf(EMantleWeaponHold Hold) +{ + switch (Hold) + { + case EMantleWeaponHold::Consumable: return EItemType::Consumable; + case EMantleWeaponHold::Item: return EItemType::Item; + default: return EItemType::Weapon; + } +} + +FQuat MantleWeaponBuilderLogic::QuarterTurn(const EQuarterTurn Turn) +{ + const FVector Axis = Turn == EQuarterTurn::Around ? FVector::UpVector : Turn == EQuarterTurn::Forward ? FVector::RightVector : FVector::ForwardVector; + return FQuat(Axis, UE_DOUBLE_HALF_PI); +} + +bool MantleWeaponBuilderLogic::TakesClips(EMantleWeaponHold Hold) +{ + return FMantleWeaponDocument::GetHoldInfo(ToDocHold(Hold)).bHasClips; +} + bool MantleWeaponBuilderLogic::IsHoldAvailable(EMantleWeaponHold Hold) { // Every hold is available. @@ -345,6 +372,7 @@ FText MantleWeaponBuilderLogic::HoldLabel(EMantleWeaponHold Hold) case EMantleWeaponHold::Shield: return LOCTEXT("HoldShield", "Shield"); case EMantleWeaponHold::Throwable: return LOCTEXT("HoldThrowable", "Throwable"); case EMantleWeaponHold::Consumable: return LOCTEXT("HoldConsumable", "Consumable"); + case EMantleWeaponHold::Item: return LOCTEXT("HoldItem", "Usable item"); } return FText::GetEmpty(); } @@ -352,14 +380,18 @@ FText MantleWeaponBuilderLogic::HoldLabel(EMantleWeaponHold Hold) FString MantleWeaponBuilderLogic::DefaultName(EMantleWeaponHold Hold) { // The fist weapon's label explains the hold; its name is the thing itself. - return Hold == EMantleWeaponHold::Unarmed ? FString(TEXT("My Knuckles")) : FString::Printf(TEXT("My %s"), *HoldLabel(Hold).ToString()); + if (Hold == EMantleWeaponHold::Unarmed) + { + return TEXT("My Knuckles"); + } + return Hold == EMantleWeaponHold::Item ? FString(TEXT("My Item")) : FString::Printf(TEXT("My %s"), *HoldLabel(Hold).ToString()); } FText MantleWeaponBuilderLogic::MissingModelMessage(EMantleWeaponHold Hold) { return Hold == EMantleWeaponHold::Unarmed ? LOCTEXT("FistWeaponNeedsModel", "Fist weapons need a 3D model: pick the model of the knuckles, claws or gauntlet the hand wears.") - : LOCTEXT("WeaponNeedsModel", "Pick the 3D model of your weapon."); + : LOCTEXT("ItemNeedsModel", "Pick the 3D model of your item."); } FMantleWeaponTuning MantleWeaponBuilderLogic::DefaultTuning(EMantleWeaponHold Hold) diff --git a/Source/MantleEditor/Private/MantleWeaponFit.cpp b/Source/MantleEditor/Private/MantleWeaponFit.cpp index 0544068c..f215334a 100644 --- a/Source/MantleEditor/Private/MantleWeaponFit.cpp +++ b/Source/MantleEditor/Private/MantleWeaponFit.cpp @@ -33,6 +33,8 @@ namespace MantleWeaponFitImpl {TEXT("shield"), 70.f, 25.f, 130.f}, {TEXT("throwable"), 15.f, 3.f, 70.f}, {TEXT("consumable"), 15.f, 4.f, 35.f}, + // A creator's usable item can be anything held in a hand (a key, a phone, a lantern, a fishing rod). + {TEXT("usable item"), 25.f, 3.f, 150.f}, }; static_assert(UE_ARRAY_COUNT(Table) == static_cast(EMantleWeaponFitHold::Count), "one size per hold"); return Table[FMath::Clamp(static_cast(Hold), 0, UE_ARRAY_COUNT(Table) - 1)]; @@ -187,7 +189,8 @@ namespace MantleWeaponFitImpl for (int32 H = 0; H < static_cast(EMantleWeaponFitHold::Count); ++H) { const EMantleWeaponFitHold Other = static_cast(H); - if (Other == Skip || !FitsHold(Other, Cm)) + // A usable item has no shape of its own, so it is never suggested for something else. + if (Other == Skip || Other == EMantleWeaponFitHold::Item || !FitsHold(Other, Cm)) { continue; } @@ -265,7 +268,7 @@ namespace MantleWeaponFitImpl for (int32 H = 0; H < static_cast(EMantleWeaponFitHold::Count); ++H) { const EMantleWeaponFitHold Other = static_cast(H); - if ((bChosenHoldOnly && Other != Current) || !FitsHold(Other, Fixed)) + if ((bChosenHoldOnly && Other != Current) || (Other == EMantleWeaponFitHold::Item && Current != Other) || !FitsHold(Other, Fixed)) { continue; } @@ -395,6 +398,8 @@ FMantleWeaponFitResult FMantleWeaponFit::Fit(const FMantleWeaponFitInput& In) const bool bBow = In.Hold == EMantleWeaponFitHold::Bow; const bool bShield = In.Hold == EMantleWeaponFitHold::Shield; const bool bStaff = In.Hold == EMantleWeaponFitHold::Staff; + // A consumable and a usable item have no shaft to find: a bottle's longest side is its height. + const bool bWhole = In.Hold == EMantleWeaponFitHold::Consumable || In.Hold == EMantleWeaponFitHold::Item; FVector X = bBow ? Axes[1] : bShield ? Axes[2] : Axes[0]; FVector Z = (bBow || bShield) ? Axes[0] : Axes[1]; // Stable sign on symmetric models; the creator confirms the front and handle with Flip/Turn and the points. @@ -406,6 +411,14 @@ FMantleWeaponFitResult FMantleWeaponFit::Fit(const FMantleWeaponFitInput& In) }; X = StableSign(X); Z = StableSign(Z); + // Held whole: the model stands as it was made, its own up and its own front. Only one clearly lying along its Y (a flashlight + // made sideways) is turned a quarter, to point forward. The builder's quarter turns reach any other way round. + if (bWhole) + { + const FVector Size = Bounds.GetSize(); + X = Size.Y > FMantleWeaponFit::ItemLyingAlongYRatio * FMath::Max(Size.X, Size.Z) ? FVector::YAxisVector : FVector::XAxisVector; + Z = FVector::UpVector; + } // A blade runs handle to tip along +X. The handle is the end with the crossguard: the widest cross-section in the // outer third at either end (a tip tapers to nothing), whatever way the model happened to face in its file. The // creator's Flip (bReverseLength) puts the handle at the other end. @@ -501,7 +514,7 @@ FMantleWeaponFitResult FMantleWeaponFit::Fit(const FMantleWeaponFitInput& In) const FMatrix Frame(FVector(X.X, Y.X, Z.X), FVector(X.Y, Y.Y, Z.Y), FVector(X.Z, Y.Z, Z.Z), FVector::ZeroVector); FBox Box(ForceInit); for (const auto& P : Pts) Box += FVector((P - Centroid) | X, (P - Centroid) | Y, (P - Centroid) | Z); - const double Length = (bBow || bShield) ? Box.GetSize().Z : Box.GetSize().X; + const double Length = bWhole ? Box.GetSize().GetMax() : (bBow || bShield) ? Box.GetSize().Z : Box.GetSize().X; const FScaleDecision Decision = DecideScale(In.Hold, Length); const double Scale = Decision.Scale; Result.Scale = static_cast(Scale); @@ -573,9 +586,10 @@ FMantleWeaponFitResult FMantleWeaponFit::Fit(const FMantleWeaponFitInput& In) Result.GripFromRearCm = static_cast((Grip.X - Box.Min.X) * Scale); Result.MeshToWeapon = FTransform(FQuat(Frame), -FVector(Centroid | X, Centroid | Y, Centroid | Z) * Scale - Origin, FVector(Scale)); auto Point = [&](const TCHAR* Role, FVector P) { Result.Points.Add(FName(Role), FTransform(FQuat::Identity, P * Scale - Origin)); }; - if (In.Hold == EMantleWeaponFitHold::Consumable) + if (In.Hold == EMantleWeaponFitHold::Consumable || In.Hold == EMantleWeaponFitHold::Item) { - // An item held whole in the palm: its middle is the grip. + // An item held whole in the palm. The builder moves this to the game's default grip once the creator's turn and size are in + // (FMantleWeaponBuilderKind). Point(TEXT("Grip"), Center); } else if (bShield) diff --git a/Source/MantleEditor/Private/MantleWeaponPublish.cpp b/Source/MantleEditor/Private/MantleWeaponPublish.cpp index 788d2b7b..f31ec146 100644 --- a/Source/MantleEditor/Private/MantleWeaponPublish.cpp +++ b/Source/MantleEditor/Private/MantleWeaponPublish.cpp @@ -31,7 +31,7 @@ FString FMantleWeaponPublishSource::ProblemWith(const FString& WeaponName) FString Text; if (!FFileHelper::LoadFileToString(Text, *AMantleWeaponSpawnPoint::BuiltDocumentFile(WeaponName))) { - return FString::Printf(TEXT("The weapon '%s' has no settings file. Press Create weapon, then Publish."), *WeaponName); + return FString::Printf(TEXT("The weapon '%s' has no settings file. Press Create item, then Publish."), *WeaponName); } const FString Problem = FMantlePlaceAssets::WeaponDocumentProblem(WeaponName, Text); if (!Problem.IsEmpty()) @@ -40,7 +40,7 @@ FString FMantleWeaponPublishSource::ProblemWith(const FString& WeaponName) } if (!IFileManager::Get().FileExists(*(FPaths::ProjectContentDir() / TEXT("MantleWeapons") / WeaponName / (TEXT("SKM_") + WeaponName + TEXT(".uasset"))))) { - return FString::Printf(TEXT("The weapon '%s' has no 3D model. Press Create weapon, then Publish."), *WeaponName); + return FString::Printf(TEXT("The weapon '%s' has no 3D model. Press Create item, then Publish."), *WeaponName); } return FString(); } @@ -65,7 +65,7 @@ bool FMantleWeaponPublishSource::Prepare(FMantleValidationResult& OutValidation, Dependencies = FMantlePlaceDependencies(); if (!Dependencies.AddBuiltWeapon(WeaponName, WeaponName)) { - OutMessage = FString::Printf(TEXT("The weapon '%s' could not be loaded. Press Create weapon again, then Publish."), *WeaponName); + OutMessage = FString::Printf(TEXT("The weapon '%s' could not be loaded. Press Create item again, then Publish."), *WeaponName); return false; } // The gathered model and materials are held only weakly; keep them until the conversion is done. diff --git a/Source/MantleEditor/Private/SMantleAnimPackSection.cpp b/Source/MantleEditor/Private/SMantleAnimPackSection.cpp new file mode 100644 index 00000000..d5f227b0 --- /dev/null +++ b/Source/MantleEditor/Private/SMantleAnimPackSection.cpp @@ -0,0 +1,441 @@ +// Copyright Joshua Eger. All Rights Reserved. +#include "SMantleAnimPackSection.h" + +#include "MantleAnimPack.h" +#include "MantleAvatarContract.h" +#include "MantleBuiltInMannequin.h" +#include "MantleCreatorClips.h" +#include "MantleEmoteRetarget.h" +#include "MantleRuntime.h" + +#include "Animation/AnimSequence.h" +#include "Animation/Skeleton.h" +#include "AssetRegistry/AssetData.h" +#include "Engine/SkeletalMesh.h" +#include "PropertyCustomizationHelpers.h" +#include "Styling/AppStyle.h" +#include "Widgets/Input/SButton.h" +#include "Widgets/Input/SCheckBox.h" +#include "Widgets/Input/SEditableTextBox.h" +#include "Widgets/Layout/SBox.h" +#include "Widgets/SBoxPanel.h" +#include "Widgets/Text/STextBlock.h" + +#define LOCTEXT_NAMESPACE "MantleAnimPackSection" + +// Named, not anonymous: MantleEditor builds as a unity build. +namespace MantleAnimPackSectionPrivate +{ + FLinearColor PackGoodColor() { return FLinearColor(0.55f, 0.80f, 0.55f); } + FLinearColor PackWarnColor() { return FLinearColor(0.95f, 0.65f, 0.25f); } +} + +void SMantleAnimPackSection::Construct(const FArguments& InArgs) +{ + using namespace MantleAnimPackSectionPrivate; + Clips->bFreeNamed = true; + Clips->Conversion = EMantleClipConversion::SampleOnOwnMesh; + Clips->RowExtra = [this](FName Slot) { return MakeRowExtra(Slot); }; + Clips->PreviewAs = [this](UAnimSequence* Clip, USkeletalMesh*& InOutBody) { return ShowForPreview(Clip, InOutBody); }; + if (const FMantleAvatarContract* Contract = FMantleAvatarContract::Get()) + { + Clips->PreviewMesh = FMantleBuiltInMannequin::UEFNMannequin(*Contract); + } + // One empty row to start with; the control's "Add a clip" makes more. + Clips->AddFreeSlot(FString()); + Clips->OnChanged.BindRaw(this, &SMantleAnimPackSection::ClipsChanged); + + ChildSlot + [ + SNew(SVerticalBox) + + SVerticalBox::Slot().AutoHeight().Padding(0, 0, 0, 6) + [ + SNew(STextBlock).AutoWrapText(true).ColorAndOpacity(FSlateColor::UseSubduedForeground()) + .Text(LOCTEXT("Help", "A set of named animations in your library. A place's script plays a clip as /. A clip can be made on the UEFN, MetaHuman, UE5 or UE4 Mannequin, or on a rig of your own.")) + ] + + SVerticalBox::Slot().AutoHeight().Padding(0, 2) + [ + SNew(SHorizontalBox) + + SHorizontalBox::Slot().AutoWidth().VAlign(VAlign_Center).Padding(0, 0, 8, 0) + [ + SNew(STextBlock).Text(LOCTEXT("NameLabel", "Pack name")) + ] + + SHorizontalBox::Slot().FillWidth(1.0f) + [ + SNew(SEditableTextBox) + .HintText(LOCTEXT("NameHint", "for example Dance moves")) + .ToolTipText(LOCTEXT("NameTip", "What the pack is called in your library. Publishing again under the same name adds a new version of the same item.")) + .Text_Lambda([this] { return FText::FromString(PackName); }) + .OnTextChanged_Lambda([this](const FText& Text) + { + PackName = Text.ToString(); + Recompute(); + }) + ] + ] + + SVerticalBox::Slot().AutoHeight().Padding(0, 8, 0, 4) + [ + SNew(STextBlock).Font(FAppStyle::GetFontStyle("BoldFont")).Text(LOCTEXT("ClipsHeading", "Clips")) + ] + + SVerticalBox::Slot().AutoHeight() + [ + SAssignNew(ClipSlots, SMantleClipSlots).Model(Clips) + ] + + SVerticalBox::Slot().AutoHeight() + [ + SNew(STextBlock).AutoWrapText(true) + .ColorAndOpacity(FSlateColor(PackWarnColor())) + .Visibility_Lambda([this] { return PreviewError.IsEmpty() ? EVisibility::Collapsed : EVisibility::Visible; }) + .Text_Lambda([this] { return FText::FromString(PreviewError); }) + ] + // Publish. + + SVerticalBox::Slot().AutoHeight().Padding(0, 14, 0, 0) + [ + SNew(STextBlock).Font(FAppStyle::GetFontStyle("BoldFont")).Text(LOCTEXT("PublishHeading", "Publish to your library")) + ] + + SVerticalBox::Slot().AutoHeight().Padding(0, 6, 0, 0) + [ + SNew(SCheckBox) + .Style(&FAppStyle::Get().GetWidgetStyle("RadioButton")) + .IsChecked_Lambda([this] { return Choice.bPublic ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; }) + .OnCheckStateChanged_Lambda([this](ECheckBoxState State) { if (State == ECheckBoxState::Checked) { Choice.bPublic = true; } }) + [ + SNew(STextBlock).Text(LOCTEXT("PublishPublic", "Public: other creators can find it and use it in their places")) + ] + ] + + SVerticalBox::Slot().AutoHeight().Padding(0, 4, 0, 0) + [ + SNew(SCheckBox) + .Style(&FAppStyle::Get().GetWidgetStyle("RadioButton")) + .IsChecked_Lambda([this] { return Choice.bPublic ? ECheckBoxState::Unchecked : ECheckBoxState::Checked; }) + .OnCheckStateChanged_Lambda([this](ECheckBoxState State) { if (State == ECheckBoxState::Checked) { Choice.bPublic = false; } }) + [ + SNew(STextBlock).Text(LOCTEXT("PublishPrivate", "Private: only you can use it")) + ] + ] + + SVerticalBox::Slot().AutoHeight().Padding(0, 8, 0, 0) + [ + SNew(SCheckBox) + .Visibility_Lambda([this] { return Choice.bPublic ? EVisibility::Visible : EVisibility::Collapsed; }) + .IsChecked_Lambda([this] { return Choice.bRightsDeclared ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; }) + .OnCheckStateChanged_Lambda([this](ECheckBoxState State) { Choice.bRightsDeclared = State == ECheckBoxState::Checked; }) + [ + SNew(STextBlock).AutoWrapText(true) + .Text(LOCTEXT("PublishRights", "I own this content or its license permits public redistribution on Mantle")) + ] + ] + + SVerticalBox::Slot().AutoHeight().Padding(0, 10, 0, 0) + [ + SNew(SHorizontalBox) + + SHorizontalBox::Slot().AutoWidth().VAlign(VAlign_Center) + [ + SNew(SButton) + .ButtonStyle(&FAppStyle::Get(), "PrimaryButton") + .Text_Lambda([this] + { + const FMantleAnimPackPublish& Publisher = FMantleAnimPackPublish::Get(); + const TSharedPtr Session = Publisher.GetSession(); + const bool bDoneHere = Session.IsValid() && Session->IsFinished() && Session->Succeeded() && Publisher.GetName().Equals(PackName, ESearchCase::IgnoreCase); + return bDoneHere ? LOCTEXT("Republish", "Republish") : LOCTEXT("Publish", "Publish"); + }) + .IsEnabled_Lambda([this] { return Problem().IsEmpty() && Choice.IsReady() && !FMantleAnimPackPublish::Get().IsBusy(); }) + .ToolTipText(LOCTEXT("PublishTip", "Uploads each clip and adds the pack to your Mantle library. Publishing again under the same name adds a new version of the same item; only what changed is uploaded.")) + .OnClicked(this, &SMantleAnimPackSection::OnPublish) + ] + + SHorizontalBox::Slot().FillWidth(1.0f).VAlign(VAlign_Center).Padding(12, 0, 0, 0) + [ + SNew(STextBlock).AutoWrapText(true) + .ColorAndOpacity_Lambda([this] { return FSlateColor(Problem().IsEmpty() ? PackGoodColor() : PackWarnColor()); }) + .Text_Lambda([this] { return FText::FromString(StatusLine()); }) + ] + ] + ]; + Recompute(); +} + +// ---- what a row's animation is made on ---- + +const SMantleAnimPackSection::FRigInfo* SMantleAnimPackSection::RigInfoFor(const FName Slot) const +{ + const TArray* Held = Clips->Clips.Find(Slot); + if (!Held || Held->Num() == 0) + { + return nullptr; + } + const FString Key = (*Held)[0].ToString(); + if (const FRigInfo* Known = RigCache.Find(Key)) + { + return Known; + } + const UAnimSequence* Sequence = Cast((*Held)[0].TryLoad()); + if (!Sequence) + { + return nullptr; + } + FRigInfo Info; + const USkeleton* Skeleton = Sequence->GetSkeleton(); + Info.SkeletonName = Skeleton ? Skeleton->GetName() : FString(TEXT("unknown")); + const FMantleAvatarContract* Contract = FMantleAvatarContract::Get(); + Info.SkeletonId = Contract && Skeleton ? FMantleEmoteRetarget::IdentifySkeleton(Skeleton, *Contract) : FString(); + Info.bUefn = !Info.SkeletonId.IsEmpty(); + if (const USkeletalMesh* Preview = Sequence->GetPreviewMesh()) + { + Info.DefaultMeshPath = Preview->GetPathName(); + } + return &RigCache.Add(Key, MoveTemp(Info)); +} + +USkeletalMesh* SMantleAnimPackSection::OwnMeshFor(const FName Slot) const +{ + const FRigInfo* Info = RigInfoFor(Slot); + if (!Info || Info->bUefn) + { + return nullptr; + } + if (const FSoftObjectPath* Picked = MeshPicks.Find(Slot)) + { + if (!Picked->IsNull()) + { + return Cast(Picked->TryLoad()); + } + } + return Info->DefaultMeshPath.IsEmpty() ? nullptr : Cast(FSoftObjectPath(Info->DefaultMeshPath).TryLoad()); +} + +FString SMantleAnimPackSection::RigLine(const FName Slot) const +{ + const FRigInfo* Info = RigInfoFor(Slot); + if (!Info) + { + return FString(TEXT("Skeleton: pick an animation")); + } + return RigText(Info->SkeletonId, Info->SkeletonName); +} + +FString SMantleAnimPackSection::RigText(const FString& SkeletonId, const FString& SkeletonName) +{ + if (SkeletonId.IsEmpty()) + { + return FString::Printf(TEXT("Skeleton: Own rig: %s"), *SkeletonName); + } + const TCHAR* Converted = SkeletonId == TEXT("metahuman") ? TEXT("MetaHuman") + : SkeletonId == TEXT("ue5mannequin") ? TEXT("UE5 Mannequin") + : SkeletonId == TEXT("ue4mannequin") ? TEXT("UE4 Mannequin") : nullptr; + return Converted ? FString::Printf(TEXT("Skeleton: %s (converted to UEFN)"), Converted) : FString(TEXT("Skeleton: UEFN")); +} + +UAnimationAsset* SMantleAnimPackSection::ShowForPreview(UAnimSequence* Clip, USkeletalMesh*& InOutBody) +{ + PreviewError.Reset(); + // The control names the clip, not its row: the first row holding it says which mesh a rig of the creator's own plays on. + for (const FMantleClipSlotDef& Def : Clips->Slots) + { + if (Clips->Load(Def.Name, 0) != Clip) + { + continue; + } + const FRigInfo* Info = RigInfoFor(Def.Name); + if (Info && !Info->bUefn) + { + USkeletalMesh* Own = OwnMeshFor(Def.Name); + if (!Own || Own->GetSkeleton() != Clip->GetSkeleton()) + { + PreviewError = FString::Printf(TEXT("Pick a mesh made for %s on the clip's row to see it."), *Info->SkeletonName); + return nullptr; + } + InOutBody = Own; + return Clip; + } + break; + } + return FMantleCreatorClips::MakePreview(Clip, InOutBody, Previewed, PreviewError); +} + +TSharedRef SMantleAnimPackSection::MakeRowExtra(const FName Slot) +{ + return SNew(SVerticalBox) + + SVerticalBox::Slot().AutoHeight() + [ + SNew(STextBlock) + .ColorAndOpacity(FSlateColor::UseSubduedForeground()) + .AutoWrapText(true) + .Text_Lambda([this, Slot] { return FText::FromString(RigLine(Slot)); }) + ] + + SVerticalBox::Slot().AutoHeight().Padding(0, 2, 0, 0) + [ + SNew(SBox) + .Visibility_Lambda([this, Slot] + { + const FRigInfo* Info = RigInfoFor(Slot); + return Info && !Info->bUefn ? EVisibility::Visible : EVisibility::Collapsed; + }) + [ + SNew(SHorizontalBox) + + SHorizontalBox::Slot().AutoWidth().VAlign(VAlign_Center).Padding(0, 0, 6, 0) + [ + SNew(STextBlock) + .ColorAndOpacity(FSlateColor::UseSubduedForeground()) + .Text(LOCTEXT("MeshLabel", "Mesh to play it on")) + .ToolTipText(LOCTEXT("MeshTip", "A clip on a rig of your own is sampled over a mesh made for that rig. Its animation's preview mesh is used until you pick another.")) + ] + + SHorizontalBox::Slot().FillWidth(1.0f) + [ + SNew(SObjectPropertyEntryBox) + .AllowedClass(USkeletalMesh::StaticClass()) + .DisplayThumbnail(false) + .AllowClear(true) + .ObjectPath_Lambda([this, Slot] + { + if (const FSoftObjectPath* Picked = MeshPicks.Find(Slot)) + { + if (!Picked->IsNull()) + { + return Picked->ToString(); + } + } + const FRigInfo* Info = RigInfoFor(Slot); + return Info ? Info->DefaultMeshPath : FString(); + }) + .OnShouldFilterAsset_Lambda([](const FAssetData& Asset) + { + return Asset.AssetClassPath != USkeletalMesh::StaticClass()->GetClassPathName(); + }) + .OnObjectChanged_Lambda([this, Slot](const FAssetData& Asset) + { + if (Asset.IsValid()) + { + MeshPicks.Add(Slot, Asset.ToSoftObjectPath()); + } + else + { + MeshPicks.Remove(Slot); + } + Recompute(); + }) + ] + ] + ]; +} + +// ---- the input and its checks ---- + +FMantleAnimPackInput SMantleAnimPackSection::MakeInput() const +{ + FMantleAnimPackInput Input; + Input.Name = PackName.TrimStartAndEnd(); + for (const FMantleClipSlotDef& Def : Clips->Slots) + { + const FString Name = Def.Label.ToString().TrimStartAndEnd(); + const bool bHasClip = Clips->NumClips(Def.Name) > 0; + if (Name.IsEmpty() && !bHasClip) + { + // An empty row is just an unfinished row. + continue; + } + FMantleAnimPackInput::FClip& Clip = Input.Clips.AddDefaulted_GetRef(); + Clip.Name = Name; + Clip.Sequence = Clips->Load(Def.Name, 0); + Clip.OwnMesh = OwnMeshFor(Def.Name); + } + return Input; +} + +void SMantleAnimPackSection::Recompute() +{ + PublishRefusal = FText::GetEmpty(); + CachedProblem.Reset(); + for (const FMantleClipSlotDef& Def : Clips->Slots) + { + const FString Name = Def.Label.ToString().TrimStartAndEnd(); + if (Name.IsEmpty() && Clips->NumClips(Def.Name) == 0) + { + continue; + } + const FString Shown = Name.IsEmpty() ? FString(TEXT("a clip")) : FString::Printf(TEXT("the clip '%s'"), *Name); + if (Clips->NumClips(Def.Name) == 0) + { + CachedProblem = FString::Printf(TEXT("Pick an animation for %s, or remove it."), *Shown); + return; + } + const FRigInfo* Info = RigInfoFor(Def.Name); + const UAnimSequence* Sequence = Clips->Load(Def.Name, 0); + if (!Info || !Sequence) + { + CachedProblem = FString::Printf(TEXT("The animation for %s could not be loaded. Pick it again."), *Shown); + return; + } + if (!Info->bUefn) + { + const USkeletalMesh* Mesh = OwnMeshFor(Def.Name); + if (!Mesh) + { + CachedProblem = FString::Printf(TEXT("%s is made on its own rig (%s). Pick a mesh for that rig on its row, so the clip can be played on it."), *Shown, *Info->SkeletonName); + return; + } + if (Mesh->GetSkeleton() != Sequence->GetSkeleton()) + { + CachedProblem = FString::Printf(TEXT("The mesh picked for %s is not made for its rig (%s). Pick a mesh on that skeleton."), *Shown, *Info->SkeletonName); + return; + } + } + } + CachedProblem = MakeInput().Problem(); +} + +void SMantleAnimPackSection::ClipsChanged() +{ + Recompute(); +} + +FString SMantleAnimPackSection::StatusLine() const +{ + if (!PublishRefusal.IsEmpty()) + { + return PublishRefusal.ToString(); + } + if (!CachedProblem.IsEmpty()) + { + return CachedProblem; + } + if (Choice.bPublic && !Choice.bRightsDeclared) + { + return TEXT("Tick the declaration to publish publicly, or choose Private."); + } + const FMantleAnimPackPublish& Publisher = FMantleAnimPackPublish::Get(); + const TSharedPtr Session = Publisher.GetSession(); + if (Session.IsValid() && Publisher.GetName().Equals(PackName.TrimStartAndEnd(), ESearchCase::IgnoreCase)) + { + if (!Session->IsFinished()) + { + return FString::Printf(TEXT("%s (%d%%)"), *Session->GetStatusText(), FMath::RoundToInt(Session->GetProgress() * 100.f)); + } + FString Said = Session->GetResult().Message; + if (!Session->Succeeded()) + { + for (const TArray* Issues : { &Session->GetResult().Validation.Issues, &Session->GetAttention() }) + { + if (const FMantleValidationIssue* First = Issues->FindByPredicate([](const FMantleValidationIssue& Issue) { return Issue.Severity == EMantleIssueSeverity::Error; })) + { + Said += TEXT(" ") + First->Problem + (First->Remedy.IsEmpty() ? FString() : TEXT(" ") + First->Remedy); + break; + } + } + } + return Said; + } + return TEXT("Ready: adds this pack to your library."); +} + +FReply SMantleAnimPackSection::OnPublish() +{ + FString Error; + PublishRefusal = FText::GetEmpty(); + if (!FMantleAnimPackPublish::Get().Start(MakeInput(), Choice, Error)) + { + PublishRefusal = FText::FromString(Error); + UE_LOG(LogMantle, Warning, TEXT("MANTLE_ANIM_PACK_PUBLISH_FAILED %s"), *Error); + } + return FReply::Handled(); +} + +#undef LOCTEXT_NAMESPACE diff --git a/Source/MantleEditor/Private/SMantleAnimPackSection.h b/Source/MantleEditor/Private/SMantleAnimPackSection.h new file mode 100644 index 00000000..d623827d --- /dev/null +++ b/Source/MantleEditor/Private/SMantleAnimPackSection.h @@ -0,0 +1,83 @@ +// Copyright Joshua Eger. All Rights Reserved. +#pragma once + +#include "CoreMinimal.h" +#include "MantleAnimPackPublish.h" +#include "MantleLibraryPublish.h" +#include "SMantleClipSlots.h" +#include "UObject/StrongObjectPtr.h" +#include "Widgets/DeclarativeSyntaxSupport.h" +#include "Widgets/SCompoundWidget.h" + +class SWidget; + +/** + * The Animation pack section (mantle #333 G10), a part of the Cosmetics panel's upload flow: a pack name, then a list of named clips in the + * shared Clips control (its free-named mode), then Publish to the library. A clip made on the UEFN, MetaHuman, UE5 or UE4 Mannequin skeleton + * is shown as "UEFN"; a clip on any other rig is shown as "Own rig: " and is sampled over a mesh on that skeleton (its animation's + * preview mesh, or the one picked on its row). Publishing again with the same name makes a new version of the same library item. + * Nothing is written until Publish. + */ +class SMantleAnimPackSection : public SCompoundWidget +{ + /** Mantle.Dev.ClipSlotShots sets the section up and scrolls to its clips. */ + friend struct FMantleClipSlotShotAccess; + +public: + SLATE_BEGIN_ARGS(SMantleAnimPackSection) {} + SLATE_END_ARGS() + + void Construct(const FArguments& InArgs); + + /** The input a publish would send now, from the name and the rows. */ + FMantleAnimPackInput MakeInput() const; + + /** Why it cannot be published now, in plain words; empty when it can (worked out when something changed, not every frame). */ + FString Problem() const { return CachedProblem; } + + /** A row's skeleton line: the rig its animation was made on (SkeletonId, a contract id; empty for a rig of the creator's own, SkeletonName), and what happens to it. Pure (tested). */ + static FString RigText(const FString& SkeletonId, const FString& SkeletonName); + +private: + /** What a row's animation is made on, read once per animation. */ + struct FRigInfo + { + /** The UEFN, MetaHuman, UE5 or UE4 Mannequin skeleton: converted to UEFN, no mesh needed. */ + bool bUefn = false; + /** Which of those it is (the contract's id); empty for a rig of the creator's own. */ + FString SkeletonId; + FString SkeletonName; + /** The animation's own preview mesh, the mesh used when none is picked on the row. */ + FString DefaultMeshPath; + }; + + const FRigInfo* RigInfoFor(FName Slot) const; + USkeletalMesh* OwnMeshFor(FName Slot) const; + FString RigLine(FName Slot) const; + /** Play: the clip as players will see it (retargeted onto the UEFN mannequin, or on the row's mesh for a rig of the creator's own). */ + UAnimationAsset* ShowForPreview(UAnimSequence* Clip, USkeletalMesh*& InOutBody); + TSharedRef MakeRowExtra(FName Slot); + void ClipsChanged(); + void Recompute(); + FString StatusLine() const; + FReply OnPublish(); + + TSharedRef Clips = MakeShared(); + TSharedPtr ClipSlots; + /** The retargeted copy on the preview, and why the last Play showed nothing. */ + TStrongObjectPtr Previewed; + FString PreviewError; + + /** What the creator typed for the pack's name. */ + FString PackName; + + /** The mesh picked on a row, by the row's id (a clip on its own rig). */ + TMap MeshPicks; + + /** The rig of each animation shown, by the animation's path. */ + mutable TMap RigCache; + + FMantleVehicleLibraryChoice Choice; + FString CachedProblem; + FText PublishRefusal; +}; diff --git a/Source/MantleEditor/Private/SMantleBuilderFlow.cpp b/Source/MantleEditor/Private/SMantleBuilderFlow.cpp index 863e142c..7e0a9c57 100644 --- a/Source/MantleEditor/Private/SMantleBuilderFlow.cpp +++ b/Source/MantleEditor/Private/SMantleBuilderFlow.cpp @@ -21,7 +21,10 @@ void SMantleBuilderFlow::Construct(const FArguments& InArgs) SNew(SVerticalBox) + SVerticalBox::Slot().AutoHeight().Padding(12.f, 10.f, 12.f, 6.f) [ - MakeStepBar() + SAssignNew(BarBox, SBox) + [ + MakeStepBar() + ] ] + SVerticalBox::Slot().AutoHeight().Padding(16.f, 6.f, 16.f, 2.f) [ @@ -156,6 +159,17 @@ void SMantleBuilderFlow::GoTo(int32 Index) BuildContent(); } +void SMantleBuilderFlow::SetSteps(const TArray& InSteps) +{ + Steps = InSteps; + Current = FMath::Clamp(Current, 0, FMath::Max(0, Steps.Num() - 1)); + if (BarBox.IsValid()) + { + BarBox->SetContent(MakeStepBar()); + } + BuildContent(); +} + void SMantleBuilderFlow::Refresh() { BuildContent(); diff --git a/Source/MantleEditor/Private/SMantleClipSlots.cpp b/Source/MantleEditor/Private/SMantleClipSlots.cpp index 3eeae4a0..333317d0 100644 --- a/Source/MantleEditor/Private/SMantleClipSlots.cpp +++ b/Source/MantleEditor/Private/SMantleClipSlots.cpp @@ -1,18 +1,24 @@ // Copyright Joshua Eger. All Rights Reserved. #include "SMantleClipSlots.h" +#include "MantleAnimPack.h" + #include "MantleCosmeticPreviewViewport.h" +#include "MantleBuiltInMannequin.h" #include "Animation/AnimSequence.h" #include "MantleAnimClipWriter.h" #include "MantleCustomAvatar.h" #include "AssetRegistry/AssetData.h" #include "Engine/SkeletalMesh.h" +#include "Engine/StreamableRenderAsset.h" #include "PropertyCustomizationHelpers.h" #include "Styling/AppStyle.h" #include "Widgets/Input/SButton.h" #include "Widgets/Input/SEditableTextBox.h" #include "Widgets/Layout/SBox.h" +#include "Widgets/SBoxPanel.h" +#include "Widgets/SNullWidget.h" #include "Widgets/Text/STextBlock.h" #define LOCTEXT_NAMESPACE "MantleClipSlots" @@ -191,40 +197,164 @@ TArray FMantleClipSlotsModel::MissingRequired() const return Missing; } +FName FMantleClipSlotsModel::AddFreeSlot(const FString& Name) +{ + FMantleClipSlotDef& Def = Slots.AddDefaulted_GetRef(); + Def.Name = FName(*FString::Printf(TEXT("clip_%d"), NextFreeId++)); + Def.Label = FText::FromString(Name); + Def.MaxClips = 1; + const FName Id = Def.Name; + OnChanged.ExecuteIfBound(); + return Id; +} + +FString FMantleClipSlotsModel::NameOf(const FName Slot) const +{ + const FMantleClipSlotDef* Def = Find(Slot); + return Def ? Def->Label.ToString() : FString(); +} + +void FMantleClipSlotsModel::RenameFreeSlot(const FName Slot, const FString& NewName) +{ + if (FMantleClipSlotDef* Def = Slots.FindByPredicate([Slot](const FMantleClipSlotDef& Each) { return Each.Name == Slot; })) + { + Def->Label = FText::FromString(NewName); + OnChanged.ExecuteIfBound(); + } +} + +void FMantleClipSlotsModel::RemoveFreeSlot(const FName Slot) +{ + Slots.RemoveAll([Slot](const FMantleClipSlotDef& Each) { return Each.Name == Slot; }); + Clips.Remove(Slot); + Speeds.Remove(Slot); + OnChanged.ExecuteIfBound(); +} + // ---- the widget ---- +FText SMantleClipSlots::HelpText(const FMantleClipSlotsModel& InModel) +{ + if (InModel.bFreeNamed) + { + return LOCTEXT("FreeNamedHelp", "Give each clip a name and pick its animation. Scripts play a clip by its name."); + } + const FText Kept = InModel.Conversion == EMantleClipConversion::SampleOnOwnMesh + ? LOCTEXT("ConvertOwn", "Each clip is kept on this model's own skeleton. Only animations made for it are listed.") + : LOCTEXT("ConvertRetarget", "Each clip is retargeted to Mantle's character."); + const bool bAnyRequired = InModel.Slots.ContainsByPredicate([](const FMantleClipSlotDef& Def) { return Def.bRequired; }); + return bAnyRequired ? FText::Format(LOCTEXT("WithRequired", "{0} Slots marked * need a clip."), Kept) : Kept; +} + +FText SMantleClipSlots::BodyNote(const USkeletalMesh* Shown) +{ + return Shown && FMantleBuiltInMannequin::Is(Shown) + ? LOCTEXT("NoBodyMesh", "This project has no UEFN Mannequin mesh, so the preview shows a figure of its bones.") + : FText::GetEmpty(); +} + void SMantleClipSlots::Construct(const FArguments& InArgs) { Model = InArgs._Model; - TSharedRef Box = SNew(SVerticalBox); if (InArgs._ShowPreview) { - Box->AddSlot().AutoHeight().Padding(0, 0, 0, 6) + SAssignNew(Viewport, SMantleCosmeticPreviewViewport); + const auto Line = [this] { return BodyNote(Viewport.IsValid() ? Viewport->GetShownBody() : nullptr); }; + Note = SNew(STextBlock) + .AutoWrapText(true) + .ColorAndOpacity(FSlateColor::UseSubduedForeground()) + .Visibility_Lambda([Line] { return Line().IsEmpty() ? EVisibility::Collapsed : EVisibility::Visible; }) + .Text_Lambda(Line); + } + SAssignNew(Rows, SVerticalBox); + Help = SNew(STextBlock) + .AutoWrapText(true) + .ColorAndOpacity(FSlateColor::UseSubduedForeground()) + .Text_Lambda([this] { return Model.IsValid() ? HelpText(*Model) : FText::GetEmpty(); }); + Arrange(false); + RebuildNow(); +} + +void SMantleClipSlots::Arrange(bool bInWide) +{ + bWide = bInWide; + // The widgets stay; only where they sit changes. Detached first: a widget has one parent. + ChildSlot[SNullWidget::NullWidget]; + TSharedRef List = SNew(SVerticalBox) + + SVerticalBox::Slot().AutoHeight().Padding(0, 0, 0, 6) + [ + Help.ToSharedRef() + ] + + SVerticalBox::Slot().AutoHeight() + [ + Rows.ToSharedRef() + ]; + if (!Viewport.IsValid()) + { + ChildSlot[List]; + } + else if (bWide) + { + // Beside the slots, so the preview takes none of the list's height. + ChildSlot [ - SNew(SBox).HeightOverride(260.0f) + SNew(SHorizontalBox) + + SHorizontalBox::Slot().AutoWidth().VAlign(VAlign_Top).Padding(0, 0, 8, 0) [ - SAssignNew(Viewport, SMantleCosmeticPreviewViewport) + SNew(SBox).WidthOverride(SidePreviewWidth) + [ + SNew(SVerticalBox) + + SVerticalBox::Slot().AutoHeight() + [ + SNew(SBox).HeightOverride(SidePreviewHeight) + [ + Viewport.ToSharedRef() + ] + ] + + SVerticalBox::Slot().AutoHeight().Padding(0, 4, 0, 0) + [ + Note.ToSharedRef() + ] + ] + ] + + SHorizontalBox::Slot().FillWidth(1.0f) + [ + List ] ]; } - Box->AddSlot().AutoHeight().Padding(0, 0, 0, 6) - [ - SNew(STextBlock) - .AutoWrapText(true) - .ColorAndOpacity(FSlateColor::UseSubduedForeground()) - .Text_Lambda([this] - { - return Model.IsValid() && Model->Conversion == EMantleClipConversion::SampleOnOwnMesh - ? LOCTEXT("ConvertOwn", "Each clip is kept on this model's own skeleton. Only animations made for it are listed. Slots marked * need a clip.") - : LOCTEXT("ConvertRetarget", "Each clip is retargeted to Mantle's character. Slots marked * need a clip."); - }) - ]; - Box->AddSlot().AutoHeight() - [ - SAssignNew(Rows, SVerticalBox) - ]; - ChildSlot[Box]; - RebuildNow(); + else + { + ChildSlot + [ + SNew(SVerticalBox) + + SVerticalBox::Slot().AutoHeight().Padding(0, 0, 0, 6) + [ + SNew(SBox).HeightOverride(StackedPreviewHeight) + [ + Viewport.ToSharedRef() + ] + ] + + SVerticalBox::Slot().AutoHeight().Padding(0, 0, 0, 6) + [ + Note.ToSharedRef() + ] + + SVerticalBox::Slot().AutoHeight() + [ + List + ] + ]; + } +} + +void SMantleClipSlots::Tick(const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime) +{ + SCompoundWidget::Tick(AllottedGeometry, InCurrentTime, InDeltaTime); + const float Width = AllottedGeometry.GetLocalSize().X; + if (Viewport.IsValid() && Width > 0.0f && IsWideEnough(Width) != bWide) + { + Arrange(!bWide); + } } void SMantleClipSlots::Refresh() @@ -255,18 +385,50 @@ void SMantleClipSlots::ShowPreviewBody() { Viewport->ShowOverlay(Body, nullptr, TMap(), TMap(), false, Body->GetPathName()); } + ApplyHeldItem(); } void SMantleClipSlots::Preview(UAnimationAsset* Animation) { - if (!Viewport.IsValid() || !Model.IsValid()) + if (Model.IsValid()) + { + ShowClip(Model->PreviewMesh.Get(), Animation); + } +} + +void SMantleClipSlots::PlayClip(UAnimSequence* Clip) +{ + if (!Model.IsValid() || !Model->PreviewAs) { + Preview(Clip); return; } - if (USkeletalMesh* Body = Model->PreviewMesh.Get()) + if (!Viewport.IsValid() || !Clip) { - Viewport->ShowOverlay(Body, nullptr, TMap(), TMap(), false, Body->GetPathName()); - Viewport->SetAnimation(Animation); + return; + } + USkeletalMesh* Body = Model->PreviewMesh.Get(); + UAnimationAsset* Shown = Model->PreviewAs(Clip, Body); + ShowClip(Body, Shown); +} + +void SMantleClipSlots::ShowClip(USkeletalMesh* Body, UAnimationAsset* Animation) +{ + if (!Viewport.IsValid() || !Body) + { + return; + } + Viewport->ShowOverlay(Body, nullptr, TMap(), TMap(), false, Body->GetPathName()); + // The camera stays as it frames the body (ShowOverlay moves it only for another body): a playing clip never resizes the figure. + Viewport->SetAnimation(Animation); + ApplyHeldItem(); +} + +void SMantleClipSlots::ApplyHeldItem() +{ + if (Viewport.IsValid() && Model.IsValid()) + { + Viewport->SetHeldItem(Model->HeldItem.Mesh.Get(), Model->HeldItem.Socket, Model->HeldItem.Local); } } @@ -285,6 +447,26 @@ void SMantleClipSlots::RebuildNow() MakeSlotRow(Def) ]; } + if (Model->bFreeNamed) + { + const TSharedPtr Held = Model; + Rows->AddSlot().AutoHeight().Padding(0, 8, 0, 0) + [ + SNew(SHorizontalBox) + + SHorizontalBox::Slot().AutoWidth() + [ + SNew(SButton) + .Text(LOCTEXT("AddClip", "Add a clip")) + .ToolTipText(LOCTEXT("AddClipTip", "Add a row: a name, and the animation it plays.")) + .OnClicked_Lambda([this, Held] + { + Held->AddFreeSlot(FString()); + Refresh(); + return FReply::Handled(); + }) + ] + ]; + } } TSharedRef SMantleClipSlots::MakePicker(const FName Slot, const int32 Index) @@ -306,6 +488,11 @@ TSharedRef SMantleClipSlots::MakePicker(const FName Slot, const int32 I }) .OnObjectChanged_Lambda([this, Held, Slot, Index](const FAssetData& Asset) { + if (Held->bFreeNamed && Asset.IsValid() && Held->NameOf(Slot).IsEmpty()) + { + // A new row takes its name from the animation (lowercase), until the creator types another. + Held->RenameFreeSlot(Slot, FMantleAnimPack::NameFrom(Asset.AssetName.ToString())); + } Held->SetClip(Slot, Index, Asset.IsValid() ? Asset.ToSoftObjectPath() : FSoftObjectPath()); Refresh(); }); @@ -333,12 +520,12 @@ TSharedRef SMantleClipSlots::MakeSlotRow(const FMantleClipSlotDef& Def) + SHorizontalBox::Slot().AutoWidth().Padding(4, 0, 0, 0) [ SNew(SButton) - .Visibility(bFilled ? EVisibility::Visible : EVisibility::Collapsed) + .Visibility(bFilled && (!Held->bFreeNamed || Viewport.IsValid()) ? EVisibility::Visible : EVisibility::Collapsed) .ToolTipText(LOCTEXT("PlayTip", "Play this clip on the preview.")) .Text(LOCTEXT("Play", "Play")) .OnClicked_Lambda([this, Held, Slot, Index] { - Preview(Held->Load(Slot, Index)); + PlayClip(Held->Load(Slot, Index)); return FReply::Handled(); }) ] @@ -397,20 +584,56 @@ TSharedRef SMantleClipSlots::MakeSlotRow(const FMantleClipSlotDef& Def) One ]; } - TSharedRef Header = SNew(SHorizontalBox) - + SHorizontalBox::Slot().AutoWidth() + TSharedRef Header = SNew(SHorizontalBox); + if (Held->bFreeNamed) + { + // The creator's own name for this clip, and a way to take the row away. + Header->AddSlot().AutoWidth() + [ + SNew(SBox).WidthOverride(160.0f) + [ + SNew(SEditableTextBox) + .HintText(LOCTEXT("ClipNameHint", "clip name")) + .ToolTipText(LOCTEXT("ClipNameTip", "What a script plays this clip as.")) + .Text_Lambda([Held, Slot] { return FText::FromString(Held->NameOf(Slot)); }) + .OnTextCommitted_Lambda([Held, Slot](const FText& Text, ETextCommit::Type) + { + Held->RenameFreeSlot(Slot, Text.ToString().TrimStartAndEnd()); + }) + ] + ]; + Header->AddSlot().FillWidth(1.0f) + [ + SNullWidget::NullWidget + ]; + Header->AddSlot().AutoWidth().Padding(4, 0, 0, 0) + [ + SNew(SButton) + .Text(LOCTEXT("RemoveClip", "Remove")) + .OnClicked_Lambda([this, Held, Slot] + { + Held->RemoveFreeSlot(Slot); + Refresh(); + return FReply::Handled(); + }) + ]; + } + else + { + Header->AddSlot().AutoWidth() [ SNew(STextBlock) .Font(FAppStyle::GetFontStyle("BoldFont")) .Text(Def.bRequired ? FText::Format(LOCTEXT("RequiredLabel", "{0} *"), Def.Label) : Def.Label) - ] - + SHorizontalBox::Slot().FillWidth(1.0f).Padding(8, 0, 0, 0).VAlign(VAlign_Center) + ]; + Header->AddSlot().FillWidth(1.0f).Padding(8, 0, 0, 0).VAlign(VAlign_Center) [ SNew(STextBlock) .ColorAndOpacity(FSlateColor::UseSubduedForeground()) .AutoWrapText(true) .Text(Def.Hint) ]; + } TSharedRef Row = SNew(SVerticalBox) + SVerticalBox::Slot().AutoHeight() [ @@ -420,6 +643,13 @@ TSharedRef SMantleClipSlots::MakeSlotRow(const FMantleClipSlotDef& Def) [ Pickers ]; + if (Held->bFreeNamed && Held->RowExtra) + { + Row->AddSlot().AutoHeight().Padding(0, 2, 0, 0) + [ + Held->RowExtra(Slot) + ]; + } if (Def.bSpeed && Filled > 0) { Row->AddSlot().AutoHeight().Padding(0, 2, 0, 0) diff --git a/Source/MantleEditor/Private/SMantleClipSlots.h b/Source/MantleEditor/Private/SMantleClipSlots.h index 2dd890a9..73e94235 100644 --- a/Source/MantleEditor/Private/SMantleClipSlots.h +++ b/Source/MantleEditor/Private/SMantleClipSlots.h @@ -7,8 +7,10 @@ class SMantleCosmeticPreviewViewport; class SVerticalBox; +class SWidget; class UAnimSequence; class UAnimationAsset; +class UStreamableRenderAsset; class USkeletalMesh; /** @@ -38,6 +40,17 @@ struct FMantleClipSlotDef bool bImpact = false; }; +/** A prop the preview body holds while it plays the clips. */ +struct FMantlePreviewHeldItem +{ + /** A static or skeletal mesh (the owner keeps it alive); none holds nothing. */ + TWeakObjectPtr Mesh; + + /** The bone or socket of the preview body it hangs from, and where it sits from there. */ + FName Socket; + FTransform Local = FTransform::Identity; +}; + /** * The shared Clips control's data (#326, built first; mantle #333's item and consumable clips use it too): the slots, the clips picked in each * (a clip is an animation asset), the speeds typed, and what to filter and preview on. The owner reads it when it publishes. @@ -60,12 +73,21 @@ struct FMantleClipSlotsModel /** The body the preview plays the clips on (the picked avatar, or a mannequin), and the key the camera frames once per change of. */ TWeakObjectPtr PreviewMesh; + /** Optional: held in the preview. Refresh() the control after changing it. */ + FMantlePreviewHeldItem HeldItem; + /** True hides an animation from the pickers (not on the body's skeleton, ...). Unset shows every animation. */ TFunction HideAsset; /** Called after any change. */ FSimpleDelegate OnChanged; + /** + * What the Play button shows for a clip, when it is not the clip as it is on PreviewMesh: returns the animation to loop and may name another + * body for it (InOutBody starts as PreviewMesh). Null result: the body holds its reference pose. Unset: the clip itself on PreviewMesh. + */ + TFunction PreviewAs; + const FMantleClipSlotDef* Find(FName Slot) const; int32 NumClips(FName Slot) const; int32 TotalClips() const; @@ -95,11 +117,37 @@ struct FMantleClipSlotsModel /** The labels of the required slots that hold no clip. */ TArray MissingRequired() const; + + /** + * Free-named mode (an animation pack): there is no fixed slot table. The creator adds rows, each one clip with a name of their own typed in the + * row (the slot's Label); the control draws the name box, a Remove button and an "Add a clip" button. A row's Slots entry is named by an id + * ("clip_1", ...) that stays the same when the row is renamed, so Clips, Speeds and the rest keep following it. Off by default: the fixed-table + * callers are unchanged. + */ + bool bFreeNamed = false; + + /** Free-named mode: a widget drawn under each row (the owner puts what is particular to its clips there, such as the skeleton). Unset: nothing. */ + TFunction(FName)> RowExtra; + + /** Free-named mode: adds an empty row called Name and returns its id. */ + FName AddFreeSlot(const FString& Name); + + /** Free-named mode: the row's name as typed. */ + FString NameOf(FName Slot) const; + + /** Free-named mode: renames a row (the id stays). */ + void RenameFreeSlot(FName Slot, const FString& NewName); + + /** Free-named mode: removes the row and its clip. */ + void RemoveFreeSlot(FName Slot); + + /** The next row id's number. */ + int32 NextFreeId = 1; }; /** * The shared Clips control: a preview of the body, then each slot as a labeled row of pickers (the same browse box and "use selected" arrow - * Build a weapon's picker has, SMantleWeaponBuilder.cpp MakeMeshOrSoundPicker), a play button that shows the clip on the preview, and a speed box + * Build an item's picker has, SMantleWeaponBuilder.cpp MakeMeshOrSoundPicker), a play button that shows the clip on the preview, and a speed box * for a moving slot. A slot with room shows one empty picker more. It edits the model and tells it OnChanged; it publishes nothing. */ class SMantleClipSlots : public SCompoundWidget @@ -119,19 +167,43 @@ class SMantleClipSlots : public SCompoundWidget /** Shows Animation looping on the preview body; null holds the reference pose. */ void Preview(UAnimationAsset* Animation); + /** The Play button: Clip as the model's PreviewAs shows it (itself on the preview body when unset). */ + void PlayClip(UAnimSequence* Clip); + /** Puts the model's preview body on the stage (reference pose, camera framed on it) when it is not there already. */ void ShowPreviewBody(); + /** The line over the rows: what happens to the clips; "Slots marked *" only when a slot is required. Pure (tested). */ + static FText HelpText(const FMantleClipSlotsModel& InModel); + + /** The line under the preview when the body shown has no mesh to draw (Mantle's built-in mannequin, drawn as a figure of its bones); empty otherwise. Pure (tested). */ + static FText BodyNote(const USkeletalMesh* Shown); + + /** The preview stands beside the rows from this width, else above them, low enough that the rows stay in sight. */ + static constexpr float WideFromWidth = 640.0f; + static constexpr float SidePreviewWidth = 260.0f; + static constexpr float SidePreviewHeight = 300.0f; + static constexpr float StackedPreviewHeight = 180.0f; + static bool IsWideEnough(float Width) { return Width >= WideFromWidth; } + + virtual void Tick(const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime) override; + /** The stage, for tests. */ TSharedPtr GetPreviewViewport() const { return Viewport; } private: void RebuildNow(); + void Arrange(bool bInWide); + void ApplyHeldItem(); + void ShowClip(USkeletalMesh* Body, UAnimationAsset* Animation); TSharedRef MakePicker(FName Slot, int32 Index); TSharedRef MakeSlotRow(const FMantleClipSlotDef& Def); TSharedPtr Model; TSharedPtr Rows; + TSharedPtr Help; + TSharedPtr Note; + bool bWide = false; TSharedPtr Viewport; bool bRebuildQueued = false; }; diff --git a/Source/MantleEditor/Private/SMantleCustomAvatarSection.h b/Source/MantleEditor/Private/SMantleCustomAvatarSection.h index 614c007a..0d7f5408 100644 --- a/Source/MantleEditor/Private/SMantleCustomAvatarSection.h +++ b/Source/MantleEditor/Private/SMantleCustomAvatarSection.h @@ -51,6 +51,9 @@ struct FMantleCustomAvatarDraft */ class SMantleCustomAvatarSection : public SCompoundWidget { + /** Mantle.Dev.ClipSlotShots sets the section up and scrolls to its clips. */ + friend struct FMantleClipSlotShotAccess; + public: DECLARE_DELEGATE(FOnSizeChanged); diff --git a/Source/MantleEditor/Private/SMantleWeaponBuilder.cpp b/Source/MantleEditor/Private/SMantleWeaponBuilder.cpp index f83319ed..63cb62f0 100644 --- a/Source/MantleEditor/Private/SMantleWeaponBuilder.cpp +++ b/Source/MantleEditor/Private/SMantleWeaponBuilder.cpp @@ -47,6 +47,10 @@ #include "MantleModelThumbnail.h" #include "MantleThumbnailStore.h" #include "SMantleThumbnailSection.h" +#include "MantleItemClips.h" +#include "MantleConsumableEffect.h" +#include "SMantleClipSlots.h" +#include "Animation/AnimSequence.h" #define LOCTEXT_NAMESPACE "MantleWeaponBuilder" @@ -59,7 +63,7 @@ namespace MantleWeaponBuilderPanelPrivate { return SNew(SDockTab) .TabRole(ETabRole::NomadTab) - .Label(LOCTEXT("TabLabel", "Build a weapon")) + .Label(LOCTEXT("TabLabel", "Build an item")) [ SNew(SMantleWeaponBuilder) ]; @@ -103,6 +107,7 @@ namespace MantleWeaponBuilderPanelPrivate ? LOCTEXT("DeliveryBeamGun", "Beam (laser, flamethrower)") : LOCTEXT("DeliveryBeam", "Held beam"); case EMantleWeaponSourceDelivery::Use: return LOCTEXT("DeliveryUse", "Use it up"); + case EMantleWeaponSourceDelivery::Signal: return LOCTEXT("DeliverySignal", "Your script decides"); } return FText::GetEmpty(); } @@ -252,6 +257,7 @@ namespace MantleWeaponBuilderPanelPrivate case EMantleWeaponHold::Shield: return LOCTEXT("BlurbShield", "A left-hand shield for blocking and bashing."); case EMantleWeaponHold::Throwable: return LOCTEXT("BlurbThrowable", "A one-handed item thrown at a target."); case EMantleWeaponHold::Consumable: return LOCTEXT("BlurbConsumable", "A potion, medkit or snack the character drinks, eats or uses up to heal."); + case EMantleWeaponHold::Item: return LOCTEXT("BlurbItem", "Anything the character holds and uses; your place's script decides what using it does."); case EMantleWeaponHold::Count: break; } return FText::GetEmpty(); @@ -810,8 +816,8 @@ namespace MantleWeaponBuilderPanelPrivate void FMantleWeaponBuilderPanel::RegisterTab() { FGlobalTabmanager::Get()->RegisterNomadTabSpawner(TabName, FOnSpawnTab::CreateStatic(&MantleWeaponBuilderPanelPrivate::SpawnWeaponBuilderTab)) - .SetDisplayName(LOCTEXT("TabTitle", "Build a weapon")) - .SetTooltipText(LOCTEXT("TabTooltip", "Turn a 3D model into a weapon players can use.")) + .SetDisplayName(LOCTEXT("TabTitle", "Build an item")) + .SetTooltipText(LOCTEXT("TabTooltip", "Turn a 3D model into an item players can use: a weapon, a consumable or a usable item.")) .SetMenuType(ETabSpawnerMenuType::Hidden); } @@ -844,7 +850,7 @@ void SMantleWeaponBuilder::Construct(const FArguments& InArgs) SAssignNew(Flow, SMantleBuilderFlow) .Steps(MakeSteps()) - .FinishLabel(LOCTEXT("CreateWeapon", "Create weapon")) + .FinishLabel(LOCTEXT("CreateItem", "Create item")) .OnFinish(FSimpleDelegate::CreateSP(this, &SMantleWeaponBuilder::Create)); ChildSlot @@ -864,26 +870,36 @@ SMantleWeaponBuilder::~SMantleWeaponBuilder() TArray SMantleWeaponBuilder::MakeSteps() { TArray Steps; + StepsType = MantleWeaponBuilderLogic::ItemTypeOf(Working->Hold); + const bool bWeapon = StepsType == MantleWeaponBuilderLogic::EItemType::Weapon; + const bool bUsableItem = StepsType == MantleWeaponBuilderLogic::EItemType::Item; { FMantleBuilderStep& Step = Steps.AddDefaulted_GetRef(); - Step.Title = LOCTEXT("StepKind", "What kind of weapon?"); - Step.Help = LOCTEXT("StepKindHelp", "Pick the closest match. This decides how the character holds your weapon. Then give it a name."); - Step.MakeContent = [this] { return MakeKindStep(); }; + Step.Title = LOCTEXT("StepType", "What kind of item?"); + Step.Help = LOCTEXT("StepTypeHelp", "Pick what you are making and give it a name. The next screens are the ones that kind of item needs."); + Step.MakeContent = [this] { return MakeTypeStep(); }; Step.CanContinue = [this](FText& OutWhyNot) { if (Working->DisplayName.TrimStartAndEnd().IsEmpty()) { - OutWhyNot = LOCTEXT("NeedName", "Give your weapon a name first."); + OutWhyNot = LOCTEXT("NeedName", "Give your item a name first."); return false; } return true; }; } + if (bWeapon) + { + FMantleBuilderStep& Step = Steps.AddDefaulted_GetRef(); + Step.Title = LOCTEXT("StepKind", "What kind of weapon?"); + Step.Help = LOCTEXT("StepKindHelp", "Pick the closest match. This decides how the character holds your weapon."); + Step.MakeContent = [this] { return MakeKindStep(); }; + } { FMantleBuilderStep& Step = Steps.AddDefaulted_GetRef(); Step.Title = LOCTEXT("StepModel", "Choose the 3D model"); - Step.Help = LOCTEXT("StepModelHelp", "Pick the model you imported. Every weapon needs a 3D model."); + Step.Help = LOCTEXT("StepModelHelp", "Pick the model you imported. Every item needs a 3D model."); Step.MakeContent = [this] { return MakeModelStep(); }; Step.CanContinue = [this](FText& OutWhyNot) { @@ -898,30 +914,49 @@ TArray SMantleWeaponBuilder::MakeSteps() { FMantleBuilderStep& Step = Steps.AddDefaulted_GetRef(); Step.Title = LOCTEXT("StepSize", "Size and direction"); - Step.Help = LOCTEXT("StepSizeHelp", "Check that this weapon model is the right size and faces the right direction for its hold. The gray figure shows how it fits beside a character."); + Step.Help = LOCTEXT("StepSizeHelp", "Check that the model is the right size and faces the right direction. The gray figure shows how it fits beside a character."); Step.OnEnter = [this] { Refit(); }; Step.MakeContent = [this] { return MakeSizeStep(); }; } { FMantleBuilderStep& Step = Steps.AddDefaulted_GetRef(); Step.Title = LOCTEXT("StepPoints", "Place hands and action points"); - Step.Help = LOCTEXT("StepPointsHelp", "Choose a point in the list, then drag it in the picture onto the right place on your model. Hand points mark the middle of each palm. Other points mark where an aim, shot, swing, cast, arrow or shield action starts."); + Step.Help = bWeapon + ? LOCTEXT("StepPointsHelp", "Choose a point in the list, then drag it in the picture onto the right place on your model. Hand points mark the middle of each palm. Other points mark where an aim, shot, swing, cast, arrow or shield action starts.") + : LOCTEXT("StepGripHelp", "Choose the point in the list, then drag it in the picture to where the middle of the palm holds your model."); Step.OnEnter = [this] { Refit(); }; Step.MakeContent = [this] { return MakePointsStep(); }; Step.CanContinue = [this](FText& OutWhyNot) { return HasAllRequiredPoints(OutWhyNot); }; } + // A usable item has no attack or effect of its own, so nothing to set. + if (!bUsableItem) { FMantleBuilderStep& Step = Steps.AddDefaulted_GetRef(); - Step.Title = LOCTEXT("StepTuning", "Attack and effect"); - Step.Help = LOCTEXT("StepTuningHelp", "These settings start with sensible values for this kind of weapon. Change them if you like; each number stays inside its allowed range."); + Step.Title = bWeapon ? LOCTEXT("StepTuning", "Attack and effect") : LOCTEXT("StepUse", "Use and effect"); + Step.Help = bWeapon + ? LOCTEXT("StepTuningHelp", "These settings start with sensible values for this kind of weapon. Change them if you like; each number stays inside its allowed range.") + : LOCTEXT("StepUseHelp", "What using it does. The settings start with sensible values; change them if you like."); Step.MakeContent = [this] { return MakeTuningStep(); }; } + if (bWeapon) { FMantleBuilderStep& Step = Steps.AddDefaulted_GetRef(); Step.Title = LOCTEXT("StepPartsSound", "Parts and sound"); Step.Help = LOCTEXT("StepPartsSoundHelp", "Add moving magazine, round or arrow pieces, fixed details and sounds. Each choice is saved with this weapon."); Step.MakeContent = [this] { return MakePartsAndSoundStep(); }; } + else + { + FMantleBuilderStep& Step = Steps.AddDefaulted_GetRef(); + Step.Title = LOCTEXT("StepAnimations", "Animations"); + Step.Help = LOCTEXT("StepAnimationsHelp", "Every slot is optional: an empty one plays Mantle's own animation. Press Play to see a clip as players will."); + Step.MakeContent = [this] { return MakeAnimationsStep(); }; + Step.CanContinue = [this](FText& OutWhyNot) + { + OutWhyNot = FText::FromString(ClipProblems); + return ClipProblems.IsEmpty(); + }; + } { FMantleBuilderStep& Step = Steps.AddDefaulted_GetRef(); Step.Title = FMantleThumbnailText::Heading(); @@ -931,7 +966,7 @@ TArray SMantleWeaponBuilder::MakeSteps() { FMantleBuilderStep& Step = Steps.AddDefaulted_GetRef(); Step.Title = LOCTEXT("StepCreate", "Create"); - Step.Help = LOCTEXT("StepCreateHelp", "This is what you chose. Press Create weapon to save it. You can go back to any step first."); + Step.Help = LOCTEXT("StepCreateHelp", "This is what you chose. Press Create item to save it. You can go back to any step first."); Step.MakeContent = [this] { return MakeCreateStep(); }; } return Steps; @@ -969,6 +1004,18 @@ void SMantleWeaponBuilder::SetHold(EMantleWeaponHold Hold) return; } Working->Hold = Hold; + if (ItemTypeOf(Hold) == EItemType::Weapon) + { + LastWeaponHold = Hold; + } + if (!TakesClips(Hold)) + { + // A weapon keeps Mantle's animations: clips picked for another kind of item do not follow it (the document refuses them). + Working->ClipHold.Reset(); + Working->ClipUse.Reset(); + Working->ClipEquip.Reset(); + Working->ClipPutAway.Reset(); + } Kind->SetHold(ToFitHold(Hold)); TSet ValidPointRoles; for (const FMantleBuilderPointRole& Role : Kind->GetRoles()) @@ -1041,6 +1088,24 @@ void SMantleWeaponBuilder::SetHold(EMantleWeaponHold Hold) { Working->DisplayName = DefaultName(Hold); } + RefreshStepsForType(); +} + +void SMantleWeaponBuilder::SetItemType(MantleWeaponBuilderLogic::EItemType Type) +{ + using namespace MantleWeaponBuilderLogic; + if (ItemTypeOf(Working->Hold) != Type) + { + SetHold(Type == EItemType::Consumable ? EMantleWeaponHold::Consumable : Type == EItemType::Item ? EMantleWeaponHold::Item : LastWeaponHold); + } +} + +void SMantleWeaponBuilder::RefreshStepsForType() +{ + if (Flow.IsValid() && MantleWeaponBuilderLogic::ItemTypeOf(Working->Hold) != StepsType) + { + Flow->SetSteps(MakeSteps()); + } } void SMantleWeaponBuilder::LoadSourceAsset(UMantleWeaponSource* Source) @@ -1062,7 +1127,7 @@ void SMantleWeaponBuilder::LoadSourceAsset(UMantleWeaponSource* Source) } if (EditSignature(*Working) != SourceBaselineSignature && FMessageDialog::Open(EAppMsgType::YesNo, - LOCTEXT("DiscardWeaponEdits", "This weapon has changes that have not been created yet. Replace them with the saved weapon you selected?")) != EAppReturnType::Yes) + LOCTEXT("DiscardItemEdits", "This item has changes that have not been created yet. Replace them with the saved item you selected?")) != EAppReturnType::Yes) { return; } @@ -1087,9 +1152,20 @@ void SMantleWeaponBuilder::LoadSourceAsset(UMantleWeaponSource* Source) Kind->SetHold(ToFitHold(Working->Hold)); Kind->SetFlipRotation(Working->FlipRotation); Kind->SetScaleOverride(Working->bScaleOverridden ? Working->FitScale : 0.f); + if (ItemTypeOf(Working->Hold) == EItemType::Weapon) + { + LastWeaponHold = Working->Hold; + } if (Flow.IsValid()) { - Flow->Refresh(); + if (ItemTypeOf(Working->Hold) != StepsType) + { + Flow->SetSteps(MakeSteps()); + } + else + { + Flow->Refresh(); + } } } @@ -1113,6 +1189,14 @@ void SMantleWeaponBuilder::TurnFit(const FQuat& Turn) { Working->FlipRotation = (Turn * Working->FlipRotation).GetNormalized(); Refit(); + // A quarter turn swings a consumable or a usable item out of the close-up the screen opens with: frame it again, with the figure. + if (MantleWeaponBuilderLogic::ItemTypeOf(Working->Hold) != MantleWeaponBuilderLogic::EItemType::Weapon) + { + if (const TSharedPtr Viewport = SizeViewport.Pin()) + { + Viewport->SetMesh(LoadModel()); + } + } } void SMantleWeaponBuilder::Refit() @@ -1212,7 +1296,7 @@ FText SMantleWeaponBuilder::SummaryText() const const FMantleWeaponTuning& T = Working->Tuning; TArray Lines; Lines.Add(FString::Printf(TEXT("Name: %s"), *Working->DisplayName.TrimStartAndEnd())); - Lines.Add(FString::Printf(TEXT("Weapon type: %s"), *HoldLabel(Working->Hold).ToString())); + Lines.Add(FString::Printf(TEXT("%s: %s"), ItemTypeOf(Working->Hold) == EItemType::Weapon ? TEXT("Weapon type") : TEXT("Item type"), *HoldLabel(Working->Hold).ToString())); if (Working->Model.IsNull()) { Lines.Add(TEXT("3D model: none selected")); @@ -1228,21 +1312,40 @@ FText SMantleWeaponBuilder::SummaryText() const const auto SourceDelivery = static_cast(static_cast(Delivery) + 1); const EMantleWeaponDocResource Resource = EffectiveResource(*Working); const auto SourceResource = static_cast(static_cast(Resource) + 1); - if (Working->Hold == EMantleWeaponHold::Consumable) + if (TakesClips(Working->Hold)) { - const FMantleWeaponSourceConsumable& C = Working->Consumable; - Lines.Add(FString::Printf(TEXT("Used by: %s"), C.Style == EMantleWeaponSourceUseStyle::EatDrink ? TEXT("eating or drinking") : TEXT("using it (lift and crush)"))); - if (C.Effect == EMantleWeaponSourceConsumableEffect::Heal) + if (Working->Hold == EMantleWeaponHold::Consumable) { - Lines.Add(FString::Printf(TEXT("Heals: %.0f%s; uses: %d"), C.Heal, C.HealSeconds > 0.f ? *FString::Printf(TEXT(" over %.1f seconds"), C.HealSeconds) : TEXT(""), C.Uses)); + const FMantleWeaponSourceConsumable& C = Working->Consumable; + Lines.Add(FString::Printf(TEXT("Used by: %s"), !Working->ClipUse.IsNull() ? TEXT("your own Use animation") + : C.Style == EMantleWeaponSourceUseStyle::EatDrink ? TEXT("eating or drinking") : TEXT("using it (lift and crush)"))); + if (C.Effect == EMantleWeaponSourceConsumableEffect::Heal) + { + Lines.Add(FString::Printf(TEXT("Heals: %.0f%s; uses: %d"), C.Heal, C.HealSeconds > 0.f ? *FString::Printf(TEXT(" over %.1f seconds"), C.HealSeconds) : TEXT(""), C.Uses)); + } + else if (C.Effect == EMantleWeaponSourceConsumableEffect::None) + { + Lines.Add(FString::Printf(TEXT("Effect: none of its own (a script does it); uses: %d"), C.Uses)); + } + else + { + const TCHAR* const What = C.Effect == EMantleWeaponSourceConsumableEffect::Stamina ? TEXT("stamina") : C.Effect == EMantleWeaponSourceConsumableEffect::Hunger ? TEXT("hunger") : TEXT("thirst"); + Lines.Add(FString::Printf(TEXT("Gives %s: %.0f; uses: %d"), What, C.Amount, C.Uses)); + } + Lines.Add(FString::Printf(TEXT("Use time: %s; wait between uses: %.1f seconds; %s"), + C.bOverrideUseSeconds ? *FString::Printf(TEXT("%.1f seconds"), C.UseSeconds) : TEXT("the animation's own length"), C.CooldownSeconds, + C.bMoveWhileUsing ? TEXT("can walk while using") : TEXT("stands still while using"))); } else { - Lines.Add(FString::Printf(TEXT("Effect: none of its own (a script does it); uses: %d"), C.Uses)); + Lines.Add(TEXT("Using it: your place's script decides what happens")); } - Lines.Add(FString::Printf(TEXT("Use time: %s; wait between uses: %.1f seconds; %s"), - C.bOverrideUseSeconds ? *FString::Printf(TEXT("%.1f seconds"), C.UseSeconds) : TEXT("the animation's own length"), C.CooldownSeconds, - C.bMoveWhileUsing ? TEXT("can walk while using") : TEXT("stands still while using"))); + TArray Own; + if (!Working->ClipHold.IsNull()) Own.Add(TEXT("Hold")); + if (!Working->ClipUse.IsNull()) Own.Add(TEXT("Use")); + if (!Working->ClipEquip.IsNull()) Own.Add(TEXT("Equip")); + if (!Working->ClipPutAway.IsNull()) Own.Add(TEXT("Put away")); + Lines.Add(Own.IsEmpty() ? FString(TEXT("Animations: Mantle's own")) : FString::Printf(TEXT("Your animations: %s"), *FString::Join(Own, TEXT(", ")))); return FText::FromString(FString::Join(Lines, TEXT("\n"))); } Lines.Add(FString::Printf(TEXT("Attack: %s; resource: %s"), *DeliveryLabel(SourceDelivery, IsFirearm(Working->Hold)).ToString(), *ResourceLabel(SourceResource).ToString())); @@ -1365,27 +1468,72 @@ TSharedRef SMantleWeaponBuilder::MakeHoldCard(EMantleWeaponHold Hold) ]; } -TSharedRef SMantleWeaponBuilder::MakeKindStep() +TSharedRef SMantleWeaponBuilder::MakeTypeCard(MantleWeaponBuilderLogic::EItemType Type) +{ + using namespace MantleWeaponBuilderLogic; + const FText Title = Type == EItemType::Weapon ? LOCTEXT("TypeWeapon", "Weapon") + : Type == EItemType::Consumable ? LOCTEXT("TypeConsumable", "Consumable") : LOCTEXT("TypeItem", "Usable item"); + const FText Blurb = Type == EItemType::Weapon + ? LOCTEXT("TypeWeaponBlurb", "A gun, bow, blade, staff, shield or throwable. It attacks and plays Mantle's own animations.") + : Type == EItemType::Consumable + ? LOCTEXT("TypeConsumableBlurb", "A potion, medkit or snack that is used up. It can have an effect and bring your own animations.") + : LOCTEXT("TypeItemBlurb", "Anything else the character holds and uses. Your place's script decides what using it does. It can bring your own animations."); + return SNew(SBox) + .WidthOverride(250.f) + .HeightOverride(110.f) + .Padding(FMargin(0.f, 0.f, 8.f, 8.f)) + [ + SNew(SBorder) + .BorderImage(FAppStyle::GetBrush("WhiteBrush")) + .BorderBackgroundColor_Lambda([this, Type] + { + return FSlateColor(ItemTypeOf(Working->Hold) == Type ? FLinearColor(0.10f, 0.40f, 0.80f) : FLinearColor(0.10f, 0.10f, 0.10f)); + }) + .Padding(2.f) + [ + SNew(SButton) + .HAlign(HAlign_Fill) + .VAlign(VAlign_Fill) + .OnClicked_Lambda([this, Type] + { + SetItemType(Type); + return FReply::Handled(); + }) + [ + SNew(SVerticalBox) + + SVerticalBox::Slot().AutoHeight() + [ + SNew(STextBlock) + .Font(FAppStyle::GetFontStyle("DetailsView.CategoryFontStyle")) + .Text(Title) + ] + + SVerticalBox::Slot().FillHeight(1.f).Padding(0.f, 4.f, 0.f, 0.f) + [ + SNew(STextBlock) + .AutoWrapText(true) + .ColorAndOpacity(FSlateColor::UseSubduedForeground()) + .Text(Blurb) + ] + ] + ] + ]; +} + +TSharedRef SMantleWeaponBuilder::MakeTypeStep() { + using namespace MantleWeaponBuilderLogic; using namespace MantleWeaponBuilderPanelPrivate; TSharedRef Cards = SNew(SWrapBox).UseAllottedSize(true); - // The guns first, then the rest. - const EMantleWeaponHold Order[] = { - EMantleWeaponHold::Pistol, EMantleWeaponHold::Rifle, - EMantleWeaponHold::Revolver, EMantleWeaponHold::Smg, EMantleWeaponHold::Dmr, - EMantleWeaponHold::PumpShotgun, EMantleWeaponHold::BoltSniper, EMantleWeaponHold::Lmg, - EMantleWeaponHold::Melee1h, EMantleWeaponHold::Melee2h, EMantleWeaponHold::Spear, EMantleWeaponHold::Staff, - EMantleWeaponHold::Bow, EMantleWeaponHold::Unarmed, EMantleWeaponHold::Shield, EMantleWeaponHold::Throwable, EMantleWeaponHold::Consumable, }; - for (const EMantleWeaponHold Hold : Order) + for (const EItemType Type : { EItemType::Weapon, EItemType::Consumable, EItemType::Item }) { - Cards->AddSlot()[MakeHoldCard(Hold)]; + Cards->AddSlot()[MakeTypeCard(Type)]; } return SNew(SScrollBox) + SScrollBox::Slot().Padding(0.f, 0.f, 0.f, 12.f) [ - MakeRow(LOCTEXT("OpenSavedWeapon", "Open a saved weapon to edit"), - LOCTEXT("OpenSavedWeaponTip", "Choose a weapon you made earlier to reopen its saved points, size, attack settings, details and sounds."), + MakeRow(LOCTEXT("OpenSavedItem", "Open a saved item to edit"), + LOCTEXT("OpenSavedItemTip", "Choose an item you made earlier to reopen its saved points, size, settings, details, sounds and animations."), SNew(SObjectPropertyEntryBox) .AllowedClass(UMantleWeaponSource::StaticClass()) .DisplayThumbnail(false) @@ -1410,9 +1558,9 @@ TSharedRef SMantleWeaponBuilder::MakeKindStep() ] + SScrollBox::Slot().Padding(0.f, 12.f, 0.f, 0.f) [ - MakeRow(LOCTEXT("NameLabel", "Name your weapon"), LOCTEXT("NameTip", "Players see this name."), + MakeRow(LOCTEXT("NameLabel", "Name your item"), LOCTEXT("NameTip", "Players see this name."), SNew(SEditableTextBox) - .HintText(LOCTEXT("NameHint", "Name your weapon")) + .HintText(LOCTEXT("NameHint", "Name your item")) .Text_Lambda([this] { return FText::FromString(Working->DisplayName); }) .OnTextChanged_Lambda([this](const FText& NewText) { @@ -1422,6 +1570,78 @@ TSharedRef SMantleWeaponBuilder::MakeKindStep() ]; } +TSharedRef SMantleWeaponBuilder::MakeKindStep() +{ + TSharedRef Cards = SNew(SWrapBox).UseAllottedSize(true); + // The guns first, then the rest. + const EMantleWeaponHold Order[] = { + EMantleWeaponHold::Pistol, EMantleWeaponHold::Rifle, + EMantleWeaponHold::Revolver, EMantleWeaponHold::Smg, EMantleWeaponHold::Dmr, + EMantleWeaponHold::PumpShotgun, EMantleWeaponHold::BoltSniper, EMantleWeaponHold::Lmg, + EMantleWeaponHold::Melee1h, EMantleWeaponHold::Melee2h, EMantleWeaponHold::Spear, EMantleWeaponHold::Staff, + EMantleWeaponHold::Bow, EMantleWeaponHold::Unarmed, EMantleWeaponHold::Shield, EMantleWeaponHold::Throwable, }; + for (const EMantleWeaponHold Hold : Order) + { + Cards->AddSlot()[MakeHoldCard(Hold)]; + } + + return SNew(SScrollBox) + + SScrollBox::Slot() + [ + Cards + ]; +} + +TSharedRef SMantleWeaponBuilder::MakeAnimationsStep() +{ + using namespace MantleWeaponBuilderPanelPrivate; + ClipsModel = FMantleItemClips::MakeModel(); + FMantleItemClips::ReadSource(*ClipsModel, *Working); + // The item in the preview's hand, where the game holds it, placed anew for each body the preview shows. + PreviewedItem.Reset(LoadModel()); + ClipsModel->HeldItem = FMantleItemClips::HeldItem(*Working, PreviewedItem.Get(), ClipsModel->PreviewMesh.Get()); + ClipPreviewError.Reset(); + // Checked when the screen opens and after each pick, not every frame the Next button asks. + ClipProblems = FMantleItemClips::Problems(*ClipsModel); + ClipEffectLine = FMantleConsumableEffect::Line(*Working); + ClipsModel->OnChanged.BindSPLambda(this, [this] + { + FMantleItemClips::WriteSource(*ClipsModel, *Working); + ClipProblems = FMantleItemClips::Problems(*ClipsModel); + ClipEffectLine = FMantleConsumableEffect::Line(*Working); + ClipPreviewError.Reset(); + // The screen draws again on its own body. + ClipsModel->HeldItem = FMantleItemClips::HeldItem(*Working, PreviewedItem.Get(), ClipsModel->PreviewMesh.Get()); + }); + ClipsModel->PreviewAs = [this](UAnimSequence* Clip, USkeletalMesh*& InOutBody) -> UAnimationAsset* + { + UAnimationAsset* Shown = FMantleItemClips::MakePreview(Clip, InOutBody, PreviewedClip, ClipPreviewError); + ClipsModel->HeldItem = FMantleItemClips::HeldItem(*Working, PreviewedItem.Get(), InOutBody); + return Shown; + }; + const TSharedRef Slots = SNew(SMantleClipSlots).Model(ClipsModel); + ClipsView = Slots; + return SNew(SScrollBox) + + SScrollBox::Slot() + [ + Slots + ] + + SScrollBox::Slot().Padding(0.f, 6.f, 0.f, 0.f) + [ + SNew(STextBlock) + .AutoWrapText(true) + .Visibility_Lambda([this] { return ClipEffectLine.IsEmpty() ? EVisibility::Collapsed : EVisibility::Visible; }) + .Text_Lambda([this] { return ClipEffectLine; }) + ] + + SScrollBox::Slot().Padding(0.f, 6.f) + [ + SNew(STextBlock) + .AutoWrapText(true) + .ColorAndOpacity(FSlateColor(WarnColor())) + .Text_Lambda([this] { return FText::FromString(ClipPreviewError); }) + ]; +} + TSharedRef SMantleWeaponBuilder::MakeModelStep() { return SNew(SVerticalBox) @@ -1451,7 +1671,7 @@ TSharedRef SMantleWeaponBuilder::MakeModelStep() .ColorAndOpacity(FSlateColor::UseSubduedForeground()) .Text_Lambda([this] { - return LOCTEXT("ModelHint", "Click the box and pick your weapon model from the list, or drag it in from your project's files."); + return LOCTEXT("ModelHint", "Click the box and pick your model from the list, or drag it in from your project's files."); }) ]; } @@ -1468,7 +1688,7 @@ TSharedRef SMantleWeaponBuilder::MakeSizeStep() [ SNew(STextBlock) .AutoWrapText(true) - .Text(LOCTEXT("SizeNeedsModel", "Choose your weapon's 3D model on the previous page first; its size is set from the model.")) + .Text(LOCTEXT("SizeNeedsModel", "Choose the 3D model on the previous page first; its size is set from the model.")) ]; } TSharedRef Viewport = MakeViewport(); @@ -1500,12 +1720,12 @@ TSharedRef SMantleWeaponBuilder::MakeSizeStep() SNew(STextBlock) .Text_Lambda([this] { - return FText::Format(LOCTEXT("LengthNow", "The longest side of this weapon model is about {0} cm."), FText::AsNumber(FMath::RoundToInt(ModelLengthCm()))); + return FText::Format(LOCTEXT("LengthNow", "The longest side of this model is about {0} cm."), FText::AsNumber(FMath::RoundToInt(ModelLengthCm()))); }) ] + SVerticalBox::Slot().AutoHeight() [ - MakeRow(LOCTEXT("SizeLabel", "Model size (1 = as imported)"), LOCTEXT("SizeTip", "Makes the weapon model bigger or smaller. The gray figure shows how it fits beside a character."), + MakeRow(LOCTEXT("SizeLabel", "Model size (1 = as imported)"), LOCTEXT("SizeTip", "Makes the model bigger or smaller. The gray figure shows how it fits beside a character."), SNew(SHorizontalBox) + SHorizontalBox::Slot().FillWidth(1.f) [ @@ -1545,9 +1765,19 @@ TSharedRef SMantleWeaponBuilder::MakeSizeStep() return FReply::Handled(); }) ] + + SHorizontalBox::Slot().AutoWidth() + [ + // A consumable and a usable item may stand any way round; a weapon's fit only ever gets front or top wrong. + SNew(SBox) + .Visibility_Lambda([this] { return MantleWeaponBuilderLogic::ItemTypeOf(Working->Hold) != MantleWeaponBuilderLogic::EItemType::Weapon ? EVisibility::Visible : EVisibility::Collapsed; }) + [ + MakeQuarterTurnButtons() + ] + ] + SHorizontalBox::Slot().AutoWidth().Padding(0.f, 0.f, 8.f, 0.f) [ SNew(SButton) + .Visibility_Lambda([this] { return MantleWeaponBuilderLogic::ItemTypeOf(Working->Hold) == MantleWeaponBuilderLogic::EItemType::Weapon ? EVisibility::Visible : EVisibility::Collapsed; }) .Text(LOCTEXT("FlipFrontBack", "Flip front and back")) .ToolTipText(LOCTEXT("FlipFrontBackTip", "Turn the model around if its front and back face the wrong way for this hold.")) .OnClicked_Lambda([this] @@ -1560,6 +1790,7 @@ TSharedRef SMantleWeaponBuilder::MakeSizeStep() + SHorizontalBox::Slot().AutoWidth() [ SNew(SButton) + .Visibility_Lambda([this] { return MantleWeaponBuilderLogic::ItemTypeOf(Working->Hold) == MantleWeaponBuilderLogic::EItemType::Weapon ? EVisibility::Visible : EVisibility::Collapsed; }) .Text(LOCTEXT("TurnUpsideDown", "Turn upside down")) .ToolTipText(LOCTEXT("TurnUpsideDownTip", "Turn the model over if its grip points away from the hand.")) .OnClicked_Lambda([this] @@ -1624,6 +1855,35 @@ TSharedRef SMantleWeaponBuilder::MakeSizeStep() ]; } +TSharedRef SMantleWeaponBuilder::MakeQuarterTurnButtons() +{ + using namespace MantleWeaponBuilderLogic; + auto Button = [this](const FText& Label, const FText& Tip, const EQuarterTurn Turn) -> TSharedRef + { + return SNew(SButton) + .Text(Label) + .ToolTipText(Tip) + .OnClicked_Lambda([this, Turn] + { + TurnFit(QuarterTurn(Turn)); + return FReply::Handled(); + }); + }; + return SNew(SHorizontalBox) + + SHorizontalBox::Slot().AutoWidth().Padding(0.f, 0.f, 8.f, 0.f) + [ + Button(LOCTEXT("TurnAround", "Turn around"), LOCTEXT("TurnAroundTip", "Turn the model a quarter turn about its up direction."), EQuarterTurn::Around) + ] + + SHorizontalBox::Slot().AutoWidth().Padding(0.f, 0.f, 8.f, 0.f) + [ + Button(LOCTEXT("TipForward", "Tip forward"), LOCTEXT("TipForwardTip", "Tip the model a quarter turn, its top toward the front."), EQuarterTurn::Forward) + ] + + SHorizontalBox::Slot().AutoWidth() + [ + Button(LOCTEXT("TipSideways", "Tip sideways"), LOCTEXT("TipSidewaysTip", "Tip the model a quarter turn to the side."), EQuarterTurn::Sideways) + ]; +} + TSharedRef SMantleWeaponBuilder::MakePointsStep() { using namespace MantleWeaponBuilderPanelPrivate; @@ -1787,21 +2047,44 @@ TSharedRef SMantleWeaponBuilder::MakeTuningStep() }; const TArray> Effects = { { EMantleWeaponSourceConsumableEffect::Heal, LOCTEXT("EffectHeal", "Heal") }, + { EMantleWeaponSourceConsumableEffect::Stamina, LOCTEXT("EffectStamina", "Stamina") }, + { EMantleWeaponSourceConsumableEffect::Hunger, LOCTEXT("EffectHunger", "Hunger") }, + { EMantleWeaponSourceConsumableEffect::Thirst, LOCTEXT("EffectThirst", "Thirst") }, { EMantleWeaponSourceConsumableEffect::None, LOCTEXT("EffectNone", "Nothing of its own (a script does it)") }, }; const TFunction ShowHeal = [this] { return Working->Consumable.Effect == EMantleWeaponSourceConsumableEffect::Heal ? EVisibility::Visible : EVisibility::Collapsed; }; + const TFunction ShowAmount = [this] + { + const EMantleWeaponSourceConsumableEffect Effect = Working->Consumable.Effect; + return Effect != EMantleWeaponSourceConsumableEffect::Heal && Effect != EMantleWeaponSourceConsumableEffect::None ? EVisibility::Visible : EVisibility::Collapsed; + }; return SNew(SScrollBox) + SScrollBox::Slot().Padding(0.f, 6.f) [ SNew(SVerticalBox) - + SVerticalBox::Slot().AutoHeight()[MakeRow(LOCTEXT("UseStyle", "How it is used"), - LOCTEXT("UseStyleTip", "Eat or drink plays the drinking animation of whatever the character holds. Use plays the lift-and-crush animation, a good fit for a medkit."), - MakeChoiceControl(Styles, [this] { return Working->Consumable.Style; }, [this](EMantleWeaponSourceUseStyle V) { Working->Consumable.Style = V; }))] + + SVerticalBox::Slot().AutoHeight() + [ + // The style only picks Mantle's own animation: with the creator's Use clip it has nothing to choose. + SNew(SBox).IsEnabled_Lambda([this] { return Working->ClipUse.IsNull(); }) + [ + MakeRow(LOCTEXT("UseStyle", "How it is used"), + LOCTEXT("UseStyleTip", "Eat or drink plays the drinking animation of whatever the character holds. Use plays the lift-and-crush animation, a good fit for a medkit."), + MakeChoiceControl(Styles, [this] { return Working->Consumable.Style; }, [this](EMantleWeaponSourceUseStyle V) { Working->Consumable.Style = V; })) + ] + ] + + SVerticalBox::Slot().AutoHeight() + [ + SNew(STextBlock) + .AutoWrapText(true) + .ColorAndOpacity(FSlateColor::UseSubduedForeground()) + .Visibility_Lambda([this] { return Working->ClipUse.IsNull() ? EVisibility::Collapsed : EVisibility::Visible; }) + .Text(LOCTEXT("UseStyleOwnClip", "Your own Use animation plays instead.")) + ] + SVerticalBox::Slot().AutoHeight()[MakeRow(LOCTEXT("UseEffect", "What it does"), - LOCTEXT("UseEffectTip", "Heal gives health. Nothing gives none of its own: a script in your place does the rest."), + LOCTEXT("UseEffectTip", "Heal gives health. Stamina, Hunger and Thirst give that instead. Nothing gives none of its own: a script in your place does the rest."), MakeChoiceControl(Effects, [this] { return Working->Consumable.Effect; }, [this](EMantleWeaponSourceConsumableEffect V) { Working->Consumable.Effect = V; }))] + SVerticalBox::Slot().AutoHeight()[SNew(SBox).Visibility_Lambda([ShowHeal] { return ShowHeal(); })[MakeRow(LOCTEXT("Heal", "Health given"), LOCTEXT("HealTip", "How much health one use gives, from 1 to 1000, up to the character's maximum."), @@ -1809,6 +2092,25 @@ TSharedRef SMantleWeaponBuilder::MakeTuningStep() + SVerticalBox::Slot().AutoHeight()[SNew(SBox).Visibility_Lambda([ShowHeal] { return ShowHeal(); })[MakeRow(LOCTEXT("HealSeconds", "Spread over (seconds)"), LOCTEXT("HealSecondsTip", "0 gives all of it at once. Above 0 spreads it evenly over this many seconds."), MakeFloatSpin(0.f, 60.f, 0.5f, [this] { return Working->Consumable.HealSeconds; }, [this](float V) { Working->Consumable.HealSeconds = V; }))]] + + SVerticalBox::Slot().AutoHeight()[SNew(SBox).Visibility_Lambda([ShowAmount] { return ShowAmount(); })[MakeRow(LOCTEXT("Amount", "Amount"), + LOCTEXT("AmountTip", "How much one use gives, from 1 to 10000, up to the character's maximum."), + MakeFloatSpin(1.f, 10000.f, 5.f, [this] { return Working->Consumable.Amount; }, [this](float V) { Working->Consumable.Amount = V; }))]] + + SVerticalBox::Slot().AutoHeight() + [ + SNew(STextBlock) + .AutoWrapText(true) + .ColorAndOpacity(FSlateColor::UseSubduedForeground()) + .Visibility_Lambda([ShowAmount] { return ShowAmount(); }) + .Text_Lambda([this] + { + switch (Working->Consumable.Effect) + { + case EMantleWeaponSourceConsumableEffect::Hunger: return LOCTEXT("HungerNote", "Hunger counts only in places whose script turns it on."); + case EMantleWeaponSourceConsumableEffect::Thirst: return LOCTEXT("ThirstNote", "Thirst counts only in places whose script turns it on."); + default: return LOCTEXT("StaminaNote", "Stamina counts only in places whose script turns it on."); + } + }) + ] + SVerticalBox::Slot().AutoHeight()[MakeRow(LOCTEXT("Uses", "Uses"), LOCTEXT("UsesTip", "How many times it can be used before it is gone."), MakeIntSpin(1, 100, [this] { return Working->Consumable.Uses; }, [this](int32 V) { Working->Consumable.Uses = V; }))] @@ -1826,7 +2128,7 @@ TSharedRef SMantleWeaponBuilder::MakeTuningStep() [ SNew(SBox).Visibility_Lambda([this] { return Working->Consumable.bOverrideUseSeconds ? EVisibility::Visible : EVisibility::Collapsed; }) [ - MakeRow(LOCTEXT("UseSeconds", "Use time (seconds)"), LOCTEXT("UseSecondsTip", "From 0.5 to 10 seconds. The health arrives at the same point of the animation, scaled to this time."), + MakeRow(LOCTEXT("UseSeconds", "Use time (seconds)"), LOCTEXT("UseSecondsTip", "From 0.5 to 10 seconds. The effect happens at the same point of the animation, scaled to this time."), MakeFloatSpin(0.5f, 10.f, 0.1f, [this] { return Working->Consumable.UseSeconds; }, [this](float V) { Working->Consumable.UseSeconds = V; })) ] ] @@ -2567,11 +2869,6 @@ TSharedRef SMantleWeaponBuilder::MakeTuningStep() TSharedRef SMantleWeaponBuilder::MakePartsAndSoundStep() { using namespace MantleWeaponBuilderPanelPrivate; - if (Working->Hold == EMantleWeaponHold::Consumable) - { - return SNew(STextBlock).AutoWrapText(true) - .Text(LOCTEXT("ConsumableNoParts", "A consumable has no moving parts, extra details or custom sounds. Go on to Create.")); - } const TArray> PartChoices = PartRoleChoices(Working->Hold); // An attachment's effect is an element's held effect (#904). TArray> Styles = AllStyles(); @@ -3146,8 +3443,8 @@ TSharedRef SMantleWeaponBuilder::MakeCreateStep() .ToolTipText_Lambda([this] { return CanTestLocally() - ? LOCTEXT("TestLocallyTip", "Opens the game with this weapon in your hands.") - : LOCTEXT("TestLocallyTipOff", "Press Create weapon first. If you change anything after that, press it again."); + ? LOCTEXT("TestLocallyTip", "Opens the game with this item in your hands.") + : LOCTEXT("TestLocallyTipOff", "Press Create item first. If you change anything after that, press it again."); }) .OnClicked_Lambda([this] { @@ -3165,8 +3462,8 @@ TSharedRef SMantleWeaponBuilder::MakeCreateStep() .Text_Lambda([this] { return CanTestLocally() - ? LOCTEXT("TestLocallyHelp", "Opens the game with this weapon in your hands.") - : LOCTEXT("TestLocallyHelpOff", "Press Create weapon first, and again after any change. Then you can try it here."); + ? LOCTEXT("TestLocallyHelp", "Opens the game with this item in your hands.") + : LOCTEXT("TestLocallyHelpOff", "Press Create item first, and again after any change. Then you can try it here."); }) ] ] @@ -3240,7 +3537,7 @@ TSharedRef SMantleWeaponBuilder::MakeCreateStep() .ButtonStyle(&FAppStyle::Get(), "PrimaryButton") .Text(LOCTEXT("Publish", "Publish")) .IsEnabled_Lambda([this] { return CanPublish(); }) - .ToolTipText(LOCTEXT("PublishTip", "Uploads this weapon and adds it to your Mantle library. Publishing again after a change adds a new version.")) + .ToolTipText(LOCTEXT("PublishTip", "Uploads this item and adds it to your Mantle library. Publishing again after a change adds a new version.")) .OnClicked_Lambda([this] { Publish(); @@ -3258,13 +3555,13 @@ TSharedRef SMantleWeaponBuilder::MakeCreateStep() { if (!CanTestLocally()) { - return LOCTEXT("PublishHelpOff", "Press Create weapon first, and again after any change. Then you can publish it."); + return LOCTEXT("PublishHelpOff", "Press Create item first, and again after any change. Then you can publish it."); } if (PublishChoice.bPublic && !PublishChoice.bRightsDeclared) { return LOCTEXT("PublishHelpRights", "Tick the declaration to publish publicly, or choose Private."); } - return LOCTEXT("PublishHelp", "Adds this weapon to your library. A place then stores it in Place Settings > Storage."); + return LOCTEXT("PublishHelp", "Adds this item to your library. A place then stores it in Place Settings > Storage."); }) ] ] @@ -3363,6 +3660,8 @@ bool SMantleWeaponBuilder::IsSelectedAssetPackage(const UObject* Object) const }; if (Matches(Working->Model.ToSoftObjectPath()) || Matches(Working->Projectile.Model.ToSoftObjectPath()) || Matches(Working->FireSound.ToSoftObjectPath()) || Matches(Working->FireSuppressedSound.ToSoftObjectPath()) + || Matches(Working->ClipHold.ToSoftObjectPath()) || Matches(Working->ClipUse.ToSoftObjectPath()) + || Matches(Working->ClipEquip.ToSoftObjectPath()) || Matches(Working->ClipPutAway.ToSoftObjectPath()) || Matches(SourceAssetPath)) { return true; @@ -3390,7 +3689,7 @@ void SMantleWeaponBuilder::OnObjectPropertyChanged(UObject* Object, FPropertyCha } bSelectedAssetEditedSinceCreate = true; CreatedSignature.Reset(); - TestResult = LOCTEXT("SelectedAssetChanged", "A selected model or sound changed. Create the weapon again before testing it."); + TestResult = LOCTEXT("SelectedAssetChanged", "A selected model, sound or animation changed. Create the item again before testing it."); bTestResultIsError = false; } @@ -3400,7 +3699,7 @@ void SMantleWeaponBuilder::TestLocally() { return; } - TestResult = LOCTEXT("TestStarting", "Getting your weapon ready to try..."); + TestResult = LOCTEXT("TestStarting", "Getting your item ready to try..."); bTestResultIsError = false; FString Error; @@ -3408,7 +3707,7 @@ void SMantleWeaponBuilder::TestLocally() const bool bOk = FMantleTestLocally::Get().RunWithWeapon(FMantleWeaponToTry::FromBuilderName(CreatedSafeName), Error, Notice); if (bOk) { - FString Said = TEXT("The game is opening with your weapon in your hands."); + FString Said = TEXT("The game is opening with your item in your hands."); if (!Notice.IsEmpty()) { Said += TEXT(" ") + Notice; diff --git a/Source/MantleEditor/Private/SMantleWeaponBuilder.h b/Source/MantleEditor/Private/SMantleWeaponBuilder.h index b2495f93..dd881d46 100644 --- a/Source/MantleEditor/Private/SMantleWeaponBuilder.h +++ b/Source/MantleEditor/Private/SMantleWeaponBuilder.h @@ -2,7 +2,9 @@ #pragma once #include "CoreMinimal.h" +#include "Animation/AnimSequence.h" #include "MantleThumbnailChoice.h" +#include "MantleWeaponBuilderLogic.h" #include "MantleBuilderKind.h" #include "MantleLibraryPublish.h" #include "MantleWeaponBuilderKind.h" @@ -13,6 +15,8 @@ #include "Widgets/SCompoundWidget.h" class SMantleBuilderViewport; +class SMantleClipSlots; +struct FMantleClipSlotsModel; struct FPropertyChangedEvent; namespace MantleWeaponBuilderPanelPrivate @@ -22,8 +26,8 @@ namespace MantleWeaponBuilderPanelPrivate } /** - * The "Build a weapon" window (#729): a guided flow, one decision per screen, that turns a creator's 3D model into a - * saved weapon source. The rules that need no window live in MantleWeaponBuilderLogic. + * The "Build an item" window (#729, mantle #333): a guided flow, one decision per screen, that turns a creator's 3D model into a + * saved item: a weapon, a consumable or a usable item. The rules that need no window live in MantleWeaponBuilderLogic. */ class SMantleWeaponBuilder : public SCompoundWidget { @@ -37,12 +41,20 @@ class SMantleWeaponBuilder : public SCompoundWidget private: friend class FMantleWeaponBuilderPanelSaveReopenTest; friend class FMantleWeaponBuilderPanelAssetInvalidationTest; + friend class FMantleBuildAnItemScreensTest; + friend class FMantleBuildAnItemTurnTest; + friend struct FMantleItemBuilderShotAccess; TArray MakeSteps(); + TSharedRef MakeTypeStep(); TSharedRef MakeKindStep(); + /** The Animations screen of an item that brings its own clips: the shared Clips control bound to the source. */ + TSharedRef MakeAnimationsStep(); TSharedRef MakeModelStep(); TSharedRef MakeSizeStep(); + /** The size screen's turn buttons for a consumable and a usable item. */ + TSharedRef MakeQuarterTurnButtons(); TSharedRef MakePointsStep(); TSharedRef MakeTuningStep(); TSharedRef MakePartsAndSoundStep(); @@ -54,6 +66,11 @@ class SMantleWeaponBuilder : public SCompoundWidget void SaveThumbnailChoice(const FString& SafeName); TSharedRef MakeHoldCard(EMantleWeaponHold Hold); + TSharedRef MakeTypeCard(MantleWeaponBuilderLogic::EItemType Type); + /** The first screen's pick: Weapon goes back to the weapon hold last chosen. */ + void SetItemType(MantleWeaponBuilderLogic::EItemType Type); + /** Draws the screens again when the item type changed (each type has its own). */ + void RefreshStepsForType(); void SetHold(EMantleWeaponHold Hold); void LoadSourceAsset(UMantleWeaponSource* Source); @@ -96,6 +113,21 @@ class SMantleWeaponBuilder : public SCompoundWidget TWeakPtr SizeViewport; TWeakPtr PointViewport; TSharedPtr Flow; + /** The type the flow's screens are for. */ + MantleWeaponBuilderLogic::EItemType StepsType = MantleWeaponBuilderLogic::EItemType::Weapon; + EMantleWeaponHold LastWeaponHold = EMantleWeaponHold::Rifle; + /** The Animations screen's data, and the clip its preview is playing (kept alive while it plays). */ + TSharedPtr ClipsModel; + /** Weak: the control lives only while the screen is open. */ + TWeakPtr ClipsView; + TStrongObjectPtr PreviewedClip; + /** The model the Animations screen's preview holds. */ + TStrongObjectPtr PreviewedItem; + FString ClipPreviewError; + /** FMantleItemClips::Problems of the picked clips; the Animations screen does not go on while it says something. */ + FString ClipProblems; + /** FMantleConsumableEffect::Line of the working item: when the effect lands with the creator's Use clip; empty otherwise. */ + FText ClipEffectLine; bool bNameEdited = false; /** The safe name of the weapon this window already created, so pressing Create again updates it instead of picking a new name. */ FString CreatedSafeName; diff --git a/Source/MantleEditor/Private/Tests/MantleBuildAnItemTest.cpp b/Source/MantleEditor/Private/Tests/MantleBuildAnItemTest.cpp new file mode 100644 index 00000000..2072684c --- /dev/null +++ b/Source/MantleEditor/Private/Tests/MantleBuildAnItemTest.cpp @@ -0,0 +1,573 @@ +// Copyright Joshua Eger. All Rights Reserved. +#include "MantleAssetCleanup.h" +#include "MantleAvatarContract.h" +#include "MantleBuilderKind.h" +#include "MantleBuiltInMannequin.h" +#include "MantleHandAttach.h" +#include "MantleItemClips.h" +#include "MantlePlaceAssetConverter.h" +#include "MantlePreviewExport.h" +#include "MantleWeaponBuilderExport.h" +#include "MantleWeaponBuilderKind.h" +#include "MantleWeaponBuilderLogic.h" +#include "MantleWeaponDocument.h" +#include "MantleWeaponSource.h" +#include "SMantleBuilderFlow.h" +#include "SMantleWeaponBuilder.h" + +#include "Animation/AnimData/IAnimationDataController.h" +#include "Animation/AnimSequence.h" +#include "Engine/SkeletalMesh.h" +#include "Dom/JsonObject.h" +#include "Engine/StaticMesh.h" +#include "HAL/FileManager.h" +#include "MeshDescription.h" +#include "Misc/AutomationTest.h" +#include "Misc/FileHelper.h" +#include "Misc/Paths.h" +#include "Misc/ScopeExit.h" +#include "Serialization/JsonReader.h" +#include "Serialization/JsonSerializer.h" +#include "StaticMeshAttributes.h" +#include "UObject/Package.h" + +#if WITH_DEV_AUTOMATION_TESTS + +// mantle #333 P2, Build an item: the first screen picks the item type and each type has its own screens; the Animations screen's slots are +// the source's clip fields; a weapon keeps no clips; a picked clip is shown as Mantle plays it. Everything is in memory. + +// Named, not anonymous: MantleEditor builds as a unity build. +namespace MantleBuildAnItemTestPrivate +{ + TArray StepTitles(const SMantleBuilderFlow& Flow) + { + TArray Titles; + for (const FMantleBuilderStep& Step : Flow.GetSteps()) + { + Titles.Add(Step.Title.ToString()); + } + return Titles; + } + + /** A one-second clip made in memory on Mesh's skeleton: the pelvis turns 40 degrees. */ + UAnimSequence* MakeItemClip(USkeletalMesh* Mesh, const TCHAR* Name) + { + UPackage* Package = CreatePackage(*FString::Printf(TEXT("/Game/__MantleBuildAnItemTest/%s"), Name)); + UAnimSequence* Sequence = NewObject(Package, Name, RF_Public | RF_Standalone | RF_Transient); + Sequence->SetSkeleton(Mesh->GetSkeleton()); + Sequence->SetPreviewMesh(Mesh); + const FReferenceSkeleton& Reference = Mesh->GetRefSkeleton(); + const int32 Index = Reference.FindRawBoneIndex(TEXT("pelvis")); + IAnimationDataController& Controller = Sequence->GetController(); + Controller.InitializeModel(); + Controller.OpenBracket(FText::FromString(TEXT("Build an item test")), false); + Controller.SetFrameRate(FFrameRate(30, 1), false); + Controller.SetNumberOfFrames(FFrameNumber(30), false); + if (Index != INDEX_NONE) + { + const FTransform Ref = Reference.GetRawRefBonePose()[Index]; + TArray Positions; + TArray Rotations; + TArray Scales; + for (int32 Key = 0; Key <= 30; ++Key) + { + Positions.Add(Ref.GetTranslation()); + Rotations.Add(FQuat(FVector::UpVector, FMath::DegreesToRadians(40.0 * Key / 30)) * Ref.GetRotation()); + Scales.Add(FVector::OneVector); + } + Controller.AddBoneCurve(TEXT("pelvis"), false); + Controller.SetBoneTrackKeys(TEXT("pelvis"), Positions, Rotations, Scales, false); + } + Controller.NotifyPopulated(); + Controller.CloseBracket(false); + return Sequence; + } + + void DiscardClip(UObject* Object) + { + Object->ClearFlags(RF_Public | RF_Standalone); + Object->MarkAsGarbage(); + } +} + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleBuildAnItemScreensTest, "Mantle.Editor.BuildAnItem.EachTypeHasItsOwnScreensAndAWeaponKeepsNoClips", + EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) +bool FMantleBuildAnItemScreensTest::RunTest(const FString& Parameters) +{ + using namespace MantleWeaponBuilderLogic; + using namespace MantleBuildAnItemTestPrivate; + TestTrue(TEXT("a consumable takes clips"), TakesClips(EMantleWeaponHold::Consumable)); + TestFalse(TEXT("a rifle does not"), TakesClips(EMantleWeaponHold::Rifle)); + + TSharedRef Builder = SNew(SMantleWeaponBuilder); + const TArray Weapon = StepTitles(*Builder->Flow); + TestEqual(TEXT("the first screen asks the type"), Weapon[0], FString(TEXT("What kind of item?"))); + TestTrue(TEXT("a weapon picks its kind next"), Weapon.Contains(TEXT("What kind of weapon?"))); + TestFalse(TEXT("a weapon has no Animations screen"), Weapon.Contains(TEXT("Animations"))); + + Builder->SetHold(EMantleWeaponHold::Pistol); + Builder->SetItemType(EItemType::Consumable); + TestTrue(TEXT("the consumable hold is chosen"), Builder->Working->Hold == EMantleWeaponHold::Consumable); + const TArray Consumable = StepTitles(*Builder->Flow); + TestFalse(TEXT("a consumable has no weapon kind"), Consumable.Contains(TEXT("What kind of weapon?"))); + TestFalse(TEXT("nor parts and sound"), Consumable.Contains(TEXT("Parts and sound"))); + TestTrue(TEXT("it has the Animations screen"), Consumable.Contains(TEXT("Animations"))); + + Builder->Working->ClipUse = TSoftObjectPtr(FSoftObjectPath(TEXT("/Game/__MantleBuildAnItemTest/AS_Sip.AS_Sip"))); + Builder->SetItemType(EItemType::Item); + TestTrue(TEXT("the usable item hold is chosen"), Builder->Working->Hold == EMantleWeaponHold::Item); + TestFalse(TEXT("its clips stay"), Builder->Working->ClipUse.IsNull()); + const TArray Usable = StepTitles(*Builder->Flow); + TestTrue(TEXT("a usable item has the Animations screen"), Usable.Contains(TEXT("Animations"))); + TestFalse(TEXT("and nothing about an attack, an effect or a weapon kind"), + Usable.Contains(TEXT("Use and effect")) || Usable.Contains(TEXT("Attack and effect")) || Usable.Contains(TEXT("What kind of weapon?")) || Usable.Contains(TEXT("Parts and sound"))); + Builder->SetItemType(EItemType::Weapon); + TestTrue(TEXT("back to the weapon hold chosen before"), Builder->Working->Hold == EMantleWeaponHold::Pistol); + TestTrue(TEXT("a weapon keeps no clips"), Builder->Working->ClipUse.IsNull()); + TestTrue(TEXT("the weapon screens are back"), StepTitles(*Builder->Flow) == Weapon); + return true; +} + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleBuildAnItemUsableTest, "Mantle.Editor.BuildAnItem.AUsableItemExportsNoAttackAndNoEffect", + EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) +bool FMantleBuildAnItemUsableTest::RunTest(const FString& Parameters) +{ + UMantleWeaponSource* Source = NewObject(GetTransientPackage()); + Source->DisplayName = TEXT("Lantern"); + Source->Hold = EMantleWeaponHold::Item; + Source->ClipHold = TSoftObjectPtr(FSoftObjectPath(TEXT("/Game/__MantleBuildAnItemTest/AS_Carry.AS_Carry"))); + TMap Points; + Points.Add(FName(TEXT("Grip")), FTransform(FVector(0.0, 0.0, -6.0))); + // With the grip point and without it: the point is optional. + for (const TMap& Placed : { Points, TMap() }) + { + FMantleWeaponDesc Desc; + TArray Messages; + if (!TestTrue(TEXT("a usable item builds"), FMantleWeaponBuilderExport::BuildDocument(*Source, Placed, TEXT("FixtureMesh"), Desc, Messages))) + { + for (const FText& Message : Messages) AddError(Message.ToString()); + return true; + } + TestTrue(TEXT("hold item, delivery signal"), Desc.GetHold() == EMantleWeaponDocHold::Item && Desc.GetDelivery() == EMantleWeaponDocDelivery::Signal); + TestTrue(TEXT("its clip is named"), Desc.bClips && !Desc.ClipHold.IsEmpty()); + TestEqual(TEXT("the grip is written only when placed"), Desc.Socket(EMantleWeaponDocSocket::Grip).bSet, Placed.Num() > 0); + const FString Json = FMantleWeaponDocument::Write(Desc); + TestFalse(TEXT("no fire, consumable or effect moment"), + Json.Contains(TEXT("\"fire\"")) || Json.Contains(TEXT("\"consumable\"")) || Json.Contains(TEXT("\"useEffectSeconds\""))); + FMantleWeaponDesc Back; + FString Error; + const bool bRead = FMantleWeaponDocument::Parse(Json, Back, Error); + TestTrue(FString::Printf(TEXT("the document reads back (%s)"), *Error), bRead); + } + return true; +} + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleBuildAnItemSlotsTest, "Mantle.Editor.BuildAnItem.TheFourSlotsAreTheSourcesClipFields", + EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) +bool FMantleBuildAnItemSlotsTest::RunTest(const FString& Parameters) +{ + const TSharedRef Model = FMantleItemClips::MakeModel(); + TArray Labels; + for (const FMantleClipSlotDef& Def : Model->Slots) + { + Labels.Add(Def.Label.ToString()); + TestFalse(TEXT("every slot is optional"), Def.bRequired); + TestEqual(TEXT("and holds one clip"), Def.MaxClips, 1); + } + TestEqual(TEXT("Hold, Use, Equip, Put away"), FString::Join(Labels, TEXT(",")), FString(TEXT("Hold,Use,Equip,Put away"))); + TestTrue(TEXT("the preview has a body"), Model->PreviewMesh.IsValid()); + + UMantleWeaponSource* Source = NewObject(GetTransientPackage()); + const FSoftObjectPath Sip(TEXT("/Game/__MantleBuildAnItemTest/AS_Sip.AS_Sip")); + const FSoftObjectPath Away(TEXT("/Game/__MantleBuildAnItemTest/AS_Away.AS_Away")); + Source->ClipUse = TSoftObjectPtr(Sip); + FMantleItemClips::ReadSource(*Model, *Source); + TestEqual(TEXT("the source's clip shows in its slot"), Model->TotalClips(), 1); + Model->SetClip(TEXT("putAway"), 0, Away); + Model->RemoveClip(TEXT("use"), 0); + FMantleItemClips::WriteSource(*Model, *Source); + TestTrue(TEXT("a removed clip leaves its field"), Source->ClipUse.IsNull()); + TestEqual(TEXT("a picked clip reaches its field"), Source->ClipPutAway.ToSoftObjectPath().ToString(), Away.ToString()); + TestTrue(TEXT("the other fields stay empty"), Source->ClipHold.IsNull() && Source->ClipEquip.IsNull()); + return true; +} + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleBuildAnItemPreviewTest, "Mantle.Editor.BuildAnItem.AUefnClipIsShownAsItIs", + EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) +bool FMantleBuildAnItemPreviewTest::RunTest(const FString& Parameters) +{ + using namespace MantleBuildAnItemTestPrivate; + FString Error; + const FMantleAvatarContract* Contract = FMantleAvatarContract::Get(&Error); + USkeletalMesh* Mannequin = Contract ? FMantleBuiltInMannequin::UEFNMannequin(*Contract, &Error) : nullptr; + if (!TestNotNull(FString::Printf(TEXT("the UEFN mannequin (%s)"), *Error), Mannequin)) + { + return false; + } + UAnimSequence* Clip = MakeItemClip(Mannequin, TEXT("AS_ItemUefn")); + USkeletalMesh* Body = Mannequin; + TStrongObjectPtr Kept; + UAnimSequence* Shown = FMantleItemClips::MakePreview(Clip, Body, Kept, Error); + TestTrue(FString::Printf(TEXT("a UEFN clip is shown as it is (%s)"), *Error), Shown == Clip); + TestTrue(TEXT("on a body of its skeleton"), Body && Body->GetSkeleton() == Clip->GetSkeleton()); + const TSharedRef Model = FMantleItemClips::MakeModel(); + Model->SetClip(TEXT("use"), 0, FSoftObjectPath(Clip)); + TestEqual(TEXT("and has no problem"), FMantleItemClips::Problems(*Model), FString()); + DiscardClip(Clip); + return true; +} + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleBuildAnItemRetargetPreviewTest, "Mantle.Editor.BuildAnItem.AnotherMannequinsClipIsShownRetargeted", + EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) +bool FMantleBuildAnItemRetargetPreviewTest::RunTest(const FString& Parameters) +{ + using namespace MantleBuildAnItemTestPrivate; + USkeletalMesh* Manny = LoadObject(nullptr, TEXT("/Game/Characters/UE5_Mannequins/Meshes/SKM_Manny_Simple.SKM_Manny_Simple"), nullptr, LOAD_NoWarn | LOAD_Quiet); + if (!Manny) + { + AddInfo(TEXT("this project has no UE5 Mannequin: nothing to retarget")); + return true; + } + // The engine's own noise about a clip made in memory and its retargeted copies: it has no curves, and compression starts before + // the copy's import data has loaded. + AddExpectedMessagePlain(TEXT("No animation curves found for retargeting"), ELogVerbosity::Warning, EAutomationExpectedMessageFlags::Contains, -1); + AddExpectedMessagePlain(TEXT("EnsureDependenciesAreLoaded"), ELogVerbosity::Warning, EAutomationExpectedMessageFlags::Contains, -1); + // Named afresh and not discarded: the editor still holds a handle to a retargeted clip's source, and destroying it warns in a later test. + UAnimSequence* Clip = MakeItemClip(Manny, *FString::Printf(TEXT("AS_ItemUe5_%s"), *FGuid::NewGuid().ToString())); + USkeletalMesh* Body = nullptr; + TStrongObjectPtr Kept; + FString Error; + UAnimSequence* Shown = FMantleItemClips::MakePreview(Clip, Body, Kept, Error); + if (TestNotNull(FString::Printf(TEXT("the retargeted preview (%s)"), *Error), Shown)) + { + CollectGarbage(GARBAGE_COLLECTION_KEEPFLAGS); + TestTrue(TEXT("it is a copy that is still there"), Shown != Clip && Kept.Get() == Shown && IsValid(Shown)); + TestTrue(TEXT("on the UEFN mannequin it plays on"), Body && Body != Manny && Shown->GetSkeleton() == Body->GetSkeleton()); + TestTrue(TEXT("and as long as the clip"), FMath::IsNearlyEqual(Shown->GetPlayLength(), Clip->GetPlayLength(), 0.05f)); + TArray Moved; + const int32 Pelvis = Body->GetRefSkeleton().FindRawBoneIndex(TEXT("pelvis")); + if (TestTrue(TEXT("with a pelvis"), Pelvis != INDEX_NONE)) + { + FTransform Start, End; + Shown->GetBoneTransform(Start, FSkeletonPoseBoneIndex(Body->GetSkeleton()->GetReferenceSkeleton().FindRawBoneIndex(TEXT("pelvis"))), FAnimExtractContext(0.0), true); + Shown->GetBoneTransform(End, FSkeletonPoseBoneIndex(Body->GetSkeleton()->GetReferenceSkeleton().FindRawBoneIndex(TEXT("pelvis"))), FAnimExtractContext(1.0), true); + TestTrue(TEXT("that keeps the pelvis turn"), Start.GetRotation().AngularDistance(End.GetRotation()) > FMath::DegreesToRadians(20.0)); + } + } + Clip->GetOutermost()->SetDirtyFlag(false); + return true; +} + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleBuildAnItemHeldTest, "Mantle.Editor.BuildAnItem.ThePreviewHoldsTheGripInThePalm", + EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) +bool FMantleBuildAnItemHeldTest::RunTest(const FString& Parameters) +{ + FString Error; + const FMantleAvatarContract* Contract = FMantleAvatarContract::Get(&Error); + USkeletalMesh* Mannequin = Contract ? FMantleBuiltInMannequin::UEFNMannequin(*Contract, &Error) : nullptr; + UStaticMesh* Cube = LoadObject(nullptr, TEXT("/Engine/BasicShapes/Cube.Cube")); + if (!TestNotNull(FString::Printf(TEXT("the UEFN mannequin (%s)"), *Error), Mannequin) || !TestNotNull(TEXT("a model"), Cube)) + { + return false; + } + UMantleWeaponSource* Source = NewObject(GetTransientPackage()); + Source->Hold = EMantleWeaponHold::Item; + Source->Model = Cube; + Source->bScaleOverridden = true; + Source->FitScale = 0.2f; + FMantleBuilderPoint& Grip = Source->Points.AddDefaulted_GetRef(); + Grip.Role = TEXT("Grip"); + Grip.Transform = FTransform(FVector(10.0, 5.0, -30.0)); + Grip.Source = EMantleBuilderPointSource::Creator; + + const FMantlePreviewHeldItem Held = FMantleItemClips::HeldItem(*Source, Cube, Mannequin); + const MantleHandAttach::FPalm Palm = MantleHandAttach::FindPalm(*Mannequin, false); + TestTrue(TEXT("the model is held"), Held.Mesh.Get() == Cube); + TestEqual(TEXT("where the game holds it"), Held.Socket, Palm.Where); + const FVector GripAt = Held.Local.TransformPosition(Grip.Transform.GetLocation()); + TestTrue(FString::Printf(TEXT("its grip point in the palm (%s)"), *GripAt.ToString()), GripAt.Equals(Palm.Offset.GetLocation(), 0.01)); + TestTrue(TEXT("at the fitted size"), Held.Local.GetScale3D().GetAbs().Equals(FVector(0.2), 0.001)); + TestTrue(TEXT("nothing held without a model"), !FMantleItemClips::HeldItem(*Source, nullptr, Mannequin).Mesh.IsValid()); + return true; +} + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleBuildAnItemDefaultGripTest, "Mantle.Editor.BuildAnItem.AnUnmovedGripIsNotWrittenAndIsTheGamesDefault", + EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) +bool FMantleBuildAnItemDefaultGripTest::RunTest(const FString& Parameters) +{ + FString Error; + const FMantleAvatarContract* Contract = FMantleAvatarContract::Get(&Error); + USkeletalMesh* Mannequin = Contract ? FMantleBuiltInMannequin::UEFNMannequin(*Contract, &Error) : nullptr; + UStaticMesh* Cube = LoadObject(nullptr, TEXT("/Engine/BasicShapes/Cube.Cube")); + if (!TestNotNull(FString::Printf(TEXT("the UEFN mannequin (%s)"), *Error), Mannequin) || !TestNotNull(TEXT("a model"), Cube)) + { + return false; + } + const FString Name = TEXT("MantleDefaultGripTest"); + const FString Folder = FPaths::ConvertRelativePathToFull(FPaths::ProjectContentDir() / TEXT("MantleWeapons") / Name); + ON_SCOPE_EXIT + { + for (const TCHAR* Prefix : { TEXT("SKM_"), TEXT("SK_") }) + { + const FString Asset = Prefix + Name; + if (UPackage* Package = FindPackage(nullptr, *(FString(TEXT("/Game/MantleWeapons/")) / Name / Asset))) + { + if (UObject* Found = FindObject(Package, *Asset)) + { + FMantleAssetCleanup::MoveAside({ Found }); + } + } + } + IFileManager::Get().DeleteDirectory(*Folder, false, true); + }; + + for (const EMantleWeaponHold Hold : { EMantleWeaponHold::Item, EMantleWeaponHold::Consumable }) + { + UMantleWeaponSource* Source = NewObject(GetTransientPackage()); + Source->DisplayName = Name; + Source->Hold = Hold; + Source->Model = Cube; + Source->bScaleOverridden = true; + Source->FitScale = 0.2f; + Source->FlipRotation = FQuat(FVector::RightVector, UE_DOUBLE_HALF_PI / 3.0); + // Left over from a gun: not part of the item, so it must not move the mesh's bounds. + FMantleWeaponSourcePart& Leftover = Source->Parts.AddDefaulted_GetRef(); + Leftover.Model = Cube; + Leftover.InBody = FTransform(FVector(300.0, 0.0, -200.0)); + Source->MagazineSections.Add(Cube); + + // The builder's own points, as it keeps them in the source: guesses. + FMantleWeaponBuilderKind Kind(MantleWeaponBuilderLogic::ToFitHold(Hold)); + Kind.SetFlipRotation(Source->FlipRotation); + Kind.SetScaleOverride(Source->FitScale); + Source->Points = MantleBuilderPoints::MergeGuesses({}, Kind.GuessPoints(Cube)); + FMantleBuilderPoint* Grip = Source->Points.FindByPredicate([](const FMantleBuilderPoint& Point) { return Point.Role == FName(TEXT("Grip")); }); + if (!TestNotNull(TEXT("the builder shows a grip"), Grip)) + { + return true; + } + + // Exports the source and returns whether its document has a grip. + auto ExportsAGrip = [&]() -> TOptional + { + TArray Messages; + FString Json; + TSharedPtr Root; + if (!FMantleWeaponBuilderExport::Export(*Source, Messages) || !FFileHelper::LoadFileToString(Json, *(Folder / (Name + TEXT(".weapon.json")))) + || !FJsonSerializer::Deserialize(TJsonReaderFactory<>::Create(Json), Root) || !Root) + { + for (const FText& Message : Messages) AddError(Message.ToString()); + return {}; + } + const TSharedPtr* Sockets = nullptr; + return Root->TryGetObjectField(TEXT("sockets"), Sockets) && (*Sockets)->HasField(TEXT("grip")); + }; + + const TOptional Unmoved = ExportsAGrip(); + if (!TestTrue(TEXT("it exports"), Unmoved.IsSet())) + { + return true; + } + TestFalse(TEXT("an unmoved grip is not written"), Unmoved.GetValue()); + + // The spot step four shows is the game's default on the exported mesh. + const USkeletalMesh* Item = LoadObject(nullptr, *FString::Printf(TEXT("/Game/MantleWeapons/%s/SKM_%s.SKM_%s"), *Name, *Name, *Name)); + if (!TestNotNull(TEXT("the exported mesh"), Item)) + { + return true; + } + const FTransform Default = MantleHandAttach::DefaultGripInMesh(Item->GetImportedBounds().GetBox(), false); + const FTransform MeshToWeapon = Kind.GetLastFit().MeshToWeapon; + const FVector ShownAt = MeshToWeapon.TransformPosition(Grip->Transform.GetLocation()); + TestTrue(FString::Printf(TEXT("shown at the default spot (%s, %s)"), *ShownAt.ToString(), *Default.GetLocation().ToString()), + ShownAt.Equals(Default.GetLocation(), 0.01)); + TestTrue(TEXT("with its turn"), (MeshToWeapon.GetRotation() * Grip->Transform.GetRotation()).Equals(Default.GetRotation(), 0.001)); + const FMantlePreviewHeldItem Held = FMantleItemClips::HeldItem(*Source, Cube, Mannequin); + const FTransform Expected = MeshToWeapon * Default.Inverse() * MantleHandAttach::FindPalm(*Mannequin, false).Offset; + TestTrue(TEXT("the preview holds it as the game will"), Held.Local.Equals(Expected, 0.01)); + + Grip->Transform.AddToTranslation(FVector(0.0, 0.0, 10.0)); + Grip->Source = EMantleBuilderPointSource::Creator; + TestTrue(TEXT("a moved grip is written"), ExportsAGrip().Get(false)); + Grip->ResetToGuess(); + TestFalse(TEXT("and not once reset"), ExportsAGrip().Get(true)); + } + return true; +} + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleBuildAnItemBundleClipsTest, "Mantle.Editor.BuildAnItem.TestLocallyCarriesTheItemsClips", + EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) +bool FMantleBuildAnItemBundleClipsTest::RunTest(const FString& Parameters) +{ + using namespace MantleBuildAnItemTestPrivate; + FString Error; + const FMantleAvatarContract* Contract = FMantleAvatarContract::Get(&Error); + USkeletalMesh* Mannequin = Contract ? FMantleBuiltInMannequin::UEFNMannequin(*Contract, &Error) : nullptr; + UStaticMesh* Cube = LoadObject(nullptr, TEXT("/Engine/BasicShapes/Cube.Cube")); + if (!TestNotNull(FString::Printf(TEXT("the UEFN mannequin (%s)"), *Error), Mannequin) || !TestNotNull(TEXT("a model"), Cube)) + { + return false; + } + const FString Name = TEXT("MantleBundleClipsTest"); + const FString Folder = FPaths::ConvertRelativePathToFull(FPaths::ProjectContentDir() / TEXT("MantleWeapons") / Name); + UAnimSequence* Sip = MakeItemClip(Mannequin, TEXT("AS_BundleSip")); + // The export saves a copy of the clip into the item's folder, and a copy of a transient clip cannot be saved. + Sip->ClearFlags(RF_Transient); + TArray Made = { TEXT("SKM_") + Name, TEXT("SK_") + Name }; + ON_SCOPE_EXIT + { + for (const FString& Asset : Made) + { + if (UPackage* Package = FindPackage(nullptr, *(FString(TEXT("/Game/MantleWeapons/")) / Name / Asset))) + { + if (UObject* Found = FindObject(Package, *Asset)) + { + FMantleAssetCleanup::MoveAside({ Found }); + } + } + } + IFileManager::Get().DeleteDirectory(*Folder, false, true); + DiscardClip(Sip); + }; + + UMantleWeaponSource* Source = NewObject(GetTransientPackage()); + Source->DisplayName = Name; + Source->Hold = EMantleWeaponHold::Consumable; + Source->Model = Cube; + Source->bScaleOverridden = true; + Source->FitScale = 0.2f; + Source->ClipUse = Sip; + TArray Messages; + FString Json; + TSharedPtr Root; + if (!FMantleWeaponBuilderExport::Export(*Source, Messages) || !FFileHelper::LoadFileToString(Json, *(Folder / (Name + TEXT(".weapon.json")))) + || !FJsonSerializer::Deserialize(TJsonReaderFactory<>::Create(Json), Root) || !Root) + { + for (const FText& Message : Messages) AddError(Message.ToString()); + AddError(TEXT("the item did not export")); + return false; + } + const TSharedPtr* Clips = nullptr; + FString LocalName; + if (!TestTrue(TEXT("the settings file names the Use clip"), Root->TryGetObjectField(TEXT("clips"), Clips) && (*Clips)->TryGetStringField(TEXT("use"), LocalName))) + { + return false; + } + Made.Add(LocalName); + + FMantlePlaceAssetConverter Converter; + FMantlePlaceAssetSet Set; + TMap ClipKeys; + TestTrue(TEXT("the clips convert"), FMantlePreviewExport::ConvertWeaponClips(FMantleWeaponToTry::FromBuilderName(Name), Json, Converter, Set, ClipKeys)); + for (const FMantleValidationIssue& Issue : Set.Issues) + { + AddInfo(Issue.Problem); + } + if (!TestEqual(TEXT("one clip, under the file's local name"), ClipKeys.Num(), 1) || !TestTrue(TEXT("that name"), ClipKeys.Contains(LocalName))) + { + return false; + } + TArray Uploads; + FString TakeError; + TestTrue(TEXT("the clips are handed out to cook"), Set.TakeUploads(EMantlePlaceUploadStage::AnimClip, Uploads, TakeError)); + TestTrue(TEXT("with the item's clip among them"), Uploads.Num() == 1 && Uploads[0].Key == ClipKeys[LocalName] && Uploads[0].Bytes.Num() > 0); + + TMap None; + FMantlePlaceAssetSet Empty; + TestTrue(TEXT("a file without clips adds none"), + FMantlePreviewExport::ConvertWeaponClips(FMantleWeaponToTry::FromBuilderName(Name), TEXT("{\"name\":\"x\"}"), Converter, Empty, None) && None.IsEmpty()); + return true; +} + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleBuildAnItemTurnTest, "Mantle.Editor.BuildAnItem.AnUprightTorchCanBeTurnedForward", + EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) +bool FMantleBuildAnItemTurnTest::RunTest(const FString& Parameters) +{ + using namespace MantleWeaponBuilderLogic; + + // The three turns together reach all 24 ways of standing a model. + TArray Reached = { FQuat::Identity }; + for (int32 Index = 0; Index < Reached.Num() && Reached.Num() <= 24; ++Index) + { + for (const EQuarterTurn Turn : { EQuarterTurn::Around, EQuarterTurn::Forward, EQuarterTurn::Sideways }) + { + const FQuat Next = (QuarterTurn(Turn) * Reached[Index]).GetNormalized(); + const bool bKnown = Reached.ContainsByPredicate([&Next](const FQuat& Each) + { + return Each.RotateVector(FVector::ForwardVector).Equals(Next.RotateVector(FVector::ForwardVector), 0.01) + && Each.RotateVector(FVector::UpVector).Equals(Next.RotateVector(FVector::UpVector), 0.01); + }); + if (!bKnown) + { + Reached.Add(Next); + } + } + } + TestEqual(TEXT("every way round"), Reached.Num(), 24); + + // A torch standing upright: a cube drawn out along Z. + UStaticMesh* Cube = LoadObject(nullptr, TEXT("/Engine/BasicShapes/Cube.Cube")); + if (!TestNotNull(TEXT("the engine cube"), Cube)) + { + return false; + } + UStaticMesh* Torch = DuplicateObject(Cube, GetTransientPackage()); + FMeshDescription* Description = Torch->GetMeshDescription(0); + if (!TestNotNull(TEXT("its shape"), Description)) + { + return false; + } + { + TVertexAttributesRef Positions = FStaticMeshAttributes(*Description).GetVertexPositions(); + for (const FVertexID Vertex : Description->Vertices().GetElementIDs()) + { + Positions[Vertex] *= FVector3f(0.05f, 0.05f, 0.3f); + } + Torch->CommitMeshDescription(0); + Torch->Build(true); + } + + const FString Name = TEXT("MantleTorchTurnTest"); + const FString Folder = FPaths::ConvertRelativePathToFull(FPaths::ProjectContentDir() / TEXT("MantleWeapons") / Name); + ON_SCOPE_EXIT + { + for (const TCHAR* Prefix : { TEXT("SKM_"), TEXT("SK_") }) + { + const FString Asset = Prefix + Name; + if (UPackage* Package = FindPackage(nullptr, *(FString(TEXT("/Game/MantleWeapons/")) / Name / Asset))) + { + if (UObject* Found = FindObject(Package, *Asset)) + { + FMantleAssetCleanup::MoveAside({ Found }); + } + } + } + IFileManager::Get().DeleteDirectory(*Folder, false, true); + }; + + const TSharedRef Builder = SNew(SMantleWeaponBuilder); + Builder->SetItemType(EItemType::Item); + Builder->Working->DisplayName = Name; + Builder->SetModel(Torch); + const FVector Top = FVector::UpVector; + TestTrue(TEXT("it starts upright"), Builder->Kind->GetLastFit().MeshToWeapon.GetRotation().RotateVector(Top).Equals(FVector::UpVector, 0.001)); + Builder->TurnFit(QuarterTurn(EQuarterTurn::Forward)); + TestTrue(TEXT("turned, its top points forward"), Builder->Kind->GetLastFit().MeshToWeapon.GetRotation().RotateVector(Top).Equals(FVector::ForwardVector, 0.001)); + TestTrue(TEXT("the source keeps the turn"), Builder->Working->FlipRotation.RotateVector(Top).Equals(FVector::ForwardVector, 0.001)); + + TArray Messages; + if (!TestTrue(TEXT("it exports"), FMantleWeaponBuilderExport::Export(*Builder->Working, Messages))) + { + for (const FText& Message : Messages) AddError(Message.ToString()); + return true; + } + const USkeletalMesh* Item = LoadObject(nullptr, *FString::Printf(TEXT("/Game/MantleWeapons/%s/SKM_%s.SKM_%s"), *Name, *Name, *Name)); + if (TestNotNull(TEXT("the exported mesh"), Item)) + { + const FVector Size = Item->GetImportedBounds().GetBox().GetSize(); + TestTrue(FString::Printf(TEXT("saved pointing forward (%s)"), *Size.ToString()), Size.X > 4.0 * Size.Y && Size.X > 4.0 * Size.Z); + } + return true; +} + +#endif diff --git a/Source/MantleEditor/Private/Tests/MantleCreatorClipsTest.cpp b/Source/MantleEditor/Private/Tests/MantleCreatorClipsTest.cpp new file mode 100644 index 00000000..c20031a3 --- /dev/null +++ b/Source/MantleEditor/Private/Tests/MantleCreatorClipsTest.cpp @@ -0,0 +1,654 @@ +// Copyright Joshua Eger. All Rights Reserved. +#include "Components/SceneComponent.h" +#include "Framework/Application/SlateApplication.h" +#include "Engine/StaticMesh.h" +#include "AssetCompilingManager.h" +#include "MantleCosmeticPreviewViewport.h" +#include "SMantleClipSlots.h" +#include "SMantleAnimPackSection.h" +#include "MantleAnimClipWriter.h" +#include "MantleAnimPack.h" +#include "MantleAnimPackPublish.h" +#include "MantleAvatarContract.h" +#include "MantleBuiltInMannequin.h" +#include "MantleCosmeticExport.h" +#include "MantleCreatorClips.h" +#include "MantlePlaceAssetConverter.h" +#include "MantlePlaceAssets.h" +#include "MantlePlaceValidator.h" +#include "MantleRuntimeSkeletalMeshBuilder.h" +#include "MantleSkeletonHash.h" +#include "MantleSkinnedMesh.h" + +#include "Animation/AnimData/IAnimationDataController.h" +#include "Animation/AnimSequence.h" +#include "Dom/JsonObject.h" +#include "Engine/SkeletalMesh.h" +#include "Misc/AutomationTest.h" +#include "Misc/ScopeExit.h" +#include "Serialization/JsonReader.h" +#include "Serialization/JsonSerializer.h" +#include "UObject/Package.h" + +#if WITH_DEV_AUTOMATION_TESTS + +// mantle #333 P1: the shared conversion for a creator's own clips (UEFN, retarget refusal, own mesh), its checks, and how the item's +// `clips` block is read and written by uploaded id. Everything is in memory; no network. + +// Named, not anonymous: MantleEditor builds as a unity build. +namespace MantleCreatorClipsTestPrivate +{ + /** A one-second clip made in memory on Mesh's skeleton: Bone turns 40 degrees about Z. */ + UAnimSequence* MakeClip(USkeletalMesh* Mesh, const TCHAR* Name, const FName Bone) + { + UPackage* Package = CreatePackage(*FString::Printf(TEXT("/Game/__MantleCreatorClipsTest/%s"), Name)); + UAnimSequence* Sequence = NewObject(Package, Name, RF_Public | RF_Standalone | RF_Transient); + Sequence->SetSkeleton(Mesh->GetSkeleton()); + Sequence->SetPreviewMesh(Mesh); + const FReferenceSkeleton& Reference = Mesh->GetRefSkeleton(); + const int32 Index = Reference.FindRawBoneIndex(Bone); + const int32 Frames = 30; + IAnimationDataController& Controller = Sequence->GetController(); + Controller.InitializeModel(); + Controller.OpenBracket(FText::FromString(TEXT("Creator clips test")), false); + Controller.SetFrameRate(FFrameRate(30, 1), false); + Controller.SetNumberOfFrames(FFrameNumber(Frames), false); + if (Index != INDEX_NONE) + { + const FTransform Ref = Reference.GetRawRefBonePose()[Index]; + TArray Positions; + TArray Rotations; + TArray Scales; + for (int32 Key = 0; Key <= Frames; ++Key) + { + Positions.Add(Ref.GetTranslation()); + Rotations.Add(FQuat(FVector::UpVector, FMath::DegreesToRadians(40.0 * Key / Frames)) * Ref.GetRotation()); + Scales.Add(FVector::OneVector); + } + Controller.AddBoneCurve(Bone, false); + Controller.SetBoneTrackKeys(Bone, Positions, Rotations, Scales, false); + } + Controller.NotifyPopulated(); + Controller.CloseBracket(false); + return Sequence; + } + + void Discard(UObject* Object) + { + // A made clip compresses in the background; thrown away before that lands, the engine warns. + FAssetCompilingManager::Get().FinishAllCompilation(); + Object->ClearFlags(RF_Public | RF_Standalone); + Object->MarkAsGarbage(); + } + + /** A mesh on a skeleton that is none of Mantle's: root, foo_a, foo_b. */ + USkeletalMesh* MakeForeignMesh(FString& OutError) + { + const TArray Bones = { TEXT("root"), TEXT("foo_a"), TEXT("foo_b") }; + const TArray Parents = { INDEX_NONE, 0, 1 }; + const TArray Global = { FTransform::Identity, FTransform(FVector(0.0, 0.0, 50.0)), FTransform(FVector(0.0, 0.0, 70.0)) }; + FMantleSkinnedMesh Mesh; + if (!FMantleBuiltInMannequin::MakeMesh(Bones, Parents, Global, Mesh, OutError)) + { + return nullptr; + } + FMantleSkinnedMeshBuildParams Params; + Params.bOwnSkeleton = true; + Params.MaxLODs = 1; + Params.Name = TEXT("SKM_CreatorClipsTest_Foreign"); + return FMantleRuntimeSkeletalMeshBuilder::Build(Mesh, Params, &OutError); + } +} + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleCreatorClipsUefnTest, "Mantle.CreatorClips.ConvertsAUefnClipOverTheUefnMannequin", + EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter) + +bool FMantleCreatorClipsUefnTest::RunTest(const FString& Parameters) +{ + using namespace MantleCreatorClipsTestPrivate; + FString Error; + const FMantleAvatarContract* Contract = FMantleAvatarContract::Get(&Error); + USkeletalMesh* Mannequin = Contract ? FMantleBuiltInMannequin::UEFNMannequin(*Contract, &Error) : nullptr; + if (!TestNotNull(FString::Printf(TEXT("the UEFN mannequin (%s)"), *Error), Mannequin)) + { + return false; + } + UAnimSequence* Sequence = MakeClip(Mannequin, TEXT("AS_CreatorUefn"), TEXT("pelvis")); + FMantleCreatorClip Clip; + const bool bConverted = FMantleCreatorClips::ConvertToUefn(Sequence, Clip, Error); + Discard(Sequence); + if (!TestTrue(FString::Printf(TEXT("a clip on the UEFN skeleton converts (%s)"), *Error), bConverted)) + { + return false; + } + // The clip's bone table is the contract's uefn skeleton in its order (the backend hashes the same table), whatever mesh it was sampled over. + const FMantleContractSkeleton* Fixture = Contract->FindSkeleton(Contract->EmoteSkeleton); + if (!TestNotNull(TEXT("the contract's uefn skeleton"), Fixture)) + { + return false; + } + TestEqual(TEXT("its skeleton hash is the uefn fixture's"), Clip.SkeletonHash, FMantleSkeletonHash::Compute(Fixture->Bones, Fixture->Parents)); + TestEqual(TEXT("one frame per 30th of a second, and the first"), Clip.Frames, 31); + TestEqual(TEXT("the bone table is the fixture's"), Clip.Bones, Fixture->Bones.Num()); + TestTrue(TEXT("the pelvis has a track"), Clip.Tracks >= 1); + TestTrue(TEXT("it has bytes and a hash"), Clip.Bytes.Num() > 8 && Clip.Hash.StartsWith(TEXT("sha256:"))); + TestTrue(TEXT("the file starts as MAN1"), Clip.Bytes.Num() >= 4 && FMemory::Memcmp(Clip.Bytes.GetData(), "MAN1", 4) == 0); + + TArray Issues; + TestTrue(TEXT("it is within the place clip limits"), FMantleCreatorClips::CheckClip(TEXT("AS_CreatorUefn"), nullptr, &Clip, FMantlePlaceAssetLimits(), Issues)); + return true; +} + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleCreatorClipsOtherSkeletonTest, "Mantle.CreatorClips.RefusesAnotherSkeletonAndSamplesOnAnOwnMesh", + EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter) + +bool FMantleCreatorClipsOtherSkeletonTest::RunTest(const FString& Parameters) +{ + using namespace MantleCreatorClipsTestPrivate; + FString Error; + USkeletalMesh* Foreign = MakeForeignMesh(Error); + if (!TestNotNull(FString::Printf(TEXT("a mesh on another skeleton (%s)"), *Error), Foreign)) + { + return false; + } + UAnimSequence* Sequence = MakeClip(Foreign, TEXT("AS_CreatorForeign"), TEXT("foo_a")); + ON_SCOPE_EXIT + { + Discard(Sequence); + Discard(Foreign); + }; + + FMantleCreatorClip Refused; + FString Why; + TestFalse(TEXT("a clip on a skeleton that is none of the four is refused"), FMantleCreatorClips::ConvertToUefn(Sequence, Refused, Why)); + TestTrue(FString::Printf(TEXT("with a plain sentence that names the clip (%s)"), *Why), Why.Contains(TEXT("AS_CreatorForeign")) && Why.Contains(TEXT("UEFN Mannequin"))); + TestEqual(TEXT("and nothing is made"), Refused.Bytes.Num(), 0); + + // The own-skeleton route (Custom avatars) keeps it on the mesh's own bones. + FMantleCreatorClip Own; + if (!TestTrue(FString::Printf(TEXT("sampled over its own mesh (%s)"), *Error), FMantleCreatorClips::ConvertOnOwnMesh(Sequence, Foreign, Own, Error))) + { + return false; + } + TestEqual(TEXT("its skeleton hash is the mesh's"), Own.SkeletonHash, FMantleSkeletonHash::Compute(Foreign->GetRefSkeleton())); + TestEqual(TEXT("three bones"), Own.Bones, 3); + TestEqual(TEXT("one animated bone"), Own.Tracks, 1); + return true; +} + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleCreatorClipsChecksTest, "Mantle.CreatorClips.ChecksEachClipAndTheWholeItem", + EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter) + +bool FMantleCreatorClipsChecksTest::RunTest(const FString& Parameters) +{ + const FMantlePlaceAssetLimits Limits; + auto Clip = [](const int32 Bytes, const int32 Bones, const double Seconds) + { + FMantleCreatorClip Made; + Made.Bytes.SetNumZeroed(Bytes); + Made.Bones = Bones; + Made.Seconds = Seconds; + return Made; + }; + auto Check = [&Limits, &Clip](const TCHAR* Name, const int32 Bytes, const int32 Bones, const double Seconds, TArray& Into) + { + const FMantleCreatorClip Made = Clip(Bytes, Bones, Seconds); + return FMantleCreatorClips::CheckClip(Name, nullptr, &Made, Limits, Into); + }; + TArray Issues; + TestTrue(TEXT("a small clip passes"), Check(TEXT("A"), 50000, 88, 2.5, Issues)); + TestEqual(TEXT("with no issue"), Issues.Num(), 0); + + Issues.Reset(); + TestFalse(TEXT("a clip over 8 MiB cooked is refused"), Check(TEXT("Big"), (8 << 20) + 1, 88, 2.5, Issues)); + TestTrue(TEXT("naming the clip"), Issues.Num() == 1 && Issues[0].Problem.Contains(TEXT("Big"))); + + Issues.Reset(); + TestFalse(TEXT("a skeleton with more than 256 bones is refused"), Check(TEXT("Bones"), 1000, 257, 2.5, Issues)); + Issues.Reset(); + TestFalse(TEXT("a clip over 60 seconds is refused"), Check(TEXT("Long"), 1000, 88, 60.5, Issues)); + Issues.Reset(); + TestTrue(TEXT("exactly 256 bones and 60 seconds pass"), Check(TEXT("Edge"), 1000, 256, 60.0, Issues)); + + // All of one item's clips together: at most 8 MiB. + const FMantleCreatorClip A = Clip(4 << 20, 88, 1.0); + const FMantleCreatorClip B = Clip(4 << 20, 88, 1.0); + const FMantleCreatorClip C = Clip(1, 88, 1.0); + Issues.Reset(); + TestTrue(TEXT("two 4 MiB clips are exactly the item's room"), FMantleCreatorClips::CheckItemTotal(TArray{ &A, &B }, Issues)); + TestFalse(TEXT("one byte more is refused"), FMantleCreatorClips::CheckItemTotal(TArray{ &A, &B, &C }, Issues)); + TestTrue(TEXT("with a sentence about the item's clips together"), Issues.Num() == 1 && Issues[0].Problem.Contains(TEXT("together"))); + return true; +} + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleCreatorClipsDocumentTest, "Mantle.CreatorClips.TheClipsBlockIsReadAndWrittenByUploadedId", + EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter) + +bool FMantleCreatorClipsDocumentTest::RunTest(const FString& Parameters) +{ + using namespace MantleCreatorClipsTestPrivate; + FString Error; + const FMantleAvatarContract* Contract = FMantleAvatarContract::Get(&Error); + USkeletalMesh* Mannequin = Contract ? FMantleBuiltInMannequin::UEFNMannequin(*Contract, &Error) : nullptr; + if (!TestNotNull(FString::Printf(TEXT("the UEFN mannequin (%s)"), *Error), Mannequin)) + { + return false; + } + // The builder copies each clip into the weapon's folder under the local name the file writes; here the folder is made in memory. + const FString Weapon = TEXT("CreatorClipsTestItem"); + UPackage* Package = CreatePackage(*FString::Printf(TEXT("/Game/MantleWeapons/%s/Hold_A"), *Weapon)); + UAnimSequence* Hold = NewObject(Package, TEXT("Hold_A"), RF_Public | RF_Standalone | RF_Transient); + Hold->SetSkeleton(Mannequin->GetSkeleton()); + ON_SCOPE_EXIT + { + Discard(Hold); + }; + const FString OwnedId = TEXT("ast_u00000000000000000000000000000abc"); + const FString Text = FString::Printf(TEXT("{\"name\":\"%s\",\"clips\":{\"hold\":\"Hold_A\",\"use\":\"%s\"}}"), *Weapon, *OwnedId); + + // Read: a local name loads from the folder; an uploaded id (a clip from a pack the creator owns) needs nothing. + FMantleBuiltWeaponParts Parts; + TestEqual(TEXT("the file is accepted"), FMantlePlaceAssets::WeaponDocumentProblem(Weapon, Text, &Parts), FString()); + UAnimSequence* const* FoundHold = Parts.Clips.Find(FName(TEXT("hold"))); + TestTrue(TEXT("the hold clip is the folder's copy"), FoundHold && *FoundHold == Hold); + TestFalse(TEXT("a slot that already names an uploaded id is not loaded"), Parts.Clips.Contains(FName(TEXT("use")))); + TestFalse(TEXT("a slot the file leaves out is not there"), Parts.Clips.Contains(FName(TEXT("equip")))); + const FString Missing = FMantlePlaceAssets::WeaponDocumentProblem(Weapon, Text.Replace(TEXT("Hold_A"), TEXT("NoSuchClip")), nullptr); + TestTrue(TEXT("a clip missing from the folder is named in plain words"), Missing.Contains(TEXT("NoSuchClip")) && Missing.Contains(TEXT("hold"))); + + // Write: the converted clip's key becomes its uploaded id; the id the creator copied in stays. + FMantlePlaceAssetSet Set; + FMantleConvertedWeapon Converted; + Converted.Name = Weapon; + Converted.DocumentText = Text; + Converted.MeshKey = TEXT("skeletalmesh:/Game/Test"); + Converted.ClipKeys.Emplace(TEXT("hold"), TEXT("itemclip:/Game/Test/Hold_A")); + Set.Uploaded.FindOrAdd(Converted.MeshKey).Id = TEXT("ast_u00000000000000000000000000000001"); + const FString HoldId = TEXT("ast_u00000000000000000000000000000002"); + Set.Uploaded.FindOrAdd(Converted.ClipKeys[0].Value).Id = HoldId; + TArray Bytes; + if (!TestTrue(FString::Printf(TEXT("with every id the upload is written (%s)"), *Error), Set.WeaponBytes(Converted, Bytes, Error))) + { + return false; + } + const FUTF8ToTCHAR Utf8(reinterpret_cast(Bytes.GetData()), Bytes.Num()); + const FString Json(Utf8.Length(), Utf8.Get()); + TSharedPtr Root; + if (!TestTrue(TEXT("it is JSON"), FJsonSerializer::Deserialize(TJsonReaderFactory<>::Create(Json), Root) && Root.IsValid())) + { + return false; + } + const TSharedPtr* ClipsBlock = nullptr; + if (TestTrue(TEXT("it keeps its clips block"), Root->TryGetObjectField(TEXT("clips"), ClipsBlock) && ClipsBlock)) + { + TestEqual(TEXT("hold names its uploaded id"), (*ClipsBlock)->GetStringField(TEXT("hold")), HoldId); + TestEqual(TEXT("use keeps the id the creator copied in"), (*ClipsBlock)->GetStringField(TEXT("use")), OwnedId); + } + TestFalse(TEXT("no local name is left"), Json.Contains(TEXT("Hold_A"))); + + // A clip that did not upload stops the item's upload, naming the slot. + Set.Uploaded.Remove(Converted.ClipKeys[0].Value); + FString Why; + TestFalse(TEXT("a clip without an id stops the upload"), Set.WeaponBytes(Converted, Bytes, Why)); + TestTrue(TEXT("and says which"), Why.Contains(TEXT("hold"))); + return true; +} + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleAnimPackTest, "Mantle.CreatorClips.AnAnimPackConvertsOnAnyRigAndWritesItsDocument", + EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter) + +bool FMantleAnimPackTest::RunTest(const FString& Parameters) +{ + using namespace MantleCreatorClipsTestPrivate; + FString Error; + USkeletalMesh* Foreign = MakeForeignMesh(Error); + if (!TestNotNull(FString::Printf(TEXT("a mesh on a rig of its own (%s)"), *Error), Foreign)) + { + return false; + } + UAnimSequence* Sequence = MakeClip(Foreign, TEXT("AS_PackForeign"), TEXT("foo_a")); + ON_SCOPE_EXIT + { + Discard(Sequence); + Discard(Foreign); + }; + + // Any rig: sampled over its own mesh, the document's skeleton is the mesh's hash; without a mesh a rig that is none of Mantle's is refused. + FMantleCreatorClip Own; + FString Skeleton; + if (!TestTrue(FString::Printf(TEXT("a clip on its own rig converts (%s)"), *Error), FMantleAnimPack::ConvertClip(Sequence, Foreign, Own, Skeleton, Error))) + { + return false; + } + TestEqual(TEXT("its skeleton field is the rig's hash"), Skeleton, FMantleSkeletonHash::Compute(Foreign->GetRefSkeleton())); + FMantleCreatorClip Refused; + FString RefusedSkeleton; + FString Why; + TestFalse(TEXT("with no mesh it must be a Mantle body"), FMantleAnimPack::ConvertClip(Sequence, nullptr, Refused, RefusedSkeleton, Why)); + TestTrue(TEXT("and the skeleton field stays empty"), RefusedSkeleton.IsEmpty()); + + // The pack's checks. + TestEqual(TEXT("a pack with clips and names is fine"), FMantleAnimPack::CheckPack(TArray{ TEXT("wave"), TEXT("Sit") }).Num(), 0); + TestEqual(TEXT("no clips is refused"), FMantleAnimPack::CheckPack(TArray()).Num(), 1); + TestEqual(TEXT("a repeated name (any case) is refused"), FMantleAnimPack::CheckPack(TArray{ TEXT("wave"), TEXT("Wave") }).Num(), 1); + TestEqual(TEXT("an empty name is refused"), FMantleAnimPack::CheckPack(TArray{ TEXT("") , TEXT("x") }).Num(), 1); + TestEqual(TEXT("a name with a space, a dash, a slash or a leading digit is refused"), + FMantleAnimPack::CheckPack(TArray{ TEXT("a b"), TEXT("a-b"), TEXT("a/b"), TEXT("1a") }).Num(), 4); + TestEqual(TEXT("a name made from an asset name is usable"), FMantleAnimPack::NameFrom(TEXT("AS_Wave-01")), FString(TEXT("as_wave_01"))); + TestTrue(TEXT("even one that starts with a digit"), FMantleAnimPack::IsNameValid(FMantleAnimPack::NameFrom(TEXT("01_Sit")))); + TArray Many; + for (int32 Index = 0; Index <= FMantleAnimPack::MaxClips; ++Index) + { + Many.Add(FString::Printf(TEXT("c%d"), Index)); + } + TestEqual(TEXT("one over the dependency limit is refused"), FMantleAnimPack::CheckPack(Many).Num(), 1); + Many.Pop(); + TestEqual(TEXT("exactly the limit is fine"), FMantleAnimPack::CheckPack(Many).Num(), 0); + + // The largest pack the rules allow (64 clips, 64 character names, the longest ids and a skeleton hash) is far under the cook's 64 KiB document limit. + TArray Largest; + for (int32 Index = 0; Index < FMantleAnimPack::MaxClips; ++Index) + { + Largest.Add({ FString::ChrN(64, TEXT('n')), TEXT("ast_u") + FString::ChrN(32, TEXT('a')), TEXT("skel_") + FString::ChrN(16, TEXT('f')) }); + } + TestTrue(TEXT("the largest pack's document fits"), FTCHARToUTF8(*FMantleAnimPack::WriteDocument(Largest)).Length() <= 64 * 1024); + + // The document: format, then {name, asset, skeleton} in the order given. + const TArray Entries = { { TEXT("wave"), TEXT("ast_u1"), TEXT("uefn") }, { TEXT("spin"), TEXT("ast_u2"), Skeleton } }; + const FString Text = FMantleAnimPack::WriteDocument(Entries); + TSharedPtr Root; + if (!TestTrue(TEXT("the document is JSON"), FJsonSerializer::Deserialize(TJsonReaderFactory<>::Create(Text), Root) && Root.IsValid())) + { + return false; + } + TestEqual(TEXT("its format"), Root->GetStringField(TEXT("format")), FString(FMantleAnimPack::DocumentFormat())); + const TArray>* Clips = nullptr; + if (TestTrue(TEXT("it lists its clips"), Root->TryGetArrayField(TEXT("clips"), Clips) && Clips && Clips->Num() == 2)) + { + const TSharedPtr Second = (*Clips)[1]->AsObject(); + TestEqual(TEXT("second name"), Second->GetStringField(TEXT("name")), FString(TEXT("spin"))); + TestEqual(TEXT("second asset"), Second->GetStringField(TEXT("asset")), FString(TEXT("ast_u2"))); + TestEqual(TEXT("second skeleton"), Second->GetStringField(TEXT("skeleton")), Skeleton); + } + return true; +} + +// mantle #333 G10: the pack's publish source converts every clip into the set (no network), and once the clips have ids the document names +// them with the right skeleton field; a clip without an id is refused by name; the upload stage is the animpack kind. +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleAnimPackPublishTest, "Mantle.CreatorClips.AnAnimPackPublishConvertsItsClipsAndItsDocumentNamesTheirUploadedIds", + EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter) + +bool FMantleAnimPackPublishTest::RunTest(const FString& Parameters) +{ + using namespace MantleCreatorClipsTestPrivate; + FString Error; + USkeletalMesh* Foreign = MakeForeignMesh(Error); + if (!TestNotNull(FString::Printf(TEXT("a mesh on a rig of its own (%s)"), *Error), Foreign)) + { + return false; + } + UAnimSequence* Sequence = MakeClip(Foreign, TEXT("AS_PackPublishForeign"), TEXT("foo_a")); + ON_SCOPE_EXIT + { + Discard(Sequence); + Discard(Foreign); + }; + + FMantleAnimPackInput Input; + Input.Name = TEXT("Tricks"); + FMantleAnimPackInput::FClip& Clip = Input.Clips.AddDefaulted_GetRef(); + Clip.Name = TEXT("spin"); + Clip.Sequence = Sequence; + Clip.OwnMesh = Foreign; + TestTrue(TEXT("a named pack with a clip can be published"), Input.Problem().IsEmpty()); + FMantleAnimPackInput Twice = Input; + const FMantleAnimPackInput::FClip FirstClip = Twice.Clips[0]; + Twice.Clips.Add(FirstClip); + Twice.Clips.Last().Name = TEXT("SPIN"); + TestFalse(TEXT("a repeated name (any case) cannot"), Twice.Problem().IsEmpty()); + FMantleAnimPackInput Unnamed = Input; + Unnamed.Name.Reset(); + TestFalse(TEXT("a pack with no name cannot"), Unnamed.Problem().IsEmpty()); + + // Conversion: the clip goes into the set as an animclip, and the pack records its key and skeleton field. + FMantleAnimPackPublishSource Source(Input); + FMantlePlaceAssetSet Set; + Source.Convert(0, Set); + if (!TestEqual(TEXT("one clip converted"), Set.Clips.Num(), 1) || !TestEqual(TEXT("one pack"), Set.AnimPacks.Num(), 1)) + { + return false; + } + TestEqual(TEXT("the clip's key"), Set.Clips[0].Key, FMantleAnimPackPublishSource::ClipKeyFor(Sequence->GetPathName(), Foreign->GetPathName())); + TestTrue(TEXT("the clip has bytes"), Set.Clips[0].Bytes.Num() > 0); + const FString Hash = FMantleSkeletonHash::Compute(Foreign->GetRefSkeleton()); + TestEqual(TEXT("its skeleton field is the rig's hash"), Set.AnimPacks[0].Entries[0].Skeleton, Hash); + + // Two names on the same animation and mesh: one clip is converted and uploaded, and both entries point at its key. + { + FMantleAnimPackInput Shared = Input; + FMantleAnimPackInput::FClip& Second = Shared.Clips.AddDefaulted_GetRef(); + Second.Name = TEXT("spin2"); + Second.Sequence = Sequence; + Second.OwnMesh = Foreign; + FMantleAnimPackPublishSource SharedSource(Shared); + FMantlePlaceAssetSet SharedSet; + SharedSource.Convert(0, SharedSet); + if (TestEqual(TEXT("two names on one animation upload one clip"), SharedSet.Clips.Num(), 1) && TestEqual(TEXT("one pack for them"), SharedSet.AnimPacks.Num(), 1) + && TestEqual(TEXT("both names are in the pack"), SharedSet.AnimPacks[0].Entries.Num(), 2)) + { + TestEqual(TEXT("both point at the same clip"), SharedSet.AnimPacks[0].Entries[0].ClipKey, SharedSet.AnimPacks[0].Entries[1].ClipKey); + TestEqual(TEXT("and the same skeleton field"), SharedSet.AnimPacks[0].Entries[0].Skeleton, SharedSet.AnimPacks[0].Entries[1].Skeleton); + SharedSet.RecordUpload(SharedSet.Clips[0].Key, TEXT("ast_u_shared"), TEXT("h"), 1); + TArray SharedBytes; + FString SharedError; + if (TestTrue(TEXT("the document is written from the one upload"), SharedSet.AnimPackBytes(SharedSet.AnimPacks[0], SharedBytes, SharedError))) + { + const FUTF8ToTCHAR SharedText(reinterpret_cast(SharedBytes.GetData()), SharedBytes.Num()); + const FString SharedString(SharedText.Length(), SharedText.Get()); + int32 Count = 0; + for (int32 At = SharedString.Find(TEXT("ast_u_shared")); At != INDEX_NONE; At = SharedString.Find(TEXT("ast_u_shared"), ESearchCase::CaseSensitive, ESearchDir::FromStart, At + 1)) + { + ++Count; + } + TestEqual(TEXT("the id is named by both entries"), Count, 2); + } + } + } + + // A UEFN entry beside it (written by hand: no second rig needed to test the document). + FMantleConvertedAnimPack::FEntry& Uefn = Set.AnimPacks[0].Entries.AddDefaulted_GetRef(); + Uefn.Name = TEXT("wave"); + Uefn.ClipKey = FMantleAnimPackPublishSource::ClipKeyFor(TEXT("/Game/Test/Wave"), FString()); + Uefn.Skeleton = TEXT("uefn"); + + // Without ids nothing is written, and the first clip without one is named. + TArray Bytes; + TestFalse(TEXT("no ids yet"), Set.AnimPackBytes(Set.AnimPacks[0], Bytes, Error)); + TestTrue(TEXT("it names the pack and the clip"), Error.Contains(TEXT("Tricks")) && Error.Contains(TEXT("spin"))); + Set.RecordUpload(Set.Clips[0].Key, TEXT("ast_u_spin"), TEXT("h"), 1); + Error.Reset(); + TestFalse(TEXT("one clip still missing"), Set.AnimPackBytes(Set.AnimPacks[0], Bytes, Error)); + TestTrue(TEXT("it names the missing clip"), Error.Contains(TEXT("wave"))); + Set.RecordUpload(Uefn.ClipKey, TEXT("ast_u_wave"), TEXT("h"), 1); + + // The upload stage: the animpack kind, with the document's entries in order, each with its uploaded id and skeleton. + TArray Uploads; + TestTrue(TEXT("the stage is taken"), Set.TakeUploads(EMantlePlaceUploadStage::AnimPack, Uploads, Error)); + if (!TestEqual(TEXT("one document upload"), Uploads.Num(), 1)) + { + return false; + } + TestEqual(TEXT("its cook kind"), FString(Uploads[0].Options.Kind), FString(TEXT("animpack"))); + TestFalse(TEXT("with a hash"), Uploads[0].Hash.IsEmpty()); + const FUTF8ToTCHAR Converted(reinterpret_cast(Uploads[0].Bytes.GetData()), Uploads[0].Bytes.Num()); + const FString Text(Converted.Length(), Converted.Get()); + TSharedPtr Root; + if (!TestTrue(TEXT("the document is JSON"), FJsonSerializer::Deserialize(TJsonReaderFactory<>::Create(Text), Root) && Root.IsValid())) + { + return false; + } + TestEqual(TEXT("its format"), Root->GetStringField(TEXT("format")), FString(FMantleAnimPack::DocumentFormat())); + const TArray>* Entries = nullptr; + if (TestTrue(TEXT("it lists two clips"), Root->TryGetArrayField(TEXT("clips"), Entries) && Entries && Entries->Num() == 2)) + { + const TSharedPtr First = (*Entries)[0]->AsObject(); + TestEqual(TEXT("first name"), First->GetStringField(TEXT("name")), FString(TEXT("spin"))); + TestEqual(TEXT("first asset is the uploaded id"), First->GetStringField(TEXT("asset")), FString(TEXT("ast_u_spin"))); + TestEqual(TEXT("first skeleton is the hash"), First->GetStringField(TEXT("skeleton")), Hash); + const TSharedPtr Second = (*Entries)[1]->AsObject(); + TestEqual(TEXT("second asset is the uploaded id"), Second->GetStringField(TEXT("asset")), FString(TEXT("ast_u_wave"))); + TestEqual(TEXT("second skeleton is uefn"), Second->GetStringField(TEXT("skeleton")), FString(TEXT("uefn"))); + } + return true; +} + +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleCreatorClipsPropBoneTest, "Mantle.CreatorClips.TheBuiltInMannequinHasEveryUefnBoneSoAPropTrackSurvives", + EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter) + +bool FMantleCreatorClipsPropBoneTest::RunTest(const FString& Parameters) +{ + using namespace MantleCreatorClipsTestPrivate; + FString Error; + const FMantleAvatarContract* Contract = FMantleAvatarContract::Get(&Error); + const FMantleContractSkeleton* Fixture = Contract ? Contract->FindSkeleton(Contract->EmoteSkeleton) : nullptr; + USkeletalMesh* Built = FMantleBuiltInMannequin::Get(&Error); + if (!TestNotNull(FString::Printf(TEXT("the contract's uefn skeleton and the built-in mannequin (%s)"), *Error), Fixture) || !TestNotNull(TEXT("the built-in mannequin"), Built)) + { + return false; + } + for (const FName Bone : Fixture->Bones) + { + if (Built->GetRefSkeleton().FindRawBoneIndex(Bone) == INDEX_NONE) + { + AddError(FString::Printf(TEXT("the built-in mannequin lacks the uefn bone %s"), *Bone.ToString())); + } + } + + // A clip that moves a prop bone keeps that track (it was lost when the mannequin lacked the bone). A project's own UEFN mannequin is sampled + // instead of the built-in one when there is one, so this half only speaks for the built-in one. + if (FMantleCosmeticExport::FindUEFNMannequin(*Contract)) + { + return true; + } + const FName PropBone(TEXT("prop_01")); + UAnimSequence* Sequence = MakeClip(Built, TEXT("AS_CreatorProp"), PropBone); + FMantleCreatorClip Clip; + const bool bConverted = FMantleCreatorClips::ConvertToUefn(Sequence, Clip, Error); + Discard(Sequence); + if (TestTrue(FString::Printf(TEXT("a clip that only moves a prop bone converts (%s)"), *Error), bConverted)) + { + TestEqual(TEXT("with its track"), Clip.Tracks, 1); + } + return true; +} + +// The shared clip preview can hold a prop: it hangs from the named bone and follows the clip; none given, none shown. +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleCreatorClipsHeldItemTest, "Mantle.CreatorClips.ThePreviewsHeldItemFollowsTheHand", + EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter) + +bool FMantleCreatorClipsHeldItemTest::RunTest(const FString& Parameters) +{ + using namespace MantleCreatorClipsTestPrivate; + if (!FSlateApplication::IsInitialized()) + { + AddInfo(TEXT("Slate is not running here; the preview was not built.")); + return true; + } + FString Error; + const FMantleAvatarContract* Contract = FMantleAvatarContract::Get(&Error); + USkeletalMesh* Mannequin = Contract ? FMantleBuiltInMannequin::UEFNMannequin(*Contract, &Error) : nullptr; + UStaticMesh* Prop = LoadObject(nullptr, TEXT("/Engine/BasicShapes/Cube.Cube")); + if (!TestNotNull(FString::Printf(TEXT("the UEFN mannequin (%s)"), *Error), Mannequin) || !TestNotNull(TEXT("a prop"), Prop)) + { + return false; + } + TSharedRef Model = MakeShared(); + Model->PreviewMesh = Mannequin; + TSharedRef Control = SNew(SMantleClipSlots).Model(Model); + const TSharedPtr Stage = Control->GetPreviewViewport(); + if (!TestTrue(TEXT("the control has a preview stage"), Stage.IsValid())) + { + return false; + } + TestNull(TEXT("none given: nothing held"), Stage->GetHeldItem()); + + const FName Hand(TEXT("hand_r")); + Model->HeldItem.Mesh = Prop; + Model->HeldItem.Socket = Hand; + Model->HeldItem.Local = FTransform(FVector(5.0, 0.0, 0.0)); + Control->ShowPreviewBody(); + if (!TestNotNull(TEXT("the prop is held"), Stage->GetHeldItem())) + { + return false; + } + UAnimSequence* Clip = MakeClip(Mannequin, TEXT("AS_CreatorHeld"), TEXT("upperarm_r")); + FAssetCompilingManager::Get().FinishAllCompilation(); + const FBox Framed = Stage->GetFrameBox(); + TestTrue(TEXT("the camera holds the body"), Framed.IsValid && Framed == SMantleCosmeticPreviewViewport::BodyBox(Mannequin)); + TestTrue(TEXT("the built-in mannequin is framed at a body's height, not at its one triangle's"), + SMantleCosmeticPreviewViewport::BodyBox(FMantleBuiltInMannequin::Get()).GetSize().Z > 150.0); + Control->Preview(Clip); + TestTrue(TEXT("playing a clip, with a prop in hand, leaves the camera's frame as it was"), Stage->GetFrameBox() == Framed); + const auto Follows = [&Stage, &Model, Hand] + { + const FVector Expected = (Model->HeldItem.Local * Stage->GetBodySocket(Hand)).GetLocation(); + return Stage->GetHeldItem() && Stage->GetHeldItem()->GetComponentLocation().Equals(Expected, 0.1); + }; + Stage->PoseAt(0.0f); + const FVector Start = Stage->GetBodySocket(Hand).GetLocation(); + TestTrue(TEXT("at the clip's start the prop is at the hand"), Follows()); + Stage->PoseAt(0.9f); + TestFalse(TEXT("the clip moves the hand"), Stage->GetBodySocket(Hand).GetLocation().Equals(Start, 1.0)); + TestTrue(TEXT("and the prop with it"), Follows()); + + Model->HeldItem.Socket = TEXT("no_such_bone"); + Control->ShowPreviewBody(); + TestNull(TEXT("a bone the body lacks holds nothing"), Stage->GetHeldItem()); + Discard(Clip); + return true; +} + +// A pack row says which rig its clip was made on, and Play puts that clip on the preview as players will see it. +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleCreatorClipsPackPreviewTest, "Mantle.CreatorClips.APackRowNamesItsSourceRigAndPlaysTheClip", + EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter) + +bool FMantleCreatorClipsPackPreviewTest::RunTest(const FString& Parameters) +{ + using namespace MantleCreatorClipsTestPrivate; + TestEqual(TEXT("UEFN"), SMantleAnimPackSection::RigText(TEXT("uefn"), TEXT("SK_A")), FString(TEXT("Skeleton: UEFN"))); + TestEqual(TEXT("UE4"), SMantleAnimPackSection::RigText(TEXT("ue4mannequin"), TEXT("SK_A")), FString(TEXT("Skeleton: UE4 Mannequin (converted to UEFN)"))); + TestEqual(TEXT("UE5"), SMantleAnimPackSection::RigText(TEXT("ue5mannequin"), TEXT("SK_A")), FString(TEXT("Skeleton: UE5 Mannequin (converted to UEFN)"))); + TestEqual(TEXT("MetaHuman"), SMantleAnimPackSection::RigText(TEXT("metahuman"), TEXT("SK_A")), FString(TEXT("Skeleton: MetaHuman (converted to UEFN)"))); + TestEqual(TEXT("own rig"), SMantleAnimPackSection::RigText(FString(), TEXT("SK_A")), FString(TEXT("Skeleton: Own rig: SK_A"))); + + FString Error; + const FMantleAvatarContract* Contract = FMantleAvatarContract::Get(&Error); + USkeletalMesh* Mannequin = Contract ? FMantleBuiltInMannequin::UEFNMannequin(*Contract, &Error) : nullptr; + if (!TestNotNull(FString::Printf(TEXT("the UEFN mannequin (%s)"), *Error), Mannequin)) + { + return false; + } + UAnimSequence* Sequence = MakeClip(Mannequin, TEXT("AS_CreatorPackPreview"), TEXT("upperarm_r")); + TStrongObjectPtr Kept; + USkeletalMesh* Body = nullptr; + TestTrue(TEXT("a UEFN clip previews as it is"), FMantleCreatorClips::MakePreview(Sequence, Body, Kept, Error) == Sequence); + TestTrue(TEXT("on a body of its skeleton"), Body && Body->GetSkeleton() == Sequence->GetSkeleton()); + + if (FSlateApplication::IsInitialized()) + { + TSharedRef Model = MakeShared(); + Model->PreviewAs = [Mannequin, Sequence](UAnimSequence*, USkeletalMesh*& InOutBody) -> UAnimationAsset* + { + InOutBody = Mannequin; + return Sequence; + }; + TSharedRef Control = SNew(SMantleClipSlots).Model(Model); + Control->PlayClip(Sequence); + TestTrue(TEXT("Play shows the body the owner names"), Control->GetPreviewViewport()->GetShownBody() == Mannequin); + TestTrue(TEXT("and plays what the owner returns"), Control->GetPreviewViewport()->GetAnimation() == Sequence); + } + Discard(Sequence); + return true; +} + +#endif // WITH_DEV_AUTOMATION_TESTS diff --git a/Source/MantleEditor/Private/Tests/MantleCustomAvatarTest.cpp b/Source/MantleEditor/Private/Tests/MantleCustomAvatarTest.cpp index 060f3234..cc5f6249 100644 --- a/Source/MantleEditor/Private/Tests/MantleCustomAvatarTest.cpp +++ b/Source/MantleEditor/Private/Tests/MantleCustomAvatarTest.cpp @@ -13,6 +13,8 @@ #include "Dom/JsonObject.h" #include "Misc/AutomationTest.h" #include "SMantleClipSlots.h" +#include "MantleBuiltInMannequin.h" +#include "MantleCosmeticThumbnail.h" #include "MantleCosmeticPreviewViewport.h" #include "Animation/AnimSequence.h" #include "ReferenceSkeleton.h" @@ -597,6 +599,74 @@ bool FMantleClipPreviewTest::RunTest(const FString& Parameters) } +// The line over the slots mentions "Slots marked *" only when the table has a slot that needs a clip. +IMPLEMENT_SIMPLE_AUTOMATION_TEST( + FMantleClipSlotsHelpTest, + "Mantle.Editor.CustomAvatar.ClipSlotsHelp", + EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) + +bool FMantleClipSlotsHelpTest::RunTest(const FString& Parameters) +{ + for (const EMantleClipConversion Conversion : { EMantleClipConversion::RetargetToUefn, EMantleClipConversion::SampleOnOwnMesh }) + { + FMantleClipSlotsModel Model; + Model.Conversion = Conversion; + FMantleClipSlotDef& Slot = Model.Slots.AddDefaulted_GetRef(); + Slot.Name = TEXT("hold"); + TestFalse(TEXT("no slot required: the line does not speak of marked slots"), SMantleClipSlots::HelpText(Model).ToString().Contains(TEXT("marked *"))); + Model.Slots[0].bRequired = true; + TestTrue(TEXT("a required slot: the line says what * means"), SMantleClipSlots::HelpText(Model).ToString().Contains(TEXT("Slots marked * need a clip."))); + } + TestTrue(TEXT("no body on the stage: no line under the preview"), SMantleClipSlots::BodyNote(nullptr).IsEmpty()); + TestTrue(TEXT("a body with a mesh: no line"), SMantleClipSlots::BodyNote(LoadObject(nullptr, TEXT("/Engine/EngineMeshes/SkeletalCube.SkeletalCube"))).IsEmpty()); + TestFalse(TEXT("the built-in mannequin has no mesh: the line says so"), SMantleClipSlots::BodyNote(FMantleBuiltInMannequin::Get()).IsEmpty()); + return true; +} + + +// The preview holds the whole body in a view of any shape. +IMPLEMENT_SIMPLE_AUTOMATION_TEST( + FMantleClipPreviewFramingTest, + "Mantle.Editor.CustomAvatar.ClipPreviewFraming", + EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) + +bool FMantleClipPreviewFramingTest::RunTest(const FString& Parameters) +{ + const FBox Body(FVector(-90.0, -20.0, 0.0), FVector(90.0, 20.0, 185.0)); + const FRotator View(-4.0f, -70.0f, 0.0f); + constexpr float Fov = 45.0f; + for (const FIntPoint Size : { FIntPoint(870, 180), FIntPoint(260, 300), FIntPoint(300, 300) }) + { + for (const int32 Constraint : { int32(AspectRatio_MaintainXFOV), int32(AspectRatio_MajorAxisFOV) }) + { + const float Fit = SMantleCosmeticPreviewViewport::FitFieldOfView(Fov, Size, Constraint, 1.777777f); + const FVector Camera = FMantleCosmeticThumbnail::FrameCamera(Body, View, Fit, 1.0f); + // The tangents the engine draws with (FEditorViewportClient::CalcSceneView). + const double Base = FMath::Tan(FMath::DegreesToRadians(static_cast(Fov)) * 0.5); + const double Shape = static_cast(Size.X) / Size.Y; + const bool bMaintainX = Constraint == AspectRatio_MaintainXFOV || Size.X > Size.Y; + const double Vertical = bMaintainX ? Base / Shape : Base / 1.777777; + const double Horizontal = bMaintainX ? Base : Vertical * Shape; + const FRotationMatrix Axes(View); + bool bInside = true; + for (int32 Corner = 0; Corner < 8; ++Corner) + { + const FVector Point((Corner & 1) ? Body.Max.X : Body.Min.X, (Corner & 2) ? Body.Max.Y : Body.Min.Y, (Corner & 4) ? Body.Max.Z : Body.Min.Z); + const FVector Offset = Point - Camera; + const double Depth = Offset | Axes.GetUnitAxis(EAxis::X); + bInside &= Depth > 0.0 && FMath::Abs(Offset | Axes.GetUnitAxis(EAxis::Y)) <= Depth * Horizontal + 0.1 + && FMath::Abs(Offset | Axes.GetUnitAxis(EAxis::Z)) <= Depth * Vertical + 0.1; + } + TestTrue(FString::Printf(TEXT("head to feet is in view at %dx%d (constraint %d)"), Size.X, Size.Y, Constraint), bInside); + } + } + TestEqual(TEXT("a view not laid out yet keeps its field of view"), SMantleCosmeticPreviewViewport::FitFieldOfView(Fov, FIntPoint::ZeroValue, AspectRatio_MaintainXFOV, 1.0f), Fov); + + TestTrue(TEXT("the preview stands beside the slots only where there is width for both"), SMantleClipSlots::IsWideEnough(870.0f) && !SMantleClipSlots::IsWideEnough(400.0f)); + return true; +} + + // A publish or Test locally where materials cannot be read (no renderer) is refused in plain words instead of uploading white. IMPLEMENT_SIMPLE_AUTOMATION_TEST( FMantleCustomAvatarRendererTest, diff --git a/Source/MantleEditor/Private/Tests/MantleLibraryPublishTest.cpp b/Source/MantleEditor/Private/Tests/MantleLibraryPublishTest.cpp index beff8392..6098ee07 100644 --- a/Source/MantleEditor/Private/Tests/MantleLibraryPublishTest.cpp +++ b/Source/MantleEditor/Private/Tests/MantleLibraryPublishTest.cpp @@ -1,6 +1,7 @@ // Copyright Joshua Eger. All Rights Reserved. #include "MantleCosmeticPackage.h" #include "MantleLibraryPublish.h" +#include "MantlePlaceLimits.h" #include "Dom/JsonObject.h" #include "Misc/AutomationTest.h" @@ -215,7 +216,7 @@ bool FMantleLibraryPublishCapTest::RunTest(const FString& Parameters) { using namespace MantleLibraryPublishTestPrivate; TArray Declared; - for (int32 Index = 0; Index < 32; ++Index) + for (int32 Index = 0; Index < FMantlePlaceLimits::MaxStorageEntries; ++Index) { Declared.Add(FString::Printf(TEXT("{\"name\":\"Item%d\",\"item\":\"%s\",\"version\":1}"), Index, *ItemId(100 + Index))); } @@ -223,10 +224,10 @@ bool FMantleLibraryPublishCapTest::RunTest(const FString& Parameters) FString Out; FString Error; const TArray Refs = { MakeRef(AssetTruck, TEXT("Truck"), ItemId(1), 1) }; - TestFalse(TEXT("a 33rd item is refused"), FMantleLibraryPublish::RewritePlace(Json, Refs, Out, Error)); + TestFalse(TEXT("one item past the most a place stores is refused"), FMantleLibraryPublish::RewritePlace(Json, Refs, Out, Error)); TestFalse(TEXT("with a sentence saying why"), Error.IsEmpty()); - // The same 32 with a vehicle whose item is already one of them is not a 33rd. + // The same storage with a vehicle whose item is already in it is not one more. const TArray Known = { MakeRef(AssetTruck, TEXT("Truck"), ItemId(100), 5) }; TestTrue(TEXT("a new version of a stored item fits a full storage"), FMantleLibraryPublish::RewritePlace(Json, Known, Out, Error)); return true; diff --git a/Source/MantleEditor/Private/Tests/MantleLibraryTest.cpp b/Source/MantleEditor/Private/Tests/MantleLibraryTest.cpp index 04ec452c..80ecf260 100644 --- a/Source/MantleEditor/Private/Tests/MantleLibraryTest.cpp +++ b/Source/MantleEditor/Private/Tests/MantleLibraryTest.cpp @@ -2,6 +2,7 @@ #include "MantleApiClient.h" #include "MantleLibraryPanel.h" #include "MantlePlaceLimits.h" +#include "MantlePlaceSettingsActor.h" #include "MantlePlaceStorage.h" #include "MantleVehicleSpawnPoint.h" @@ -305,33 +306,61 @@ bool FMantleLibraryStorageSecondVersionTest::RunTest(const FString& Parameters) IMPLEMENT_SIMPLE_AUTOMATION_TEST( FMantleLibraryStorageCapTest, - "Mantle.Library.Storage.RefusesPastThe32Cap", + "Mantle.Library.Storage.CapsVehiclesWeaponsAndWheelsNotPackages", EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) bool FMantleLibraryStorageCapTest::RunTest(const FString& Parameters) { using namespace MantleLibraryTestPrivate; + // #475: 40 script packages and MaxStoredItems vehicles, weapons and wheels all fit. TArray Entries; - for (int32 Index = 1; Index <= FMantlePlaceLimits::MaxStorageEntries; ++Index) + TArray Settings; + const auto Add = [this, &Entries, &Settings](const int32 Number, const TCHAR* Kind) { - const FMantleLibraryAddPlan Plan = FMantleLibraryStorage::PlanAdd(Entries, ItemId(Index), TEXT("Car"), 1, TEXT("active")); - if (!TestTrue(FString::Printf(TEXT("item %d fits"), Index), Plan.Result == EMantleLibraryAdd::Added)) + const FMantleLibraryAddPlan Plan = FMantleLibraryStorage::PlanAdd(Entries, ItemId(Number), TEXT("Thing"), 1, TEXT("active"), Kind, + FMantleLibraryStorage::CountStoredItems(Settings)); + if (!TestTrue(FString::Printf(TEXT("item %d (%s) fits"), Number, Kind), Plan.Result == EMantleLibraryAdd::Added)) { AddError(Plan.Message); - return false; + return; } Entries.Add(Plan.Entry); + FMantleStorageSetting& Setting = Settings.AddDefaulted_GetRef(); + Setting.Kind = Kind; + }; + for (int32 Index = 1; Index <= 40; ++Index) + { + Add(Index, TEXT("script")); } - TestEqual(TEXT("the place holds the most it can"), Entries.Num(), FMantlePlaceLimits::MaxStorageEntries); - TestEqual(TEXT("and passes the place's rules"), FMantleStorage::CheckEntries(Entries).Num(), 0); + const TCHAR* const Kinds[] = { TEXT("vehicle"), TEXT("weapon"), TEXT("wheel") }; + for (int32 Index = 0; Index < FMantlePlaceLimits::MaxStoredItems; ++Index) + { + Add(100 + Index, Kinds[Index % 3]); + } + TestEqual(TEXT("packages do not count"), FMantleLibraryStorage::CountStoredItems(Settings), FMantlePlaceLimits::MaxStoredItems); + TestEqual(TEXT("and the storage passes the place's rules"), FMantleStorage::CheckEntries(Entries).Num(), 0); - const FMantleLibraryAddPlan Over = FMantleLibraryStorage::PlanAdd(Entries, ItemId(100), TEXT("Car"), 1, TEXT("active")); - TestTrue(TEXT("one more is refused as full"), Over.Result == EMantleLibraryAdd::Full); - TestTrue(TEXT("with the cap in the message"), Over.Message.Contains(FString::FromInt(FMantlePlaceLimits::MaxStorageEntries))); + for (const TCHAR* Kind : Kinds) + { + const FMantleLibraryAddPlan Over = FMantleLibraryStorage::PlanAdd(Entries, ItemId(500), TEXT("Thing"), 1, TEXT("active"), Kind, + FMantleLibraryStorage::CountStoredItems(Settings)); + TestTrue(FString::Printf(TEXT("one more %s is refused as full"), Kind), Over.Result == EMantleLibraryAdd::Full); + TestTrue(TEXT("with the cap in the message"), Over.Message.Contains(FString::FromInt(FMantlePlaceLimits::MaxStoredItems))); + } + Add(501, TEXT("script")); - // An item already stored is reported as stored, even in a full place: that is what the creator should fix. - const FMantleLibraryAddPlan Again = FMantleLibraryStorage::PlanAdd(Entries, ItemId(1), TEXT("Car"), 2, TEXT("active")); + // An item already stored is reported as stored, even then: that is what the creator should fix. + const FMantleLibraryAddPlan Again = FMantleLibraryStorage::PlanAdd(Entries, ItemId(100), TEXT("Thing"), 2, TEXT("active"), TEXT("vehicle"), + FMantlePlaceLimits::MaxStoredItems); TestTrue(TEXT("a stored item is reported as stored"), Again.Result == EMantleLibraryAdd::AlreadyStored); + + // The whole storage has its own, much larger limit. + while (Entries.Num() < FMantlePlaceLimits::MaxStorageEntries) + { + Entries.Add(MakeEntry(FString::Printf(TEXT("Fill%d"), Entries.Num()), ItemId(1000 + Entries.Num()), 1)); + } + const FMantleLibraryAddPlan Full = FMantleLibraryStorage::PlanAdd(Entries, ItemId(502), TEXT("Thing"), 1, TEXT("active"), TEXT("script"), 0); + TestTrue(TEXT("a package past the most a place stores is refused as full"), Full.Result == EMantleLibraryAdd::Full); return true; } diff --git a/Source/MantleEditor/Private/Tests/MantleWeaponBuilderConsumableTest.cpp b/Source/MantleEditor/Private/Tests/MantleWeaponBuilderConsumableTest.cpp index 117fe41c..914c8f64 100644 --- a/Source/MantleEditor/Private/Tests/MantleWeaponBuilderConsumableTest.cpp +++ b/Source/MantleEditor/Private/Tests/MantleWeaponBuilderConsumableTest.cpp @@ -1,9 +1,17 @@ // Copyright Joshua Eger. All Rights Reserved. +#include "MantleAvatarContract.h" +#include "MantleBuiltInMannequin.h" #include "MantleWeaponBuilderExport.h" +#include "MantleConsumableEffect.h" #include "MantleWeaponBuilderLogic.h" #include "MantleWeaponDocument.h" #include "MantleWeaponSource.h" +#include "Animation/AnimData/IAnimationDataController.h" +#include "Animation/AnimSequence.h" +#include "AssetCompilingManager.h" +#include "Engine/SkeletalMesh.h" #include "Misc/AutomationTest.h" +#include "UObject/Package.h" #if WITH_DEV_AUTOMATION_TESTS namespace MantleWeaponBuilderConsumableTestPrivate @@ -23,6 +31,23 @@ namespace MantleWeaponBuilderConsumableTestPrivate Points.Add(FName(TEXT("Grip")), FTransform(FQuat::Identity, FVector(0.0, 0.0, -6.0))); return Points; } + + /** A clip of Frames frames at 30 per second, made in memory on Mesh's skeleton; only its length matters here. */ + UAnimSequence* MakeTimedClip(USkeletalMesh* Mesh, const TCHAR* Name, const int32 Frames) + { + UPackage* Package = CreatePackage(*FString::Printf(TEXT("/Game/__MantleEffectTest/%s"), Name)); + UAnimSequence* Sequence = NewObject(Package, Name, RF_Public | RF_Standalone | RF_Transient); + Sequence->SetSkeleton(Mesh->GetSkeleton()); + Sequence->SetPreviewMesh(Mesh); + IAnimationDataController& Controller = Sequence->GetController(); + Controller.InitializeModel(); + Controller.OpenBracket(FText::FromString(TEXT("Consumable effect test")), false); + Controller.SetFrameRate(FFrameRate(30, 1), false); + Controller.SetNumberOfFrames(FFrameNumber(Frames), false); + Controller.NotifyPopulated(); + Controller.CloseBracket(false); + return Sequence; + } } // #1025: a consumable builds a use document (no fire), in both styles, and the document survives a write and a read. @@ -111,4 +136,163 @@ bool FMantleWeaponBuilderConsumableNoEffectTest::RunTest(const FString& Paramete TestTrue(TEXT("the document reads back"), FMantleWeaponDocument::Parse(Json, Back, Error)); return true; } +// mantle #333: a consumable's clips block names the copies made in its folder; one animation in two slots is one copy, and a clip needs the consumable hold (the document check refuses it elsewhere). +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleWeaponBuilderConsumableClipsTest, "Mantle.Editor.WeaponBuilderConsumable.ExportsTheClipsBlock", EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) +bool FMantleWeaponBuilderConsumableClipsTest::RunTest(const FString& Parameters) +{ + using namespace MantleWeaponBuilderConsumableTestPrivate; + UMantleWeaponSource* Input = MakeConsumable(EMantleWeaponSourceUseStyle::Use); + Input->ClipHold = TSoftObjectPtr(FSoftObjectPath(TEXT("/Game/__MantleClipsTest/AS_Sip.AS_Sip"))); + Input->ClipUse = Input->ClipHold; + Input->ClipPutAway = TSoftObjectPtr(FSoftObjectPath(TEXT("/Game/__MantleClipsTest/AS_Away.AS_Away"))); + FMantleWeaponDesc Desc; + TArray Messages; + if (!TestTrue(TEXT("a consumable with clips builds"), FMantleWeaponBuilderExport::BuildDocument(*Input, GripPoint(), TEXT("FixtureMesh"), Desc, Messages))) + { + for (const FText& Message : Messages) AddError(Message.ToString()); + return true; + } + TestTrue(TEXT("it has a clips block"), Desc.bClips); + TestFalse(TEXT("hold names a copy"), Desc.ClipHold.IsEmpty()); + TestEqual(TEXT("one animation in two slots is one copy"), Desc.ClipUse, Desc.ClipHold); + TestTrue(TEXT("equip is left out"), Desc.ClipEquip.IsEmpty()); + TestTrue(TEXT("putAway is another copy"), !Desc.ClipPutAway.IsEmpty() && Desc.ClipPutAway != Desc.ClipHold); + + const FString Json = FMantleWeaponDocument::Write(Desc); + TestTrue(TEXT("the document writes the block"), Json.Contains(TEXT("\"clips\"")) && Json.Contains(TEXT("\"putAway\"")) && !Json.Contains(TEXT("\"equip\""))); + FMantleWeaponDesc Back; + FString Error; + if (TestTrue(FString::Printf(TEXT("it reads back (%s)"), *Error), FMantleWeaponDocument::Parse(Json, Back, Error))) + { + TestEqual(TEXT("and writes the same text"), FMantleWeaponDocument::Write(Back), Json); + } + + // No clips set: no block at all. + UMantleWeaponSource* Plain = MakeConsumable(EMantleWeaponSourceUseStyle::Use); + FMantleWeaponDesc PlainDesc; + TArray PlainMessages; + TestTrue(TEXT("a consumable without clips builds"), FMantleWeaponBuilderExport::BuildDocument(*Plain, GripPoint(), TEXT("FixtureMesh"), PlainDesc, PlainMessages)); + TestFalse(TEXT("and has no clips block"), PlainDesc.bClips); + + return true; +} + +// mantle #333 G4: stamina, hunger and thirst each write their own effect and amount, no other's, and survive a write and a read. +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleWeaponBuilderConsumableEffectsTest, "Mantle.Editor.WeaponBuilderConsumable.ExportsEachEffect", EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) +bool FMantleWeaponBuilderConsumableEffectsTest::RunTest(const FString& Parameters) +{ + using namespace MantleWeaponBuilderConsumableTestPrivate; + const TPair Effects[] = { + { EMantleWeaponSourceConsumableEffect::Stamina, TEXT("stamina") }, + { EMantleWeaponSourceConsumableEffect::Hunger, TEXT("hunger") }, + { EMantleWeaponSourceConsumableEffect::Thirst, TEXT("thirst") }, + }; + for (const auto& Effect : Effects) + { + UMantleWeaponSource* Input = MakeConsumable(EMantleWeaponSourceUseStyle::EatDrink); + Input->Consumable.Effect = Effect.Key; + Input->Consumable.Amount = 250.f; + FMantleWeaponDesc Desc; + TArray Messages; + if (!TestTrue(FString::Printf(TEXT("%s builds"), Effect.Value), FMantleWeaponBuilderExport::BuildDocument(*Input, GripPoint(), TEXT("FixtureMesh"), Desc, Messages))) + { + for (const FText& Message : Messages) AddError(Message.ToString()); + continue; + } + const FString Json = FMantleWeaponDocument::Write(Desc); + TestTrue(FString::Printf(TEXT("%s: the effect is named"), Effect.Value), Json.Contains(FString::Printf(TEXT("\"%s\""), Effect.Value))); + FMantleWeaponDesc Back; + FString Error; + if (TestTrue(FString::Printf(TEXT("%s reads back"), Effect.Value), FMantleWeaponDocument::Parse(Json, Back, Error))) + { + TestEqual(TEXT("and writes the same text"), FMantleWeaponDocument::Write(Back), Json); + const FMantleWeaponDocConsumable& C = Back.Consumable.Value; + const TMantleWeaponDocValue* const Amounts[] = { &C.Stamina, &C.Hunger, &C.Thirst }; + for (int32 Index = 0; Index < UE_ARRAY_COUNT(Amounts); ++Index) + { + const bool bOwn = Effects[Index].Key == Effect.Key; + TestEqual(FString::Printf(TEXT("%s: only its own amount is written (%s)"), Effect.Value, Effects[Index].Value), Amounts[Index]->bSet, bOwn); + if (bOwn) TestEqual(TEXT("with the number typed"), Amounts[Index]->Value, 250.0); + } + TestFalse(FString::Printf(TEXT("%s: no heal numbers"), Effect.Value), C.Heal.bSet || C.HealSeconds.bSet); + } + else + { + AddError(Error); + } + Input->Consumable.Amount = 0.f; + TestFalse(FString::Printf(TEXT("%s: an amount of 0 is refused"), Effect.Value), FMantleWeaponBuilderExport::BuildDocument(*Input, GripPoint(), TEXT("FixtureMesh"), Desc, Messages)); + Input->Consumable.Amount = 10001.f; + TestFalse(FString::Printf(TEXT("%s: an amount above 10000 is refused"), Effect.Value), FMantleWeaponBuilderExport::BuildDocument(*Input, GripPoint(), TEXT("FixtureMesh"), Desc, Messages)); + } + return true; +} + +// mantle #333: the hidden effect moment is 0.6 x the Use clip's length, at least 0.1 s before its end, and is written only with a Use clip. +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleWeaponBuilderConsumableEffectMomentTest, "Mantle.Editor.WeaponBuilderConsumable.WritesTheEffectMoment", EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) +bool FMantleWeaponBuilderConsumableEffectMomentTest::RunTest(const FString& Parameters) +{ + using namespace MantleWeaponBuilderConsumableTestPrivate; + TestEqual(TEXT("a long clip: its share"), FMantleConsumableEffect::MomentIn(2.5).Get(-1.0), 1.5); + TestEqual(TEXT("a short clip: the margin before its end"), FMantleConsumableEffect::MomentIn(0.2).Get(-1.0), 0.1); + TestEqual(TEXT("shorter than the margin: the start"), FMantleConsumableEffect::MomentIn(0.05).Get(-1.0), 0.0); + TestFalse(TEXT("no length: no moment"), FMantleConsumableEffect::MomentIn(0.0).IsSet()); + + FString MeshError; + const FMantleAvatarContract* Contract = FMantleAvatarContract::Get(&MeshError); + USkeletalMesh* Mannequin = Contract ? FMantleBuiltInMannequin::UEFNMannequin(*Contract, &MeshError) : nullptr; + if (!TestNotNull(FString::Printf(TEXT("the UEFN mannequin (%s)"), *MeshError), Mannequin)) + { + return false; + } + UAnimSequence* Clip = MakeTimedClip(Mannequin, TEXT("AS_EffectUse"), 60); + UMantleWeaponSource* Input = MakeConsumable(EMantleWeaponSourceUseStyle::Use); + const auto Build = [this](const UMantleWeaponSource& Source) + { + FMantleWeaponDesc Desc; + TArray Messages; + if (!TestTrue(TEXT("it builds"), FMantleWeaponBuilderExport::BuildDocument(Source, GripPoint(), TEXT("FixtureMesh"), Desc, Messages))) + { + for (const FText& Message : Messages) AddError(Message.ToString()); + } + return Desc; + }; + + // Without a Use clip nothing is written, even with other clips. + Input->ClipHold = Clip; + TestFalse(TEXT("no Use clip, no moment"), Build(*Input).UseEffectSeconds.bSet); + TestTrue(TEXT("and no line"), FMantleConsumableEffect::Line(*Input).IsEmpty()); + + Input->ClipUse = Clip; + const FMantleWeaponDesc Desc = Build(*Input); + TestTrue(TEXT("a Use clip writes the moment"), Desc.UseEffectSeconds.bSet); + TestEqual(TEXT("0.6 of two seconds"), Desc.UseEffectSeconds.Value, 1.2); + TestEqual(TEXT("the line"), FMantleConsumableEffect::Line(*Input).ToString(), FString(TEXT("The effect happens at 1.2 s."))); + const FString Json = FMantleWeaponDocument::Write(Desc); + FMantleWeaponDesc Back; + FString Error; + if (TestTrue(TEXT("the document reads back"), FMantleWeaponDocument::Parse(Json, Back, Error))) + { + TestEqual(TEXT("with the moment"), Back.UseEffectSeconds.Value, 1.2); + } + else + { + AddError(Error); + } + + // A chosen use time speeds the clip up: the document keeps the clip's own seconds, the line says when it happens as played. + Input->Consumable.bOverrideUseSeconds = true; + Input->Consumable.UseSeconds = 4.0f; + TestEqual(TEXT("the document keeps clip seconds"), Build(*Input).UseEffectSeconds.Value, 1.2); + TestEqual(TEXT("the line scales"), FMantleConsumableEffect::Line(*Input).ToString(), FString(TEXT("The effect happens at 2.4 s."))); + + Input->ClipHold.Reset(); + Input->ClipUse.Reset(); + // A made clip compresses in the background; thrown away before that lands, the engine warns. + FAssetCompilingManager::Get().FinishAllCompilation(); + Clip->ClearFlags(RF_Public | RF_Standalone); + Clip->MarkAsGarbage(); + return true; +} + #endif diff --git a/Source/MantleEditor/Private/Tests/MantleWeaponFitTest.cpp b/Source/MantleEditor/Private/Tests/MantleWeaponFitTest.cpp index 1b4cd4fe..c2503561 100644 --- a/Source/MantleEditor/Private/Tests/MantleWeaponFitTest.cpp +++ b/Source/MantleEditor/Private/Tests/MantleWeaponFitTest.cpp @@ -1,5 +1,7 @@ // Copyright Joshua Eger. All Rights Reserved. #include "MantleWeaponFit.h" +#include "MantleBuilderPoint.h" +#include "MantleWeaponBuilderKind.h" #include "Misc/AutomationTest.h" @@ -492,4 +494,52 @@ bool FMantleWeaponFitStaffTest::RunTest(const FString& Parameters) return true; } +IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMantleWeaponFitItemUprightTest, "Mantle.Editor.WeaponFit.ATallItemStaysUpright", + EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) +bool FMantleWeaponFitItemUprightTest::RunTest(const FString& Parameters) +{ + using namespace MantleWeaponFitTestPrivate; + struct FCase + { + const TCHAR* What; + FVector Size; + /** The mesh axis that ends up forward. */ + FVector Front; + }; + const FCase Cases[] = { + { TEXT("a tall bottle"), FVector(6, 6, 25), FVector::XAxisVector }, + { TEXT("a phone standing, wider than it is deep"), FVector(1, 7, 15), FVector::XAxisVector }, + { TEXT("a rod lying along X"), FVector(30, 5, 5), FVector::XAxisVector }, + { TEXT("a flashlight lying along Y"), FVector(6, 30, 8), FVector::YAxisVector }, + }; + for (const EMantleWeaponFitHold Hold : { EMantleWeaponFitHold::Consumable, EMantleWeaponFitHold::Item }) + { + for (const FCase& Case : Cases) + { + // Standing on its pivot. + TArray Positions; + AddBox(Positions, FVector(-0.5 * Case.Size.X, -0.5 * Case.Size.Y, 0.0), FVector(0.5 * Case.Size.X, 0.5 * Case.Size.Y, Case.Size.Z)); + FMantleWeaponFitInput In; + In.Positions = Positions; + In.Hold = Hold; + const FMantleWeaponFitResult Fit = FMantleWeaponFit::Fit(In); + const FQuat Turn = Fit.MeshToWeapon.GetRotation(); + TestTrue(FString::Printf(TEXT("%s keeps its own up"), Case.What), Turn.RotateVector(FVector::UpVector).Equals(FVector::UpVector, 1.0e-4)); + TestTrue(FString::Printf(TEXT("%s: the front"), Case.What), Turn.RotateVector(Case.Front).Equals(FVector::ForwardVector, 1.0e-4)); + TestEqual(FString::Printf(TEXT("%s is sized by its longest side"), Case.What), double(Fit.LengthCm), Case.Size.GetMax(), 0.01); + + // So the default grip is the bottom it stands on. + FMantleWeaponBuilderKind Kind(Hold); + const TArray Guesses = Kind.GuessPointsFromPositions(Positions, TArray()); + const FMantleBuilderPoint* Grip = Guesses.FindByPredicate([](const FMantleBuilderPoint& Point) { return Point.Role == FName(TEXT("Grip")); }); + if (TestNotNull(FString::Printf(TEXT("%s has a grip"), Case.What), Grip)) + { + TestTrue(FString::Printf(TEXT("%s is held at its bottom (%s)"), Case.What, *Grip->Transform.GetLocation().ToString()), + Grip->Transform.GetLocation().Equals(FVector::ZeroVector, 0.01)); + } + } + } + return true; +} + #endif // WITH_DEV_AUTOMATION_TESTS diff --git a/Source/MantleEditor/Private/Tests/MantleWeaponPublishPartsTest.cpp b/Source/MantleEditor/Private/Tests/MantleWeaponPublishPartsTest.cpp index 8c245d26..76fc41a1 100644 --- a/Source/MantleEditor/Private/Tests/MantleWeaponPublishPartsTest.cpp +++ b/Source/MantleEditor/Private/Tests/MantleWeaponPublishPartsTest.cpp @@ -1,5 +1,7 @@ // Copyright Joshua Eger. All Rights Reserved. #include "MantleAssetCleanup.h" +#include "MantleAvatarContract.h" +#include "MantleBuiltInMannequin.h" #include "MantlePlaceAssetConverter.h" #include "MantlePlaceAssets.h" #include "MantlePng.h" @@ -11,6 +13,7 @@ #include "MantleWeaponSource.h" #include "AssetRegistry/AssetRegistryModule.h" +#include "Animation/AnimSequence.h" #include "Engine/SkeletalMesh.h" #include "Engine/StaticMesh.h" #include "Materials/Material.h" @@ -445,4 +448,84 @@ bool FMantleWeaponPublishRoundTest::RunTest(const FString& Parameters) return true; } +// mantle #333: an item's clips are limited together (8 MiB), and a clip another weapon of the same publish already converted still counts. +IMPLEMENT_SIMPLE_AUTOMATION_TEST( + FMantleWeaponPublishSharedClipTotalTest, + "Mantle.WeaponPublish.Parts.AClipAlreadyConvertedStillCountsTowardTheItemTotal", + EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::ProductFilter) + +bool FMantleWeaponPublishSharedClipTotalTest::RunTest(const FString& Parameters) +{ + using namespace MantleWeaponPublishPartsTestPrivate; + UStaticMesh* Cube = LoadObject(nullptr, TEXT("/Engine/BasicShapes/Cube.Cube")); + FString Error; + const FMantleAvatarContract* Contract = FMantleAvatarContract::Get(&Error); + USkeletalMesh* Mannequin = Contract ? FMantleBuiltInMannequin::UEFNMannequin(*Contract, &Error) : nullptr; + if (!TestNotNull(TEXT("fixture cube"), Cube) || !TestNotNull(FString::Printf(TEXT("the UEFN mannequin (%s)"), *Error), Mannequin)) + { + return false; + } + + FExportedWeapon Item; + UMantleWeaponSource* Input = NewObject(); + Input->DisplayName = Item.Name; + Input->Hold = EMantleWeaponHold::Consumable; + Input->Model = Cube; + Input->bScaleOverridden = true; + Input->FitScale = 1.f; + TArray Messages; + if (!TestTrue(TEXT("the builder exports the item"), FMantleWeaponBuilderExport::Export(*Input, Messages))) + { + for (const FText& Message : Messages) + { + AddError(Message.ToString()); + } + return false; + } + // Two clips in its folder, named in its settings file. Their bytes are what an earlier item of the same publish converted. + TArray Keys; + for (const TCHAR* Name : { TEXT("Hold_A"), TEXT("Use_A") }) + { + UPackage* Package = CreatePackage(*(Item.PackageFolder() / Name)); + UAnimSequence* Sequence = NewObject(Package, Name, RF_Public | RF_Standalone | RF_Transient); + Sequence->SetSkeleton(Mannequin->GetSkeleton()); + Keys.Add(FString::Printf(TEXT("itemclip:%s"), *Sequence->GetPathName())); + } + const FString File = Item.Folder() / (Item.Name + TEXT(".weapon.json")); + FString Text; + if (!TestTrue(TEXT("its settings file is written"), FFileHelper::LoadFileToString(Text, *File))) + { + return false; + } + const int32 Open = Text.Find(TEXT("{")); + Text.InsertAt(Open + 1, TEXT("\"clips\":{\"hold\":\"Hold_A\",\"use\":\"Use_A\"},")); + if (!TestTrue(TEXT("the clips block is saved"), FFileHelper::SaveStringToFile(Text, *File))) + { + return false; + } + FMantlePlaceDependencies Dependencies; + if (!TestTrue(TEXT("the item is gathered"), Dependencies.AddBuiltWeapon(Item.Name, TEXT("Spawn"))) || !TestEqual(TEXT("one item"), Dependencies.Weapons.Num(), 1)) + { + return false; + } + + const auto Convert = [&](const int32 BytesEach, FMantlePlaceAssetSet& Set) + { + for (const FString& Key : Keys) + { + FMantleConvertedClip& Earlier = Set.Clips.AddDefaulted_GetRef(); + Earlier.Key = Key; + Earlier.Bytes.SetNumZeroed(BytesEach); + } + FMantlePlaceAssetConverter Converter; + return Converter.ConvertWeapon(Dependencies.Weapons[0], Set); + }; + FMantlePlaceAssetSet Fits; + TestTrue(TEXT("two earlier 4 MiB clips are exactly the item's room"), Convert(4 << 20, Fits)); + FMantlePlaceAssetSet Over; + TestFalse(TEXT("two earlier 5 MiB clips are too much together"), Convert(5 << 20, Over)); + TestTrue(TEXT("and the refusal says so"), Over.Issues.ContainsByPredicate([](const FMantleValidationIssue& Issue) { return Issue.Problem.Contains(TEXT("together")); })); + return true; +} + #endif // WITH_DEV_AUTOMATION_TESTS diff --git a/Source/MantleEditor/Private/Tests/MantleWeaponPublishTest.cpp b/Source/MantleEditor/Private/Tests/MantleWeaponPublishTest.cpp index 617fefde..897fe53c 100644 --- a/Source/MantleEditor/Private/Tests/MantleWeaponPublishTest.cpp +++ b/Source/MantleEditor/Private/Tests/MantleWeaponPublishTest.cpp @@ -402,7 +402,7 @@ bool FMantleWeaponPublishSourceTest::RunTest(const FString& Parameters) using namespace MantleWeaponPublishTestPrivate; TestFalse(TEXT("a name outside the builder's folder is refused"), FMantleWeaponPublishSource::ProblemWith(TEXT("..\\Elsewhere")).IsEmpty()); TestTrue(TEXT("a weapon with no settings file is refused in plain words"), - FMantleWeaponPublishSource::ProblemWith(TEXT("ZzNoSuchWeapon")).Contains(TEXT("Press Create weapon"))); + FMantleWeaponPublishSource::ProblemWith(TEXT("ZzNoSuchWeapon")).Contains(TEXT("Press Create item"))); { FBuiltWeaponFolder Sword(TEXT("melee_1h")); diff --git a/Source/MantleEditor/Public/MantlePlaceAssetConverter.h b/Source/MantleEditor/Public/MantlePlaceAssetConverter.h index ad4dfcd3..ed69c3d0 100644 --- a/Source/MantleEditor/Public/MantlePlaceAssetConverter.h +++ b/Source/MantleEditor/Public/MantlePlaceAssetConverter.h @@ -49,6 +49,8 @@ enum class EMantlePlaceUploadStage : uint8 Wheel, /** A Custom avatar (#326): its document names its skeletal mesh's, materials' and clips' ids, so it goes after them. */ CustomAvatar, + /** An animation pack (#333 G10): its document names its clips' ids, so it goes after them. */ + AnimPack, /** A cell file of the place's scenery (large places): it names assets by id only, uploaded by a queue of its own after them. */ Cell, /** The cell index: it names the cell files' uploaded ids, so it goes after them. */ @@ -576,6 +578,9 @@ struct MANTLEEDITOR_API FMantleConvertedWeapon /** #898: FMantlePlaceAssets::SoundKey of the attack sounds (sounds.fire, sounds.fireSuppressed), empty for one the file leaves. */ FString FireSoundKey; FString FireSuppressedSoundKey; + + /** mantle #333: slot name (hold, use, equip, putAway) and the key of the animclip upload (FMantlePlaceAssetSet::Clips) that clips. names. */ + TArray> ClipKeys; }; /** @@ -652,6 +657,31 @@ struct MANTLEEDITOR_API FMantleConvertedCustomAvatar FString ThumbnailKey; }; +/** + * One animation pack (#333 G10), ready but for its ids: each clip's name, the key of its animclip upload (FMantleConvertedClip::Key) and + * its skeleton field ("uefn" or a skeleton hash). FMantlePlaceAssetSet::AnimPackBytes writes its document (FMantleAnimPack::WriteDocument) + * once the clips have ids. + */ +struct MANTLEEDITOR_API FMantleConvertedAnimPack +{ + struct FEntry + { + FString Name; + FString ClipKey; + FString Skeleton; + }; + + /** The publish's key. */ + FString Key; + FString Name; + + /** /Game/MantleAnimPacks/: what its library item is remembered under. */ + FString Path; + + /** The clips, in the order the creator gave them. */ + TArray Entries; +}; + /** One file for the upload queue (F4 #338): its kind and options, bytes, content address, and the Unreal asset to name in messages. */ struct MANTLEEDITOR_API FMantlePlaceUpload { @@ -716,6 +746,9 @@ struct MANTLEEDITOR_API FMantlePlaceAssetSet /** Custom avatars (#326), uploaded after the wheels: their documents name their body's, materials' and clips' ids. */ TArray CustomAvatars; + /** Animation packs (#333 G10), uploaded after the Custom avatars: their documents name their clips' ids. */ + TArray AnimPacks; + /** What conversion changed or could not do, in plain words, naming the Unreal asset. Errors stop the publish. */ TArray Issues; @@ -758,6 +791,7 @@ struct MANTLEEDITOR_API FMantlePlaceAssetSet const FMantleConvertedWeapon* FindWeapon(const FString& Key) const; const FMantleConvertedWheel* FindWheel(const FString& Key) const; const FMantleConvertedCustomAvatar* FindCustomAvatar(const FString& Key) const; + const FMantleConvertedAnimPack* FindAnimPack(const FString& Key) const; /** Records an uploaded (or already held) asset under its local key. */ void RecordUpload(const FString& Key, const FString& Id, const FString& Hash, int64 Bytes); @@ -859,6 +893,9 @@ struct MANTLEEDITOR_API FMantlePlaceAssetSet /** A Custom avatar's upload bytes: its document with the uploaded ids of its body, materials and clips. False naming the first without an id. */ bool CustomAvatarBytes(const FMantleConvertedCustomAvatar& Avatar, TArray& OutBytes, FString& OutError) const; + /** An animation pack's upload bytes: its document (FMantleAnimPack::WriteDocument) with the uploaded id of each clip. False naming the first clip without an id. */ + bool AnimPackBytes(const FMantleConvertedAnimPack& Pack, TArray& OutBytes, FString& OutError) const; + /** A wheel's upload bytes: its document (FMantleWheelDocument::Build) with the uploaded ids of its model and materials. False naming the first without an id. */ bool WheelBytes(const FMantleConvertedWheel& Wheel, TArray& OutBytes, FString& OutError) const; @@ -1162,6 +1199,14 @@ class MANTLEEDITOR_API FMantlePlaceAssetConverter */ bool ConvertWeapon(const FMantleGatheredWeapon& Weapon, FMantlePlaceAssetSet& Out); + /** + * mantle #333: an item's own clips by slot (FMantleBuiltWeaponParts::Clips), converted to the UEFN mannequin's skeleton and added + * to Out as animclips, checked one by one and together. OutSlotKeys gets {slot, upload key} per filled slot. False, with the + * reasons in Out.Issues and no clip added, when one cannot be used. + */ + bool ConvertItemClips(const FString& WeaponName, const TMap& Clips, FMantlePlaceAssetSet& Out, + TArray>& OutSlotKeys); + /** * A wheel's library picture (#124), the same shared thumbnail system a weapon's uses: the creator's saved choice for this wheel * (FMantleThumbnailStore, class "wheel", under WheelThumbnailStoreKey; Automatic when none) resolved against a render of Model in the diff --git a/Source/MantleEditor/Public/MantlePlaceAssets.h b/Source/MantleEditor/Public/MantlePlaceAssets.h index 9da34332..d73c8948 100644 --- a/Source/MantleEditor/Public/MantlePlaceAssets.h +++ b/Source/MantleEditor/Public/MantlePlaceAssets.h @@ -670,6 +670,12 @@ struct MANTLEEDITOR_API FMantleBuiltWeaponParts /** sounds.fire and sounds.fireSuppressed; null when the file names none. */ USoundWave* Fire = nullptr; USoundWave* FireSuppressed = nullptr; + + /** + * mantle #333: clips.hold, clips.use, clips.equip and clips.putAway (FMantleCreatorClips::ItemSlotNames) that name an animation + * in the weapon's folder, by slot name. A slot that names an uploaded id (ast_...) or none is not here. + */ + TMap Clips; }; /** diff --git a/Source/MantleEditor/Public/MantlePlacePublishSession.h b/Source/MantleEditor/Public/MantlePlacePublishSession.h index e5f1f7ad..573a548c 100644 --- a/Source/MantleEditor/Public/MantlePlacePublishSession.h +++ b/Source/MantleEditor/Public/MantlePlacePublishSession.h @@ -511,7 +511,7 @@ class MANTLEEDITOR_API FMantlePlacePublishSession : public TSharedFromThis 0 || Set.Weapons.Num() > 0 || Set.Wheels.Num() > 0 || Set.CustomAvatars.Num() > 0 || Packages.Num() > 0) && !IsFinished(); } + bool NeedsVehicleChoice() const { return bGoLive && (Set.Vehicles.Num() > 0 || Set.Weapons.Num() > 0 || Set.Wheels.Num() > 0 || Set.CustomAvatars.Num() > 0 || Set.AnimPacks.Num() > 0 || Packages.Num() > 0) && !IsFinished(); } /** True while the Library step has nothing to do but wait for a valid VehicleChoice. */ bool IsWaitingForVehicleChoice() const { return Phase == EMantlePublishPhase::Library && !VehicleChoice.IsReady(); } @@ -611,6 +611,7 @@ class MANTLEEDITOR_API FMantlePlacePublishSession : public TSharedFromThis Mantle. */ +/** The "Build an item" window's tab (#729): registered at module startup, opened from Tools > Mantle. */ struct MANTLEEDITOR_API FMantleWeaponBuilderPanel { static const FName TabName; diff --git a/Source/MantleEditor/Public/MantleWeaponFit.h b/Source/MantleEditor/Public/MantleWeaponFit.h index 1f3775ee..62af2132 100644 --- a/Source/MantleEditor/Public/MantleWeaponFit.h +++ b/Source/MantleEditor/Public/MantleWeaponFit.h @@ -14,7 +14,7 @@ enum class EMantleWeaponFitHold : uint8 PumpShotgun, BoltSniper, Lmg, - Melee1h, Melee2h, Spear, Staff, Bow, Unarmed, Shield, Throwable, Consumable, + Melee1h, Melee2h, Spear, Staff, Bow, Unarmed, Shield, Throwable, Consumable, Item, Count }; @@ -104,6 +104,10 @@ struct MANTLEEDITOR_API FMantleWeaponFit * the larger of the other two; a grenade or a ball is compact and is held at its middle (#840). */ static constexpr double ElongatedThrowableRatio = 2.5; + /** A consumable and a usable item keep the model's own up and front; one whose Y side is more than this many times its other sides lies + * along Y, and is turned a quarter to point forward. */ + static constexpr double ItemLyingAlongYRatio = 1.25; + /** A shield's Grip guess (the middle of the left palm) sits this far behind the back of the shield, at its middle: the * SwordShield pack's palm is 0.5 to 2.4 cm behind its shield's back in the idle and the guard (#840 step 2). */ static constexpr double ShieldPalmBehindCm = 1.5; diff --git a/Source/MantleEditor/Public/SMantleBuilderFlow.h b/Source/MantleEditor/Public/SMantleBuilderFlow.h index 625f646e..1d765c91 100644 --- a/Source/MantleEditor/Public/SMantleBuilderFlow.h +++ b/Source/MantleEditor/Public/SMantleBuilderFlow.h @@ -51,6 +51,11 @@ class MANTLEEDITOR_API SMantleBuilderFlow : public SCompoundWidget /** Builds the current step's content again, e.g. after something it shows has changed. */ void Refresh(); + /** Replaces the steps (a builder whose screens depend on an earlier choice) and stays on the current one, drawing the bar and content again. */ + void SetSteps(const TArray& InSteps); + + const TArray& GetSteps() const { return Steps; } + private: TSharedRef MakeStepBar(); TSharedRef MakeStepButton(int32 Index); @@ -59,6 +64,7 @@ class MANTLEEDITOR_API SMantleBuilderFlow : public SCompoundWidget FReply OnNext(); TArray Steps; + TSharedPtr BarBox; FText FinishLabel; FSimpleDelegate OnFinish; int32 Current = 0; diff --git a/Source/MantleRuntime/Private/MantleAvatarCheck.cpp b/Source/MantleRuntime/Private/MantleAvatarCheck.cpp index c5198f53..b46a71c9 100644 --- a/Source/MantleRuntime/Private/MantleAvatarCheck.cpp +++ b/Source/MantleRuntime/Private/MantleAvatarCheck.cpp @@ -86,6 +86,21 @@ bool FMantleAvatarCheck::ParseResponse(const FString& Json, const TArray* PackFacts = nullptr; + if (Entry.Kind == TEXT("animPack") && (*Object)->TryGetObjectField(TEXT("animPack"), PackFacts) && PackFacts) + { + TSharedRef Facts = MakeShared(); + FString FactsError; + if (FMantleAnimPackFacts::FromJson(**PackFacts, *Facts, FactsError)) + { + Entry.AnimPack = Facts; + } + else + { + UE_LOG(LogMantle, Warning, TEXT("MANTLE_AVATAR_CHECK %s: the animation pack facts are unusable: %s"), *Entry.Key, *FactsError); + Entry.bAllowed = false; + } + } if (Entry.Item.IsEmpty() || Entry.Version < 1) { // An allowed answer that names no item or version cannot be drawn: refused. @@ -158,6 +173,18 @@ void FMantleAvatarCheck::RecordCustom(const FString& Name, const FString& Item, Known.Add(MantleAvatarCheckPrivate::ExactKey(Name), MoveTemp(Entry)); } +void FMantleAvatarCheck::RecordAnimPack(const FString& Name, const FString& Item, const int32 Version, TSharedRef Facts) +{ + FMantleAvatarCheckEntry Entry; + Entry.Key = Name; + Entry.bAllowed = true; + Entry.Item = Item; + Entry.Version = Version; + Entry.Kind = TEXT("animPack"); + Entry.AnimPack = Facts; + Known.Add(MantleAvatarCheckPrivate::ExactKey(Name), MoveTemp(Entry)); +} + void FMantleAvatarCheck::ResetForTesting() { Known.Reset(); diff --git a/Source/MantleRuntime/Private/MantleCustomAvatar.cpp b/Source/MantleRuntime/Private/MantleCustomAvatar.cpp index c9fd920b..59583e9a 100644 --- a/Source/MantleRuntime/Private/MantleCustomAvatar.cpp +++ b/Source/MantleRuntime/Private/MantleCustomAvatar.cpp @@ -296,6 +296,39 @@ float FMantleCustomClipFact::MarkerTime(const FName Name) const return -1.0f; } +bool FMantleAnimPackFacts::FromJson(const FJsonObject& Facts, FMantleAnimPackFacts& OutFacts, FString& OutError) +{ + using namespace MantleCustomAvatarPrivate; + FMantleAnimPackFacts Out; + Facts.TryGetStringField(TEXT("document"), Out.Document); + const TArray>* Clips = nullptr; + if (!Facts.TryGetArrayField(TEXT("clips"), Clips) || Clips->IsEmpty()) + { + OutError = TEXT("the pack names no clips"); + return false; + } + for (const TSharedPtr& Value : *Clips) + { + const TSharedPtr* Object = nullptr; + FMantleAnimPackClipFact Fact; + if (!Value.IsValid() || !Value->TryGetObject(Object) || !Object || !ReadClipFact(*Object, Fact) + || !(*Object)->TryGetStringField(TEXT("name"), Fact.Name) || Fact.Name.IsEmpty() + || !(*Object)->TryGetStringField(TEXT("skeleton"), Fact.Skeleton)) + { + OutError = TEXT("a pack clip has no name, asset, skeleton or length"); + return false; + } + Out.Clips.Add(MoveTemp(Fact)); + } + OutFacts = MoveTemp(Out); + return true; +} + +const FMantleAnimPackClipFact* FMantleAnimPackFacts::Find(const FString& Name) const +{ + return Clips.FindByPredicate([&Name](const FMantleAnimPackClipFact& Clip) { return Clip.Name.Equals(Name, ESearchCase::IgnoreCase); }); +} + bool FMantleCustomAvatarFacts::FromJson(const FJsonObject& Facts, FMantleCustomAvatarFacts& OutFacts, FString& OutError) { using namespace MantleCustomAvatarPrivate; diff --git a/Source/MantleRuntime/Private/MantleHandAttach.cpp b/Source/MantleRuntime/Private/MantleHandAttach.cpp new file mode 100644 index 00000000..a23bf071 --- /dev/null +++ b/Source/MantleRuntime/Private/MantleHandAttach.cpp @@ -0,0 +1,58 @@ +// Copyright Joshua Eger. All Rights Reserved. +#include "MantleHandAttach.h" + +#include "Components/SkeletalMeshComponent.h" +#include "Engine/SkeletalMesh.h" + +FTransform MantleHandAttach::DriverPalmOnHand(const bool bRightHand) +{ + // As the sockets sit on SK_UEFN_Mannequin, neither turned nor scaled (Mantle.UsableItem.PalmOnAnyBody holds these to the asset). + return FTransform(bRightHand ? FVector(-7.5, 2.0, 0.0) : FVector(7.5, -2.35, 0.0)); +} + +MantleHandAttach::FPalm MantleHandAttach::FindPalm(const USkeletalMesh& Body, const bool bRightHand) +{ + const FName PalmSocket(bRightHand ? TEXT("palm_r_Socket") : TEXT("palm_l_Socket")); + FPalm Out; + if (Body.FindSocket(PalmSocket)) + { + Out.Where = PalmSocket; + return Out; + } + Out.Where = FName(bRightHand ? TEXT("hand_r") : TEXT("hand_l")); + Out.Offset = DriverPalmOnHand(bRightHand); + return Out; +} + +FQuat MantleHandAttach::RelaxedHandInBody(const bool bRightHand) +{ + // Mantle.UsableItem.UprightDefaultGrip holds these to the idle. + return (bRightHand ? FQuat(0.590967775, 0.285799062, 0.586783463, -0.474089815) : FQuat(0.448976976, 0.626815457, -0.174599909, 0.612402588)).GetNormalized(); +} + +FTransform MantleHandAttach::DefaultGripInMesh(const FBox& MeshBounds, const bool bRightHand) +{ + // The mesh's +X on the body's forward (+Y), its +Z on up. + const FQuat Upright(FVector::UpVector, UE_DOUBLE_HALF_PI); + const FVector Center = MeshBounds.GetCenter(); + // The grip's frame in the mesh: whatever the hand bone's must be for the mesh to come out upright. + return FTransform(Upright.Inverse() * RelaxedHandInBody(bRightHand), FVector(Center.X, Center.Y, MeshBounds.Min.Z)); +} + +void MantleHandAttach::AttachToPalm(const TConstArrayView Items, USkeletalMeshComponent& Body, const bool bRightHand, + const FTransform& GripInMesh) +{ + const USkeletalMesh* BodyMesh = Body.GetSkeletalMeshAsset(); + if (!BodyMesh) + { + return; + } + const FPalm Palm = FindPalm(*BodyMesh, bRightHand); + // The item in the palm's space, then the palm in the attach point's. + const FTransform Relative = GripInMesh.Inverse() * Palm.Offset; + for (USceneComponent* Item : Items) + { + Item->AttachToComponent(&Body, FAttachmentTransformRules::SnapToTargetNotIncludingScale, Palm.Where); + Item->SetRelativeTransform(Relative); + } +} diff --git a/Source/MantleRuntime/Private/MantlePlaceAssets.cpp b/Source/MantleRuntime/Private/MantlePlaceAssets.cpp index eff059eb..77c52c08 100644 --- a/Source/MantleRuntime/Private/MantlePlaceAssets.cpp +++ b/Source/MantleRuntime/Private/MantlePlaceAssets.cpp @@ -1007,6 +1007,19 @@ TSharedPtr FMantlePlaceAssets::FindLiveClip(const FString return nullptr; } +bool FMantlePlaceAssets::IsLiveClip(const FString& Id) +{ + using namespace MantlePlaceAssetsPrivate; + for (int32 Index = GLiveSets.Num() - 1; Index >= 0; --Index) + { + if (GLiveSets[Index]->FindRecord(Id, EAssetKind::AnimClip)) + { + return true; + } + } + return false; +} + UMantleBuiltVehicle* FMantlePlaceAssets::FindLiveVehicle(const FString& Id, FString& OutError) { using namespace MantlePlaceAssetsPrivate; @@ -2655,6 +2668,11 @@ void FMantlePlaceAssets::QueueWeaponPartsOf(const FString& WeaponId, const FMant } } } + // A consumable's or an item's own clips (#333): played on its holder, and their lengths timed by the server (which reads only their headers). + for (const FString& Clip : Named.Clips) + { + QueuePart(Clip, EAssetKind::AnimClip, false); + } QueueMaterialsOf(WeaponId, MaterialIds); QueueSoundsOf(WeaponId, Named.Sounds); // The hotbar icon is a color texture, as a livery is; a dedicated server draws no hotbar and fetches none. diff --git a/Source/MantleRuntime/Private/MantlePlaceStorage.cpp b/Source/MantleRuntime/Private/MantlePlaceStorage.cpp index 2c05045b..6f5e900d 100644 --- a/Source/MantleRuntime/Private/MantlePlaceStorage.cpp +++ b/Source/MantleRuntime/Private/MantlePlaceStorage.cpp @@ -662,11 +662,12 @@ TArray FMantleStorage::CheckAvatarEntries(const TArray>* Packs = nullptr; + if (Root.IsValid() && Root->TryGetArrayField(TEXT("animPacks"), Packs)) + { + for (const TSharedPtr& Value : *Packs) + { + const TSharedPtr* Object = nullptr; + const TSharedPtr* FactsObject = nullptr; + FString Item; + double Version = 0.0; + if (!Value.IsValid() || !Value->TryGetObject(Object) || !(*Object)->TryGetStringField(TEXT("item"), Item) + || !(*Object)->TryGetObjectField(TEXT("facts"), FactsObject) || !FactsObject) + { + continue; + } + (*Object)->TryGetNumberField(TEXT("version"), Version); + const TSharedRef Facts = MakeShared(); + FString FactsError; + if (!FMantleAnimPackFacts::FromJson(**FactsObject, *Facts, FactsError)) + { + UE_LOG(LogMantle, Warning, TEXT("MANTLE_AVATAR_STORAGE place %s: animation pack %s facts unusable: %s"), *PlaceId, *Item, *FactsError); + continue; + } + for (const FMantleAvatarStorageEntry& Stored : PlaceEntries) + { + if (Stored.Kind == TEXT("animPack") && Stored.Item == Item) + { + FMantleAvatarCheck::Get().RecordAnimPack(Stored.Name, Item, static_cast(Version), Facts); + } + } + } + } for (const FString& Item : Missing) { UE_LOG(LogMantle, Warning, TEXT("MANTLE_AVATAR_STORAGE place %s: item %s did not resolve (unknown, not usable by the owner, or a custom avatar)"), diff --git a/Source/MantleRuntime/Private/MantleSlotClipAnimInstance.cpp b/Source/MantleRuntime/Private/MantleSlotClipAnimInstance.cpp index 980cb6f4..99e94cdf 100644 --- a/Source/MantleRuntime/Private/MantleSlotClipAnimInstance.cpp +++ b/Source/MantleRuntime/Private/MantleSlotClipAnimInstance.cpp @@ -280,6 +280,11 @@ float FMantleSlotClipPlay::TimeAt(const double ServerSeconds) const { return 0.0f; } + if (ServerSeconds < StartServerSeconds) + { + // A client whose server clock is still behind the start holds the first frame; wrapping a negative time would flash the loop's end. + return static_cast(FMath::Clamp(StartOffset, 0.0, Length)); + } double Time = StartOffset + (ServerSeconds - StartServerSeconds) * Rate; if (!bLoop) { diff --git a/Source/MantleRuntime/Private/MantleWeaponAsset.cpp b/Source/MantleRuntime/Private/MantleWeaponAsset.cpp index 972c1e97..e3af029e 100644 --- a/Source/MantleRuntime/Private/MantleWeaponAsset.cpp +++ b/Source/MantleRuntime/Private/MantleWeaponAsset.cpp @@ -20,7 +20,7 @@ TArray FMantleWeaponAsset::NamedIds() const TArray Ids; MantleWeaponAssetPrivate::AddOnce(Ids, Mesh); MantleWeaponAssetPrivate::AddOnce(Ids, Icon); - for (const TArray* List : { &Attachments, &Sounds, &Materials }) + for (const TArray* List : { &Attachments, &Sounds, &Materials, &Clips }) { for (const FString& Id : *List) { @@ -99,5 +99,9 @@ bool FMantleWeaponAsset::Read(const TConstArrayView Bytes, FMantleWeaponA { Out.Materials = Desc.Materials.Value; } + for (const FString* Clip : { &Desc.ClipHold, &Desc.ClipUse, &Desc.ClipEquip, &Desc.ClipPutAway }) + { + MantleWeaponAssetPrivate::AddOnce(Out.Clips, *Clip); + } return true; } diff --git a/Source/MantleRuntime/Private/MantleWeaponDocument.cpp b/Source/MantleRuntime/Private/MantleWeaponDocument.cpp index 2fa4722c..f6736eca 100644 --- a/Source/MantleRuntime/Private/MantleWeaponDocument.cpp +++ b/Source/MantleRuntime/Private/MantleWeaponDocument.cpp @@ -17,9 +17,9 @@ namespace MantleWeaponDocumentPrivate const TCHAR* const GWeaponDocHoldNames[] = { TEXT("pistol"), TEXT("revolver"), TEXT("rifle"), TEXT("smg"), TEXT("dmr"), TEXT("pump_shotgun"), TEXT("bolt_sniper"), TEXT("lmg"), TEXT("melee_1h"), TEXT("melee_2h"), TEXT("spear"), TEXT("staff"), TEXT("bow"), TEXT("unarmed"), TEXT("shield"), TEXT("throwable"), - TEXT("consumable") + TEXT("consumable"), TEXT("item") }; - const TCHAR* const GWeaponDocDeliveryNames[] = { TEXT("hitscan"), TEXT("projectile"), TEXT("sweep"), TEXT("beam"), TEXT("use") }; + const TCHAR* const GWeaponDocDeliveryNames[] = { TEXT("hitscan"), TEXT("projectile"), TEXT("sweep"), TEXT("beam"), TEXT("use"), TEXT("signal") }; const TCHAR* const GWeaponDocResourceNames[] = { TEXT("magazine"), TEXT("quiver"), TEXT("charges"), TEXT("none") }; // The firearms' three, then the elements (EMantleWeaponDocEffects). const TCHAR* const GWeaponDocEffectsNames[] = { @@ -46,9 +46,9 @@ namespace MantleWeaponDocumentPrivate const TCHAR* const GWeaponDocV2Fields[] = { TEXT("hold"), TEXT("delivery"), TEXT("charge"), TEXT("block"), TEXT("resource"), TEXT("charges"), TEXT("projectile"), TEXT("sweep"), TEXT("beam"), TEXT("effectsColor"), TEXT("consumable"), TEXT("equipStyle"), TEXT("dodgeStyle"), TEXT("comboSet"), TEXT("quiver"), TEXT("style"), TEXT("bash"), - TEXT("throw"), TEXT("tapLook"), TEXT("holdLook"), TEXT("stance"), TEXT("staffMelee"), TEXT("extra"), TEXT("gravity"), TEXT("suppressor"), TEXT("bipod"), TEXT("paintSlots") + TEXT("throw"), TEXT("tapLook"), TEXT("holdLook"), TEXT("stance"), TEXT("staffMelee"), TEXT("clips"), TEXT("useEffectSeconds"), TEXT("extra"), TEXT("gravity"), TEXT("suppressor"), TEXT("bipod"), TEXT("paintSlots") }; - // consumable.style, and what a consumable (delivery use) refuses: a weapon's numbers, and attachments (its mesh shows alone). + // consumable.style, and what a consumable (delivery use) and a usable item (delivery signal) refuse: a weapon's numbers, and attachments (its mesh shows alone). const TCHAR* const GWeaponDocUseStyleNames[] = { TEXT("eatDrink"), TEXT("use") }; // equipStyle: a shipped hold's named draw/put-away option. const TCHAR* const GWeaponDocEquipStyleNames[] = { @@ -93,7 +93,7 @@ namespace MantleWeaponDocumentPrivate } return false; } - const TCHAR* const GWeaponDocConsumableEffectNames[] = { TEXT("heal"), TEXT("none") }; + const TCHAR* const GWeaponDocConsumableEffectNames[] = { TEXT("heal"), TEXT("none"), TEXT("stamina"), TEXT("hunger"), TEXT("thirst") }; // extra.kind, the schema's enum in order. Every kind is built. const TCHAR* const GWeaponDocExtraNames[] = { TEXT("none"), TEXT("telekinesis"), TEXT("blink"), TEXT("heal"), TEXT("dash"), TEXT("levitate") }; // extra.look, blink's looks in the enum's order (overhead the default). @@ -518,7 +518,18 @@ namespace MantleWeaponDocumentPrivate Table.Add(WeaponDocHold(false, { EAction::Equip, EAction::Holster, EAction::Idle, EAction::Throw }, { EDelivery::Projectile }, ECharge::None, { EResource::None }, EBlock::None, { ESocket::GripR }, { ESocket::Tip })); // consumable: used on its holder, one hand; where the palm holds it is optional (grip). - Table.Add(WeaponDocHold(false, { EAction::Use }, { EDelivery::Use }, ECharge::None, { EResource::None }, EBlock::None, {}, { ESocket::Grip })); + { + FMantleWeaponDocHoldInfo Consumable = WeaponDocHold(false, { EAction::Use }, { EDelivery::Use }, ECharge::None, { EResource::None }, EBlock::None, {}, { ESocket::Grip }); + // Creator clips and the effect moment (x-clips, #333). + Consumable.bHasClips = true; + Table.Add(Consumable); + } + // item (#333): a creator's usable item, the consumable's contract with the signal delivery. + { + FMantleWeaponDocHoldInfo Item = WeaponDocHold(false, { EAction::Use }, { EDelivery::Signal }, ECharge::None, { EResource::None }, EBlock::None, {}, { ESocket::Grip }); + Item.bHasClips = true; + Table.Add(Item); + } check(Table.Num() == static_cast(EMantleWeaponDocHold::Count)); return Table; } @@ -1612,7 +1623,8 @@ namespace MantleWeaponDocumentPrivate void ReadConsumable(const TSharedPtr& Obj, const FString& Path, FMantleWeaponDocConsumable& Out) { - Keys(Obj, Path, { TEXT("style"), TEXT("effect"), TEXT("heal"), TEXT("healSeconds"), TEXT("uses"), TEXT("useSeconds"), TEXT("cooldownSeconds"), TEXT("moveWhileUsing") }, + Keys(Obj, Path, { TEXT("style"), TEXT("effect"), TEXT("heal"), TEXT("healSeconds"), TEXT("stamina"), TEXT("hunger"), TEXT("thirst"), TEXT("uses"), TEXT("useSeconds"), + TEXT("cooldownSeconds"), TEXT("moveWhileUsing") }, { TEXT("style") }); if (const TSharedPtr Style = Field(Obj, TEXT("style"))) { @@ -1621,6 +1633,9 @@ namespace MantleWeaponDocumentPrivate OptChoice(Obj, Path, TEXT("effect"), GWeaponDocConsumableEffectNames, Out.Effect); OptNumber(Obj, Path, TEXT("heal"), 1.0, 1000.0, Out.Heal); OptNumber(Obj, Path, TEXT("healSeconds"), 0.0, 60.0, Out.HealSeconds); + OptNumber(Obj, Path, TEXT("stamina"), 1.0, 10000.0, Out.Stamina); + OptNumber(Obj, Path, TEXT("hunger"), 1.0, 10000.0, Out.Hunger); + OptNumber(Obj, Path, TEXT("thirst"), 1.0, 10000.0, Out.Thirst); OptInteger(Obj, Path, TEXT("uses"), 1, 100, Out.Uses); OptNumber(Obj, Path, TEXT("useSeconds"), 0.5, 10.0, Out.UseSeconds); OptNumber(Obj, Path, TEXT("cooldownSeconds"), 0.0, 600.0, Out.CooldownSeconds); @@ -1751,8 +1766,8 @@ namespace MantleWeaponDocumentPrivate } } } - // A consumable is used, never fired: no weapon numbers, and its mesh alone. - if (D.GetDelivery() == EMantleWeaponDocDelivery::Use) + // A consumable and a usable item are used, never fired: no weapon numbers, and their mesh alone. + if (FMantleWeaponDocument::IsUsedNotFired(D.GetDelivery())) { for (const TCHAR* Key : GWeaponDocUseRefused) { @@ -1835,7 +1850,7 @@ namespace MantleWeaponDocumentPrivate const FString Path; Keys(Root, Path, { TEXT("schemaVersion"), TEXT("name"), TEXT("archetype"), TEXT("hold"), TEXT("delivery"), TEXT("twoHanded"), TEXT("effects"), - TEXT("equipStyle"), TEXT("dodgeStyle"), TEXT("comboSet"), TEXT("quiver"), TEXT("style"), TEXT("suppressor"), TEXT("tapLook"), TEXT("holdLook"), TEXT("stance"), TEXT("staffMelee"), TEXT("color"), TEXT("effectsColor"), TEXT("mesh"), TEXT("materials"), TEXT("paintSlots"), TEXT("icon"), TEXT("sockets"), TEXT("parts"), TEXT("attachments"), TEXT("fire"), + TEXT("equipStyle"), TEXT("dodgeStyle"), TEXT("comboSet"), TEXT("quiver"), TEXT("style"), TEXT("suppressor"), TEXT("tapLook"), TEXT("holdLook"), TEXT("stance"), TEXT("staffMelee"), TEXT("clips"), TEXT("useEffectSeconds"), TEXT("color"), TEXT("effectsColor"), TEXT("mesh"), TEXT("materials"), TEXT("paintSlots"), TEXT("icon"), TEXT("sockets"), TEXT("parts"), TEXT("attachments"), TEXT("fire"), TEXT("charge"), TEXT("magazine"), TEXT("reload"), TEXT("resource"), TEXT("charges"), TEXT("projectile"), TEXT("sweep"), TEXT("beam"), TEXT("consumable"), TEXT("block"), TEXT("bash"), TEXT("bipod"), TEXT("throw"), TEXT("extra"), TEXT("gravity"), TEXT("sounds"), TEXT("firstPerson"), TEXT("spread"), TEXT("sway"), TEXT("recoil") }, { TEXT("schemaVersion"), TEXT("name") }); @@ -1897,8 +1912,8 @@ namespace MantleWeaponDocumentPrivate Out.Delivery.Set(Delivery); } } - // Fire on every delivery but use (a version-1 document's hitscan included); use refuses it (CheckKeys). - if (!(Out.Delivery.bSet && Out.Delivery.Value == EMantleWeaponDocDelivery::Use)) + // Fire on every delivery but use and signal (a version-1 document's hitscan included); those refuse it (CheckKeys). + if (!(Out.Delivery.bSet && FMantleWeaponDocument::IsUsedNotFired(Out.Delivery.Value))) { Required(Root, Path, { TEXT("fire") }); } @@ -1926,6 +1941,25 @@ namespace MantleWeaponDocumentPrivate { Text(Icon, TEXT("icon"), EWeaponDocText::LocalName, Out.Icon); } + if (const TSharedPtr Clips = Field(Root, TEXT("clips"))) + { + TSharedPtr ClipsObj; + if (Object(Clips, TEXT("clips"), ClipsObj)) + { + Out.bClips = true; + Keys(ClipsObj, TEXT("clips"), { TEXT("hold"), TEXT("use"), TEXT("equip"), TEXT("putAway") }, {}); + FString* const Slots[] = { &Out.ClipHold, &Out.ClipUse, &Out.ClipEquip, &Out.ClipPutAway }; + const TCHAR* const SlotKeys[] = { TEXT("hold"), TEXT("use"), TEXT("equip"), TEXT("putAway") }; + for (int32 Slot = 0; Slot < 4; ++Slot) + { + if (const TSharedPtr Value = Field(ClipsObj, SlotKeys[Slot])) + { + Text(Value, At(TEXT("clips"), SlotKeys[Slot]), EWeaponDocText::LocalName, *Slots[Slot]); + } + } + } + } + OptNumber(Root, Path, TEXT("useEffectSeconds"), 0.0, 60.0, Out.UseEffectSeconds); if (const TSharedPtr Sockets = Field(Root, TEXT("sockets"))) { TSharedPtr SocketsObj; @@ -2534,6 +2568,9 @@ namespace MantleWeaponDocumentPrivate } Number(Node, TEXT("heal"), In.Heal); Number(Node, TEXT("healSeconds"), In.HealSeconds); + Number(Node, TEXT("stamina"), In.Stamina); + Number(Node, TEXT("hunger"), In.Hunger); + Number(Node, TEXT("thirst"), In.Thirst); Integer(Node, TEXT("uses"), In.Uses); Number(Node, TEXT("useSeconds"), In.UseSeconds); Number(Node, TEXT("cooldownSeconds"), In.CooldownSeconds); @@ -2879,6 +2916,24 @@ namespace MantleWeaponDocumentPrivate { WeaponDocPut(Node, TEXT("icon"), WeaponDocStringNode(D.Icon)); } + if (D.bClips) + { + FWeaponDocNodePtr Clips = WeaponDocObjectNode(); + const FString* const Slots[] = { &D.ClipHold, &D.ClipUse, &D.ClipEquip, &D.ClipPutAway }; + const TCHAR* const SlotKeys[] = { TEXT("hold"), TEXT("use"), TEXT("equip"), TEXT("putAway") }; + for (int32 Slot = 0; Slot < 4; ++Slot) + { + if (!Slots[Slot]->IsEmpty()) + { + WeaponDocPut(Clips, SlotKeys[Slot], WeaponDocStringNode(*Slots[Slot])); + } + } + WeaponDocPut(Node, TEXT("clips"), Clips); + } + if (D.UseEffectSeconds.bSet) + { + WeaponDocPut(Node, TEXT("useEffectSeconds"), WeaponDocNumberNode(D.UseEffectSeconds.Value)); + } FWeaponDocNodePtr Sockets = WeaponDocObjectNode(); for (int32 Index = 0; Index < static_cast(EMantleWeaponDocSocket::Count); ++Index) { @@ -2899,8 +2954,8 @@ namespace MantleWeaponDocumentPrivate } WeaponDocPut(Node, TEXT("attachments"), Attachments); } - // A consumable has no fire. - if (D.GetDelivery() != EMantleWeaponDocDelivery::Use) + // A consumable and a usable item have no fire. + if (!FMantleWeaponDocument::IsUsedNotFired(D.GetDelivery())) { WeaponDocPut(Node, TEXT("fire"), Fire(D.Fire)); } @@ -3820,6 +3875,16 @@ void FMantleWeaponDocument::CheckRules(const FMantleWeaponDesc& D, TArray(Amount.Owner)); + R.Add(FString::Printf(TEXT("consumable/%s"), Amount.Field), TEXT("mantle"), FString::Printf(TEXT("is the %s effect's, but the effect is %s: drop it, or write effect %s"), + Owner, WeaponDocNameAt(GWeaponDocConsumableEffectNames, static_cast(C.Effect.Value)), Owner)); + } } } @@ -4166,6 +4239,11 @@ const TCHAR* FMantleWeaponDocument::HoldName(const EMantleWeaponDocHold Hold) return MantleWeaponDocumentPrivate::WeaponDocNameAt(MantleWeaponDocumentPrivate::GWeaponDocHoldNames, static_cast(Hold)); } +bool FMantleWeaponDocument::IsUsedNotFired(const EMantleWeaponDocDelivery Delivery) +{ + return Delivery == EMantleWeaponDocDelivery::Use || Delivery == EMantleWeaponDocDelivery::Signal; +} + const TCHAR* FMantleWeaponDocument::DeliveryName(const EMantleWeaponDocDelivery Delivery) { return MantleWeaponDocumentPrivate::WeaponDocNameAt(MantleWeaponDocumentPrivate::GWeaponDocDeliveryNames, static_cast(Delivery)); diff --git a/Source/MantleRuntime/Private/Tests/MantleAvatarStorageTest.cpp b/Source/MantleRuntime/Private/Tests/MantleAvatarStorageTest.cpp index b98b8c86..535a66d8 100644 --- a/Source/MantleRuntime/Private/Tests/MantleAvatarStorageTest.cpp +++ b/Source/MantleRuntime/Private/Tests/MantleAvatarStorageTest.cpp @@ -113,6 +113,11 @@ bool FMantleAvatarStorageParserTest::RunTest(const FString& Parameters) } TestEqual(TEXT("Storage stays a namespace of its own"), Result.Place.Storage.Num(), 0); + // #333: an animation pack is an avatarStorage entry kind too. + const FMantleParseResult Pack = FMantlePlaceParser::ParseFromString(PlaceJson(TEXT("[") + Entry(TEXT("Gestures"), TEXT("animPack"), ItemBody, 1) + TEXT("]"))); + TestTrue(TEXT("an animation pack entry parses and is kept by kind"), + Pack.bSuccess && Pack.Place.AvatarStorage.Num() == 1 && Pack.Place.AvatarStorage[0].Kind == TEXT("animPack")); + // A place with none, and an empty array, are valid. TestTrue(TEXT("an empty array parses"), FMantlePlaceParser::ParseFromString(PlaceJson(TEXT("[]"))).bSuccess); diff --git a/Source/MantleRuntime/Private/Tests/MantleCustomAvatarTest.cpp b/Source/MantleRuntime/Private/Tests/MantleCustomAvatarTest.cpp index 851d8418..432da3cb 100644 --- a/Source/MantleRuntime/Private/Tests/MantleCustomAvatarTest.cpp +++ b/Source/MantleRuntime/Private/Tests/MantleCustomAvatarTest.cpp @@ -236,6 +236,15 @@ bool FMantleCustomAvatarClipTest::RunTest(const FString& Parameters) TestFalse(TEXT("not ended yet"), Once.HasEnded(10.5)); TestTrue(TEXT("ended after its length"), Once.HasEnded(11.5)); TestFalse(TEXT("a loop never ends"), Loop.HasEnded(100.0)); + // A clock behind the start (negative elapsed time) holds the first frame, never the loop's end. + Loop.StartOffset = 0.3; + Once.StartOffset = 0.3; + TestTrue(TEXT("a looping clip before its start holds StartOffset"), FMath::IsNearlyEqual(Loop.TimeAt(9.9), 0.3f, 1.0e-4f)); + TestTrue(TEXT("a one-shot before its start holds StartOffset"), FMath::IsNearlyEqual(Once.TimeAt(9.9), 0.3f, 1.0e-4f)); + Loop.StartOffset = 0.0; + Once.StartOffset = 0.0; + TestTrue(TEXT("a looping clip before its start holds the first frame"), FMath::IsNearlyEqual(Loop.TimeAt(9.5), 0.0f, 1.0e-4f)); + TestTrue(TEXT("a one-shot before its start holds the first frame"), FMath::IsNearlyEqual(Once.TimeAt(9.5), 0.0f, 1.0e-4f)); return true; } diff --git a/Source/MantleRuntime/Private/Tests/MantlePlaceStorageTest.cpp b/Source/MantleRuntime/Private/Tests/MantlePlaceStorageTest.cpp index 538b9329..70a55516 100644 --- a/Source/MantleRuntime/Private/Tests/MantlePlaceStorageTest.cpp +++ b/Source/MantleRuntime/Private/Tests/MantlePlaceStorageTest.cpp @@ -198,7 +198,32 @@ bool FMantlePlaceStorageParserRefusesTest::RunTest(const FString& Parameters) TooMany += (i > 0 ? TEXT(",") : TEXT("")) + StorageEntry(*FString::Printf(TEXT("Item%d"), i), ItemTruck, 1); } TooMany += TEXT("]"); - ExpectRefused(TEXT("more than 32 entries"), PlaceJson(FString(), TooMany), TEXT("/storage")); + ExpectRefused(TEXT("one entry past the most a place stores"), PlaceJson(FString(), TooMany), TEXT("/storage")); + + // #475: 40 script packages beside 32 vehicles, weapons and wheels parse (the file does not say which entry is which), + // and the most entries a place stores still fit one resolve request, which the API reads at most 64 KiB of. + FString Many = TEXT("["); + TArray FullRefs; + for (int32 i = 0; i < FMantlePlaceLimits::MaxStorageEntries; ++i) + { + const FString Item = FString::Printf(TEXT("itm_u%032d"), i); + if (i < FMantlePlaceLimits::MaxStoredItems + 40) + { + Many += (i > 0 ? TEXT(",") : TEXT("")) + StorageEntry(*FString::Printf(TEXT("Item%d"), i), *Item, 1); + } + FMantleStorageRef Ref; + Ref.Item = Item; + Ref.Version = MAX_int32; + FullRefs.Add(MoveTemp(Ref)); + } + Many += TEXT("]"); + const FMantleParseResult ManyParsed = FMantlePlaceParser::ParseFromString(PlaceJson(FString(), Many)); + if (TestTrue(TEXT("72 entries parse"), ManyParsed.bSuccess)) + { + TestEqual(TEXT("all of them"), ManyParsed.Place.Storage.Num(), FMantlePlaceLimits::MaxStoredItems + 40); + } + TestTrue(TEXT("a full storage's resolve request fits 64 KiB"), + FTCHARToUTF8(*FMantleApiClient::MakeResolveStorageBody(FullRefs)).Length() <= 64 * 1024); // VehicleSpawn's storageItem and vehicle. ExpectRefused(TEXT("a storageItem no entry names"), diff --git a/Source/MantleRuntime/Private/Tests/MantleWeaponAssetTest.cpp b/Source/MantleRuntime/Private/Tests/MantleWeaponAssetTest.cpp index afe50e68..2988b81b 100644 --- a/Source/MantleRuntime/Private/Tests/MantleWeaponAssetTest.cpp +++ b/Source/MantleRuntime/Private/Tests/MantleWeaponAssetTest.cpp @@ -66,6 +66,7 @@ bool FMantleWeaponAssetReadTest::RunTest(const FString& Parameters) TestTrue(TEXT("a sound used for both shots is listed once"), Asset.Sounds == TArray({ FString(SoundId) })); TestTrue(TEXT("the slot materials keep their order"), Asset.Materials == TArray({ FString(MaterialA), FString(MaterialB) })); TestEqual(TEXT("every named id once"), Asset.NamedIds().Num(), 5); + TestEqual(TEXT("a weapon names no clips"), Asset.Clips.Num(), 0); // A byte-order mark in front is skipped. TArray WithBom = { 0xEF, 0xBB, 0xBF }; diff --git a/Source/MantleRuntime/Public/MantleAvatarCheck.h b/Source/MantleRuntime/Public/MantleAvatarCheck.h index cd99d333..156afc32 100644 --- a/Source/MantleRuntime/Public/MantleAvatarCheck.h +++ b/Source/MantleRuntime/Public/MantleAvatarCheck.h @@ -16,7 +16,7 @@ struct MANTLERUNTIME_API FMantleAvatarCheckEntry FString Item; /** The stored version, 0 when refused. */ int32 Version = 0; - /** "avatarItem" for every entry today (custom avatars come with #326). */ + /** "avatarItem", "customAvatar" (#326) or "animPack" (#333). */ FString Kind; /** The item's slot ("avatar", "top", "emote", ...), as the backend names it. */ FString Slot; @@ -30,6 +30,9 @@ struct MANTLERUNTIME_API FMantleAvatarCheckEntry /** A Custom avatar's facts (#326), when Kind is "customAvatar": the capsule's bounds, clip lengths and marker times. */ TSharedPtr Custom; + + /** An animation pack's facts (#333), when Kind is "animPack": each clip's name, asset, skeleton, length and markers. */ + TSharedPtr AnimPack; }; /** @@ -54,6 +57,9 @@ class MANTLERUNTIME_API FMantleAvatarCheck /** A local run's (or a preview's) Custom avatar: Name answers as an allowed customAvatar with Facts, as the check route would (#326). */ void RecordCustom(const FString& Name, const FString& Item, int32 Version, TSharedRef Facts); + /** A local run's animation pack (#333): Name answers as an allowed animPack with Facts, as the check route would. */ + void RecordAnimPack(const FString& Name, const FString& Item, int32 Version, TSharedRef Facts); + /** True when every one of Keys has an answer (allowed or refused). */ bool AreKnown(const TArray& Keys) const; diff --git a/Source/MantleRuntime/Public/MantleCustomAvatar.h b/Source/MantleRuntime/Public/MantleCustomAvatar.h index 859482b9..e9d0b7a5 100644 --- a/Source/MantleRuntime/Public/MantleCustomAvatar.h +++ b/Source/MantleRuntime/Public/MantleCustomAvatar.h @@ -97,6 +97,29 @@ struct MANTLERUNTIME_API FMantleCustomClipFact float MarkerTime(FName Name) const; }; +/** One clip of an animation pack (#333): the name scripts play it by ("/"), its asset, the skeleton it was made on, length and markers. */ +struct MANTLERUNTIME_API FMantleAnimPackClipFact : public FMantleCustomClipFact +{ + FString Name; + FString Skeleton; +}; + +/** + * What the backend's check route and owner resolve answer for an animation pack version (#333 G10, cook.AnimPackFacts): its clips in the + * document's order. A dedicated server times a pack clip from these and loads none. + */ +struct MANTLERUNTIME_API FMantleAnimPackFacts +{ + FString Document; + TArray Clips; + + /** {document, clips: [{name, asset, skeleton, durationSeconds, markers?}]}; false with a reason when a clip lacks any of them. */ + static bool FromJson(const FJsonObject& Facts, FMantleAnimPackFacts& OutFacts, FString& OutError); + + /** The clip named Name (names are unique ignoring case), or null. */ + const FMantleAnimPackClipFact* Find(const FString& Name) const; +}; + /** * What the backend's check route and owner resolve answer for a Custom avatar version (cook.CustomAvatarFacts): enough for a * dedicated server to size the capsule and time ClipEnded and impact without loading a clip. diff --git a/Source/MantleRuntime/Public/MantleHandAttach.h b/Source/MantleRuntime/Public/MantleHandAttach.h new file mode 100644 index 00000000..484a9983 --- /dev/null +++ b/Source/MantleRuntime/Public/MantleHandAttach.h @@ -0,0 +1,45 @@ +// Copyright Joshua Eger. All Rights Reserved. +#pragma once + +#include "CoreMinimal.h" + +class USceneComponent; +class USkeletalMesh; +class USkeletalMeshComponent; + +/** Where an item held in the palm (a usable item, a consumable) sits on a body, #333. Shared: the game and the plugin's Hold preview place it alike. */ +namespace MantleHandAttach +{ + struct FPalm + { + /** The socket or bone of the body to attach to. */ + FName Where; + /** The palm, relative to Where. */ + FTransform Offset = FTransform::Identity; + }; + + /** The UEFN driver skeleton's palm socket (palm_l_Socket, palm_r_Socket), relative to its hand bone. */ + MANTLERUNTIME_API FTransform DriverPalmOnHand(bool bRightHand); + + /** + * The palm of one of Body's hands: its palm socket where it has one (the UEFN driver skeleton's), else its hand bone (hand_l, hand_r) with + * DriverPalmOnHand on it. Avatar bodies have no palm socket. + */ + MANTLERUNTIME_API FPalm FindPalm(const USkeletalMesh& Body, bool bRightHand); + + /** + * A hand bone's rotation in the body's mesh space (forward +Y, up +Z) with the arm in the relaxed carry: the first frame of + * M_Relaxed_Stand_Idle_Loop. + */ + MANTLERUNTIME_API FQuat RelaxedHandInBody(bool bRightHand); + + /** + * The grip of an item whose creator placed none, as a GripInMesh for AttachToPalm: the bottom center of MeshBounds (the item mesh's, in its + * own space) sits in the palm, and with the arm in the relaxed carry the mesh stands upright, its +Z up and its +X forward. + */ + MANTLERUNTIME_API FTransform DefaultGripInMesh(const FBox& MeshBounds, bool bRightHand); + + /** Attaches each of Items to Body with the grip point (GripInMesh, in the item mesh's space) in the palm. */ + MANTLERUNTIME_API void AttachToPalm(TConstArrayView Items, USkeletalMeshComponent& Body, bool bRightHand, + const FTransform& GripInMesh); +} diff --git a/Source/MantleRuntime/Public/MantlePlaceAssets.h b/Source/MantleRuntime/Public/MantlePlaceAssets.h index 41d6511a..e85e3563 100644 --- a/Source/MantleRuntime/Public/MantlePlaceAssets.h +++ b/Source/MantleRuntime/Public/MantlePlaceAssets.h @@ -574,6 +574,10 @@ class MANTLERUNTIME_API FMantlePlaceAssets : public FGCObject, public TSharedFro */ static TSharedPtr FindLiveClip(const FString& Id, FString& OutError, bool* bOutStillLoading = nullptr); + /** #333: whether a live set holds the clip Id (loaded or still on its way): a place clip, or one a stored or Test Locally weapon + * brought (a consumable's or an item's own clips, which the place's asset list does not name). */ + static bool IsLiveClip(const FString& Id); + /** * The decoded sound for an uploaded id in the newest live set that has it; null with the * reason otherwise. bOutStillLoading, when given, says the null is only because it has not diff --git a/Source/MantleRuntime/Public/MantlePlaceLimits.h b/Source/MantleRuntime/Public/MantlePlaceLimits.h index 613d6159..7b1c9655 100644 --- a/Source/MantleRuntime/Public/MantlePlaceLimits.h +++ b/Source/MantleRuntime/Public/MantlePlaceLimits.h @@ -620,8 +620,19 @@ struct MANTLERUNTIME_API FMantlePlaceLimits /** True when Id is "uid_" followed by 1 to 40 of a-z, 0-9 and '_'. */ static bool IsUIDocumentId(const FString& Id); - /** storage[]: the library items a place holds, 0 to this many. Mirrors the schema's maxItems. */ - static constexpr int32 MaxStorageEntries = 32; + /** + * storage[]: the library items a place holds, 0 to this many. Mirrors the schema's maxItems and the backend. It is + * what one storage resolve request holds: the API reads at most 64 KiB of its body and an entry takes at most 70 + * bytes of it. + */ + static constexpr int32 MaxStorageEntries = 936; + + /** + * How many storage[] entries may be anything but a script package: vehicles, weapons and wheels count together + * (script packages have no limit of their own). A place file does not say an entry's kind, so the parser cannot + * count them; the editor does where it knows the kind, and the backend's publish does. Mirrors the backend. + */ + static constexpr int32 MaxStoredItems = 32; /** avatarStorage[]: the avatar items and custom avatars a place stores, 0 to this many (#296). Mirrors the schema's maxItems. */ static constexpr int32 MaxAvatarStorageEntries = 1000; diff --git a/Source/MantleRuntime/Public/MantlePlaceStorage.h b/Source/MantleRuntime/Public/MantlePlaceStorage.h index 1534a3ad..068467e4 100644 --- a/Source/MantleRuntime/Public/MantlePlaceStorage.h +++ b/Source/MantleRuntime/Public/MantlePlaceStorage.h @@ -107,7 +107,7 @@ class MANTLERUNTIME_API FMantleStorage /** * The schema's rules for an avatarStorage array (#296), shared by the parser and the editor validator: at most * FMantlePlaceLimits::MaxAvatarStorageEntries entries, names matching StorageNamePattern and unique (case-sensitively, - * and in a namespace of their own, apart from storage's), kind "avatarItem" or "customAvatar", items itm_u plus 32 + * and in a namespace of their own, apart from storage's), kind "avatarItem", "customAvatar" or "animPack", items itm_u plus 32 * lowercase hex digits and each stored once, versions of at least 1. Paths are "/avatarStorage" or * "/avatarStorage//". */ diff --git a/Source/MantleRuntime/Public/MantlePlaceTypes.h b/Source/MantleRuntime/Public/MantlePlaceTypes.h index bc98f26d..11e390a4 100644 --- a/Source/MantleRuntime/Public/MantlePlaceTypes.h +++ b/Source/MantleRuntime/Public/MantlePlaceTypes.h @@ -849,7 +849,7 @@ struct FMantleUIDocument }; /** - * One avatar item or custom avatar a place stores (#296), the avatarStorage array's entry: a creator-chosen + * One avatar item, custom avatar or animation pack a place stores (#296), the avatarStorage array's entry: a creator-chosen * name for an immutable item version. Names are a namespace of their own, apart from Storage's. */ struct FMantleAvatarStorageEntry @@ -857,7 +857,7 @@ struct FMantleAvatarStorageEntry /** An ASCII letter then up to 63 letters, digits or '_'; unique in avatarStorage (case-sensitive). */ FString Name; - /** "avatarItem" (a body, hair, clothing or emote) or "customAvatar" (#326's library kind). */ + /** "avatarItem" (a body, hair, clothing or emote), "customAvatar" (#326's library kind) or "animPack" (#333's named clips). */ FString Kind; /** itm_u and 32 lowercase hex digits. */ diff --git a/Source/MantleRuntime/Public/MantlePreviewLaunch.h b/Source/MantleRuntime/Public/MantlePreviewLaunch.h index 5b794364..3e47e40b 100644 --- a/Source/MantleRuntime/Public/MantlePreviewLaunch.h +++ b/Source/MantleRuntime/Public/MantlePreviewLaunch.h @@ -141,17 +141,19 @@ struct FMantlePreviewManifest }; /** - * The bounds of a local preview bundle. Place and script sizes are the publishing limits (the + * The bounds of a local preview bundle. Place and per-script sizes are the publishing limits (the * backend's places.MaxPlaceFileBytes and scripts.MaxScriptSourceBytes), so a bundle that previews is a - * bundle that publishes; the manifest and script count only keep the bundle finite. + * bundle that publishes; the manifest, the script count and the scripts' total only keep the bundle + * finite, far above what a place with many script packages needs. */ namespace MantlePreviewLimits { - constexpr int64 MaxManifestBytes = 1024 * 1024; + constexpr int64 MaxManifestBytes = 16 * 1024 * 1024; constexpr int64 MaxPlaceFileBytes = 8 * 1024 * 1024; constexpr int64 MaxScriptBytes = 1024 * 1024; - constexpr int64 MaxTotalScriptBytes = 8 * 1024 * 1024; - constexpr int32 MaxScripts = 256; + constexpr int64 MaxTotalScriptBytes = 256 * 1024 * 1024; + /** The place's own scripts and every script package's files (up to 64 a package) are all listed. */ + constexpr int32 MaxScripts = 65536; /** Schema 2: the asset count, one asset file and all asset files together. */ constexpr int32 MaxAssets = 4096; diff --git a/Source/MantleRuntime/Public/MantleWeaponAsset.h b/Source/MantleRuntime/Public/MantleWeaponAsset.h index faeb6017..fdc33c56 100644 --- a/Source/MantleRuntime/Public/MantleWeaponAsset.h +++ b/Source/MantleRuntime/Public/MantleWeaponAsset.h @@ -32,6 +32,9 @@ struct MANTLERUNTIME_API FMantleWeaponAsset /** Shot sound ids, each once. */ TArray Sounds; + /** The animclip ids of the document's clips block (a consumable's or a usable item's own animations, #333), each once. */ + TArray Clips; + /** The hotbar icon's texture id, "" when the document names none. */ FString Icon; @@ -45,7 +48,7 @@ struct MANTLERUNTIME_API FMantleWeaponAsset */ TMap> AttachmentMaterials; - /** Every distinct asset id the document names (mesh, attachments, sounds, materials, attachments' materials, icon). */ + /** Every distinct asset id the document names (mesh, attachments, sounds, materials, attachments' materials, icon, clips). */ TArray NamedIds() const; /** Reads MWP1 bytes with the strict document reader. False with every problem in OutError. */ diff --git a/Source/MantleRuntime/Public/MantleWeaponDocument.h b/Source/MantleRuntime/Public/MantleWeaponDocument.h index e7d08cf6..073aa1ca 100644 --- a/Source/MantleRuntime/Public/MantleWeaponDocument.h +++ b/Source/MantleRuntime/Public/MantleWeaponDocument.h @@ -11,15 +11,17 @@ // meshes and sounds are local names inside the weapon's own set, which the reader of the document resolves. No UObjects: // any thread. // -// Schema v2 names the hold (sixteen: the eight firearm archetypes, then melee_1h, melee_2h, spear, staff, bow, -// unarmed, shield, throwable) and the delivery (hitscan, projectile, sweep, beam), with charge, block, a resource and each -// delivery's numbers. A v1 document (archetype) reads as v2 with hold = archetype, delivery = hitscan and resource = +// Schema v2 names the hold (eighteen: the eight firearm archetypes, then melee_1h, melee_2h, spear, staff, bow, +// unarmed, shield, throwable, consumable, item) and the delivery (hitscan, projectile, sweep, beam, use, signal), with +// charge, block, a resource and each delivery's numbers. A v1 document (archetype) reads as v2 with hold = archetype, delivery = hitscan and resource = // magazine; Write always writes v2. Decision 4 (2026-10-11): a shield is its own item (hold shield), which the client // pairs at run time with a main-hand weapon by the schema's x-pairings (MantleWeaponArchetypeLibrary::FindPairing); a // document has no off-hand mesh. // // The consumable hold (a potion, a medkit, food) with its one delivery, use, and the consumable block: an item used -// on its holder, no fire. It has no clips of its own: its use plays the potion clip of whatever the holder holds. +// on its holder, no fire. It has no built-in clips of its own: its use plays the potion clip of whatever the holder holds. +// The item hold (#333) with its one delivery, signal, is a creator's usable item: no fire and no effect, each use told +// to the place's script. Both may carry creator clips (x-clips). /** * An optional value of the document: Value holds the schema's default until the document sets it, and bSet says whether @@ -80,6 +82,8 @@ enum class EMantleWeaponDocHold : uint8 Throwable, /** An item used on its holder (delivery use, the consumable block). */ Consumable, + /** A creator's usable item (delivery signal, #333): no built-in attack or effect; each use reaches the place's script. */ + Item, Count }; @@ -92,6 +96,8 @@ enum class EMantleWeaponDocDelivery : uint8 Beam, /** No attack; the item is used on its holder (a consumable). */ Use, + /** No built-in attack or effect; each use is reported to the place's script (a usable item, #333). */ + Signal, Count }; @@ -321,6 +327,8 @@ struct FMantleWeaponDocHoldInfo bool bHasShieldThrow = false; /** The hold may fight with the Melee key in its own combo (x-staffMelee: the staff). */ bool bHasStaffMelee = false; + /** The hold takes creator clips (x-clips: the consumable and the usable item). The effect moment is the consumable's alone. */ + bool bHasClips = false; /** The hold carries one extra on Q (x-extra: the staff). */ bool bHasExtra = false; /** The hold may be a gravity gun (x-gravity: the firearm holds). */ @@ -710,6 +718,12 @@ enum class EMantleWeaponDocConsumableEffect : uint8 Heal, /** Nothing built in: the place's server script does it all (Backpack.ItemUsed fires either way). */ None, + /** #333 G4: gives the holder stamina (Stamina), while the place's script has it on. */ + Stamina, + /** #333 G4: fills the holder's hunger (Hunger), while the place's script has it on. */ + Hunger, + /** #333 G4: fills the holder's thirst (Thirst), while the place's script has it on. */ + Thirst, Count }; @@ -723,6 +737,10 @@ struct FMantleWeaponDocConsumable TMantleWeaponDocValue Heal{ 50.0 }; /** With effect heal. 0: the whole heal at the effect moment; above 0: spread evenly over this many seconds from it. */ TMantleWeaponDocValue HealSeconds{ 0.0 }; + /** #333 G4, each with its own effect only: stamina given (up to the maximum), hunger and thirst filled (up to theirs). 1 to 10000. */ + TMantleWeaponDocValue Stamina{ 50.0 }; + TMantleWeaponDocValue Hunger{ 50.0 }; + TMantleWeaponDocValue Thirst{ 50.0 }; TMantleWeaponDocValue Uses{ 1 }; /** Seconds one use takes; unset: the clip's own length (the value here is only the clips' length, 2.5). */ TMantleWeaponDocValue UseSeconds{ 2.5 }; @@ -952,6 +970,22 @@ struct MANTLERUNTIME_API FMantleWeaponDesc * library thumbnail. Empty: the hotbar shows no picture. */ FString Icon; + /** + * Optional, consumables and usable items only (x-clips, #333): animclip assets (ast_u... ids) replacing the built-in animations. Each slot is optional and + * empty keeps the built-in: Hold loops on the upper body while the item is held, Use plays on use, Equip when it is taken out, PutAway + * when it is put away. A weapon keeps its own animations and refuses the block. + */ + FString ClipHold; + FString ClipUse; + FString ClipEquip; + FString ClipPutAway; + /** True when the document wrote a clips block, even an empty one. */ + bool bClips = false; + /** + * Optional, consumables only (#333): seconds after the Use clip starts when the effect lands. The plugin writes 0.6 x the Use clip's + * length; the backend bounds it (at least 0, before the clip's end). + */ + TMantleWeaponDocValue UseEffectSeconds; /** The hold's sockets are required, its optional sockets allowed (x-holds); the sockets block is written when any is set. */ TMantleWeaponDocValue Sockets[static_cast(EMantleWeaponDocSocket::Count)]; TMantleWeaponDocValue Parts; @@ -1096,6 +1130,9 @@ class MANTLERUNTIME_API FMantleWeaponDocument /** A firearm hold: one of the eight archetypes. */ static bool IsFirearmHold(EMantleWeaponDocHold Hold); + /** A delivery that attacks with nothing, so the document has no fire and no weapon numbers: use (a consumable) and signal (a usable item). */ + static bool IsUsedNotFired(EMantleWeaponDocDelivery Delivery); + /** Archetype's hold. */ static EMantleWeaponDocHold HoldOfArchetype(EMantleWeaponDocArchetype Archetype); diff --git a/Source/MantleRuntime/Public/MantleWeaponSource.h b/Source/MantleRuntime/Public/MantleWeaponSource.h index e4fdc44d..ec6a7b01 100644 --- a/Source/MantleRuntime/Public/MantleWeaponSource.h +++ b/Source/MantleRuntime/Public/MantleWeaponSource.h @@ -29,12 +29,14 @@ enum class EMantleWeaponHold : uint8 Throwable, /** A potion, a medkit, food: used on its holder (delivery Use, the Consumable numbers). */ Consumable, + /** A usable item (#333): held and used, with no effect of its own (delivery Signal; the place's script hears Backpack.ToolUsed). */ + Item, Count UMETA(Hidden) }; /** Default uses the hold's first allowed delivery/resource, so old firearm sources remain hitscan/magazine. */ UENUM() -enum class EMantleWeaponSourceDelivery : uint8 { Default, Hitscan, Projectile, Sweep, Beam, Use }; +enum class EMantleWeaponSourceDelivery : uint8 { Default, Hitscan, Projectile, Sweep, Beam, Use, Signal }; UENUM() enum class EMantleWeaponSourceResource : uint8 { Default, Magazine, Quiver, Charges, None }; UENUM() @@ -53,9 +55,10 @@ enum class EMantleWeaponSourceAction : uint8 /** Which of each hold's two potion clips a consumable plays (the document's consumable.style). */ UENUM() enum class EMantleWeaponSourceUseStyle : uint8 { EatDrink, Use }; -/** What a consumable does by itself (the document's consumable.effect): heal, or nothing (the place's script does it). */ +/** What a consumable does by itself (the document's consumable.effect): heal, nothing (the place's script does it), or (#333 G4, appended so saved + * sources keep their numbers) stamina, hunger or thirst. */ UENUM() -enum class EMantleWeaponSourceConsumableEffect : uint8 { Heal, None }; +enum class EMantleWeaponSourceConsumableEffect : uint8 { Heal, None, Stamina, Hunger, Thirst }; USTRUCT() struct MANTLERUNTIME_API FMantleWeaponSourceCharge @@ -131,6 +134,8 @@ struct MANTLERUNTIME_API FMantleWeaponSourceConsumable /** With effect Heal: health given (1..1000), and 0 for all at once or the seconds it is spread over. */ UPROPERTY(EditAnywhere, Category = "Mantle") float Heal = 50.f; UPROPERTY(EditAnywhere, Category = "Mantle") float HealSeconds = 0.f; + /** With effect Stamina, Hunger or Thirst: how much one use gives (1..10000). */ + UPROPERTY(EditAnywhere, Category = "Mantle") float Amount = 50.f; UPROPERTY(EditAnywhere, Category = "Mantle") int32 Uses = 1; /** False: one use takes the clip's own length (2.5 s) and useSeconds is not written. */ UPROPERTY(EditAnywhere, Category = "Mantle") bool bOverrideUseSeconds = false; @@ -388,4 +393,9 @@ class MANTLERUNTIME_API UMantleWeaponSource : public UDataAsset UPROPERTY(EditAnywhere, Category = "Mantle") TSoftObjectPtr FireSuppressedSound; UPROPERTY(EditAnywhere, Category = "Mantle") bool bSuppressed = false; UPROPERTY(EditAnywhere, Category = "Mantle") FString FireSoundTrigger; + /** (mantle #333) Creator clips, Usable item and consumable holds only: animations copied into the item's assets, replacing the built-in ones. Hold loops on the upper body while the item is held, Use plays on use, Equip when it is taken out, PutAway when it is put away. Unset keeps the built-in. */ + UPROPERTY(EditAnywhere, Category = "Mantle") TSoftObjectPtr ClipHold; + UPROPERTY(EditAnywhere, Category = "Mantle") TSoftObjectPtr ClipUse; + UPROPERTY(EditAnywhere, Category = "Mantle") TSoftObjectPtr ClipEquip; + UPROPERTY(EditAnywhere, Category = "Mantle") TSoftObjectPtr ClipPutAway; };