Grass Cutters Together: the project as of moon-sweepers f3666f0

A clean start for the shared repository: the Unity project (Assets, Packages, ProjectSettings), ArtSource, Docs and
Tools as they stood at f3666f0 in the old local repository, with its generated prefabs and scene brought up to date.
Images, audio, models and binaries go through Git LFS (.gitattributes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NiemandKG
2026-11-06 18:44:40 +06:00
parent 0f0467cd0c
commit d1c3761e58
4190 changed files with 270757 additions and 1 deletions

413
Tools/Trailer/cut.py Normal file
View File

@ -0,0 +1,413 @@
"""
The edit. Everything is placed in TRACK time (seconds of the original song), so the shot list can be read against the words;
`KEEP` says which stretches of the song survive and the rest follows.
py -I cut.py edl.py out.mp4 [from to] renders the whole film, or a stretch of it in track time
An edl may also set SIZE (w, h) for an upright film, TRACK for another song, and PUNCH, SHAKE and ABERRATE for how hard
the picture answers the kick.
"""
import importlib.util
import math
import os
import random
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
W, H, FPS = 1920, 1080, 60
SR = 48000
PROJECT = r"D:\PROJECTS\LOCAL\GrassCutter"
TRACK = os.path.join(PROJECT, r"ArtSource\Trailer\mowin.mp3")
FONT = os.path.join(PROJECT, r"Assets\Fonts\LilitaOne-Regular.ttf")
# ───────────────────────── time ─────────────────────────
class Clock:
"""Output seconds <-> track seconds, across the splices."""
def __init__(self, keep):
self.keep = keep
self.total = sum(b - a for a, b in keep)
def track(self, t):
for a, b in self.keep:
if t < b - a:
return a + t
t -= b - a
return self.keep[-1][1]
def out(self, t):
done = 0.0
for a, b in self.keep:
if t < a:
return done
if t <= b:
return done + t - a
done += b - a
return done
# ───────────────────────── sound ─────────────────────────
def decode(path):
p = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", "2", "-ar", str(SR), "-"], capture_output=True, check=True)
return np.frombuffer(p.stdout, np.float32).reshape(-1, 2).copy()
def mix(song, clock, sfx, out_wav):
n = int(clock.total * SR)
bus = np.zeros((n + SR * 2, 2), np.float32)
fade = int(0.012 * SR)
at = 0
for a, b in clock.keep:
piece = song[int(a * SR):int(b * SR)].copy()
piece[:fade] *= np.linspace(0, 1, fade)[:, None]
piece[-fade:] *= np.linspace(1, 0, fade)[:, None]
bus[at:at + len(piece)] += piece
at += len(piece)
cache = {}
for item in sfx:
# (track time, clip, gain) plays the clip through; a fourth number cuts it, or loops it, to that many seconds; a fifth
# starts it that many seconds in (a line of dialogue out of a longer recording)
t, path, gain = item[:3]
clip = cache.setdefault(path, decode(path))
if len(item) > 4 and item[4]:
clip = clip[int(item[4] * SR):]
if len(item) > 3 and item[3]:
want = int(item[3] * SR)
clip = np.tile(clip, (want // len(clip) + 1, 1))[:want].copy()
ramp = min(int(0.15 * SR), want // 3)
clip[:ramp] *= np.linspace(0, 1, ramp)[:, None]
clip[-ramp:] *= np.linspace(1, 0, ramp)[:, None]
i = int(clock.out(t) * SR)
m = min(len(clip), len(bus) - i)
if m > 0:
bus[i:i + m] += clip[:m] * gain
bus = bus[:n]
tail = int(1.6 * SR)
bus[-tail:] *= np.linspace(1, 0, tail)[:, None] ** 1.5
peak = np.abs(bus).max()
if peak > 0.98:
bus *= 0.98 / peak
raw = (bus * 32767).astype(np.int16)
import wave
with wave.open(out_wav, "wb") as f:
f.setnchannels(2)
f.setsampwidth(2)
f.setframerate(SR)
f.writeframes(raw.tobytes())
def pulse(song):
"""The kick: how hard the low end hits at each track second * FPS, 0..1, decaying."""
mono = song.mean(axis=1)
hop = SR // FPS
frames = len(mono) // hop
# a low band by way of a long running mean
low = cv2.blur(mono.reshape(-1, 1), (1, 481)).ravel()
energy = np.sqrt(np.add.reduce((low[:frames * hop] ** 2).reshape(frames, hop), axis=1) / hop)
rise = np.maximum(0.0, np.diff(energy, prepend=0.0))
rise /= np.percentile(rise, 99.5) + 1e-6
out = np.zeros(frames, np.float32)
v = 0.0
for i in range(frames):
v = max(v * 0.86, min(1.0, float(rise[i])))
out[i] = v
return out
# ───────────────────────── pictures ─────────────────────────
class Roll:
"""A folder of numbered frames."""
def __init__(self, folder):
self.files = sorted(f for f in os.listdir(folder) if f.endswith(".jpg"))
self.folder = folder
if not self.files:
raise SystemExit("empty take: " + folder)
def __len__(self):
return len(self.files)
def read(self, i):
i = max(0, min(len(self.files) - 1, int(i)))
return cv2.imread(os.path.join(self.folder, self.files[i]), cv2.IMREAD_COLOR)
class Shot:
def __init__(self, take, at, end, start=0.0, speed=1.0, rate=60, zoom=(1.0, 1.0), pan=(0.0, 0.0), ramp=None, grade=None, into=None, flip=False):
self.take, self.at, self.end, self.start, self.speed, self.rate = take, at, end, start, speed, rate
self.zoom, self.pan, self.ramp, self.grade, self.into, self.flip = zoom, pan, ramp, grade, into, flip
self.after = None
def source(self, k, seconds):
"""Seconds into the take at k (0..1) of the shot. A ramp is [(k, speed), ...]."""
if not self.ramp:
return self.start + k * seconds * self.speed
pts = self.ramp
pos, last_k, last_v = 0.0, pts[0][0], pts[0][1]
for pk, pv in pts[1:]:
if k <= pk:
v = last_v + (pv - last_v) * (k - last_k) / max(1e-6, pk - last_k)
return self.start + (pos + (k - last_k) * (last_v + v) * 0.5) * seconds
pos += (pk - last_k) * (last_v + pv) * 0.5
last_k, last_v = pk, pv
return self.start + (pos + (k - last_k) * last_v) * seconds
def vignette():
y, x = np.mgrid[0:H, 0:W].astype(np.float32)
r = np.sqrt(((x - W / 2) / (W / 2)) ** 2 + ((y - H / 2) / (H / 2)) ** 2)
return (1.0 - 0.22 * np.clip((r - 0.7) / 0.8, 0, 1) ** 2)[..., None]
def setup(w, h):
"""The frame size, and what is made to it."""
global W, H, GRAIN, VIG
W, H = w, h
GRAIN = np.random.default_rng(7).normal(0, 1, (H + 128, W + 128, 1)).astype(np.float32)
VIG = vignette()
setup(W, H)
def fit(img, z, dx, dy, roll=0.0):
h, w = img.shape[:2]
# the take covers the frame: an upright film keeps the middle of a wide take
s = max(W / w, H / h) * z
c, si = math.cos(math.radians(roll)) * s, math.sin(math.radians(roll)) * s
m = np.float32([[c, si, W / 2 - c * w / 2 - si * h / 2 + dx], [-si, c, H / 2 + si * w / 2 - c * h / 2 + dy]])
return cv2.warpAffine(img, m, (W, H), flags=cv2.INTER_AREA if s < 1 else cv2.INTER_CUBIC, borderMode=cv2.BORDER_REFLECT)
def aberrate(img, amount):
"""Colour fringes that grow towards the edges."""
if amount < 0.25:
return img
b, g, r = cv2.split(img)
def scaled(ch, k):
s = 1 + k / W
m = np.float32([[s, 0, W / 2 * (1 - s)], [0, s, H / 2 * (1 - s)]])
return cv2.warpAffine(ch, m, (W, H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)
return cv2.merge((scaled(b, amount * 2), g, scaled(r, -amount * 2)))
def bloom(img, amount):
small = cv2.resize(img, (W // 4, H // 4), interpolation=cv2.INTER_AREA).astype(np.float32) / 255
hot = np.clip(small - 0.8, 0, 1) * 2.4
hot = cv2.GaussianBlur(hot, (0, 0), 14)
return img.astype(np.float32) / 255 + cv2.resize(hot, (W, H), interpolation=cv2.INTER_LINEAR) * amount
def finish(f, grade, grain_at):
"""f is float BGR 0..1 and may run over."""
g = grade or {}
f = f * g.get("gain", 1.0)
# filmic shoulder, a touch more contrast, teal shadows and warm lights
f = f / (1 + np.maximum(f - 0.8, 0) * 1.1)
lum = (f * [0.114, 0.587, 0.299]).sum(axis=2, keepdims=True)
f = lum + (f - lum) * g.get("sat", 1.14)
c = g.get("contrast", 1.1)
f = np.clip(f, 0, 1.4)
f = 0.5 + (f - 0.5) * c
tint = g.get("tint", (0.018, 0.0, -0.014))
f = f + (1 - np.clip(lum * 1.6, 0, 1)) * tint - np.clip(lum * 1.6 - 0.6, 0, 1) * tint
f = f * VIG
ox, oy = grain_at
f = f + GRAIN[oy:oy + H, ox:ox + W] * 0.012
return (np.clip(f, 0, 1) * 255 + 0.5).astype(np.uint8)
# ───────────────────────── type ─────────────────────────
class Type:
def __init__(self, text, at, end, size=150, x=0.5, y=0.5, how="slam", colour=(255, 255, 255), edge=(22, 58, 24)):
self.text, self.at, self.end, self.size, self.x, self.y, self.how = text, at, end, size, x, y, how
font = ImageFont.truetype(FONT, size)
pad = size // 3
box = font.getbbox(text, stroke_width=size // 14)
w, h = box[2] - box[0] + pad * 2, box[3] - box[1] + pad * 2
im = Image.new("RGBA", (w, h), (0, 0, 0, 0))
d = ImageDraw.Draw(im)
shadow = Image.new("RGBA", (w, h), (0, 0, 0, 0))
ImageDraw.Draw(shadow).text((pad - box[0], pad - box[1] + size // 18), text, font=font, fill=(0, 0, 0, 170), stroke_width=size // 14, stroke_fill=(0, 0, 0, 170))
im.alpha_composite(shadow)
d.text((pad - box[0], pad - box[1]), text, font=font, fill=colour + (255,), stroke_width=size // 14, stroke_fill=edge + (255,))
a = np.asarray(im, np.float32)
a[..., 3] /= 255
self.rgba = a[..., [2, 1, 0, 3]]
def draw(self, f, t, jolt):
life = t - self.at
left = self.end - t
k = min(1.0, life / (0.1 if self.how == "slam" else 0.28))
ease = 1 - (1 - k) ** 3
if self.how == "slam":
scale, alpha = 1.55 - 0.55 * ease, min(1.0, life / 0.03)
elif self.how == "rise":
scale, alpha = 1.0 + 0.04 * life, ease
else:
scale, alpha = 1.0, ease
alpha *= min(1.0, left / 0.08)
if alpha <= 0:
return f
h, w = self.rgba.shape[:2]
nw, nh = max(2, int(w * scale)), max(2, int(h * scale))
lay = cv2.resize(self.rgba, (nw, nh), interpolation=cv2.INTER_AREA if scale < 1 else cv2.INTER_LINEAR)
cx = int(self.x * W + random.uniform(-1, 1) * jolt * 6)
cy = int(self.y * H + random.uniform(-1, 1) * jolt * 6 + (0 if self.how != "rise" else (1 - ease) * 24))
x0, y0 = cx - nw // 2, cy - nh // 2
ax0, ay0, ax1, ay1 = max(0, x0), max(0, y0), min(W, x0 + nw), min(H, y0 + nh)
if ax0 >= ax1 or ay0 >= ay1:
return f
part = lay[ay0 - y0:ay1 - y0, ax0 - x0:ax1 - x0]
a = part[..., 3:] * alpha
f[ay0:ay1, ax0:ax1] = f[ay0:ay1, ax0:ax1] * (1 - a) + part[..., :3] * a
return f
class Logo:
def __init__(self, path, at, end, width=1100, y=0.42):
im = cv2.imread(path, cv2.IMREAD_UNCHANGED).astype(np.float32)
im[..., 3] /= 255
s = width / im.shape[1]
self.rgba = cv2.resize(im, (width, int(im.shape[0] * s)), interpolation=cv2.INTER_AREA)
self.at, self.end, self.y = at, end, y
def draw(self, f, t, jolt):
k = min(1.0, (t - self.at) / 0.14)
ease = 1 - (1 - k) ** 3
scale = 1.5 - 0.5 * ease
h, w = self.rgba.shape[:2]
nw, nh = int(w * scale), int(h * scale)
lay = cv2.resize(self.rgba, (nw, nh), interpolation=cv2.INTER_AREA)
x0, y0 = W // 2 - nw // 2, int(self.y * H) - nh // 2
cut = lay[max(0, -y0):, max(0, -x0):]
x0, y0 = max(0, x0), max(0, y0)
cut = cut[:H - y0, :W - x0]
a = cut[..., 3:] * min(1.0, (t - self.at) / 0.04)
hh, ww = cut.shape[:2]
f[y0:y0 + hh, x0:x0 + ww] = f[y0:y0 + hh, x0:x0 + ww] * (1 - a) + cut[..., :3] * a
return f
# ───────────────────────── the render ─────────────────────────
def render(edl, out, span=None):
clock = Clock(edl.KEEP)
song = decode(getattr(edl, "TRACK", TRACK)) * getattr(edl, "TRACK_GAIN", 1.0)
kick = pulse(song)
shots = sorted(edl.SHOTS, key=lambda s: s.at)
for a, b in zip(shots, shots[1:]):
b.after = a.into
rolls = {}
for s in shots:
rolls.setdefault(s.take, Roll(os.path.join(edl.ROLLS, s.take)))
wav = out + ".wav"
mix(song, clock, getattr(edl, "SFX", []), wav)
first, last = 0, int(clock.total * FPS)
if span:
first, last = int(clock.out(span[0]) * FPS), int(clock.out(span[1]) * FPS)
cmd = ["ffmpeg", "-y", "-v", "error", "-f", "rawvideo", "-pix_fmt", "bgr24", "-s", f"{W}x{H}", "-r", str(FPS), "-i", "-",
"-ss", f"{first / FPS:.3f}", "-t", f"{(last - first) / FPS:.3f}", "-i", wav,
"-map", "0:v", "-map", "1:a", "-c:v", "h264_nvenc", "-preset", "p6", "-rc", "vbr", "-cq", "20", "-b:v", "16M", "-maxrate", "30M",
"-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "320k", "-shortest", out]
pipe = subprocess.Popen(cmd, stdin=subprocess.PIPE)
hits = getattr(edl, "FLASH", [])
types = getattr(edl, "TYPE", [])
pool = ThreadPoolExecutor(6)
rng = random.Random(3)
idx = 0
def active(tt):
for s in reversed(shots):
if s.at <= tt < s.end:
return s
return None
def frame_of(s, tt):
len_track = clock.out(s.end) - clock.out(s.at)
k = (clock.out(tt) - clock.out(s.at)) / max(1e-6, len_track)
src = s.source(k, len_track)
i = src * s.rate
step = abs(s.speed if not s.ramp else max(v for _, v in s.ramp)) * s.rate / FPS
roll = rolls[s.take]
if step > 1.5:
n = min(5, int(step))
parts = list(pool.map(lambda j: roll.read(i + j * step / n).astype(np.float32), range(n)))
img = (sum(parts) / n).astype(np.uint8)
else:
img = roll.read(i)
z = s.zoom[0] + (s.zoom[1] - s.zoom[0]) * k
px, py = s.pan if isinstance(s.pan[0], (int, float)) else (s.pan[0][0] + (s.pan[1][0] - s.pan[0][0]) * k, s.pan[0][1] + (s.pan[1][1] - s.pan[0][1]) * k)
if s.flip:
img = img[:, ::-1]
return img, z, px, py, k
for n in range(first, last):
t = n / FPS
tt = clock.track(t)
s = active(tt)
if s is None:
pipe.stdin.write(np.zeros((H, W, 3), np.uint8).tobytes())
continue
kick_v = float(kick[min(len(kick) - 1, int(tt * FPS))]) * getattr(edl, "REACT", lambda x: 1.0)(tt)
img, z, px, py, k = frame_of(s, tt)
z *= 1 + getattr(edl, "PUNCH", 0.028) * kick_v
shake = getattr(edl, "SHAKE", 9) * kick_v ** 2
dx = px + rng.uniform(-shake, shake)
dy = py + rng.uniform(-shake, shake)
pic = fit(img, z, dx, dy)
# whip: the tail of a shot smears out and the head of the next smears in, sideways, off the beat grid's hit
gap_out = clock.out(s.end) - t
gap_in = t - clock.out(s.at)
for how, left, way in ((s.into, gap_out, 1), (s.after, gap_in, -1)):
if how == "whip" and left < 0.1:
p = 1 - left / 0.1
ks = int(4 + p * p * 240) | 1
pic = cv2.blur(np.roll(pic, int(p * p * 460) * way, axis=1), (ks, 1))
pic = aberrate(pic, getattr(edl, "ABERRATE", 3.2) * kick_v)
f = bloom(pic, 0.5 + 0.35 * kick_v)
flash = 0.0
for at, power in hits:
d = t - clock.out(at)
if 0 <= d < 0.22:
flash = max(flash, power * (1 - d / 0.22) ** 2)
if flash:
f = f + flash
o = finish(f, s.grade, (rng.randrange(128), rng.randrange(128))).astype(np.float32)
fade = getattr(edl, "BLACK", lambda x: 0.0)(tt)
if fade:
o *= 1 - fade
for ty in types:
if ty.at <= tt < ty.end:
o = ty.draw(o, tt, kick_v)
pipe.stdin.write(np.clip(o, 0, 255).astype(np.uint8).tobytes())
idx += 1
if idx % 300 == 0:
print(f"{idx}/{last - first}", flush=True)
pipe.stdin.close()
pipe.wait()
os.remove(wav)
if __name__ == "__main__":
# the cuts share looks.py and vertical.py from here, and -I leaves this folder off the path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
spec = importlib.util.spec_from_file_location("edl", sys.argv[1])
edl = importlib.util.module_from_spec(spec)
sys.modules["edl"] = edl
sys.modules["cut"] = sys.modules["__main__"]
spec.loader.exec_module(edl)
setup(*getattr(edl, "SIZE", (1920, 1080)))
render(edl, sys.argv[2], (float(sys.argv[3]), float(sys.argv[4])) if len(sys.argv) > 4 else None)

174
Tools/Trailer/edl.py Normal file
View File

@ -0,0 +1,174 @@
"""The trailer. Times are seconds of the song. The song still leads, but the picture is the game, not a dance: the crew
work out of step, the kick only nudges the frame, and first-person takes show what playing it is like. The bridge is
left out of the song: the last chorus comes straight after the second verse."""
from cut import Logo, Shot, Type
import os
from cut import PROJECT
from looks import BAR, BARE, BEAT, DUSK, GOLD, HOT, LOGO, NIGHT, PLAY, clip, runner # noqa: F401
# shot again on the build of 5 November: the new crew, the deck, the house, drones, belts, vending machines, weather
ROLLS = os.path.join(PROJECT, "Builds", "Trailer", "rolls_1105")
KEEP = [(2.2, 60.58), (75.1, 97.77), (116.1, 170.0)]
PUNCH, SHAKE, ABERRATE = 0.012, 3.5, 1.4
S = Shot
SHOTS = []
run = runner(SHOTS)
# ───────────────────────── cold open ─────────────────────────
run(2.2,
(5.8, "o_space_k", {"speed": 1.5, "zoom": (1.0, 1.04), "grade": {"sat": 1.1, "contrast": 1.06, "tint": (0, 0, 0)}}),
(5.4, "o_dive", {"speed": 0.84, "grade": GOLD, "into": "whip"}),
(1.93, "o_skim", {"start": 2.2, "speed": 1.35, "grade": GOLD, "into": "whip"}),
(BEAT * 4, "o_giant", {"start": 0.6, "speed": 0.7, "grade": GOLD}),
)
# the crew, one by one
t = 15.33 + BEAT * 4
for i in range(8):
SHOTS.append(S(f"p_{i}", t, t + BEAT, start=0.8, speed=1.0, zoom=(1.0, 1.03), grade=HOT))
t += BEAT
run(t,
(BEAT * 2, "c_swing", {"start": 0.5, "grade": HOT}),
(0, "m_blade", {"rate": 120, "start": 0.4, "speed": 0.5, "grade": GOLD}),
until=22.9)
# ───────────────────────── chorus: what you do here ─────────────────────────
run(22.9,
(2.1, "c_swing_s", {"rate": 120, "start": 1.2, "speed": 0.5, "grade": HOT}),
(BAR, "g_scythe", {"start": 1.0, "grade": PLAY}),
(BAR, "c_rider_side", {"start": 0.2, "grade": HOT, "zoom": (1.0, 1.04)}),
(BAR, "c_combine_over", {"start": 1.34, "grade": HOT}),
(BAR, "v_sixteen", {"start": 1.2, "grade": HOT}),
(BAR, "c_top", {"start": 1.2, "grade": HOT}),
(BAR, "c_tractor", {"start": 1.3, "grade": HOT}),
(0, "c_rider", {"start": 0.2, "grade": HOT}),
until=38.23)
# ───────────────────────── verse one: from nail scissors up ─────────────────────────
run(38.23,
(1.6, "v_around", {"start": 0.2, "speed": 1.6, "grade": HOT}),
(1.5, "g_scissors", {"start": 1.0, "grade": PLAY}),
(0.9, "v_scissors", {"start": 0.6, "grade": HOT}),
(1.0, "g_shears", {"start": 1.0, "grade": PLAY}),
(0.8, "v_snip", {"start": 0.6, "grade": HOT}),
(1.0, "g_sickle", {"start": 1.0, "grade": PLAY}),
(1.5, "v_knees", {"start": 0.2, "speed": 0.9, "grade": HOT}),
(1.6, "g_wide", {"start": 1.2, "grade": PLAY}),
(1.6, "v_strip", {"rate": 30, "start": 1.6, "speed": 3.0, "grade": HOT, "zoom": (1.2, 1.3), "pan": (70.0, 0.0)}),
(1.6, "g_deposit", {"start": 1.0, "grade": PLAY}),
(1.4, "v_sunset", {"rate": 30, "start": 0.0, "speed": 1.5, "grade": DUSK}),
(1.3, "n_line", {"start": 0.8, "grade": NIGHT}),
(1.3, "n_tractor", {"start": 0.8, "grade": NIGHT}),
(1.7, "v_phone", {"start": 0.3, "grade": HOT}),
(1.5, "v_sixteen_end", {"start": 0.6, "grade": HOT}),
(1.2, "v_rhythm", {"start": 0.3, "grade": HOT}),
(0, "g_coop", {"start": 1.0, "grade": PLAY}),
until=60.58)
# ───────────────────────── verse two: machines and a factory ─────────────────────────
run(75.1,
(1.4, "w_wheels", {"start": 1.0, "speed": 0.8, "grade": HOT}),
(1.4, "g_ride", {"start": 1.5, "grade": PLAY}),
(1.2, "w_trucks", {"start": 2.3, "grade": HOT}),
(1.4, "g_combine", {"start": 2.0, "grade": PLAY}),
(1.2, "b_header", {"rate": 120, "start": 0.6, "speed": 0.5, "grade": HOT}),
(1.6, "y_house", {"start": 0.8, "grade": GOLD}),
(1.6, "k_grow", {"start": 3.0, "speed": 1.4, "grade": HOT}),
(0.9, "k_hammer", {"start": 0.6, "grade": HOT}),
(1.5, "y_belts", {"start": 0.6, "grade": HOT}),
(1.6, "y_drones", {"start": 0.4, "grade": GOLD}),
(1.6, "k_robots", {"start": 1.6, "grade": HOT}),
(1.4, "y_vending", {"start": 0.6, "grade": DUSK}),
(1.5, "y_fp_beer", {"start": 3.0, "grade": PLAY}),
(1.2, "c_combine_top", {"start": 0.8, "grade": HOT}),
(1.2, "b_line", {"rate": 120, "start": 1.0, "speed": 0.5, "grade": HOT}),
(1.4, "w_three", {"start": 0.3, "grade": GOLD}),
(0, "n_air", {"start": 0.3, "grade": NIGHT}),
until=97.77)
# ───────────────────────── last chorus: everyone, everything ─────────────────────────
run(116.1,
(BAR, "f_hero", {"start": 0.4, "grade": HOT, "zoom": (1.0, 1.04)}),
(BAR, "f_in", {"start": 0.0, "grade": HOT}),
(BAR, "f_air", {"start": 0.6, "grade": HOT}),
(BAR, "y_twister", {"start": 1.2, "grade": HOT}),
(BAR, "b_grass", {"rate": 120, "start": 0.2, "speed": 0.5, "grade": GOLD}),
(BAR, "y_ufo", {"start": 0.4, "grade": DUSK}),
(BAR, "c_line", {"start": 1.2, "grade": HOT}),
(0, "f_in", {"start": 1.6, "grade": HOT}),
until=131.03)
run(131.03,
(9.0, "e_cut_k", {"speed": 1.0, "zoom": (1.0, 1.05), "grade": {"sat": 1.1, "contrast": 1.08, "tint": (0, 0, 0)}}),
(BAR, "f_hero", {"start": 2.0, "grade": HOT}),
(BAR, "y_acid", {"start": 0.4, "grade": HOT}),
(2.0, "f_in", {"start": 0.9, "speed": 0.9, "grade": HOT}),
(0, "f_air", {"start": 0.2, "speed": 0.9, "grade": HOT, "zoom": (1.0, 1.06)}),
until=147.72)
# ───────────────────────── nothing left ─────────────────────────
run(147.72,
(2.6, "e_bare", {"start": 1.0, "speed": 0.9, "grade": BARE}),
(5.0, "e_crew", {"speed": 0.85, "grade": BARE}),
(2.4, "e_look", {"start": 0.3, "speed": 0.7, "grade": BARE}),
(0, "e_up", {"speed": 0.48, "zoom": (1.0, 1.08), "grade": dict(BARE, sat=1.2)}),
until=170.0)
FLASH = [(22.9, 0.5), (75.1, 0.3), (116.1, 0.6), (159.0, 0.7)]
def REACT(t):
if t < 22.9:
return 0.25
if t < 38.2:
return 0.6
if t < 97.8:
return 0.35
if t < 147.7:
return 0.7
if t < 159:
return 0.0
return 0.4
def BLACK(t):
if t < 2.7:
return 1 - (t - 2.2) / 0.5
if t > 168.6:
return min(1.0, (t - 168.6) / 1.2)
return 0.0
TYPE = [
Type("HERBARIA-7", 5.75, 8.0, 150, y=0.5, how="rise"),
Type("EARTH HAS RUN OUT OF GRASS", 8.5, 10.9, 84, y=0.2, how="rise"),
Type("THIS PLANET HAS TOO MUCH", 11.1, 13.35, 84, y=0.2, how="rise"),
Type("MOW IT!", 23.0, 24.95, 210, y=0.74, how="slam"),
Type("ALL OF IT", 28.74, 30.5, 170, how="slam"),
Type("TOGETHER", 30.6, 32.4, 170, y=0.78, how="slam"),
Type("THE WHOLE PLANET", 36.3, 38.2, 150, how="slam"),
Type("START SMALL", 39.85, 42.3, 120, y=0.82, how="rise"),
Type("GROW BIGGER", 44.5, 47.0, 120, y=0.82, how="rise"),
Type("UP TO 16 PLAYERS", 57.05, 58.5, 120, y=0.82, how="slam"),
Type("DRIVE IT", 75.2, 77.9, 150, y=0.8, how="slam"),
Type("BUILD IT", 81.7, 83.3, 150, y=0.8, how="slam"),
Type("AUTOMATE IT", 85.8, 88.9, 150, y=0.8, how="slam"),
Type("MOW IT!", 116.1, 118.0, 240, how="slam"),
Type("TAKE THE WHOLE PLANET", 129.0, 131.0, 130, how="slam"),
Type("ZERO GRASS REMAINING", 150.6, 154.8, 92, y=0.22, how="rise"),
Type("WAIT...", 155.6, 157.9, 92, y=0.78, how="rise"),
Type("WISHLIST NOW ON STEAM", 161.0, 170.0, 76, y=0.76, how="rise"),
Type("CO-OP FOR 1 TO 16 PLAYERS", 162.0, 170.0, 50, y=0.85, how="rise", colour=(226, 240, 200)),
Logo(LOGO, 159.0, 170.0, 1180, 0.4),
]
_names = ["HANK", "OTIS", "LIN", "RUSTAM", "MARCUS", "GUS", "WADE", "KENJI"]
for i, n in enumerate(_names):
TYPE.append(Type(n, 15.33 + BEAT * (4 + i), 15.33 + BEAT * (5 + i), 96, x=0.2, y=0.84, how="slam"))
SFX = [(40.0, clip("snip"), 0.5), (41.5, clip("shears_snip_1"), 0.7), (42.6, clip("shears_snip_2"), 0.7)]
SFX += [(22.9, clip("scythe_swing_1"), 0.5), (116.1, clip("scythe_swing_2"), 0.5)]
SFX += [(50.75, clip("cash_register"), 0.6)]
SFX += [(82.5, clip("build_place"), 0.7)]
SFX += [(159.0, clip("confetti"), 0.7)]

125
Tools/Trailer/gameplay.py Normal file
View File

@ -0,0 +1,125 @@
"""The gameplay trailer: the game's own music, and the game shown as it plays, most of it through the player's eyes with the
HUD. Times are seconds of music_game_loop.wav, which beats at 79.5 a minute; every shot is a whole number of beats."""
import os
from cut import Logo, Type
from looks import AUDIO, GOLD, HOT, LOGO, NIGHT, PLAY, ROLLS, SPACE, clip, runner # noqa: F401
TRACK = os.path.join(AUDIO, "music_game_loop.wav")
TRACK_GAIN = 0.75
B = 60 / 79.5
KEEP = [(0.0, 103.5)]
PUNCH, SHAKE, ABERRATE = 0.006, 1.5, 0.8
SHOTS = []
run = runner(SHOTS)
run(0.0,
(B * 6, "o_space_k", {"speed": 1.2, "zoom": (1.0, 1.04), "grade": SPACE}),
(B * 4, "o_skim", {"start": 1.0, "speed": 1.2, "grade": GOLD}),
# the tools, one after another
(B * 5, "g_scissors", {"start": 0.1, "grade": PLAY}),
(B * 3, "g_shears", {"start": 0.8, "grade": PLAY}),
(B * 3, "g_sickle", {"start": 0.8, "grade": PLAY}),
(B * 4, "g_scythe", {"start": 1.2, "grade": PLAY}),
(B * 5, "g_deposit", {"start": 0.1, "grade": PLAY}),
(B * 4, "g_supply", {"start": 0.0, "grade": PLAY}),
(B * 4, "g_shop", {"start": 0.4, "grade": PLAY}),
(B * 4, "g_wide", {"start": 1.5, "grade": PLAY}),
# together
(B * 5, "g_coop", {"start": 1.5, "grade": PLAY}),
(B * 4, "v_sixteen", {"start": 0.9, "grade": HOT}),
(B * 3, "c_line", {"start": 1.2, "grade": HOT}),
# the factory
(B * 6, "g_build", {"start": 0.3, "grade": PLAY}),
(B * 4, "k_grow", {"start": 2.5, "grade": HOT}),
(B * 4, "k_belt", {"start": 0.3, "grade": HOT}),
(B * 4, "k_robots", {"start": 0.4, "grade": HOT}),
# the machines
(B * 5, "g_ride", {"start": 1.5, "grade": PLAY}),
(B * 4, "g_combine", {"start": 2.0, "grade": PLAY}),
(B * 3, "c_tractor", {"start": 1.2, "grade": HOT}),
(B * 3, "w_trucks", {"start": 1.6, "grade": HOT}),
# night, the planet, the crew
(B * 4, "n_line", {"start": 0.8, "grade": NIGHT}),
(B * 3, "n_tractor", {"start": 0.7, "grade": NIGHT}),
(B * 4, "g_map", {"start": 0.0, "grade": PLAY}),
(B * 4, "c_ring", {"start": 0.8, "grade": GOLD}),
(B * 4, "g_character", {"start": 0.0, "grade": PLAY}),
(B * 4, "f_air", {"start": 0.6, "grade": HOT}),
(B * 8, "e_cut_k", {"speed": 1.4, "zoom": (1.0, 1.05), "grade": SPACE}),
(0, "e_up", {"speed": 0.4, "zoom": (1.0, 1.08), "grade": dict(GOLD, sat=1.2)}),
until=103.5)
def at(take):
return next(s.at for s in SHOTS if s.take == take)
def REACT(t):
return 0.15
def BLACK(t):
if t < 0.5:
return 1 - t / 0.5
if t > 102.0:
return min(1.0, (t - 102.0) / 1.4)
return 0.0
FLASH = [(at("e_up"), 0.5)]
def caption(text, take, beats=None, size=72):
a = at(take) + 0.15
end = next(s.end for s in SHOTS if s.take == take) if beats is None else a + beats * B
return Type(text, a, end - 0.1, size, y=0.86, how="rise")
TYPE = [
Type("EARTH HAS RUN OUT OF GRASS", 0.6, at("o_skim") - 0.1, 84, y=0.2, how="rise"),
Type("HERBARIA-7 HAS TOO MUCH", at("o_skim") + 0.1, at("g_scissors") - 0.1, 84, y=0.2, how="rise"),
caption("START WITH NAIL SCISSORS", "g_scissors"),
caption("CASH IN, BUY BETTER BLADES", "g_shears", 10),
caption("HAND IN WHAT YOU CUT", "g_deposit"),
caption("GEAR UP", "g_supply"),
caption("UNLOCK UPGRADES", "g_shop"),
caption("WIDER BLADES, BIGGER STRIPS", "g_wide"),
caption("MOW WITH YOUR FRIENDS", "g_coop"),
caption("UP TO 16 PLAYERS", "v_sixteen", 7),
caption("BUILD A GRASS FACTORY", "g_build", 10),
caption("BELTS, PRESSES, BALERS", "k_belt"),
caption("ROBOTS THAT MOW FOR YOU", "k_robots"),
caption("DRIVE MOWERS, TRACTORS AND COMBINES", "g_ride", 15, 64),
caption("WORK THROUGH THE NIGHT", "n_line", 7),
caption("A WHOLE PLANET TO CLEAR", "g_map", 8),
caption("PICK YOUR CREW", "g_character"),
caption("MOW IT ALL", "f_air"),
caption("UNTIL NOT A BLADE IS LEFT", "e_cut_k", 7),
Logo(LOGO, at("e_up"), 103.5, 1180, 0.4),
Type("WISHLIST NOW ON STEAM", at("e_up") + 2.0, 103.5, 76, y=0.76, how="rise"),
Type("CO-OP FOR 1 TO 16 PLAYERS", at("e_up") + 3.0, 103.5, 50, y=0.85, how="rise", colour=(226, 240, 200)),
]
def loop(name, take, gain, beats=None):
a = at(take)
end = next(s.end for s in SHOTS if s.take == take) if beats is None else a + beats * B
return (a, clip(name), gain, end - a)
SFX = [loop("grass_rustle_loop", "g_scissors", 0.35, 15), loop("grass_rustle_loop", "g_wide", 0.35, 9)]
SFX += [(at("g_scissors") + 0.3 + 0.6 * i, clip("snip"), 0.3) for i in range(6)]
SFX += [(at("g_shears") + 0.2 + 0.7 * i, clip("shears_snip_%d" % (i % 2 + 1)), 0.35) for i in range(3)]
SFX += [(at("g_sickle") + 0.3 + 0.8 * i, clip("scythe_swing_%d" % (i % 3 + 1)), 0.3) for i in range(7)]
SFX += [(at("g_wide") + 0.4 + 0.9 * i, clip("scythe_swing_%d" % (i % 3 + 1)), 0.3) for i in range(7)]
SFX += [(at("g_deposit") + 1.9, clip("cash_register"), 0.6), (at("g_deposit") + 2.1, clip("coin_tick"), 0.4)]
SFX += [(at("g_supply") + 0.05, clip("ui_open"), 0.5), (at("g_shop") + 0.05, clip("ui_open"), 0.5), (at("g_shop") + 1.8, clip("perk_unlock"), 0.5)]
SFX += [(at("g_build") + 2.7, clip("build_place"), 0.7)]
SFX += [loop("conveyor_loop", "k_belt", 0.4), (at("k_belt") + 1.2, clip("press_thump"), 0.5)]
SFX += [loop("robot_mower_loop", "k_robots", 0.4), (at("k_robots") + 0.8, clip("robot_chirp"), 0.5)]
SFX += [loop("mower_engine_loop", "g_ride", 0.45), loop("combine_engine_loop", "g_combine", 0.45), loop("tractor_engine_loop", "c_tractor", 0.4, 6)]
SFX += [loop("night_crickets_loop", "n_line", 0.5, 7)]
SFX += [(at("g_map") + 0.05, clip("ui_open"), 0.5), (at("g_character") + 0.05, clip("ui_open"), 0.5)]
SFX += [(at("e_cut_k") + 0.5, clip("sector_clear"), 0.5), (at("e_up"), clip("milestone"), 0.6), (at("e_up") + 0.1, clip("confetti"), 0.6)]

44
Tools/Trailer/grid.py Normal file
View File

@ -0,0 +1,44 @@
"""Contact sheets of a rendered cut. py -I grid.py in.mp4 outdir step [from to]"""
import os
import sys
import cv2
import numpy as np
src, out, step = sys.argv[1], sys.argv[2], float(sys.argv[3])
start = float(sys.argv[4]) if len(sys.argv) > 4 else 0.0
cap = cv2.VideoCapture(src)
fps = cap.get(cv2.CAP_PROP_FPS)
end = float(sys.argv[5]) if len(sys.argv) > 5 else cap.get(cv2.CAP_PROP_FRAME_COUNT) / fps
os.makedirs(out, exist_ok=True)
upright = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) > cap.get(cv2.CAP_PROP_FRAME_WIDTH)
cols, rows, w, h = (8, 3, 240, 427) if upright else (5, 6, 400, 225)
cells, page, t = [], 0, start
def flush():
global cells, page
if not cells:
return
while len(cells) % cols:
cells.append(np.zeros((h, w, 3), np.uint8))
sheet = np.vstack([np.hstack(cells[i:i + cols]) for i in range(0, len(cells), cols)])
page += 1
cv2.imwrite(os.path.join(out, f"page{page:02d}.jpg"), sheet, [cv2.IMWRITE_JPEG_QUALITY, 85])
cells = []
while t < end:
cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000)
ok, f = cap.read()
if not ok:
break
f = cv2.resize(f, (w, h), interpolation=cv2.INTER_AREA)
cv2.putText(f, f"{t:.1f}", (6, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 0, 0), 3, cv2.LINE_AA)
cv2.putText(f, f"{t:.1f}", (6, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (255, 255, 255), 1, cv2.LINE_AA)
cells.append(f)
if len(cells) == cols * rows:
flush()
t += step
flush()
print(page)

View File

@ -0,0 +1,75 @@
{
"earth": {
"clip": "ArtSource/Trailer/boss/dir_earth.wav",
"from": 0.0,
"to": 2.7999375,
"parts": [
{
"take": "d_earth_0",
"at": 0.0,
"secs": 1.75,
"loop": "boss_angry",
"first": 44,
"speed": 1.0,
"score": 0.762
},
{
"take": "d_earth_1",
"at": 1.75,
"secs": 1.125,
"loop": "boss_angry",
"first": 122,
"speed": 0.8,
"score": 0.97
}
]
},
"scissors": {
"clip": "ArtSource/Trailer/boss/dir_scissors.wav",
"from": 0.0,
"to": 2.5095,
"parts": [
{
"take": "d_scissors_0",
"at": 0.0,
"secs": 2.5833333333333335,
"loop": "boss_angry",
"first": 85,
"speed": 1.1,
"score": 0.823
}
]
},
"did": {
"clip": "ArtSource/Trailer/boss/dir_did.wav",
"from": 0.0,
"to": 3.0155625,
"parts": [
{
"take": "d_did_0",
"at": 0.0,
"secs": 3.0833333333333335,
"loop": "boss_stern",
"first": 75,
"speed": 1.0,
"score": 0.605
}
]
},
"noted": {
"clip": "ArtSource/Trailer/boss/asst_noted.wav",
"from": 0.0,
"to": 2.77775,
"parts": [
{
"take": "d_noted_0",
"at": 0.0,
"secs": 2.8333333333333335,
"loop": "asst_fed",
"first": 13,
"speed": 1.0,
"score": 0.705
}
]
}
}

206
Tools/Trailer/lipsync.py Normal file
View File

@ -0,0 +1,206 @@
"""Lip sync by casting, not by animation: the Director's and the assistant's filmed loops (ArtSource/Director/video) are
searched for the stretch whose mouth opens and shuts most like the line being spoken, and that stretch becomes a take.
The mouth is found by following the eyes (template matching against the first frame) and measuring how much of a box under
the nose is dark (an open mouth shows its inside). The line's loudness, frame by frame at the loop's 24 fps, is compared with
that, over every loop of the right mood, every start and a few speeds. A line is split at its pauses, and each part gets its
own stretch, so the cut between them is a cut on a pause.
Each part is written as a take of 1920x1080 frames at 60 fps (the figure keyed over the mission-control backdrop) into
Builds/Trailer/rolls_z/d_<line>_<part>, and lipsync.json says where the parts go: the edit reads it.
py -I lipsync.py
"""
import json
import os
import subprocess
import sys
import wave
import cv2
import numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.normpath(os.path.join(HERE, "..", ".."))
sys.path.insert(0, os.path.join(ROOT, "Tools", "director"))
import talk_videos # noqa: E402
from talk_videos import frames, key # noqa: E402
VID = os.path.join(ROOT, "ArtSource", "Director", "video")
AUDIO = os.path.join(ROOT, "Assets", "Audio")
OUT = os.path.join(ROOT, "Builds", "Trailer", "rolls_z")
BG = os.path.join(ROOT, "Assets", "Art", "UI", "T_Dir_BgWide.png")
FPS, OFPS = 24, 60
W, H = 1920, 1080
# where the face is in each loop's first frame: the eyes to follow, the mouth to measure (x0, y0, x1, y1)
FACE = {
"boss": {"eyes": (230, 240, 560, 370), "mouth": (325, 398, 445, 455)},
"asst": {"eyes": (250, 250, 520, 350), "mouth": (300, 360, 430, 425)},
}
# the trailer's own takes of their lines (Eleven v4, trimmed to the voice): name: (file, from, to, loops to try)
LINE_DIR = os.path.join(ROOT, "ArtSource", "Trailer", "boss")
LINES = {
"earth": ("dir_earth", 0.0, None, ["boss_angry", "boss_stern"]),
"scissors": ("dir_scissors", 0.0, None, ["boss_angry", "boss_stern"]),
"did": ("dir_did", 0.0, None, ["boss_calm", "boss_stern"]),
"noted": ("asst_noted", 0.0, None, ["asst_fed", "asst_stern"]),
}
def mouth_track(loop):
"""Per frame: how open the mouth is, and where the face is (offset from the first frame)."""
who = loop.split("_")[0]
ex0, ey0, ex1, ey1 = FACE[who]["eyes"]
mx0, my0, mx1, my1 = FACE[who]["mouth"]
tmpl, opens, offs = None, [], []
for rgb in frames(os.path.join(VID, loop + "_src.webm")):
g = cv2.cvtColor(rgb[:700], cv2.COLOR_RGB2GRAY)
if tmpl is None:
tmpl = g[ey0:ey1, ex0:ex1].copy()
dx = dy = 0
else:
m = cv2.matchTemplate(g, tmpl, cv2.TM_CCOEFF_NORMED)
_, _, _, (bx, by) = cv2.minMaxLoc(m)
dx, dy = bx - ex0, by - ey0
box = rgb[my0 + dy:my1 + dy, mx0 + dx:mx1 + dx].astype(np.float32)
v = box.max(axis=2)
inside = (v < 120) & (box[..., 0] > box[..., 2]) # dark and reddish: the inside of a mouth
teeth = (box.min(axis=2) > 200)
opens.append(float(inside.mean() + 0.5 * teeth.mean()))
offs.append((dx, dy))
return np.array(opens), offs
def decode(path, a, b):
p = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", "1", "-ar", "16000", "-"], capture_output=True, check=True)
x = np.frombuffer(p.stdout, np.float32)
end = len(x) if b is None else int(b * 16000)
return x[int(a * 16000):end]
def envelope(x):
hop = 16000 // FPS
n = len(x) // hop
e = np.array([np.sqrt(np.mean(x[i * hop:(i + 1) * hop] ** 2)) for i in range(n)])
return np.convolve(e, np.ones(2) / 2, mode="same")
def parts(env, gap=0.18, quiet=0.1):
"""Stretches of speech, split where it is quiet for longer than `gap` seconds."""
loud = env > quiet * env.max()
runs, start, still = [], None, 0
for i, on in enumerate(loud):
if on:
if start is None:
start = i
still = 0
elif start is not None:
still += 1
if still > gap * FPS:
runs.append((start, i - still + 1))
start = None
if start is not None:
runs.append((start, len(loud)))
# glue scraps under a third of a second onto their neighbour
out = []
for r in runs:
if out and (r[1] - r[0] < FPS / 3 or out[-1][1] - out[-1][0] < FPS / 3):
out[-1] = (out[-1][0], r[1])
else:
out.append(r)
return out
def z(v):
s = v.std()
return (v - v.mean()) / s if s > 1e-6 else v * 0
def best(env, tracks, loops, used):
"""The loop, first frame and speed whose mouth follows this loudness best."""
want = z(env)
top = (-9, None, 0, 1.0)
for loop in loops:
o = tracks[loop][0]
for speed in (0.8, 0.9, 1.0, 1.1, 1.25):
span = (len(env) - 1) * speed
for s in range(0, int(len(o) - span - 1)):
if any(loop == u and abs(s - us) < FPS for u, us in used):
continue
idx = (s + np.arange(len(env)) * speed).astype(int)
seq = o[idx]
score = float(np.mean(z(seq) * want)) + 0.15 * min(1.0, seq.std() / 0.05)
if score > top[0]:
top = (score, loop, s, speed)
return top
def render(name, loop, first, speed, frames_out, offs):
"""The stretch of the loop as a take: the figure, keyed, over the backdrop, head and shoulders filling the frame."""
folder = os.path.join(OUT, name)
os.makedirs(folder, exist_ok=True)
for f in os.listdir(folder):
os.remove(os.path.join(folder, f))
bg = cv2.imread(BG, cv2.IMREAD_COLOR)
s = max(W / bg.shape[1], H / bg.shape[0])
bg = cv2.resize(bg, (int(bg.shape[1] * s) + 1, int(bg.shape[0] * s) + 1), interpolation=cv2.INTER_AREA)
y0, x0 = (bg.shape[0] - H) // 2, (bg.shape[1] - W) // 2
bg = (bg[y0:y0 + H, x0:x0 + W].astype(np.float32) * np.array([0.95, 0.86, 0.82])).astype(np.float32)
# her loops sit on a lighter black than his: flood up to just over it
talk_videos.FLOOD = 20 if loop.startswith("asst") else 9
talk_videos.SOLID = talk_videos.FLOOD + 15
need = sorted({int(first + i * FPS / OFPS * speed) for i in range(frames_out)})
keep = {}
for i, rgb in enumerate(frames(os.path.join(VID, loop + "_src.webm"))):
if i in need:
keep[i] = (rgb, key(rgb))
if i > need[-1]:
break
top, crop = 30, 560 # head to chest
sc = H / crop
fw = int(768 * sc)
for k in range(frames_out):
i = min(int(first + k * FPS / OFPS * speed), max(keep))
rgb, a = keep[i]
fig = cv2.resize(cv2.cvtColor(rgb[top:top + crop], cv2.COLOR_RGB2BGR), (fw, int(crop * sc)), interpolation=cv2.INTER_AREA).astype(np.float32)
al = cv2.resize(a[top:top + crop], (fw, int(crop * sc)), interpolation=cv2.INTER_AREA).astype(np.float32)[..., None] / 255
out = bg.copy()
fx = (W - fw) // 2
fh = min(H, fig.shape[0])
out[:fh, fx:fx + fw] = fig[:fh] * al[:fh] + out[:fh, fx:fx + fw] * (1 - al[:fh])
cv2.imwrite(os.path.join(folder, "%05d.jpg" % k), out.astype(np.uint8), [cv2.IMWRITE_JPEG_QUALITY, 93])
def main():
tracks = {}
plan = {}
for name, (clip, a, b, loops) in LINES.items():
for loop in loops:
if loop not in tracks:
tracks[loop] = mouth_track(loop)
o = tracks[loop][0]
print(f"{loop}: {len(o)} frames, open {o.min():.3f}..{o.max():.3f}")
x = decode(os.path.join(LINE_DIR, clip + ".wav"), a, b)
env = envelope(x)
used, out = [], []
runs = parts(env)
# the parts tile the whole line: each runs to where the next starts, the last just past the end
cuts = [0] + [max(0, r[0] - 2) for r in runs[1:]] + [len(env) + 2]
for k in range(len(runs)):
lo, hi = cuts[k], cuts[k + 1]
score, loop, first, speed = best(np.pad(env, (0, 6))[lo:hi], tracks, loops, used)
used.append((loop, first))
take = f"d_{name}_{k}"
secs = (hi - lo) / FPS
render(take, loop, first, speed, int(secs * OFPS) + 18, tracks[loop][1])
out.append({"take": take, "at": lo / FPS, "secs": secs, "loop": loop, "first": first, "speed": speed, "score": round(score, 3)})
print(f"{take}: {lo / FPS:5.2f}+{secs:4.2f}s {loop} from {first} x{speed} score {score:.2f}")
plan[name] = {"clip": os.path.relpath(os.path.join(LINE_DIR, clip + ".wav"), ROOT).replace(os.sep, "/"), "from": a, "to": b if b is not None else a + len(x) / 16000, "parts": out}
with open(os.path.join(HERE, "lipsync.json"), "w") as f:
json.dump(plan, f, indent=1)
if __name__ == "__main__":
main()

36
Tools/Trailer/looks.py Normal file
View File

@ -0,0 +1,36 @@
"""What every cut shares: the song's beat, the grades, where the takes and the sounds are, and laying shots end to end."""
import os
from cut import PROJECT, Shot
ROLLS = os.path.join(PROJECT, r"Builds\Trailer\rolls")
AUDIO = os.path.join(PROJECT, r"Assets\Audio")
LOGO = os.path.join(PROJECT, r"Assets\Art\UI\logo_grasscutter.png")
BEAT = 0.4665
BAR = BEAT * 4
GOLD = {"tint": (-0.02, 0.0, 0.03), "sat": 1.08, "gain": 1.02, "contrast": 1.1}
DUSK = {"tint": (-0.05, -0.012, 0.06), "sat": 1.24, "gain": 1.04, "contrast": 1.12}
NIGHT = {"tint": (0.05, 0.012, -0.03), "sat": 0.95, "gain": 1.5, "contrast": 1.16}
BARE = {"tint": (-0.03, -0.004, 0.035), "sat": 1.0, "gain": 1.0, "contrast": 1.16}
HOT = {"sat": 1.1, "contrast": 1.1, "gain": 1.0}
PLAY = {"sat": 1.04, "contrast": 1.04, "gain": 1.0} # first person: the HUD keeps its own colours
SPACE = {"sat": 1.1, "contrast": 1.06, "tint": (0, 0, 0)}
def clip(name):
return os.path.join(AUDIO, name + ".wav")
def runner(shots):
"""run(at, (seconds, take, keywords), ...): back to back from `at`. With `until` the last shot runs to it."""
def run(at, *cuts, until=None):
t = at
for i, c in enumerate(cuts):
secs, take = c[0], c[1]
kw = c[2] if len(c) > 2 else {}
end = until if until is not None and i == len(cuts) - 1 else t + secs
shots.append(Shot(take, t, end, **kw))
t = end
return t
return run

393
Tools/Trailer/polden.py Normal file
View File

@ -0,0 +1,393 @@
"""The scripted trailer, Docs/TRAILER_SCRIPT.md (the Polden workshop way): the Director's call opens it, one pair of nail
scissors against the planet, then a co-op evening told by four players on voice chat (foreman, gremlin, engineer,
tourist), the loop from hands to machines to factory, the planet fighting back, the bald planet, and the Director again.
Every line is an Eleven v4 take: the crew's put through a headset filter (ArtSource/Trailer/crew), the Director's and the
assistant's clean (ArtSource/Trailer/boss). The music is ElevenLabs too
(ArtSource/Trailer/polden_music.mp3); under the storm it goes dull and the storm loop comes up.
py -I cut.py polden.py out.mp4 [from to]
"""
import json
import os
import wave
import numpy as np
from cut import PROJECT, SR, Logo, Shot, Type, decode
from looks import GOLD, HOT, LOGO, NIGHT, PLAY, SPACE, clip
TR = os.path.join(PROJECT, "Builds", "Trailer")
ROLLS = TR
OUT = os.path.join(TR, "polden")
os.makedirs(OUT, exist_ok=True)
CREW = os.path.join(PROJECT, "ArtSource", "Trailer", "crew")
MUSIC = os.path.join(PROJECT, "ArtSource", "Trailer", "polden_music.mp3")
PUNCH, SHAKE, ABERRATE = 0.008, 1.5, 0.8
STUDIO = {"sat": 1.02, "contrast": 1.04, "gain": 1.0, "tint": (0, 0, 0)}
B = 60 / 129.2 # the music's beat
def roll(take):
base = take.split("@")[0]
for d in ("rolls_z", "rolls3", "rolls_1105"):
if os.path.isdir(os.path.join(TR, d, base)):
return os.path.join(TR, d, take)
raise SystemExit("no take " + take)
# ───────────────────────── what the game heard ─────────────────────────
_logs = {}
def log(take):
base = take.split("@")[0]
if base not in _logs:
rows = []
path = os.path.join(os.path.dirname(roll(take)), base, "sounds.txt")
if os.path.exists(path):
for line in open(path, encoding="utf-8"):
p = line.rstrip("\n").split("\t")
if len(p) >= 5:
rows.append((int(p[0]) / 60.0, p[1], float(p[2].replace(",", ".")), float(p[4].replace(",", "."))))
_logs[base] = rows
return _logs[base]
def when(take, name, n=0):
hits = [t for t, nm, _, _ in log(take) if nm == name]
if len(hits) <= n:
raise SystemExit(f"{take}: no {name} #{n} in sounds.txt")
return hits[n]
def seconds(path):
with wave.open(path) as w:
return w.getnframes() / w.getframerate()
# ───────────────────────── laying shots ─────────────────────────
SHOTS, HEAR, EXTRA, LINES, SUBS = [], [], [], [], []
now = 0.0
def put(take, start, secs, hear=False, sound=None, **kw):
global now
SHOTS.append(Shot(roll(take), now, now + secs, start=start, **kw))
if hear or sound:
st, sf = sound if sound else (take, start)
HEAR.append((now, st, sf, secs))
now += secs
return now
WHO = {"fo": (255, 214, 90), "gr": (255, 140, 90), "en": (140, 220, 255), "to": (190, 255, 150)}
def say(name, at, text, gain=1.0):
"""A crew line on voice chat, with its subtitle (Steam plays trailers muted until you click)."""
path = os.path.join(CREW, name + ".wav")
d = seconds(path)
LINES.append((at, path, 1.15 * gain))
SUBS.append((at, at + max(d, 1.0) + 0.25, text, WHO[name[:2]]))
return at + d
def sub(at, secs, text, colour=(255, 255, 255)):
SUBS.append((at, at + secs, text, colour))
LIP = json.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lipsync.json")))
TALK = [] # the Director's and the assistant's lines: (at, clip, gain, seconds, from)
def speak(line, text, zooms=((1.0, 1.04), (1.12, 1.16)), colour=(255, 255, 255)):
"""A line of theirs, the trailer's own take of it (ArtSource/Trailer/boss). Shown as ElevenLabs' talking avatar of
the figure (rolls_z/el_<line>, made from that same take) when there is one; otherwise in their own filmed loops, cut
where the mouth moves with it (lipsync.py chose the stretches). The shot ends with the voice: no air after it."""
L = LIP[line]
path = os.path.join(PROJECT, L["clip"])
secs = L["to"] - L["from"]
at = now
if os.path.isdir(os.path.join(TR, "rolls_z", "el_" + line)):
put("el_" + line, 0.0, secs, grade=STUDIO, zoom=zooms[0])
else:
for k, p in enumerate(L["parts"]):
put(p["take"], 0.0, min(p["secs"], at + secs - now), grade=STUDIO, zoom=zooms[k % len(zooms)])
TALK.append((at, path, 1.0, secs, L["from"]))
sub(at + 0.05, now - at - 0.1, text, colour)
return at
# ───────────────────────── 1 · We have a situation ─────────────────────────
speak("earth", "EARTH IS OUT OF GRASS! NO GRASS!")
TITLE1 = 0.6
speak("scissors", "I don't care if you have to use nail scissors!", zooms=((1.1, 1.18),))
BLADE_AT = now
put("z_blade", 0.5, 4.0, grade=HOT)
say("to_nails", BLADE_AT + 0.4, "...these are nail scissors.")
EXTRA += [(BLADE_AT + 0.15 + 0.42 * i, clip("snip"), 0.35) for i in range(4)]
EXTRA += [(BLADE_AT, clip("grass_rustle_loop"), 0.35, 4.0), (BLADE_AT, clip("ambience_loop"), 0.5, 4.0)]
MUSIC_AT = now # the music starts on the cut to the crew; its big hit then lands on the bald planet
# ───────────────────────── 2 · Meet the crew ─────────────────────────
CREW_AT = now
put("v_touch", 0.3, 3.0, grade=GOLD)
say("fo_rows", CREW_AT + 0.15, "Okay team. Rows. Straight rows.")
t = put("p_4", 1.0, 1.1, grade=GOLD)
say("gr_big", t - 1.0, "Wait... how big is this planet?")
WHOLE_AT = now
put("o_dive", 0.6, 2.4, grade=SPACE)
t = now
put("o_giant", 0.4, 3.0, grade=GOLD)
say("to_sky", t + 0.2, "Guys... look at the sky.")
# ───────────────────────── 3 · By hand ─────────────────────────
HAND_AT = now
put("g_scissors", 0.6, B * 3, grade=PLAY)
put("c_swing", 0.4, B * 3, grade=HOT)
t = now
put("g_deposit", 1.0, B * 4, grade=PLAY)
say("fo_hand", t + 0.2, "Hand it in, hand it in!")
CATCH_AT = now
put("z_catch", 0.55, 2.5, hear=True, grade=HOT)
say("gr_catch", CATCH_AT + 0.25, "Catch!")
THROW, HIT = 0.32 * 3.2 - 0.55, 0.32 * 3.2 + 0.42 - 0.55
EXTRA += [(CATCH_AT + THROW, clip("throw_whoosh"), 0.7), (CATCH_AT + HIT, clip("cardboard_thud_1"), 1.0), (CATCH_AT + HIT + 0.02, clip("land"), 0.6)]
SIXTEEN_AT = now
put("v_sixteen", 0.8, B * 6, grade=HOT)
# ───────────────────────── 4 · Bigger blades ─────────────────────────
BLADES_AT = now
put("g_shears", 0.8, B * 2, grade=PLAY)
put("g_sickle", 0.8, B * 2, grade=PLAY)
put("g_scythe", 1.2, B * 2, grade=PLAY)
put("g_wide", 1.5, B * 2, grade=PLAY)
put("c_tractor", 1.6, B * 3, grade=HOT)
t = now
put("g_combine", 1.0, B * 3, grade=PLAY)
say("fo_back", t + 0.1, "We are SO back.")
put("c_combine", 0.6, B * 4, grade=HOT)
t = now
put("c_combine_top", 0.5, B * 4, grade=HOT)
say("en_pickup", t + 0.1, "Who took the pickup?")
t = now
put("w_wheels", 0.3, B * 5, grade=HOT)
say("gr_nobody", t + 0.15, "Nobody!")
EXTRA += [(BLADES_AT + B * 2 * i + 0.1, clip("scythe_swing_%d" % (i % 3 + 1)), 0.35) for i in range(4)]
EXTRA += [(BLADES_AT + B * 8, clip("combine_engine_loop"), 0.3, B * 14)]
# ───────────────────────── 5 · Let the factory do it ─────────────────────────
FACTORY_AT = now
put("k_grow", 0.4, B * 6, grade=HOT)
put("k_hammer", 1.0, B * 2, grade=HOT)
put("y_drones", 0.4, B * 4, grade=GOLD)
put("k_robots", 0.5, B * 3, grade=HOT)
t = now
put("k_belt", 0.6, B * 6, grade=HOT)
say("en_works", t + 0.2, "It works. It actually works.")
EXTRA += [(t, clip("conveyor_loop"), 0.35, B * 6)]
SPILL_AT = now
put("z_spill", 1.2, 3.0, hear=True, grade=HOT)
say("en_mostly", SPILL_AT + 1.0, "...it mostly works.")
# ───────────────────────── 6 · The planet fights back ─────────────────────────
STORM_AT = now
put("y_acid", 0.4, 2.9, grade=HOT)
say("to_rain", STORM_AT + 0.2, "Is the rain... eating the grass?")
t = now
put("s_storm", 2.0, 2.2, grade=HOT)
say("fo_save", t + 0.1, "The bundles! Save the bundles!")
T0 = "s_thrown"
FLING = when(T0, "throw_whoosh")
t = now
put(T0, FLING - 1.1, 2.3, grade=PLAY)
say("gr_goin", t, "I'm going in!")
EXTRA += [(t + 1.1, clip("throw_whoosh"), 0.8)]
speak("noted", "You got thrown by a twister. Noted.", zooms=((1.0, 1.05), (1.14, 1.18)), colour=(255, 200, 220))
UFO_AT = now
put("y_ufo", 0.4, 2.6, grade=GOLD)
STORM_END = now
EXTRA += [(STORM_AT, clip("rain_loop"), 0.45, 5.1), (STORM_AT + 2.9, clip("twister_loop"), 0.5, 5.9), (STORM_AT + 2.9, clip("wind_loop"), 0.35, 5.9),
(STORM_AT + 3.0, clip("thunder"), 0.55), (UFO_AT, clip("ufo_hum_loop"), 0.45, 2.6), (UFO_AT + 0.8, clip("ufo_beam_loop"), 0.35, 1.8)]
# ───────────────────────── 7 · Not a single blade ─────────────────────────
BIG_AT = now
for take, start, grade in (("f_air", 0.6, HOT), ("y_house", 0.8, GOLD), ("f_top", 0.5, HOT), ("y_house_night", 0.6, NIGHT),
("f_in", 0.6, HOT), ("f_side", 0.8, HOT)):
put(take, start, B * 2, grade=grade)
CUT_AT = now
put("e_cut_k", 2.0, B * 6, speed=1.6, zoom=(1.0, 1.05), grade=SPACE)
t = now
put("e_crew", 0.6, B * 5, grade=GOLD)
say("to_did", t + 0.1, "We did that?")
say("fo_did", t + 1.2, "We did that.")
# ───────────────────────── 8 · CTA ─────────────────────────
CTA_AT = now
speak("did", "You magnificent idiots actually did it.")
LOGO_AT = now
put("e_up", 1.52, 6.0, speed=0.45, zoom=(1.06, 1.12), grade=dict(GOLD, sat=1.2))
say("gr_keep", LOGO_AT + 0.5, "Can we keep the combine?")
EXTRA += [(LOGO_AT, clip("milestone"), 0.6), (LOGO_AT + 0.1, clip("confetti"), 0.6)]
HIT = 66.5 # the song's last hit, in its own seconds
# where the song's zero falls: the hit mid bald planet, and a whole number of beats skipped so the cuts stay on the beat
SONG_AT = MUSIC_AT - max(0, round((MUSIC_AT - (CUT_AT + 1.54 - HIT)) / B)) * B
EXTRA += [(SONG_AT + HIT, clip("ambience_loop"), 0.5, LOGO_AT + 2.0 - (SONG_AT + HIT))]
END = now
KEEP = [(0.0, END)]
# ───────────────────────── the sound ─────────────────────────
def voice(name):
return name.startswith("dir_") or name.startswith("asst_")
def gather():
"""What the takes heard: the Director's lines, cut to the stretch each shot shows; the game's effects within it."""
pieces, sfx = [], []
for at, take, frm, secs in HEAR:
for ts, name, vol, dist in log(take):
if not os.path.exists(clip(name)):
continue
if voice(name):
L = seconds(clip(name))
a, b = max(ts, frm), min(ts + L, frm + secs)
if b - a > 0.02:
pieces.append([at + a - frm, name, b - a, a - ts])
elif frm <= ts < frm + secs and not name.startswith("phone"):
fall = 1.0 / (1.0 + dist / 10.0) if dist > 0 else 1.0
sfx.append((at + ts - frm, clip(name), min(1.0, vol) * fall * 0.8))
voices = [(a, clip(n), 1.0, d, o) for a, n, d, o in pieces]
# a pile of bundles logs a clunk a frame: one per name every 0.15 s is plenty
sfx.sort(key=lambda x: x[0])
last, thin = {}, []
for at, path, g in sfx:
if at - last.get(path, -9) >= 0.15:
last[path] = at
thin.append((at, path, g * 0.6))
return voices, thin
DIRECTOR, HEARD = gather()
VOICES = DIRECTOR + TALK + [(a, p, g, seconds(p)) for a, p, g in LINES]
SFX = DIRECTOR + TALK + LINES + HEARD + [e for e in EXTRA if os.path.exists(e[1])]
MISSING = sorted({os.path.basename(e[1]) for e in EXTRA if not os.path.exists(e[1])})
def bed():
"""Nothing under the call; the music from the pull-back on, dull and low under the storm, ducked under every line."""
n = int((END + 2) * SR)
out = np.zeros((n, 2), np.float32)
song = decode(MUSIC)
# the song in two: through its last hit, which buttons the bald planet, and on as it rings out under "we did that"
# and the Director (no dead air); then from two beats before that hit again, so it lands on the logo
lead = int((HIT - 0.9) * SR)
i = int(MUSIC_AT * SR)
j = int((LOGO_AT - 0.9) * SR)
a = song[int((MUSIC_AT - SONG_AT) * SR):].copy()
up = int(0.2 * SR)
a[:up] *= np.linspace(0.0, 1.0, up)[:, None]
a = a[:max(0, j - i) + int(0.3 * SR)]
fade = int(0.3 * SR)
a[-fade:] *= np.linspace(1.0, 0.0, fade)[:, None] ** 2
out[i:i + len(a)] += a[:n - i] * 0.9
b = song[lead:lead + n - j].copy()
b[:int(0.05 * SR)] *= np.linspace(0.0, 1.0, int(0.05 * SR))[:, None]
out[j:j + len(b)] += b * 0.9
# the storm: the band through a wall, the storm loop over it
s, e = int(STORM_AT * SR), int(STORM_END * SR)
import subprocess
seg = out[s:e].copy()
p = subprocess.run(["ffmpeg", "-v", "error", "-f", "f32le", "-ac", "2", "-ar", str(SR), "-i", "-", "-af", "lowpass=f=420,lowpass=f=420",
"-f", "f32le", "-ac", "2", "-ar", str(SR), "-"], input=seg.tobytes(), capture_output=True, check=True)
dull = np.frombuffer(p.stdout, np.float32).reshape(-1, 2)[:len(seg)] * 0.8
x = int(0.35 * SR)
w = np.ones(len(seg), np.float32)
w[:x] = np.linspace(0, 1, x)
w[-x:] = np.linspace(1, 0, x)
out[s:e] = seg * (1 - w[:, None]) + dull * w[:, None]
storm = decode(clip("music_storm_loop"))
k = min(len(storm), e - s)
out[s:s + k] += storm[:k] * 0.55 * w[:k, None]
# under the voices
duck = np.ones(n, np.float32)
for v in VOICES:
at, d = v[0], v[3]
a, b = int((at - 0.12) * SR), int((at + d + 0.2) * SR)
duck[max(0, a):min(n, b)] = 0.38
kernel = int(0.18 * SR)
duck = np.convolve(duck, np.ones(kernel) / kernel, mode="same").astype(np.float32)
out *= duck[:, None]
path = os.path.join(OUT, "bed.wav")
raw = (np.clip(out, -1, 1) * 32767).astype(np.int16)
with wave.open(path, "wb") as f:
f.setnchannels(2)
f.setsampwidth(2)
f.setframerate(SR)
f.writeframes(raw.tobytes())
return path
TRACK = bed()
TRACK_GAIN = 1.0
def REACT(t):
return 0.0 if t < MUSIC_AT + 1.0 or CTA_AT <= t < LOGO_AT else 0.3
def BLACK(t):
if t < 0.25:
return 1 - t / 0.25
if t > END - 1.0:
return min(1.0, (t - (END - 1.0)) / 1.0)
return 0.0
FLASH = [(CREW_AT, 0.4), (BIG_AT, 0.45), (LOGO_AT, 0.6)]
def card(text, at, secs, size=110):
return Type(text, at, at + secs, size, y=0.2, how="slam")
TYPE = [
card("EARTH RAN OUT OF GRASS", TITLE1, 3.0),
card("MOW A WHOLE PLANET", WHOLE_AT + 0.1, 2.3),
card("UP TO 16 PLAYERS ONLINE", SIXTEEN_AT + 0.1, B * 6 - 0.2),
card("FROM NAIL SCISSORS TO A COMBINE", BLADES_AT + 0.05, B * 8 - 0.1, 96),
card("LET THE FACTORY DO IT", FACTORY_AT + 0.05, B * 8 - 0.1),
card("AN ALIEN WORLD", UFO_AT + 0.1, 2.4),
card("NOT A SINGLE BLADE LEFT", CUT_AT + 0.1, B * 6 - 0.2),
Logo(LOGO, LOGO_AT, END, 1180, 0.4),
Type("WISHLIST NOW ON STEAM", LOGO_AT + 1.6, END, 76, y=0.76, how="rise"),
Type("ONLINE CO-OP FOR 1 TO 16 PLAYERS", LOGO_AT + 2.4, END, 50, y=0.85, how="rise", colour=(226, 240, 200)),
]
# subtitles, low and small, in each speaker's colour
for a, b, text, colour in SUBS:
if a < LOGO_AT:
TYPE.append(Type(text, a, b, 52, y=0.9, how="fade", colour=colour, edge=(18, 22, 16)))
else:
TYPE.append(Type(text, a, b, 48, y=0.94, how="fade", colour=colour, edge=(18, 22, 16)))
if __name__ == "__main__":
for s in SHOTS:
print(f"{s.at:7.2f} {s.end - s.at:5.2f} {os.path.basename(s.take):24s} from {s.start:6.2f}")
print("song %.2f " % SONG_AT, end="")
print("music %.2f crew %.2f hand %.2f blades %.2f factory %.2f storm %.2f big %.2f cta %.2f logo %.2f end %.2f" % (
MUSIC_AT, CREW_AT, HAND_AT, BLADES_AT, FACTORY_AT, STORM_AT, BIG_AT, CTA_AT, LOGO_AT, END))
for v in VOICES:
print("voice %7.2f %-16s %5.2f" % (v[0], os.path.basename(v[1]), v[3]))
print("missing sounds:", MISSING)

23
Tools/Trailer/remix.py Normal file
View File

@ -0,0 +1,23 @@
"""Lays the sound of an edit again under a finished render, picture untouched: py -I remix.py edl.py film.mp4"""
import importlib.util
import os
import subprocess
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import cut # noqa: E402
spec = importlib.util.spec_from_file_location("edl", sys.argv[1])
edl = importlib.util.module_from_spec(spec)
sys.modules["edl"] = edl
spec.loader.exec_module(edl)
film = sys.argv[2]
wav = film + ".remix.wav"
song = cut.decode(getattr(edl, "TRACK", cut.TRACK)) * getattr(edl, "TRACK_GAIN", 1.0)
cut.mix(song, cut.Clock(edl.KEEP), getattr(edl, "SFX", []), wav)
tmp = film + ".remix.mp4"
subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", film, "-i", wav, "-map", "0:v", "-map", "1:a", "-c:v", "copy", "-c:a", "aac", "-b:a", "320k",
"-shortest", "-movflags", "+faststart", tmp], check=True)
os.replace(tmp, film)
os.remove(wav)
print("remixed", film)

28
Tools/Trailer/sheet.py Normal file
View File

@ -0,0 +1,28 @@
"""Contact sheet: one row per take, n frames across it. py -I sheet.py rolls out.jpg [per_row] [take,take,...]"""
import os, sys
import cv2
import numpy as np
root, out = sys.argv[1], sys.argv[2]
n = int(sys.argv[3]) if len(sys.argv) > 3 else 3
only = sys.argv[4].split(",") if len(sys.argv) > 4 else None
cell = (480, 270) if n <= 3 else (360, 202)
rows = []
takes = sorted(t for t in os.listdir(root) if os.path.isdir(os.path.join(root, t)))
if only:
takes = [t for t in takes if any(t == o or t.startswith(o) for o in only)]
for t in takes:
files = sorted(f for f in os.listdir(os.path.join(root, t)) if f.endswith(".jpg"))
if not files:
continue
pick = [files[int(i * (len(files) - 1) / max(1, n - 1))] for i in range(n)]
row = []
for j, f in enumerate(pick):
im = cv2.resize(cv2.imread(os.path.join(root, t, f)), cell, interpolation=cv2.INTER_AREA)
if j == 0:
cv2.putText(im, t, (8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 3, cv2.LINE_AA)
cv2.putText(im, t, (8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1, cv2.LINE_AA)
row.append(im)
rows.append(np.hstack(row))
cv2.imwrite(out, np.vstack(rows), [cv2.IMWRITE_JPEG_QUALITY, 88])
print(len(rows), "takes")

View File

@ -0,0 +1,29 @@
"""Short 1, the premise: Earth ran out of grass, so the crew went to a planet that has too much, and mowed it."""
from looks import BAR, GOLD, HOT, ROLLS, SPACE, clip, runner # noqa: F401
from vertical import ABERRATE, BLACK, CARD, PUNCH, SHAKE, SIZE, card, hook # noqa: F401
KEEP = [(2.2, 15.33), (22.9, 31.3), CARD]
SHOTS = []
run = runner(SHOTS)
run(2.2,
(5.3, "o_space_k", {"speed": 1.5, "zoom": (1.15, 1.25), "grade": SPACE}),
(4.1, "o_dive", {"start": 0.9, "speed": 0.9, "grade": GOLD}),
(1.8, "o_skim", {"start": 2.2, "speed": 1.35, "grade": GOLD}),
(0, "o_giant", {"start": 0.6, "speed": 0.7, "grade": GOLD}),
until=15.33)
run(22.9,
(2.1, "c_swing_s", {"rate": 120, "start": 1.2, "speed": 0.5, "grade": HOT}),
(BAR, "v_sixteen", {"start": 1.2, "grade": HOT}),
(BAR, "f_air", {"start": 0.6, "grade": HOT}),
(0, "e_cut_k", {"start": 2.0, "speed": 2.6, "zoom": (1.15, 1.2), "grade": SPACE}),
until=31.3)
run(CARD[0], (0, "e_up", {"start": 0.2, "speed": 0.48, "grade": dict(GOLD, sat=1.2)}), until=CARD[1])
def REACT(t):
return 0.3 if t < 22.9 else 0.6
TYPE = hook(["EARTH RAN OUT", "OF GRASS"], 2.5, 7.4) + hook(["SO WE FOUND", "A PLANET WITH", "TOO MUCH"], 7.6, 15.3, how="rise")
TYPE += hook(["AND MOWED", "ALL OF IT"], 26.9, 31.3) + card()
SFX = [(22.9, clip("scythe_swing_1"), 0.5), (CARD[0], clip("confetti"), 0.7)]

View File

@ -0,0 +1,22 @@
"""Short 2, the climb: every blade from nail scissors to the combine, one bar each, in first person."""
from looks import BAR, HOT, PLAY, ROLLS, clip, runner # noqa: F401
from vertical import ABERRATE, BLACK, CARD, PUNCH, SHAKE, SIZE, card, hook, label # noqa: F401
KEEP = [(22.9, 38.23), CARD]
SHOTS = []
run = runner(SHOTS)
STEPS = [("g_scissors", 0.6, "NAIL SCISSORS"), ("g_shears", 0.8, "GARDEN SHEARS"), ("g_sickle", 0.8, "SICKLE"), ("g_scythe", 1.2, "SCYTHE"),
("g_wide", 1.2, "TWO-HANDED SCYTHE"), ("g_ride", 1.6, "RIDE-ON MOWER"), ("g_combine", 2.0, "COMBINE")]
end = run(22.9, *[(BAR, take, {"start": s, "grade": PLAY}) for take, s, _ in STEPS])
run(end, (0, "f_air", {"start": 0.6, "grade": HOT}), until=38.23)
run(CARD[0], (0, "e_up", {"start": 0.2, "speed": 0.48, "grade": HOT}), until=CARD[1])
def REACT(t):
return 0.5
TYPE = hook(["FROM NAIL SCISSORS", "TO A COMBINE"], 22.9, 38.2, size=84)
TYPE += [label(text, 22.9 + i * BAR + 0.05, 22.9 + (i + 1) * BAR - 0.05, 96 if len(text) < 14 else 76) for i, (_, _, text) in enumerate(STEPS)]
TYPE += [label("ALL OF IT", end + 0.05, 38.2)] + card()
SFX = [(22.9, clip("snip"), 0.5), (22.9 + BAR, clip("shears_snip_1"), 0.5), (22.9 + BAR * 3, clip("scythe_swing_1"), 0.5), (CARD[0], clip("confetti"), 0.7)]

View File

@ -0,0 +1,26 @@
"""Short 3, the crowd: sixteen players and every machine on one planet, the last chorus."""
from looks import BAR, HOT, NIGHT, PLAY, ROLLS, clip, runner # noqa: F401
from vertical import ABERRATE, BLACK, CARD, PUNCH, SHAKE, SIZE, card, hook # noqa: F401
KEEP = [(116.1, 131.03), CARD]
SHOTS = []
run = runner(SHOTS)
run(116.1,
(BAR, "v_sixteen", {"start": 1.0, "grade": HOT}),
(BAR, "c_line", {"start": 1.2, "grade": HOT}),
(BAR, "g_coop", {"start": 1.5, "grade": PLAY}),
(BAR, "n_line", {"start": 0.8, "grade": NIGHT}),
(BAR, "f_hero", {"start": 0.4, "grade": HOT}),
(BAR, "f_in", {"start": 0.6, "grade": HOT}),
(BAR, "f_side", {"start": 0.3, "grade": HOT}),
(0, "f_air", {"start": 0.6, "grade": HOT}),
until=131.03)
run(CARD[0], (0, "e_up", {"start": 0.2, "speed": 0.48, "grade": HOT}), until=CARD[1])
def REACT(t):
return 0.6
TYPE = hook(["16 PLAYERS", "ONE PLANET"], 116.1, 123.5) + hook(["NOT ONE BLADE", "OF GRASS LEFT"], 123.6, 131.0) + card()
SFX = [(116.1, clip("scythe_swing_2"), 0.5), (CARD[0], clip("confetti"), 0.7)]

View File

@ -0,0 +1,24 @@
"""Short 4, the slow part of the song under the slow-motion takes: blades through grass, strips from above."""
from looks import GOLD, HOT, ROLLS, clip, runner # noqa: F401
from vertical import ABERRATE, BLACK, CARD, PUNCH, SHAKE, SIZE, card, hook # noqa: F401
KEEP = [(97.77, 112.0), CARD]
SHOTS = []
run = runner(SHOTS)
run(97.77,
(2.65, "b_grass", {"rate": 120, "speed": 0.5, "start": 0.2, "grade": GOLD}),
(2.1, "m_blade", {"rate": 120, "start": 0.3, "speed": 0.4, "grade": GOLD}),
(2.0, "b_header", {"rate": 120, "start": 0.6, "speed": 0.5, "grade": GOLD}),
(2.6, "c_swing_s", {"rate": 120, "start": 1.0, "speed": 0.5, "grade": GOLD}),
(2.0, "b_line", {"rate": 120, "start": 0.25, "speed": 0.5, "grade": GOLD}),
(0, "c_top", {"start": 0.8, "speed": 0.8, "grade": HOT}),
until=112.0)
run(CARD[0], (0, "e_up", {"start": 0.2, "speed": 0.48, "grade": GOLD}), until=CARD[1])
def REACT(t):
return 0.1
TYPE = hook(["THE MOST", "SATISFYING JOB", "IN SPACE"], 97.9, 111.9, how="rise") + card()
SFX = [(CARD[0], clip("confetti"), 0.7)]

View File

@ -0,0 +1,23 @@
"""Short 5, the whole planet going from green to bare, seen from orbit, then the armada that did it."""
from looks import BAR, HOT, ROLLS, SPACE, clip, runner # noqa: F401
from vertical import ABERRATE, BLACK, CARD, PUNCH, SHAKE, SIZE, card, hook # noqa: F401
KEEP = [(131.03, 147.72), CARD]
SHOTS = []
run = runner(SHOTS)
run(131.03,
(9.0, "e_cut_k", {"speed": 1.0, "zoom": (1.2, 1.3), "grade": SPACE}),
(BAR, "f_air", {"start": 0.6, "grade": HOT}),
(BAR, "f_top", {"start": 0.4, "grade": HOT}),
(BAR, "f_in", {"start": 0.9, "grade": HOT}),
(0, "f_hero", {"start": 1.0, "grade": HOT}),
until=147.72)
run(CARD[0], (0, "e_up", {"start": 0.2, "speed": 0.48, "grade": HOT}), until=CARD[1])
def REACT(t):
return 0.2 if t < 140 else 0.6
TYPE = hook(["WE MOWED", "AN ENTIRE", "PLANET"], 131.1, 140.0) + hook(["16 OF US"], 140.1, 147.7) + card()
SFX = [(131.2, clip("sector_clear"), 0.5), (CARD[0], clip("confetti"), 0.7)]

View File

@ -0,0 +1,28 @@
"""Short 6, the factory: building it, belts and robots, the money coming in."""
from looks import HOT, PLAY, ROLLS, clip, runner # noqa: F401
from vertical import ABERRATE, BLACK, CARD, PUNCH, SHAKE, SIZE, card, hook, label # noqa: F401
KEEP = [(80.7, 97.77), CARD]
SHOTS = []
run = runner(SHOTS)
run(80.7,
(3.0, "g_build", {"start": 1.6, "grade": PLAY}),
(2.4, "k_grow", {"start": 2.5, "speed": 1.4, "zoom": (1.35, 1.45), "grade": HOT}),
(1.4, "k_hammer", {"start": 0.6, "grade": HOT}),
(2.6, "k_belt", {"start": 0.3, "grade": HOT}),
(2.4, "k_robots", {"start": 0.6, "grade": HOT}),
(1.8, "k_robots2", {"start": 0.6, "grade": HOT}),
(2.0, "g_deposit", {"start": 1.6, "grade": PLAY}),
(0, "g_shop", {"start": 0.6, "grade": PLAY}),
until=97.77)
run(CARD[0], (0, "e_up", {"start": 0.2, "speed": 0.48, "grade": HOT}), until=CARD[1])
def REACT(t):
return 0.45
TYPE = hook(["TURNING GRASS", "INTO MONEY"], 80.8, 97.7)
TYPE += [label("BUILD", 80.8, 83.6), label("BALE", 86.2, 88.6), label("AUTOMATE", 88.8, 92.9), label("CASH IN", 93.0, 95.0), label("UPGRADE", 95.1, 97.7)]
TYPE += card()
SFX = [(82.1, clip("build_place"), 0.7), (86.4, clip("press_thump"), 0.5), (94.0, clip("cash_register"), 0.6), (CARD[0], clip("confetti"), 0.7)]

View File

@ -0,0 +1,26 @@
"""Short 7, the roll call: the eight of them two beats each, then off to work."""
from looks import BAR, BEAT, HOT, ROLLS, clip, runner # noqa: F401
from vertical import ABERRATE, BLACK, CARD, PUNCH, SHAKE, SIZE, card, hook, label # noqa: F401
START = 15.33 + BEAT * 4
KEEP = [(START, 30.6), CARD]
NAMES = ["HANK", "OTIS", "LIN", "RUSTAM", "MARCUS", "GUS", "WADE", "KENJI"]
SHOTS = []
run = runner(SHOTS)
t = run(START, *[(BEAT * 2, f"p_{i}", {"start": 0.3, "speed": 0.9, "zoom": (1.0, 1.04), "grade": HOT}) for i in range(8)])
run(t,
(BAR, "c_swing_s", {"rate": 120, "start": 1.2, "speed": 0.5, "grade": HOT}),
(BAR, "v_sixteen", {"start": 1.2, "grade": HOT}),
(0, "f_air", {"start": 0.6, "grade": HOT}),
until=30.6)
run(CARD[0], (0, "e_up", {"start": 0.2, "speed": 0.48, "grade": HOT}), until=CARD[1])
def REACT(t):
return 0.45
TYPE = hook(["PICK YOUR", "GRASS CUTTER"], START, t)
TYPE += [label(n, START + i * BEAT * 2 + 0.03, START + (i + 1) * BEAT * 2 - 0.03, 120) for i, n in enumerate(NAMES)]
TYPE += hook(["THEN GET", "TO WORK"], t + 0.1, 30.55) + card()
SFX = [(t, clip("scythe_swing_1"), 0.5), (CARD[0], clip("confetti"), 0.7)]

View File

@ -0,0 +1,24 @@
"""Short 8, the night shift: sundown, work lights, the crew still in a line."""
from looks import DUSK, GOLD, NIGHT, ROLLS, clip, runner # noqa: F401
from vertical import ABERRATE, BLACK, CARD, PUNCH, SHAKE, SIZE, card, hook # noqa: F401
KEEP = [(47.56, 60.58), CARD]
SHOTS = []
run = runner(SHOTS)
run(47.56,
(2.8, "v_sunset", {"rate": 30, "start": 0.0, "speed": 1.4, "grade": DUSK}),
(2.4, "n_line", {"start": 0.6, "grade": NIGHT}),
(2.2, "n_air", {"start": 0.4, "grade": NIGHT}),
(2.2, "n_tractor", {"start": 0.6, "grade": NIGHT}),
(1.6, "n_left", {"start": 0.2, "grade": NIGHT}),
(0, "v_rhythm", {"start": 0.3, "grade": GOLD}),
until=60.58)
run(CARD[0], (0, "e_up", {"start": 0.2, "speed": 0.48, "grade": GOLD}), until=CARD[1])
def REACT(t):
return 0.35
TYPE = hook(["THE GRASS", "DOESN'T SLEEP"], 47.6, 52.6) + hook(["NEITHER", "DO WE"], 52.7, 58.9) + hook(["NIGHT SHIFT", "OVER"], 59.0, 60.5) + card()
SFX = [(52.4, clip("night_crickets_loop"), 0.4, 6.0), (CARD[0], clip("confetti"), 0.7)]

107
Tools/Trailer/space.py Normal file
View File

@ -0,0 +1,107 @@
"""
The game's sky stays daylight blue from orbit, so the orbital takes get a real one: the ball is keyed out, lit from one side
with a terminator and an atmosphere, and set against stars. py -I space.py rolls take take_k
"""
import os
import sys
import cv2
import numpy as np
root, src, dst = sys.argv[1:4]
front = len(sys.argv) > 4
W, H = 2560, 1440
os.makedirs(os.path.join(root, dst), exist_ok=True)
rng = np.random.default_rng(11)
# the stars: a field a little bigger than the frame that drifts
sky = np.zeros((H + 400, W + 400, 3), np.float32)
for n, size, lo, hi in ((9000, 1, 0.12, 0.5), (1300, 2, 0.35, 0.8), (130, 3, 0.7, 1.0)):
ys = rng.integers(0, sky.shape[0], n)
xs = rng.integers(0, sky.shape[1], n)
v = rng.uniform(lo, hi, n)
tint = rng.uniform(0.82, 1.0, (n, 3))
for y, x, a, c in zip(ys, xs, v, tint):
cv2.circle(sky, (int(x), int(y)), size - 1, (float(a * c[0]), float(a * c[1]), float(a * c[2])), -1, cv2.LINE_AA)
sky = cv2.GaussianBlur(sky, (0, 0), 0.8)
# a band of faint dust across it
y, x = np.mgrid[0:sky.shape[0], 0:sky.shape[1]].astype(np.float32)
band = np.exp(-(((x * 0.34 + y - 1200) / 340) ** 2))
noise = cv2.GaussianBlur(rng.random(sky.shape[:2], np.float32), (0, 0), 60)
noise = (noise - noise.min()) / (noise.max() - noise.min())
sky += (band * noise * 0.16)[..., None] * np.array([0.9, 0.55, 0.5], np.float32)
# what makes the front ragged, as if it were made of many crews
ragged = cv2.GaussianBlur(rng.random((H, W), np.float32), (0, 0), 7) + cv2.GaussianBlur(rng.random((H, W), np.float32), (0, 0), 30) * 2.2
ragged = (ragged - ragged.mean()) / ragged.std()
blot = cv2.GaussianBlur(rng.random((H, W), np.float32), (0, 0), 16)
blot = np.clip((blot - blot.mean()) / blot.std() * 0.5 + 0.5, 0, 1)
spot = None
light = np.array([-0.62, -0.42, 0.66], np.float32)
light /= np.linalg.norm(light)
files = sorted(f for f in os.listdir(os.path.join(root, src)) if f.endswith(".jpg"))
fit = None
for i, name in enumerate(files):
img = cv2.imread(os.path.join(root, src, name), cv2.IMREAD_COLOR).astype(np.float32) / 255
b, g, r = cv2.split(img)
mask = ((g > b * 1.03) | (r > b * 1.03)).astype(np.uint8) * 255
mask = cv2.morphologyEx(cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((5, 5), np.uint8)), cv2.MORPH_CLOSE, np.ones((9, 9), np.uint8))
n, labels, stats, _ = cv2.connectedComponentsWithStats(mask)
if n > 1:
mask = (labels == 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA]))).astype(np.uint8) * 255
edge = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0]
pts = max(edge, key=len)[:, 0, :].astype(np.float64)
pts = pts[(pts[:, 0] > 3) & (pts[:, 0] < W - 4) & (pts[:, 1] > 3) & (pts[:, 1] < H - 4)]
# a circle through the rim, least squares
A = np.c_[2 * pts, np.ones(len(pts))]
c = np.linalg.lstsq(A, (pts ** 2).sum(axis=1), rcond=None)[0]
cx, cy, rad = c[0], c[1], np.sqrt(c[2] + c[0] ** 2 + c[1] ** 2)
now = np.array([cx, cy, rad])
fit = now if fit is None else fit * 0.7 + now * 0.3
cx, cy, rad = fit
yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
nx, ny = (xx - cx) / rad, (yy - cy) / rad
rr = nx * nx + ny * ny
inside = np.clip((1 - np.sqrt(rr)) * rad / 2.0 + 0.5, 0, 1)
nz = np.sqrt(np.clip(1 - rr, 0, 1))
lit = np.clip(nx * light[0] + ny * light[1] + nz * light[2], 0, 1)
if front:
k = i / (len(files) - 1)
seen = (r > g * 0.92) & (rr < 0.8)
if seen.sum() > 300:
ys, xs = np.nonzero(seen)
now = np.array([(xs.mean() - cx) / rad, (ys.mean() - cy) / rad])
spot = now if spot is None else spot * 0.85 + now * 0.15
bx, by = spot if spot is not None else (0.0, 0.0)
bz = np.sqrt(max(0.0, 1 - bx * bx - by * by))
ang = np.arccos(np.clip(nx * bx + ny * by + nz * bz, -1, 1))
reach = 0.06 + 1.95 * (k * k * (3 - 2 * k))
edge = reach - ang + ragged * 0.022
cover = np.clip(edge / 0.012, 0, 1)[..., None]
lum = img.mean(axis=2, keepdims=True)
lum = lum * 0.3 + cv2.GaussianBlur(lum, (0, 0), 90)[..., None] * 0.7
tan = lum * (0.96 + blot[..., None] * 0.08) * np.array([0.56, 0.86, 1.3], np.float32)
img = img * (1 - cover) + tan * cover
# a soft terminator with a warm edge
day = np.clip(lit * 1.5, 0, 1) ** 0.75
warm = np.clip(1 - np.abs(lit - 0.1) / 0.16, 0, 1) * 0.5
surface = img * (day[..., None] * 1.28 + 0.012) + warm[..., None] * img * np.array([0.0, 0.25, 0.8], np.float32)
if front:
surface += (np.exp(-(edge / 0.018) ** 2) * (0.25 + day))[..., None] * np.array([0.25, 0.8, 1.0], np.float32) * 0.9
# the thin air at the rim, inside and out
rim = (1 - nz) ** 3.2 * np.clip(lit * 2.2 + 0.05, 0, 1)
surface += rim[..., None] * np.array([1.0, 0.72, 0.32], np.float32) * 0.85
out = np.maximum(np.sqrt(rr) - 1, 0) * rad
side = np.clip((nx * light[0] + ny * light[1]) / np.maximum(np.sqrt(rr), 1e-3) + 0.35, 0, 1)
halo = (np.exp(-out / (rad * 0.016)) * 0.7 + np.exp(-out / (rad * 0.07)) * 0.16) * side
dx = int(40 + i * 0.05)
back = sky[120:120 + H, dx:dx + W] + halo[..., None] * np.array([1.0, 0.7, 0.34], np.float32)
# the sun just out of frame
sun = 0.5 / (1 + ((xx + 300) ** 2 + (yy + 150) ** 2) / 420000)
back = back + sun[..., None] * np.array([0.8, 0.9, 1.0], np.float32)
frame = surface * inside[..., None] + back * (1 - inside[..., None])
cv2.imwrite(os.path.join(root, dst, name), (np.clip(frame, 0, 1) * 255).astype(np.uint8), [cv2.IMWRITE_JPEG_QUALITY, 96])
if i % 60 == 0:
print(name, f"centre {cx:.0f},{cy:.0f} radius {rad:.0f}", flush=True)

66
Tools/Trailer/splice.py Normal file
View File

@ -0,0 +1,66 @@
"""
Replaces a stretch of a finished render without encoding the rest again: the stretch is cut on keyframes, rendered anew and joined.
py -I splice.py edl.py film.mp4 out_from out_to seconds of the film
"""
import importlib.util
import os
import shutil
import subprocess
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
edl, film, lo, hi = sys.argv[1], sys.argv[2], float(sys.argv[3]), float(sys.argv[4])
spec = importlib.util.spec_from_file_location("edl", edl)
plan = importlib.util.module_from_spec(spec)
sys.modules["edl"] = plan
spec.loader.exec_module(plan)
def song(t):
"""The film's second t in the song's time, through the kept stretches."""
for a, b in plan.KEEP:
if t <= b - a:
return a + t
t -= b - a
raise ValueError("past the end of the song")
tmp = os.path.join(os.path.dirname(film), "splice")
shutil.rmtree(tmp, ignore_errors=True)
os.makedirs(tmp)
def run(*a):
return subprocess.run(a, check=True, capture_output=True, text=True).stdout
def frames(path):
return int(run("ffprobe", "-v", "error", "-select_streams", "v", "-count_packets", "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0", path).strip().strip(","))
keys = [float(x.strip(",")) for x in run("ffprobe", "-v", "error", "-select_streams", "v", "-skip_frame", "nokey", "-show_entries", "frame=pts_time", "-of", "csv=p=0", film).split()]
a = max(k for k in keys if k <= lo)
b = min(k for k in keys if k >= hi)
print("keyframes", a, b, flush=True)
part = os.path.join(tmp, "part.mp4")
here = os.path.dirname(os.path.abspath(__file__))
subprocess.run([sys.executable, "-I", os.path.join(here, "cut.py"), edl, part, f"{song(a) + 0.002:.3f}", f"{song(b) + 0.08:.3f}"], check=True, stdout=subprocess.DEVNULL)
run("ffmpeg", "-y", "-v", "error", "-i", film, "-map", "0:v", "-c", "copy", "-f", "segment", "-segment_times", f"{a - 0.004:.6f},{b - 0.004:.6f}", "-reset_timestamps", "1", os.path.join(tmp, "seg%d.mp4"))
partv = os.path.join(tmp, "partv.mp4")
# the render runs a little long so that the encoder's tail can't fall short
run("ffmpeg", "-y", "-v", "error", "-i", part, "-map", "0:v", "-c", "copy", "-frames:v", str(round((b - a) * 60)), partv)
seg = [os.path.join(tmp, f"seg{i}.mp4") for i in range(3)]
counts = [frames(p) for p in seg]
new = frames(partv)
print("frames", counts, "new", new, flush=True)
assert new == counts[1], "the new stretch must be as long as the old one"
listing = os.path.join(tmp, "list.txt")
with open(listing, "w", encoding="utf-8") as f:
for p in (seg[0], partv, seg[2]):
f.write("file '" + p.replace("\\", "/") + "'\n")
joined = os.path.join(tmp, "joined.mp4")
run("ffmpeg", "-y", "-v", "error", "-f", "concat", "-safe", "0", "-i", listing, "-i", film, "-map", "0:v", "-map", "1:a", "-c", "copy", "-movflags", "+faststart", joined)
assert frames(joined) == frames(film)
os.replace(joined, film)
shutil.rmtree(tmp)
print("done", flush=True)

324
Tools/Trailer/story.py Normal file
View File

@ -0,0 +1,324 @@
"""The story trailer: told the way the game opens. The Director's call from Earth in the real opening film, cut between the
phone in your hand and his face filling the frame; the planet; his assistant in your ear; then the game, with his calls
and her warnings over it, to the hundred percent and his joke about a second planet over the logo.
Every s_ take carries a sounds.txt from the game (frame, name, volume, pitch, metres off), so a shot brings its own voices
and effects with it, cut to exactly the stretch of the take it shows. The music bed is built here: silence under the call,
the game's music from the planet on, ducked under every line.
py -I cut.py story.py out.mp4 [from to]
"""
import os
import wave
import numpy as np
from cut import PROJECT, SR, Logo, Shot, Type, decode
from looks import AUDIO, GOLD, HOT, LOGO, NIGHT, PLAY, SPACE, clip # noqa: F401
ROLLS = os.path.join(PROJECT, r"Builds\Trailer\rolls3")
OUT = os.path.join(PROJECT, r"Builds\Trailer\story")
os.makedirs(OUT, exist_ok=True)
PUNCH, SHAKE, ABERRATE = 0.006, 1.2, 0.6
STUDIO = {"sat": 1.02, "contrast": 1.04, "gain": 1.0, "tint": (0, 0, 0)}
B = 60 / 79.5
# ───────────────────────── what the game heard ─────────────────────────
_logs = {}
def log(take):
base = take.split("@")[0]
if base not in _logs:
rows = []
path = os.path.join(ROLLS, base, "sounds.txt")
if os.path.exists(path):
for line in open(path, encoding="utf-8"):
p = line.rstrip("\n").split("\t")
if len(p) >= 5:
rows.append((int(p[0]) / 60.0, p[1], float(p[2].replace(",", ".")), float(p[4].replace(",", "."))))
_logs[base] = rows
return _logs[base]
def when(take, name, n=0):
hits = [t for t, nm, _, _ in log(take) if nm == name]
if len(hits) <= n:
raise SystemExit(f"{take}: no {name} #{n} in sounds.txt")
return hits[n]
_lengths = {}
def length(name):
if name not in _lengths:
with wave.open(clip(name)) as w:
_lengths[name] = w.getnframes() / w.getframerate()
return _lengths[name]
def voice(name):
return name.startswith("dir_") or name.startswith("asst_")
# ───────────────────────── laying shots ─────────────────────────
SHOTS = []
HEAR = [] # (at, take, from, seconds): that stretch of the take's sound, at that time
EXTRA = [] # sounds by hand: (at, clip path, gain[, seconds[, offset]])
now = 0.0
def put(take, start, secs, hear=True, sound=None, **kw):
"""The next shot: `secs` of `take` from `start` seconds in. Its own sound comes with it unless hear is False, or
sound=(take, from) brings another stretch instead."""
global now
SHOTS.append(Shot(take, now, now + secs, start=start, **kw))
if hear:
st, sf = sound if sound else (take, start)
HEAR.append((now, st, sf, secs))
now += secs
return now
def gap(secs):
global now
now += secs
# ───────────────────────── the cut ─────────────────────────
I, BOSS = "s_intro", "s_intro@s_boss"
RING = when(I, "phone_ring")
V = when(I, "dir_intro")
SPACE_AT = when(I, "space_rumble")
TAG = when(I, "dir_intro_tag")
# 1. the planks in the half dark, the phone ringing, coming up
put(I, RING - 1.6, V - (RING - 1.6), grade=PLAY)
# 2. the call: (from, to) in the line, and whose picture
CALL = [
(0.0, 2.32, I), # Listen up, you incompetent idiots!
(2.32, 6.2, BOSS), # EARTH IS OUT OF GRASS! NO GRASS!
(6.2, 9.2, I), # NOT A SINGLE DAMN BLADE!
(15.9, 20.2, BOSS), # And Earth needs EVERY. SINGLE. BLADE.
(20.2, 23.3, I), # I want it CUT! I want it PACKED!
(23.3, 25.95, BOSS), # And I want it SHIPPED BACK TO EARTH!
(25.95, 28.8, I), # I don't care if you have to use nail scissors!
(28.8, 33.0, BOSS), # NOW GET OUT THERE AND MOW THAT GODDAMN PLANET!
]
for a, b, who in CALL:
kw = {"grade": STUDIO if who == BOSS else PLAY}
if who == BOSS and a == 15.9:
kw["zoom"] = (1.0, 1.18)
put(who, V + a, b - a, **kw)
# 3. the phone goes, the head comes up, the cuts climb to the planet; his deadpan over it
put(I, V + 33.0, SPACE_AT - (V + 33.0), grade=PLAY)
MUSIC_AT = now
# the planet from orbit: the composited orbit take, with the film's own sound (the rumble, his "we take grass very seriously")
put("o_space_k", 1.0, TAG + length("dir_intro_tag") + 0.5 - SPACE_AT, sound=(I, SPACE_AT), grade=SPACE, zoom=(1.0, 1.05))
# 4. her hello: "Hi. I'm the Director's assistant. I'll be in your ear the whole time. He shouts. I explain."
# the film ends and she starts inside s_intro; s_after picks up 4 frames after s_intro's last
ASST = "s_after@s_asst"
A = when(I, "asst_hello")
AFTER = (3420 + 4) / 60.0
put(I, A - 0.3, 3.95, grade=PLAY) # her window in the corner of your view
put(BOSS, V + 3.0, 0.95, sound=(I, A + 4.62), grade=STUDIO) # He shouts. (over him shouting)
put(ASST, A + 6.05 - AFTER, 1.3, sound=(I, A + 6.05), grade=STUDIO) # I explain.
# 5. the game: the tools one after another, the crew
put("g_scissors", 0.3, B * 3, hear=False, grade=PLAY)
put("g_shears", 0.8, B * 2, hear=False, grade=PLAY)
put("g_sickle", 0.8, B * 2, hear=False, grade=PLAY)
put("g_scythe", 1.2, B * 3, hear=False, grade=PLAY)
put("g_wide", 1.5, B * 3, hear=False, grade=PLAY)
TOOLS_AT = SHOTS[-5].at
put("g_coop", 1.5, B * 4, hear=False, grade=PLAY)
put("v_sixteen", 0.9, B * 4, hear=False, grade=HOT)
COOP_AT = SHOTS[-2].at
# 6. belts: "Conveyor belts! Grass that moves BY ITSELF! ... This is what peak civilization looks like."
DB, DBB = "s_dir_belts", "s_dir_belts@s_boss"
VB = when(DB, "dir_belts")
put("k_belt", 0.6, 5.3, hear=False, sound=None, grade=HOT)
HEAR.append((SHOTS[-1].at, DB, VB - 0.1, 5.3))
put(DBB, VB + 6.3, 4.2, grade=STUDIO)
BELT_AT = SHOTS[-2].at
# 7. the combine: "A COMBINE HARVESTER?! (laughs) NOW we're talking! Earth's lawns will be green by Christmas!"
DC, DCB = "s_dir_combine", "s_dir_combine@s_boss"
VC = when(DC, "dir_combine")
put(DCB, VC - 0.1, 3.85, grade=STUDIO)
put("c_combine", 0.6, 2.4, hear=False, grade=HOT)
HEAR.append((SHOTS[-1].at, DC, VC + 3.75, 2.4))
put("c_combine_over", 1.0, 3.3, hear=False, grade=HOT)
HEAR.append((SHOTS[-1].at, DC, VC + 6.15, 3.3))
# 8. the weather: a twister over the meadow, the warning in your ear, and up you go
put("s_storm", 2.0, 3.6, hear=False, grade=HOT)
T0, TA = "s_thrown", "s_thrown@s_asst"
VT = when(T0, "asst_twister")
FLING = when(T0, "throw_whoosh")
VN = when(T0, "asst_thrown")
put(T0, VT - 0.2, 1.8, grade=PLAY) # Twister incoming!
put(T0, FLING - 1.6, VN - 0.1 - (FLING - 1.6), grade=PLAY) # it comes, and you go up
put(TA, VN - 0.1, length("asst_thrown") + 0.25, grade=STUDIO) # You got thrown by a twister. Noted.
STORM_AT = SHOTS[-4].at
# 9. the saucer, and him on the phone about it
U0, UB = "s_ufocall", "s_ufocall@s_boss"
VU = when(U0, "dir_ufo")
put("s_ufo", 4.0, 3.4, sound=(U0, VU - 1.65), grade=GOLD) # (the call connects) Was that a UFO?!
put(UB, VU + 2.6, 4.95, grade=STUDIO) # Listen to me. Do NOT let them take the grass.
put("s_ufo_top", 3.0, 3.1, hear=False, grade=GOLD)
HEAR.append((SHOTS[-1].at, U0, VU + 8.6, 3.1)) # THAT GRASS BELONGS TO EARTH!
UFO_AT = SHOTS[-3].at
# 10. everybody, everything, the whole ball
put("f_air", 0.6, B * 4, hear=False, grade=HOT)
put("n_line", 0.8, B * 3, hear=False, grade=NIGHT)
put("e_cut_k", 2.0, B * 5, hear=False, speed=1.6, zoom=(1.0, 1.05), grade=SPACE)
BIG_AT = SHOTS[-3].at
# 11. one hundred percent, and the joke over the logo
M, MB = "s_dir_m100", "s_dir_m100@s_boss"
VM = when(M, "dir_m100")
put(MB, VM - 0.1, 1.75, grade=STUDIO) # One hundred percent.
put(MB, VM + 4.1, 0.9, grade=STUDIO) # You did it.
put(MB, VM + 5.8, 3.4, grade=STUDIO, zoom=(1.0, 1.12)) # You magnificent idiots actually did it.
put("e_up", 0.2, 2.2, hear=False, speed=0.6, zoom=(1.02, 1.06), grade=dict(GOLD, sat=1.2))
HEAR.append((SHOTS[-1].at, M, VM + 10.4, 2.2)) # Earth has grass again!
LOGO_AT = now
put("e_up", 1.52, 9.0, hear=False, speed=0.45, zoom=(1.06, 1.12), grade=dict(GOLD, sat=1.2))
HEAR.append((LOGO_AT + 0.6, M, VM + 14.1, 3.05)) # Now. About the second planet.
HEAR.append((LOGO_AT + 4.4, M, VM + 19.0, 0.9)) # I'm kidding.
HEAR.append((LOGO_AT + 6.3, M, VM + 21.5, 2.2)) # Unless?
END = now
KEEP = [(0.0, END)]
# ───────────────────────── the sound ─────────────────────────
def gather():
pieces, sfx = [], []
for at, take, frm, secs in HEAR:
for ts, name, vol, dist in log(take):
if not os.path.exists(clip(name)):
continue
if voice(name):
L = length(name)
a, b = max(ts, frm), min(ts + L, frm + secs)
if b - a > 0.02:
pieces.append([at + a - frm, name, b - a, a - ts])
elif frm <= ts < frm + secs:
fall = 1.0 / (1.0 + dist / 10.0) if dist > 0 else 1.0
sfx.append((at + ts - frm, clip(name), min(1.0, vol) * fall * 0.85))
# a line laid in pieces that follow on in both picture and recording is one piece: no dip at the cut
pieces.sort(key=lambda p: (p[1], p[0]))
merged = []
for p in pieces:
q = merged[-1] if merged else None
if q and q[1] == p[1] and abs(q[0] + q[2] - p[0]) < 0.03 and abs(q[3] + q[2] - p[3]) < 0.03:
q[2] += p[2]
else:
merged.append(p)
voices = [(a, clip(n), 1.0, d, o) for a, n, d, o in merged]
return voices, sfx
VOICES, HEARD = gather()
# loops the takes don't log
EXTRA += [(STORM_AT, clip("twister_loop"), 0.5, 9.0), (STORM_AT, clip("wind_loop"), 0.35, 9.0), (STORM_AT + 0.4, clip("thunder"), 0.5)]
EXTRA += [(UFO_AT, clip("ufo_hum_loop"), 0.4, 12.0), (UFO_AT + 9.0, clip("ufo_beam_loop"), 0.35, 3.1)]
EXTRA += [(BELT_AT, clip("conveyor_loop"), 0.35, 5.3)] if os.path.exists(clip("conveyor_loop")) else []
EXTRA += [(TOOLS_AT + 0.3 + 0.6 * i, clip("snip"), 0.3) for i in range(4)]
EXTRA += [(TOOLS_AT + B * 5 + 0.3 + 0.75 * i, clip("scythe_swing_%d" % (i % 3 + 1)), 0.3) for i in range(8)]
EXTRA += [(TOOLS_AT, clip("grass_rustle_loop"), 0.3, B * 13)]
EXTRA += [(LOGO_AT, clip("milestone"), 0.6), (LOGO_AT + 0.1, clip("confetti"), 0.6)]
SFX = VOICES + HEARD + EXTRA
def bed():
"""Silence under the call; the music from the planet on, under every line ducked, out before the joke."""
n = int((END + 2) * SR)
out = np.zeros((n, 2), np.float32)
song = decode(clip("music_game_loop"))
i = int(MUSIC_AT * SR)
stop = int((LOGO_AT + 1.0) * SR)
k = 0
while i < stop:
m = min(len(song), stop - i)
out[i:i + m] += song[:m] * 0.8
i += m
k += 1
# rise in over the first second and a half, out over the last one
a = int(MUSIC_AT * SR)
ramp = int(1.5 * SR)
out[a:a + ramp] *= np.linspace(0.3, 1.0, ramp)[:, None]
tail = int(1.0 * SR)
out[stop - tail:stop] *= np.linspace(1.0, 0.0, tail)[:, None]
# under the voices
duck = np.ones(n, np.float32)
for at, _, _, d, _ in VOICES:
s, e = int((at - 0.15) * SR), int((at + d + 0.25) * SR)
duck[max(0, s):min(n, e)] = 0.32
kernel = int(0.2 * SR)
duck = np.convolve(duck, np.ones(kernel) / kernel, mode="same").astype(np.float32)
out *= duck[:, None]
path = os.path.join(OUT, "bed.wav")
raw = (np.clip(out, -1, 1) * 32767).astype(np.int16)
with wave.open(path, "wb") as f:
f.setnchannels(2)
f.setsampwidth(2)
f.setframerate(SR)
f.writeframes(raw.tobytes())
return path
TRACK = bed()
TRACK_GAIN = 1.0
def REACT(t):
return 0.0 if t < MUSIC_AT else 0.25
def BLACK(t):
if t < 0.6:
return 1 - t / 0.6
if t > END - 1.2:
return min(1.0, (t - (END - 1.2)) / 1.2)
return 0.0
FLASH = [(MUSIC_AT, 0.35), (LOGO_AT, 0.6)]
def caption(text, at, secs, size=72):
return Type(text, at + 0.1, at + secs - 0.1, size, y=0.86, how="rise")
TYPE = [
caption("START WITH NAIL SCISSORS", TOOLS_AT, B * 5),
caption("WORK YOUR WAY UP TO THE SCYTHE", TOOLS_AT + B * 7, B * 6),
caption("MOW WITH YOUR FRIENDS", COOP_AT, B * 4),
caption("UP TO 16 PLAYERS", COOP_AT + B * 4, B * 4),
caption("BUILD A GRASS FACTORY", BELT_AT, 5.3),
caption("WEATHER THAT FIGHTS BACK", STORM_AT, 3.6),
caption("A WHOLE PLANET TO CLEAR", BIG_AT + B * 7, B * 5),
Logo(LOGO, LOGO_AT, END, 1180, 0.4),
Type("WISHLIST NOW ON STEAM", LOGO_AT + 1.6, END, 76, y=0.76, how="rise"),
Type("CO-OP FOR 1 TO 16 PLAYERS", LOGO_AT + 2.4, END, 50, y=0.85, how="rise", colour=(226, 240, 200)),
]
if __name__ == "__main__":
for s in SHOTS:
print(f"{s.at:7.2f} {s.end - s.at:5.2f} {s.take:28s} from {s.start:6.2f}")
print("music at %.2f, logo at %.2f, end %.2f" % (MUSIC_AT, LOGO_AT, END))
for v in VOICES:
print("voice %7.2f %-14s %5.2f from %5.2f" % (v[0], os.path.basename(v[1]), v[3], v[4]))

58
Tools/Trailer/teaser.py Normal file
View File

@ -0,0 +1,58 @@
"""The teaser, forty seconds of the song: the cold open, straight into the first chorus, and the logo on the outro's hit."""
from cut import Logo, Type
from looks import BAR, GOLD, HOT, LOGO, PLAY, ROLLS, SPACE, clip, runner # noqa: F401
KEEP = [(2.2, 15.33), (22.9, 38.23), (159.0, 170.0)]
PUNCH, SHAKE, ABERRATE = 0.016, 4.0, 1.8
SHOTS = []
run = runner(SHOTS)
run(2.2,
(5.3, "o_space_k", {"speed": 1.5, "zoom": (1.0, 1.04), "grade": SPACE}),
(4.1, "o_dive", {"start": 0.9, "speed": 0.9, "grade": GOLD, "into": "whip"}),
(1.8, "o_skim", {"start": 2.2, "speed": 1.35, "grade": GOLD, "into": "whip"}),
(0, "o_giant", {"start": 0.6, "speed": 0.7, "grade": GOLD}),
until=15.33)
run(22.9,
(2.1, "c_swing_s", {"rate": 120, "start": 1.2, "speed": 0.5, "grade": HOT}),
(BAR, "g_scythe", {"start": 1.0, "grade": PLAY}),
(BAR, "c_combine_over", {"start": 1.34, "grade": HOT}),
(BAR, "v_sixteen", {"start": 1.2, "grade": HOT}),
(BAR, "k_grow", {"start": 3.0, "speed": 1.6, "grade": HOT}),
(BAR, "f_air", {"start": 0.6, "grade": HOT}),
(BAR, "c_top", {"start": 1.2, "grade": HOT}),
(0, "e_cut_k", {"start": 2.0, "speed": 2.6, "zoom": (1.0, 1.05), "grade": {"sat": 1.1, "contrast": 1.08, "tint": (0, 0, 0)}}),
until=38.23)
run(159.0, (0, "e_up", {"start": 0.2, "speed": 0.48, "zoom": (1.02, 1.08), "grade": {"sat": 1.2, "contrast": 1.12}}), until=170.0)
FLASH = [(22.9, 0.5), (159.0, 0.7)]
def REACT(t):
return 0.25 if t < 22.9 else 0.6 if t < 38.3 else 0.4
def BLACK(t):
if t < 2.7:
return 1 - (t - 2.2) / 0.5
if t > 168.6:
return min(1.0, (t - 168.6) / 1.2)
return 0.0
TYPE = [
Type("EARTH HAS RUN OUT OF GRASS", 5.0, 8.4, 84, y=0.2, how="rise"),
Type("THIS PLANET HAS TOO MUCH", 9.0, 12.4, 84, y=0.2, how="rise"),
Type("HERBARIA-7", 12.6, 15.3, 150, y=0.5, how="rise"),
Type("MOW IT!", 23.0, 24.95, 210, y=0.74, how="slam"),
Type("UP TO 16 PLAYERS", 28.74, 30.5, 120, y=0.8, how="slam"),
Type("BUILD IT", 30.6, 32.4, 150, y=0.8, how="slam"),
Type("DRIVE IT", 32.47, 34.3, 150, y=0.8, how="slam"),
Type("THE WHOLE PLANET", 36.2, 38.2, 150, how="slam"),
Type("WISHLIST NOW ON STEAM", 161.0, 170.0, 76, y=0.76, how="rise"),
Type("CO-OP FOR 1 TO 16 PLAYERS", 162.0, 170.0, 50, y=0.85, how="rise", colour=(226, 240, 200)),
Logo(LOGO, 159.0, 170.0, 1180, 0.4),
]
SFX = [(22.9, clip("scythe_swing_1"), 0.5), (159.0, clip("confetti"), 0.7)]

29
Tools/Trailer/vertical.py Normal file
View File

@ -0,0 +1,29 @@
"""What the upright clips for Shorts and Reels share: the frame, a hook in the top third, a label low down, and the
same six-second end card on the song's last hit."""
from cut import Logo, Type
from looks import LOGO
SIZE = (1080, 1920)
PUNCH, SHAKE, ABERRATE = 0.016, 4.0, 1.6
CARD = (159.0, 165.0)
def hook(lines, at, end, size=96, y=0.13, how="slam"):
"""Up to three short lines, stacked from y down."""
return [Type(text, at, end, size, y=y + i * size * 1.05 / 1920, how=how) for i, text in enumerate(lines)]
def label(text, at, end, size=104, y=0.74):
return Type(text, at, end, size, y=y, how="slam")
def card():
a, b = CARD
return [Logo(LOGO, a, b, 940, 0.4),
Type("WISHLIST ON STEAM", a + 0.6, b, 84, y=0.6, how="rise"),
Type("CO-OP FOR 1 TO 16 PLAYERS", a + 1.0, b, 54, y=0.66, how="rise", colour=(226, 240, 200))]
def BLACK(t):
"""In from black over a quarter second, out over the last second."""
return 0.0 if t < CARD[1] - 1.0 else min(1.0, (t - CARD[1] + 1.0) / 0.9)

236
Tools/Trailer/voices.py Normal file
View File

@ -0,0 +1,236 @@
"""Every spoken line in the scripted trailer, made whole and then cut: the crew's evening as one Eleven v4 dialogue (four
voices in one take, so they answer each other), and the Director's and the assistant's calls each read through in one go
as in the game, with the trailer's phrases cut out of them. A phrase read inside its speech sounds like it; read alone it
sounds like a line being read.
Where each phrase falls in a take is found by listening (faster-whisper's word timings, matched in order against the
script): the timings the API sends back drift too far to cut by. Whole takes are kept in Tools/audio/eleven_raw/whole_*.wav (+ .json). The crew's lines then go
through a headset (ArtSource/Trailer/crew), the Director's and the assistant's stay clean (ArtSource/Trailer/boss).
ELEVEN_KEY_FILE=... py -I voices.py [again] ("again" makes the whole takes anew)
"""
import base64
import difflib
import json
import os
import re
import subprocess
import sys
import numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.normpath(os.path.join(HERE, "..", ".."))
sys.path.insert(0, os.path.join(ROOT, "Tools", "audio"))
import eleven # noqa: E402
RAW = os.path.join(ROOT, "Tools", "audio", "eleven_raw")
CREW = os.path.join(ROOT, "ArtSource", "Trailer", "crew")
BOSS = os.path.join(ROOT, "ArtSource", "Trailer", "boss")
MODEL = "eleven_v4"
RATE = 24000
FO, GR, EN, TO = "rPMkKgdwgIwqv4fXgR6N", "Q0Co3mt4NHZCSmKqCMMo", "sWsBiVcjjowceAScTnu3", "i9SZdx1xJqqryIiaFdmN"
DIRECTOR, ASSISTANT = "1BfrkuYXmEwp8AWqSLWk", "fgDJOgmENIR82PueQrVs"
GA, TA = "[strong Indian accent] ", "[strong Singaporean accent] "
# the evening, in the order the trailer tells it
EVENING = [
("to_nails", TO, TA + "[deadpan] [quietly] ...these are nail scissors."),
("fo_rows", FO, "[confident] Okay team. Rows. Straight rows."),
("gr_big", GR, GA + "[curious] Wait... how big is this planet?"),
("to_sky", TO, TA + "[awed] [softly] Guys... look at the sky."),
("fo_hand", FO, "[urgent] Hand it in, hand it in!"),
("gr_catch", GR, GA + "[mischievously] Catch!"),
("fo_back", FO, "[excited] [laughs] We are SO back."),
("en_pickup", EN, "[suspicious] Who took the pickup?"),
("gr_nobody", GR, GA + "[shouting] [laughing] Nobody!"),
("en_works", EN, "[proud] It works. It actually works."),
("en_mostly", EN, "[sighs] ...it mostly works."),
("to_rain", TO, TA + "[worried] Is the rain... eating the grass?"),
("fo_save", FO, "[shouting] The bundles! Save the bundles!"),
("gr_goin", GR, GA + "[excited] [shouting] I'm going in!"),
("to_did", TO, TA + "[amazed] [softly] We did that?"),
("fo_did", FO, "[proud] [warmly] We did that."),
("gr_keep", GR, GA + "[hopeful] Can we keep the combine?"),
]
# their calls, whole, from the game's own scripts; then which phrases the trailer takes out of each
LINES = json.load(open(os.path.join(ROOT, "Tools", "director", "lines.json"), encoding="utf-8"))["lines"]
ASST = json.load(open(os.path.join(ROOT, "Tools", "director", "assistant_lines.json"), encoding="utf-8"))["lines"]
SPEECHES = {
"intro": (DIRECTOR, LINES["dir_intro"], [("dir_earth", "EARTH IS OUT OF GRASS! NO GRASS!"),
("dir_scissors", "I don't care if you have to use nail scissors!")]),
"m100": (DIRECTOR, LINES["dir_m100"], [("dir_did", "You magnificent idiots actually did it.")]),
"thrown": (ASSISTANT, ASST["asst_thrown"], [("asst_noted", "You got thrown by a twister. [pause] Noted.")]),
}
HEADSET = ("highpass=f=260,lowpass=f=4200,acompressor=threshold=-20dB:ratio=4:attack=5:release=60:makeup=4,"
"aecho=0.8:0.5:12:0.08,volume=-1dB,alimiter=limit=0.89")
CLEAN = "apad=pad_dur=0.25,loudnorm=I=-16:TP=-1.5:LRA=11"
def fetch(name, path, payload):
"""A take with timings, kept; made again only when asked."""
wav, meta = os.path.join(RAW, f"whole_{name}.wav"), os.path.join(RAW, f"whole_{name}.json")
if os.path.exists(meta) and "again" not in sys.argv:
return np.frombuffer(open_pcm(wav), np.int16).astype(np.float32) / 32768, json.load(open(meta))
d = json.loads(eleven.post(path, payload, accept="application/json"))
pcm = base64.b64decode(d.pop("audio_base64"))
os.makedirs(RAW, exist_ok=True)
eleven.save_pcm(wav, pcm, channels=1, rate=RATE)
json.dump(d, open(meta, "w"), indent=1)
print("made", os.path.basename(wav), "%.1fs" % (len(pcm) / 2 / RATE))
return np.frombuffer(pcm, np.int16).astype(np.float32) / 32768, d
def open_pcm(path):
import wave
with wave.open(path) as w:
return w.readframes(w.getnframes())
def tighten(x, gap=0.3):
"""Shorten any silence inside a phrase to `gap` seconds: a pause the tag asked for, not a hole."""
hop = RATE // 100
e = np.array([np.sqrt(np.mean(x[i:i + hop] ** 2)) for i in range(0, len(x) - hop, hop)])
quiet = e < max(1e-4, 0.03 * e.max())
keep = np.ones(len(x), bool)
i = 0
while i < len(quiet):
if quiet[i]:
j = i
while j < len(quiet) and quiet[j]:
j += 1
if 0 < i and j < len(quiet) and (j - i) * hop > gap * RATE:
keep[i * hop + int(gap / 2 * RATE):j * hop - int(gap / 2 * RATE)] = False
i = j
else:
i += 1
return x[keep]
def write(x, out, chain):
"""Trim the ends, run the chain, 48 kHz mono."""
trim = "silenceremove=start_periods=1:start_threshold=-40dB,areverse,silenceremove=start_periods=1:start_threshold=-40dB,areverse"
pcm = (np.clip(x, -1, 1) * 32767).astype(np.int16).tobytes()
subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "s16le", "-ar", str(RATE), "-ac", "1", "-i", "-",
"-af", trim + "," + chain, "-ar", "48000", "-ac", "1", out], input=pcm, check=True)
def words(text):
"""The words a line says, without its tags, as whisper would spell them."""
text = re.sub(r"\[[^\]]*\]", " ", text)
return [w for w in re.sub(r"[^a-z' ]", " ", text.lower()).split() if w]
_heard = None
def heard(x):
"""Every word in a take, with when it was said (faster-whisper on the CPU)."""
global _heard
from faster_whisper import WhisperModel
if _heard is None:
_heard = WhisperModel("small.en", device="cpu", compute_type="int8")
sixteen = np.interp(np.arange(0, len(x), RATE / 16000), np.arange(len(x)), x).astype(np.float32)
segs, _ = _heard.transcribe(sixteen, beam_size=5, word_timestamps=True)
out = []
for sg in segs:
for w in sg.words:
for part in words(w.word):
out.append((part, w.start, w.end))
return out
def place(x, lines):
"""Where each line (a list of words) was said in the take: matched in order against what whisper heard. The
timings the API sends with a dialogue only say which input is which, not where its speech is."""
got = heard(x)
flat, owner = [], []
for k, ws in enumerate(lines):
flat += ws
owner += [k] * len(ws)
sm = difflib.SequenceMatcher(None, flat, [g[0] for g in got], autojunk=False)
hit = {}
for a, b, n in sm.get_matching_blocks():
for i in range(n):
k = owner[a + i]
s, e = got[b + i][1], got[b + i][2]
lo, hi = hit.get(k, (s, e))
hit[k] = (min(lo, s), max(hi, e))
missing = [k for k in range(len(lines)) if k not in hit]
if missing:
raise SystemExit("not heard: " + ", ".join(" ".join(lines[k]) for k in missing))
return [hit[k] for k in range(len(lines))]
def gap(x, a, b):
"""The quietest moment between a and b seconds: the middle of the longest near-silence, else the softest 10 ms.
Whisper's word ends run late and its starts early, so lines are parted here, not at its timings."""
hop = RATE // 100
lo, hi = int(max(0, a) * RATE), int(min(len(x) / RATE, b) * RATE)
e = np.array([np.sqrt(np.mean(x[i:i + hop] ** 2)) + 1e-9 for i in range(lo, max(lo + 1, hi - hop), hop)])
db = 20 * np.log10(e)
quiet = db < -50
best, run, start = (0, 0), 0, 0
for i, q in enumerate(quiet):
if q:
if run == 0:
start = i
run += 1
if run > best[0]:
best = (run, start)
else:
run = 0
k = best[1] + best[0] // 2 if best[0] else int(np.argmin(db))
return (lo + k * hop) / RATE
def cut(x, spans, k):
"""Line k's stretch: from the quiet before it to the quiet after it (the ends are trimmed to the voice afterwards)."""
a, b = spans[k]
lo = gap(x, spans[k - 1][1] - 0.3, a + 0.2) if k > 0 else 0.0
hi = gap(x, b - 0.2, spans[k + 1][0] + 0.6) if k + 1 < len(spans) else len(x) / RATE
return x[int(lo * RATE):int(hi * RATE)]
def evening():
x, _ = fetch("evening", f"/text-to-dialogue/with-timestamps?output_format=pcm_{RATE}",
{"model_id": MODEL, "inputs": [{"text": t, "voice_id": v} for _, v, t in EVENING]})
spans = place(x, [words(t) for _, _, t in EVENING])
os.makedirs(CREW, exist_ok=True)
for k, (name, _, _) in enumerate(EVENING):
write(tighten(cut(x, spans, k)), os.path.join(CREW, name + ".wav"), HEADSET)
print(f"{name:12s} {spans[k][0]:6.2f}-{spans[k][1]:6.2f}")
def speeches():
os.makedirs(BOSS, exist_ok=True)
for name, (voice, text, cuts) in SPEECHES.items():
x, _ = fetch(name, f"/text-to-speech/{voice}/with-timestamps?output_format=pcm_{RATE}",
{"model_id": MODEL, "text": text, "voice_settings": {"stability": 0.5}})
# the whole speech in sentences, so each phrase is matched where it really falls
parts, which = [], {}
rest = text
for out, phrase in cuts:
i = rest.find(phrase)
if i < 0:
raise SystemExit(f"{name}: no '{phrase}' in its script")
if words(rest[:i]):
parts.append(words(rest[:i]))
which[out] = len(parts)
parts.append(words(phrase))
rest = rest[i + len(phrase):]
if words(rest):
parts.append(words(rest))
spans = place(x, parts)
for out, _ in cuts:
k = which[out]
write(tighten(cut(x, spans, k)), os.path.join(BOSS, out + ".wav"), CLEAN)
print(f"{out:12s} {spans[k][0]:6.2f}-{spans[k][1]:6.2f}")
if __name__ == "__main__":
evening()
speeches()