diff --git a/.gitignore b/.gitignore index c25e699..b4e5e2f 100644 --- a/.gitignore +++ b/.gitignore @@ -44,3 +44,6 @@ hyperate-api-key.txt # Internal concept draft, not part of the public repo HypeBlock_Konzept.pdf + +# ElevenLabs API key for the trailer voice-over (secret) +elevenlabs-api-key.txt diff --git a/CLAUDE.md b/CLAUDE.md index 1673549..de65a3a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -26,6 +26,22 @@ The user speaks German; answer in German. - Check API names with `javap` against the jars in `.gradle/loom-cache/minecraftMaven/` and the Fabric API module jars in `~/.gradle/caches/modules-2/files-2.1/net.fabricmc.fabric-api/`. +## Trailer (`tools/trailer/`) + +- `HYPEBLOCK_TRAILER=1 ./gradlew runClientGameTest` runs `TrailerRecorder`: camera flights through the + sample world at 30 fps (1920x1080), one shot per mp4 in `build/run/trailer/shots/` + (`HYPEBLOCK_TRAILER_SHOTS=bridge,...` redoes single shots). The server is frozen and stepped one tick + per recorded tick (`/tick freeze` + `/tick step 1`) and the BPM is refreshed server-side every tick, + otherwise countdowns run ~4x too fast and `HeartRates` (wall-clock ageing) goes OFFLINE. + PNG frames are piped straight into ffmpeg (little free disk space on this Mac). +- Python (numpy, pillow, scipy; a venv is enough): `render.py --lang en|de` (edit, Minecraft-style + transitions, tooltips/toasts in the game font from the client jar), `voiceover.py --lang en|de` + (ElevenLabs, voice Laura `5Aahq892EEb6MdNwMM3p` via `ELEVEN_VOICE_ID`, `ELEVEN_MODEL=eleven_v4`, + free tier: mp3_44100_128 only), `mix.py --lang en|de` (synthesised score, SFX, VO, ducking, mux) → + `build/trailer/HypeBlock-Trailer[-de].mp4`. VO lines and cue times: `script.py`; event times in + the footage (door/bridge open): constants at the top of `render.py`. +- ElevenLabs key: `elevenlabs-api-key.txt` in the repo root (git-ignored, starts with `sk_`). + ## HypeRate API key (secret) - Never commit it. Locally: `hyperate-api-key.txt` in the repo root (git-ignored); CI: secret diff --git a/CURSEFORGE.md b/CURSEFORGE.md new file mode 100644 index 0000000..dc4b0c4 --- /dev/null +++ b/CURSEFORGE.md @@ -0,0 +1,130 @@ +# CurseForge listing + +Texts and settings for https://www.curseforge.com/minecraft (Mods). Create the project on +https://authors.curseforge.com/ → **Create Project** → Minecraft → Mods. Upload the jar from the +GitHub release (built by CI with the API key from the repository secret), not a local build without +`hyperate-api-key.txt`. + +## Project settings + +| Field | Value | +| --- | --- | +| Name | HypeBlock – Real Heart Rate Redstone | +| Summary (max. ~200 chars) | Your real heart rate in Minecraft: a pulse in your HUD and a HypeBlock that turns heart rates into redstone. Doors that open when you're calm, traps when you panic. Powered by HypeRate. | +| Main category | Redstone | +| Further categories | Utility & QoL (not "Miscellaneous": CurseForge rejects it for mods, "425 is not a valid Game Category For ClassId 6") | +| License | MIT | +| Source | https://github.com/HypeRate/HypeBlock | +| Issues | https://github.com/HypeRate/HypeBlock/issues | +| Website | https://minecraft.hyperate.io/ | +| Logo | `site/assets/logo.png` (400×400, the HypeBlock face) | +| Screenshots | `docs/screenshots/` in this order: `heartbeat`, `strength`, `calm-door`, `bridge-warning`, `bridge-open`, `command-block`, `settings` (captions: see below) | +| Video | the trailer on YouTube, once it is uploaded | + +## File upload + +| Field | Value | +| --- | --- | +| File | `hypeblock-0.1.0.jar` from https://github.com/HypeRate/HypeBlock/releases/tag/v0.1.0 | +| Display name | `HypeBlock 0.1.0 (Fabric 26.3)` | +| Release type | Beta for 0.x, Release from 1.0 | +| Game version | 26.3 | +| Mod loader | Fabric | +| Java | 25 | +| Environment | Client and Server (both sides need it for the HypeBlock; the HUD works on its own) | +| Related projects | Fabric API: **Required dependency** | +| Additional file | `HypeBlock-Showcase-world.zip` (sample world), as an additional file of the jar | + +Changelog for 0.1.0: + +``` +First beta. +• Heart rate tile in the HUD, live from HypeRate (/hr ) +• The HypeBlock: threshold, signal strength and heartbeat outputs, owner or group (average/highest), delay +• Join/leave per block, owner and operators manage settings and participants +• /hypeblock bpm and /hypeblock value for command blocks and data packs +• English and German +``` + +## Screenshot captions + +| File | Caption | +| --- | --- | +| heartbeat | A heart of redstone lamps beating with your real pulse | +| strength | Signal strength: the higher your pulse, the more lamps light up | +| calm-door | The calm door only opens after five seconds below 80 BPM | +| bridge-warning | HypeBridge: over 110 BPM the warning lamp goes on … | +| bridge-open | … and after five seconds over 110 the bridge opens above the lava | +| command-block | For map makers: every player's BPM in the scoreboard | +| settings | Settings: source, group value, output, threshold, delay, participants | + +## Description + +``` +❤️ HypeBlock brings your REAL heart rate into Minecraft. + +Your pulse beats in your HUD. Place a HypeBlock and it turns heart rates into redstone: +lamps that blink with your heartbeat, doors that only open when you're calm, +traps that go off when the whole group panics. + +━━━━━━━━━━━━━━━━━━━━ +✨ FEATURES +━━━━━━━━━━━━━━━━━━━━ +❤️ Heart rate HUD: a beating heart with your live BPM in any corner of the screen +🟥 The HypeBlock: right-click it, choose a rule, done. No redstone knowledge needed +🎚️ Three outputs: + • Threshold: power 15 when the pulse is above or below a value (optional delay in seconds) + • Signal strength: power 1-15 across a BPM range (e.g. 60-160) + • Heartbeat: a redstone pulse on every beat +👥 Owner only, or a group: everyone who joins the block counts (average or highest pulse) +🔒 Nobody can sign you up: players join and leave a HypeBlock themselves +🛠️ For map makers: /hypeblock bpm and /hypeblock value return the BPM as a command result +🌍 Sample world with five stations to try everything (heartbeat heart, signal bar, calm door, HypeBridge, scoreboard) +🇬🇧 🇩🇪 English and German + +━━━━━━━━━━━━━━━━━━━━ +🛠️ INSTALL +━━━━━━━━━━━━━━━━━━━━ +1. Install with the CurseForge app (Fabric API comes along automatically) + or put the jar and Fabric API into your mods folder +2. Start HypeRate on your smartwatch, phone or chest strap +3. In Minecraft press T and type: /hr YOUR-HYPERATE-ID + Your heart rate appears in the top left corner. That's it. +4. Craft a HypeBlock (iron ingots in the corners, redstone on the sides, a comparator in the middle) + or take it from the Redstone Blocks tab in creative, then right-click it + +⚠️ Multiplayer: the server needs HypeBlock too, and every player who wants to share a heart rate. +Same network: open your world to LAN and your friends join under Multiplayer. + +❤️ HypeRate: https://www.hyperate.io/ +🌐 Website: https://minecraft.hyperate.io/ +💻 Source code: https://github.com/HypeRate/HypeBlock + +━━━━━━━━━━━━━━━━━━━━ +⌨️ COMMANDS +━━━━━━━━━━━━━━━━━━━━ +• /hr YOUR-ID: connect (saved for next time) • /hr: status • /hr off: disconnect +• /hr fake 120 / /hr fake off: test value without a sensor +• /hr share on|off: share your heart rate with the server (default: on) +• /hr hud on|off|top_left|top_right|bottom_left|bottom_right +• /hypeblock list: who shares a heart rate right now + +━━━━━━━━━━━━━━━━━━━━ +🧩 COMPATIBILITY +━━━━━━━━━━━━━━━━━━━━ +Minecraft Java 26.3, Fabric Loader 0.20.1+, Fabric API, Java 25. +Heart rates are only kept in memory while you're online, nothing is saved to disk. + +HypeBlock is a fan-made mod and not affiliated with or endorsed by Mojang Studios or Microsoft. +``` + +## Upload checklist + +1. Raise `version` in `gradle.properties` (first upload: 0.1.0 as is) +2. Tag `v` on `main` and push it; CI builds the jar with the API key from the repository + secret `HYPERATE_API_KEY` and attaches it to the GitHub release. Upload that jar. +3. Raise the version on the website: `grep -rn 0.1.0 site/` lists every place +4. Test the jar once in a clean CurseForge profile (26.3, Fabric) +5. Upload it with the changelog, game version 26.3, loader Fabric, release type Beta, + Fabric API as required dependency, the sample world as additional file +6. CurseForge reviews new projects by hand (usually a few days) before the page goes live diff --git a/site/ai/service.json b/site/ai/service.json index 23d5ff5..e5ddab7 100644 --- a/site/ai/service.json +++ b/site/ai/service.json @@ -24,6 +24,6 @@ ], "pricing": "free", "license": "MIT", - "download": "https://github.com/HypeRate/HypeBlock/releases/latest", + "download": "https://github.com/HypeRate/HypeBlock/releases", "source": "https://github.com/HypeRate/HypeBlock" } \ No newline at end of file diff --git a/site/ai/summary.json b/site/ai/summary.json index 4f928b6..d86d573 100644 --- a/site/ai/summary.json +++ b/site/ai/summary.json @@ -15,7 +15,7 @@ "de" ], "links": { - "download": "https://github.com/HypeRate/HypeBlock/releases/latest", + "download": "https://github.com/HypeRate/HypeBlock/releases", "source": "https://github.com/HypeRate/HypeBlock", "llms": "https://minecraft.hyperate.io/llms.txt" } diff --git a/site/assets/trailer-de.jpg b/site/assets/trailer-de.jpg new file mode 100644 index 0000000..c599fea Binary files /dev/null and b/site/assets/trailer-de.jpg differ diff --git a/site/assets/trailer.jpg b/site/assets/trailer.jpg new file mode 100644 index 0000000..e6b44bb Binary files /dev/null and b/site/assets/trailer.jpg differ diff --git a/site/index.html b/site/index.html index f6433a9..a4beb36 100644 --- a/site/index.html +++ b/site/index.html @@ -67,7 +67,7 @@ "operatingSystem": "Windows, macOS, Linux (Minecraft Java Edition)", "softwareVersion": "0.1.0", "license": "https://opensource.org/licenses/MIT", - "downloadUrl": "https://github.com/HypeRate/HypeBlock/releases/latest", + "downloadUrl": "https://github.com/HypeRate/HypeBlock/releases", "codeRepository": "https://github.com/HypeRate/HypeBlock", "softwareRequirements": "Minecraft Java Edition 26.3, Fabric Loader 0.20.1 or newer, Fabric API, HypeRate app on a smartwatch, phone or chest strap", "featureList": [ @@ -90,7 +90,20 @@ "author": { "@id": "https://www.hyperate.io/#organization" }, "publisher": { "@id": "https://www.hyperate.io/#organization" }, "isAccessibleForFree": true, - "sameAs": ["https://github.com/HypeRate/HypeBlock"] + "sameAs": ["https://github.com/HypeRate/HypeBlock"], + "subjectOf": { "@id": "https://minecraft.hyperate.io/#trailer" } + }, + { + "@type": "VideoObject", + "@id": "https://minecraft.hyperate.io/#trailer", + "name": "HypeBlock – Your REAL Heart Rate in Minecraft | Fabric Mod Trailer", + "description": "Trailer of the HypeBlock mod: the real heart rate from HypeRate in the Minecraft HUD and as redstone (heartbeat, signal strength, calm door, HypeBridge, command blocks), recorded in the HypeBlock Showcase sample world.", + "thumbnailUrl": "https://minecraft.hyperate.io/assets/trailer.jpg", + "uploadDate": "2026-12-01", + "duration": "PT2M18S", + "contentUrl": "https://youtu.be/t0Yt1Q8s9jE", + "embedUrl": "https://www.youtube-nocookie.com/embed/t0Yt1Q8s9jE", + "inLanguage": "en" }, { "@type": "FAQPage", @@ -308,6 +321,22 @@ .btn.soon:hover { transform: none; } .hero-note { margin-top: 18px; color: var(--dim); font-size: 15px; } + /* ---------- Trailer (YouTube loads only after a click) ---------- */ + .video { padding: 8px; max-width: 960px; margin: 0 auto; } + .yt { display: block; position: relative; width: 100%; aspect-ratio: 16 / 9; padding: 0; border: 0; background: #000; cursor: pointer; overflow: hidden; } + .yt img { width: 100%; height: 100%; object-fit: cover; transition: transform .3s; } + .yt:hover img { transform: scale(1.02); } + .yt .play { + position: absolute; left: 50%; top: 83%; font-size: clamp(9px, 1.5vw, 16px); width: 7em; height: 4.9em; transform: translate(-50%, -50%); + background: var(--redstone); border: 3px solid #000; + box-shadow: inset 3px 3px 0 rgba(255,255,255,.35), inset -3px -4px 0 rgba(0,0,0,.35), 0 5px 0 #000; + } + .yt .play::after { content: ""; position: absolute; left: 2.6em; top: 1.3em; border-style: solid; border-width: .95em 0 .95em 1.6em; border-color: transparent transparent transparent #fff; } + .yt:hover .play { background: #ff5566; } + .yt iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; } + .yt-note { text-align: center; color: var(--dim); font-size: 14px; margin: 10px 0 2px; } + .yt-note a { color: var(--soft); } + /* ---------- Sections ---------- */ section { padding: 90px 18px; position: relative; } section.alt { background: linear-gradient(180deg, rgba(255,255,255,.02), rgba(255,255,255,.035)); border-top: 3px solid #000; border-bottom: 3px solid #000; } @@ -561,7 +590,8 @@

HypeBlockYour heartbeat
runs Minecraft.

A free mod by HypeRate: see your real heart rate in the game and turn it into redstone. Lamps that beat with you, doors that only open when you're calm, bridges that drop when your squad panics.

@@ -577,6 +607,20 @@

HypeBlock0 €free and open source (MIT) +
+
+

See it in action

+

Two minutes in the HypeBlock Showcase world: the heart rate HUD, every output, the calm door and the HypeBridge with a real countdown.

+
+ +
+

The video loads from YouTube (privacy-enhanced mode) when you click play. Watch on YouTube

+
+
+

Wire up your heart

@@ -766,7 +810,7 @@

