Merge #29: cutscene kit and roof luggage

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Forrest 2026-10-07 22:00:01 -04:00
commit 78ff549407
4 changed files with 773 additions and 133 deletions

View file

@ -0,0 +1,698 @@
class_name CutsceneKit
extends RefCounted
## The pieces the cutscenes share (FarmersReturn's ending, the opening intro), all static:
## * The farmers' station wagon (car_002, no collision) with its engine sound and, National
## Lampoon style, a tall, crooked pile of luggage strapped to the roof rack (Luggage, which
## sways when the car turns or brakes).
## * The farmers: tinted mannequins in straw sun hats, with the player's animations.
## * Routes: a corner-rounded Curve3D through any list of points, and placing a node on it
## facing the way it runs (drive a route backwards by reversing its points).
## * The cutscene camera: easing toward a shot, and following behind a car.
## * The letterbox overlay (Letterbox): black bars, a caption, and a skip hint.
## The caller owns everything built here and frees it.
const CAR_SCENE := "res://assets/farm/ithappy/farm/prefabs/assets/transport/car_002.tscn"
const FARMER_SCENE := "res://assets/kaykit_characters/characters/Mannequin_Medium.glb"
const ANIMATIONS := "res://game/resources/player_animations.res"
## The farmers' tints: the farmer (blue) and the farmer's wife (red).
const FARMER_TINTS: Array[Color] = [Color(0.35, 0.5, 0.85), Color(0.85, 0.45, 0.4)]
const STRAW := Color(0.92, 0.8, 0.45)
const BAGS: Array[String] = [
"res://assets/farm/ithappy/farm/prefabs/assets/prop/bag_001.tscn",
"res://assets/farm/ithappy/farm/prefabs/assets/prop/bag_002.tscn",
"res://assets/farm/ithappy/farm/prefabs/assets/prop/bag_003.tscn",
]
const CRATES: Array[String] = [
"res://assets/farm/ithappy/farm/prefabs/assets/box/box_004.tscn",
"res://assets/farm/ithappy/farm/prefabs/assets/box/box_005.tscn",
]
## The roof is the top part of the car this deep (a share of its height): the roof skin and the
## rack on it. Its footprint is where the luggage goes.
const ROOF_BAND := 0.15
## The pile, bottom up. Each piece: "bag" / "crate" (an index into BAGS / CRATES, and a scale),
## "case" (a primitive suitcase: its size in meters and color), or "hatbox" (its radius and
## color); "at" is where its middle goes, as a share of the roof's half width (x, + to the car's
## left) and half length (z, + forward); "yaw" and "tilt" (pitch, roll) are degrees. Each piece
## rests on whatever is under its middle already, so the pile builds itself on any roof.
const PILE: Array[Dictionary] = [
{"case": Vector3(0.56, 0.22, 0.9), "color": Color(0.45, 0.27, 0.14), "at": Vector2(-0.47, 0.41), "yaw": 3.0},
{"case": Vector3(0.52, 0.26, 0.84), "color": Color(0.2, 0.5, 0.47), "at": Vector2(0.51, 0.45), "yaw": -4.0},
{"bag": 0, "scale": 0.72, "at": Vector2(-0.45, -0.5), "yaw": 30.0},
{"bag": 1, "scale": 0.68, "at": Vector2(0.47, -0.47), "yaw": -20.0},
{"case": Vector3(0.84, 0.2, 0.56), "color": Color(0.74, 0.2, 0.17), "at": Vector2(0.05, 0.33), "yaw": 7.0, "tilt": Vector2(0.0, 2.0)},
{"crate": 1, "scale": 0.5, "at": Vector2(-0.38, -0.5), "yaw": 10.0, "tilt": Vector2(0.0, -3.0)},
{"crate": 0, "scale": 0.44, "at": Vector2(0.44, -0.46), "yaw": -6.0, "tilt": Vector2(2.0, 3.0)},
{"case": Vector3(0.5, 0.36, 0.17), "color": Color(0.86, 0.66, 0.22), "at": Vector2(0.14, 0.29), "yaw": -8.0, "tilt": Vector2(0.0, 4.0)},
{"bag": 2, "scale": 0.5, "at": Vector2(-0.45, 0.42), "yaw": 25.0},
{"crate": 1, "scale": 0.32, "at": Vector2(-0.42, 0.4), "yaw": 25.0, "tilt": Vector2(3.0, -2.0)},
{"hatbox": 0.18, "color": Color(0.9, 0.55, 0.65), "at": Vector2(-0.3, -0.5), "tilt": Vector2(-4.0, 6.0)},
]
## Where the straps cross the pile (a share of the roof's half length), and their look.
const STRAPS: Array[float] = [0.36, 0.06, -0.5]
const STRAP_WIDTH := 0.06
const STRAP_THICK := 0.018
const STRAP_COLOR := Color(0.13, 0.11, 0.09)
const MATTRESS_RADIUS := 0.17
const MATTRESS_LENGTH := 1.1
# --- The car ---------------------------------------------------------------------------------
## The farmers' station wagon under parent, its collision off; loaded with the roof luggage
## (load_roof) unless loaded is false.
static func make_car(parent: Node, loaded := true) -> Node3D:
var car := (load(CAR_SCENE) as PackedScene).instantiate() as Node3D
parent.add_child(car)
for body in car.find_children("*", "CollisionObject3D", true, false):
(body as CollisionObject3D).collision_layer = 0
if loaded:
load_roof(car)
return car
## The car's engine: a 3D player on the car with the truck_engine loop, already playing (if audio
## has the sound; there's no audio in some tests).
static func add_engine(car: Node3D, audio: FarmAudio) -> AudioStreamPlayer3D:
var engine := AudioStreamPlayer3D.new()
engine.name = "Engine"
engine.bus = &"SFX"
engine.unit_size = 10.0
engine.volume_db = -6.0
if audio != null:
engine.stream = audio.stream_of("truck_engine")
car.add_child(engine)
if engine.stream != null:
engine.play()
return engine
## The roof in the car's space, from its meshes (not the luggage): the top is the top of the
## car's AABB (the roof rack), and the footprint and the bottom are those of its vertices in the
## top ROOF_BAND of its height (the roof skin and the rack).
static func roof_of(car: Node3D) -> AABB:
var skip := luggage_of(car)
var whole := mesh_bounds(car, car, skip)
var band := whole.end.y - whole.size.y * ROOF_BAND
var lo := Vector3(INF, INF, INF)
var hi := -lo
for node in car.find_children("*", "MeshInstance3D", true, false):
var mi := node as MeshInstance3D
if mi.mesh == null or (skip != null and skip.is_ancestor_of(mi)):
continue
var xf := _to_space(mi, car)
for s in mi.mesh.get_surface_count():
for v: Vector3 in mi.mesh.surface_get_arrays(s)[Mesh.ARRAY_VERTEX]:
var p := xf * v
if p.y >= band:
lo = lo.min(p)
hi = hi.max(p)
if lo.x == INF:
return AABB(Vector3(whole.position.x, band, whole.position.z), Vector3(whole.size.x, whole.end.y - band, whole.size.z))
return AABB(Vector3(lo.x, lo.y, lo.z), Vector3(hi.x - lo.x, whole.end.y - lo.y, hi.z - lo.z))
## The bounds of every mesh under node (and node itself, if it's one), in space's coordinates
## (space is node or one of its ancestors), leaving out the meshes under skip. Works out of the
## tree too. Empty if there are none.
static func mesh_bounds(node: Node, space: Node, skip: Node = null) -> AABB:
var meshes := node.find_children("*", "MeshInstance3D", true, false)
if node is MeshInstance3D:
meshes.append(node)
var out := AABB()
var first := true
for m in meshes:
var mi := m as MeshInstance3D
if mi.mesh == null or (skip != null and (skip == mi or skip.is_ancestor_of(mi))):
continue
var box := _to_space(mi, space) * mi.get_aabb()
out = box if first else out.merge(box)
first = false
return out
static func _to_space(node: Node, space: Node) -> Transform3D:
var xf := Transform3D.IDENTITY
var n := node
while n != null and n != space:
if n is Node3D:
xf = (n as Node3D).transform * xf
n = n.get_parent()
return xf
# --- The roof luggage --------------------------------------------------------------------------
## The roof load: the pile on the rack (pieces), the straps over it, and the rolled mattress
## hanging off the car's right side (hanging), all under this node. It sits on the middle of the
## rack's top, which is the pivot of its sway.
class Luggage extends Node3D:
## Sway: a stiff, under-damped spring (per second squared, per second), the lean per m/s² of
## braking and per rad/s of turning, and the most it leans (radians).
const STIFFNESS := 80.0
const DAMPING := 4.5
const LEAN_PER_ACCEL := 0.0045
const LEAN_PER_TURN := 0.05
const MAX_ACCEL := 15.0
const MAX_TURN := 2.0
const MAX_LEAN := 0.12
var pieces: Array[Node3D] = []
var straps: Array[Node3D] = []
var hanging: Node3D
## The lean (x: forward, about the car's x; y: to the car's right, about its z, radians) and
## how fast it's changing.
var lean := Vector2.ZERO
var lean_speed := Vector2.ZERO
## One step of the sway. turn_rate: the car's heading change (rad/s, + turning left);
## accel: its change in speed along its way (m/s², - braking). Braking tips the pile forward,
## a turn throws it to the outside, and it wobbles back.
func sway(delta: float, turn_rate: float, accel: float) -> void:
if delta <= 0.0:
return
var want := Vector2(-clampf(accel, -MAX_ACCEL, MAX_ACCEL) * LEAN_PER_ACCEL,
clampf(turn_rate, -MAX_TURN, MAX_TURN) * LEAN_PER_TURN)
var left := minf(delta, 0.25) # a long step doesn't fling it
while left > 0.0:
var h := minf(left, 1.0 / 60.0)
lean_speed += ((want - lean) * STIFFNESS - lean_speed * DAMPING) * h
lean = (lean + lean_speed * h).clampf(-MAX_LEAN, MAX_LEAN)
left -= h
rotation = Vector3(lean.x, 0.0, lean.y)
## A jolt (rad/s: forward, to the right): a door slam, the engine catching. sway() plays it out.
func nudge(kick: Vector2) -> void:
lean_speed += kick
## Straight and still.
func settle() -> void:
lean = Vector2.ZERO
lean_speed = Vector2.ZERO
rotation = Vector3.ZERO
## The car's Luggage, or null.
static func luggage_of(car: Node3D) -> Luggage:
return car.get_node_or_null(^"Luggage") as Luggage if car != null else null
## sway() on the car's luggage, if it has any.
static func sway_luggage(car: Node3D, delta: float, turn_rate: float, accel: float) -> void:
var luggage := luggage_of(car)
if luggage != null:
luggage.sway(delta, turn_rate, accel)
## Straps the roof luggage onto car (once; a second call returns the first load): the PILE,
## stacked from the roof's footprint and height (roof_of), the STRAPS over it, and a rolled
## mattress hanging off the car's right side. No collision on any of it.
static func load_roof(car: Node3D) -> Luggage:
var old := luggage_of(car)
if old != null:
return old
var roof := roof_of(car)
var half := Vector2(roof.size.x, roof.size.z) * 0.5
var luggage := Luggage.new()
luggage.name = "Luggage"
luggage.position = Vector3(roof.get_center().x, roof.end.y, roof.get_center().z)
car.add_child(luggage)
var pile := Pile.new(half, 0.5)
for spec in PILE:
var piece := _piece(spec)
var tilt: Vector2 = spec.get("tilt", Vector2.ZERO)
piece.rotation = Vector3(deg_to_rad(tilt.x), deg_to_rad(float(spec.get("yaw", 0.0))), deg_to_rad(tilt.y))
luggage.add_child(piece)
var at: Vector2 = spec["at"]
_stack(luggage, pile, piece, at * half, 0.04 if spec.has("bag") else 0.0)
var strap_mat := _material(STRAP_COLOR)
var buckle_mat := _material(Color(0.62, 0.62, 0.58))
var faces := _faces(luggage)
for z in STRAPS:
var strap := _strap(faces, z * half.y, half.x, roof.size.y, strap_mat, buckle_mat)
luggage.add_child(strap)
luggage.straps.append(strap)
luggage.hanging = _mattress(pile, half, roof.size.y)
luggage.add_child(luggage.hanging)
return luggage
## Where the pile has got to: the height of its top (above the rack) on a grid over the roof,
## twice: what the next piece can rest on (under the middle of each piece, as their bounds are
## boxy) and the whole outline (what the straps go over).
class Pile extends RefCounted:
const CELL := 0.04
var origin: Vector2
var nx: int
var nz: int
var rests := PackedFloat32Array()
var outline := PackedFloat32Array()
func _init(half: Vector2, margin: float) -> void:
origin = -half - Vector2(margin, margin)
nx = ceili((half.x + margin) * 2.0 / CELL)
nz = ceili((half.y + margin) * 2.0 / CELL)
rests.resize(nx * nz)
rests.fill(0.0)
outline.resize(nx * nz)
outline.fill(0.0)
## The highest top under rect (x, z): of what a piece can rest on, or of the outline.
func top(rect: Rect2, of_outline := false) -> float:
var grid := outline if of_outline else rests
var out := 0.0
var c := _cells(rect)
for j in range(c.position.y, c.end.y):
for i in range(c.position.x, c.end.x):
out = maxf(out, grid[j * nx + i])
return out
## A piece over rect (x, z) with its top at `to`.
func raise(rect: Rect2, to: float) -> void:
var c := _cells(rect)
var middle := _cells(rect.grow_individual(-rect.size.x * 0.1, -rect.size.y * 0.1, -rect.size.x * 0.1, -rect.size.y * 0.1))
for j in range(c.position.y, c.end.y):
for i in range(c.position.x, c.end.x):
var k := j * nx + i
outline[k] = maxf(outline[k], to)
if middle.has_point(Vector2i(i, j)):
rests[k] = maxf(rests[k], to)
## The cells whose middles are in rect (at least one), as a Rect2i of indices (clipped to the
## grid).
func _cells(rect: Rect2) -> Rect2i:
var a := ((rect.position - origin) / CELL).round()
var b := ((rect.end - origin) / CELL).round()
var lo := Vector2i(clampi(int(a.x), 0, nx - 1), clampi(int(a.y), 0, nz - 1))
var hi := Vector2i(clampi(maxi(int(b.x), lo.x + 1), 0, nx), clampi(maxi(int(b.y), lo.y + 1), 0, nz))
return Rect2i(lo, hi - lo)
## The x where the pile starts (its outline's leftmost cell, - x) between z0 and z1.
func min_x(z0: float, z1: float) -> float:
var c := _cells(Rect2(origin.x, z0, nx * CELL, z1 - z0))
for i in nx:
for j in range(c.position.y, c.end.y):
if outline[j * nx + i] > 0.0:
return origin.x + i * CELL
return 0.0
## Puts piece (already turned and scaled) on top of what's under its middle at `at` (x, z) and
## raises the pile under it (its bounds are boxy, so neighbours that only touch at the corners
## stand side by side instead of on each other). Soft pieces sink in a little (not into the rack).
static func _stack(luggage: Luggage, pile: Pile, piece: Node3D, at: Vector2, sink: float) -> void:
var b := Transform3D(piece.basis, Vector3.ZERO) * mesh_bounds(piece, piece)
var rect := Rect2(at.x + b.position.x, at.y + b.position.z, b.size.x, b.size.z)
var base := pile.top(rect.grow_individual(-rect.size.x * 0.3, -rect.size.y * 0.3, -rect.size.x * 0.3, -rect.size.y * 0.3))
var y := maxf(base - sink, 0.0)
piece.position = Vector3(at.x, y - b.position.y, at.y)
pile.raise(rect, y + b.size.y)
luggage.pieces.append(piece)
static func _piece(spec: Dictionary) -> Node3D:
if spec.has("case"):
return _suitcase(spec["case"], spec["color"])
if spec.has("hatbox"):
return _hatbox(float(spec["hatbox"]), spec["color"])
var path: String = BAGS[int(spec["bag"])] if spec.has("bag") else CRATES[int(spec["crate"])]
var prop := (load(path) as PackedScene).instantiate() as Node3D
for body in prop.find_children("*", "CollisionObject3D", true, false):
body.get_parent().remove_child(body)
body.free()
var s := float(spec.get("scale", 1.0))
prop.scale = Vector3(s, s, s)
return prop
## A suitcase: a box with a darker seam around its middle, a handle on its long side, and two
## latches.
static func _suitcase(size: Vector3, color: Color) -> Node3D:
var root := Node3D.new()
var trim := _material(color.darkened(0.45))
_box(root, size, Vector3.ZERO, _material(color))
_box(root, Vector3(size.x + 0.012, 0.022, size.z + 0.012), Vector3.ZERO, trim)
# The handle sits on the +x face if the case lies wide, else on its top edge (standing up).
var standing := size.y > size.z
var face := Vector3(size.x * 0.5, 0.0, 0.0) if not standing else Vector3(0.0, size.y * 0.5, 0.0)
var out := Vector3.RIGHT if not standing else Vector3.UP
var along := Vector3(0.0, 0.0, 1.0) if not standing else Vector3(1.0, 0.0, 0.0)
var grip := Vector3(0.025, 0.025, 0.025) + along * 0.13
_box(root, grip, face + out * 0.04, trim)
for side: float in [-1.0, 1.0]:
_box(root, Vector3(0.022, 0.022, 0.022) + out * 0.02, face + out * 0.02 + along * 0.055 * side, trim)
_box(root, Vector3(0.03, 0.03, 0.03) + along * 0.01, face + along * size.dot(along) * 0.33 * side, _material(Color(0.75, 0.72, 0.6)))
return root
## Every triangle of the pieces' meshes, in the luggage's space (three points each).
static func _faces(luggage: Luggage) -> PackedVector3Array:
var out := PackedVector3Array()
for piece in luggage.pieces:
var meshes := piece.find_children("*", "MeshInstance3D", true, false)
if piece is MeshInstance3D:
meshes.append(piece)
for node in meshes:
var mi := node as MeshInstance3D
if mi.mesh == null:
continue
var xf := _to_space(mi, luggage)
for v in mi.mesh.get_faces():
out.append(xf * v)
return out
## The pile's outline where a strap crosses it at z: the highest of its triangles cut by the
## planes at z and at the strap's edges, in steps of 2 cm across x (bin -> height).
static func _profile(faces: PackedVector3Array, z: float) -> Dictionary:
const STEP := 0.02
var tops := {}
var w := STRAP_WIDTH * 0.5
for t in range(0, faces.size(), 3):
var tri := [faces[t], faces[t + 1], faces[t + 2]]
if minf(faces[t].z, minf(faces[t + 1].z, faces[t + 2].z)) > z + w \
or maxf(faces[t].z, maxf(faces[t + 1].z, faces[t + 2].z)) < z - w:
continue
for plane: float in [z - w, z, z + w]:
var hits: Array[Vector2] = []
for e in 3:
var p: Vector3 = tri[e]
var q: Vector3 = tri[(e + 1) % 3]
if p.z != q.z and (p.z - plane) * (q.z - plane) <= 0.0:
var f := (plane - p.z) / (q.z - p.z)
hits.append(Vector2(lerpf(p.x, q.x, f), lerpf(p.y, q.y, f)))
if hits.size() < 2:
continue
var a := hits[0] if hits[0].x <= hits[1].x else hits[1]
var b := hits[1] if hits[0].x <= hits[1].x else hits[0]
for i in range(floori(a.x / STEP), floori(b.x / STEP) + 1):
var x0 := maxf(a.x, i * STEP)
var x1 := minf(b.x, (i + 1) * STEP)
var ys := [a.y, b.y] if b.x - a.x < 1e-6 else \
[lerpf(a.y, b.y, (x0 - a.x) / (b.x - a.x)), lerpf(a.y, b.y, (x1 - a.x) / (b.x - a.x))]
tops[i] = maxf(float(tops.get(i, -INF)), maxf(ys[0], ys[1]))
var out := {} # x -> height, at both edges of each step
for i: int in tops:
for x: float in [i * STEP, (i + 1) * STEP]:
out[x] = maxf(float(out.get(x, -INF)), tops[i])
return out
## A round hatbox (radius r) with a lid and a ribbon round its middle.
static func _hatbox(r: float, color: Color) -> Node3D:
var root := Node3D.new()
var h := r * 1.1
# radius, height, middle (y), color: the box, its lid, the ribbon
for part in [[r, h, 0.0, color], [r + 0.012, 0.05, h * 0.5 - 0.02, color.lightened(0.3)],
[r + 0.006, 0.025, -0.04, Color(0.35, 0.2, 0.45)]]:
var mesh := CylinderMesh.new()
mesh.top_radius = part[0]
mesh.bottom_radius = part[0]
mesh.height = part[1]
var mi := MeshInstance3D.new()
mi.mesh = mesh
mi.position.y = part[2]
mi.material_override = _material(part[3])
root.add_child(mi)
return root
## A strap across the pile at z: taut over the top of the pile (the upper hull of its outline
## there) and down to the roof's edges on both sides (drop below the rack's top), with a buckle.
static func _strap(faces: PackedVector3Array, z: float, half_x: float, drop: float, mat: Material, buckle: Material) -> Node3D:
var profile := _profile(faces, z)
var xs := profile.keys()
xs.sort()
var points: Array[Vector2] = []
for x: float in xs:
points.append(Vector2(x, float(profile[x]) + STRAP_THICK * 0.5))
var ends := Vector2(-half_x, half_x)
if not points.is_empty():
ends = Vector2(minf(-half_x, points[0].x - 0.005), maxf(half_x, points[-1].x + 0.005))
points.push_front(Vector2(ends.x, -drop))
points.append(Vector2(ends.y, -drop))
var hull: Array[Vector2] = []
for p in points: # in x order: the upper hull is the strap pulled tight
while hull.size() >= 2 and (hull[-1] - hull[-2]).cross(p - hull[-2]) >= 0.0:
hull.pop_back()
hull.append(p)
var strap := Node3D.new()
strap.name = "Strap"
var highest: MeshInstance3D = null
for i in hull.size() - 1:
var a := hull[i]
var d := hull[i + 1] - a
var seg := _box(strap, Vector3(d.length() + STRAP_THICK, STRAP_THICK, STRAP_WIDTH), Vector3.ZERO, mat)
seg.position = Vector3(a.x + d.x * 0.5, a.y + d.y * 0.5, z)
seg.rotation.z = atan2(d.y, d.x)
if highest == null or seg.position.y > highest.position.y:
highest = seg
var b := _box(strap, Vector3(0.07, STRAP_THICK * 2.0, STRAP_WIDTH + 0.02), Vector3.ZERO, buckle)
b.transform = highest.transform
return strap
## A rolled-up mattress hanging off the car's right side (- x) beside the pile, tied with two
## cords that run up to the pile, its back end sagging.
static func _mattress(pile: Pile, half: Vector2, drop: float) -> Node3D:
var r := MATTRESS_RADIUS
var root := Node3D.new()
root.name = "Mattress"
var z0 := half.y * 0.05
var side := minf(pile.min_x(z0 - MATTRESS_LENGTH * 0.5, z0 + MATTRESS_LENGTH * 0.5), -half.x)
root.position = Vector3(side - r - 0.01, r - drop, z0)
root.rotation = Vector3(deg_to_rad(-7.0), 0.0, deg_to_rad(-12.0))
var roll := CylinderMesh.new()
roll.top_radius = r
roll.bottom_radius = r
roll.height = MATTRESS_LENGTH
var body := MeshInstance3D.new()
body.mesh = roll
body.rotation.x = PI / 2.0
body.material_override = _material(Color(0.78, 0.82, 0.9))
root.add_child(body)
var stripe := _material(Color(0.42, 0.52, 0.72))
for end: float in [-1.0, 1.0]: # the rolled-up ends
var cap := CylinderMesh.new()
cap.top_radius = r * 0.72
cap.bottom_radius = r * 0.72
cap.height = 0.012
var c := MeshInstance3D.new()
c.mesh = cap
c.rotation.x = PI / 2.0
c.position = Vector3(0.0, 0.0, end * MATTRESS_LENGTH * 0.5)
c.material_override = stripe
root.add_child(c)
var cord := _material(Color(0.5, 0.38, 0.22))
var to_root := root.transform.affine_inverse()
for along: float in [-0.3, 0.3]:
var ring := TorusMesh.new()
ring.inner_radius = r - 0.004
ring.outer_radius = r + 0.022
var t := MeshInstance3D.new()
t.mesh = ring
t.rotation.x = PI / 2.0
t.position = Vector3(0.0, 0.0, along * MATTRESS_LENGTH)
t.material_override = cord
root.add_child(t)
# The cord runs from the top of the ring in over the edge, tied off on top of the pile.
var from := root.transform * Vector3(0.0, r + 0.015, along * MATTRESS_LENGTH)
var tie := Vector2(side + 0.12, from.z)
var on := Vector3(tie.x, minf(pile.top(Rect2(tie - Vector2(0.03, 0.03), Vector2(0.06, 0.06)), true), r * 2.0) + 0.012, tie.y)
_rod(root, to_root * from, to_root * on, 0.012, cord)
return root
static func _box(parent: Node3D, size: Vector3, at: Vector3, mat: Material) -> MeshInstance3D:
var mesh := BoxMesh.new()
mesh.size = size
var mi := MeshInstance3D.new()
mi.mesh = mesh
mi.position = at
mi.material_override = mat
parent.add_child(mi)
return mi
## A thin cylinder from a to b (in parent's space).
static func _rod(parent: Node3D, a: Vector3, b: Vector3, radius: float, mat: Material) -> MeshInstance3D:
var mesh := CylinderMesh.new()
mesh.top_radius = radius
mesh.bottom_radius = radius
mesh.height = a.distance_to(b)
mesh.radial_segments = 6
var mi := MeshInstance3D.new()
mi.mesh = mesh
mi.material_override = mat
parent.add_child(mi)
var up := (b - a).normalized()
var side := up.cross(Vector3.FORWARD if absf(up.z) < 0.9 else Vector3.RIGHT).normalized()
mi.transform = Transform3D(Basis(side, up, side.cross(up)), (a + b) * 0.5)
return mi
static func _material(color: Color) -> StandardMaterial3D:
var m := StandardMaterial3D.new()
m.albedo_color = color
return m
# --- The farmers -----------------------------------------------------------------------------
## A farmer under parent: a Mannequin_Medium tinted all over with a straw sun hat, under its own
## root (returned); its AnimationPlayer (the player's animations) is anim_of(root).
static func make_farmer(parent: Node, tint: Color) -> Node3D:
var root := Node3D.new()
parent.add_child(root)
var model := (load(FARMER_SCENE) as PackedScene).instantiate() as Node3D
root.add_child(model)
for mi in model.find_children("*", "MeshInstance3D", true, false):
var m := mi as MeshInstance3D
var base := m.get_active_material(0)
if base is BaseMaterial3D:
var tinted := (base as BaseMaterial3D).duplicate() as BaseMaterial3D
tinted.albedo_color = tint
m.material_override = tinted
var straw := _material(STRAW) # a straw sun hat for the trip
for part in [[0.62, 0.05, 2.12], [0.34, 0.26, 2.26]]: # brim, crown: radius, height, y
var mesh := CylinderMesh.new()
mesh.top_radius = part[0]
mesh.bottom_radius = part[0]
mesh.height = part[1]
var hat := MeshInstance3D.new()
hat.mesh = mesh
hat.position = Vector3(0.0, part[2], 0.0)
hat.material_override = straw
model.add_child(hat)
var anim := AnimationPlayer.new()
anim.name = "AnimationPlayer"
root.add_child(anim)
anim.root_node = anim.get_path_to(model)
anim.add_animation_library(&"", load(ANIMATIONS) as AnimationLibrary)
return root
static func anim_of(farmer: Node3D) -> AnimationPlayer:
return farmer.get_node_or_null(^"AnimationPlayer") as AnimationPlayer
## Turns node (about y) to face the point at, if it isn't standing on it.
static func face(node: Node3D, at: Vector3) -> void:
var d := at - node.global_position
if Vector2(d.x, d.z).length_squared() > 1e-6:
node.rotation.y = atan2(d.x, d.z)
# --- Routes ----------------------------------------------------------------------------------
## A smooth route through points (two or more, any order): each inner corner is rounded, its
## handles a quarter of the way toward its neighbours.
static func route_curve(points: Array[Vector3], rounding := 0.25) -> Curve3D:
var curve := Curve3D.new()
for p in points:
curve.add_point(p)
for i in range(1, points.size() - 1):
var t := (points[i + 1] - points[i - 1]) * rounding
curve.set_point_in(i, -t)
curve.set_point_out(i, t)
return curve
## points in the other order (to drive a route backwards).
static func reversed(points: Array[Vector3]) -> Array[Vector3]:
var out := points.duplicate()
out.reverse()
return out
## Puts node distance along curve (clamped to it), level and facing the way the curve runs there
## (its + z ahead).
static func place_on_curve(node: Node3D, curve: Curve3D, distance: float) -> void:
var length := curve.get_baked_length()
var at := curve.sample_baked(distance, true)
var ahead := curve.sample_baked(minf(distance + 1.0, length), true)
var behind := curve.sample_baked(maxf(distance - 1.0, 0.0), true)
var dir := ahead - behind
dir.y = 0.0
if dir.length_squared() > 1e-6:
node.rotation = Vector3(0.0, atan2(dir.x, dir.z), 0.0)
node.global_position = at
# --- The camera and the overlay --------------------------------------------------------------
## A camera under parent, made current (the caller puts the old one back).
static func make_camera(parent: Node, fov := 45.0) -> Camera3D:
var camera := Camera3D.new()
camera.fov = fov
parent.add_child(camera)
camera.make_current()
return camera
## Eases camera toward want, turning it to look at look: 1 - e^(-rate * delta) of the way each
## step. A step of a second or more, or a camera that hasn't moved from the origin yet (just
## made), cuts straight to the shot.
static func move_camera(camera: Camera3D, want: Vector3, look: Vector3, delta: float, rate: float) -> void:
var k := 1.0 - exp(-rate * delta) if delta < 1.0 else 1.0
camera.global_position = camera.global_position.lerp(want, k) if camera.global_position != Vector3.ZERO else want
var target := camera.global_transform.looking_at(look, Vector3.UP)
camera.global_basis = camera.global_basis.slerp(target.basis, k).orthonormalized() if k < 1.0 else target.basis
## Behind and above target, off its left side (+ x), looking a little ahead of it.
static func follow_camera(camera: Camera3D, target: Node3D, delta: float, rate := 2.5) -> void:
var fwd := target.global_basis.z
var want := target.global_position - fwd * 11.0 + Vector3(0.0, 8.0, 0.0) + target.global_basis.x * 3.0
var look := target.global_position + fwd * 4.0 + Vector3(0.0, 1.0, 0.0)
move_camera(camera, want, look, delta, rate)
## Shows or hides the game's HUD layer (cutscenes hide it).
static func set_hud(sim: FarmSim, on: bool) -> void:
if sim.hud != null and sim.hud.get_parent() is CanvasLayer:
(sim.hud.get_parent() as CanvasLayer).visible = on
## The cutscene chrome over the 3D view: black bars at the top and bottom, a caption in the top
## one, and the skip hint at the bottom right.
class Letterbox extends CanvasLayer:
const BAR := 96.0
var bars: Array[ColorRect] = []
var caption: Label
var hint: Label
## A Letterbox under parent with caption and hint (the caller says how to skip).
static func make_letterbox(parent: Node, caption: String, hint: String, layer := 5) -> Letterbox:
var box := Letterbox.new()
box.layer = layer
parent.add_child(box)
for top in [true, false]:
var bar := ColorRect.new()
bar.color = Color.BLACK
bar.mouse_filter = Control.MOUSE_FILTER_IGNORE
box.add_child(bar)
bar.set_anchors_and_offsets_preset(Control.PRESET_TOP_WIDE if top else Control.PRESET_BOTTOM_WIDE)
if top:
bar.offset_bottom = Letterbox.BAR
else:
bar.offset_top = -Letterbox.BAR
box.bars.append(bar)
box.caption = Label.new()
box.caption.text = caption
box.caption.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
box.caption.add_theme_font_size_override("font_size", 38)
box.caption.add_theme_color_override("font_color", Color(0.95, 0.85, 0.55))
box.add_child(box.caption)
box.caption.set_anchors_and_offsets_preset(Control.PRESET_TOP_WIDE)
box.caption.offset_top = 22.0
box.hint = Label.new()
box.hint.text = hint
box.hint.add_theme_font_size_override("font_size", 22)
box.hint.add_theme_color_override("font_color", Color(0.8, 0.8, 0.75))
box.add_child(box.hint)
box.hint.set_anchors_and_offsets_preset(Control.PRESET_BOTTOM_RIGHT)
box.hint.offset_left = -360.0
box.hint.offset_top = -70.0
return box

