diff --git a/Resources/ScriptApi/mantle.d.luau b/Resources/ScriptApi/mantle.d.luau index e4159b00..8b4770b5 100644 --- a/Resources/ScriptApi/mantle.d.luau +++ b/Resources/ScriptApi/mantle.d.luau @@ -338,9 +338,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 or a place clip fires it when its creator set an "impact" marker in it. 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)> @@ -429,7 +429,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. 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. 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, 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 @@ -965,6 +965,8 @@ declare extern type BackpackService with 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..7fd214f6 100644 --- a/Resources/ScriptApi/mantle.d.ts +++ b/Resources/ScriptApi/mantle.d.ts @@ -341,9 +341,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 or a place clip fires it when its creator set an "impact" marker in it. 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]>; @@ -434,7 +434,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. 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. 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, 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; @@ -972,6 +972,8 @@ interface BackpackService { 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..9d6cc937 100644 --- a/Resources/ScriptApi/mantle.pyi +++ b/Resources/ScriptApi/mantle.pyi @@ -335,7 +335,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. 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. 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, 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.""" @@ -941,6 +941,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..de360d66 100644 --- a/Resources/ScriptApi/mantle_api.json +++ b/Resources/ScriptApi/mantle_api.json @@ -1,4 +1,4 @@ -{"major":1,"minor":115,"classes":[ +{"major":1,"minor":116,"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}, @@ -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. 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. 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, 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}, @@ -173,8 +173,8 @@ {"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 or a place clip fires it when its creator set an \"impact\" marker in it. 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}, @@ -291,7 +291,8 @@ "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":"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/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/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/MantlePlaceAssetConverter.cpp b/Source/MantleEditor/Private/MantlePlaceAssetConverter.cpp index 7abc12b6..707e878e 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 Distinct; + TArray Made; + TArray Creator; + Creator.Reserve(Parts.Clips.Num()); + TSet Counted; + bool bRefused = false; + for (const TCHAR* SlotName : FMantleCreatorClips::ItemSlotNames()) + { + UAnimSequence* const* Found = Parts.Clips.Find(FName(SlotName)); + if (!Found || !*Found) + { + continue; + } + UAnimSequence* Sequence = *Found; + const FString ClipKey = FString::Printf(TEXT("itemclip:%s"), *Sequence->GetPathName()); + Converted.ClipKeys.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(), *Weapon.Name, *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"), *Weapon.Name, 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"), *Weapon.Name, 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"), *Weapon.Name, *Issue.Problem); + Out.Issues.Add(MoveTemp(Issue)); + } + if (bRefused) + { + return false; + } + for (FMantleConvertedClip& Upload : Made) + { + Out.Clips.Add(MoveTemp(Upload)); + } + } // #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 // 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. { diff --git a/Source/MantleEditor/Private/MantlePlaceAssets.cpp b/Source/MantleEditor/Private/MantlePlaceAssets.cpp index ddb68de1..7a78d2f0 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); 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/MantleWeaponBuilderExport.cpp b/Source/MantleEditor/Private/MantleWeaponBuilderExport.cpp index 75c5cb58..fc8c5012 100644 --- a/Source/MantleEditor/Private/MantleWeaponBuilderExport.cpp +++ b/Source/MantleEditor/Private/MantleWeaponBuilderExport.cpp @@ -2,6 +2,7 @@ #include "MantleWeaponBuilderExport.h" #include "AssetRegistry/AssetRegistryModule.h" +#include "Animation/AnimSequence.h" #include "Engine/SkeletalMesh.h" #include "MantlePlaceLimits.h" #include "Engine/StaticMesh.h" @@ -40,6 +41,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 +257,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 +405,57 @@ 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)) - { - 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 + // #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) { - // 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; + } + 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); + } + 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); } - 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 +791,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)) { @@ -891,6 +935,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..039e32c6 100644 --- a/Source/MantleEditor/Private/MantleWeaponBuilderKind.cpp +++ b/Source/MantleEditor/Private/MantleWeaponBuilderKind.cpp @@ -608,7 +608,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 +724,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 +1128,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..658ef249 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"); @@ -345,6 +351,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,7 +359,11 @@ 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) diff --git a/Source/MantleEditor/Private/MantleWeaponFit.cpp b/Source/MantleEditor/Private/MantleWeaponFit.cpp index 0544068c..70c81368 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; } @@ -573,7 +576,7 @@ 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. Point(TEXT("Grip"), Center); 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/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..f3d11a81 100644 --- a/Source/MantleEditor/Private/SMantleWeaponBuilder.cpp +++ b/Source/MantleEditor/Private/SMantleWeaponBuilder.cpp @@ -103,6 +103,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 +253,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(); 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/MantleWeaponBuilderConsumableTest.cpp b/Source/MantleEditor/Private/Tests/MantleWeaponBuilderConsumableTest.cpp index 117fe41c..a400113d 100644 --- a/Source/MantleEditor/Private/Tests/MantleWeaponBuilderConsumableTest.cpp +++ b/Source/MantleEditor/Private/Tests/MantleWeaponBuilderConsumableTest.cpp @@ -3,6 +3,7 @@ #include "MantleWeaponBuilderLogic.h" #include "MantleWeaponDocument.h" #include "MantleWeaponSource.h" +#include "Animation/AnimSequence.h" #include "Misc/AutomationTest.h" #if WITH_DEV_AUTOMATION_TESTS @@ -111,4 +112,45 @@ 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; +} + #endif 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/Public/MantlePlaceAssetConverter.h b/Source/MantleEditor/Public/MantlePlaceAssetConverter.h index ad4dfcd3..6b30c1cd 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; 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 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..d3c28f03 100644 --- a/Source/MantleRuntime/Private/MantlePlaceAssets.cpp +++ b/Source/MantleRuntime/Private/MantlePlaceAssets.cpp @@ -2655,6 +2655,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..7ea275ab 100644 --- a/Source/MantleRuntime/Private/MantlePlaceStorage.cpp +++ b/Source/MantleRuntime/Private/MantlePlaceStorage.cpp @@ -662,11 +662,12 @@ TArray FMantleStorage::CheckAvatarEntries(const 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..a117be89 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[] = { @@ -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; } @@ -1751,8 +1762,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 +1846,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 +1908,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 +1937,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; @@ -2879,6 +2909,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 +2947,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 +3868,16 @@ void FMantleWeaponDocument::CheckRules(const FMantleWeaponDesc& D, TArray(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/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/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/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/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..0f0cf26a 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). */ @@ -952,6 +960,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 +1120,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..b2fb2a78 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() @@ -388,4 +390,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; };