A2: Player figure and animation

The islander is built in headless Blender (tools/models/figure.py,
`make figure`, `make art`) as twelve rigid parts with their origins at
their joints: an oilskin coat, a sou'wester, sea boots, a bedding roll
and the canvas wing-sail. Debian's Blender can't write glTF, so the
figure is jointed rather than skinned.

FigureRig hangs the parts on pivots, paints them from Palette with the
coat in the player's own oilskin, and plays FigurePoses' hand-written
key poses through one AnimationTree: idle, walk and run by speed,
crouch and creep, air, skydive, glide, swim and aboard; long, short and
carried holds; reload and use layers; fire, boathook swing, keg throw
and building as one-shots; and a flinch when health drops. The chest
takes a third of the pitch and the held item all of it.

Figures animate from replicated state only: positions, look, health,
the held item and the FLAG_ bits (reloading and using now reach
mirrored players), with actions from FX. Every boathook swing is now a
sim "swing" event, sent as a SHOT with no item, so misses are seen and
heard; the new FX kind PLACE shows pieces placed. Protocol version 4.

Tests: test_figure_rig (15), plus swing and PLACE cases in test_harvest
and test_net_fx. make check passes (604 tests); make client-check
passes. Captures: figure_states, figure_actions, figure_close
(make figure-captures), client_glide and client_landed.

