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:
413
Tools/Trailer/cut.py
Normal file
413
Tools/Trailer/cut.py
Normal 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)
|
||||
Reference in New Issue
Block a user