View file

@ -0,0 +1 @@
uid://b003m7se63ke4

View file

@ -7,13 +7,12 @@ extends Node3D
## camera follows the car, then frames the yard; the HUD hides behind letterbox bars. Fire,
## interact, or Space / Enter / A skips to the end. finished is emitted once it's
## over (or skipped), and EndPanel shows the final assessment over the scene.
## Built when it starts, after the game is over, so nothing is created during play.
## Built when it starts, after the game is over, so nothing is created during play. The car (with
## its roof luggage, which sways on the turns and tips forward as it stops), the farmers, the
## camera moves, and the letterbox come from CutsceneKit, which the opening intro shares.
signal finished
const CAR_SCENE := "res://assets/farm/ithappy/farm/prefabs/assets/transport/car_002.tscn"
const FARMER_SCENE := "res://assets/kaykit_characters/characters/Mannequin_Medium.glb"
const ANIMATIONS := "res://game/resources/player_animations.res"
## The road from the south along the east side, in at GapDriveway, through the farmyard to the
## parking spot east of the house (game/LAYOUT.md); the car faces the way it drives.
const ROUTE: Array[Vector3] = [
@ -30,7 +29,6 @@ const SCARECROW_SPOT := Vector3(24.6, 0.0, -34.0)
const YARD_CAMERA := Vector3(28.0, 10.0, -45.5)
const YARD_LOOK := Vector3(24.8, 0.8, -30.8)
const WALK_SPEED := 2.0
const TINTS: Array[Color] = [Color(0.35, 0.5, 0.85), Color(0.85, 0.45, 0.4)]
## Seconds: honk after parking, farmers out, then waving, cheering, and the end.
const OUT_AT := 0.9
const WAVE_TIME := 2.2
@ -47,13 +45,14 @@ var _car: Node3D
var _engine: AudioStreamPlayer3D
var _curve := Curve3D.new()
var _driven: float = 0.0
var _speed: float = 0.0 # the last step's, for the luggage's sway
var _parked_for: float = 0.0
var _farmers: Array[Node3D] = []
var _anims: Array[AnimationPlayer] = []
var _camera: Camera3D
var _previous_camera: Camera3D
var _stage_left: float = 0.0
var _overlay: CanvasLayer
var _overlay: CutsceneKit.Letterbox
var _caption: Label
@ -76,59 +75,17 @@ func start() -> void:
elapsed = 0.0
stage = "drive"
_driven = 0.0
_speed = DRIVE_SPEED
_parked_for = 0.0
for p in ROUTE:
_curve.add_point(p)
for i in range(1, ROUTE.size() - 1): # round the corners
var t := (ROUTE[i + 1] - ROUTE[i - 1]) * 0.25
_curve.set_point_in(i, -t)
_curve.set_point_out(i, t)
_car = (load(CAR_SCENE) as PackedScene).instantiate() as Node3D
add_child(_car)
for body in _car.find_children("*", "CollisionObject3D", true, false):
(body as CollisionObject3D).collision_layer = 0
_engine = AudioStreamPlayer3D.new()
_engine.bus = &"SFX"
_engine.unit_size = 10.0
_engine.volume_db = -6.0
if sim.audio != null:
_engine.stream = sim.audio.stream_of("truck_engine")
_car.add_child(_engine)
if _engine.stream != null:
_engine.play()
_curve = CutsceneKit.route_curve(ROUTE)
_car = CutsceneKit.make_car(self)
_engine = CutsceneKit.add_engine(_car, sim.audio)
_place_car(0.0)
var library := load(ANIMATIONS) as AnimationLibrary
for i in 2:
var root := Node3D.new()
root.visible = false
add_child(root)
var model := (load(FARMER_SCENE) as PackedScene).instantiate() as Node3D
root.add_child(model)
for mi in model.find_children("*", "MeshInstance3D", true, false):
var m := mi as MeshInstance3D
var base := m.get_active_material(0)
if base is BaseMaterial3D:
var tinted := (base as BaseMaterial3D).duplicate() as BaseMaterial3D
tinted.albedo_color = TINTS[i]
m.material_override = tinted
var straw := StandardMaterial3D.new() # a straw sun hat for the trip
straw.albedo_color = Color(0.92, 0.8, 0.45)
for part in [[0.62, 0.05, 2.12], [0.34, 0.26, 2.26]]: # brim, crown: radius, height, y
var mesh := CylinderMesh.new()
mesh.top_radius = part[0]
mesh.bottom_radius = part[0]
mesh.height = part[1]
var hat := MeshInstance3D.new()
hat.mesh = mesh
hat.position = Vector3(0.0, part[2], 0.0)
hat.material_override = straw
model.add_child(hat)
var anim := AnimationPlayer.new()
root.add_child(anim)
anim.root_node = anim.get_path_to(model)
anim.add_animation_library(&"", library)
_farmers.append(root)
_anims.append(anim)
var farmer := CutsceneKit.make_farmer(self, CutsceneKit.FARMER_TINTS[i])
farmer.visible = false
_farmers.append(farmer)
_anims.append(CutsceneKit.anim_of(farmer))
# The scarecrow waits by the yard (in co-op, both, side by side).
for a in sim.avatars:
var at := SCARECROW_SPOT + Vector3(1.6, 0.0, 0.6) * a.slot
@ -140,14 +97,12 @@ func start() -> void:
a.body.net_yaw = yaw
a.body.start_channel(&"Idle_A")
_previous_camera = get_viewport().get_camera_3d()
_camera = Camera3D.new()
_camera.fov = 45.0
add_child(_camera)
_camera.make_current()
_follow_camera(1.0)
_camera = CutsceneKit.make_camera(self)
CutsceneKit.follow_camera(_camera, _car, 1.0)
if sim.audio != null:
sim.audio.focus = _car
_build_overlay()
_overlay = CutsceneKit.make_letterbox(self, "The farmers are on their way home", "[Space / Enter / A] skip")
_caption = _overlay.caption
_set_hud(false)
@ -158,10 +113,13 @@ func skip() -> void:
_driven = _curve.get_baked_length()
_place_car(_driven)
_stop_engine()
var luggage := CutsceneKit.luggage_of(_car)
if luggage != null:
luggage.settle()
for i in 2:
_farmers[i].visible = true
_farmers[i].global_position = FARMER_SPOTS[i]
_face(_farmers[i], SCARECROW_SPOT)
CutsceneKit.face(_farmers[i], SCARECROW_SPOT)
_anims[i].play(&"Cheering")
_frame_yard(1.0)
_finish()
@ -179,6 +137,7 @@ func clear() -> void:
_engine = null
_camera = null
_overlay = null
_caption = null
_curve = Curve3D.new()
if sim != null:
_set_hud(true)
@ -202,9 +161,15 @@ func step(delta: float) -> void:
var length := _curve.get_baked_length()
var left := length - _driven
var speed := DRIVE_SPEED * clampf(left / 9.0, 0.18, 1.0) # ease into the spot
var was := _driven
var heading := _car.rotation.y
_driven = minf(_driven + speed * delta, length)
_place_car(_driven)
_follow_camera(delta)
if delta > 0.0: # the luggage leans out on the turns and tips forward as the car stops
var moved := (_driven - was) / delta
CutsceneKit.sway_luggage(_car, delta, angle_difference(heading, _car.rotation.y) / delta, (moved - _speed) / delta)
_speed = moved
CutsceneKit.follow_camera(_camera, _car, delta)
if _driven >= length:
_parked_for += delta
if _parked_for >= 0.15 and _engine != null and _engine.playing:
@ -220,6 +185,7 @@ func step(delta: float) -> void:
_anims[i].play(&"Walking_A", 0.1)
"walk":
_frame_yard(delta)
CutsceneKit.sway_luggage(_car, delta, 0.0, 0.0)
var arrived := 0
for i in 2:
var f := _farmers[i]
@ -229,12 +195,12 @@ func step(delta: float) -> void:
arrived += 1
continue
f.global_position += to.limit_length(WALK_SPEED * delta)
_face(f, f.global_position + to)
CutsceneKit.face(f, f.global_position + to)
if arrived == 2:
stage = "wave"
_stage_left = WAVE_TIME
for i in 2:
_face(_farmers[i], SCARECROW_SPOT)
CutsceneKit.face(_farmers[i], SCARECROW_SPOT)
_anims[i].play(&"Waving", 0.15)
if sim.audio != null:
sim.audio.play("victory")
@ -242,6 +208,7 @@ func step(delta: float) -> void:
_caption.text = "The farmers are home!"
"wave", "cheer":
_frame_yard(delta)
CutsceneKit.sway_luggage(_car, delta, 0.0, 0.0)
_stage_left -= delta
if _stage_left <= 0.0:
if stage == "wave":
@ -263,46 +230,16 @@ func _finish() -> void:
func _set_hud(on: bool) -> void:
if sim.hud != null and sim.hud.get_parent() is CanvasLayer:
(sim.hud.get_parent() as CanvasLayer).visible = on
CutsceneKit.set_hud(sim, on)
func _place_car(distance: float) -> void:
var length := _curve.get_baked_length()
var at := _curve.sample_baked(distance, true)
var ahead := _curve.sample_baked(minf(distance + 1.0, length), true)
var behind := _curve.sample_baked(maxf(distance - 1.0, 0.0), true)
var dir := ahead - behind
dir.y = 0.0
if dir.length_squared() > 1e-6:
_car.rotation = Vector3(0.0, atan2(dir.x, dir.z), 0.0)
_car.global_position = Vector3(at.x, 0.0, at.z)
## Behind and above the car, looking a little ahead of it.
func _follow_camera(delta: float) -> void:
var fwd := _car.global_basis.z
var want := _car.global_position - fwd * 11.0 + Vector3(0.0, 8.0, 0.0) + _car.global_basis.x * 3.0
var look := _car.global_position + fwd * 4.0 + Vector3(0.0, 1.0, 0.0)
_move_camera(want, look, delta, 2.5)
CutsceneKit.place_on_curve(_car, _curve, distance)
## A wide shot of the yard from the north-east: the car, the porch, and the scarecrow.
func _frame_yard(delta: float) -> void:
_move_camera(YARD_CAMERA, YARD_LOOK, delta, 1.2)
func _move_camera(want: Vector3, look: Vector3, delta: float, rate: float) -> void:
var k := 1.0 - exp(-rate * delta) if delta < 1.0 else 1.0
_camera.global_position = _camera.global_position.lerp(want, k) if _camera.global_position != Vector3.ZERO else want
var target := _camera.global_transform.looking_at(look, Vector3.UP)
_camera.global_basis = _camera.global_basis.slerp(target.basis, k).orthonormalized() if k < 1.0 else target.basis
func _face(node: Node3D, at: Vector3) -> void:
var d := at - node.global_position
if Vector2(d.x, d.z).length_squared() > 1e-6:
node.rotation.y = atan2(d.x, d.z)
CutsceneKit.move_camera(_camera, YARD_CAMERA, YARD_LOOK, delta, 1.2)
func _stop_engine() -> void:
@ -310,38 +247,6 @@ func _stop_engine() -> void:
_engine.stop()
func _build_overlay() -> void:
_overlay = CanvasLayer.new()
_overlay.layer = 5
add_child(_overlay)
for top in [true, false]:
var bar := ColorRect.new()
bar.color = Color.BLACK
bar.mouse_filter = Control.MOUSE_FILTER_IGNORE
_overlay.add_child(bar)
bar.set_anchors_and_offsets_preset(Control.PRESET_TOP_WIDE if top else Control.PRESET_BOTTOM_WIDE)
if top:
bar.offset_bottom = 96.0
else:
bar.offset_top = -96.0
_caption = Label.new()
_caption.text = "The farmers are on their way home"
_caption.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
_caption.add_theme_font_size_override("font_size", 38)
_caption.add_theme_color_override("font_color", Color(0.95, 0.85, 0.55))
_overlay.add_child(_caption)
_caption.set_anchors_and_offsets_preset(Control.PRESET_TOP_WIDE)
_caption.offset_top = 22.0
var hint := Label.new()
hint.text = "[Space / Enter / A] skip"
hint.add_theme_font_size_override("font_size", 22)
hint.add_theme_color_override("font_color", Color(0.8, 0.8, 0.75))
_overlay.add_child(hint)
hint.set_anchors_and_offsets_preset(Control.PRESET_BOTTOM_RIGHT)
hint.offset_left = -360.0
hint.offset_top = -70.0
func _unhandled_input(event: InputEvent) -> void:
if not running or done:
return