Forest Logo
search
package_2

stance

By @gabrielselvenca

Roblox

Mirrored from Wally

Stance

Procedural animation layers for R15 characters in Roblox.

The Animator keeps playing your keyframe animations. Stance runs right after it, every frame, and adds poses, IK and springs on top through Motor6D.Transform (or AnimationConstraint.Transform). Nothing fights the Animator, and there is no C0 to restore when a layer turns off.

You write small modules ("layers"). Stance handles the loop, springs, blending, IK, and level of detail for every character in the game.

local Posture = { name = "Posture" }

function Posture.layer(rig, out, dt, now, api)
    local speed = rig.hrp.CFrame.LookVector:Dot(rig.velocity)
    local lean = math.clamp(speed / 20, 0, 1) * math.rad(6) * api.LOD.weight(rig, "Posture", "pose")
    out.Waist += Vector3.new(-lean, 0, 0) -- Waist -X bends forward
    return lean > 0
end

return Posture

That is a complete layer: every character bends forward a little as it runs, the joint spring smooths it, and it fades out with distance. Returning false when there's nothing to add lets the rig rest.

Install

Stance is a single ModuleScript with no dependencies. Any of these works:

  • Wally: add Stance = "gabrielselvenca/stance@0.1.0" to [dependencies] in wally.toml.
  • Model file: download Stance.rbxm from Releases and drop it in ReplicatedStorage.
  • By hand: create a ModuleScript named Stance and paste src/init.luau into it.

Tag the characters you want animated. From a server Script:

local CollectionService = game:GetService("CollectionService")

game.Players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function(character)
        CollectionService:AddTag(character, "ProcRig")
    end)
end)

NPCs work the same way: tag the model.

Then start it from one LocalScript:

local Stance = require(game.ReplicatedStorage.Stance) -- or ReplicatedStorage.Packages.Stance with Wally

Stance.add(game.ReplicatedStorage.Layers) -- a Folder of layer ModuleScripts, or a table
Stance.start()

Add every module before start().

How a frame works

  1. The Animator writes the keyframe pose into each joint's Transform.
  2. Stance reads it as the base of that joint.
  3. The current state pose runs (if a module owns the state), then every layer, in order.
  4. Both write into out (spring targets) and rig.direct (no spring).
  5. Joint springs move toward out.
  6. The final rotation is base:Lerp(identity, suppress) * (spring + direct).

suppress is how much of the keyframe to hide, from 0 to 1. A layer that only adds on top returns nothing for it. A layer that replaces the animation (a custom walk cycle, a climb) returns 1.

A rig that has nothing to do goes to rest: Stance hands the keyframe back once and stops touching it until it moves again.

Modules

A module is a table. Every key is optional.

KeyCalledPurpose
nameUsed for LOD lookups and warnings
orderLayers run from low to high (default 50)
lod{ pose, ik, ray }, see LOD
init(rig)once per rigCreate the fields your module keeps on the rig
layer(rig, out, dt, now, api)each updateAdd to out / rig.direct. Return active, suppress
states{ StateName = { duration = s, far = bool } }
pose(rig, out, t, state)each update, while in one of its statest = seconds in the state. Return suppress, spin
owner(rig, dt, now, api)every frame, local player onlyInput, physics, choosing states
onStateChanged(rig, old, new, api)any rig, on changeOne-shot effects

Stance ignores any other key, so your own systems can read extra fields from the same module (input binds, network validation).

spin from pose turns the whole body around rig.spinAxis (flips, rolls). It is applied after the springs, so it isn't smoothed away.

Writing poses

Joint keys: Root, RootPos (studs), Waist, Neck, LShoulder, LElbow, RShoulder, RElbow, LHip, LKnee, LAnkle, RHip, RKnee, RAnkle. Values are Vector3 angles (X, Y, Z) in radians.

local Pose = Stance.Pose

local CROUCH = Pose.define({ -- degrees, converted once
    RootPos = { 0, -1.2, 0 },
    LHip = { 60, 0, 0 }, LKnee = { -100, 0, 0 },
    RHip = { 60, 0, 0 }, RKnee = { -100, 0, 0 },
})