HypeB
  • Command block scoreboard
  • Unpack the ZIP into your saves folder.

    @@ -794,7 +838,7 @@

    Questions

    Build something that feels you.

    @@ -840,7 +884,11 @@

    About HypeBlock

    "nav.expert": "Experten-Modus", "nav.about": "Über uns", "hero.title1": "Dein Herzschlag", "hero.title2": "steuert Minecraft.", "hero.lead": "Eine kostenlose Mod von HypeRate: Sieh deinen echten Puls im Spiel und mach Redstone daraus. Lampen, die mit dir schlagen, Türen, die nur aufgehen, wenn du ruhig bist, Brücken, die nachgeben, wenn dein Team in Panik gerät.", - "hero.download": "Download", "hero.world": "Beispielwelt", "hero.soon": "bald", + "hero.download": "Download", "hero.world": "Beispielwelt", "hero.soon": "bald", "hero.trailer": "Trailer", + "trailer.title": "So sieht es aus", + "trailer.lead": "Zwei Minuten in der Beispielwelt HypeBlock Showcase: Puls im HUD, alle Ausgaben, die Ruhe-Tür und die HypeBridge mit echtem Countdown.", + "trailer.note": "Das Video wird erst beim Klick auf Play von YouTube geladen (erweiterter Datenschutzmodus).", + "trailer.open": "Auf YouTube ansehen", "hero.note": "Kostenlos · Minecraft Java 26.3 · Fabric · Einzelspieler & Multiplayer", "n1": "Ausgaben: Schwellwert, Signalstärke, Herzschlag", "n2": "Redstone-Signal, direkt aus deinem Puls", @@ -966,6 +1014,8 @@

    About HypeBlock

    function setLang(l) { lang = l; document.documentElement.lang = l; + var thumb = document.querySelector("#ytPlay img"); + if (thumb) thumb.src = l === "de" ? "assets/trailer-de.jpg" : "assets/trailer.jpg"; document.querySelectorAll("[data-i18n]").forEach(function (el) { var key = el.getAttribute("data-i18n"); var text = l === "en" ? original[key] : T.de[key]; @@ -1184,6 +1234,22 @@

    About HypeBlock

    addEventListener("scroll", function () { tile.classList.toggle("show", scrollY > innerHeight * 0.6); }, { passive: true }); // ---------- Reveal on scroll ---------- + // ---------- Trailer: load the YouTube player only after a click ---------- + var yt = document.getElementById("ytPlay"); + if (yt) yt.addEventListener("click", function () { + var f = document.createElement("iframe"); + f.src = "https://www.youtube-nocookie.com/embed/t0Yt1Q8s9jE?autoplay=1&rel=0&playsinline=1"; + f.title = "HypeBlock trailer"; + f.allow = "autoplay; encrypted-media; picture-in-picture; fullscreen"; + f.allowFullscreen = true; + yt.replaceChildren(f); + yt.style.cursor = "default"; + // If a consent blocker swallowed the player, open YouTube instead + setTimeout(function () { + if (!/youtube/.test(f.getAttribute("src") || "")) window.open("https://youtu.be/t0Yt1Q8s9jE", "_blank", "noopener"); + }, 1500); + }, { once: true }); + if ("IntersectionObserver" in window && !reduce) { var io = new IntersectionObserver(function (es) { es.forEach(function (e) { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } }); }, { threshold: 0.12 }); document.querySelectorAll(".reveal").forEach(function (n) { io.observe(n); }); diff --git a/site/llms.txt b/site/llms.txt index 25198a9..5f9ff70 100644 --- a/site/llms.txt +++ b/site/llms.txt @@ -21,7 +21,7 @@ HypeBlock is made by [HypeRate](https://www.hyperate.io/), a live heart rate pla ## Links - [Website](https://minecraft.hyperate.io/): overview, interactive HypeBlock demo, build ideas, expert section, install guide, FAQ -- [Download (latest release)](https://github.com/HypeRate/HypeBlock/releases/latest) +- [Download (releases)](https://github.com/HypeRate/HypeBlock/releases) - [Source code on GitHub](https://github.com/HypeRate/HypeBlock) - [Release feed](https://github.com/HypeRate/HypeBlock/releases.atom) - [HypeRate](https://www.hyperate.io/) @@ -48,3 +48,7 @@ Only your current BPM, while you are online. The server keeps it in memory and n ### Is it free? Yes. HypeBlock costs 0 € and is open source under the MIT license. The heart rate comes from the free HypeRate app. + +## Video + +- [HypeBlock trailer on YouTube](https://youtu.be/t0Yt1Q8s9jE): 2:18, the HUD, all outputs, calm door and HypeBridge in the sample world diff --git a/src/gametest/java/io/hyperate/hypeblock/gametest/HeartRateClientGameTest.java b/src/gametest/java/io/hyperate/hypeblock/gametest/HeartRateClientGameTest.java index b9aaae4..d1cf6ca 100644 --- a/src/gametest/java/io/hyperate/hypeblock/gametest/HeartRateClientGameTest.java +++ b/src/gametest/java/io/hyperate/hypeblock/gametest/HeartRateClientGameTest.java @@ -30,7 +30,7 @@ public class HeartRateClientGameTest implements FabricClientGameTest { @Override public void runTest(ClientGameTestContext context) { - if ("1".equals(System.getenv("HYPEBLOCK_SAMPLE_WORLD"))) return; // only the sample world builder + if ("1".equals(System.getenv("HYPEBLOCK_SAMPLE_WORLD")) || "1".equals(System.getenv("HYPEBLOCK_TRAILER"))) return; // only the sample world builder / trailer try (TestSingleplayerContext singleplayer = context.worldBuilder().create()) { singleplayer.getConnection().waitForChunksRender(); TestServerContext server = singleplayer.getServer(); diff --git a/src/gametest/java/io/hyperate/hypeblock/gametest/SampleWorldBuilder.java b/src/gametest/java/io/hyperate/hypeblock/gametest/SampleWorldBuilder.java index 57f4687..45b7b93 100644 --- a/src/gametest/java/io/hyperate/hypeblock/gametest/SampleWorldBuilder.java +++ b/src/gametest/java/io/hyperate/hypeblock/gametest/SampleWorldBuilder.java @@ -58,9 +58,9 @@ */ public class SampleWorldBuilder implements FabricClientGameTest { static final String WORLD_NAME = "HypeBlock Showcase"; - private static final int[] STATION_X = {4, 20, 36, 52, 68}; + static final int[] STATION_X = {4, 20, 36, 52, 68}; - private int y; // standing height (first air block above the grass) + int y; // standing height (first air block above the grass) @Override public void runTest(ClientGameTestContext context) { @@ -103,7 +103,7 @@ public void runTest(ClientGameTestContext context) { context.runOnClient(client -> client.options.chatVisibility().set(ChatVisiblity.FULL)); } - private void flatCreative(WorldCreationUiState ui) { + void flatCreative(WorldCreationUiState ui) { ui.setName(WORLD_NAME); ui.setGameMode(WorldCreationUiState.SelectedGameMode.CREATIVE); ui.setAllowCommands(true); @@ -116,7 +116,7 @@ private void flatCreative(WorldCreationUiState ui) { // ---------------------------------------------------------------- build - private void build(MinecraftServer server) { + void build(MinecraftServer server) { ServerLevel level = server.overworld(); y = level.getHeight(Heightmap.Types.MOTION_BLOCKING, 0, 0); int ground = y - 1; @@ -337,7 +337,7 @@ private void tp(TestServerContext server, double x, double py, double z, float y // ---------------------------------------------------------------- helpers - private List hypeBlocks() { + List hypeBlocks() { return List.of( new BlockPos(STATION_X[0], y, 2), new BlockPos(STATION_X[1], y, 2), @@ -350,7 +350,7 @@ private static HypeBlockEntity block(MinecraftServer server, BlockPos pos) { return (HypeBlockEntity) server.overworld().getBlockEntity(pos); } - private static void hypeBlock(ServerLevel level, int x, int y, int z, UnaryOperator settings) { + static void hypeBlock(ServerLevel level, int x, int y, int z, UnaryOperator settings) { BlockPos pos = new BlockPos(x, y, z); level.setBlockAndUpdate(pos, ModBlocks.HYPEBLOCK.defaultBlockState()); HypeBlockEntity be = (HypeBlockEntity) level.getBlockEntity(pos); @@ -370,11 +370,11 @@ private static void sign(ServerLevel level, int x, int y, int z, String... lines } } - private static void set(ServerLevel level, int x, int y, int z, BlockState state) { + static void set(ServerLevel level, int x, int y, int z, BlockState state) { level.setBlock(new BlockPos(x, y, z), state, 3); } - private static void run(MinecraftServer server, String command) { + static void run(MinecraftServer server, String command) { server.getCommands().performPrefixedCommand(server.createCommandSourceStack().withSuppressedOutput(), command); } diff --git a/src/gametest/java/io/hyperate/hypeblock/gametest/TrailerRecorder.java b/src/gametest/java/io/hyperate/hypeblock/gametest/TrailerRecorder.java new file mode 100644 index 0000000..1e8ed78 --- /dev/null +++ b/src/gametest/java/io/hyperate/hypeblock/gametest/TrailerRecorder.java @@ -0,0 +1,506 @@ +package io.hyperate.hypeblock.gametest; + +import io.hyperate.hypeblock.HeartRates; +import io.hyperate.hypeblock.block.HypeBlockEntity; +import io.hyperate.hypeblock.block.HypeBlockSettings; +import io.hyperate.hypeblock.client.HeartSource; +import io.hyperate.hypeblock.client.HypeBlockScreen; +import net.fabricmc.fabric.api.client.gametest.v1.FabricClientGameTest; +import net.fabricmc.fabric.api.client.gametest.v1.context.ClientGameTestContext; +import net.fabricmc.fabric.api.client.gametest.v1.context.TestServerContext; +import net.fabricmc.fabric.api.client.gametest.v1.context.TestSingleplayerContext; +import net.fabricmc.fabric.api.client.gametest.v1.screenshot.TestScreenshotOptions; +import net.minecraft.client.CloudStatus; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.player.ChatVisiblity; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.phys.Vec3; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +/** + * Records the camera flights for the trailer from the sample world, frame by frame at 30 fps. + * Only runs with HYPEBLOCK_TRAILER=1 (optionally HYPEBLOCK_TRAILER_SHOTS=name,name to redo single shots): + * + * HYPEBLOCK_TRAILER=1 ./gradlew runClientGameTest + * + * The camera is placed on the client every tick (old and new position), frames between two ticks are + * rendered with the matching partial tick, so the motion is smooth at 30 fps while the world runs at + * its normal 20 ticks per second. Each shot is encoded to build/run/trailer/shots/.mp4 right + * away and its PNG frames are deleted (they are big). + */ +public class TrailerRecorder implements FabricClientGameTest { + private static final int FPS = 30; + private static final int W = 1920, H = 1080; + private static final int[] SX = SampleWorldBuilder.STATION_X; + + private final SampleWorldBuilder world = new SampleWorldBuilder(); + private int y; + private UUID player; + private Path out; + + @Override + public void runTest(ClientGameTestContext context) { + if (!"1".equals(System.getenv("HYPEBLOCK_TRAILER"))) return; + String only = System.getenv("HYPEBLOCK_TRAILER_SHOTS"); + Set wanted = only == null || only.isBlank() ? null + : Arrays.stream(only.split(",")).map(String::trim).collect(Collectors.toSet()); + out = Path.of(System.getProperty("user.dir")).resolve("../trailer/shots").normalize(); + try { + Files.createDirectories(out); + } catch (IOException e) { + throw new RuntimeException(e); + } + + context.getInput().resizeWindow(W, H); + context.runOnClient(mc -> { + mc.options.chatVisibility().set(ChatVisiblity.HIDDEN); + mc.options.fov().set(60); + mc.options.bobView().set(false); + }); + + try (TestSingleplayerContext sp = context.worldBuilder() + .setUseConsistentSettings(false) + .adjustSettings(world::flatCreative) + .create()) { + sp.getConnection().waitForChunksRender(); + TestServerContext server = sp.getServer(); + player = context.computeOnClient(mc -> mc.player.getUUID()); + server.runOnServer(s -> { + world.build(s); + extras(s); + }); + y = world.y; + context.runOnClient(mc -> { + mc.options.renderDistance().set(10); + mc.options.cloudStatus().set(CloudStatus.FANCY); + }); + context.waitTicks(60); + server.runOnServer(s -> { + run(s, "gamemode spectator @a"); + run(s, "scoreboard objectives setdisplay sidebar"); + }); + context.waitTicks(40); + + for (Shot shot : shots()) { + if (wanted != null && !wanted.contains(shot.name)) continue; + record(context, server, shot); + } + context.runOnClient(mc -> HeartSource.setFake(0)); + } + context.runOnClient(mc -> mc.options.chatVisibility().set(ChatVisiblity.FULL)); + } + + /** A pedestal with an extra HypeBlock and a lamp for the close-up of the four states. */ + private void extras(MinecraftServer s) { + ServerLevel level = s.overworld(); + int y = world.y; + SampleWorldBuilder.set(level, -3, y, -6, Blocks.POLISHED_BLACKSTONE.defaultBlockState()); + SampleWorldBuilder.hypeBlock(level, -3, y + 1, -6, st -> st.withThreshold(100).withDelaySeconds(3)); + SampleWorldBuilder.set(level, -3, y + 2, -6, Blocks.REDSTONE_LAMP.defaultBlockState()); + } + + private BlockPos pedestal() { return new BlockPos(-3, y + 1, -6); } + + // ---------------------------------------------------------------- shot list + + private List shots() { + List list = new ArrayList<>(); + int s1 = SX[0], s2 = SX[1], s3 = SX[2], s4 = SX[3], s5 = SX[4]; + + // Opening: sunset, flying west along the walkway towards the sun + list.add(new Shot("overview", 14, 12450, false, path( + k(86, y + 16, -12, 62, y, 6), + k(62, y + 9, -10, 38, y, 6), + k(38, y + 6, -8, 16, y + 1, 6), + k(18, y + 4, -6, 0, y + 1, 4))) + .setup(c -> { joinAll(c); bpm(c, 118); })); + + // HUD: the heart tile in the corner, pulse rising + list.add(new Shot("hud", 11, 6000, true, path( + k(s1 - 6.5, y + 1.62, -1.2, s1 + 0.5, y + 0.2, 6.5), + k(s1 - 3.5, y + 1.62, -1.0, s1 + 0.5, y + 0.2, 6.5))) + .setup(c -> bpm(c, 74)) + .at(2.5, c -> fake(c, 82)) + .at(5.0, c -> fake(c, 93)) + .at(7.5, c -> fake(c, 107)) + .creative()); + + // The four states on the pedestal block: offline, idle, counting, active + BlockPos p = pedestal(); + list.add(new Shot("states", 15, 6000, false, + orbit(p.getX() + 0.5, p.getY() + 0.5, p.getZ() + 0.5, 3.2, 0.9, -40, 50, 15)) + .setup(c -> { leave(c, p); bpm(c, 90); }) + .at(3.0, c -> c.server.runOnServer(s -> block(s, p).join(s.getPlayerList().getPlayer(player)))) + .at(6.5, c -> fake(c, 122))); + + // Heartbeat heart at night, slow orbit from above + list.add(new Shot("heartbeat", 14, 18000, false, + orbit(s1 + 0.5, y, 6.5, 7, 5.5, 205, 280, 14)) + .setup(c -> { joinAll(c); bpm(c, 92); }) + .at(6.0, c -> fake(c, 128))); + + // Signal strength: dolly along the lamp bar while the pulse climbs 60 -> 160 + Shot strength = new Shot("strength", 15, 7000, false, path( + k(s2 + 7.5, y + 4.5, 2.5, s2 + 0.5, y, 9.5), + k(s2 + 8.0, y + 5.5, 7.0, s2 + 0.5, y, 10), + k(s2 + 8.5, y + 7.0, 12.5, s2 + 0.5, y, 10.5))) + .setup(c -> { joinAll(c); bpm(c, 60); }); + for (int i = 1; i <= 20; i++) { + int v = 60 + i * 5; + strength.at(1.0 + i * 0.55, c -> fake(c, v)); + } + list.add(strength); + + // Calm door: crosshair on the block, pulse drops, countdown, door opens, push in + BlockPos doorBlock = new BlockPos(s3 + 1, y, 4); + list.add(new Shot("calmdoor", 15, 9000, true, path( + k(s3 + 1.5, y + 1.62, -3.0, s3 + 1.5, y + 0.5, 4.5), + k(s3 + 1.4, y + 1.62, -1.8, s3 + 1.5, y + 0.5, 4.5), + k(s3 + 1.3, y + 1.62, -1.0, s3 + 1.5, y + 0.5, 4.5), + k(s3 + 0.5, y + 1.62, 2.5, s3 + 0.5, y + 1.0, 7.5), + k(s3 + 0.5, y + 1.5, 4.6, s3 + 0.5, y + 0.6, 7.5)).holdUntil(0.62)) + .setup(c -> { joinAll(c); bpm(c, 97); }) + .at(2.5, c -> fake(c, 88)) + .at(3.5, c -> fake(c, 76)) + .at(4.5, c -> fake(c, 71)) + .creative()); + + // HypeBridge at dusk: warning lamp, countdown, bridge opens over the lava, crane up + list.add(new Shot("bridge", 17, 12900, true, path( + k(s4 + 4.5, y + 2.4, 0.2, s4 + 1.5, y + 0.5, 4.5), + k(s4 + 4.0, y + 2.4, 0.6, s4 + 1.5, y + 0.5, 4.5), + k(s4 + 3.6, y + 2.4, 1.0, s4 + 1.5, y + 0.5, 4.5), + k(s4 + 4.5, y + 7, 4, s4 + 0.5, y - 1, 9), + k(s4 + 0.5, y + 9, 2.5, s4 + 0.5, y - 1, 9.5)).holdUntil(0.6)) + .setup(c -> { joinAll(c); bpm(c, 95); }) + .at(3.0, c -> fake(c, 112)) + .at(4.0, c -> fake(c, 124)) + .creative()); + + // Settings screen: cycle through the modes + BlockPos trigger = new BlockPos(s4 + 1, y, 4); + list.add(new Shot("settings", 11, 9000, true, path( + k(s4 + 3.5, y + 1.62, 0.5, s4 + 1.5, y + 0.5, 4.5), + k(s4 + 3.3, y + 1.62, 0.8, s4 + 1.5, y + 0.5, 4.5))) + .setup(c -> { + joinAll(c); + bpm(c, 104); + c.context.setScreen(() -> new HypeBlockScreen(trigger)); + }) + .at(2.5, c -> settings(c, trigger, st -> st.withOutput(HypeBlockSettings.Output.STRENGTH))) + .at(5.0, c -> settings(c, trigger, st -> st.withOutput(HypeBlockSettings.Output.HEARTBEAT))) + .at(7.5, c -> settings(c, trigger, st -> st.withOutput(HypeBlockSettings.Output.THRESHOLD) + .withAggregate(HypeBlockSettings.Aggregate.MAX))) + .after(c -> { + c.context.setScreen(() -> null); + settings(c, trigger, st -> st.withAggregate(HypeBlockSettings.Aggregate.AVERAGE)); + })); + + // Command block and the scoreboard sidebar + list.add(new Shot("command", 11, 6000, true, path( + k(s5 - 2.5, y + 2.6, -4.0, s5 + 0.5, y + 0.5, 3.5), + k(s5 + 0.5, y + 2.0, -1.8, s5 + 0.5, y + 0.5, 3.5))) + .setup(c -> { + bpm(c, 96); + c.server.runOnServer(s -> run(s, "scoreboard objectives setdisplay sidebar bpm")); + }) + .at(5.0, c -> fake(c, 104)) + .after(c -> c.server.runOnServer(s -> run(s, "scoreboard objectives setdisplay sidebar")))); + + // Finale: night, everything running, big pull back over the whole walkway + list.add(new Shot("finale", 16, 18000, false, path( + k(s4 + 6, y + 3, -3, s4 + 0.5, y, 8), + k(s3 + 4, y + 14, -12, s3, y, 6), + k(s3 - 6, y + 30, -30, s3 - 4, y, 6))) + .setup(c -> { joinAll(c); bpm(c, 126); })); + return list; + } + + // ---------------------------------------------------------------- recording + + private void record(ClientGameTestContext context, TestServerContext server, Shot shot) { + Ctx c = new Ctx(context, server); + double[] start = shot.cam.at(0); + server.runOnServer(s -> { + run(s, "kill @e[type=!player]"); + run(s, "time set " + shot.time); + run(s, String.format(java.util.Locale.ROOT, "tp @a %.2f %.2f %.2f", start[0], start[1] - 1.62, start[2])); + }); + server.runOnServer(s -> { + if (shot.creative) { + run(s, "gamemode creative @a"); + run(s, "clear @a"); + String[] items = {"hypeblock:hypeblock", "redstone", "redstone_lamp", "repeater", "comparator", "sticky_piston", "iron_door", "lever", "redstone_torch"}; + for (int i = 0; i < items.length; i++) run(s, "item replace entity @a hotbar." + i + " with " + items[i]); + } else { + run(s, "gamemode spectator @a"); + } + }); + context.waitTicks(2); + context.runOnClient(mc -> { + if (mc.gui.hud.isHidden() == shot.gui) mc.gui.hud.toggle(); + if (shot.creative) { + mc.player.getAbilities().flying = true; + mc.player.onUpdateAbilities(); + } + }); + if (shot.setup != null) shot.setup.accept(c); + place(context, shot.cam, 0, 0); + context.waitTicks(30); + place(context, shot.cam, 0, 0); + context.waitTicks(10); + // From here the server only advances one tick per recorded tick, so countdowns and pulses + // run at real speed in the video however slow the recording is. + server.runOnServer(s -> run(s, "tick freeze")); + context.waitTicks(2); + + Path dir = out.resolve(shot.name + "_frames"); + try { + Files.createDirectories(dir); + } catch (IOException e) { + throw new RuntimeException(e); + } + Process ffmpeg = startEncoder(out.resolve(shot.name + ".mp4")); + java.io.OutputStream pipe = ffmpeg.getOutputStream(); + int frames = (int) Math.round(shot.seconds * FPS); + int event = 0; + int f = 0; + long started = System.currentTimeMillis(); + for (int tick = 0; f < frames; tick++) { + double t0 = tick / 20.0, t1 = (tick + 1) / 20.0; + while (event < shot.events.size() && shot.events.get(event).time < t1) { + shot.events.get(event).action.accept(c); + event++; + } + place(context, shot.cam, t0, t1); + while (f < frames && f / (double) FPS < t1) { + float delta = (float) (f / (double) FPS * 20.0 - tick); + Path png = context.takeScreenshot(TestScreenshotOptions.of(String.format("f_%05d", f)) + .disableCounterPrefix().withDeltaTicks(delta).withSize(W, H).withDestinationDir(dir)); + try { + pipe.write(Files.readAllBytes(png)); + Files.delete(png); + } catch (IOException e) { + throw new RuntimeException(e); + } + f++; + } + server.runOnServer(s -> { + // keep the value fresh: HeartRates ages by wall clock, the client only sends every 20 ticks + HeartRates.remove(player); + HeartRates.update(player, serverBpm); + run(s, "tick step 1"); + }); + context.waitTick(); + } + server.runOnServer(s -> run(s, "tick unfreeze")); + if (shot.after != null) shot.after.accept(c); + System.out.printf("[trailer] %s: %d frames in %.1f s%n", shot.name, frames, (System.currentTimeMillis() - started) / 1000.0); + try { + pipe.close(); + if (ffmpeg.waitFor() != 0) throw new RuntimeException("ffmpeg failed for " + shot.name); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + dir.toFile().delete(); + } + + private double lastYaw = Double.NaN; + + /** Old position = camera at t0, new position = camera at t1; frames in between use the partial tick. */ + private void place(ClientGameTestContext context, Cam cam, double t0, double t1) { + double[] a = cam.at(t0), b = cam.at(t1); + context.runOnClient(mc -> { + LocalPlayer p = mc.player; + float[] ra = rot(a), rb = rot(b); + double ya = Double.isNaN(lastYaw) || t0 == 0 ? ra[0] : lastYaw + Mth.wrapDegrees(ra[0] - lastYaw); + double yb = ya + Mth.wrapDegrees(rb[0] - ya); + lastYaw = yb; + double eye = p.getEyeHeight(); + p.setDeltaMovement(Vec3.ZERO); + p.snapTo(b[0], b[1] - eye, b[2], (float) yb, rb[1]); + p.setOldPosAndRot(new Vec3(a[0], a[1] - eye, a[2]), (float) ya, ra[1]); + }); + } + + private static float[] rot(double[] k) { + double dx = k[3] - k[0], dy = k[4] - k[1], dz = k[5] - k[2]; + double h = Math.sqrt(dx * dx + dz * dz); + float yaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); + float pitch = (float) -Math.toDegrees(Math.atan2(dy, h)); + return new float[]{yaw, pitch}; + } + + /** ffmpeg reads the PNG frames from stdin, so only one frame is on disk at a time. */ + private static Process startEncoder(Path mp4) { + try { + return new ProcessBuilder("/opt/homebrew/bin/ffmpeg", "-y", "-loglevel", "error", + "-f", "image2pipe", "-framerate", String.valueOf(FPS), "-i", "-", + "-c:v", "libx264", "-preset", "medium", "-crf", "13", "-pix_fmt", "yuv420p", mp4.toString()) + .redirectOutput(ProcessBuilder.Redirect.INHERIT) + .redirectError(ProcessBuilder.Redirect.INHERIT) + .start(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + // ---------------------------------------------------------------- shot helpers + + private void joinAll(Ctx c) { + c.server.runOnServer(s -> { + for (BlockPos pos : world.hypeBlocks()) block(s, pos).join(s.getPlayerList().getPlayer(player)); + block(s, pedestal()).join(s.getPlayerList().getPlayer(player)); + }); + } + + private void leave(Ctx c, BlockPos pos) { + c.server.runOnServer(s -> block(s, pos).removeParticipant(player)); + } + + /** Sets the fake BPM and waits until the server has it (not recorded: use in setup only). */ + private int serverBpm; + + private void bpm(Ctx c, int bpm) { + serverBpm = bpm; + c.context.runOnClient(mc -> HeartSource.setFake(bpm, false)); + c.server.waitFor(s -> HeartRates.get(player).orElse(0) == bpm, 100); + c.context.waitTicks(30); + } + + /** Sets the fake BPM during a shot; the client sends it within a second. */ + private void fake(Ctx c, int bpm) { + serverBpm = bpm; + c.context.runOnClient(mc -> HeartSource.setFake(bpm, false)); + } + + private static void settings(Ctx c, BlockPos pos, UnaryOperator change) { + c.server.runOnServer(s -> block(s, pos).applySettings(change.apply(block(s, pos).settings()))); + } + + private static HypeBlockEntity block(MinecraftServer server, BlockPos pos) { + return (HypeBlockEntity) server.overworld().getBlockEntity(pos); + } + + private static void run(MinecraftServer server, String command) { + SampleWorldBuilder.run(server, command); + } + + // ---------------------------------------------------------------- camera paths + + interface Cam { + /** Eye position and look-at target at time t (seconds): {x, y, z, tx, ty, tz}. */ + double[] at(double t); + } + + static double[] k(double x, double y, double z, double tx, double ty, double tz) { + return new double[]{x, y, z, tx, ty, tz}; + } + + /** Smooth path through the keys (Catmull-Rom), eased in and out over the whole shot. */ + static PathCam path(double[]... keys) { + return new PathCam(keys); + } + + static final class PathCam implements Cam { + final double[][] keys; + double seconds = -1; + double hold = -1; // if set: ease to key 2 by this fraction, then ease through the rest + + PathCam(double[][] keys) { this.keys = keys; } + + PathCam holdUntil(double fraction) { + this.hold = fraction; + return this; + } + + @Override + public double[] at(double t) { + double u = Mth.clamp(t / seconds, 0, 1); + int n = keys.length - 1; + double s; + if (hold > 0 && n >= 3) { + // keys 0..2 slowly during [0, hold], keys 2..n eased during [hold, 1] + if (u < hold) s = (u / hold) * 2; + else s = 2 + ease((u - hold) / (1 - hold)) * (n - 2); + } else { + s = ease(u) * n; + } + int i = Math.min((int) Math.floor(s), n - 1); + double f = s - i; + double[] p0 = keys[Math.max(i - 1, 0)], p1 = keys[i], p2 = keys[i + 1], p3 = keys[Math.min(i + 2, n)]; + double[] r = new double[6]; + for (int j = 0; j < 6; j++) r[j] = catmull(p0[j], p1[j], p2[j], p3[j], f); + return r; + } + } + + static Cam orbit(double cx, double cy, double cz, double radius, double height, double deg0, double deg1, double seconds) { + return t -> { + double u = Mth.clamp(t / seconds, 0, 1); + double a = Math.toRadians(deg0 + (deg1 - deg0) * (0.15 * ease(u) + 0.85 * u)); + return new double[]{cx + Math.sin(a) * radius, cy + height, cz - Math.cos(a) * radius, cx, cy, cz}; + }; + } + + static double ease(double u) { + return u * u * u * (u * (u * 6 - 15) + 10); + } + + static double catmull(double p0, double p1, double p2, double p3, double t) { + double t2 = t * t, t3 = t2 * t; + return 0.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3); + } + + // ---------------------------------------------------------------- shots + + record Ctx(ClientGameTestContext context, TestServerContext server) {} + + record Event(double time, Consumer action) {} + + static final class Shot { + final String name; + final double seconds; + final int time; + final boolean gui; + final Cam cam; + final List events = new ArrayList<>(); + Consumer setup, after; + boolean creative; + + /** Creative instead of spectator: hotbar, hand and crosshair, the look-at line works. */ + Shot creative() { creative = true; return this; } + + Shot(String name, double seconds, int time, boolean gui, Cam cam) { + this.name = name; + this.seconds = seconds; + this.time = time; + this.gui = gui; + this.cam = cam; + if (cam instanceof PathCam pc) pc.seconds = seconds; + } + + Shot setup(Consumer c) { setup = c; return this; } + Shot after(Consumer c) { after = c; return this; } + Shot at(double t, Consumer c) { + events.add(new Event(t, c)); + events.sort((a, b) -> Double.compare(a.time, b.time)); + return this; + } + } +} diff --git a/src/gametest/resources/fabric.mod.json b/src/gametest/resources/fabric.mod.json index 37b785f..818534f 100644 --- a/src/gametest/resources/fabric.mod.json +++ b/src/gametest/resources/fabric.mod.json @@ -7,7 +7,8 @@ "entrypoints": { "fabric-client-gametest": [ "io.hyperate.hypeblock.gametest.HeartRateClientGameTest", - "io.hyperate.hypeblock.gametest.SampleWorldBuilder" + "io.hyperate.hypeblock.gametest.SampleWorldBuilder", + "io.hyperate.hypeblock.gametest.TrailerRecorder" ] }, "depends": { diff --git a/tools/trailer/fx.py b/tools/trailer/fx.py new file mode 100644 index 0000000..b1da5d6 --- /dev/null +++ b/tools/trailer/fx.py @@ -0,0 +1,364 @@ +"""Minecraft-themed transitions and frame effects. Frames are uint8 arrays (H, W, 3).""" +import numpy as np +from PIL import Image + +import mc + + +def ease(u): + u = min(max(u, 0.0), 1.0) + return u * u * (3 - 2 * u) + + +def ease_out(u): + u = min(max(u, 0.0), 1.0) + return 1 - (1 - u) ** 3 + + +def over(dst, rgba, x, y, alpha=1.0): + """Alpha-composites an RGBA image/array onto dst at (x, y), in place.""" + if isinstance(rgba, Image.Image): + rgba = np.asarray(rgba) + h, w = rgba.shape[:2] + H, W = dst.shape[:2] + x0, y0 = max(x, 0), max(y, 0) + x1, y1 = min(x + w, W), min(y + h, H) + if x1 <= x0 or y1 <= y0 or alpha <= 0: + return dst + src = rgba[y0 - y:y1 - y, x0 - x:x1 - x] + a = src[:, :, 3:4].astype(np.float32) * (alpha / 255.0) + region = dst[y0:y1, x0:x1].astype(np.float32) + dst[y0:y1, x0:x1] = (region * (1 - a) + src[:, :, :3].astype(np.float32) * a).astype(np.uint8) + return dst + + +def mix(a, b, t): + return (a.astype(np.float32) * (1 - t) + b.astype(np.float32) * t).astype(np.uint8) + + +def scale_frame(f, s, cx=0.5, cy=0.5): + """Zoom into the frame by s >= 1 around (cx, cy).""" + if abs(s - 1) < 1e-4: + return f + H, W = f.shape[:2] + w, h = W / s, H / s + x0, y0 = (W - w) * cx, (H - h) * cy + img = Image.fromarray(f).resize((W, H), Image.BILINEAR, box=(x0, y0, x0 + w, y0 + h)) + return np.asarray(img).copy() + + +def pixelate(f, block): + if block <= 1: + return f + H, W = f.shape[:2] + img = Image.fromarray(f) + small = img.resize((max(1, W // block), max(1, H // block)), Image.BOX) + return np.asarray(small.resize((W, H), Image.NEAREST)).copy() + + +class Grade: + """Light cinematic grade: a bit of contrast and saturation, vignette.""" + + def __init__(self, W, H, vignette=0.28): + yy, xx = np.mgrid[0:H, 0:W].astype(np.float32) + d = ((xx - W / 2) / (W / 2)) ** 2 + ((yy - H / 2) / (H / 2)) ** 2 + self.vig = (1 - vignette * np.clip(d - 0.25, 0, None) / 1.75)[:, :, None].astype(np.float32) + x = np.arange(256, dtype=np.float32) / 255 + curve = x + 0.10 * np.sin((x - 0.5) * np.pi) * (1 - np.abs(2 * x - 1)) * 1.6 + self.lut = np.clip(curve * 255, 0, 255).astype(np.uint8) + + def __call__(self, f, vignette=1.0, sat=1.12, exposure=1.0): + f = self.lut[f].astype(np.float32) + if exposure != 1.0: + f = 255 * (1 - (1 - f / 255) ** exposure) + luma = f @ np.array([0.299, 0.587, 0.114], dtype=np.float32) + f = luma[:, :, None] + (f - luma[:, :, None]) * sat + if vignette > 0: + f = f * (1 - vignette + vignette * self.vig) + return np.clip(f, 0, 255).astype(np.uint8) + + +# ---------------------------------------------------------------- transitions +# Each takes (A, B, p) with p in [0, 1] and returns the frame. + +class CrackShatter: + """A giant block-breaking crack runs over the frame, then it bursts into block pieces.""" + + def __init__(self, W, H, seed=1, cell=120): + self.W, self.H, self.cell = W, H, cell + side = max(W, H) + self.cracks = [] + for k in range(10): + t = mc.mc_texture(f"block/destroy_stage_{k}").resize((side, side), Image.NEAREST) + t = t.crop(((side - W) // 2, (side - H) // 2, (side - W) // 2 + W, (side - H) // 2 + H)) + self.cracks.append(np.asarray(t).astype(np.float32) / 255) + rng = np.random.default_rng(seed) + self.pieces = [] + for gy in range(0, H, cell): + for gx in range(0, W, cell): + cx = (gx + cell / 2 - W / 2) / (W / 2) + cy = (gy + cell / 2 - H / 2) / (H / 2) + vx = cx * rng.uniform(300, 900) + rng.uniform(-200, 200) + vy = -rng.uniform(300, 1100) + cy * 300 + self.pieces.append((gx, gy, vx, vy, rng.uniform(0.0, 0.25))) + + def crack(self, f, stage): + """Like the game: the crack multiplies the colour (x2); on dark frames it glows red.""" + c = self.cracks[stage] + a = c[:, :, 3:4] + f = f.astype(np.float32) + mult = 1 - a + a * (c[:, :, :3] * 2) + out = f * mult + dark = 1 - np.clip(f.mean(axis=2, keepdims=True) / 90, 0, 1) + out = out + a * (1 - c[:, :, :3]) * dark * np.array([230, 30, 40], np.float32) + return np.clip(out, 0, 255).astype(np.uint8) + + def __call__(self, A, B, p): + split = 0.5 + if p < split: + q = p / split + stage = min(int(q * 10), 9) + out = A.copy() + shake = int(6 * q) + if shake: + out = np.roll(out, (np.random.randint(-shake, shake + 1), np.random.randint(-shake, shake + 1)), axis=(0, 1)) + return self.crack(out, stage) + q = (p - split) / (1 - split) + crackedA = self.crack(A, 9) + out = mix(B, np.zeros_like(B), 0.5 * (1 - q)) + T = 1.1 + c = self.cell + for gx, gy, vx, vy, delay in self.pieces: + tt = max(0.0, q - delay) / (1 - delay) * T + if tt <= 0: + out[gy:gy + c, gx:gx + c] = crackedA[gy:gy + c, gx:gx + c] + continue + s = max(0.05, 1 - tt / T * 0.85) + x = gx + vx * tt + y = gy + vy * tt + 0.5 * 2600 * tt * tt + size = max(2, int(c * s)) + piece = crackedA[gy:gy + c, gx:gx + c] + if piece.size == 0: + continue + img = np.asarray(Image.fromarray(piece).resize((size, size), Image.NEAREST)) + rgba = np.dstack([img, np.full(img.shape[:2], 255, np.uint8)]) + over(out, rgba, int(x + (c - size) / 2), int(y + (c - size) / 2), 1.0) + return out + + +class Mosaic: + """Pixelates into big blocks and back out into the next shot.""" + + def __init__(self, max_block=96): + self.max_block = max_block + + def __call__(self, A, B, p): + tri = 1 - abs(2 * p - 1) + block = int(round(1 + (self.max_block - 1) * tri ** 1.6)) + src = A if p < 0.5 else B + return pixelate(src, block) + + +class BlockWipe: + """The next shot is placed block by block, diagonally across the screen, each block popping in.""" + + def __init__(self, W, H, cell=120, seed=2): + self.cell = cell + rng = np.random.default_rng(seed) + cols, rows = (W + cell - 1) // cell, (H + cell - 1) // cell + self.cells = [] + for r in range(rows): + for c in range(cols): + key = (c / cols) * 0.75 + (r / rows) * 0.25 + rng.uniform(0, 0.12) + self.cells.append((c * cell, r * cell, key / 0.87)) + + def __call__(self, A, B, p): + out = A.copy() + c = self.cell + for x, y, key in self.cells: + local = (p - key * 0.72) / 0.28 + if local <= 0: + continue + if local >= 1: + out[y:y + c, x:x + c] = B[y:y + c, x:x + c] + continue + s = 0.3 + 0.7 * ease_out(local) + size = max(2, int(c * s)) + piece = B[y:y + c, x:x + c] + img = np.asarray(Image.fromarray(piece).resize((size, size), Image.NEAREST)).astype(np.float32) + flash = (1 - local) * 0.6 + img = img * (1 - flash) + 255 * flash + rgba = np.dstack([img.astype(np.uint8), np.full(img.shape[:2], 255, np.uint8)]) + over(out, rgba, x + (c - size) // 2, y + (c - size) // 2) + return out + + +class RedstoneWipe: + """A glowing redstone line sweeps across; behind it the next shot is 'powered on'.""" + + def __init__(self, W, H, seed=3): + self.W, self.H = W, H + self.xx = np.arange(W, dtype=np.float32)[None, :] + rng = np.random.default_rng(seed) + self.sparks = [(rng.uniform(0, H), rng.uniform(-60, 60), rng.uniform(0, 1), rng.integers(6, 16)) for _ in range(140)] + dust = mc.mc_texture("block/redstone_dust_line0") + a = np.asarray(dust)[:, :, 3] + self.dust_mask = a # 16x16, a horizontal line in the middle + + def __call__(self, A, B, p): + W, H = self.W, self.H + edge = -150 + ease(p) * (W + 300) + left = (self.xx < edge)[:, :, None] + out = np.where(left, B, A).astype(np.float32) + d = (self.xx - edge) + glow = np.exp(-(d / 70) ** 2) + 0.5 * np.exp(-(np.clip(-d, 0, None) / 400)) * (d < 0) + glow = glow[:, :, None] * np.array([1.0, 0.12, 0.05], dtype=np.float32) + out = out + glow * 255 * 0.9 + core = np.exp(-(d / 10) ** 2)[:, :, None] * np.array([1.0, 0.25, 0.15], dtype=np.float32) + out = out + core * 255 + out = np.clip(out, 0, 255).astype(np.uint8) + for sy, off, ph, size in self.sparks: + age = (p * 3 + ph) % 1 + x = int(edge - off - age * 120) + y = int(sy + np.sin(ph * 30) * 20 - age * 60) + if 0 <= x < W - size and 0 <= y < H - size: + v = 1 - age + out[y:y + size, x:x + size] = np.clip( + out[y:y + size, x:x + size] * (1 - v) + np.array([255, 40, 30]) * v, 0, 255).astype(np.uint8) + return out + + +class HeartPunch: + """A hard cut on a heartbeat: zoom punch, red flash, colour split.""" + + def __call__(self, A, B, p): + if p < 0.5: + q = p / 0.5 + f = scale_frame(A, 1 + 0.07 * q * q) + flash = 0.5 * q * q + else: + q = (p - 0.5) / 0.5 + f = scale_frame(B, 1.07 - 0.07 * ease_out(q)) + flash = 0.55 * (1 - q) ** 2 + f = f.astype(np.float32) + if flash > 0.02: + shift = int(14 * flash) + r = np.roll(f[:, :, 0], shift, axis=1) + b = np.roll(f[:, :, 2], -shift, axis=1) + f = np.dstack([r, f[:, :, 1], b]) + f = f * (1 - flash) + np.array([255, 30, 50], dtype=np.float32) * flash * 0.8 + f * flash * 0.2 + return np.clip(f, 0, 255).astype(np.uint8) + + +class ChunkLoad: + """The next shot loads in chunk by chunk, spiralling out from the centre.""" + + def __init__(self, W, H, cell=135, seed=4): + self.cell = cell + rng = np.random.default_rng(seed) + cols, rows = (W + cell - 1) // cell, (H + cell - 1) // cell + cells = [] + for r in range(rows): + for c in range(cols): + cx, cy = (c + 0.5) * cell - W / 2, (r + 0.5) * cell - H / 2 + dist = np.hypot(cx, cy) / np.hypot(W / 2, H / 2) + ang = (np.arctan2(cy, cx) / (2 * np.pi)) % 1 + cells.append((c * cell, r * cell, dist * 0.85 + ang * 0.1 + rng.uniform(0, 0.08))) + mx = max(k for _, _, k in cells) + self.cells = [(x, y, k / mx) for x, y, k in cells] + + def __call__(self, A, B, p): + dim = 1 - 0.75 * ease(p * 1.4) + out = (A.astype(np.float32) * dim).astype(np.uint8) + c = self.cell + for x, y, key in self.cells: + local = (p - key * 0.75) / 0.25 + if local <= 0: + continue + v = ease(local) + out[y:y + c, x:x + c] = (B[y:y + c, x:x + c].astype(np.float32) * v + out[y:y + c, x:x + c] * (1 - v)).astype(np.uint8) + return out + + +class DirtLoading: + """The old options/loading screen: dirt falls over the frame, 'Loading terrain...', dirt falls away.""" + + def __init__(self, W, H, scale, label="Loading terrain"): + self.W, self.H = W, H + self.bg = mc.dirt_background(W, H, scale=int(8 * scale)) + self.scale = scale + self.texts = [mc.text_image(label + "." * i, max(1, int(5 * scale))) for i in range(4)] + + def __call__(self, A, B, p): + H = self.H + out = None + if p < 0.3: + y = int(-H + ease(p / 0.3) * H) + out = A.copy() + out[max(0, y):y + H] = self.bg[max(0, -y):H - max(0, y) + max(0, -y)][:out[max(0, y):y + H].shape[0]] + elif p < 0.7: + out = self.bg.copy() + else: + y = int(ease((p - 0.7) / 0.3) * H) + out = B.copy() + out[y:] = self.bg[:H - y] + if 0.22 < p < 0.78: + t = self.texts[int(p * 12) % 4] + a = min(1, (p - 0.22) / 0.06, (0.78 - p) / 0.06) + over(out, t, (self.W - self.texts[3].width) // 2, (self.H - t.height) // 2, a) + return out + + +class Fade: + def __init__(self, color=(0, 0, 0)): + self.color = np.array(color, dtype=np.float32) + + def __call__(self, A, B, p): + if p < 0.5: + return mix(A, np.broadcast_to(self.color, A.shape).astype(np.uint8), ease(p / 0.5)) + return mix(np.broadcast_to(self.color, B.shape).astype(np.uint8), B, ease((p - 0.5) / 0.5)) + + +# ---------------------------------------------------------------- logo + +class PixelLogo: + """The HypeBlock face, built pixel by pixel like falling sand (bottom rows land first).""" + + def __init__(self, px, seed=5): + self.tex = np.asarray(mc.hb_texture("hypeblock_active")) + self.px = px + rng = np.random.default_rng(seed) + self.items = [] + for r in range(16): + for c in range(16): + col = self.tex[r, c] + if col[3] == 0: + continue + delay = (15 - r) / 15 * 0.55 + rng.uniform(0, 0.25) + self.items.append((r, c, tuple(int(v) for v in col[:3]), delay)) + self.size = 16 * px + + def draw(self, out, x0, y0, t, build=1.2, pulse=0.0, alpha=1.0): + """t: seconds since the build started. pulse: 0..1 heartbeat scale bump.""" + px = self.px + s = 1 + 0.06 * pulse + p = max(1, int(round(px * s))) + cx, cy = x0 + self.size / 2, y0 + self.size / 2 + for r, c, col, delay in self.items: + lt = (t - delay * build) / (0.45 * build) + if lt <= 0: + continue + land = min(lt, 1.0) + fall = (1 - land) ** 2 + bounce = 0.0 + if 1.0 < lt < 1.4: + bounce = np.sin((lt - 1.0) / 0.4 * np.pi) * 0.25 + x = cx + (c - 8) * p + y = cy + (r - 8) * p - fall * 900 - bounce * p + xi, yi = int(x), int(y) + ye, xe = min(yi + p, out.shape[0]), min(xi + p, out.shape[1]) + if ye <= max(yi, 0) or xe <= max(xi, 0): + continue + region = out[max(yi, 0):ye, max(xi, 0):xe].astype(np.float32) + a = alpha * min(1.0, lt * 3) + out[max(yi, 0):ye, max(xi, 0):xe] = (region * (1 - a) + np.array(col, dtype=np.float32) * a).astype(np.uint8) diff --git a/tools/trailer/mc.py b/tools/trailer/mc.py new file mode 100644 index 0000000..6bacd96 --- /dev/null +++ b/tools/trailer/mc.py @@ -0,0 +1,197 @@ +"""Minecraft-style UI pieces for the trailer: bitmap font, tooltips, toasts, textures. + +All Minecraft textures are read straight from the 26.3 client jar in the loom cache, the HypeBlock +textures from the mod resources. Everything is drawn at 1x and scaled up with nearest neighbour, +so it looks exactly like the game GUI. +""" +import glob +import io +import os +import zipfile + +import numpy as np +from PIL import Image + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) +_jar = None + + +def jar(): + global _jar + if _jar is None: + hits = glob.glob(os.path.join(ROOT, ".gradle/loom-cache/minecraftMaven/net/minecraft/minecraft-clientOnly-*/*/*.jar")) + hits = [h for h in hits if "sources" not in h] + if not hits: + raise SystemExit("Minecraft client jar not found: run ./gradlew build once") + _jar = zipfile.ZipFile(hits[0]) + return _jar + + +def mc_texture(path): + """assets/minecraft/textures/.png as RGBA image.""" + return Image.open(io.BytesIO(jar().read(f"assets/minecraft/textures/{path}.png"))).convert("RGBA") + + +def hb_texture(name): + return Image.open(os.path.join(ROOT, "src/main/resources/assets/hypeblock/textures/block", name + ".png")).convert("RGBA") + + +def rgb(hex_color): + return ((hex_color >> 16) & 255, (hex_color >> 8) & 255, hex_color & 255) + + +class Font: + """The Minecraft bitmap font (ascii.png), optionally the enchanting table glyphs (ascii_sga.png).""" + + def __init__(self, sheet="font/ascii"): + img = mc_texture(sheet) + self.cell = img.width // 16 + self.glyphs = {} + self.widths = {} + a = np.array(img)[:, :, 3] + for code in range(32, 127): + cx, cy = (code % 16) * self.cell, (code // 16) * self.cell + g = img.crop((cx, cy, cx + self.cell, cy + self.cell)) + cols = np.where(a[cy:cy + self.cell, cx:cx + self.cell].max(axis=0) > 0)[0] + w = 3 if code == 32 else (int(cols.max()) + 1 if len(cols) else 0) + self.glyphs[chr(code)] = g + self.widths[chr(code)] = w + self.yoff = {} + if sheet == "font/ascii": + self._extra("font/accented", ascent=10) + + def _extra(self, sheet, ascent): + """Glyphs from another bitmap provider of the default font (umlauts etc.), as in default.json.""" + import json + providers = json.loads(jar().read("assets/minecraft/font/include/default.json"))["providers"] + prov = next(p for p in providers if p.get("file", "").endswith(sheet.split("/")[-1] + ".png")) + img = mc_texture(sheet) + rows = prov["chars"] + cw, ch = img.width // len(rows[0]), img.height // len(rows) + a = np.array(img)[:, :, 3] + for r, line in enumerate(rows): + for c, char in enumerate(line): + if char == "\x00" or char in self.glyphs: + continue + g = img.crop((c * cw, r * ch, c * cw + cw, r * ch + ch)) + cols = np.where(a[r * ch:r * ch + ch, c * cw:c * cw + cw].max(axis=0) > 0)[0] + self.glyphs[char] = g + self.widths[char] = int(cols.max()) + 1 if len(cols) else 0 + self.yoff[char] = 7 - ascent + + def width(self, text, bold=False): + return sum(self.widths.get(c, 5) + 1 + (1 if bold else 0) for c in text) - 1 + + def draw(self, img, x, y, text, color=0xFFFFFF, shadow=True, bold=False, alpha=255, alt=None, alt_mask=None): + """Draws at 1x onto img. alt: second Font for characters where alt_mask[i] is True (scramble).""" + def put(px, py, ch, col, font): + g = font.glyphs.get(ch) or font.glyphs["?"] + tint = Image.new("RGBA", g.size, col + (alpha,)) + mask = g.getchannel("A").point(lambda v: v * alpha // 255) + py += font.yoff.get(ch, 0) + img.paste(tint, (px, py), mask) + if bold: + img.paste(tint, (px + 1, py), mask) + + cx = x + for i, ch in enumerate(text): + font = alt if (alt is not None and alt_mask is not None and alt_mask[i] and ch != " ") else self + c = rgb(color) + if shadow: + put(cx + 1, y + 1, ch, tuple(v // 4 for v in c), font) + put(cx, y, ch, c, font) + cx += self.widths.get(ch, 5) + 1 + (1 if bold else 0) + return cx + + +_font = None +_sga = None + + +def font(): + global _font + if _font is None: + _font = Font() + return _font + + +def sga(): + global _sga + if _sga is None: + _sga = Font("font/ascii_sga") + return _sga + + +def upscale(img, s): + return img.resize((img.width * s, img.height * s), Image.NEAREST) + + +def text_image(text, scale, color=0xFFFFFF, bold=False, shadow=True, reveal=1.0, seed=0): + """Text as RGBA at the given scale. reveal < 1 shows the remaining letters as enchanting glyphs.""" + f = font() + w = f.width(text, bold) + 2 + top = 3 if any(c in f.yoff for c in text) else 0 + img = Image.new("RGBA", (w, 10 + top), (0, 0, 0, 0)) + mask = None + if reveal < 1.0: + rng = np.random.default_rng(seed) + order = rng.permutation(len(text)) + shown = int(round(reveal * len(text))) + mask = [True] * len(text) + for i in order[:shown]: + mask[i] = False + f.draw(img, 0, top, text, color, shadow=shadow, bold=bold, alt=sga() if mask else None, alt_mask=mask) + return upscale(img, scale) + + +def tooltip(lines, scale): + """An item tooltip: lines = [(text, color)], first line is the item name.""" + f = font() + w = max(f.width(t) for t, _ in lines) + 8 + h = 8 + len(lines) * 10 + (2 if len(lines) > 1 else 0) + img = Image.new("RGBA", (w + 2, h + 2), (0, 0, 0, 0)) + px = img.load() + bg = (16, 0, 16, 240) + for yy in range(1, h + 1): + for xx in range(1, w + 1): + px[xx, yy] = bg + for xx in range(2, w): + px[xx, 0] = bg + px[xx, h + 1] = bg + for yy in range(2, h): + px[0, yy] = bg + px[w + 1, yy] = bg + # purple border, gradient top -> bottom + for yy in range(2, h): + t = (yy - 2) / max(h - 3, 1) + col = (int(80 + (40 - 80) * t), 0, int(255 + (127 - 255) * t), 200) + px[1, yy] = col + px[w, yy] = col + for xx in range(2, w): + px[xx, 1] = (80, 0, 255, 200) + px[xx, h] = (40, 0, 127, 200) + y = 4 + for i, (t, c) in enumerate(lines): + f.draw(img, 5, y, t, c) + y += 10 + (2 if i == 0 else 0) + return upscale(img, scale) + + +def toast(title, desc, icon, scale, title_color=0xFFFF00): + """An advancement toast (160x32) with a 16x16 icon.""" + img = mc_texture("gui/sprites/toast/advancement").copy() + img.alpha_composite(icon.resize((16, 16), Image.NEAREST), (8, 8)) + f = font() + f.draw(img, 30, 7, title, title_color, shadow=False) + f.draw(img, 30, 18, desc, 0xFFFFFF, shadow=False) + return upscale(img, scale) + + +def dirt_background(w, h, scale=4, darken=0.25): + """The classic options background: dirt texture, darkened.""" + d = mc_texture("block/dirt").convert("RGB") + d = upscale(d, scale) + tile = np.array(d).astype(np.float32) * darken + reps_y = h // tile.shape[0] + 1 + reps_x = w // tile.shape[1] + 1 + return np.tile(tile, (reps_y, reps_x, 1))[:h, :w].astype(np.uint8) diff --git a/tools/trailer/mix.py b/tools/trailer/mix.py new file mode 100644 index 0000000..03d34e1 --- /dev/null +++ b/tools/trailer/mix.py @@ -0,0 +1,464 @@ +"""Score, sound design and voice-over mix for the trailer, then muxes the final video. + + python tools/trailer/mix.py [--lang en] [--no-vo] + +Reads build/trailer/timeline.json (from render.py) and build/trailer/vo//*.mp3, writes +build/trailer/audio.wav and build/trailer/HypeBlock-Trailer[-de].mp4. The music is synthesised here +(D minor, 100 BPM, heartbeat kick), so there are no licensing questions. +""" +import argparse +import json +import os +import subprocess +import sys + +import numpy as np +from scipy import signal + +sys.path.insert(0, os.path.dirname(__file__)) +import mc # noqa: E402 +from script import LINES # noqa: E402 + +SR = 44100 +OUT = os.path.join(mc.ROOT, "build/trailer") +rng = np.random.default_rng(42) + +NOTE = {n: i for i, n in enumerate(["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"])} +NOTE.update({"Db": 1, "Eb": 3, "Gb": 6, "Ab": 8, "Bb": 10}) + + +def hz(name): + """'A4' -> 440.""" + n, octave = name[:-1], int(name[-1]) + return 440.0 * 2 ** ((NOTE[n] + 12 * (octave + 1) - 69) / 12) + + +def tt(seconds): + return np.arange(int(seconds * SR)) / SR + + +def env_adsr(n, a, d, s, r, sustain_len=None): + a, d, r = int(a * SR), int(d * SR), int(r * SR) + hold = max(0, n - a - d - r) if sustain_len is None else int(sustain_len * SR) + e = np.concatenate([np.linspace(0, 1, max(a, 1)), np.linspace(1, s, max(d, 1)), + np.full(hold, s), np.linspace(s, 0, max(r, 1))]) + return e[:n] if len(e) >= n else np.pad(e, (0, n - len(e))) + + +def lowpass(x, cutoff, order=2): + sos = signal.butter(order, min(cutoff, SR / 2 - 100), "low", fs=SR, output="sos") + return signal.sosfilt(sos, x) + + +def highpass(x, cutoff, order=2): + sos = signal.butter(order, cutoff, "high", fs=SR, output="sos") + return signal.sosfilt(sos, x) + + +def bandpass(x, lo, hi, order=2): + sos = signal.butter(order, [lo, hi], "band", fs=SR, output="sos") + return signal.sosfilt(sos, x) + + +def saw(f, t, phase=0.0): + return 2 * ((f * t + phase) % 1) - 1 + + +# ---------------------------------------------------------------- instruments + +def pad(freqs, dur, bright=1800, gain=0.12): + t = tt(dur + 1.5) + x = np.zeros_like(t) + for f in freqs: + for det in (-0.006, 0.0, 0.0065): + x += saw(f * (1 + det), t, rng.uniform()) + x = lowpass(x / (len(freqs) * 3), bright, 2) + lfo = 1 + 0.15 * np.sin(2 * np.pi * 0.25 * t) + return x * env_adsr(len(t), 0.8, 0.5, 0.85, 1.4, dur - 1.3 if dur > 1.3 else 0) * gain * lfo + + +def pluck(f, dur=1.6, gain=0.18, bright=1.0): + """Celesta-ish pluck: a few harmonics with fast decays.""" + t = tt(dur) + x = np.zeros_like(t) + for k, (amp, dec) in enumerate([(1.0, 2.2), (0.45, 3.5), (0.22, 5.0), (0.12, 7.0), (0.05, 9.0)]): + x += amp * bright ** k * np.sin(2 * np.pi * f * (k + 1) * t) * np.exp(-dec * t) + x += 0.3 * np.sin(2 * np.pi * f * 4.01 * t) * np.exp(-14 * t) + return x * np.minimum(1, t / 0.003) * gain + + +def bass(f, dur, gain=0.28): + t = tt(dur + 0.2) + x = np.sin(2 * np.pi * f * t) + 0.35 * lowpass(saw(f, t), 400) + return x * env_adsr(len(t), 0.01, 0.2, 0.7, 0.15) * gain + + +def heartbeat(gain=0.9): + """lub-dub: two pitched thumps.""" + def thump(f0, f1, dur, g): + t = tt(dur) + f = f1 + (f0 - f1) * np.exp(-t * 28) + ph = 2 * np.pi * np.cumsum(f) / SR + return np.sin(ph) * np.exp(-t * 11) * g * np.minimum(1, t / 0.002) + lub = thump(115, 44, 0.45, 1.0) + dub = thump(135, 52, 0.4, 0.7) + out = np.zeros(int(0.7 * SR)) + out[:len(lub)] += lub + o = int(0.24 * SR) + out[o:o + len(dub)] += dub[:len(out) - o] + return np.tanh(out * 1.6) * gain + + +def kick(gain=0.8): + t = tt(0.5) + f = 45 + 120 * np.exp(-t * 35) + return np.tanh(np.sin(2 * np.pi * np.cumsum(f) / SR) * np.exp(-t * 7) * 2) * gain + + +def snare(gain=0.35): + t = tt(0.35) + n = bandpass(rng.standard_normal(len(t)), 900, 7000) * np.exp(-t * 18) + tone = np.sin(2 * np.pi * 190 * t) * np.exp(-t * 25) + return (n * 0.9 + tone * 0.5) * gain + + +def hat(gain=0.08, dur=0.06): + t = tt(dur) + return highpass(rng.standard_normal(len(t)), 7000) * np.exp(-t * 60) * gain + + +def impact(gain=1.0, length=3.5): + t = tt(length) + f = 32 + 60 * np.exp(-t * 6) + sub = np.sin(2 * np.pi * np.cumsum(f) / SR) * np.exp(-t * 1.3) + noise = lowpass(rng.standard_normal(len(t)), 2500) * np.exp(-t * 4) * 0.5 + crack = highpass(rng.standard_normal(len(t)), 2000) * np.exp(-t * 30) * 0.4 + return np.tanh((sub + noise + crack) * 1.4) * gain + + +def riser(dur, gain=0.25): + t = tt(dur) + u = t / dur + n = rng.standard_normal(len(t)) + # sweep: blend of band-passed noise slices with rising centre + out = np.zeros_like(t) + seg = int(0.05 * SR) + for i in range(0, len(t), seg): + c = 300 + 6000 * u[i] ** 2 + out[i:i + seg] = bandpass(n[i:i + seg + 2000], c * 0.7, min(c * 1.4, 20000))[:len(out[i:i + seg])] + tone = saw(110 * 2 ** (u * 2), t) * 0.15 + return (out + lowpass(tone, 3000)) * u ** 2 * gain + + +def whoosh(dur=0.7, gain=0.2): + t = tt(dur) + u = t / dur + n = rng.standard_normal(len(t)) + out = lowpass(n, 2500) * np.sin(np.pi * u) ** 2 + return highpass(out, 200) * gain + + +def crunch(gain=0.5): + """Block break: a few gritty noise grains.""" + out = np.zeros(int(0.5 * SR)) + for k in range(5): + t = tt(0.09) + g = bandpass(rng.standard_normal(len(t)), 300 + 300 * k, 3500) * np.exp(-t * 45) + o = int(k * 0.045 * SR) + out[o:o + len(t)] += g * (1 - k * 0.12) + return np.tanh(out * 2) * gain + + +def tick(gain=0.25): + t = tt(0.05) + return (np.sin(2 * np.pi * 2400 * t) * np.exp(-t * 160) + highpass(rng.standard_normal(len(t)), 4000) * np.exp(-t * 300) * 0.5) * gain + + +def chime(freqs, gain=0.15): + t = tt(3.0) + x = np.zeros_like(t) + for f in freqs: + for k, (r, a) in enumerate([(1, 1.0), (2.76, 0.4), (5.4, 0.2)]): + x += a * np.sin(2 * np.pi * f * r * t) * np.exp(-t * (1.2 + k * 1.5)) + return x * gain / len(freqs) + + +def blip(gain=0.12): + """GUI click.""" + t = tt(0.06) + return np.sin(2 * np.pi * 1300 * t) * np.exp(-t * 90) * gain + + +# ---------------------------------------------------------------- arrangement + +class Track: + def __init__(self, total): + self.n = int((total + 4) * SR) + self.buses = {k: np.zeros((self.n, 2)) for k in ("music", "drums", "sfx", "vo")} + + def add(self, bus, t, x, gain=1.0, pan=0.0): + i = int(t * SR) + if i >= self.n or i + len(x) <= 0: + return + if i < 0: + x, i = x[-i:], 0 + x = x[:self.n - i] + l, r = np.cos((pan + 1) * np.pi / 4), np.sin((pan + 1) * np.pi / 4) + self.buses[bus][i:i + len(x), 0] += x * gain * l * 1.414 + self.buses[bus][i:i + len(x), 1] += x * gain * r * 1.414 + + +def reverb(x, seconds=2.8, wet=0.3, seed=0): + r = np.random.default_rng(seed) + t = tt(seconds) + out = np.zeros_like(x) + for ch in range(2): + ir = r.standard_normal(len(t)) * np.exp(-t * 6.9 / seconds) + ir = lowpass(ir, 5000) + ir /= np.sqrt(np.sum(ir ** 2)) + out[:, ch] = signal.fftconvolve(x[:, ch], ir)[:len(x)] + return x * (1 - wet) + out * wet * 1.6 + + +CHORDS = { # D minor: i - VI - III - VII + "Dm": (["D3", "A3", "D4", "F4", "A4", "E5"], "D2"), + "Bb": (["Bb2", "F3", "Bb3", "D4", "F4", "C5"], "Bb1"), + "F": (["F2", "C3", "F3", "A3", "C4", "G4"], "F2"), + "C": (["C3", "G3", "C4", "E4", "G4", "D5"], "C2"), +} +PROG = ["Dm", "Bb", "F", "C"] +BEAT = 0.6 # 100 BPM +BAR = 4 * BEAT +MELODY = [ # finale lead, (beat offset, note, beats) + (0, "A4", 1.5), (1.5, "G4", 0.5), (2, "F4", 1), (3, "E4", 1), + (4, "D4", 1), (5, "F4", 1), (6, "A4", 2), + (8, "C5", 1), (9, "Bb4", 0.5), (9.5, "A4", 1.5), (11, "G4", 0.5), (11.5, "F4", 0.5), + (12, "E4", 2), (14, "G4", 1), (15, "A4", 1), +] + + +def compose(tl, tr): + c = {x["name"]: x for x in tl["clips"]} + ev = tl["events"] + total = tl["total"] + + # --- transitions: whooshes, the crack, the punch + for x in tl["clips"]: + if not x["out"]: + continue + name, d = x["out"] + t0 = x["end"] - d + if name == "crack": + for k in range(4): + tr.add("sfx", t0 + k * d * 0.12, crunch(0.25 + 0.05 * k), pan=rng.uniform(-0.3, 0.3)) + tr.add("sfx", t0 + d * 0.5, crunch(0.7)) + tr.add("sfx", t0 + d * 0.5, impact(0.55, 2.5)) + elif name == "punch": + tr.add("sfx", t0 + d * 0.5 - 0.02, heartbeat(1.0)) + tr.add("sfx", t0 + d * 0.5, impact(0.35, 2.0)) + elif name == "dirt": + tr.add("sfx", t0, whoosh(0.6, 0.25)) + tr.add("sfx", t0 + d * 0.7, whoosh(0.6, 0.25)) + elif name == "fade": + pass + else: + tr.add("sfx", t0, whoosh(d + 0.2, 0.22), pan=-0.2) + if name in ("block", "chunks"): + for k in range(8): + tr.add("sfx", t0 + d * (0.1 + k * 0.1), blip(0.05), pan=rng.uniform(-0.6, 0.6)) + + # --- intro: heartbeats in the dark, low drone + ov = c["overview"] + for k in range(4): + tr.add("drums", 0.35 + k * 1.0, heartbeat(0.75 + 0.05 * k)) + drone = pad([hz("D2"), hz("A2")], ov["start"] + 1.0, bright=500, gain=0.18) + tr.add("music", 0.0, drone * np.minimum(1, tt(len(drone) / SR) / 2.5)) + + # --- overview: calm, wide pads and sparse plucks + t = ov["start"] + 0.65 + logo = ev["logo"] + bar = 0 + while t < logo + 1.7: + ch = PROG[bar % 4] + notes, b = CHORDS[ch] + tr.add("music", t, pad([hz(n) for n in notes[:4]], BAR + 0.2, bright=1400, gain=0.16)) + tr.add("music", t, bass(hz(b), BAR * 0.95, 0.18)) + for k in range(4): + n = notes[2 + (k * 3 + bar) % 4] + tr.add("music", t + k * BEAT + rng.uniform(0, 0.04), pluck(hz(n) * 2, 2.0, 0.07), pan=rng.uniform(-0.5, 0.5)) + t += BAR + bar += 1 + + # --- logo: riser and the big hit, heartbeat pulses with the logo + tr.add("sfx", logo + 1.7 - 2.6, riser(2.6, 0.3)) + hit = logo + 1.7 + tr.add("sfx", hit, impact(1.0, 4.0)) + tr.add("music", hit, pad([hz(n) for n in ["D2", "A2", "D3", "F3", "A3", "D4"]], 3.0, bright=2500, gain=0.2)) + for k in range(4): + tr.add("drums", logo + 2.2 + k * 0.75 - 0.02, heartbeat(0.55)) + + # --- groove from the HUD on: heartbeat kick, arp, pads, bass + g0 = c["hud"]["start"] + 0.3 + calm0, calm1 = c["calmdoor"]["start"] + 0.6, ev["door_open"] + bridge0, bridge1 = c["bridge"]["start"], ev["bridge_open"] + fin = c["finale"] + end = c["end"] + t = g0 + bar = 0 + while t < fin["start"] + 0.2: + ch = PROG[bar % 4] + notes, b = CHORDS[ch] + calm = calm0 <= t < calm1 + tense = bridge0 <= t < bridge1 + intensity = 0.6 if t < c["states"]["start"] else (0.8 if t < c["heartbeat"]["start"] else 1.0) + if calm: + tr.add("music", t, pad([hz(n) for n in notes[:4]], BAR + 0.2, bright=900, gain=0.14)) + tr.add("music", t, pluck(hz(notes[4]) * 2, 2.4, 0.05)) + elif tense: + tr.add("music", t, pad([hz("D3"), hz("A3"), hz("Eb4")], BAR + 0.2, bright=1200, gain=0.12)) + tr.add("music", t, bass(hz("D2"), BAR, 0.2)) + for k in range(16): + tr.add("music", t + k * BEAT / 4, pluck(hz("D5") if k % 4 else hz("A5"), 0.3, 0.035), pan=0.3 if k % 2 else -0.3) + else: + tr.add("music", t, pad([hz(n) for n in notes[:5]], BAR + 0.2, bright=2000, gain=0.13)) + for k in range(4): + tr.add("music", t + k * BEAT, bass(hz(b) * (2 if k == 3 else 1), BEAT * 0.9, 0.22)) + arp = [notes[2], notes[3], notes[4], notes[3], notes[5], notes[4], notes[3], notes[4]] + for k in range(8): + tr.add("music", t + k * BEAT / 2, pluck(hz(arp[k]), 0.9, 0.06 * intensity, bright=0.8), pan=-0.4 if k % 2 else 0.4) + # drums + if not calm: + for k in range(4): + if k in (0, 2) and not tense: + tr.add("drums", t + k * BEAT - 0.01, heartbeat(0.55 * intensity)) + if tense and k == 0: + tr.add("drums", t, kick(0.5)) + if intensity >= 1.0 and not tense: + tr.add("drums", t + k * BEAT + BEAT / 2, hat(0.05), pan=0.3) + if k in (1, 3): + tr.add("drums", t + k * BEAT, snare(0.12)) + t += BAR + bar += 1 + + # calm door: breath-like noise swell and the chime when it opens + tr.add("sfx", calm0 + 2.5, lowpass(rng.standard_normal(int(3 * SR)), 600) * np.sin(np.pi * tt(3.0) / 3.0) ** 2 * 0.06) + tr.add("sfx", calm1, chime([hz("D5"), hz("F#5"), hz("A5")], 0.25)) + tr.add("sfx", calm1 + 0.3, chime([hz("D6")], 0.1)) + # bridge: lamp click, countdown ticks, riser, the hit + tr.add("sfx", ev["bridge_lamp"], impact(0.3, 1.5)) + for k in range(5): + tr.add("sfx", ev["bridge_open"] - 5 + k, tick(0.3 + 0.05 * k)) + tr.add("sfx", bridge1 - 2.2, riser(2.2, 0.28)) + tr.add("sfx", bridge1, impact(0.9, 3.5)) + # states: a click on each change + for s in ev["states"][1:]: + tr.add("sfx", s, blip(0.15)) + + # --- finale: big + f0 = fin["start"] + tr.add("sfx", f0 + 0.2, impact(0.6, 3.0)) + t = f0 + bar = 0 + words = [3.2, 4.1, 5.0, 6.0] + while t < end["start"] + 0.5: + ch = PROG[bar % 4] + notes, b = CHORDS[ch] + tr.add("music", t, pad([hz(n) for n in notes], BAR + 0.2, bright=3200, gain=0.16)) + for k in range(4): + tr.add("music", t + k * BEAT, bass(hz(b), BEAT * 0.9, 0.26)) + tr.add("drums", t + k * BEAT, kick(0.55)) + tr.add("drums", t + k * BEAT + BEAT / 2, hat(0.06)) + if k in (1, 3): + tr.add("drums", t + k * BEAT, snare(0.2)) + t += BAR + bar += 1 + for beat, note, beats in MELODY: + for rep in (0, 16): + at = f0 + 8 * BEAT + (beat + rep) * BEAT + if at < end["start"]: + tr.add("music", at, pad([hz(note)], beats * BEAT * 0.9, bright=4000, gain=0.1), pan=0.1) + tr.add("music", at, pluck(hz(note) * 2, 1.2, 0.08)) + for w in words: + tr.add("sfx", f0 + w, impact(0.45, 1.6)) + tr.add("sfx", f0 + 8.0 - 1.8, riser(1.8, 0.25)) + tr.add("sfx", f0 + 8.0, impact(1.0, 4.0)) + + # --- end card: logo hit, last heartbeats, silence + e0 = end["start"] + tr.add("sfx", e0 + 1.0, impact(0.8, 4.5)) + tr.add("music", e0 + 1.0, pad([hz(n) for n in ["D2", "A2", "D3", "F3", "A3", "E4"]], 6.0, bright=1500, gain=0.18)) + for k in range(7): + g = 0.6 * (1 - k / 8) + tr.add("drums", e0 + 2.0 + k * 0.85 - 0.02, heartbeat(g)) + + +def load_vo(lang, tl): + c = {x["name"]: x for x in tl["clips"]} + placed = [] + d = os.path.join(OUT, "vo", lang) + for lid, clip, at, en, de in LINES: + path = os.path.join(d, lid + ".mp3") + if not os.path.exists(path): + continue + raw = subprocess.run(["ffmpeg", "-loglevel", "error", "-i", path, "-f", "f32le", "-ac", "1", "-ar", str(SR), "-"], + capture_output=True, check=True).stdout + x = np.frombuffer(raw, np.float32).astype(np.float64) + # trim leading silence so the line starts on its cue + nz = np.where(np.abs(x) > 0.01)[0] + if len(nz): + x = x[max(0, nz[0] - int(0.03 * SR)):nz[-1] + int(0.15 * SR)] + placed.append((lid, c[clip]["start"] + at, x)) + return placed + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--lang", default="en") + ap.add_argument("--no-vo", action="store_true") + args = ap.parse_args() + tl = json.load(open(os.path.join(OUT, "timeline.json"))) + total = tl["total"] + tr = Track(total) + compose(tl, tr) + + vo = [] if args.no_vo else load_vo(args.lang, tl) + for i, (lid, t, x) in enumerate(vo): + end = t + len(x) / SR + if i + 1 < len(vo) and end > vo[i + 1][1] - 0.1: + print(f"warning: {lid} ({len(x) / SR:.2f} s) runs into the next line by {end - vo[i + 1][1]:.2f} s") + tr.add("vo", t, x, 1.0) + + music = reverb(tr.buses["music"], 3.2, 0.35, 1) + drums = reverb(tr.buses["drums"], 1.2, 0.12, 2) + sfx = reverb(tr.buses["sfx"], 2.0, 0.2, 3) + voice = tr.buses["vo"] + + # duck music under the voice + env = np.abs(voice[:, 0]) + env = lowpass(env, 6, 1) + env = np.convolve(env, np.ones(int(0.25 * SR)) / int(0.25 * SR), mode="same") + duck = 1 - 0.62 * np.clip(env / 0.03, 0, 1) + bed = (music + drums * 0.9) * duck[:, None] + sfx * (0.6 + 0.4 * duck[:, None]) + mixed = bed * 0.75 + voice * 2.1 + + n = int(total * SR) + mixed = mixed[:n] + fade = int(0.8 * SR) + mixed[-fade:] *= np.linspace(1, 0, fade)[:, None] + peak = np.max(np.abs(mixed)) + mixed = np.tanh(mixed / peak * 1.4) / np.tanh(1.4) * 0.92 + wav = os.path.join(OUT, f"audio-{args.lang}.wav") + from scipy.io import wavfile + wavfile.write(wav, SR, (mixed * 32767).astype(np.int16)) + print("wrote", wav, f"({len(vo)} voice lines)") + + video = os.path.join(OUT, f"video-{args.lang}.mp4") + name = "HypeBlock-Trailer" + ("" if args.lang == "en" else "-" + args.lang) + ".mp4" + final = os.path.join(OUT, name) + subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", video, "-i", wav, "-map", "0:v", "-map", "1:a", + "-c:v", "copy", "-c:a", "aac", "-b:a", "256k", "-shortest", "-movflags", "+faststart", final], check=True) + print("wrote", final) + + +if __name__ == "__main__": + main() diff --git a/tools/trailer/render.py b/tools/trailer/render.py new file mode 100644 index 0000000..dd2ec83 --- /dev/null +++ b/tools/trailer/render.py @@ -0,0 +1,349 @@ +"""Cuts the HypeBlock trailer from the recorded shots (build/run/trailer/shots/*.mp4). + + python tools/trailer/render.py [--scale 0.5] [--from 20 --to 40] + +Writes build/trailer/video.mp4 (no sound) and build/trailer/timeline.json (cue times for mix.py). +The edit is the CLIPS list below: shots with their in point and length, the transition into the +next clip, and the overlays (titles, tooltips, toasts) in clip-local seconds. +""" +import argparse +import json +import os +import subprocess + +import numpy as np + +import fx +import mc + +ROOT = mc.ROOT +SHOTS = os.path.join(ROOT, "build/run/trailer/shots") +OUT = os.path.join(ROOT, "build/trailer") +FPS = 30 + +HB_ICON = mc.hb_texture("hypeblock_active") +LANG = "en" +DE = {'EVERY GAME HAS A PULSE.': 'JEDES SPIEL HAT EINEN PULS.', 'Your real heart rate in Minecraft': 'Dein echter Puls in Minecraft', 'Heart rate HUD': 'Puls im HUD', 'Type /hr ': 'Tippe /hr ', 'Live from your watch or strap': 'Live von Uhr oder Brustgurt', 'Grey: a heart rate is missing': 'Grau: ein Puls fehlt', 'Dark red: ready': 'Dunkelrot: bereit', 'Orange: counting down': 'Orange: Countdown', 'Bright red: signal on!': 'Hellrot: Signal an!', 'Output: Heartbeat': 'Ausgang: Herzschlag', 'A redstone pulse on every beat': 'Ein Redstone-Impuls pro Schlag', 'Output: Signal strength': 'Ausgang: Signalstärke', '60-160 BPM = power 1-15': '60-160 BPM = Stärke 1-15', 'Power': 'Stärke', 'Trigger: below 80 BPM': 'Auslöser: unter 80 BPM', 'Hold it for 5 seconds': '5 Sekunden lang halten', 'Advancement Made!': 'Fortschritt erzielt!', 'Inner Peace': 'Innere Ruhe', 'Over 110 BPM': 'Über 110 BPM', 'Warning lamp: at once': 'Warnlampe: sofort', 'Bridge: after 5 seconds': 'Brücke: nach 5 Sekunden', 'Challenge Complete!': 'Aufgabe erledigt!', 'Lava? No problem.': 'Lava? Kein Problem.', 'For map makers': 'Für Map-Bauer', 'TRAPS.': 'FALLEN.', 'DOORS.': 'TÜREN.', 'BOSS FIGHTS.': 'BOSSKÄMPFE.', 'RACES.': 'RENNEN.', 'YOUR HEART IS': 'DEIN HERZ IST', 'THE NEW REDSTONE.': 'DAS NEUE REDSTONE.', 'Free mod for Minecraft Java 26.3 - Fabric': 'Kostenlose Mod für Minecraft Java 26.3 - Fabric', 'Loading terrain': 'Gelände wird geladen'} + + +def T(text): + return DE.get(text, text) if LANG == "de" else text + + + +# ---------------------------------------------------------------- the edit + +def clips(): + # out: transition into the next clip (name, seconds) + return [ + dict(name="intro", gen="intro", dur=5.0, out=("crack", 1.3)), + dict(name="overview", src=0.0, dur=14.0, out=("block", 1.0), vignette=1.2), + dict(name="hud", src=0.6, dur=10.4, out=("mosaic", 0.8), vignette=0.4), + dict(name="states", src=0.0, dur=15.0, out=("redstone", 1.1)), + dict(name="heartbeat", src=0.0, dur=13.5, out=("punch", 0.5), vignette=1.0, exposure=1.6), + dict(name="strength", src=0.0, dur=14.5, out=("block", 1.0)), + dict(name="calmdoor", src=0.0, dur=15.0, out=("crack", 1.3), vignette=0.5), + dict(name="bridge", src=0.0, dur=17.0, out=("dirt", 1.6), vignette=0.6), + dict(name="settings", src=0.3, dur=10.5, out=("mosaic", 0.8), vignette=0.2), + dict(name="command", src=0.0, dur=10.5, out=("chunks", 1.5), vignette=0.4), + dict(name="finale", src=0.0, dur=16.0, out=("fade", 1.2), vignette=1.0, exposure=1.5), + dict(name="end", gen="end", dur=9.0, out=None), + ] + + +# Overlays per clip: (t0, t1, draw(frame, local_t, overlay_t, S)) in clip-local seconds. +# Event times in the footage (seen in the recorded shots). +STATE_TIMES = [0.0, 3.0, 6.5, 9.5] # offline, idle, counting, active on the pedestal +DOOR_OPEN = 8.5 +BRIDGE_LAMP = 3.0 +BRIDGE_OPEN = 8.0 +LOGO_START = 8.6 # in the overview clip + + +def fade_alpha(lt, t0, t1, edge=0.3): + return max(0.0, min(1.0, (lt - t0) / edge, (t1 - lt) / edge)) + + +_cache = {} + + +def cached(key, make): + if key not in _cache: + _cache[key] = make() + return _cache[key] + + +def centered_text(frame, text, y, scale, color=0xFFFFFF, bold=False, alpha=1.0, reveal=1.0, seed=0): + img = mc.text_image(text, scale, color, bold=bold, reveal=reveal, seed=seed) if reveal < 1 else \ + cached(("t", text, scale, color, bold), lambda: mc.text_image(text, scale, color, bold=bold)) + fx.over(frame, img, (frame.shape[1] - img.width) // 2, int(y), alpha) + + +def tooltip_at(frame, lines, x, y, S, lt, t0, t1, slide=True): + img = cached(("tip", tuple(lines), S), lambda: mc.tooltip(lines, max(2, int(round(4 * S))))) + a = fade_alpha(lt, t0, t1, 0.25) + dx = int((1 - fx.ease_out(min(1, (lt - t0) / 0.35))) * -40 * S) if slide else 0 + fx.over(frame, img, int(x * S) + dx, int(y * S), a) + + +def toast_at(frame, title, desc, S, lt, t0, t1, color=0xFFFF00): + img = cached(("toast", title, desc, S), lambda: mc.toast(title, desc, HB_ICON, max(2, int(round(5 * S))), color)) + W = frame.shape[1] + inn = fx.ease_out((lt - t0) / 0.4) + out = fx.ease((lt - (t1 - 0.4)) / 0.4) + x = int(W - img.width * (inn - out)) + fx.over(frame, img, x - int(30 * S * (inn - out)), int(40 * S)) + + +def overlays(): + G = 0xAAAAAA + o = {} + + def logo(frame, lt, S, t_build): + H, W = frame.shape[:2] + dark = fx.ease((t_build + 0.6) / 1.2) * 0.7 + frame[:] = (frame.astype(np.float32) * (1 - dark)).astype(np.uint8) + L = cached(("logo", S), lambda: fx.PixelLogo(int(22 * S))) + beat = t_build - 2.2 + pulse = max(0.0, 1 - (beat % 0.75) / 0.25) if beat > 0 else 0.0 + L.draw(frame, (W - L.size) // 2, int(H * 0.17), t_build, build=1.3, pulse=pulse) + if t_build > 1.7: + r = min(1.0, (t_build - 1.7) / 0.9) + centered_text(frame, "HYPEBLOCK", H * 0.17 + L.size + 40 * S, int(12 * S), bold=True, reveal=r, seed=7) + if t_build > 2.8: + a = min(1.0, (t_build - 2.8) / 0.5) + centered_text(frame, T("Your real heart rate in Minecraft"), H * 0.17 + L.size + 170 * S, int(4 * S), G, alpha=a) + + o["intro"] = [(0.6, 4.4, lambda f, lt, S: centered_text( + f, T("EVERY GAME HAS A PULSE."), f.shape[0] / 2 - 40 * S, int(7 * S), + alpha=fade_alpha(lt, 0.6, 4.4, 0.4), reveal=min(1.0, (lt - 0.6) / 1.0), seed=3))] + o["overview"] = [(LOGO_START - 0.6, 99, lambda f, lt, S: logo(f, lt, S, lt - LOGO_START))] + o["hud"] = [(1.2, 8.6, lambda f, lt, S: tooltip_at( + f, [(T("Heart rate HUD"), 0xFFFFFF), (T("Type /hr "), G), (T("Live from your watch or strap"), G)], + 24, 150, S, lt, 1.2, 8.6))] + + state_lines = [("HypeBlock", 0xFFFFFF), (T("Grey: a heart rate is missing"), 0xAAAAAA), + (T("Dark red: ready"), 0xCC3333), (T("Orange: counting down"), 0xFFAA00), + (T("Bright red: signal on!"), 0xFF5555)] + + def states(f, lt, S): + n = 1 + sum(1 for t in STATE_TIMES if lt >= t + 0.3) + tooltip_at(f, state_lines[:n], 1240, 360, S, lt, 0.5, 14.3, slide=False) + + o["states"] = [(0.5, 14.3, states)] + o["heartbeat"] = [(1.0, 9.0, lambda f, lt, S: tooltip_at( + f, [(T("Output: Heartbeat"), 0xFFFFFF), (T("A redstone pulse on every beat"), G)], 70, 820, S, lt, 1.0, 9.0))] + + def strength(f, lt, S): + tooltip_at(f, [(T("Output: Signal strength"), 0xFFFFFF), (T("60-160 BPM = power 1-15"), G)], 70, 820, S, lt, 0.8, 13.0) + bpm = 60 if lt < 1.55 else min(160, 60 + 5 * int((lt - 1.0) / 0.55)) + power = max(1, min(15, int(round(1 + (bpm - 60) / 100 * 14)))) + a = fade_alpha(lt, 0.8, 13.0) + t1 = mc.text_image(f"{bpm} BPM", int(6 * S), 0xFF5555, bold=True) + t2 = mc.text_image(f"{T('Power')} {power}", int(4 * S), 0xFFFFFF) + x = f.shape[1] - int(90 * S) - t1.width + fx.over(f, t1, x, int(80 * S), a) + fx.over(f, t2, f.shape[1] - int(90 * S) - t2.width, int(80 * S) + t1.height + int(10 * S), a) + + o["strength"] = [(0.8, 13.0, strength)] + o["calmdoor"] = [ + (0.8, 8.2, lambda f, lt, S: tooltip_at( + f, [(T("Trigger: below 80 BPM"), 0xFFFFFF), (T("Hold it for 5 seconds"), G)], 70, 820, S, lt, 0.8, 8.2)), + (DOOR_OPEN + 0.2, DOOR_OPEN + 4.4, lambda f, lt, S: toast_at( + f, T("Advancement Made!"), T("Inner Peace"), S, lt, DOOR_OPEN + 0.2, DOOR_OPEN + 4.4)), + ] + o["bridge"] = [ + (0.6, 7.8, lambda f, lt, S: tooltip_at( + f, [(T("Over 110 BPM"), 0xFFFFFF), (T("Warning lamp: at once"), G), (T("Bridge: after 5 seconds"), G)], + 70, 780, S, lt, 0.6, 7.8)), + (BRIDGE_OPEN + 0.3, BRIDGE_OPEN + 4.6, lambda f, lt, S: toast_at( + f, T("Challenge Complete!"), T("Lava? No problem."), S, lt, BRIDGE_OPEN + 0.3, BRIDGE_OPEN + 4.6, 0xFF55FF)), + ] + o["command"] = [(1.0, 9.4, lambda f, lt, S: tooltip_at( + f, [(T("For map makers"), 0xFFFFFF), ("/hypeblock bpm ", G), ("/hypeblock value ", G)], + 70, 800, S, lt, 1.0, 9.4))] + + words = [("TRAPS.", 3.2), ("DOORS.", 4.1), ("BOSS FIGHTS.", 5.0), ("RACES.", 6.0)] + + def finale(f, lt, S): + H = f.shape[0] + for i, (w, t) in enumerate(words): + nxt = words[i + 1][1] if i + 1 < len(words) else 7.2 + if t <= lt < nxt: + k = 1 + 0.15 * (1 - fx.ease_out((lt - t) / 0.3)) + centered_text(f, T(w), H / 2 - 50 * S * k, int(round(9 * S * k)), bold=True, alpha=fade_alpha(lt, t, nxt, 0.12)) + if lt >= 8.0: + a = fade_alpha(lt, 8.0, 14.6, 0.5) + centered_text(f, T("YOUR HEART IS"), H / 2 - 110 * S, int(7 * S), alpha=a, bold=True) + centered_text(f, T("THE NEW REDSTONE."), H / 2 - 10 * S, int(9 * S), 0xFF5555, alpha=a, bold=True, + reveal=min(1.0, (lt - 8.6) / 0.9) if lt < 9.5 else 1.0, seed=9) + + o["finale"] = [(3.0, 15.0, finale)] + return o + + +# ---------------------------------------------------------------- generated clips + +def gen_intro(lt, W, H, S): + f = np.zeros((H, W, 3), np.uint8) + # a dark red glow on every heartbeat (lub-dub at 60 BPM, matches mix.py) + beat = (lt - 0.35) % 1.0 if lt > 0.35 else 1.0 + g = 0.22 * max(0.0, 1 - beat / 0.35) + 0.12 * max(0.0, 1 - abs(beat - 0.28) / 0.25) + if g > 0: + yy, xx = np.ogrid[0:H, 0:W] + d = ((xx - W / 2) / (W * 0.55)) ** 2 + ((yy - H / 2) / (H * 0.6)) ** 2 + glow = np.exp(-d * 2.5)[:, :, None] * np.array([150, 10, 20], np.float32) * g + f = np.clip(glow, 0, 255).astype(np.uint8) + return f + + +def gen_end(lt, W, H, S): + f = cached(("dirt", W, H), lambda: mc.dirt_background(W, H, int(8 * S), 0.18)).copy() + L = cached(("logo_end", S), lambda: fx.PixelLogo(int(16 * S), seed=11)) + beat = lt - 2.0 + pulse = max(0.0, 1 - (beat % 0.85) / 0.25) if 0 < beat < 6.5 else 0.0 + L.draw(f, (W - L.size) // 2, int(H * 0.12), lt + 0.3, build=1.0, pulse=pulse) + y = H * 0.12 + L.size + 30 * S + if lt > 1.0: + centered_text(f, "HYPEBLOCK", y, int(11 * S), bold=True, reveal=min(1.0, (lt - 1.0) / 0.8), seed=12) + if lt > 2.0: + a = min(1.0, (lt - 2.0) / 0.5) + centered_text(f, T("Free mod for Minecraft Java 26.3 - Fabric"), y + 130 * S, int(4 * S), 0xAAAAAA, alpha=a) + if lt > 2.6: + a = min(1.0, (lt - 2.6) / 0.5) + centered_text(f, "minecraft.hyperate.io", y + 200 * S, int(6 * S), 0xFFFF55, alpha=a, bold=True) + if lt > 3.4: + a = min(1.0, (lt - 3.4) / 0.5) + centered_text(f, "Powered by HypeRate", y + 300 * S, int(4 * S), 0xFF5555, alpha=a) + fade = fx.ease((lt - 8.0) / 1.0) + if fade > 0: + f = (f.astype(np.float32) * (1 - fade)).astype(np.uint8) + return f + + +GENERATORS = {"intro": gen_intro, "end": gen_end} + + +# ---------------------------------------------------------------- reading shots + +class Reader: + def __init__(self, name, src, W, H): + self.W, self.H = W, H + path = os.path.join(SHOTS, name + ".mp4") + self.proc = subprocess.Popen( + ["ffmpeg", "-loglevel", "error", "-ss", f"{src:.3f}", "-i", path, + "-vf", f"scale={W}:{H}:flags=lanczos", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], + stdout=subprocess.PIPE) + self.index = -1 + self.last = np.zeros((H, W, 3), np.uint8) + + def frame(self, index): + while self.index < index: + buf = self.proc.stdout.read(self.W * self.H * 3) + self.index += 1 + if len(buf) == self.W * self.H * 3: + self.last = np.frombuffer(buf, np.uint8).reshape(self.H, self.W, 3).copy() + return self.last + + def close(self): + self.proc.kill() + + +# ---------------------------------------------------------------- main + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--scale", type=float, default=1.0) + ap.add_argument("--from", dest="t_from", type=float, default=0) + ap.add_argument("--to", dest="t_to", type=float, default=1e9) + ap.add_argument("--out", default=None) + ap.add_argument("--lang", default="en", choices=["en", "de"]) + args = ap.parse_args() + global LANG + LANG = args.lang + if args.out is None: + args.out = os.path.join(OUT, f"video-{LANG}.mp4") + S = args.scale + W, H = int(1920 * S) // 2 * 2, int(1080 * S) // 2 * 2 + os.makedirs(OUT, exist_ok=True) + + cl = clips() + t = 0.0 + for i, c in enumerate(cl): + c["start"] = t + c["end"] = t + c["dur"] + tr = c["out"][1] if c["out"] else 0 + t = c["end"] - tr + total = cl[-1]["end"] + + timeline = {"total": total, "fps": FPS, "clips": [{k: c[k] for k in ("name", "start", "end", "dur")} | {"out": c["out"]} for c in cl], + "events": {"logo": cl[1]["start"] + LOGO_START, + "door_open": cl[6]["start"] + DOOR_OPEN, + "bridge_lamp": cl[7]["start"] + BRIDGE_LAMP, + "bridge_open": cl[7]["start"] + BRIDGE_OPEN, + "states": [cl[3]["start"] + s for s in STATE_TIMES]}} + with open(os.path.join(OUT, "timeline.json"), "w") as fh: + json.dump(timeline, fh, indent=1) + print(f"total {total:.2f} s") + + grade = fx.Grade(W, H) + trans = { + "crack": fx.CrackShatter(W, H, cell=max(8, int(120 * S))), + "block": fx.BlockWipe(W, H, cell=max(8, int(120 * S))), + "mosaic": fx.Mosaic(max_block=max(4, int(96 * S))), + "redstone": fx.RedstoneWipe(W, H), + "punch": fx.HeartPunch(), + "chunks": fx.ChunkLoad(W, H, cell=max(8, int(135 * S))), + "dirt": fx.DirtLoading(W, H, S, T("Loading terrain")), + "fade": fx.Fade(), + } + ovl = overlays() + readers = {} + + t_from, t_to = max(0, args.t_from), min(total, args.t_to) + enc = subprocess.Popen( + ["ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{W}x{H}", + "-r", str(FPS), "-i", "-", "-c:v", "libx264", "-preset", "medium", "-crf", "17", + "-pix_fmt", "yuv420p", "-movflags", "+faststart", args.out], stdin=subprocess.PIPE) + + def clip_frame(i, c, gt): + lt = gt - c["start"] + if "gen" in c: + f = GENERATORS[c["gen"]](lt, W, H, S) + else: + if i not in readers: + readers[i] = Reader(c["name"], c["src"], W, H) + f = grade(readers[i].frame(int(round(lt * FPS))), vignette=c.get("vignette", 1.0) * 0.8, exposure=c.get("exposure", 1.0)) + for t0, t1, draw in ovl.get(c["name"], []): + if t0 <= lt < t1: + draw(f, lt, S) + return f + + n0, n1 = int(t_from * FPS), int(t_to * FPS) + for n in range(n0, n1): + gt = n / FPS + active = [i for i, c in enumerate(cl) if c["start"] <= gt < c["end"]] + if len(active) == 1: + frame = clip_frame(active[0], cl[active[0]], gt) + else: + a, b = active[0], active[1] + A = clip_frame(a, cl[a], gt) + B = clip_frame(b, cl[b], gt) + name, d = cl[a]["out"] + p = (gt - cl[b]["start"]) / d + frame = trans[name](A, B, p) + for i in list(readers): + if gt >= cl[i]["end"]: + readers.pop(i).close() + enc.stdin.write(np.ascontiguousarray(frame).tobytes()) + if n % 150 == 0: + print(f"{gt:6.1f} / {t_to:.1f} s", flush=True) + enc.stdin.close() + enc.wait() + for r in readers.values(): + r.close() + print("wrote", args.out) + + +if __name__ == "__main__": + main() diff --git a/tools/trailer/script.py b/tools/trailer/script.py new file mode 100644 index 0000000..ff5958a --- /dev/null +++ b/tools/trailer/script.py @@ -0,0 +1,53 @@ +"""Voice-over lines of the trailer: (id, clip, clip-local start in seconds, English, German). + +Start times refer to the clips in render.py; mix.py places each recorded line there. +""" +import render + +D, B = render.DOOR_OPEN, render.BRIDGE_OPEN +L = render.LOGO_START + +LINES = [ + ("v01", "intro", 0.9, "Every game has a pulse.", + "Jedes Spiel hat einen Puls."), + ("v02", "overview", 1.6, "But this time... the world can feel yours.", + "Aber diesmal... spürt die Welt deinen."), + ("v03", "overview", L + 1.9, "HypeBlock.", + "HypeBlock."), + ("v04", "hud", 0.7, "Connect HypeRate once, and your real heart rate lives right in your HUD. Beat for beat.", + "Einmal mit HypeRate verbinden, und dein echter Puls schlägt direkt in deinem HUD. Schlag für Schlag."), + ("v05", "states", 0.5, "Place a HypeBlock. It reads your pulse, and turns it into redstone.", + "Stell einen HypeBlock hin. Er liest deinen Puls und macht daraus Redstone."), + ("v06", "states", 6.6, "Orange: it's counting down...", + "Orange: der Countdown läuft..."), + ("v07", "states", 9.6, "...bright red means power.", + "...hellrot heißt: Strom."), + ("v08", "heartbeat", 0.8, "Set it to Heartbeat, and redstone pulses with every beat of your heart.", + "Im Herzschlag-Modus pulsiert dein Redstone mit jedem Schlag deines Herzens."), + ("v09", "strength", 1.0, "Signal strength turns your BPM into power, from one to fifteen. The more hyped you get, the further it reaches.", + "Signalstärke macht aus deinen BPM eine Stärke von eins bis fünfzehn. Je mehr Hype, desto weiter reicht das Signal."), + ("v10", "calmdoor", 0.6, "Or flip the rule. This door only opens if you stay calm. Below eighty, for five seconds.", + "Oder dreh die Regel um. Diese Tür öffnet sich nur, wenn du ruhig bleibst. Unter achtzig, fünf Sekunden lang."), + ("v11", "calmdoor", D + 0.9, "Breathe... and you're in.", + "Durchatmen... und du bist drin."), + ("v12", "bridge", 0.4, "The HypeBridge. Over one-ten, the warning lamp goes on.", + "Die HypeBridge. Über hundertzehn geht die Warnlampe an."), + ("v13", "bridge", 4.8, "Hold it for five seconds...", + "Halte das fünf Sekunden..."), + ("v14", "bridge", B + 0.4, "...and the bridge opens. Right over the lava.", + "...und die Brücke öffnet sich. Direkt über der Lava."), + ("v15", "settings", 0.6, "Owner only, or the whole group. Average or highest. Threshold, delay, range. All in one screen.", + "Nur der Besitzer oder die ganze Gruppe. Durchschnitt oder Höchstwert. Schwelle, Verzögerung, Bereich. Alles in einem Fenster."), + ("v16", "command", 0.6, "And for map makers: every heart rate as a command result. Scoreboards, data packs, anything.", + "Und für Map-Bauer: jeder Puls als Befehlsergebnis. Scoreboards, Datenpakete, alles."), + ("v17", "finale", 0.6, "So... what will you build?", + "Also... was baust du?"), + ("v18", "finale", 3.2, "Traps.", "Fallen."), + ("v19", "finale", 4.1, "Doors.", "Türen."), + ("v20", "finale", 5.0, "Boss fights.", "Bosskämpfe."), + ("v21", "finale", 6.0, "Races.", "Rennen."), + ("v22", "finale", 8.2, "Your heart is the new redstone.", + "Dein Herz ist das neue Redstone."), + ("v23", "end", 1.3, "HypeBlock. Powered by HypeRate.", + "HypeBlock. Powered by HypeRate."), +] diff --git a/tools/trailer/thumbnail.py b/tools/trailer/thumbnail.py new file mode 100644 index 0000000..e6ceef2 --- /dev/null +++ b/tools/trailer/thumbnail.py @@ -0,0 +1,75 @@ +"""YouTube thumbnail (1280x720) from a heartbeat frame, the HypeBlock face and game-font titles. + + python tools/trailer/thumbnail.py -> build/trailer/thumbnail-en.jpg, thumbnail-de.jpg +""" +import os +import subprocess + +import numpy as np +from PIL import Image, ImageFilter + +import fx +import mc + +W, H = 1280, 720 +FRAME = 412 # heartbeat shot: the lamp heart fully lit +OUT = os.path.join(mc.ROOT, "build/trailer") + +TEXT = { + "en": ("YOUR HEART", "= REDSTONE", "Real heart rate in Minecraft"), + "de": ("DEIN PULS", "= REDSTONE", "Echter Herzschlag in Minecraft"), +} + + +def background(): + shot = os.path.join(mc.ROOT, "build/run/trailer/shots/heartbeat.mp4") + raw = subprocess.run(["ffmpeg", "-loglevel", "error", "-i", shot, "-vf", + f"select=eq(n\\,{FRAME}),scale={W}:{H}", "-frames:v", "1", + "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], capture_output=True, check=True).stdout + f = np.frombuffer(raw, np.uint8).reshape(H, W, 3) + f = fx.Grade(W, H, vignette=0.5)(f, vignette=1.0, sat=1.25, exposure=1.7) + img = Image.fromarray(f).filter(ImageFilter.GaussianBlur(2.5)) + a = np.asarray(img).astype(np.float32) + # darken the left side for the text + ramp = np.clip(1 - np.linspace(0, 1, W) * 1.6, 0, 1)[None, :, None] + a = a * (1 - 0.72 * ramp) + return a.astype(np.uint8).copy() + + +def glow(frame, cx, cy, radius, color, strength): + yy, xx = np.ogrid[0:H, 0:W] + d = ((xx - cx) ** 2 + (yy - cy) ** 2) / radius ** 2 + g = np.exp(-d * 2)[:, :, None] * np.array(color, np.float32) * strength + frame[:] = np.clip(frame.astype(np.float32) + g, 0, 255).astype(np.uint8) + + +def make(lang): + l1, l2, sub = TEXT[lang] + f = background() + # the HypeBlock face, big, on the right + glow(f, 1060, 330, 300, (255, 40, 60), 0.55) + face = mc.hb_texture("hypeblock_active").resize((352, 352), Image.NEAREST) + shadow = Image.new("RGBA", face.size, (0, 0, 0, 170)) + fx.over(f, Image.composite(shadow, Image.new("RGBA", face.size, (0, 0, 0, 0)), face.getchannel("A")), 892, 168) + fx.over(f, face, 880, 150) + # titles in the game font + fx.over(f, mc.text_image(l1, 10, 0xFFFFFF, bold=True), 60, 150) + fx.over(f, mc.text_image(l2, 10, 0xFF5555, bold=True), 60, 280) + fx.over(f, mc.text_image(sub, 4, 0xFFFF55), 64, 440) + # a HUD-style heart rate tile + tile = mc.text_image("128 BPM", 5, 0xFFFFFF) + x, y = 64, 540 + f[y - 14:y + tile.height + 12, x - 14:x + tile.width + 90] = ( + f[y - 14:y + tile.height + 12, x - 14:x + tile.width + 90].astype(np.float32) * 0.35).astype(np.uint8) + heart = mc.hb_texture("hypeblock_active").crop((3, 3, 13, 13)).resize((60, 60), Image.NEAREST) + fx.over(f, heart, x, y - 6) + fx.over(f, tile, x + 76, y) + path = os.path.join(OUT, f"thumbnail-{lang}.jpg") + Image.fromarray(f).save(path, quality=90) + print("wrote", path, os.path.getsize(path) // 1024, "KB") + + +if __name__ == "__main__": + os.makedirs(OUT, exist_ok=True) + for lang in TEXT: + make(lang) diff --git a/tools/trailer/voiceover.py b/tools/trailer/voiceover.py new file mode 100644 index 0000000..f308bc3 --- /dev/null +++ b/tools/trailer/voiceover.py @@ -0,0 +1,92 @@ +"""Records the voice-over lines with ElevenLabs (voice "Henny"). + + python tools/trailer/voiceover.py [--lang en|de] [--only v03,v14] [--list] + +The API key is read from elevenlabs-api-key.txt in the repo root (git-ignored), never from the code. +Voice and model can be overridden with ELEVEN_VOICE_ID / ELEVEN_MODEL; by default the voice named +"Henny" and the newest v4 model the key can use are picked. Output: build/trailer/vo//.mp3 +""" +import argparse +import json +import os +import sys +import urllib.request + +sys.path.insert(0, os.path.dirname(__file__)) +import mc # noqa: E402 +from script import LINES # noqa: E402 + +API = "https://api.elevenlabs.io" + + +def key(): + path = os.path.join(mc.ROOT, "elevenlabs-api-key.txt") + if not os.path.exists(path): + raise SystemExit("Put the ElevenLabs API key into elevenlabs-api-key.txt in the repo root") + return open(path).read().strip() + + +def call(path, body=None, raw=False): + req = urllib.request.Request(API + path, data=json.dumps(body).encode() if body is not None else None, + headers={"xi-api-key": key(), "Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=120) as r: + data = r.read() + except urllib.error.HTTPError as e: + raise SystemExit(f"ElevenLabs {path.split('?')[0]}: HTTP {e.code} {e.read()[:500].decode(errors='replace')}") + return data if raw else json.loads(data) + + +def find_voice(): + if os.environ.get("ELEVEN_VOICE_ID"): + return os.environ["ELEVEN_VOICE_ID"], "env" + voices = call("/v2/voices?search=Henny&page_size=50").get("voices", []) + if not voices: + raise SystemExit("No voice named Henny found for this API key") + v = voices[0] + return v["voice_id"], v["name"] + + +def find_model(): + if os.environ.get("ELEVEN_MODEL"): + return os.environ["ELEVEN_MODEL"] + models = call("/v1/models") + tts = [m for m in models if m.get("can_do_text_to_speech")] + v4 = [m for m in tts if "v4" in m["model_id"].lower() or "v4" in m.get("name", "").lower()] + if not v4: + raise SystemExit("No v4 model for this key. Models: " + ", ".join(m["model_id"] for m in tts)) + return v4[0]["model_id"] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--lang", default="en", choices=["en", "de"]) + ap.add_argument("--only", default="") + ap.add_argument("--list", action="store_true") + args = ap.parse_args() + voice, vname = find_voice() + model = find_model() + print(f"voice {vname} ({voice}), model {model}") + if args.list: + return + out = os.path.join(mc.ROOT, "build/trailer/vo", args.lang) + os.makedirs(out, exist_ok=True) + only = set(filter(None, args.only.split(","))) + texts = [(i, en if args.lang == "en" else de) for i, _, _, en, de in LINES] + for n, (lid, text) in enumerate(texts): + if only and lid not in only: + continue + body = { + "text": text, + "model_id": model, + "previous_text": texts[n - 1][1] if n > 0 else None, + "next_text": texts[n + 1][1] if n + 1 < len(texts) else None, + } + audio = call(f"/v1/text-to-speech/{voice}?output_format=mp3_44100_128", body, raw=True) + with open(os.path.join(out, lid + ".mp3"), "wb") as fh: + fh.write(audio) + print(lid, len(audio), "bytes:", text) + + +if __name__ == "__main__": + main()