Closes #42

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-13 17:35:53 -05:00
co-authored by Claude Opus 5.5
parent da0c65f3ce
commit 07738330b5
66 changed files with 6230 additions and 88 deletions
+438
View File
@@ -0,0 +1,438 @@
## A player's figure (A2): the islander that tools/models/figure.py builds in Blender,
## hung on a hierarchy of pivots and animated by an AnimationTree.
##
## The parts are rigid OBJ models, one per limb, each with its origin at the joint it
## turns about (assets/models/figure/, with figure.json giving the joints). Debian's
## Blender can't export a skinned glTF, so the figure is jointed like a carved toy
## rather than skinned, which suits the folk-art look.
##
## Every animation is built here in code from key poses (FigurePoses), and played by
## one AnimationTree:
##
## move Transition: ground (idle, walk, run by speed), crouch (still and
## creeping by speed), air, skydive, glide, swim, aboard
## hold filtered to the arms: how the held item is carried (long, short, carry)
## reload, use filtered to the arms and head, blended in while they last
## act OneShot on the upper body: fire_long, fire_short, swing, throw, build
## hit OneShot flinch
##
## drive() sets the tree's parameters from a SimEntity, which on a network client is
## only what snapshots and FX replicate (position, look, the FLAG_ bits, the held
## item and health), and trigger() plays one-off actions from FX records. Nothing
## here reads input or any other client-only state. advance() steps the tree; the
## tree runs in manual mode so tests and captures can pose a figure exactly.
class_name FigureRig
extends Node3D
const MODEL_DIR: String = "res://assets/models/figure"
## Joints the animations turn (and, for the hips, move). The spine and hands aren't
## animated: the code turns the spine with the player's pitch and points the hand
## along the aim.
const ANIMATED: Array[String] = [
"hips", "waist", "neck", "shoulder_r", "elbow_r", "shoulder_l", "elbow_l",
"hip_r", "knee_r", "hip_l", "knee_l",
]
## Joint -> its parent pivot. "spine" sits on the waist joint and carries the chest.
const PARENT: Dictionary = {
"hips": "", "waist": "hips", "spine": "waist", "neck": "spine",
"shoulder_r": "spine", "elbow_r": "shoulder_r", "shoulder_l": "spine", "elbow_l": "shoulder_l",
"hip_r": "hips", "knee_r": "hip_r", "hip_l": "hips", "knee_l": "hip_l", "sail": "",
}
## Part model -> the joint pivot it hangs on.
const PART_JOINT: Dictionary = {
"pelvis": "hips", "torso": "spine", "head": "neck",
"upper_arm_r": "shoulder_r", "forearm_r": "elbow_r",
"upper_arm_l": "shoulder_l", "forearm_l": "elbow_l",
"thigh_r": "hip_r", "shin_r": "knee_r", "thigh_l": "hip_l", "shin_l": "knee_l",
"sail": "sail",
}
## Material names in the part models -> Palette colours. COAT and COAT_DARK are the
## player's own oilskin.
const COLOURS: Dictionary = {
"TAR": Palette.TAR, "TAR_WEATHERED": Palette.TAR_WEATHERED, "SKIN": Palette.SKIN,
"INK": Palette.INK, "BARK": Palette.BARK, "CANVAS": Palette.CANVAS, "GILT": Palette.GILT,
"PLANK": Palette.PLANK, "OCHRE_RED": Palette.OCHRE_RED, "TANNED_SAIL": Palette.TANNED_SAIL,
}
const COAT_SHADE: float = 0.28
## The states of `move`, in input order.
const STATES: Array[String] = ["ground", "crouch", "air", "skydive", "glide", "swim", "aboard"]
const HOLDS: Array[String] = ["long", "short", "carry"]
const ACTIONS: Array[String] = ["fire_long", "fire_short", "swing", "throw", "build"]
## How long a figure must be off the ground before it's drawn in the air, so steps
## down a slope don't flicker into a leap.
const AIR_DELAY: float = 0.12
## How quickly the drawn speed follows the real one, per second.
const SPEED_FOLLOW: float = 10.0
## How much of the look's pitch the chest takes; the held item takes all of it.
const SPINE_PITCH: float = 0.35
static var _layout: Dictionary = {}
static var _meshes: Dictionary = {}
static var _library: AnimationLibrary = null
var coat: Color = Palette.OILSKIN
var tree: AnimationTree
## Joint name -> its pivot node.
var joints: Dictionary = {}
## The state, hold and speed last driven, for tests and captures.
var state: String = "ground"
var hold: String = "long"
var speed: float = 0.0
var _hand: Node3D
var _held: MeshInstance3D
var _sail: Node3D
var _pitch: float = 0.0
var _holding: bool = true
var _airborne: float = 0.0
var _last_position: Vector3 = Vector3.INF
var _last_health: int = -1
var _reload: float = 0.0
var _use: float = 0.0
var _reloading: bool = false
var _using: bool = false
## Builds the figure in `coat_colour`.
func _init(coat_colour: Color = Palette.OILSKIN) -> void:
coat = coat_colour
var layout: Dictionary = FigureRig.layout()
var at: Dictionary = layout.get("joints", {})
for joint: String in PARENT:
var pivot: Node3D = Node3D.new()
pivot.name = joint
var parent_name: String = PARENT[joint]
var place: Vector3 = _vector(at.get("waist" if joint == "spine" else joint, [0, 0, 0]))
if parent_name != "":
var parent_joint: String = "waist" if parent_name == "spine" else parent_name
place -= _vector(at.get(parent_joint, [0, 0, 0]))
pivot.position = place
joints[joint] = pivot
(self if parent_name == "" else joints[parent_name] as Node3D).add_child(pivot)
for part: String in PART_JOINT:
var mesh: ArrayMesh = FigureRig.part_mesh(part, coat)
if mesh == null:
continue
var instance: MeshInstance3D = MeshInstance3D.new()
instance.name = part
instance.mesh = mesh
(joints[PART_JOINT[part]] as Node3D).add_child(instance)
_sail = joints["sail"]
_sail.visible = false
_hand = Node3D.new()
_hand.name = "hand_r"
_hand.position = _vector(layout.get("hand_r", [-0.24, 0.86, 0.03])) - _vector(at.get("elbow_r", [0, 0, 0]))
(joints["elbow_r"] as Node3D).add_child(_hand)
_held = MeshInstance3D.new()
_held.name = "Held"
_hand.add_child(_held)
tree = _build_tree()
add_child(tree)
## figure.json: joints, parts and hands.
static func layout() -> Dictionary:
if _layout.is_empty():
var parsed: Variant = JSON.parse_string(FileAccess.get_file_as_string(MODEL_DIR + "/figure.json"))
_layout = parsed if parsed is Dictionary else {"joints": {}}
return _layout
## A part's model painted for a coat colour; shared, so don't change it.
static func part_mesh(part: String, coat_colour: Color) -> ArrayMesh:
var key: String = "%s@%s" % [part, coat_colour.to_html(false)]
if _meshes.has(key):
return _meshes[key]
var path: String = "%s/%s.obj" % [MODEL_DIR, part]
var made: ArrayMesh = null
if ResourceLoader.exists(path):
var source: Mesh = load(path) as Mesh
if source != null:
made = ArrayMesh.new()
for surface: int in source.get_surface_count():
var material: Material = source.surface_get_material(surface)
var name: String = material.resource_name if material != null else ""
made.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, source.surface_get_arrays(surface))
var paint: StandardMaterial3D = StandardMaterial3D.new()
paint.albedo_color = colour_of(name, coat_colour)
paint.roughness = 0.6 if name.begins_with("COAT") else 0.88
if name == "GILT":
paint.metallic = 0.35
made.surface_set_material(made.get_surface_count() - 1, paint)
made.surface_set_name(made.get_surface_count() - 1, name)
made.resource_name = key
_meshes[key] = made
return made
## The Palette colour of a part's material, with COAT the player's own.
static func colour_of(material_name: String, coat_colour: Color) -> Color:
if material_name == "COAT":
return coat_colour
if material_name == "COAT_DARK":
return coat_colour.darkened(COAT_SHADE)
return COLOURS.get(material_name, Palette.HOLD_SHADOW)
## Every animation the figure has, built once from FigurePoses.
static func library() -> AnimationLibrary:
if _library == null:
_library = AnimationLibrary.new()
var rest: Dictionary = layout().get("joints", {})
for name: String in FigurePoses.clips():
_library.add_animation(name, FigurePoses.animation(name, rest))
return _library
static func clear() -> void:
_meshes.clear()
_layout.clear()
_library = null
func hand() -> Node3D:
return _hand
func held() -> MeshInstance3D:
return _held
func sail() -> Node3D:
return _sail
## Sets the tree from an entity's replicated state. `delta` is the time since the last
## drive, for the speed it derives from movement and for the delay before the air.
func drive(entity: SimEntity, delta: float) -> void:
var flat: Vector3 = Vector3(entity.velocity.x, 0.0, entity.velocity.z)
var moved: float = flat.length()
if moved == 0.0 and _last_position != Vector3.INF and delta > 0.0:
var step: Vector3 = entity.position - _last_position
moved = Vector2(step.x, step.z).length() / delta
# A jump in place (a correction, a respawn) isn't running.
if moved > Tuning.SLIDE_MAX_SPEED * 2.0:
moved = 0.0
_last_position = entity.position
speed = moved if delta <= 0.0 else lerpf(speed, moved, clampf(delta * SPEED_FOLLOW, 0.0, 1.0))
_airborne = 0.0 if entity.on_ground or entity.swimming else _airborne + delta
state = state_of(entity, _airborne >= AIR_DELAY)
_holding = state in ["ground", "crouch", "air"]
hold = hold_of(EntityView.held_code(entity))
_reloading = entity.reload_ticks > 0 and _holding
_using = entity.use_ticks > 0 and _holding
if _last_health >= 0 and entity.health < _last_health and not entity.eliminated:
flinch()
_last_health = entity.health
_pitch = float(entity.pitch) / PlayerCommand.PITCH_MAX * (PI * 0.5)
_sail.visible = state == "glide"
_hand.visible = _holding
tree.set("parameters/move/transition_request", state)
tree.set("parameters/ground/blend_position", speed)
tree.set("parameters/crouch/blend_position", speed)
tree.set("parameters/ground_pace/scale", clampf(speed / Tuning.WALK_SPEED, 0.75, 1.3) if speed > 0.3 else 1.0)
tree.set("parameters/hold/transition_request", hold)
tree.set("parameters/holding/blend_amount", 1.0 if _holding else 0.0)
## Which of STATES an entity is drawn in.
static func state_of(entity: SimEntity, airborne: bool) -> String:
match entity.drop_state:
Drop.ABOARD:
return "aboard"
Drop.FREEFALL:
return "skydive"
Drop.GLIDING:
return "glide"
if entity.swimming:
return "swim"
if airborne:
return "air"
return "crouch" if entity.crouching else "ground"
## How an item is carried: long things in both hands, small weapons in one, and
## everything else (tonics, bandages, kegs) held up in front.
static func hold_of(code: int) -> String:
var id: String = ItemModels.id_of(code)
if ItemModels.info(id).get("support") != null:
return "long"
var def: ItemDef = ItemCatalog.get_def(code)
if def != null and def.is_weapon() and id != "powder_keg":
return "short"
return "carry"
## Plays the one-off action an FX record shows: a shot, a swing or throw, a harvest
## hit (a swing) or a piece placed.
func hear(record: Dictionary) -> void:
match int(record.get("kind", 0)):
NetFx.SHOT:
var id: String = ItemModels.id_of(int(record.get("item", -1)))
if id == ItemCatalog.BOATHOOK:
act("swing")
elif id == "powder_keg":
act("throw")
else:
act("fire_long" if hold_of(int(record["item"])) == "long" else "fire_short")
NetFx.PLACE:
act("build")
## Plays one of ACTIONS on the upper body, from its start.
func act(action: String) -> void:
if not ACTIONS.has(action) or not _holding:
return
tree.set("parameters/action/transition_request", action)
tree.set("parameters/act/request", AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE)
func flinch() -> void:
tree.set("parameters/hit/request", AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE)
## Steps the animation by `delta` and points the chest and held item along the look.
func advance(delta: float) -> void:
_reload = move_toward(_reload, 1.0 if _reloading else 0.0, delta * 6.0)
_use = move_toward(_use, 1.0 if _using else 0.0, delta * 6.0)
tree.set("parameters/reload/blend_amount", _reload)
tree.set("parameters/use/blend_amount", _use)
tree.advance(delta)
_aim()
## Whether an action or flinch is playing.
func acting() -> bool:
return bool(tree.get("parameters/act/active")) or bool(tree.get("parameters/hit/active"))
## The hand's orientation relative to the figure.
func hand_basis() -> Basis:
return relative(_hand).basis
## A node's transform relative to this figure, without needing the scene tree.
func relative(node: Node3D) -> Transform3D:
var out: Transform3D = Transform3D.IDENTITY
var at: Node = node
while at != null and at != self:
out = (at as Node3D).transform * out
at = at.get_parent()
return out
func _aim() -> void:
var spine: Node3D = joints["spine"]
spine.rotation = Vector3(-_pitch * SPINE_PITCH if _holding else 0.0, 0.0, 0.0)
# The item points along the look whatever the arm is doing; the arm only places it.
var parent: Transform3D = relative(_hand.get_parent() as Node3D)
_hand.basis = parent.basis.orthonormalized().inverse() * Basis(Vector3.RIGHT, -_pitch)
func _build_tree() -> AnimationTree:
var made: AnimationTree = AnimationTree.new()
made.name = "Animation"
made.add_animation_library("", FigureRig.library())
made.callback_mode_process = AnimationMixer.ANIMATION_CALLBACK_MODE_PROCESS_MANUAL
made.deterministic = true
var root: AnimationNodeBlendTree = AnimationNodeBlendTree.new()
var ground: AnimationNodeBlendSpace1D = AnimationNodeBlendSpace1D.new()
ground.add_blend_point(_clip("idle"), 0.0, -1, &"idle")
ground.add_blend_point(_clip("walk"), Tuning.WALK_SPEED, -1, &"walk")
ground.add_blend_point(_clip("run"), Tuning.SPRINT_SPEED, -1, &"run")
ground.min_space = 0.0
ground.max_space = Tuning.SPRINT_SPEED
ground.sync = true
root.add_node("ground", ground)
root.add_node("ground_pace", AnimationNodeTimeScale.new())
root.connect_node("ground_pace", 0, "ground")
var crouch: AnimationNodeBlendSpace1D = AnimationNodeBlendSpace1D.new()
crouch.add_blend_point(_clip("crouch_idle"), 0.0, -1, &"crouch_idle")
crouch.add_blend_point(_clip("crouch_walk"), Tuning.CROUCH_SPEED, -1, &"crouch_walk")
crouch.min_space = 0.0
crouch.max_space = Tuning.CROUCH_SPEED
crouch.sync = true
root.add_node("crouch", crouch)
var move: AnimationNodeTransition = AnimationNodeTransition.new()
move.xfade_time = 0.18
move.input_count = STATES.size()
for index: int in STATES.size():
move.set_input_name(index, STATES[index])
root.add_node("move", move)
root.connect_node("move", 0, "ground_pace")
root.connect_node("move", 1, "crouch")
for index: int in range(2, STATES.size()):
root.add_node("clip_" + STATES[index], _clip(STATES[index]))
root.connect_node("move", index, "clip_" + STATES[index])
var holds: AnimationNodeTransition = AnimationNodeTransition.new()
holds.xfade_time = 0.15
holds.input_count = HOLDS.size()
for index: int in HOLDS.size():
holds.set_input_name(index, HOLDS[index])
root.add_node("hold_" + HOLDS[index], _clip("hold_" + HOLDS[index]))
root.add_node("hold", holds)
for index: int in HOLDS.size():
root.connect_node("hold", index, "hold_" + HOLDS[index])
var holding: AnimationNodeBlend2 = _filtered(AnimationNodeBlend2.new(), FigurePoses.ARMS) as AnimationNodeBlend2
root.add_node("holding", holding)
root.connect_node("holding", 0, "move")
root.connect_node("holding", 1, "hold")
var last: String = "holding"
for layer: String in ["reload", "use"]:
root.add_node("clip_" + layer, _clip(layer))
root.add_node(layer, _filtered(AnimationNodeBlend2.new(), FigurePoses.ARMS_AND_HEAD))
root.connect_node(layer, 0, last)
root.connect_node(layer, 1, "clip_" + layer)
last = layer
var actions: AnimationNodeTransition = AnimationNodeTransition.new()
actions.xfade_time = 0.0
actions.input_count = ACTIONS.size()
for index: int in ACTIONS.size():
actions.set_input_name(index, ACTIONS[index])
root.add_node("clip_" + ACTIONS[index], _clip(ACTIONS[index]))
root.add_node("action", actions)
for index: int in ACTIONS.size():
root.connect_node("action", index, "clip_" + ACTIONS[index])
var act_shot: AnimationNodeOneShot = _filtered(AnimationNodeOneShot.new(), FigurePoses.UPPER) as AnimationNodeOneShot
act_shot.fadein_time = 0.04
act_shot.fadeout_time = 0.12
root.add_node("act", act_shot)
root.connect_node("act", 0, last)
root.connect_node("act", 1, "action")
root.add_node("clip_flinch", _clip("flinch"))
var hit: AnimationNodeOneShot = _filtered(AnimationNodeOneShot.new(), FigurePoses.TORSO) as AnimationNodeOneShot
hit.fadein_time = 0.03
hit.fadeout_time = 0.1
root.add_node("hit", hit)
root.connect_node("hit", 0, "act")
root.connect_node("hit", 1, "clip_flinch")
root.connect_node("output", 0, "hit")
made.tree_root = root
made.root_node = NodePath("..")
made.active = true
return made
func _clip(name: String) -> AnimationNodeAnimation:
var node: AnimationNodeAnimation = AnimationNodeAnimation.new()
node.animation = name
return node
func _filtered(node: AnimationNode, filtered: Array[String]) -> AnimationNode:
node.filter_enabled = true
for joint: String in filtered:
node.set_filter_path(NodePath(FigurePoses.path_of(joint)), true)
return node
static func _vector(values: Variant) -> Vector3:
var list: Array = values if values is Array else [0, 0, 0]
return Vector3(float(list[0]), float(list[1]), float(list[2]))