function Module.pose(rig, out, t)
    local s = Pose.smoothstep(0, 0.2, t) -- ease in over 0.2 s
    Pose.add(out, CROUCH, s)
    return s, 0 -- hide the keyframe as the crouch comes in
end

IK

Two-bone IK for arms and legs. Chains: LArm, RArm, LLeg, RLeg.

local rootAngles, midAngles, reached = api.IK.solve(rig, "RArm", targetWorldPosition, pole)

pole is optional: where the elbow or knee points, in the space of the parent part (UpperTorso for arms, LowerTorso for legs).

The result is absolute: it is correct when the keyframe is suppressed. To place one limb while the animation keeps playing, convert it:

rig.direct.RShoulder += api.IK.relative(rig, "RShoulder", rootAngles)
rig.direct.RElbow += api.IK.relative(rig, "RElbow", midAngles)

Use rig.direct for IK. The springs lag a few frames, and a planted foot can't.

IK.relative works for any absolute rotation, not only IK results. It is how one layer overrides a few joints (aim the arms) while the keyframe keeps playing on the rest: suppress hides the keyframe on every joint at once.

LOD

Every non-local rig gets a tier, rechecked 5 times per second:

TierWhenUpdate rate
1 Fullcloser than 30 studs and on screenevery frame
2 Mediumcloser than 80 studs and on screenevery 2 frames
3 Lowcloser than 150 studs, or off screen but nearevery 5 frames
4 Offbeyond thatkeyframe only

The local player is always Full. Only maxFull rigs (default 4) can be Full at once; the farthest drop to Medium. Lower graphics quality shrinks the distances, and zooming the camera in (a smaller FieldOfView) counts as closer. Tier changes blend over a few frames instead of popping. Updates are staggered per rig, so 50 rigs at "every 5 frames" don't all update on the same frame.

Updates also have a budget, config.budget (2 ms by default). Past it, the rigs left wait for the next frame, and the next frame starts from a different rig, so nobody waits twice in a row. The local player never waits.

Each module declares up to which tier each part of it runs:

Module.lod = { pose = 3, ik = 2, ray = 1 } -- the default
  • pose: the pose or layer itself.
  • ik: IK and small detail.
  • ray: new raycasts. Between ray and ik, reuse the last hit you stored on the rig. 0 means never.

Read them with api.LOD.weight(rig, name, "pose" | "ik") (a 0 to 1 weight, already blended) and api.LOD.canRaycast(rig, name).

The rig

Fields you will read the most:

Field
model, humanoid, hrp, jointsThe character, and its joints by key
isLocalThe local player's character
velocity, accel, turnRateMeasured from the root part, smoothed
state, t0, stateParamsCurrent state, when it started (os.clock), its parameters
tier, weight, detailLOD tier, base pose weight, IK/detail weight
paramsRaycastParams that exclude the character
thigh, shinLeg bone lengths
seedRandom per rig, to keep crowds out of sync
lodTierSet it to pin the LOD tier. nil = by distance
disableddisabled.ModuleName = true turns a module off for this rig

Your modules can add their own fields in init. Prefix them (rig.climbPhase) to avoid collisions.

Customizing

Everything below works without editing the module.

Tuning. Any key of Stance.config can go in start():

Stance.start({
    enter = { 50, 120, 250 }, exit = { 55, 130, 270 }, -- bigger LOD distances
    period = { 1, 1, 3, 3 },                          -- Medium updates every frame
    maxFull = 8,
    springs = { Neck = { stiffness = 300, damping = 30 } }, -- a snappier head, other joints keep the default
})

Per character. Every module's init runs when a rig is tracked, in order. A small module with a low order is the place to set things up per character:

Stance.add({
    name = "Setup",
    order = -math.huge,
    init = function(rig)
        if rig.model:HasTag("Boss") then
            rig.lodTier = 1 -- always Full, at any distance. Pinned rigs don't count toward maxFull
        end
        if rig.model:HasTag("Horse") then
            rig.disabled.FootIK = true -- a module written for humans
        end
    end,
})

rig.lodTier and rig.disabled can also change at any time later (Stance.rigOf(model)).

Another module's LOD. module.lod is copied when the module is added. To change it without touching the module:

Stance.add(Layers)
Stance.LOD.ANIMS.FootIK = { pose = 3, ik = 3, ray = 2 } -- foot IK on Low too

Replacing functions. Modules call Pose, IK and LOD through those tables, so a replacement applies everywhere:

-- LOD distances from the camera instead of the character (spectating, cutscenes)
Stance.LOD.origin = function()
    return workspace.CurrentCamera.CFrame.Position
end

-- ignore the player's graphics setting
Stance.LOD.quality = function()
    return 1
end

-- your own solver: same arguments, same return values
Stance.IK.solve = function(rig, chain, target, pole)
    ...
end

IK chains. Stance.IK.CHAINS sets the bones, the side the elbow or knee bends to, and the default pole. Edit it before start():

Stance.IK.CHAINS.LLeg.pole = Vector3.new(0.3, 0, -1) -- knees point slightly outward
Stance.IK.CHAINS.RLeg.pole = Vector3.new(-0.3, 0, -1)

Bone lengths are measured per rig, so scaled characters work without changes. To turn IK off for one limb on one rig, set rig.ik.LLeg = nil in init; IK.solve returns nil for it.

Extra joints (beta)

Tails, wings, ears, a cape: any Motor6D or AnimationConstraint past the R15 set can be animated like the others.

Stance.start({
    extraJoints = {
        Tail = { "Tail", "TailJoint" }, -- part name, joint name inside it
        Tail2 = { "TailTip", "TailJoint" },
    },
})

They are optional: a rig without the part is still animated, its out.Tail is just nil. Check before writing:

function Wag.layer(rig, out, dt, now)
    if not out.Tail then
        return false
    end
    out.Tail += Vector3.new(0, math.sin(now * 6) * 0.4, 0)
    return true
end

Pose.add skips keys the rig doesn't have, so a pose table can include them. The part is searched in the whole character, so it can live inside an Accessory.

Beta, because:

  • Joints are found once, when the rig is tracked. A tail added later needs the tag removed and added again.
  • IK chains only use the R15 joints.
  • The API may still change.

API

Stance.add(moduleOrFolder)
Stance.start(options?)        -- client only; options: any Stance.config key, plus `api`
Stance.setState(rig, state, params?)
Stance.wake(rig)              -- a resting rig updates again (an event turned a layer on)
Stance.localRig()
Stance.rigOf(model)
Stance.rigs                   -- every tracked rig
Stance.modules                -- every module, sorted by order
Stance.states                 -- state -> { module, duration, far }
Stance.cost()                 -- seconds per frame spent in Stance, smoothed
Stance.config                 -- tunables, see the top of src/init.luau
Stance.Pose, Stance.IK, Stance.LOD -- see Customizing
Stance.LOD.origin()           -- where distances are measured from
Stance.LOD.quality()          -- 0.4 to 1, scales distances and maxFull

api, the last argument of layer, owner and onStateChanged, is Stance.api: setState, wake, localRig, Pose, IK, LOD. Pass { api = { ... } } to start to add your own fields or replace one. A common case is a setState that also tells the server:

Stance.start({
    api = {
        setState = function(rig, state, params)
            Stance.setState(rig, state, params)
            StateRemote:FireServer(state, params)
        end,
    },
})

Networking

Stance doesn't replicate anything. Layers driven by physics (lean, foot IK, gait) need nothing, because every client already sees every character move. For states and aim targets, send a small message and call Stance.setState on the other clients. Never send poses.

Performance

Measured in Studio with 50 R15 characters walking around the camera and the 19 modules of the demo game loaded: 0.9 ms per frame on the client. With just the local player: 0.06 ms.

debug.profilebegin("Stance") wraps the loop, so it shows up in the MicroProfiler.

Limits

  • R15 only (extra joints on top of it are in beta).
  • Two-bone IK only (no spine chains).
  • One state at a time per rig.
  • Layers run on the client. The server never sees the procedural pose.

Planned, not in this version:

  • Chain IK (spines, tails) and an aim helper with angle limits.
  • A weight per layer that the game can fade from outside (today it's rig.disabled, on or off).
  • R6 and custom rigs.
  • Parallel Luau for the heavy math.

License

MIT, see LICENSE.

Package Details

Install command (Click to copy)


Version

0.1.0

License

MIT

check_circle

Safe for commercial use

Automated license review — not legal advice.