Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

addons: add Koi Pond, a pixel-art koi pond screensaver and card

nottoobrightef49a8a3c029
diff --git a/addons/README.md b/addons/README.md
index c88aadef5..eb67d43b0 100644
--- a/addons/README.md
+++ b/addons/README.md
@@ -43,6 +43,7 @@ the core bigger or change how it behaves. You install an add-on only if you want
| [Haunted](haunted/) | A Halloween screensaver (and a card that starts it): the theme's night photos crossfading, bats drifting across, a ghost floating up, a flickering jack-o'-lantern glow and a small clock, drawn on the TV with no network | CleanYourTV contributors | Not yet tested on a real TV | None | <img src="haunted/screenshot.jpg" width="240" alt="Haunted on a TV"> |
| [Lịch Vạn Niên](lich-van-nien/) | Vietnamese lunar almanac, offline: the tile says whether today is hoàng đạo (auspicious) or hắc đạo and lists the day's good hours; OK opens the lunar date, can chi, the day's star and trực, a 12-hour ring with the zodiac animals, and what the day suits or should avoid; Left/Right page through days | [@mevvmevvcodinggarg](https://github.com/mevvmevvcodinggarg) | Expressluck AiPro4K (sepolia), Android TV 14 | start at boot (re-enable today's tile) | <img src="lich-van-nien/screenshot.jpg" width="240" alt="Lịch Vạn Niên on a TV"> |
| [Neon Dream](neon-dream/) | A neon screensaver and a card: a city in the rain or a synthwave grid with a clock drifting over it; scene, colours (magenta, amber, green) and clock are set in its own screen, with a Preview and a shortcut to the screensaver menu | [@SmartGenius2](https://github.com/SmartGenius2) | Challenger R3 (Android TV 11) | None | <img src="neon-dream/screenshot.jpg" width="240" alt="Neon Dream on a TV"> |
+| [Koi Pond](koi-pond/) | A pixel-art koi pond seen from above as the screensaver and a card: koi and fry over a rippling, light-netted floor, lily pads and lotus, the time of day from the clock with fireflies after dark, rain now and then, and on the card OK starts a breathing guide (in 4 s, out 6 s) while arrows drop a pebble; drawn on the TV with no network | [@nottoobright](https://github.com/nottoobright) | TCL Smart TV Pro G08 (Google TV 14) | None | <img src="koi-pond/screenshot.jpg" width="240" alt="Koi Pond on a TV"> |
A widget, an info tile, a storage or smart-home card: if it can live as its own small app, it can live
here. See the rules below.
diff --git a/addons/koi-pond/.gitignore b/addons/koi-pond/.gitignore
new file mode 100644
index 000000000..a7e04a21b
--- /dev/null
+++ b/addons/koi-pond/.gitignore
@@ -0,0 +1,4 @@
+.gradle/
+build/
+app/build/
+local.properties
diff --git a/addons/koi-pond/README.md b/addons/koi-pond/README.md
new file mode 100644
index 000000000..7c2934943
--- /dev/null
+++ b/addons/koi-pond/README.md
@@ -0,0 +1,89 @@
+# Koi Pond
+
+A calm koi pond seen from above, in pixel art, as the TV's screensaver and as a card on Home. Koi swim in pairs and
+alone, their shadows sliding over the pond floor; small fry dart about in schools; lily pads, lotus flowers and
+duckweed float at the edges, and light ripples across the floor.
+
+- **Water that moves.** A real ripple simulation: rain drops, surfacing koi and pebbles send out rings that bend
+ the light on the floor.
+- **The time of day, from the TV's clock.** Dawn, day, golden hour, dusk and night, blended slowly into each
+ other; fireflies blink over the pond after dark.
+- **Rain now and then.** Every 20 to 40 minutes a shower of a few minutes: drops land on the water, the light
+ dims a little and the fish go deeper.
+- **A breathing guide** (on the card): press OK and a soft ring grows as you breathe in (4 s) and shrinks as you
+ breathe out (6 s), while the koi gather around it. Each time the breath turns, a ring of ripples rolls out across
+ the water, so you can follow it without reading the label. OK again stops it.
+
+The pond is drawn at 480x270 and scaled up with sharp pixels, on one render thread at about 30 frames a second, so
+it stays light on a 1 GB TV. The fish, pads, flowers, icon and banner are drawn in code for this add-on.
+
+On cleanyourtv's Home it is a module card, **Koi Pond**:
+
+| Key | What it does |
+|---|---|
+| OK | Start or stop the breathing guide |
+| Arrows | Drop a pebble: a ripple, and the fish scatter |
+| Back | Leave |
+
+As a screensaver any key wakes the TV, as usual.
+
+- Package: `io.github.nottoobright.koipond`
+- Author: [@nottoobright](https://github.com/nottoobright)
+- Tested on: TCL Smart TV Pro G08 (G08_4K_GB), Google TV 14, firmware UTT2.250416.001, 7 Nov 2026: card and screensaver, all five times of day, rain, pebbles and the breathing guide; about 10 ms a frame (99th percentile 12 ms, 16 ms in the rain) against a 33 ms budget; any key wakes the screensaver back to Home. `am start com.android.systemui/.Somnambulator` does not start a screensaver on this TV; a short `screen_off_timeout` does
+
+## Permissions
+
+None. No network access (no `INTERNET` permission): nothing leaves the TV. No background service: it runs only
+while the screensaver or the card's screen is showing.
+
+## Build and install
+
+JDK 17 and Android SDK 34, as for the launcher. From the repo root, build, install and make it the screensaver in
+one go:
+
+```bash
+TV_HOST=<tv ip> addons/koi-pond/build-and-install.sh
+```
+
+On Windows: `addons\koi-pond\build-and-install.ps1 -TvHost <tv ip>`. Add `START=1` (or `-Start`) to see it now.
+No JDK? Build in Docker with `tools/docker-build.sh addons/koi-pond`, then install with `SKIP_BUILD=1` (or
+`-SkipBuild`). The script keeps the screensaver the TV had before, in `/data/local/tmp/cyt-koipond-before`.
+
+Or by hand, as for any add-on:
+
+```bash
+cd addons/koi-pond && ./gradlew assembleRelease && cd ../..
+TV_HOST=<tv ip> tools/venv/bin/python -I tools/tv.py --push addons/koi-pond/app/build/outputs/apk/release/app-release.apk /data/local/tmp/addon.apk
+TV_HOST=<tv ip> tools/venv/bin/python -I tools/tv.py 'pm install -r /data/local/tmp/addon.apk; rm -f /data/local/tmp/addon.apk'
+```
+
+then pick **Koi Pond** as the screensaver in Settings (Device Preferences > Screen saver, or System > Ambient mode on
+Google TV; the menu's name depends on the TV). If the menu does not list it, the script above sets it with
+`settings put secure screensaver_components` instead.
+
+## Undo
+
+```bash
+TV_HOST=<tv ip> addons/koi-pond/build-and-install.sh --uninstall
+```
+
+puts the previous screensaver back and removes the app. Without the script: pick another screensaver in Settings,
+then `TV_HOST=<tv ip> tools/venv/bin/python -I tools/tv.py 'pm uninstall io.github.nottoobright.koipond'`.
+
+## See a time of day or the rain now
+
+The card's screen takes three extras, handy for a screenshot:
+
+```bash
+TV_HOST=<tv ip> tools/venv/bin/python -I tools/tv.py 'am start -n io.github.nottoobright.koipond/.PondActivity --ei minute 1260 --ez rain true'
+```
+
+`minute` fixes the clock (minutes after midnight: 360 dawn, 720 day, 1050 golden hour, 1140 dusk, 1260 night),
+`rain` starts a shower at once and `breathe` starts the breathing guide.
+
+## Change the look
+
+- Colours of each time of day: the five palettes in `TimeOfDay.java`, and when each begins in its anchors.
+- How often it rains and for how long: the rain schedule in `PondModel.java`.
+- The fish: varieties, sizes and speeds in `PondModel.java`; their colours and shapes in `PondRenderer.java`.
+- The breathing rhythm: `IN_MS` and `OUT_MS` in `Breath.java`.
diff --git a/addons/koi-pond/app/build.gradle b/addons/koi-pond/app/build.gradle
new file mode 100644
index 000000000..bc73cab28
--- /dev/null
+++ b/addons/koi-pond/app/build.gradle
@@ -0,0 +1,35 @@
+plugins {
+ id 'com.android.application'
+}
+
+dependencies {
+ testImplementation 'junit:junit:4.13.2'
+}
+
+android {
+ namespace 'io.github.nottoobright.koipond'
+ compileSdk 34
+
+ defaultConfig {
+ applicationId 'io.github.nottoobright.koipond'
+ minSdk 26
+ targetSdk 34
+ versionCode 1
+ versionName '1.0'
+ }
+
+ buildTypes {
+ release {
+ minifyEnabled true
+ shrinkResources true
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt')
+ // Sideloaded over ADB like the launcher: signed with the debug key.
+ signingConfig signingConfigs.debug
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_17
+ targetCompatibility JavaVersion.VERSION_17
+ }
+}
diff --git a/addons/koi-pond/app/src/main/AndroidManifest.xml b/addons/koi-pond/app/src/main/AndroidManifest.xml
new file mode 100644
index 000000000..37bfa0da9
--- /dev/null
+++ b/addons/koi-pond/app/src/main/AndroidManifest.xml
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- No permissions: the pond is drawn on the TV, nothing goes over the network. -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <uses-feature android:name="android.software.leanback" android:required="false" />
+ <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
+
+ <application
+ android:allowBackup="false"
+ android:banner="@drawable/banner"
+ android:icon="@drawable/icon"
+ android:label="@string/app_name"
+ android:supportsRtl="false">
+
+ <!-- The tile, and the card on cleanyourtv's Home (docs/modules.md): the pond until Back, OK to breathe. -->
+ <activity
+ android:name=".PondActivity"
+ android:exported="true"
+ android:screenOrientation="landscape"
+ android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
+ </intent-filter>
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="com.gathin.tvhome.category.DOCK_CARD" />
+ </intent-filter>
+ <meta-data android:name="com.gathin.tvhome.card" android:resource="@xml/module_card" />
+ </activity>
+
+ <!-- The screensaver: Settings > System > Ambient mode / Screen saver > Koi Pond (the menu's name depends on the TV). -->
+ <service
+ android:name=".PondDream"
+ android:exported="true"
+ android:label="@string/app_name"
+ android:permission="android.permission.BIND_DREAM_SERVICE">
+ <intent-filter>
+ <action android:name="android.service.dreams.DreamService" />
+ <category android:name="android.intent.category.DEFAULT" />
+ </intent-filter>
+ </service>
+ </application>
+</manifest>
diff --git a/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/Breath.java b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/Breath.java
new file mode 100644
index 000000000..2d2981461
--- /dev/null
+++ b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/Breath.java
@@ -0,0 +1,34 @@
+package io.github.nottoobright.koipond;
+
+/** The breathing rhythm: in 4 s, out 6 s, repeating, with a sine ease so the ring never jerks. */
+final class Breath {
+
+ static final long IN_MS = 4000, OUT_MS = 6000, CYCLE_MS = IN_MS + OUT_MS;
+
+ private Breath() {
+ }
+
+ /** Ring size 0..1, eased (sine in/out): 0 at the start of an in-breath, 1 at its end, back to 0 at the end of the out-breath. */
+ static float size(long elapsedMs) {
+ long e = phaseMs(elapsedMs);
+ if (e < IN_MS) {
+ return (float) (0.5 - 0.5 * Math.cos(Math.PI * e / IN_MS));
+ }
+ return (float) (0.5 + 0.5 * Math.cos(Math.PI * (e - IN_MS) / OUT_MS));
+ }
+
+ static boolean inhaling(long elapsedMs) {
+ return phaseMs(elapsedMs) < IN_MS;
+ }
+
+ /** Whole seconds left in the current phase, counting down 4..1 or 6..1. */
+ static int secondsLeft(long elapsedMs) {
+ long e = phaseMs(elapsedMs);
+ long left = e < IN_MS ? IN_MS - e : CYCLE_MS - e;
+ return (int) ((left + 999) / 1000);
+ }
+
+ private static long phaseMs(long elapsedMs) {
+ return Math.max(0L, elapsedMs) % CYCLE_MS;
+ }
+}
diff --git a/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/Palette.java b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/Palette.java
new file mode 100644
index 000000000..1a77f0cad
--- /dev/null
+++ b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/Palette.java
@@ -0,0 +1,82 @@
+package io.github.nottoobright.koipond;
+
+/**
+ * The colours of the pond at one moment of the day, all 0xFFRRGGBB. Immutable, so one instance can be shared
+ * between the clock and the render thread.
+ */
+final class Palette {
+
+ /** Darkest floor colour (floor texture 0). */
+ final int deep;
+ /** Lightest floor colour (floor texture 255). */
+ final int floor;
+ /** Light the caustic net adds at full strength. */
+ final int caustic;
+ /** Per-channel multiplier for the whole frame; 0xFFFFFFFF leaves it unchanged. */
+ final int ambient;
+ final int padDark, padLight, padVein;
+ final int lotus, lotusCore;
+ final int duckweed;
+
+ Palette(int deep, int floor, int caustic, int ambient, int padDark, int padLight, int padVein,
+ int lotus, int lotusCore, int duckweed) {
+ this.deep = deep;
+ this.floor = floor;
+ this.caustic = caustic;
+ this.ambient = ambient;
+ this.padDark = padDark;
+ this.padLight = padLight;
+ this.padVein = padVein;
+ this.lotus = lotus;
+ this.lotusCore = lotusCore;
+ this.duckweed = duckweed;
+ }
+
+ /** Every colour blended with {@link TimeOfDay#lerp}; t is clamped, and the ends return a or b themselves. */
+ static Palette lerp(Palette a, Palette b, float t) {
+ if (a == b || t <= 0f) return a;
+ if (t >= 1f) return b;
+ return new Palette(
+ TimeOfDay.lerp(a.deep, b.deep, t),
+ TimeOfDay.lerp(a.floor, b.floor, t),
+ TimeOfDay.lerp(a.caustic, b.caustic, t),
+ TimeOfDay.lerp(a.ambient, b.ambient, t),
+ TimeOfDay.lerp(a.padDark, b.padDark, t),
+ TimeOfDay.lerp(a.padLight, b.padLight, t),
+ TimeOfDay.lerp(a.padVein, b.padVein, t),
+ TimeOfDay.lerp(a.lotus, b.lotus, t),
+ TimeOfDay.lerp(a.lotusCore, b.lotusCore, t),
+ TimeOfDay.lerp(a.duckweed, b.duckweed, t));
+ }
+
+ /** The colours in field order, for comparing palettes channel by channel. */
+ int[] colors() {
+ return new int[] {deep, floor, caustic, ambient, padDark, padLight, padVein, lotus, lotusCore, duckweed};
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof Palette)) return false;
+ Palette p = (Palette) o;
+ return deep == p.deep && floor == p.floor && caustic == p.caustic && ambient == p.ambient
+ && padDark == p.padDark && padLight == p.padLight && padVein == p.padVein
+ && lotus == p.lotus && lotusCore == p.lotusCore && duckweed == p.duckweed;
+ }
+
+ @Override
+ public int hashCode() {
+ return java.util.Arrays.hashCode(colors());
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder s = new StringBuilder("Palette[");
+ int[] c = colors();
+ for (int i = 0; i < c.length; i++) {
+ if (i > 0) s.append(' ');
+ s.append(String.format("%08X", c[i]));
+ }
+ return s.append(']').toString();
+ }
+}
diff --git a/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/PondActivity.java b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/PondActivity.java
new file mode 100644
index 000000000..28d5edca0
--- /dev/null
+++ b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/PondActivity.java
@@ -0,0 +1,81 @@
+package io.github.nottoobright.koipond;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.os.Bundle;
+import android.view.KeyEvent;
+import android.view.View;
+import android.view.WindowManager;
+
+/** The tile and the card: the pond full screen until Back; OK starts the breathing guide, arrows drop a pebble. */
+public class PondActivity extends Activity {
+
+ private PondView view;
+
+ @Override
+ protected void onCreate(Bundle state) {
+ super.onCreate(state);
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+ view = new PondView(this);
+ setContentView(view);
+ hideSystemUi();
+ view.setShowHint(true);
+
+ // Debug and screenshot extras: am start ... --ei minute 1080 --ez rain true --ez breathe true
+ Intent intent = getIntent();
+ int minute = intent.getIntExtra("minute", -1);
+ if (minute >= 0) view.setFixedMinute(minute);
+ if (intent.getBooleanExtra("rain", false)) view.startRain();
+ if (intent.getBooleanExtra("breathe", false)) view.toggleBreath();
+ }
+
+ @SuppressWarnings("deprecation")
+ private void hideSystemUi() {
+ // The systemUiVisibility flags still work on API 26..34; WindowInsetsController needs API 30.
+ view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
+ | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
+ | View.SYSTEM_UI_FLAG_FULLSCREEN
+ | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
+ | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
+ | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
+ }
+
+ @Override
+ public void onWindowFocusChanged(boolean hasFocus) {
+ super.onWindowFocusChanged(hasFocus);
+ if (hasFocus) hideSystemUi();
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ view.start();
+ }
+
+ @Override
+ protected void onPause() {
+ view.stop();
+ super.onPause();
+ }
+
+ @Override
+ public boolean onKeyDown(int keyCode, KeyEvent event) {
+ switch (keyCode) {
+ case KeyEvent.KEYCODE_DPAD_CENTER:
+ case KeyEvent.KEYCODE_ENTER:
+ case KeyEvent.KEYCODE_NUMPAD_ENTER:
+ case KeyEvent.KEYCODE_BUTTON_A:
+ // A held OK would flip the guide on and off with every repeat.
+ if (event.getRepeatCount() == 0) view.toggleBreath();
+ return true;
+ case KeyEvent.KEYCODE_DPAD_UP:
+ case KeyEvent.KEYCODE_DPAD_DOWN:
+ case KeyEvent.KEYCODE_DPAD_LEFT:
+ case KeyEvent.KEYCODE_DPAD_RIGHT:
+ if (event.getRepeatCount() == 0) view.pebble();
+ return true;
+ default:
+ return super.onKeyDown(keyCode, event);
+ }
+ }
+}
diff --git a/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/PondDream.java b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/PondDream.java
new file mode 100644
index 000000000..7167c8ad8
--- /dev/null
+++ b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/PondDream.java
@@ -0,0 +1,31 @@
+package io.github.nottoobright.koipond;
+
+import android.service.dreams.DreamService;
+
+/** The screensaver: the pond without hint or breathing guide, until any key wakes the TV. */
+public class PondDream extends DreamService {
+
+ private PondView view;
+
+ @Override
+ public void onAttachedToWindow() {
+ super.onAttachedToWindow();
+ setInteractive(false);
+ setFullscreen(true);
+ setScreenBright(true);
+ view = new PondView(this);
+ setContentView(view);
+ }
+
+ @Override
+ public void onDreamingStarted() {
+ super.onDreamingStarted();
+ view.start();
+ }
+
+ @Override
+ public void onDreamingStopped() {
+ view.stop();
+ super.onDreamingStopped();
+ }
+}
diff --git a/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/PondModel.java b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/PondModel.java
new file mode 100644
index 000000000..de1332fd1
--- /dev/null
+++ b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/PondModel.java
@@ -0,0 +1,1056 @@
+package io.github.nottoobright.koipond;
+
+import java.util.Random;
+
+/**
+ * Everything that moves in the pond, in pond pixels (W x H): koi, fry schools, lily pads, duckweed, fireflies and
+ * the rain schedule. Pure Java and deterministic for a seed: one Random, used only here. Everything is allocated in
+ * the constructor, so step() can run every frame on the render thread without feeding the garbage collector.
+ */
+final class PondModel {
+
+ static final int W = 480, H = 270;
+ static final int KOHAKU = 0, SHOWA = 1, OGON = 2, ASAGI = 3, CHAGOI = 4, SANKE = 5, SPINE = 10;
+
+ private static final float PI = (float) Math.PI, TWO_PI = 2f * PI;
+ private static final int KOI_COUNT = 8, SCHOOLS = 3, PER_SCHOOL = 8, FIREFLY_COUNT = 16;
+
+ // Koi steering. Edge avoidance starts EDGE_ZONE px before the EDGE margin, so turns begin early and stay gentle.
+ private static final float EDGE = 16f, EDGE_ZONE = 50f, LOOK_AHEAD = 12f;
+ private static final float KOI_TURN = 0.8f, KOI_FLEE_SPEED = 45f;
+ private static final float ORBIT_RATE = 0.15f; // rad/s round the breathing ring: 58..72 px radius gives 9..11 px/s
+
+ private static final float FRY_SPEED = 20f, FRY_FLEE_SPEED = 70f, FRY_SEPARATION = 3f;
+ private static final float SCATTER_RADIUS = 120f, FLEE_SECONDS = 3f;
+
+ private static final long MINUTE_MS = 60_000L, RAIN_FADE_MS = 30_000L;
+
+ private static final int DROP_CAPACITY = 64;
+
+ final Koi[] koi;
+ final Fry[] fry;
+ final Pad[] pads;
+ final int[] duckweed;
+ final Firefly[] fireflies;
+
+ private final Random rng;
+ private double time; // seconds of model time, summed from the clamped dt
+
+ // Pending ripple drops, a ring buffer: when full the oldest drop is overwritten.
+ private final float[] dropX = new float[DROP_CAPACITY], dropY = new float[DROP_CAPACITY];
+ private final int[] dropStrength = new int[DROP_CAPACITY];
+ private int dropHead, dropCount;
+
+ // Rain: the schedule is anchored on the first nowMs that step() sees.
+ private final long firstRainDelayMs;
+ private boolean clockStarted;
+ private long rainStartMs, rainEndMs;
+ private float rainLevel, rainAccumulator;
+
+ // Breathing gather.
+ private boolean gatherOn;
+ private float gatherX = W / 2f, gatherY = H / 2f, gatherWeight, orbitPhase;
+ private final int[] slot = new int[KOI_COUNT];
+ private final int[] order = new int[KOI_COUNT];
+ private final float[] orderAngle = new float[KOI_COUNT];
+
+ // Fry schools: a slowly wandering target each, and per-step centroid and mean velocity.
+ private final float[] schoolX = new float[SCHOOLS], schoolY = new float[SCHOOLS];
+ private final float[] schoolAngle = new float[SCHOOLS], schoolTurn = new float[SCHOOLS];
+ private final float[] schoolTimer = new float[SCHOOLS];
+ private final float[] centreX = new float[SCHOOLS], centreY = new float[SCHOOLS];
+ private final float[] meanVx = new float[SCHOOLS], meanVy = new float[SCHOOLS];
+ private final int[] schoolSize = new int[SCHOOLS];
+
+ // Duckweed: origins, the cluster each point belongs to, and each cluster's current whole-pixel drift.
+ private final int[] weedX, weedY, weedCluster;
+ private final float[] clusterPhase;
+ private final int[] clusterDx, clusterDy;
+
+ /** One koi. The head leads; the spine follows it like a chain. */
+ static final class Koi {
+ float x, y;
+ float heading;
+ float speed;
+ final int variety;
+ final float length;
+ float depth;
+ float wiggle;
+ final float[] spineX = new float[SPINE], spineY = new float[SPINE];
+ final long pattern;
+
+ private float cruise, cruiseTimer;
+ private float wanderAngle, wanderRate, wanderTimer;
+ private float turn;
+ private int buddy = -1;
+ private float buddyTimer;
+ private float depthTarget, depthTimer;
+ private boolean surfacing;
+ private float surfaceTimer;
+ private float flee, fleeX, fleeY;
+ private float orbitRadius;
+
+ Koi(int variety, float length, long pattern) {
+ this.variety = variety;
+ this.length = length;
+ this.pattern = pattern;
+ }
+ }
+
+ /** One small fish of a school. */
+ static final class Fry {
+ float x, y, heading;
+ final int color;
+ final int school;
+
+ private float vx, vy;
+ private final float pace;
+ private float flee, fleeX, fleeY;
+
+ Fry(int color, int school, float pace) {
+ this.color = color;
+ this.school = school;
+ this.pace = pace;
+ }
+ }
+
+ /** A lily pad. x, y drift a pixel or two around the origin it was placed at. */
+ static final class Pad {
+ float x, y;
+ final float r;
+ final float notch;
+ final boolean lotus;
+ final float phase;
+
+ private final float originX, originY;
+
+ Pad(float x, float y, float r, float notch, boolean lotus, float phase) {
+ this.originX = this.x = x;
+ this.originY = this.y = y;
+ this.r = r;
+ this.notch = notch;
+ this.lotus = lotus;
+ this.phase = phase;
+ }
+ }
+
+ /** A firefly; the renderer shows it after dark. */
+ static final class Firefly {
+ float x, y;
+ final float phase;
+
+ private float angle, pace, homeX, homeY, homeTimer;
+
+ Firefly(float phase) {
+ this.phase = phase;
+ }
+ }
+
+ PondModel(long seed) {
+ rng = new Random(seed);
+ koi = makeKoi();
+ fry = makeFry();
+ pads = makePads();
+
+ int clusters = 6 + rng.nextInt(5);
+ clusterPhase = new float[clusters];
+ clusterDx = new int[clusters];
+ clusterDy = new int[clusters];
+ int[] tx = new int[clusters * 90], ty = new int[clusters * 90], tc = new int[clusters * 90];
+ int n = makeDuckweed(clusters, tx, ty, tc);
+ weedX = new int[n];
+ weedY = new int[n];
+ weedCluster = new int[n];
+ System.arraycopy(tx, 0, weedX, 0, n);
+ System.arraycopy(ty, 0, weedY, 0, n);
+ System.arraycopy(tc, 0, weedCluster, 0, n);
+ duckweed = new int[n];
+
+ fireflies = makeFireflies();
+ firstRainDelayMs = 6 * MINUTE_MS + (long) (rng.nextFloat() * 8 * MINUTE_MS);
+
+ driftPads();
+ driftDuckweed(true);
+ }
+
+ // ---- public API --------------------------------------------------------------------------------------------
+
+ void step(float dt, long nowMs) {
+ if (!(dt > 0f)) dt = 0f; // also catches NaN
+ if (dt > 0.1f) dt = 0.1f;
+ time += dt;
+
+ stepRain(dt, nowMs);
+
+ float gatherGoal = gatherOn ? 1f : 0f;
+ gatherWeight += clamp(gatherGoal - gatherWeight, -dt / 2.5f, dt / 2.5f);
+ orbitPhase = wrap(orbitPhase + ORBIT_RATE * dt);
+
+ stepKoi(dt);
+ stepSchools(dt);
+ stepFry(dt);
+ driftPads();
+ driftDuckweed(false);
+ stepFireflies(dt);
+ }
+
+ void setGather(boolean on, float x, float y) {
+ if (!on) {
+ gatherOn = false;
+ return;
+ }
+ if (gatherOn && x == gatherX && y == gatherY) return; // already gathering there: keep the slots
+ gatherOn = true;
+ gatherX = x;
+ gatherY = y;
+ // Hand out ring slots in the order the koi already lie round the point, so nobody has to cross the circle.
+ for (int i = 0; i < KOI_COUNT; i++) {
+ order[i] = i;
+ orderAngle[i] = (float) Math.atan2(koi[i].y - y, koi[i].x - x);
+ }
+ for (int i = 1; i < KOI_COUNT; i++) {
+ int o = order[i];
+ float a = orderAngle[o];
+ int j = i - 1;
+ while (j >= 0 && orderAngle[order[j]] > a) {
+ order[j + 1] = order[j];
+ j--;
+ }
+ order[j + 1] = o;
+ }
+ for (int j = 0; j < KOI_COUNT; j++) {
+ Koi k = koi[order[j]];
+ slot[order[j]] = j;
+ // Outside the largest ring (46 px, glow to about 51), so the koi circle round it, not under it.
+ k.orbitRadius = 58f + 14f * rng.nextFloat();
+ }
+ orbitPhase = orderAngle[order[0]];
+ }
+
+ void scatter(float x, float y) {
+ queueDrop(x, y, 600);
+ for (Koi k : koi) {
+ float dx = k.x - x, dy = k.y - y;
+ float d = (float) Math.sqrt(dx * dx + dy * dy);
+ if (d >= SCATTER_RADIUS) continue;
+ float level = 0.35f + 0.65f * (1f - d / SCATTER_RADIUS);
+ if (level > k.flee) k.flee = level;
+ if (d > 0.5f) {
+ k.fleeX = dx / d;
+ k.fleeY = dy / d;
+ } else {
+ k.fleeX = (float) Math.cos(k.heading);
+ k.fleeY = (float) Math.sin(k.heading);
+ }
+ }
+ for (Fry f : fry) {
+ float dx = f.x - x, dy = f.y - y;
+ float d = (float) Math.sqrt(dx * dx + dy * dy);
+ if (d >= SCATTER_RADIUS) continue;
+ float level = 0.4f + 0.6f * (1f - d / SCATTER_RADIUS);
+ if (level > f.flee) f.flee = level;
+ if (d > 0.5f) {
+ f.fleeX = dx / d;
+ f.fleeY = dy / d;
+ } else {
+ float a = rng.nextFloat() * TWO_PI;
+ f.fleeX = (float) Math.cos(a);
+ f.fleeY = (float) Math.sin(a);
+ }
+ }
+ // Move each nearby school's target away too, or the fry would dart straight back.
+ for (int s = 0; s < SCHOOLS; s++) {
+ float dx = schoolX[s] - x, dy = schoolY[s] - y;
+ float d = (float) Math.sqrt(dx * dx + dy * dy);
+ if (d >= SCATTER_RADIUS) continue;
+ if (d < 0.5f) {
+ dx = 1f;
+ dy = 0f;
+ d = 1f;
+ }
+ float push = SCATTER_RADIUS - d;
+ schoolX[s] = clamp(schoolX[s] + dx / d * push, 30f, W - 30f);
+ schoolY[s] = clamp(schoolY[s] + dy / d * push, 25f, H - 25f);
+ schoolAngle[s] = (float) Math.atan2(dy, dx);
+ }
+ }
+
+ void startRain(long nowMs) {
+ clockStarted = true;
+ // If a shower is already falling, carry on from its current level instead of dropping to zero.
+ rainStartMs = nowMs - (long) (rainLevelAt(nowMs) * RAIN_FADE_MS);
+ rainEndMs = nowMs + rainDurationMs();
+ }
+
+ float rainLevel() {
+ return rainLevel;
+ }
+
+ int drainDrops(float[] xs, float[] ys, int[] strengths, int max) {
+ int n = Math.min(Math.min(dropCount, max), Math.min(xs.length, Math.min(ys.length, strengths.length)));
+ if (n <= 0) return 0;
+ for (int i = 0; i < n; i++) {
+ int j = (dropHead + i) % DROP_CAPACITY;
+ xs[i] = dropX[j];
+ ys[i] = dropY[j];
+ strengths[i] = dropStrength[j];
+ }
+ dropHead = (dropHead + n) % DROP_CAPACITY;
+ dropCount -= n;
+ return n;
+ }
+
+ // ---- rain --------------------------------------------------------------------------------------------------
+
+ private void stepRain(float dt, long nowMs) {
+ if (!clockStarted) {
+ clockStarted = true;
+ rainStartMs = nowMs + firstRainDelayMs;
+ rainEndMs = rainStartMs + rainDurationMs();
+ }
+ if (nowMs >= rainEndMs) {
+ rainStartMs = rainEndMs + 20 * MINUTE_MS + (long) (rng.nextFloat() * 20 * MINUTE_MS);
+ rainEndMs = rainStartMs + rainDurationMs();
+ }
+ rainLevel = rainLevelAt(nowMs);
+ rainAccumulator += rainLevel * 10f * dt;
+ while (rainAccumulator >= 1f) {
+ rainAccumulator -= 1f;
+ queueDrop(6f + rng.nextFloat() * (W - 12f), 6f + rng.nextFloat() * (H - 12f), 80 + rng.nextInt(121));
+ }
+ if (rainLevel == 0f) rainAccumulator = 0f;
+ }
+
+ private float rainLevelAt(long nowMs) {
+ if (!clockStarted || nowMs < rainStartMs || nowMs >= rainEndMs) return 0f;
+ float in = (nowMs - rainStartMs) / (float) RAIN_FADE_MS;
+ float out = (rainEndMs - nowMs) / (float) RAIN_FADE_MS;
+ return Math.min(1f, Math.min(in, out));
+ }
+
+ private long rainDurationMs() {
+ return 3 * MINUTE_MS + (long) (rng.nextFloat() * 3 * MINUTE_MS);
+ }
+
+ private void queueDrop(float x, float y, int strength) {
+ if (dropCount == DROP_CAPACITY) {
+ dropHead = (dropHead + 1) % DROP_CAPACITY;
+ dropCount--;
+ }
+ int j = (dropHead + dropCount) % DROP_CAPACITY;
+ dropX[j] = x;
+ dropY[j] = y;
+ dropStrength[j] = strength;
+ dropCount++;
+ }
+
+ // ---- koi ---------------------------------------------------------------------------------------------------
+
+ private void stepKoi(float dt) {
+ float free = 1f - gatherWeight;
+ for (int i = 0; i < koi.length; i++) {
+ Koi k = koi[i];
+
+ if ((k.cruiseTimer -= dt) <= 0f) {
+ k.cruise = 8f + 8f * rng.nextFloat();
+ k.cruiseTimer = 4f + 8f * rng.nextFloat();
+ }
+ if ((k.wanderTimer -= dt) <= 0f) {
+ // Now and then a straight stretch, otherwise a gentle curve one way or the other.
+ k.wanderRate = rng.nextFloat() < 0.25f ? 0f : (rng.nextFloat() - 0.5f) * 0.6f;
+ k.wanderTimer = 2f + 6f * rng.nextFloat();
+ }
+ // The wander heading curves on its own and is pulled back towards the real heading, so other forces
+ // can bend the path without the two drifting apart.
+ k.wanderAngle = wrap(k.wanderAngle + k.wanderRate * dt
+ + wrap(k.heading - k.wanderAngle) * Math.min(1f, dt * 0.4f));
+
+ float fx = (float) Math.cos(k.wanderAngle) * free;
+ float fy = (float) Math.sin(k.wanderAngle) * free;
+ float speedGoal = k.cruise;
+
+ // Koi often swim in pairs: now and then one picks the nearest fish and keeps loosely beside it.
+ if ((k.buddyTimer -= dt) <= 0f) {
+ k.buddy = rng.nextFloat() < 0.55f ? nearestKoi(i) : -1;
+ k.buddyTimer = 12f + 25f * rng.nextFloat();
+ }
+ if (k.buddy >= 0 && free > 0f) {
+ Koi b = koi[k.buddy];
+ float dx = b.x - k.x, dy = b.y - k.y;
+ float d = (float) Math.sqrt(dx * dx + dy * dy);
+ if (d > 150f) {
+ k.buddy = -1;
+ } else {
+ float pull = clamp((d - 22f) / 40f, 0f, 1f);
+ if (d > 0.01f) {
+ fx += dx / d * pull * 0.8f * free;
+ fy += dy / d * pull * 0.8f * free;
+ }
+ fx += (float) Math.cos(b.heading) * 0.5f * free;
+ fy += (float) Math.sin(b.heading) * 0.5f * free;
+ speedGoal = speedGoal * 0.6f + b.speed * 0.4f + pull * 3f;
+ }
+ }
+
+ // Separation: the head keeps clear of every other koi's body.
+ for (int j = 0; j < koi.length; j++) {
+ if (j == i) continue;
+ Koi o = koi[j];
+ float minD = 0.6f * Math.max(k.length, o.length);
+ float reach = o.length + minD;
+ if (Math.abs(k.x - o.x) > reach || Math.abs(k.y - o.y) > reach) continue;
+ for (int s = 0; s < SPINE; s++) {
+ float dx = k.x - o.spineX[s], dy = k.y - o.spineY[s];
+ float d2 = dx * dx + dy * dy;
+ if (d2 >= minD * minD || d2 < 1e-6f) continue;
+ float d = (float) Math.sqrt(d2);
+ float w = (1f - d / minD) * 2.5f;
+ fx += dx / d * w;
+ fy += dy / d * w;
+ }
+ }
+
+ // Pond edge, tested a little ahead of the head so the turn starts before the edge.
+ float hx = (float) Math.cos(k.heading), hy = (float) Math.sin(k.heading);
+ float px = k.x + hx * LOOK_AHEAD, py = k.y + hy * LOOK_AHEAD;
+ float urgency = 0f;
+ float lo = EDGE + EDGE_ZONE;
+ float e;
+ if (px < lo) {
+ e = Math.min(2f, (lo - px) / EDGE_ZONE);
+ fx += e * e * 3f;
+ urgency = Math.max(urgency, e);
+ } else if (px > W - lo) {
+ e = Math.min(2f, (px - (W - lo)) / EDGE_ZONE);
+ fx -= e * e * 3f;
+ urgency = Math.max(urgency, e);
+ }
+ if (py < lo) {
+ e = Math.min(2f, (lo - py) / EDGE_ZONE);
+ fy += e * e * 3f;
+ urgency = Math.max(urgency, e);
+ } else if (py > H - lo) {
+ e = Math.min(2f, (py - (H - lo)) / EDGE_ZONE);
+ fy -= e * e * 3f;
+ urgency = Math.max(urgency, e);
+ }
+ urgency = Math.min(urgency, 1f);
+
+ if (k.flee > 0f) {
+ fx += k.fleeX * k.flee * 3f;
+ fy += k.fleeY * k.flee * 3f;
+ }
+
+ if (gatherWeight > 0f) {
+ float a = orbitPhase + slot[i] * TWO_PI / KOI_COUNT;
+ float ca = (float) Math.cos(a), sa = (float) Math.sin(a);
+ float r = k.orbitRadius > 0f ? k.orbitRadius : 65f;
+ float dx = gatherX + ca * r - k.x, dy = gatherY + sa * r - k.y;
+ float d = (float) Math.sqrt(dx * dx + dy * dy);
+ float w = gatherWeight * 1.6f;
+ if (d > 0.01f) {
+ float pull = Math.min(1f, d / 12f);
+ fx += dx / d * pull * w;
+ fy += dy / d * pull * w;
+ }
+ // Along the circle, so a koi that has reached its slot keeps swimming round with it.
+ fx -= sa * 0.7f * w;
+ fy += ca * 0.7f * w;
+ float orbitSpeed = clamp(ORBIT_RATE * r + d * 0.15f, 6f, 14f);
+ speedGoal += (orbitSpeed - speedGoal) * gatherWeight;
+ }
+
+ float goal = (fx * fx + fy * fy > 1e-8f) ? (float) Math.atan2(fy, fx) : k.heading;
+ float diff = wrap(goal - k.heading);
+ float maxTurn = KOI_TURN + k.flee * 2.2f + urgency * 1.4f;
+ float want = clamp(diff * 1.8f, -maxTurn, maxTurn);
+ // The turn rate itself eases, so a fish never snaps from one curve into another.
+ k.turn += (want - k.turn) * Math.min(1f, dt * (3f + 6f * (urgency + k.flee)));
+ k.heading = wrap(k.heading + k.turn * dt);
+
+ if (k.surfacing) speedGoal *= 0.75f;
+ speedGoal += (KOI_FLEE_SPEED - speedGoal) * k.flee;
+ speedGoal *= 1f - Math.min(0.3f, Math.abs(k.turn) * 0.2f);
+ k.speed += (speedGoal - k.speed) * Math.min(1f, dt * (0.6f + 5f * k.flee));
+
+ k.x = clamp(k.x + (float) Math.cos(k.heading) * k.speed * dt, 1f, W - 1f);
+ k.y = clamp(k.y + (float) Math.sin(k.heading) * k.speed * dt, 1f, H - 1f);
+ followSpine(k);
+
+ k.wiggle += dt * (2f + k.speed * 0.4f);
+ if (k.wiggle > TWO_PI) k.wiggle -= TWO_PI;
+
+ stepDepth(k, dt);
+ k.flee = Math.max(0f, k.flee - dt / FLEE_SECONDS);
+ }
+ }
+
+ private void stepDepth(Koi k, float dt) {
+ if ((k.depthTimer -= dt) <= 0f) {
+ k.depthTarget = 0.1f + 0.7f * rng.nextFloat();
+ k.depthTimer = 8f + 14f * rng.nextFloat();
+ }
+ if (!k.surfacing && (k.surfaceTimer -= dt) <= 0f && k.flee < 0.05f) k.surfacing = true;
+
+ float target, rate;
+ if (k.surfacing) {
+ target = 0.05f;
+ rate = 0.6f;
+ } else {
+ target = Math.min(1f, k.depthTarget + 0.25f * rainLevel);
+ rate = 0.12f;
+ }
+ k.depth += (target - k.depth) * Math.min(1f, dt * rate);
+
+ if (k.surfacing && k.depth < 0.08f) {
+ float hx = (float) Math.cos(k.heading), hy = (float) Math.sin(k.heading);
+ queueDrop(k.x + hx * 1.5f, k.y + hy * 1.5f, 110 + rng.nextInt(21));
+ k.surfacing = false;
+ k.surfaceTimer = 20f + 40f * rng.nextFloat();
+ }
+ }
+
+ private static void followSpine(Koi k) {
+ float spacing = k.length / (SPINE - 1);
+ k.spineX[0] = k.x;
+ k.spineY[0] = k.y;
+ // The direction the previous segment points backwards; each joint may bend at most MAX_BEND from it, so a
+ // sharp turn curves the whole body a little instead of folding it in two.
+ float px = -(float) Math.cos(k.heading), py = -(float) Math.sin(k.heading);
+ for (int s = 1; s < SPINE; s++) {
+ float dx = k.spineX[s] - k.spineX[s - 1], dy = k.spineY[s] - k.spineY[s - 1];
+ float d = (float) Math.sqrt(dx * dx + dy * dy);
+ float ux, uy;
+ if (d < 1e-4f) {
+ ux = px;
+ uy = py;
+ } else {
+ ux = dx / d;
+ uy = dy / d;
+ }
+ if (ux * px + uy * py < COS_BEND) {
+ float side = px * uy - py * ux >= 0f ? SIN_BEND : -SIN_BEND;
+ ux = px * COS_BEND - py * side;
+ uy = px * side + py * COS_BEND;
+ }
+ k.spineX[s] = k.spineX[s - 1] + ux * spacing;
+ k.spineY[s] = k.spineY[s - 1] + uy * spacing;
+ px = ux;
+ py = uy;
+ }
+ }
+
+ private static final float MAX_BEND = 0.36f;
+ private static final float COS_BEND = (float) Math.cos(MAX_BEND), SIN_BEND = (float) Math.sin(MAX_BEND);
+
+ private int nearestKoi(int i) {
+ int best = -1;
+ float bestD = Float.MAX_VALUE;
+ for (int j = 0; j < koi.length; j++) {
+ if (j == i) continue;
+ float dx = koi[j].x - koi[i].x, dy = koi[j].y - koi[i].y;
+ float d = dx * dx + dy * dy;
+ if (d < bestD) {
+ bestD = d;
+ best = j;
+ }
+ }
+ return best;
+ }
+
+ // ---- fry ---------------------------------------------------------------------------------------------------
+
+ private void stepSchools(float dt) {
+ for (int s = 0; s < SCHOOLS; s++) {
+ if ((schoolTimer[s] -= dt) <= 0f) {
+ schoolTurn[s] = (rng.nextFloat() - 0.5f) * 0.8f;
+ schoolTimer[s] = 2f + 5f * rng.nextFloat();
+ }
+ float a = schoolAngle[s] + schoolTurn[s] * dt;
+ float tx = schoolX[s], ty = schoolY[s];
+ float cx = 0f, cy = 0f;
+ if (tx < 60f) cx += 1f;
+ if (tx > W - 60f) cx -= 1f;
+ if (ty < 45f) cy += 1f;
+ if (ty > H - 45f) cy -= 1f;
+ if (gatherWeight > 0f) {
+ float dx = tx - gatherX, dy = ty - gatherY;
+ float d = (float) Math.sqrt(dx * dx + dy * dy);
+ if (d < 110f && d > 0.01f) {
+ cx += dx / d * 2f * gatherWeight;
+ cy += dy / d * 2f * gatherWeight;
+ }
+ }
+ if (cx != 0f || cy != 0f) {
+ float want = (float) Math.atan2(cy, cx);
+ a += clamp(wrap(want - a), -1.2f * dt, 1.2f * dt);
+ }
+ schoolAngle[s] = wrap(a);
+ schoolX[s] = clamp(tx + (float) Math.cos(a) * 14f * dt, 20f, W - 20f);
+ schoolY[s] = clamp(ty + (float) Math.sin(a) * 14f * dt, 20f, H - 20f);
+ }
+ }
+
+ private void stepFry(float dt) {
+ for (int s = 0; s < SCHOOLS; s++) {
+ centreX[s] = centreY[s] = meanVx[s] = meanVy[s] = 0f;
+ schoolSize[s] = 0;
+ }
+ for (Fry f : fry) {
+ centreX[f.school] += f.x;
+ centreY[f.school] += f.y;
+ meanVx[f.school] += f.vx;
+ meanVy[f.school] += f.vy;
+ schoolSize[f.school]++;
+ }
+ for (int s = 0; s < SCHOOLS; s++) {
+ int n = Math.max(1, schoolSize[s]);
+ centreX[s] /= n;
+ centreY[s] /= n;
+ meanVx[s] /= n;
+ meanVy[s] /= n;
+ }
+
+ for (int i = 0; i < fry.length; i++) {
+ Fry f = fry[i];
+ int s = f.school;
+ float ax = 0f, ay = 0f;
+
+ float dx = schoolX[s] - f.x, dy = schoolY[s] - f.y;
+ float d = (float) Math.sqrt(dx * dx + dy * dy);
+ if (d > 0.01f) {
+ float w = Math.min(1f, d / 25f);
+ ax += dx / d * w;
+ ay += dy / d * w;
+ }
+ dx = centreX[s] - f.x;
+ dy = centreY[s] - f.y;
+ d = (float) Math.sqrt(dx * dx + dy * dy);
+ if (d > 0.01f) {
+ float w = Math.min(1f, d / 15f) * 0.6f;
+ ax += dx / d * w;
+ ay += dy / d * w;
+ }
+ ax += meanVx[s] / FRY_SPEED * 0.6f;
+ ay += meanVy[s] / FRY_SPEED * 0.6f;
+
+ float sep = FRY_SEPARATION + 1f;
+ for (int j = 0; j < fry.length; j++) {
+ if (j == i) continue;
+ dx = f.x - fry[j].x;
+ dy = f.y - fry[j].y;
+ float d2 = dx * dx + dy * dy;
+ if (d2 >= sep * sep || d2 < 1e-6f) continue;
+ d = (float) Math.sqrt(d2);
+ float w = (1f - d / sep) * 2.5f;
+ ax += dx / d * w;
+ ay += dy / d * w;
+ }
+
+ for (Koi k : koi) {
+ dx = f.x - k.x;
+ dy = f.y - k.y;
+ float d2 = dx * dx + dy * dy;
+ if (d2 >= 22f * 22f || d2 < 1e-6f) continue;
+ d = (float) Math.sqrt(d2);
+ float w = (1f - d / 22f) * 1.5f;
+ ax += dx / d * w;
+ ay += dy / d * w;
+ }
+
+ if (gatherWeight > 0f) {
+ dx = f.x - gatherX;
+ dy = f.y - gatherY;
+ d = (float) Math.sqrt(dx * dx + dy * dy);
+ if (d < 85f && d > 0.01f) {
+ float w = (1f - d / 85f) * 2f * gatherWeight;
+ ax += dx / d * w;
+ ay += dy / d * w;
+ }
+ }
+
+ if (f.flee > 0f) {
+ ax += f.fleeX * f.flee * 4f;
+ ay += f.fleeY * f.flee * 4f;
+ }
+
+ if (f.x < 12f) ax += (12f - f.x) / 12f * 2f;
+ if (f.x > W - 12f) ax -= (f.x - (W - 12f)) / 12f * 2f;
+ if (f.y < 12f) ay += (12f - f.y) / 12f * 2f;
+ if (f.y > H - 12f) ay -= (f.y - (H - 12f)) / 12f * 2f;
+
+ ax += (rng.nextFloat() - 0.5f) * 0.4f;
+ ay += (rng.nextFloat() - 0.5f) * 0.4f;
+
+ float m = (float) Math.sqrt(ax * ax + ay * ay);
+ float speed = f.pace * (FRY_SPEED + (FRY_FLEE_SPEED - FRY_SPEED) * f.flee) * clamp(0.55f + 0.45f * m, 0.55f, 1f);
+ float wantVx = m > 1e-4f ? ax / m * speed : f.vx;
+ float wantVy = m > 1e-4f ? ay / m * speed : f.vy;
+ float ease = Math.min(1f, dt * (2.5f + 8f * f.flee));
+ f.vx += (wantVx - f.vx) * ease;
+ f.vy += (wantVy - f.vy) * ease;
+
+ f.x = clamp(f.x + f.vx * dt, 2f, W - 2f);
+ f.y = clamp(f.y + f.vy * dt, 2f, H - 2f);
+ if (f.vx * f.vx + f.vy * f.vy > 0.25f) f.heading = (float) Math.atan2(f.vy, f.vx);
+ f.flee = Math.max(0f, f.flee - dt / FLEE_SECONDS);
+ }
+ }
+
+ // ---- pads, duckweed, fireflies -----------------------------------------------------------------------------
+
+ private void driftPads() {
+ for (Pad p : pads) {
+ p.x = p.originX + (float) (Math.sin(time * 0.05 + p.phase) * 1.4 + Math.sin(time * 0.13 + p.phase * 1.7) * 0.6);
+ p.y = p.originY + (float) (Math.cos(time * 0.04 + p.phase) * 1.4 + Math.sin(time * 0.11 + p.phase * 2.3) * 0.6);
+ }
+ }
+
+ private void driftDuckweed(boolean force) {
+ boolean changed = force;
+ for (int c = 0; c < clusterPhase.length; c++) {
+ int dx = (int) Math.round(Math.sin(time * 0.04 + clusterPhase[c]) * 1.4);
+ int dy = (int) Math.round(Math.cos(time * 0.033 + clusterPhase[c] * 1.3) * 1.2);
+ if (dx != clusterDx[c] || dy != clusterDy[c]) {
+ clusterDx[c] = dx;
+ clusterDy[c] = dy;
+ changed = true;
+ }
+ }
+ if (!changed) return;
+ for (int i = 0; i < duckweed.length; i++) {
+ int c = weedCluster[i];
+ int x = Math.max(0, Math.min(W - 1, weedX[i] + clusterDx[c]));
+ int y = Math.max(0, Math.min(H - 1, weedY[i] + clusterDy[c]));
+ duckweed[i] = (x << 16) | y;
+ }
+ }
+
+ private void stepFireflies(float dt) {
+ for (Firefly f : fireflies) {
+ if ((f.homeTimer -= dt) <= 0f) pickFireflyHome(f);
+ f.angle += (rng.nextFloat() - 0.5f) * dt * 3f;
+ float dx = f.homeX - f.x, dy = f.homeY - f.y;
+ if (dx * dx + dy * dy > 20f * 20f) {
+ float want = (float) Math.atan2(dy, dx);
+ f.angle += clamp(wrap(want - f.angle), -0.8f * dt, 0.8f * dt);
+ }
+ f.angle = wrap(f.angle);
+ f.x = clamp(f.x + (float) Math.cos(f.angle) * f.pace * dt, 3f, W - 3f);
+ float bob = (float) Math.cos(time * 1.6 + f.phase) * 3f;
+ f.y = clamp(f.y + ((float) Math.sin(f.angle) * f.pace + bob) * dt, 3f, H - 3f);
+ }
+ }
+
+ private void pickFireflyHome(Firefly f) {
+ float x = 0f, y = 0f;
+ for (int t = 0; t < 8; t++) {
+ x = 10f + rng.nextFloat() * (W - 20f);
+ y = 10f + rng.nextFloat() * (H - 20f);
+ if (outerness(x, y) > 0.45f || rng.nextFloat() < 0.15f) break;
+ }
+ f.homeX = x;
+ f.homeY = y;
+ f.homeTimer = 10f + 20f * rng.nextFloat();
+ }
+
+ /** 0 at the centre, 1 on the ellipse touching the pond's edges. */
+ private static float outerness(float x, float y) {
+ float dx = (x - W / 2f) / (W / 2f), dy = (y - H / 2f) / (H / 2f);
+ return dx * dx + dy * dy;
+ }
+
+ /** Below 1 where a pad of radius r centred at (x, y) would reach into the central ellipse that pads keep out of. */
+ private static float centralEllipse(float x, float y, float r) {
+ float dx = (x - W / 2f) / (W * 0.32f + r), dy = (y - H / 2f) / (H * 0.30f + r);
+ return dx * dx + dy * dy;
+ }
+
+ // ---- construction ------------------------------------------------------------------------------------------
+
+ private Koi[] makeKoi() {
+ int[] varieties = {KOHAKU, SHOWA, OGON, ASAGI, CHAGOI, SANKE, rng.nextInt(6), rng.nextInt(6)};
+ for (int i = varieties.length - 1; i > 0; i--) {
+ int j = rng.nextInt(i + 1);
+ int t = varieties[i];
+ varieties[i] = varieties[j];
+ varieties[j] = t;
+ }
+ Koi[] out = new Koi[KOI_COUNT];
+ for (int i = 0; i < KOI_COUNT; i++) {
+ float length = 26f + 20f * rng.nextFloat();
+ Koi k = new Koi(varieties[i], length, makePattern(varieties[i]));
+ for (int t = 0; t < 60; t++) {
+ k.x = 60f + rng.nextFloat() * (W - 120f);
+ k.y = 55f + rng.nextFloat() * (H - 110f);
+ boolean clear = true;
+ for (int j = 0; j < i && clear; j++) {
+ float dx = out[j].x - k.x, dy = out[j].y - k.y;
+ clear = dx * dx + dy * dy > 45f * 45f;
+ }
+ if (clear) break;
+ }
+ k.heading = rng.nextFloat() * TWO_PI - PI;
+ k.wanderAngle = k.heading;
+ k.cruise = 8f + 8f * rng.nextFloat();
+ k.speed = k.cruise;
+ k.cruiseTimer = 4f + 8f * rng.nextFloat();
+ k.wanderTimer = rng.nextFloat() * 4f;
+ k.buddyTimer = 3f + 10f * rng.nextFloat();
+ k.depthTarget = 0.1f + 0.7f * rng.nextFloat();
+ k.depth = k.depthTarget;
+ k.depthTimer = 8f + 14f * rng.nextFloat();
+ k.surfaceTimer = 5f + 55f * rng.nextFloat();
+ k.wiggle = rng.nextFloat() * TWO_PI;
+ float spacing = length / (SPINE - 1);
+ float bx = (float) Math.cos(k.heading), by = (float) Math.sin(k.heading);
+ for (int s = 0; s < SPINE; s++) {
+ k.spineX[s] = k.x - bx * spacing * s;
+ k.spineY[s] = k.y - by * spacing * s;
+ }
+ out[i] = k;
+ }
+ return out;
+ }
+
+ /**
+ * Pattern bits per segment (0 = head .. 9 = tail): 0-9 centre band, 10-19 left band, 20-29 right band, 30-39 black.
+ * Patches are runs of neighbouring segments across the bands, so they read as markings rather than noise.
+ */
+ private long makePattern(int variety) {
+ long p = 0L;
+ switch (variety) {
+ case KOHAKU:
+ if (rng.nextFloat() < 0.25f) {
+ p = bit(0) | bit(1); // tancho: one red spot on the head and nothing else
+ } else {
+ p = redRuns(2 + rng.nextInt(2), 0.6f);
+ }
+ break;
+ case SANKE:
+ p = redRuns(2 + rng.nextInt(2), 0.5f) | blackSpots(1 + rng.nextInt(3));
+ break;
+ case SHOWA:
+ p = redRuns(2 + rng.nextInt(2), 0.5f) | blackRuns(2 + rng.nextInt(2), 0.7f);
+ break;
+ case OGON:
+ if (rng.nextFloat() < 0.5f) p = redRuns(1, 0.3f);
+ break;
+ case ASAGI:
+ // Asagi carry their colour low on the flanks, behind the head.
+ for (int s = 2 + rng.nextInt(2), end = 6 + rng.nextInt(3); s <= end; s++) {
+ p |= bit(10 + s) | bit(20 + s);
+ }
+ if (rng.nextFloat() < 0.5f) p |= bit(0);
+ break;
+ case CHAGOI:
+ default:
+ p = redRuns(1 + rng.nextInt(2), 0.3f);
+ break;
+ }
+ return p;
+ }
+
+ private long redRuns(int runs, float headChance) {
+ long p = 0L;
+ for (int r = 0; r < runs; r++) {
+ int start = (r == 0 && rng.nextFloat() < headChance) ? 0 : rng.nextInt(8);
+ int len = 2 + rng.nextInt(4);
+ boolean left = rng.nextFloat() < 0.75f, right = rng.nextFloat() < 0.75f;
+ for (int s = start; s < Math.min(9, start + len); s++) {
+ p |= bit(s);
+ boolean rim = s == start || s == start + len - 1;
+ if (left && !(rim && rng.nextFloat() < 0.3f)) p |= bit(10 + s);
+ if (right && !(rim && rng.nextFloat() < 0.3f)) p |= bit(20 + s);
+ }
+ }
+ return p;
+ }
+
+ private long blackSpots(int spots) {
+ long p = 0L;
+ for (int i = 0; i < spots; i++) p |= bit(30 + 2 + rng.nextInt(7));
+ return p;
+ }
+
+ private long blackRuns(int runs, float headChance) {
+ long p = 0L;
+ for (int r = 0; r < runs; r++) {
+ int start = (r == 0 && rng.nextFloat() < headChance) ? 0 : 1 + rng.nextInt(7);
+ int len = 1 + rng.nextInt(3);
+ for (int s = start; s < Math.min(9, start + len); s++) p |= bit(30 + s);
+ }
+ return p;
+ }
+
+ private static long bit(int i) {
+ return 1L << i;
+ }
+
+ private Fry[] makeFry() {
+ Fry[] out = new Fry[SCHOOLS * PER_SCHOOL];
+ for (int s = 0; s < SCHOOLS; s++) {
+ schoolX[s] = 50f + rng.nextFloat() * (W - 100f);
+ schoolY[s] = 40f + rng.nextFloat() * (H - 80f);
+ schoolAngle[s] = rng.nextFloat() * TWO_PI - PI;
+ schoolTimer[s] = rng.nextFloat() * 3f;
+ float a = rng.nextFloat() * TWO_PI;
+ for (int i = 0; i < PER_SCHOOL; i++) {
+ int color;
+ if (s == 0) color = rng.nextBoolean() ? 0xFFF2A03A : 0xFFF7D04A;
+ else if (s == 1) color = 0xFF4AA8E8;
+ else color = 0xFFE86A8A;
+ Fry f = new Fry(color, s, 0.85f + 0.3f * rng.nextFloat());
+ f.x = schoolX[s] + (rng.nextFloat() - 0.5f) * 20f;
+ f.y = schoolY[s] + (rng.nextFloat() - 0.5f) * 20f;
+ f.heading = a + (rng.nextFloat() - 0.5f) * 0.6f;
+ f.vx = (float) Math.cos(f.heading) * 15f;
+ f.vy = (float) Math.sin(f.heading) * 15f;
+ out[s * PER_SCHOOL + i] = f;
+ }
+ }
+ return out;
+ }
+
+ private Pad[] makePads() {
+ int n = 9 + rng.nextInt(4);
+ float[] px = new float[n], py = new float[n], pr = new float[n];
+ int placed = 0;
+ for (int tries = 0; placed < n && tries < 4000; tries++) {
+ float r = tries > 2500 ? 14f : 14f + 16f * rng.nextFloat();
+ float x, y;
+ if (rng.nextFloat() < 0.3f) {
+ int corner = rng.nextInt(4);
+ float ix = r * (-0.4f + 2.6f * rng.nextFloat()), iy = r * (-0.4f + 2.6f * rng.nextFloat());
+ x = (corner & 1) == 0 ? ix : W - ix;
+ y = (corner & 2) == 0 ? iy : H - iy;
+ } else {
+ int edge = rng.nextInt(4);
+ float inset = r * (-0.4f + 2.2f * rng.nextFloat());
+ if (edge < 2) {
+ x = rng.nextFloat() * W;
+ y = edge == 0 ? inset : H - inset;
+ } else {
+ y = rng.nextFloat() * H;
+ x = edge == 2 ? inset : W - inset;
+ }
+ }
+ // The whole pad stays out, with a margin so the drift never carries its rim inside.
+ if (centralEllipse(x, y, r) < 1.12f) continue;
+ boolean ok = true;
+ for (int j = 0; j < placed && ok; j++) {
+ float dx = px[j] - x, dy = py[j] - y;
+ float d = (float) Math.sqrt(dx * dx + dy * dy);
+ ok = d >= r + pr[j] - 0.3f * Math.min(r, pr[j]);
+ }
+ if (!ok) continue;
+ px[placed] = x;
+ py[placed] = y;
+ pr[placed] = r;
+ placed++;
+ }
+
+ boolean[] lotus = new boolean[placed];
+ int lotuses = Math.round(placed * 0.4f);
+ for (int l = 0; l < lotuses; l++) {
+ int j = rng.nextInt(placed);
+ while (lotus[j]) j = (j + 1) % placed;
+ lotus[j] = true;
+ }
+ Pad[] out = new Pad[placed];
+ for (int i = 0; i < placed; i++) {
+ out[i] = new Pad(px[i], py[i], pr[i], rng.nextFloat() * TWO_PI - PI, lotus[i], rng.nextFloat() * TWO_PI);
+ }
+ return out;
+ }
+
+ private int makeDuckweed(int clusters, int[] tx, int[] ty, int[] tc) {
+ int n = 0;
+ float[] subX = new float[3], subY = new float[3];
+ for (int c = 0; c < clusters; c++) {
+ clusterPhase[c] = rng.nextFloat() * TWO_PI;
+ float cx, cy, sx, sy;
+ if (pads.length > 0 && rng.nextFloat() < 0.45f) {
+ // Round a pad's rim.
+ Pad p = pads[rng.nextInt(pads.length)];
+ float a = rng.nextFloat() * TWO_PI;
+ float d = p.r + 3f + 6f * rng.nextFloat();
+ cx = p.originX + (float) Math.cos(a) * d;
+ cy = p.originY + (float) Math.sin(a) * d;
+ sx = sy = 6f;
+ } else {
+ // Along an edge, stretched along it.
+ int edge = rng.nextInt(4);
+ float inset = 3f + 22f * rng.nextFloat();
+ if (edge < 2) {
+ cx = 20f + rng.nextFloat() * (W - 40f);
+ cy = edge == 0 ? inset : H - 1 - inset;
+ sx = 14f;
+ sy = 5f;
+ } else {
+ cy = 15f + rng.nextFloat() * (H - 30f);
+ cx = edge == 2 ? inset : W - 1 - inset;
+ sx = 5f;
+ sy = 14f;
+ }
+ }
+ cx = clamp(cx, 2f, W - 3f);
+ cy = clamp(cy, 2f, H - 3f);
+ for (int i = 0; i < 3; i++) {
+ subX[i] = cx + (float) rng.nextGaussian() * sx * 0.6f;
+ subY[i] = cy + (float) rng.nextGaussian() * sy * 0.6f;
+ }
+ int count = 45 + rng.nextInt(45);
+ for (int i = 0; i < count && n < tx.length; i++) {
+ for (int t = 0; t < 6; t++) {
+ int sub = rng.nextInt(3);
+ float spread = 0.35f + 0.65f * rng.nextFloat();
+ int x = Math.round(subX[sub] + (float) rng.nextGaussian() * sx * spread);
+ int y = Math.round(subY[sub] + (float) rng.nextGaussian() * sy * spread);
+ if (x < 2 || x > W - 3 || y < 2 || y > H - 3 || onPad(x, y)) continue;
+ tx[n] = x;
+ ty[n] = y;
+ tc[n] = c;
+ n++;
+ break;
+ }
+ }
+ }
+ return n;
+ }
+
+ private boolean onPad(float x, float y) {
+ for (Pad p : pads) {
+ float dx = x - p.originX, dy = y - p.originY, r = p.r - 1.5f;
+ if (dx * dx + dy * dy < r * r) return true;
+ }
+ return false;
+ }
+
+ private Firefly[] makeFireflies() {
+ Firefly[] out = new Firefly[FIREFLY_COUNT];
+ for (int i = 0; i < FIREFLY_COUNT; i++) {
+ Firefly f = new Firefly(rng.nextFloat() * TWO_PI);
+ pickFireflyHome(f);
+ f.x = f.homeX;
+ f.y = f.homeY;
+ pickFireflyHome(f);
+ f.angle = rng.nextFloat() * TWO_PI - PI;
+ f.pace = 4f + 4f * rng.nextFloat();
+ out[i] = f;
+ }
+ return out;
+ }
+
+ // ---- maths -------------------------------------------------------------------------------------------------
+
+ private static float clamp(float v, float lo, float hi) {
+ return v < lo ? lo : (v > hi ? hi : v);
+ }
+
+ private static float wrap(float a) {
+ while (a > PI) a -= TWO_PI;
+ while (a < -PI) a += TWO_PI;
+ return a;
+ }
+}
diff --git a/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/PondRenderer.java b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/PondRenderer.java
new file mode 100644
index 000000000..230a9070b
--- /dev/null
+++ b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/PondRenderer.java
@@ -0,0 +1,1044 @@
+package io.github.nottoobright.koipond;
+
+import java.util.Arrays;
+import java.util.Random;
+
+/**
+ * Draws the pond into a 480x270 ARGB buffer with integer maths: the refracted floor and caustics, koi with their
+ * shadows, fry, lily pads with lotus and duckweed, fireflies and the breathing ring. The time-of-day grade is folded
+ * into the colours before they are drawn, so there is no separate pass over the frame. The textures and tables are
+ * built once in the constructor, and the pad sprites on the first frame, so render() then allocates nothing and
+ * needs no Canvas.
+ */
+final class PondRenderer {
+
+ private static final int W = PondModel.W, H = PondModel.H;
+ private static final int TILE = 128, TILE_MASK = TILE - 1;
+ private static final int[] BAYER = {0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5};
+ private static final float[] PROFILE = {0.09f, 0.14f, 0.165f, 0.17f, 0.155f, 0.13f, 0.10f, 0.07f, 0.045f, 0.03f};
+ private static final float TWO_PI = (float) (2 * Math.PI);
+
+ private static final int SIN_N = 1024;
+ private static final float SIN_SCALE = SIN_N / TWO_PI;
+ private static final float[] SIN = new float[SIN_N];
+
+ private static final int WHITE = 0xFFF2EEE4, RED = 0xFFD6301E, BLACK = 0xFF1C1C22;
+ private static final int GOLD = 0xFFF0B02E, GOLD_MID = 0xFFF6C44C, GOLD_LINE = 0xFFFFD873;
+ private static final int ASAGI = 0xFF7F96AB, ASAGI_NET = 0xFFA9BCCC, ASAGI_HEAD = 0xFFC6D0D6;
+ private static final int ASAGI_RED = 0xFFD8602A;
+ private static final int CHAGOI = 0xFF9C7B4F, CHAGOI_NET = 0xFF7A5E39;
+ /** Fin and tail colour per variety, indexed by PondModel.KOHAKU..SANKE. */
+ private static final int[] FIN = {0xFFF8F5EE, 0xFFCFCBC4, 0xFFFFD873, 0xFFE8875A, 0xFFB99C70, 0xFFF8F5EE};
+ private static final int FIREFLY = 0xFFD8F27A, FIREFLY_CORE = 0xFFF2FFC4, RING = 0xFFEAF6F0;
+
+ /** Side of the scratch square a koi body is rasterised into; a 40 px koi with its width and sway needs about 63. */
+ private static final int MASK = 96;
+ /** The breathing ring's radius runs from RING_MIN to RING_MIN + RING_GROW, inside the koi's orbit (58..72 px). */
+ static final float RING_MIN = 14f, RING_GROW = 32f;
+ private static final int RING_MAX = (int) (RING_MIN + RING_GROW) + 8, RING_SPAN = 2 * RING_MAX + 1;
+ /** Body sway weight per spine point, (s / 9)^1.5: nothing at the head, most at the tail. */
+ private static final float[] SWAY = new float[PondModel.SPINE];
+ /** tan(17.5 degrees): half of the ~35 degree notch in a lily pad. */
+ private static final float NOTCH_TAN = 0.3153f;
+ private static final int[] GLOW = new int[49];
+
+ /** Floor brightness levels (multiples of 18, the top one capped at 255) and caustic levels after dithering. */
+ private static final int LUM_LEVELS = 16, CAUSTIC_LEVELS = 5;
+ private static final int[] CAUSTIC_VALUE = {0, 44, 88, 132, 176};
+ /** The ring's edge glow, a256 per 1/16 px of distance from the ring line, up to 5 px. */
+ private static final int[] RING_EDGE = new int[80];
+
+ /** Pad sprite classes; a sprite byte is class | (veins << 3). */
+ private static final int PAD_OUTLINE = 1, PAD_RIM_LIGHT = 2, PAD_RIM_DARK = 3, PAD_DARK = 4, PAD_MID = 5,
+ PAD_LIGHT = 6;
+ /** Lotus sprite classes in the low 3 bits; bit 3 marks the lotus's drop shadow. */
+ private static final int LOTUS_CORE = 1, LOTUS_INNER = 2, LOTUS_INNER_EDGE = 3, LOTUS_OUTER = 4,
+ LOTUS_OUTER_EDGE = 5, LOTUS_SHADOW = 8;
+
+ static {
+ for (int i = 0; i < SIN_N; i++) SIN[i] = (float) Math.sin(i * 2 * Math.PI / SIN_N);
+ for (int dy = -3; dy <= 3; dy++) {
+ for (int dx = -3; dx <= 3; dx++) {
+ float f = Math.max(0f, 1f - (float) Math.sqrt(dx * dx + dy * dy) / 3.8f);
+ GLOW[(dy + 3) * 7 + dx + 3] = (int) (f * f * 256f);
+ }
+ }
+ for (int e16 = 0; e16 < RING_EDGE.length; e16++) {
+ float e = e16 / 16f, a = 0f;
+ if (e < 1.7f) { float c = 1f - e / 1.7f; a += 0.42f * c * c * (3f - 2f * c); }
+ if (e < 5f) { float s = 1f - e / 5f; a += 0.13f * s * s; }
+ RING_EDGE[e16] = (int) (a * 256f);
+ }
+ for (int s = 0; s < SWAY.length; s++) SWAY[s] = (float) Math.pow(s / (double) (SWAY.length - 1), 1.5);
+ }
+
+ private final Ripples ripples = new Ripples(W / 2, H / 2);
+ /** Floor brightness level 0..15 per pond pixel, already Bayer-quantised. */
+ private final byte[] floorLum = new byte[W * H];
+ /** Tileable net of light, 0..255. */
+ private final byte[] caustic = new byte[TILE * TILE];
+ /** Caustic product (0..255) to a dithered level 0..4, per Bayer cell: index (bayer << 8) | product. */
+ private final byte[] causticQ = new byte[16 * 256];
+ /** Precomputed distance from the pond centre in 1/16 px, for the breathing ring. */
+ private final short[] ringDist = new short[RING_SPAN * RING_SPAN];
+
+ /** Ungraded floor colour per level, and the graded floor plus caustic colour per (level, caustic level). */
+ private final int[] floorCol = new int[LUM_LEVELS];
+ private final int[] floorLut = new int[LUM_LEVELS * CAUSTIC_LEVELS];
+ private final int[] tintR = new int[CAUSTIC_LEVELS], tintG = new int[CAUSTIC_LEVELS], tintB = new int[CAUSTIC_LEVELS];
+ private final int[] rowDx = new int[W / 2], rowDy = new int[W / 2], rowHl = new int[W / 2];
+ /** Whether the row arrays hold anything but zeros. */
+ private boolean rowDirty = true;
+
+ // The time-of-day grade (and the rain dimming): per channel multipliers out of 256, applied to every colour
+ // before it is drawn. Scaling, blending and shadows are linear, so this matches grading the finished frame.
+ private int gradeR = 256, gradeG = 256, gradeB = 256;
+ private boolean graded;
+
+ // Koi body scratch: per pixel the best normalised squared distance q (< 1 inside), the spine parameter t,
+ // the lateral offset normalised to the half width, and the lateral offset in pixels.
+ private final float[] mq = new float[MASK * MASK];
+ private final float[] mt = new float[MASK * MASK];
+ private final float[] ml = new float[MASK * MASK];
+ private final float[] mp = new float[MASK * MASK];
+ private int mox, moy, mw, mh;
+ private int[] order = new int[32];
+ /** The current koi's spine with its swimming sway, read by buildMask and drawKoi instead of the model's. */
+ private final float[] swayX = new float[PondModel.SPINE], swayY = new float[PondModel.SPINE];
+
+ // Pad and lotus sprites, rasterised once for the model's pads in pad-local pixels (only the position moves),
+ // and their graded colours, rebuilt every frame from the palette.
+ private PondModel.Pad[] spritePads;
+ private byte[][] padSprite;
+ private int[] padExt;
+ private byte[][] lotusSprite;
+ private int[] lotusExt, lotusDx, lotusDy;
+ private final int[] padBase = new int[7];
+ private final int[] padColour = new int[32];
+ private final int[] lotusColour = new int[8];
+
+ PondRenderer(long seed) {
+ Random rnd = new Random(seed);
+ buildFloor(rnd);
+ buildCaustics(rnd);
+ for (int b = 0; b < 16; b++) {
+ for (int v = 0; v < 256; v++) {
+ float c = Math.max(0f, Math.min(255f, (v - 18) * 1.7f));
+ int lv = Math.min(4, (int) ((c * 4f + (BAYER[b] + 0.5f) * 255f / 16f) / 255f));
+ causticQ[(b << 8) | v] = (byte) lv;
+ }
+ }
+ for (int dy = -RING_MAX; dy <= RING_MAX; dy++) {
+ for (int dx = -RING_MAX; dx <= RING_MAX; dx++) {
+ ringDist[(dy + RING_MAX) * RING_SPAN + dx + RING_MAX] = (short) Math.round(Math.sqrt(dx * dx + dy * dy) * 16);
+ }
+ }
+ }
+
+ Ripples ripples() {
+ return ripples;
+ }
+
+ void render(PondModel m, Palette p, float fireflies, float breathSize, long nowMs, int[] out) {
+ render(m, p, fireflies, breathSize, 1f, nowMs, out);
+ }
+
+ /** ringAlpha (0..1) fades the breathing ring in and out; breathSize -1 leaves it out. */
+ void render(PondModel m, Palette p, float fireflies, float breathSize, float ringAlpha, long nowMs, int[] out) {
+ setGrade(p.ambient, m.rainLevel());
+ PondModel.Pad[] pads = m.pads;
+ if (spritePads != pads) buildSprites(pads);
+ padColours(p);
+ floorPass(p, nowMs, out);
+ PondModel.Koi[] koi = m.koi;
+ // Deepest first; each koi's shadow just before it, so a shallower koi shades the deeper ones below it.
+ sortByDepth(koi);
+ for (int n = 0; n < koi.length; n++) drawKoi(koi[order[n]], order[n], out);
+ drawFry(m.fry, out);
+ for (int i = 0; i < pads.length; i++) drawPadShadow(pads[i], i, out);
+ drawDuckweed(m.duckweed, p.duckweed, out);
+ for (int i = 0; i < pads.length; i++) drawPad(pads[i], i, out);
+ if (fireflies > 0f) drawFireflies(m.fireflies, Math.min(1f, fireflies), nowMs, out);
+ if (breathSize >= 0f && ringAlpha > 0f) drawRing(Math.min(1f, breathSize), Math.min(1f, ringAlpha), out);
+ }
+
+ // ---- Grade ----
+
+ private void setGrade(int amb, float rain) {
+ int dim = 256 - (int) (51f * clamp01(rain));
+ int ar = (amb >> 16) & 255, ag = (amb >> 8) & 255, ab = amb & 255;
+ gradeR = ((ar + (ar >> 7)) * dim) >> 8;
+ gradeG = ((ag + (ag >> 7)) * dim) >> 8;
+ gradeB = ((ab + (ab >> 7)) * dim) >> 8;
+ graded = gradeR != 256 || gradeG != 256 || gradeB != 256;
+ }
+
+ /** The colour under the current grade, opaque. */
+ private int grade(int c) {
+ if (!graded) return c | 0xFF000000;
+ return 0xFF000000 | ((((c >> 16) & 255) * gradeR >> 8) << 16) | ((((c >> 8) & 255) * gradeG >> 8) << 8)
+ | ((c & 255) * gradeB >> 8);
+ }
+
+ // ---- 1. Floor, caustics and refraction (the hot path) ----
+
+ private void floorPass(Palette p, long nowMs, int[] out) {
+ int dr = (p.deep >> 16) & 255, dg = (p.deep >> 8) & 255, db = p.deep & 255;
+ int fr = (p.floor >> 16) & 255, fg = (p.floor >> 8) & 255, fb = p.floor & 255;
+ final int cr = (p.caustic >> 16) & 255, cg = (p.caustic >> 8) & 255, cb = p.caustic & 255;
+ for (int q = 0; q < CAUSTIC_LEVELS; q++) {
+ int cq = CAUSTIC_VALUE[q];
+ tintR[q] = (cr * cq) >> 8;
+ tintG[q] = (cg * cq) >> 8;
+ tintB[q] = (cb * cq) >> 8;
+ }
+ for (int l = 0; l < LUM_LEVELS; l++) {
+ int i = Math.min(255, l * 18);
+ int a = i + (i >> 7);
+ int r0 = dr + (((fr - dr) * a) >> 8), g0 = dg + (((fg - dg) * a) >> 8), b0 = db + (((fb - db) * a) >> 8);
+ floorCol[l] = (r0 << 16) | (g0 << 8) | b0;
+ for (int q = 0; q < CAUSTIC_LEVELS; q++) {
+ int r = Math.min(255, r0 + tintR[q]), g = Math.min(255, g0 + tintG[q]), b = Math.min(255, b0 + tintB[q]);
+ floorLut[l * CAUSTIC_LEVELS + q] = grade((r << 16) | (g << 8) | b);
+ }
+ }
+ // Layer A scrolls in whole pixels, layer B is 0.75 scale in 8.8 fixed point; both wrap on the tile.
+ final int offAx = (int) Math.floorMod(nowMs * 7 / 1000, (long) TILE);
+ final int offAy = (int) Math.floorMod(nowMs * 3 / 1000, (long) TILE);
+ final int offBx = (int) Math.floorMod(-nowMs * 5 * 256 / 1000, TILE * 256L);
+ final int offBy = (int) Math.floorMod(nowMs * 4 * 256 / 1000, TILE * 256L);
+ final int[] hts = ripples.heights();
+ final int rw = ripples.width(), rh = ripples.height();
+ final byte[] lumT = floorLum, causT = caustic, dq = causticQ;
+ final int[] fc = floorCol, lut = floorLut, rdx = rowDx, rdy = rowDy, rhl = rowHl;
+ final int[] tr = tintR, tg = tintG, tb = tintB;
+ final int mr = gradeR, mg = gradeG, mb = gradeB;
+ boolean dirty = false;
+
+ for (int y = 0; y < H; y++) {
+ if ((y & 1) == 0) dirty = gradientRow(y >> 1, hts, rw, rh);
+ final int bRow = (y & 3) << 2;
+ final int rowA = ((y + offAy) & TILE_MASK) << 7;
+ final int rowB = (((y * 192 + offBy) >> 8) & TILE_MASK) << 7;
+ int o = y * W;
+ if (!dirty) {
+ // No ripple on this row: no refraction, so the floor and caustic levels index the graded table.
+ for (int x = 0; x < W; x++, o++) {
+ final int a = causT[rowA | ((x + offAx) & TILE_MASK)] & 255;
+ final int b = causT[rowB | (((x * 192 + offBx) >> 8) & TILE_MASK)] & 255;
+ out[o] = lut[lumT[o] * CAUSTIC_LEVELS + dq[((bRow | (x & 3)) << 8) | ((a * b) >> 8)]];
+ }
+ continue;
+ }
+ for (int x = 0; x < W; x++, o++) {
+ final int c = x >> 1;
+ final int ddx = rdx[c], ddy = rdy[c], hl = rhl[c];
+ if ((ddx | ddy | hl) == 0) {
+ final int a = causT[rowA | ((x + offAx) & TILE_MASK)] & 255;
+ final int b = causT[rowB | (((x * 192 + offBx) >> 8) & TILE_MASK)] & 255;
+ out[o] = lut[lumT[o] * CAUSTIC_LEVELS + dq[((bRow | (x & 3)) << 8) | ((a * b) >> 8)]];
+ continue;
+ }
+ int sx = x + ddx, sy = y + ddy;
+ if (sx < 0) sx = 0; else if (sx >= W) sx = W - 1;
+ if (sy < 0) sy = 0; else if (sy >= H) sy = H - 1;
+ final int a = causT[(((sy + offAy) & TILE_MASK) << 7) | ((sx + offAx) & TILE_MASK)] & 255;
+ final int b = causT[((((sy * 192 + offBy) >> 8) & TILE_MASK) << 7)
+ | (((sx * 192 + offBx) >> 8) & TILE_MASK)] & 255;
+ final int cq = dq[((bRow | (x & 3)) << 8) | ((a * b) >> 8)];
+ final int col = fc[lumT[sy * W + sx]];
+ int r = ((col >> 16) & 255) + tr[cq] + hl;
+ int g = ((col >> 8) & 255) + tg[cq] + hl;
+ int bl = (col & 255) + tb[cq] + hl;
+ if (r < 0) r = 0; else if (r > 255) r = 255;
+ if (g < 0) g = 0; else if (g > 255) g = 255;
+ if (bl < 0) bl = 0; else if (bl > 255) bl = 255;
+ out[o] = 0xFF000000 | ((r * mr >> 8) << 16) | ((g * mg >> 8) << 8) | (bl * mb >> 8);
+ }
+ }
+ }
+
+ /**
+ * Refraction offsets and highlight for one row of ripple cells; shared by the two pixel rows of the cell.
+ * Returns whether any cell of the row has a gradient.
+ */
+ private boolean gradientRow(int cy, int[] h, int rw, int rh) {
+ if (rowDirty) {
+ Arrays.fill(rowDx, 0);
+ Arrays.fill(rowDy, 0);
+ Arrays.fill(rowHl, 0);
+ rowDirty = false;
+ }
+ if (cy <= 0 || cy >= rh - 1) return false;
+ int n = Math.min(rw - 1, W / 2);
+ int base = cy * rw;
+ boolean any = false;
+ for (int cx = 1; cx < n; cx++) {
+ int i = base + cx;
+ int gx = h[i + 1] - h[i - 1], gy = h[i + rw] - h[i - rw];
+ if ((gx | gy) == 0) continue;
+ any = true;
+ rowDx[cx] = clamp(gx >> 2, -8, 8);
+ rowDy[cx] = clamp(gy >> 2, -8, 8);
+ rowHl[cx] = clamp((gx + gy) >> 1, -56, 56);
+ }
+ rowDirty = any;
+ return any;
+ }
+
+ // ---- 2 and 3. Koi ----
+
+ /**
+ * The spine with a wave travelling from head to tail along the local normal, so the whole body bends as it
+ * swims and not only in turns. Written to swayX, swayY; the model's spine is left alone.
+ */
+ private void sway(PondModel.Koi k) {
+ float[] sx = k.spineX, sy = k.spineY;
+ int n = Math.min(sx.length, PROFILE.length);
+ float amp = k.length * 0.045f;
+ for (int s = 0; s < n; s++) {
+ int a = s == 0 ? 0 : s - 1, b = s == n - 1 ? n - 1 : s + 1;
+ float tx = sx[b] - sx[a], ty = sy[b] - sy[a];
+ float d = (float) Math.sqrt(tx * tx + ty * ty);
+ float off = d > 1e-4f ? amp * SWAY[s] * sinF(k.wiggle - s * 0.7f) / d : 0f;
+ swayX[s] = sx[s] - ty * off;
+ swayY[s] = sy[s] + tx * off;
+ }
+ }
+
+ /**
+ * Rasterises the body (discs stamped every ~1 px along the swayed spine) into the scratch square. Returns false
+ * when the koi, with margin extra pixels around it, is entirely off screen.
+ */
+ private boolean buildMask(PondModel.Koi k, int margin) {
+ float[] sx = swayX, sy = swayY;
+ int n = Math.min(sx.length, PROFILE.length);
+ float len = k.length;
+ float minX = sx[0], maxX = sx[0], minY = sy[0], maxY = sy[0];
+ for (int i = 1; i < n; i++) {
+ minX = Math.min(minX, sx[i]); maxX = Math.max(maxX, sx[i]);
+ minY = Math.min(minY, sy[i]); maxY = Math.max(maxY, sy[i]);
+ }
+ float pad = len * 0.17f + 2f;
+ mox = (int) Math.floor(minX - pad);
+ moy = (int) Math.floor(minY - pad);
+ mw = Math.min(MASK, (int) Math.ceil(maxX + pad) - mox + 1);
+ mh = Math.min(MASK, (int) Math.ceil(maxY + pad) - moy + 1);
+ if (mox >= W + margin || moy >= H + margin || mox + mw <= -margin || moy + mh <= -margin) return false;
+ for (int j = 0; j < mh; j++) Arrays.fill(mq, j * MASK, j * MASK + mw, 2f);
+
+ float tx = 1f, ty = 0f;
+ for (int i = 0; i < n - 1; i++) {
+ float x0 = sx[i], y0 = sy[i], dx = sx[i + 1] - x0, dy = sy[i + 1] - y0;
+ float d = (float) Math.sqrt(dx * dx + dy * dy);
+ if (d > 1e-4f) { tx = dx / d; ty = dy / d; }
+ float w0 = len * PROFILE[i], w1 = len * PROFILE[i + 1];
+ int steps = Math.max(1, (int) Math.ceil(d));
+ int end = i == n - 2 ? steps : steps - 1;
+ for (int s = 0; s <= end; s++) {
+ float f = s / (float) steps;
+ stamp(x0 + dx * f, y0 + dy * f, Math.max(0.6f, w0 + (w1 - w0) * f), tx, ty, i + f);
+ }
+ }
+ return true;
+ }
+
+ private void stamp(float cx, float cy, float r, float tx, float ty, float t) {
+ float r2 = r * r, inv = 1f / r2, invR = 1f / r;
+ int i0 = Math.max(0, (int) Math.floor(cx - r) - mox), i1 = Math.min(mw - 1, (int) Math.ceil(cx + r) - mox);
+ int j0 = Math.max(0, (int) Math.floor(cy - r) - moy), j1 = Math.min(mh - 1, (int) Math.ceil(cy + r) - moy);
+ for (int j = j0; j <= j1; j++) {
+ float ddy = moy + j - cy;
+ int row = j * MASK;
+ for (int i = i0; i <= i1; i++) {
+ float ddx = mox + i - cx;
+ float d2 = ddx * ddx + ddy * ddy;
+ if (d2 > r2) continue;
+ float q = d2 * inv;
+ int idx = row + i;
+ if (q >= mq[idx]) continue;
+ float lat = tx * ddy - ty * ddx;
+ mq[idx] = q;
+ mt[idx] = t;
+ mp[idx] = lat;
+ ml[idx] = lat * invR;
+ }
+ }
+ }
+
+ private void drawShadow(PondModel.Koi k, int[] out) {
+ // The shadow falls on the floor: furthest from a koi at the surface, almost under one near the floor,
+ // and a little darker and sharper there.
+ float lift = 1f - clamp01(k.depth);
+ int ox = Math.round(2f + 6f * lift), oy = Math.round(3f + 9f * lift);
+ int rim = 200 + (int) (20f * lift), core = 165 + (int) (25f * lift);
+ for (int j = 0; j < mh; j++) {
+ int y = moy + j + oy;
+ if (y < 0 || y >= H) continue;
+ int row = j * MASK;
+ for (int i = 0; i < mw; i++) {
+ float q = mq[row + i];
+ if (q >= 1f) continue;
+ int x = mox + i + ox;
+ if (x < 0 || x >= W) continue;
+ int o = y * W + x;
+ out[o] = scale(out[o], q > 0.62f ? rim : core);
+ }
+ }
+ }
+
+ private void sortByDepth(PondModel.Koi[] koi) {
+ int n = koi.length;
+ if (order.length < n) order = new int[n];
+ for (int i = 0; i < n; i++) {
+ int v = i, j = i - 1;
+ while (j >= 0 && koi[order[j]].depth < koi[v].depth) { order[j + 1] = order[j]; j--; }
+ order[j + 1] = v;
+ }
+ }
+
+ /** The koi's shadow, then its fins and tail, then its body, all from one rasterised mask. */
+ private void drawKoi(PondModel.Koi k, int idx, int[] out) {
+ sway(k);
+ boolean near = buildMask(k, 14);
+ if (near) drawShadow(k, out);
+
+ int alpha = 256 - (int) (0.45f * clamp01(k.depth) * 256f);
+ float len = k.length;
+ float[] sx = swayX, sy = swayY;
+ int last = Math.min(sx.length, PROFILE.length) - 1;
+ int variety = k.variety;
+ int finCol = grade(FIN[variety >= 0 && variety < FIN.length ? variety : 0]);
+
+ // Tail: two lobes beyond the last spine point, swaying with the wiggle.
+ float tx = sx[last] - sx[last - 1], ty = sy[last] - sy[last - 1];
+ float td = (float) Math.sqrt(tx * tx + ty * ty);
+ if (td > 1e-4f) { tx /= td; ty /= td; } else { tx = -cosF(k.heading); ty = -sinF(k.heading); }
+ float sway = 0.38f * sinF(k.wiggle);
+ float cs = cosF(sway), sn = sinF(sway);
+ float dx = tx * cs - ty * sn, dy = tx * sn + ty * cs;
+ final float c45 = 0.9004f, s45 = 0.4350f;
+ drawLobes(sx[last] - tx * 0.8f, sy[last] - ty * 0.8f,
+ dx * c45 - dy * s45, dx * s45 + dy * c45, dx * c45 + dy * s45, -dx * s45 + dy * c45, 2,
+ len * 0.30f, len * 0.13f, finCol, alpha, out);
+
+ // Pectoral fins: lobes from the sides at spine[2], swept back and flapping.
+ float fx = sx[3] - sx[1], fy = sy[3] - sy[1];
+ float fd = (float) Math.sqrt(fx * fx + fy * fy);
+ if (fd > 1e-4f) { fx /= fd; fy /= fd; } else { fx = tx; fy = ty; }
+ float nx = -fy, ny = fx;
+ float sweep = 0.75f + 0.35f * sinF(k.wiggle + 1.3f);
+ float cw = cosF(sweep), sw = sinF(sweep);
+ float w2 = len * PROFILE[2] * 0.55f;
+ for (int s = -1; s <= 1; s += 2) {
+ float ax = nx * s * cw + fx * sw, ay = ny * s * cw + fy * sw;
+ drawLobes(sx[2] + nx * s * w2, sy[2] + ny * s * w2, ax, ay, 0f, 0f, 1,
+ len * 0.22f, len * 0.10f, finCol, alpha, out);
+ }
+
+ if (!near || mox >= W || moy >= H || mox + mw <= 0 || moy + mh <= 0) return;
+ long pat = k.pattern;
+ float spacing = len / last;
+ float dorsalEnd = last - 1.2f;
+ for (int j = 0; j < mh; j++) {
+ int y = moy + j;
+ if (y < 0 || y >= H) continue;
+ int row = j * MASK;
+ for (int i = 0; i < mw; i++) {
+ int m = row + i;
+ if (mq[m] >= 1f) continue;
+ int x = mox + i;
+ if (x < 0 || x >= W) continue;
+ float t = mt[m], l = ml[m], lp = mp[m];
+ int col = koiColour(variety, pat, t, l, lp, len, spacing, idx);
+ boolean edge = outside(i - 1, j) || outside(i + 1, j) || outside(i, j - 1) || outside(i, j + 1);
+ if (edge) {
+ col = scale(col, 141);
+ } else {
+ col = scale(col, 256 - (int) (44f * l * l));
+ if (lp > -0.6f && lp < 0.6f && t > 0.6f && t < dorsalEnd) col = lighten(col, 56);
+ }
+ int o = y * W + x;
+ out[o] = blend(out[o], grade(col), alpha);
+ }
+ }
+ }
+
+ private boolean outside(int i, int j) {
+ return i < 0 || j < 0 || i >= mw || j >= mh || mq[j * MASK + i] >= 1f;
+ }
+
+ /**
+ * One or two translucent elliptic lobes from a base point along unit directions (a) and (b), lighter at the
+ * rim so fins keep a shape over a busy floor. col is already graded.
+ */
+ private static void drawLobes(float bx, float by, float ax, float ay, float bxDir, float byDir, int lobes,
+ float len, float wid, int col, int alpha, int[] out) {
+ float hl = Math.max(0.8f, len * 0.5f), hw = Math.max(0.6f, wid * 0.5f);
+ // Scan only the lobes' own bounding boxes: centre base + dir * hl, half extents from both semi-axes.
+ float ex = hl * Math.abs(ax) + hw * Math.abs(ay), ey = hl * Math.abs(ay) + hw * Math.abs(ax);
+ float cxA = bx + ax * hl, cyA = by + ay * hl;
+ float minX = cxA - ex, maxX = cxA + ex, minY = cyA - ey, maxY = cyA + ey;
+ if (lobes == 2) {
+ float ex2 = hl * Math.abs(bxDir) + hw * Math.abs(byDir), ey2 = hl * Math.abs(byDir) + hw * Math.abs(bxDir);
+ float cxB = bx + bxDir * hl, cyB = by + byDir * hl;
+ minX = Math.min(minX, cxB - ex2); maxX = Math.max(maxX, cxB + ex2);
+ minY = Math.min(minY, cyB - ey2); maxY = Math.max(maxY, cyB + ey2);
+ }
+ int x0 = Math.max(0, (int) Math.floor(minX)), x1 = Math.min(W - 1, (int) Math.ceil(maxX));
+ int y0 = Math.max(0, (int) Math.floor(minY)), y1 = Math.min(H - 1, (int) Math.ceil(maxY));
+ float ihl2 = 1f / (hl * hl), ihw2 = 1f / (hw * hw);
+ int aIn = (alpha * 140) >> 8, aEdge = (alpha * 175) >> 8;
+ int edgeCol = scale(col, 220);
+ for (int y = y0; y <= y1; y++) {
+ float py = y - by;
+ int o = y * W + x0;
+ for (int x = x0; x <= x1; x++, o++) {
+ float px = x - bx;
+ float u = px * ax + py * ay - hl, v = py * ax - px * ay;
+ float e = u * u * ihl2 + v * v * ihw2;
+ if (lobes == 2) {
+ float u2 = px * bxDir + py * byDir - hl, v2 = py * bxDir - px * byDir;
+ e = Math.min(e, u2 * u2 * ihl2 + v2 * v2 * ihw2);
+ }
+ if (e > 1f) continue;
+ out[o] = e > 0.6f ? blend(out[o], edgeCol, aEdge) : blend(out[o], col, aIn);
+ }
+ }
+ }
+
+ /**
+ * Body colour at spine parameter t (0 head .. 9 tail end), lateral offset l (-1..1 of the half width) and lp
+ * (pixels). Pattern bits: 0-9 centre band per segment, 10-19 left, 20-29 right, 30-39 black spots.
+ */
+ private static int koiColour(int variety, long pat, float t, float l, float lp, float len, float spacing,
+ int idx) {
+ switch (variety) {
+ case PondModel.OGON:
+ if (lp > -0.9f && lp < 0.9f && t > 0.4f) return GOLD_LINE;
+ return l > -0.45f && l < 0.45f ? GOLD_MID : GOLD;
+ case PondModel.ASAGI:
+ if (t < 1.1f) return ASAGI_HEAD;
+ if (l > 0.64f || l < -0.64f) return ASAGI_RED;
+ return scaleNet(t * spacing, lp) ? ASAGI_NET : ASAGI;
+ case PondModel.CHAGOI:
+ return scaleNet(t * spacing, lp) ? CHAGOI_NET : CHAGOI;
+ default:
+ break;
+ }
+ // Wobble the band edges in fish-local coordinates so patches read as blobs, not blocks.
+ float segScale = PondModel.SPINE / (float) (PondModel.SPINE - 1);
+ int seg = (int) ((t + 0.35f * sinF(l * 2.4f + idx * 1.9f)) * segScale);
+ if (seg < 0) seg = 0; else if (seg > 9) seg = 9;
+ float th = 0.34f + 0.1f * sinF(t * 1.7f + idx);
+ int band = l < -th ? 10 : (l > th ? 20 : 0);
+ boolean patch = ((pat >>> (band + seg)) & 1L) != 0;
+ switch (variety) {
+ case PondModel.SHOWA:
+ // Black markings wrap across the whole width (bit 30 is the black head); red patches on white
+ // show between them.
+ if (((pat >>> (30 + seg)) & 1L) != 0) return BLACK;
+ return patch ? RED : WHITE;
+ case PondModel.SANKE:
+ if (spot(pat, t, l, len, spacing, idx)) return BLACK;
+ return patch ? RED : WHITE;
+ default:
+ return patch ? RED : WHITE;
+ }
+ }
+
+ private static boolean spot(long pat, float t, float l, float len, float spacing, int idx) {
+ int seg = (int) (t * PondModel.SPINE / (PondModel.SPINE - 1));
+ float rs = len * 0.055f + 0.6f, rs2 = rs * rs, halfW = len * 0.13f;
+ for (int s = seg - 1; s <= seg + 1; s++) {
+ if (s < 0 || s > 9 || ((pat >>> (30 + s)) & 1L) == 0) continue;
+ float ts = (s + 0.5f) * 0.9f;
+ float ls = ((s + idx) & 1) == 0 ? 0.4f : -0.45f;
+ float da = (t - ts) * spacing, dc = (l - ls) * halfW;
+ if (da * da + dc * dc < rs2) return true;
+ }
+ return false;
+ }
+
+ /** A diamond scale net about 3 px across, in fish-local pixels. */
+ private static boolean scaleNet(float along, float across) {
+ float a = (along + across) * 0.32f + 16f, b = (along - across) * 0.32f + 16f;
+ return a - (int) a < 0.28f || b - (int) b < 0.28f;
+ }
+
+ // ---- 4. Fry ----
+
+ private void drawFry(PondModel.Fry[] fry, int[] out) {
+ for (int i = 0; i < fry.length; i++) {
+ PondModel.Fry f = fry[i];
+ int col = grade(f.color), tail = scale(col, 150), shade = scale(col, 60);
+ int n = 4 + (i & 1);
+ float c = cosF(f.heading), s = sinF(f.heading);
+ // A soft shadow under the fish, then a body two pixels wide behind the head, tapering to a darker tail.
+ for (int k = 0; k < n; k++) {
+ int x = ri(f.x - c * k) + 1, y = ri(f.y - s * k) + 2;
+ if (x < 0 || y < 0 || x >= W || y >= H) continue;
+ int o = y * W + x;
+ out[o] = blend(out[o], shade, 70);
+ }
+ for (int k = 0; k < n; k++) {
+ float fx = f.x - c * k, fy = f.y - s * k;
+ int colour = k == n - 1 ? tail : col;
+ plotFry(out, ri(fx), ri(fy), colour);
+ if (k >= 1 && k <= 2) plotFry(out, ri(fx - s * 0.9f), ri(fy + c * 0.9f), colour);
+ }
+ }
+ }
+
+ private static void plotFry(int[] out, int x, int y, int colour) {
+ if (x < 0 || y < 0 || x >= W || y >= H) return;
+ int o = y * W + x;
+ out[o] = blend(out[o], colour, 235);
+ }
+
+ // ---- 5. Lily pads, lotus, duckweed ----
+
+ private static boolean padInside(int dx, int dy, float r2, float nx, float ny) {
+ if (dx * dx + dy * dy > r2) return false;
+ float dot = dx * nx + dy * ny;
+ if (dot <= 0f) return true;
+ float cr = dx * ny - dy * nx;
+ return Math.abs(cr) >= dot * NOTCH_TAN;
+ }
+
+ /** Rasterises every pad, and its lotus, into a sprite of colour classes. Only the pads' positions move. */
+ private void buildSprites(PondModel.Pad[] pads) {
+ int n = pads.length;
+ padSprite = new byte[n][];
+ padExt = new int[n];
+ lotusSprite = new byte[n][];
+ lotusExt = new int[n];
+ lotusDx = new int[n];
+ lotusDy = new int[n];
+ for (int i = 0; i < n; i++) {
+ PondModel.Pad pad = pads[i];
+ float r = Math.max(2f, pad.r);
+ float nx = cosF(pad.notch), ny = sinF(pad.notch);
+ padExt[i] = (int) Math.ceil(r) + 1;
+ padSprite[i] = padSprite(r, nx, ny, padExt[i], 5 + i % 3, pad.notch);
+ if (pad.lotus) {
+ float big = Math.max(3f, r * 0.45f);
+ lotusExt[i] = (int) Math.ceil(big) + 1;
+ lotusDx[i] = ri(-nx * r * 0.3f);
+ lotusDy[i] = ri(-ny * r * 0.3f);
+ lotusSprite[i] = lotusSprite(big, pad.phase, 8 + i % 3, lotusExt[i]);
+ }
+ }
+ spritePads = pads;
+ }
+
+ private static byte[] padSprite(float r, float nx, float ny, int ext, int veins, float notch) {
+ int side = 2 * ext + 1;
+ byte[] map = new byte[side * side];
+ float r2 = r * r, invR = 1f / r;
+ for (int dy = -ext; dy <= ext; dy++) {
+ for (int dx = -ext; dx <= ext; dx++) {
+ if (!padInside(dx, dy, r2, nx, ny)) continue;
+ int cls;
+ if (!padInside(dx - 1, dy, r2, nx, ny) || !padInside(dx + 1, dy, r2, nx, ny)
+ || !padInside(dx, dy - 1, r2, nx, ny) || !padInside(dx, dy + 1, r2, nx, ny)) {
+ cls = PAD_OUTLINE;
+ } else {
+ float d = (float) Math.sqrt(dx * dx + dy * dy) * invR;
+ float lf = -(dx + dy) * 0.7071f * invR;
+ if (d > 0.74f && lf > 0.2f) {
+ cls = PAD_RIM_LIGHT;
+ } else if (d > 0.78f && lf < -0.25f) {
+ cls = PAD_RIM_DARK;
+ } else {
+ int v = (int) ((lf * 0.8f + 1f) * 127.5f);
+ // Bayer in pad-local coordinates, so the dither moves with the pad instead of crawling.
+ int lv = (v * 2 + BAYER[((dy & 3) << 2) | (dx & 3)] * 16) >> 8;
+ cls = lv <= 0 ? PAD_DARK : (lv == 1 ? PAD_MID : PAD_LIGHT);
+ }
+ }
+ map[(dy + ext) * side + dx + ext] = (byte) cls;
+ }
+ }
+ // Veins from the notch apex, spaced so none runs into the notch; each pass over a pixel blends once more.
+ float inner = r - 1.8f, innerR2 = (r - 1.2f) * (r - 1.2f);
+ for (int v = 0; v < veins; v++) {
+ float ang = notch + (v + 0.5f) * TWO_PI / veins;
+ float vx = cosF(ang), vy = sinF(ang);
+ int lastX = Integer.MIN_VALUE, lastY = Integer.MIN_VALUE;
+ for (float s = 1.2f; s < inner; s += 0.7f) {
+ int dx = ri(vx * s), dy = ri(vy * s);
+ if (dx == lastX && dy == lastY) continue;
+ lastX = dx;
+ lastY = dy;
+ if (!padInside(dx, dy, innerR2, nx, ny)) continue;
+ addVein(map, (dy + ext) * side + dx + ext);
+ }
+ }
+ addVein(map, ext * side + ext);
+ return map;
+ }
+
+ private static void addVein(byte[] map, int i) {
+ int v = map[i];
+ if ((v & 7) != 0 && (v >> 3) < 3) map[i] = (byte) (v + 8);
+ }
+
+ private static byte[] lotusSprite(float big, float rot, int petals, int ext) {
+ // The shadow sits one pixel down-right, so the sprite is one pixel wider and taller than the flower.
+ int side = 2 * ext + 2;
+ byte[] map = new byte[side * side];
+ float halfN = petals * 0.5f, shift = (float) Math.PI / petals;
+ for (int dy = -ext; dy <= ext; dy++) {
+ for (int dx = -ext; dx <= ext; dx++) {
+ float d = (float) Math.sqrt(dx * dx + dy * dy);
+ if (d > big + 0.5f) continue;
+ float ang = (float) Math.atan2(dy, dx) + rot;
+ float ro = big * (0.42f + 0.58f * (float) Math.sqrt(Math.abs(cosF(ang * halfN))));
+ if (d > ro) continue;
+ int cls;
+ if (d < big * 0.24f) {
+ cls = LOTUS_CORE;
+ } else {
+ float rin = big * 0.66f * (0.45f + 0.55f * (float) Math.sqrt(Math.abs(cosF((ang + shift) * halfN))));
+ if (d <= rin) cls = d > rin - 0.8f ? LOTUS_INNER_EDGE : LOTUS_INNER;
+ else cls = d > ro - 0.9f ? LOTUS_OUTER_EDGE : LOTUS_OUTER;
+ }
+ int i = (dy + ext) * side + dx + ext;
+ map[i] = (byte) (map[i] | cls);
+ map[i + side + 1] = (byte) (map[i + side + 1] | LOTUS_SHADOW);
+ }
+ }
+ return map;
+ }
+
+ /** The graded pad and lotus colours for this frame's palette. */
+ private void padColours(Palette p) {
+ int dark = p.padDark, light = p.padLight;
+ int[] base = padBase;
+ base[PAD_OUTLINE] = scale(dark, 158);
+ base[PAD_RIM_LIGHT] = lighten(light, 40);
+ base[PAD_RIM_DARK] = scale(dark, 215);
+ base[PAD_DARK] = dark;
+ base[PAD_MID] = blend(dark, light, 128);
+ base[PAD_LIGHT] = light;
+ for (int cls = 1; cls < base.length; cls++) {
+ int c = base[cls];
+ for (int veins = 0; veins < 4; veins++) {
+ padColour[cls | (veins << 3)] = grade(c);
+ c = blend(c, p.padVein, 190);
+ }
+ }
+ int outer = p.lotus;
+ lotusColour[LOTUS_CORE] = grade(p.lotusCore);
+ lotusColour[LOTUS_INNER] = grade(lighten(outer, 110));
+ lotusColour[LOTUS_INNER_EDGE] = grade(lighten(outer, 70));
+ lotusColour[LOTUS_OUTER] = grade(outer);
+ lotusColour[LOTUS_OUTER_EDGE] = grade(scale(outer, 196));
+ }
+
+ private void drawPadShadow(PondModel.Pad pad, int i, int[] out) {
+ int ext = padExt[i], side = 2 * ext + 1;
+ byte[] map = padSprite[i];
+ int ox = ri(pad.x) - ext + 3, oy = ri(pad.y) - ext + 4;
+ int i0 = Math.max(0, -ox), i1 = Math.min(side, W - ox);
+ int j0 = Math.max(0, -oy), j1 = Math.min(side, H - oy);
+ for (int j = j0; j < j1; j++) {
+ int m = j * side, o = (oy + j) * W + ox;
+ for (int k = i0; k < i1; k++) {
+ if (map[m + k] != 0) out[o + k] = scale(out[o + k], 166);
+ }
+ }
+ }
+
+ private void drawPad(PondModel.Pad pad, int i, int[] out) {
+ int ext = padExt[i], side = 2 * ext + 1;
+ byte[] map = padSprite[i];
+ int[] colour = padColour;
+ int cx = ri(pad.x), cy = ri(pad.y);
+ int ox = cx - ext, oy = cy - ext;
+ int i0 = Math.max(0, -ox), i1 = Math.min(side, W - ox);
+ int j0 = Math.max(0, -oy), j1 = Math.min(side, H - oy);
+ for (int j = j0; j < j1; j++) {
+ int m = j * side, o = (oy + j) * W + ox;
+ for (int k = i0; k < i1; k++) {
+ int v = map[m + k];
+ if (v != 0) out[o + k] = colour[v];
+ }
+ }
+ byte[] lotus = lotusSprite[i];
+ if (lotus == null) return;
+ int lext = lotusExt[i], lside = 2 * lext + 2;
+ ox = cx + lotusDx[i] - lext;
+ oy = cy + lotusDy[i] - lext;
+ i0 = Math.max(0, -ox);
+ i1 = Math.min(lside, W - ox);
+ j0 = Math.max(0, -oy);
+ j1 = Math.min(lside, H - oy);
+ for (int j = j0; j < j1; j++) {
+ int m = j * lside, o = (oy + j) * W + ox;
+ for (int k = i0; k < i1; k++) {
+ if ((lotus[m + k] & LOTUS_SHADOW) != 0) out[o + k] = scale(out[o + k], 196);
+ }
+ }
+ int[] lc = lotusColour;
+ for (int j = j0; j < j1; j++) {
+ int m = j * lside, o = (oy + j) * W + ox;
+ for (int k = i0; k < i1; k++) {
+ int cls = lotus[m + k] & 7;
+ if (cls != 0) out[o + k] = lc[cls];
+ }
+ }
+ }
+
+ private void drawDuckweed(int[] pts, int colour, int[] out) {
+ int col = grade(colour), dark = scale(col, 150), light = lighten(col, 60);
+ for (int i = 0; i < pts.length; i++) {
+ int v = pts[i];
+ int x = v >>> 16, y = v & 0xFFFF;
+ if (y >= H) continue;
+ // A 2x2 frond with one corner left out (which one varies), and its shadow one pixel below-right.
+ int skip = ((i * 0x9E3779B1) >>> 30) & 3;
+ for (int q = 0; q < 4; q++) {
+ if (q == skip) continue;
+ int px = x + (q & 1), py = y + (q >> 1);
+ if (px + 1 < W && py + 1 < H) {
+ int o = (py + 1) * W + px + 1;
+ out[o] = blend(out[o], dark, 110);
+ }
+ }
+ for (int q = 0; q < 4; q++) {
+ if (q == skip) continue;
+ int px = x + (q & 1), py = y + (q >> 1);
+ if (px < W && py < H) out[py * W + px] = q == 0 ? light : col;
+ }
+ }
+ }
+
+ // ---- 6. Fireflies (ungraded, so they glow) ----
+
+ private static void drawFireflies(PondModel.Firefly[] flies, float level, long nowMs, int[] out) {
+ float secs = nowMs * 0.001f;
+ for (PondModel.Firefly f : flies) {
+ float speed = 1.2f + 0.3f * sinF(f.phase * 3.1f);
+ // On about 60% of the time: lit while the sine is above -0.3, with a smooth fade over 0.45.
+ float b = (sinF(secs * speed + f.phase) + 0.3f) / 0.45f;
+ if (b <= 0f) continue;
+ if (b > 1f) b = 1f;
+ b = b * b * (3f - 2f * b);
+ int in = (int) (b * level * 256f);
+ if (in <= 2) continue;
+ int fx = ri(f.x), fy = ri(f.y);
+ for (int dy = -3; dy <= 3; dy++) {
+ int y = fy + dy;
+ if (y < 0 || y >= H) continue;
+ for (int dx = -3; dx <= 3; dx++) {
+ int x = fx + dx;
+ if (x < 0 || x >= W) continue;
+ int o = y * W + x;
+ if ((dx | dy) == 0 || (dx * dx + dy * dy == 1)) {
+ out[o] = blend(out[o], FIREFLY_CORE, (dx | dy) == 0 ? in : in >> 1);
+ } else {
+ int w = GLOW[(dy + 3) * 7 + dx + 3];
+ if (w > 0) out[o] = add(out[o], FIREFLY, (w * in * 330) >> 16);
+ }
+ }
+ }
+ }
+ }
+
+ // ---- 7. Breathing ring ----
+
+ private void drawRing(float size, float alpha, int[] out) {
+ float radius = RING_MIN + size * RING_GROW;
+ int fade = (int) (alpha * 256f);
+ int r16 = (int) (radius * 16f);
+ int ext = Math.min(RING_MAX, (int) radius + 7);
+ // The faint fill inside, 0.07 * (d / radius)^2 in 1/256, as d16^2 * k >> 24.
+ long k = (long) (0.07 * 256 * (1L << 24) / ((double) r16 * r16));
+ // Inside this square the fill rounds to 0 (d < 0.236 * radius), so it is not visited.
+ int hole = (int) (radius * 0.16f);
+ int cx = W / 2, cy = H / 2;
+ for (int dy = -ext; dy <= ext; dy++) {
+ int y = cy + dy;
+ if (y < 0 || y >= H) continue;
+ int row = (dy + RING_MAX) * RING_SPAN + RING_MAX;
+ boolean holeRow = dy >= -hole && dy <= hole;
+ for (int dx = -ext; dx <= ext; dx++) {
+ if (holeRow && dx == -hole) { dx = hole; continue; }
+ int x = cx + dx;
+ if (x < 0 || x >= W) continue;
+ int d16 = ringDist[row + dx];
+ int e16 = Math.abs(d16 - r16);
+ int a256;
+ if (d16 >= r16) {
+ if (e16 >= 80) continue;
+ a256 = RING_EDGE[e16];
+ } else {
+ a256 = (e16 < 80 ? RING_EDGE[e16] : 0) + (int) ((d16 * (long) d16 * k) >> 24);
+ }
+ a256 = (a256 * fade) >> 8;
+ if (a256 <= 0) continue;
+ int o = y * W + x;
+ out[o] = add(out[o], RING, a256);
+ }
+ }
+ }
+
+ // ---- Textures built once ----
+
+ private void buildFloor(Random rnd) {
+ float[] lum = new float[W * H];
+ int g1 = 64, g2 = 26, g3 = 11;
+ float[] n1 = grid(rnd, g1), n2 = grid(rnd, g2), n3 = grid(rnd, g3);
+ float hw = W * 0.5f, hh = H * 0.5f;
+ for (int y = 0; y < H; y++) {
+ for (int x = 0; x < W; x++) {
+ float v = 0.55f * sample(n1, g1, x, y) + 0.30f * sample(n2, g2, x, y) + 0.15f * sample(n3, g3, x, y);
+ float ex = (x - hw) / hw, ey = (y - hh) / hh;
+ float vig = Math.min(1f, (ex * ex + ey * ey) * 0.55f);
+ lum[y * W + x] = (0.22f + 0.62f * v) * (1f - 0.3f * vig);
+ }
+ }
+ // A few darker silt patches.
+ for (int k = 0; k < 6; k++) {
+ float px = rnd.nextFloat() * W, py = rnd.nextFloat() * H;
+ float rx = 24f + rnd.nextFloat() * 40f, ry = 16f + rnd.nextFloat() * 24f;
+ float s = 0.12f + rnd.nextFloat() * 0.10f;
+ for (int y = Math.max(0, (int) (py - ry)); y < Math.min(H, (int) (py + ry) + 1); y++) {
+ for (int x = Math.max(0, (int) (px - rx)); x < Math.min(W, (int) (px + rx) + 1); x++) {
+ float qx = (x - px) / rx, qy = (y - py) / ry, d = qx * qx + qy * qy;
+ if (d >= 1f) continue;
+ float f = 1f - d;
+ lum[y * W + x] -= s * f * f * (3f - 2f * f);
+ }
+ }
+ }
+ // Sparse pebbles, lit from the upper left.
+ for (int k = 0; k < 110; k++) {
+ float px = rnd.nextFloat() * W, py = rnd.nextFloat() * H;
+ float pr = 0.8f + rnd.nextFloat() * 1.6f;
+ float tone = rnd.nextFloat() < 0.7f ? 0.10f : -0.10f;
+ int e = (int) Math.ceil(pr) + 1;
+ for (int y = (int) py - e; y <= (int) py + e; y++) {
+ for (int x = (int) px - e; x <= (int) px + e; x++) {
+ if (x < 0 || y < 0 || x >= W || y >= H) continue;
+ float dx = x - px, dy = y - py, d2 = dx * dx + dy * dy;
+ float add;
+ if (d2 <= pr * pr) {
+ add = tone;
+ if (dx + dy < -pr * 0.5f) add += 0.06f;
+ else if (dx + dy > pr * 0.5f) add -= 0.05f;
+ } else if (d2 <= (pr + 1f) * (pr + 1f) && dx + dy > 0f) {
+ add = -0.06f;
+ } else {
+ continue;
+ }
+ lum[y * W + x] += add;
+ }
+ }
+ }
+ // Ordered dither into levels 18 apart: pixel-art steps instead of a smooth gradient.
+ final float step = 18f;
+ for (int y = 0; y < H; y++) {
+ for (int x = 0; x < W; x++) {
+ float v = lum[y * W + x] * 255f + ((BAYER[((y & 3) << 2) | (x & 3)] + 0.5f) / 16f - 0.5f) * step;
+ floorLum[y * W + x] = (byte) clamp(Math.round(v / step), 0, LUM_LEVELS - 1);
+ }
+ }
+ }
+
+ private static float[] grid(Random rnd, int cell) {
+ int gw = W / cell + 2, gh = H / cell + 2;
+ float[] g = new float[gw * gh];
+ for (int i = 0; i < g.length; i++) g[i] = rnd.nextFloat();
+ return g;
+ }
+
+ private static float sample(float[] g, int cell, int x, int y) {
+ int gw = W / cell + 2;
+ float fx = x / (float) cell, fy = y / (float) cell;
+ int ix = (int) fx, iy = (int) fy;
+ float tx = fx - ix, ty = fy - iy;
+ tx = tx * tx * (3f - 2f * tx);
+ ty = ty * ty * (3f - 2f * ty);
+ int i = iy * gw + ix;
+ float top = g[i] + (g[i + 1] - g[i]) * tx;
+ float bot = g[i + gw] + (g[i + gw + 1] - g[i + gw]) * tx;
+ return top + (bot - top) * ty;
+ }
+
+ /** Voronoi with wrapped points: bright where the nearest and second-nearest points are almost equally far. */
+ private void buildCaustics(Random rnd) {
+ final int n = 14;
+ float[] px = new float[n], py = new float[n];
+ for (int i = 0; i < n; i++) { px[i] = rnd.nextFloat() * TILE; py[i] = rnd.nextFloat() * TILE; }
+ final float width = 7f;
+ for (int y = 0; y < TILE; y++) {
+ for (int x = 0; x < TILE; x++) {
+ float d1 = Float.MAX_VALUE, d2 = Float.MAX_VALUE;
+ for (int i = 0; i < n; i++) {
+ float dx = Math.abs(x - px[i]), dy = Math.abs(y - py[i]);
+ if (dx > TILE / 2f) dx = TILE - dx;
+ if (dy > TILE / 2f) dy = TILE - dy;
+ float d = (float) Math.sqrt(dx * dx + dy * dy);
+ if (d < d1) { d2 = d1; d1 = d; } else if (d < d2) { d2 = d; }
+ }
+ float v = 1f - (d2 - d1) / width;
+ caustic[(y << 7) | x] = (byte) (v > 0f ? (int) (v * v * 255f) : 0);
+ }
+ }
+ }
+
+ // ---- Small helpers ----
+
+ private static float sinF(float a) {
+ return SIN[(int) (a * SIN_SCALE) & (SIN_N - 1)];
+ }
+
+ private static float cosF(float a) {
+ return SIN[((int) (a * SIN_SCALE) + SIN_N / 4) & (SIN_N - 1)];
+ }
+
+ private static int ri(float v) {
+ return (int) Math.floor(v + 0.5f);
+ }
+
+ private static int clamp(int v, int lo, int hi) {
+ return v < lo ? lo : (v > hi ? hi : v);
+ }
+
+ private static float clamp01(float v) {
+ return v < 0f ? 0f : (v > 1f ? 1f : v);
+ }
+
+ /** dst toward src by a/256, opaque. */
+ private static int blend(int d, int s, int a) {
+ int dr = (d >> 16) & 255, dg = (d >> 8) & 255, db = d & 255;
+ int r = dr + ((((s >> 16) & 255) - dr) * a >> 8);
+ int g = dg + ((((s >> 8) & 255) - dg) * a >> 8);
+ int b = db + (((s & 255) - db) * a >> 8);
+ return 0xFF000000 | (r << 16) | (g << 8) | b;
+ }
+
+ /** Each channel times f/256. */
+ private static int scale(int c, int f) {
+ return 0xFF000000 | ((((c >> 16) & 255) * f >> 8) << 16) | ((((c >> 8) & 255) * f >> 8) << 8)
+ | ((c & 255) * f >> 8);
+ }
+
+ /** Each channel toward white by f/256. */
+ private static int lighten(int c, int f) {
+ int r = (c >> 16) & 255, g = (c >> 8) & 255, b = c & 255;
+ return 0xFF000000 | ((r + ((255 - r) * f >> 8)) << 16) | ((g + ((255 - g) * f >> 8)) << 8)
+ | (b + ((255 - b) * f >> 8));
+ }
+
+ /** Adds col times a/256, clamped. */
+ private static int add(int d, int col, int a) {
+ int r = ((d >> 16) & 255) + (((col >> 16) & 255) * a >> 8);
+ int g = ((d >> 8) & 255) + (((col >> 8) & 255) * a >> 8);
+ int b = (d & 255) + ((col & 255) * a >> 8);
+ return 0xFF000000 | (Math.min(255, r) << 16) | (Math.min(255, g) << 8) | Math.min(255, b);
+ }
+}
diff --git a/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/PondView.java b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/PondView.java
new file mode 100644
index 000000000..6b531b8ed
--- /dev/null
+++ b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/PondView.java
@@ -0,0 +1,453 @@
+package io.github.nottoobright.koipond;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.Paint;
+import android.graphics.Rect;
+import android.graphics.RectF;
+import android.graphics.Typeface;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.util.DisplayMetrics;
+import android.util.Log;
+import android.util.TypedValue;
+import android.view.Choreographer;
+import android.view.SurfaceHolder;
+import android.view.SurfaceView;
+
+import java.time.LocalTime;
+import java.util.Arrays;
+import java.util.Random;
+
+/**
+ * The pond on a render thread: steps the model, turns its drops into ripples, renders the 480x270 pixel frame and
+ * scales it to the screen without filtering, then draws the breathing label and the hint at full resolution.
+ * Frames are paced by vsync (Choreographer on the render thread's looper): one frame per 1/30 s, so every second
+ * vsync on a 60 Hz panel. Calls from the UI thread only set flags; the model and the renderer are built and touched
+ * by the render thread alone.
+ */
+public class PondView extends SurfaceView implements SurfaceHolder.Callback, Choreographer.FrameCallback {
+
+ private static final String TAG = "KoiPond";
+ private static final int W = PondModel.W, H = PondModel.H;
+ private static final long FRAME_NS = 1_000_000_000L / 30;
+ /** A vsync this much before a full frame interval still draws, so vsync jitter never skips a frame. */
+ private static final long FRAME_SLACK_NS = 4_000_000L;
+ private static final long MAX_STEP_NS = 100_000_000L;
+ private static final int STATS_FRAMES = 300;
+ private static final int MAX_DROPS = 64;
+ private static final long HINT_MS = 6000, HINT_FADE_MS = 1000;
+ private static final float RING_FADE_MS = 600f;
+ /** The ripple when the breath turns: TURN_DROPS small drops round the ring, each about as hard as a rain drop. */
+ private static final int TURN_RIPPLE = 150, TURN_DROPS = 16;
+ /** Null hardware canvases in a row, with the surface valid, before the software canvas is tried. */
+ private static final int HARDWARE_NULL_LIMIT = 3;
+ private static final int LABEL_COLOR = 0xEAF6F0;
+ private static final int LABEL_ALPHA = 250;
+ private static final int TEXT_SHADOW_ALPHA = 0xD8;
+ /** A soft dark pill behind the breathing label, so it reads on the bright daytime water too. */
+ private static final int PILL_COLOR = 0x08241F, PILL_ALPHA = 125;
+
+ private final long seed;
+ private final int[] frame = new int[W * H];
+ private final Bitmap bitmap = Bitmap.createBitmap(W, H, Bitmap.Config.ARGB_8888);
+ private final Random rng;
+
+ private final Paint pixelPaint = new Paint();
+ private final Paint labelPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
+ private final Paint numberPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
+ private final Paint hintPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
+ private final Paint pillPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
+ private final RectF pill = new RectF();
+ private float pillHalfW, pillPad, pillRadius;
+ private final Rect src = new Rect(0, 0, W, H);
+ private final Rect dst = new Rect();
+ private final float shadowR, shadowDy;
+
+ private final String breatheIn, breatheOut, hint;
+ private final String[] numbers = new String[10];
+
+ private final float[] dropX = new float[MAX_DROPS];
+ private final float[] dropY = new float[MAX_DROPS];
+ private final int[] dropStrength = new int[MAX_DROPS];
+
+ private final long[] frameNs = new long[STATS_FRAMES];
+ private final long[] sortedNs = new long[STATS_FRAMES];
+ private int statsCount;
+
+ // Set on the UI thread, consumed by the render thread at the start of the next frame.
+ private volatile boolean breathWanted;
+ private volatile int pebbleRequests, rainRequests;
+ private volatile int fixedMinute = -1;
+ private volatile boolean showHint;
+
+ // Render-thread state. The model and renderer are built on the first frame, off the UI thread, and kept for
+ // the view's life; a restarted render thread sees them through the join and start in between.
+ private PondModel model;
+ private PondRenderer renderer;
+ private Choreographer choreographer;
+ private long lastFrameNs;
+ private boolean breathing;
+ private long breathStart;
+ /** The ring's opacity 0..1, eased in and out; its size, label and count are held while it fades out. */
+ private float ringFade, ringSize;
+ /** Whether the last frame was an in-breath; a change sends the turn ripple. A new guide starts on an in-breath. */
+ private boolean wasInhaling = true;
+ private String ringLabel;
+ private int ringSecs;
+ private int pebblesDone, rainsDone;
+ private int appliedFixedMinute = -2;
+ private long nextClockNs;
+ private Palette palette;
+ private float fireflies;
+ private long modelNs, modelMs;
+ private boolean useHardwareCanvas = true;
+ private int hardwareNulls;
+
+ // UI-thread lifecycle.
+ private boolean started, surfaceReady;
+ private HandlerThread thread;
+ private volatile boolean alive;
+
+ public PondView(Context context) {
+ super(context);
+ seed = System.nanoTime();
+ rng = new Random(seed ^ 0x5DEECE66DL);
+ getHolder().addCallback(this);
+ setKeepScreenOn(true);
+
+ DisplayMetrics dm = context.getResources().getDisplayMetrics();
+ shadowR = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, dm);
+ shadowDy = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, dm);
+ Typeface light = Typeface.create("sans-serif-light", Typeface.NORMAL);
+
+ pixelPaint.setFilterBitmap(false);
+ pixelPaint.setAntiAlias(false);
+ pixelPaint.setDither(false);
+
+ Typeface regular = Typeface.create("sans-serif", Typeface.NORMAL);
+ setupText(labelPaint, regular, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 30, dm));
+ setupText(numberPaint, regular, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, dm));
+ setupText(hintPaint, light, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, dm));
+
+ breatheIn = context.getString(R.string.breathe_in);
+ breatheOut = context.getString(R.string.breathe_out);
+ hint = context.getString(R.string.hint);
+ for (int i = 0; i < numbers.length; i++) numbers[i] = Integer.toString(i);
+
+ pillPaint.setColor(PILL_COLOR | 0xFF000000);
+ pillPad = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 22, dm);
+ pillRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 18, dm);
+ pillHalfW = Math.max(labelPaint.measureText(breatheIn), labelPaint.measureText(breatheOut)) / 2f + pillPad;
+ }
+
+ private void setupText(Paint p, Typeface face, float size) {
+ p.setTypeface(face);
+ p.setTextSize(size);
+ p.setTextAlign(Paint.Align.CENTER);
+ p.setColor(LABEL_COLOR | 0xFF000000);
+ p.setAlpha(LABEL_ALPHA);
+ p.setShadowLayer(shadowR, 0, shadowDy, TEXT_SHADOW_ALPHA << 24);
+ }
+
+ /** Fades text and its shadow together; a translucent shadow colour keeps its own alpha otherwise. */
+ private void fadeText(Paint p, float f) {
+ int alpha = Math.round(LABEL_ALPHA * f);
+ if (p.getAlpha() == alpha) return;
+ p.setAlpha(alpha);
+ p.setShadowLayer(shadowR, 0, shadowDy, Math.round(TEXT_SHADOW_ALPHA * f) << 24);
+ }
+
+ // ---- Public API (UI thread) ----
+
+ /** Starts drawing once the surface exists too. */
+ public void start() {
+ started = true;
+ startThread();
+ }
+
+ /** Stops drawing and waits for the render thread to finish. */
+ public void stop() {
+ started = false;
+ stopThread();
+ }
+
+ /** Starts or stops the breathing guide; the koi gather around the ring while it runs. */
+ public void toggleBreath() {
+ breathWanted = !breathWanted;
+ }
+
+ /** Drops a pebble at a random spot in the middle half of the pond. */
+ public void pebble() {
+ pebbleRequests++;
+ }
+
+ /** Fixes the clock at a minute of the day (0..1439); a negative value follows the TV clock again. */
+ public void setFixedMinute(int minute) {
+ fixedMinute = minute < 0 ? -1 : minute % 1440;
+ }
+
+ /** Starts a rain shower at once. */
+ public void startRain() {
+ rainRequests++;
+ }
+
+ /** Shows the key hint for the first seconds. */
+ public void setShowHint(boolean show) {
+ showHint = show;
+ }
+
+ // ---- Surface ----
+
+ @Override
+ public void surfaceCreated(SurfaceHolder holder) {
+ surfaceReady = true;
+ startThread();
+ }
+
+ @Override
+ public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
+ // The render thread reads the canvas size every frame.
+ }
+
+ @Override
+ public void surfaceDestroyed(SurfaceHolder holder) {
+ surfaceReady = false;
+ stopThread();
+ }
+
+ private void startThread() {
+ if (!started || !surfaceReady || thread != null) return;
+ alive = true;
+ HandlerThread t = new HandlerThread("KoiPond");
+ t.start();
+ thread = t;
+ new Handler(t.getLooper()).post(this::begin);
+ }
+
+ private void stopThread() {
+ HandlerThread t = thread;
+ if (t == null) return;
+ alive = false;
+ // A frame in progress finishes first; no frame callback runs after the looper quits.
+ t.quit();
+ boolean interrupted = false;
+ while (true) {
+ try {
+ t.join();
+ break;
+ } catch (InterruptedException e) {
+ interrupted = true;
+ }
+ }
+ thread = null;
+ if (interrupted) Thread.currentThread().interrupt();
+ }
+
+ // ---- Render thread ----
+
+ private void begin() {
+ if (model == null) {
+ model = new PondModel(seed);
+ renderer = new PondRenderer(seed);
+ }
+ nextClockNs = 0;
+ lastFrameNs = 0;
+ choreographer = Choreographer.getInstance();
+ choreographer.postFrameCallback(this);
+ }
+
+ @Override
+ public void doFrame(long frameTimeNanos) {
+ if (!alive) return;
+ choreographer.postFrameCallback(this);
+ if (lastFrameNs != 0 && frameTimeNanos - lastFrameNs < FRAME_NS - FRAME_SLACK_NS) return;
+ // Time steps come from vsync timestamps, so render-time jitter does not reach the motion.
+ long deltaNs = lastFrameNs == 0 ? 0L : Math.max(0L, Math.min(MAX_STEP_NS, frameTimeNanos - lastFrameNs));
+ lastFrameNs = frameTimeNanos;
+ // The model clock only runs while drawing, so a pause does not jump the fish or the rain.
+ modelNs += deltaNs;
+ modelMs = modelNs / 1_000_000L;
+
+ long start = System.nanoTime();
+ frame(getHolder(), deltaNs / 1e9f, start);
+ recordStats(System.nanoTime() - start);
+ }
+
+ private void frame(SurfaceHolder holder, float dt, long nowNs) {
+ long now = modelMs;
+ consumeRequests(now);
+ updateClock(nowNs);
+
+ model.step(dt, now);
+
+ Ripples ripples = renderer.ripples();
+ int n = model.drainDrops(dropX, dropY, dropStrength, MAX_DROPS);
+ for (int i = 0; i < n; i++) {
+ int s = dropStrength[i];
+ int r = s <= 160 ? 2 : s <= 320 ? 3 : 4;
+ ripples.drop(((int) dropX[i]) >> 1, ((int) dropY[i]) >> 1, r, -s);
+ }
+ ripples.step();
+
+ updateRing(dt, now);
+ renderer.render(model, palette, fireflies, ringFade > 0f ? ringSize : -1f, ringFade, now, frame);
+ bitmap.setPixels(frame, 0, W, 0, 0, W, H);
+
+ Canvas canvas = lockCanvas(holder);
+ if (canvas == null) return;
+ try {
+ draw(canvas, now);
+ } finally {
+ holder.unlockCanvasAndPost(canvas);
+ }
+ }
+
+ private void consumeRequests(long now) {
+ boolean want = breathWanted;
+ if (want != breathing) {
+ breathing = want;
+ breathStart = now;
+ model.setGather(want, W / 2f, H / 2f);
+ }
+ int pebbles = pebbleRequests;
+ while (pebblesDone != pebbles) {
+ pebblesDone++;
+ float x = W / 4f + rng.nextFloat() * (W / 2f);
+ float y = H / 4f + rng.nextFloat() * (H / 2f);
+ model.scatter(x, y);
+ }
+ int rains = rainRequests;
+ if (rainsDone != rains) {
+ rainsDone = rains;
+ model.startRain(now);
+ }
+ }
+
+ /** Eases the ring in while breathing and out after it, holding the last size and label as it fades. */
+ private void updateRing(float dt, long now) {
+ float step = dt * 1000f / RING_FADE_MS;
+ ringFade = breathing ? Math.min(1f, ringFade + step) : Math.max(0f, ringFade - step);
+ if (!breathing) {
+ wasInhaling = true;
+ return;
+ }
+ long e = now - breathStart;
+ boolean inhaling = Breath.inhaling(e);
+ if (inhaling != wasInhaling) {
+ // The breath turns: a soft ripple rolls out from the ring, a cue that needs no reading.
+ // Small drops all round the ring, not one wide disc: a disc that size leaves a dark hole in the middle.
+ float cells = (PondRenderer.RING_MIN + Breath.size(e) * PondRenderer.RING_GROW) / 2f;
+ Ripples ripples = renderer.ripples();
+ for (int i = 0; i < TURN_DROPS; i++) {
+ double a = i * 2 * Math.PI / TURN_DROPS;
+ ripples.drop(W / 4 + (int) Math.round(Math.cos(a) * cells),
+ H / 4 + (int) Math.round(Math.sin(a) * cells), 2, -TURN_RIPPLE);
+ }
+ wasInhaling = inhaling;
+ }
+ ringSize = Breath.size(e);
+ ringLabel = inhaling ? breatheIn : breatheOut;
+ ringSecs = Breath.secondsLeft(e);
+ }
+
+ /** The minute of day, palette and fireflies change slowly: recomputed once a second, or when the fixed minute changes. */
+ private void updateClock(long nowNs) {
+ int fixed = fixedMinute;
+ if (palette != null && fixed == appliedFixedMinute && nowNs < nextClockNs) return;
+ appliedFixedMinute = fixed;
+ nextClockNs = nowNs + 1_000_000_000L;
+ float minute;
+ if (fixed >= 0) {
+ minute = fixed;
+ } else {
+ LocalTime t = LocalTime.now();
+ minute = t.getHour() * 60 + t.getMinute() + t.getSecond() / 60f + t.getNano() / 60e9f;
+ }
+ palette = TimeOfDay.at(minute);
+ fireflies = TimeOfDay.fireflies(minute);
+ }
+
+ /**
+ * The hardware canvas, or the software one where it does not work. SurfaceView's lockHardwareCanvas catches a
+ * failure itself and returns null, so a run of nulls while the surface is valid is the sign to switch; a single
+ * null, or one the software canvas shares, is only the surface not being ready yet.
+ */
+ private Canvas lockCanvas(SurfaceHolder holder) {
+ if (useHardwareCanvas) {
+ Canvas c = null;
+ try {
+ c = holder.lockHardwareCanvas();
+ } catch (RuntimeException e) {
+ Log.w(TAG, "lockHardwareCanvas failed, using lockCanvas", e);
+ useHardwareCanvas = false;
+ }
+ if (c != null) {
+ hardwareNulls = 0;
+ return c;
+ }
+ if (useHardwareCanvas) {
+ if (!holder.getSurface().isValid() || ++hardwareNulls < HARDWARE_NULL_LIMIT) return null;
+ hardwareNulls = 0;
+ Canvas software = holder.lockCanvas();
+ if (software != null) {
+ Log.w(TAG, "lockHardwareCanvas keeps returning null, using lockCanvas");
+ useHardwareCanvas = false;
+ }
+ return software;
+ }
+ }
+ return holder.lockCanvas();
+ }
+
+ private void draw(Canvas canvas, long now) {
+ int cw = canvas.getWidth(), ch = canvas.getHeight();
+ // Largest 16:9 rectangle that fits, centred; on a 16:9 TV it is the whole surface.
+ int w = cw, h = cw * H / W;
+ if (h > ch) {
+ h = ch;
+ w = ch * W / H;
+ }
+ int left = (cw - w) / 2, top = (ch - h) / 2;
+ dst.set(left, top, left + w, top + h);
+ if (w != cw || h != ch) canvas.drawColor(Color.BLACK);
+ canvas.drawBitmap(bitmap, src, dst, pixelPaint);
+
+ float scale = w / (float) W;
+ if (ringFade > 0f && ringLabel != null) {
+ fadeText(labelPaint, ringFade);
+ fadeText(numberPaint, ringFade);
+ float cx = left + w / 2f;
+ float cy = top + (H / 2f + 80f) * scale;
+ float base = cy + labelPaint.getTextSize() * 0.35f;
+ float bottom = base + numberPaint.getTextSize() * 1.3f + pillPad * 0.6f;
+ pill.set(cx - pillHalfW, base - labelPaint.getTextSize() - pillPad * 0.45f, cx + pillHalfW, bottom);
+ pillPaint.setAlpha(Math.round(PILL_ALPHA * ringFade));
+ canvas.drawRoundRect(pill, pillRadius, pillRadius, pillPaint);
+ canvas.drawText(ringLabel, cx, base, labelPaint);
+ if (ringSecs > 0 && ringSecs < numbers.length) {
+ canvas.drawText(numbers[ringSecs], cx, base + numberPaint.getTextSize() * 1.3f, numberPaint);
+ }
+ }
+ if (showHint && now < HINT_MS) {
+ fadeText(hintPaint, now < HINT_MS - HINT_FADE_MS ? 1f : (HINT_MS - now) / (float) HINT_FADE_MS);
+ float y = top + h - hintPaint.getTextSize() * 1.6f;
+ canvas.drawText(hint, left + w / 2f, y, hintPaint);
+ }
+ }
+
+ private void recordStats(long workNs) {
+ frameNs[statsCount++] = workNs;
+ if (statsCount < STATS_FRAMES) return;
+ statsCount = 0;
+ long sum = 0;
+ for (long v : frameNs) sum += v;
+ System.arraycopy(frameNs, 0, sortedNs, 0, STATS_FRAMES);
+ Arrays.sort(sortedNs);
+ long p99 = sortedNs[(int) Math.ceil(STATS_FRAMES * 0.99) - 1];
+ Log.i(TAG, "frame avg " + (sum / STATS_FRAMES) / 1000 / 1000f + " ms, p99 " + p99 / 1000 / 1000f
+ + " ms over " + STATS_FRAMES + " frames, " + (useHardwareCanvas ? "hardware" : "software") + " canvas");
+ }
+}
diff --git a/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/Ripples.java b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/Ripples.java
new file mode 100644
index 000000000..1468af7b2
--- /dev/null
+++ b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/Ripples.java
@@ -0,0 +1,102 @@
+package io.github.nottoobright.koipond;
+
+/**
+ * A ripple height field: the classic two-buffer water algorithm in integer maths. Each step the new height is half
+ * the sum of the four neighbours minus the height two steps ago, then damped. Border cells stay 0, so waves die at
+ * the pond's edge instead of wrapping.
+ */
+final class Ripples {
+
+ /**
+ * Damping shift: each step loses 1/16 of the height. With 4 a drop's ring spreads about 30 cells, then fades
+ * below 4% of its start within 60 steps (2 s at 30 fps); with 5 it still shows after 3 s.
+ */
+ static final int DAMP = 4;
+
+ /** Heights are clamped to this, so many drops on one spot cannot overflow or blow up. */
+ static final int MAX_HEIGHT = 2048;
+
+ private final int w, h;
+ private int[] cur, prev;
+
+ Ripples(int width, int height) {
+ if (width < 1 || height < 1) {
+ throw new IllegalArgumentException("ripple field must be at least 1x1");
+ }
+ w = width;
+ h = height;
+ cur = new int[w * h];
+ prev = new int[w * h];
+ }
+
+ int width() {
+ return w;
+ }
+
+ int height() {
+ return h;
+ }
+
+ /**
+ * Adds strength to the surface in a disc of radius r (cells) around (x, y), with a cosine profile so the ring
+ * comes out round rather than jaggy. Negative strength pushes the surface down. Parts on or past the border are
+ * clipped.
+ */
+ void drop(int x, int y, int r, int strength) {
+ if (r < 1) {
+ r = 1;
+ }
+ int x0 = Math.max(1, x - r), x1 = Math.min(w - 2, x + r);
+ int y0 = Math.max(1, y - r), y1 = Math.min(h - 2, y + r);
+ int[] c = cur;
+ for (int yy = y0; yy <= y1; yy++) {
+ int dy = yy - y;
+ int row = yy * w;
+ for (int xx = x0; xx <= x1; xx++) {
+ int dx = xx - x;
+ double d = Math.sqrt(dx * dx + dy * dy);
+ if (d >= r) {
+ continue;
+ }
+ long v = c[row + xx] + Math.round(strength * 0.5 * (1.0 + Math.cos(Math.PI * d / r)));
+ c[row + xx] = v > MAX_HEIGHT ? MAX_HEIGHT : (v < -MAX_HEIGHT ? -MAX_HEIGHT : (int) v);
+ }
+ }
+ }
+
+ /** Advance one step; damping so a ring fades out in about 2 s at 30 steps/s. Edges stay 0. */
+ void step() {
+ int[] c = cur, n = prev;
+ for (int y = 1; y < h - 1; y++) {
+ int i = y * w + 1;
+ for (int x = 1; x < w - 1; x++, i++) {
+ int v = ((c[i - 1] + c[i + 1] + c[i - w] + c[i + w]) >> 1) - n[i];
+ v -= v >> DAMP;
+ n[i] = v > MAX_HEIGHT ? MAX_HEIGHT : (v < -MAX_HEIGHT ? -MAX_HEIGHT : v);
+ }
+ }
+ prev = c;
+ cur = n;
+ }
+
+ /** Current height at a cell; 0 outside. */
+ int at(int x, int y) {
+ if (x < 0 || y < 0 || x >= w || y >= h) {
+ return 0;
+ }
+ return cur[y * w + x];
+ }
+
+ /**
+ * Current height buffer, row-major, width*height; read-only for the renderer. The two buffers swap on every
+ * step, so fetch it again after each step rather than keeping the reference.
+ */
+ int[] heights() {
+ return cur;
+ }
+
+ void clear() {
+ java.util.Arrays.fill(cur, 0);
+ java.util.Arrays.fill(prev, 0);
+ }
+}
diff --git a/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/TimeOfDay.java b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/TimeOfDay.java
new file mode 100644
index 000000000..491fe9ee1
--- /dev/null
+++ b/addons/koi-pond/app/src/main/java/io/github/nottoobright/koipond/TimeOfDay.java
@@ -0,0 +1,144 @@
+package io.github.nottoobright.koipond;
+
+/**
+ * Time-of-day colour grade. Five key palettes pinned to minutes of the day and blended with smoothstep between
+ * neighbouring anchors, wrapping at midnight, so the pond follows the TV clock without visible steps.
+ */
+final class TimeOfDay {
+
+ static final int DAWN = 0, DAY = 1, GOLDEN = 2, DUSK = 3, NIGHT = 4;
+
+ static final int MINUTES = 1440;
+
+ // Anchors in minute order; the last one wraps round to the first one, plus a day.
+ private static final int[] ANCHOR_MIN = {270, 360, 480, 960, 1050, 1140, 1230};
+ private static final int[] ANCHOR_KEY = {NIGHT, DAWN, DAY, DAY, GOLDEN, DUSK, NIGHT};
+
+ private static final int FIREFLY_RISE_START = 1140, FIREFLY_RISE_END = 1230;
+ private static final int FIREFLY_FALL_START = 270, FIREFLY_FALL_END = 360;
+
+ private static final Palette[] PALETTES = {
+ // DAWN: a little cooler and paler than day, pink-lavender light, soft caustics.
+ new Palette(0xFF1A4A48, 0xFF4A9C94, 0xFF1E4E4A, 0xFFF2DCE6,
+ 0xFF327142, 0xFF559F55, 0xFF23532F, 0xFFF28AAE, 0xFFF0AE50, 0xFF6CBE50),
+ // DAY: jade water, full caustics, no grade. The pads are lighter, yellower greens than the water, so
+ // they read as floating leaves; dawn and golden hour are shifted the same way.
+ new Palette(0xFF16473F, 0xFF3E9A86, 0xFF2A6A5C, 0xFFFFFFFF,
+ 0xFF2E7238, 0xFF4E9E48, 0xFF1F5228, 0xFFF27AA0, 0xFFF2A23A, 0xFF62C23A),
+ // GOLDEN: amber light and strong, warm caustics.
+ new Palette(0xFF2A4038, 0xFF6A9482, 0xFF8A6428, 0xFFFFD8A8,
+ 0xFF387234, 0xFF5DA143, 0xFF255223, 0xFFF2789A, 0xFFF5A030, 0xFF78C238),
+ // DUSK: violet-blue light, weak caustics.
+ new Palette(0xFF123C40, 0xFF2E7A7A, 0xFF183A44, 0xFFB8A8D8,
+ 0xFF1A4E36, 0xFF2A6C48, 0xFF123828, 0xFFE070A0, 0xFFE09440, 0xFF52A840),
+ // NIGHT: deep blue, caustics a faint shimmer of moonlight. Keyed bright enough that after the grade
+ // the floor stays near luma 30 (TVs crush much darker to black) and the pads sit clearly above it.
+ new Palette(0xFF0E2C30, 0xFF24605E, 0xFF060C10, 0xFF7080B0,
+ 0xFF1E5A3C, 0xFF2E7A4E, 0xFF143E2C, 0xFFD07098, 0xFFD09040, 0xFF4A9A40),
+ };
+
+ // at() is asked every frame. It is quantised to 1/16 of a minute (under 4 s, far below one colour step)
+ // and the last answer cached, so a blended palette is built a few times a minute instead of 30 times a second.
+ private static final float QUANT = 16f;
+
+ private static final class Cached {
+ final float minute;
+ final Palette palette;
+
+ Cached(float minute, Palette palette) {
+ this.minute = minute;
+ this.palette = palette;
+ }
+ }
+
+ private static volatile Cached cached = new Cached(-1f, null);
+
+ private TimeOfDay() {
+ }
+
+ /** The blended palette for a time, minuteOfDay in [0, 1440) (fractional minutes allowed; values outside wrap). */
+ static Palette at(float minuteOfDay) {
+ float m = Math.round(wrap(minuteOfDay) * QUANT) / QUANT;
+ if (m >= MINUTES) m -= MINUTES;
+ Cached c = cached;
+ if (c.minute == m) return c.palette;
+ int i = segment(m);
+ Palette p = Palette.lerp(PALETTES[ANCHOR_KEY[i]], PALETTES[ANCHOR_KEY[next(i)]], weight(m, i));
+ cached = new Cached(m, p);
+ return p;
+ }
+
+ /** Firefly intensity 0..1 for the time. */
+ static float fireflies(float minuteOfDay) {
+ float m = wrap(minuteOfDay);
+ if (m >= FIREFLY_RISE_END || m < FIREFLY_FALL_START) return 1f;
+ if (m >= FIREFLY_RISE_START) {
+ return smoothstep((m - FIREFLY_RISE_START) / (FIREFLY_RISE_END - FIREFLY_RISE_START));
+ }
+ if (m < FIREFLY_FALL_END) {
+ return 1f - smoothstep((m - FIREFLY_FALL_START) / (FIREFLY_FALL_END - FIREFLY_FALL_START));
+ }
+ return 0f;
+ }
+
+ /** The dominant key (the one with the larger weight) for the time; for logging and tests. */
+ static int key(float minuteOfDay) {
+ float m = wrap(minuteOfDay);
+ int i = segment(m);
+ return weight(m, i) > 0.5f ? ANCHOR_KEY[next(i)] : ANCHOR_KEY[i];
+ }
+
+ /** Linear blend of two 0xAARRGGBB colours, t clamped to 0..1. */
+ static int lerp(int a, int b, float t) {
+ if (t <= 0f) return a;
+ if (t >= 1f) return b;
+ int out = 0;
+ for (int shift = 0; shift < 32; shift += 8) {
+ int ca = (a >>> shift) & 0xFF;
+ int cb = (b >>> shift) & 0xFF;
+ int c = (int) (ca + (cb - ca) * t + 0.5f);
+ out |= c << shift;
+ }
+ return out;
+ }
+
+ /** Unblended palette of one key. */
+ static Palette palette(int key) {
+ return PALETTES[key];
+ }
+
+ private static float wrap(float minute) {
+ float m = minute % MINUTES;
+ if (m < 0f) m += MINUTES;
+ // -0.00001f % 1440 + 1440 rounds to 1440 in float.
+ return m >= MINUTES ? 0f : m;
+ }
+
+ /** Index of the anchor at or before m; the last anchor's segment runs over midnight to the first. */
+ private static int segment(float m) {
+ int last = ANCHOR_MIN.length - 1;
+ if (m < ANCHOR_MIN[0] || m >= ANCHOR_MIN[last]) return last;
+ int i = 0;
+ while (m >= ANCHOR_MIN[i + 1]) i++;
+ return i;
+ }
+
+ private static int next(int i) {
+ return i + 1 < ANCHOR_MIN.length ? i + 1 : 0;
+ }
+
+ /** Smoothstepped weight of the next anchor's key within segment i. */
+ private static float weight(float m, int i) {
+ int start = ANCHOR_MIN[i];
+ int end = ANCHOR_MIN[next(i)];
+ if (end <= start) end += MINUTES;
+ if (m < start) m += MINUTES;
+ return smoothstep((m - start) / (end - start));
+ }
+
+ private static float smoothstep(float x) {
+ if (x <= 0f) return 0f;
+ if (x >= 1f) return 1f;
+ return x * x * (3f - 2f * x);
+ }
+}
diff --git a/addons/koi-pond/app/src/main/res/drawable/banner.xml b/addons/koi-pond/app/src/main/res/drawable/banner.xml
new file mode 100644
index 000000000..2768b9aea
--- /dev/null
+++ b/addons/koi-pond/app/src/main/res/drawable/banner.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- The TV banner: a red-and-white koi under a lily pad on teal water. Drawn for this add-on. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="320dp" android:height="180dp"
+ android:viewportWidth="320" android:viewportHeight="180">
+ <path android:fillColor="#FF1E5E55" android:pathData="M0,0h320v180h-320z" />
+ <path android:fillColor="#FF2A7468" android:pathData="M0,120q80,-20 160,0t160,0v60h-320z" />
+ <path android:fillColor="#33000000" android:pathData="M120,104q40,-26 96,-6q-18,16 -56,18q-26,0 -40,-12z" />
+ <path android:fillColor="#FFF4EEE2" android:pathData="M110,92q40,-26 96,-6q-18,16 -56,18q-26,0 -40,-12z" />
+ <path android:fillColor="#FFF4EEE2" android:pathData="M204,86l26,-14l-6,16l8,14l-28,-8z" />
+ <path android:fillColor="#FFD2321E" android:pathData="M130,84q14,-8 26,-4q-4,12 -18,12q-6,0 -8,-8zM166,82q12,-2 20,4q-8,8 -18,6z" />
+ <path android:fillColor="#FF1E4A2E" android:pathData="M262,40a44,44 0 1,0 0.1,0zM262,84l40,-24l4,10z" />
+ <path android:fillColor="#FF2F7A3E" android:pathData="M258,46a36,36 0 1,0 0.1,0z" />
+ <path android:fillColor="#FFF07AA0" android:pathData="M248,60l8,12l8,-12l2,14l12,-4l-8,10l12,6l-14,2l4,12l-12,-8l-4,12l-4,-12l-12,8l4,-12l-14,-2l12,-6l-8,-10l12,4z" />
+ <path android:fillColor="#FFF0A030" android:pathData="M256,82a4,4 0 1,0 0.1,0z" />
+</vector>
diff --git a/addons/koi-pond/app/src/main/res/drawable/icon.xml b/addons/koi-pond/app/src/main/res/drawable/icon.xml
new file mode 100644
index 000000000..84ca979f4
--- /dev/null
+++ b/addons/koi-pond/app/src/main/res/drawable/icon.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- The app icon: a red-and-white koi on teal water. Drawn for this add-on. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp" android:height="108dp"
+ android:viewportWidth="108" android:viewportHeight="108">
+ <path android:fillColor="#FF1E5E55" android:pathData="M0,0h108v108h-108z" />
+ <path android:fillColor="#FFF4EEE2" android:pathData="M26,60q20,-22 50,-8q-10,12 -28,14q-14,0 -22,-6z" />
+ <path android:fillColor="#FFF4EEE2" android:pathData="M74,52l14,-10l-3,11l5,9l-16,-4z" />
+ <path android:fillColor="#FFD2321E" android:pathData="M34,54q8,-6 16,-4q-2,8 -10,8q-4,0 -6,-4zM56,50q8,0 12,4q-6,6 -12,4z" />
+</vector>
diff --git a/addons/koi-pond/app/src/main/res/values/strings.xml b/addons/koi-pond/app/src/main/res/values/strings.xml
new file mode 100644
index 000000000..ef55fbf38
--- /dev/null
+++ b/addons/koi-pond/app/src/main/res/values/strings.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Koi Pond</string>
+ <string name="breathe_in">Breathe in</string>
+ <string name="breathe_out">Breathe out</string>
+ <string name="hint">OK breathe · Arrows drop a pebble · Back leave</string>
+</resources>
diff --git a/addons/koi-pond/app/src/main/res/xml/module_card.xml b/addons/koi-pond/app/src/main/res/xml/module_card.xml
new file mode 100644
index 000000000..d7128c2f9
--- /dev/null
+++ b/addons/koi-pond/app/src/main/res/xml/module_card.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="utf-8"?>
+<card spec="1" label="Koi Pond" caption="A calm pond" accent="#3FB8A0" />
diff --git a/addons/koi-pond/app/src/test/java/io/github/nottoobright/koipond/BreathTest.java b/addons/koi-pond/app/src/test/java/io/github/nottoobright/koipond/BreathTest.java
new file mode 100644
index 000000000..c383dc4c4
--- /dev/null
+++ b/addons/koi-pond/app/src/test/java/io/github/nottoobright/koipond/BreathTest.java
@@ -0,0 +1,58 @@
+package io.github.nottoobright.koipond;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class BreathTest {
+
+ private static final float EPS = 1e-4f;
+
+ @Test
+ public void sizeFollowsTheCycle() {
+ assertEquals(0f, Breath.size(0), EPS);
+ assertEquals(0.5f, Breath.size(2000), EPS);
+ assertEquals(1f, Breath.size(4000), EPS);
+ assertEquals(0.5f, Breath.size(7000), EPS);
+ assertEquals(0f, Breath.size(10000), EPS);
+ assertEquals(1f, Breath.size(14000), EPS);
+ }
+
+ @Test
+ public void sizeStaysInRange() {
+ for (long t = 0; t < 25_000; t += 37) {
+ float s = Breath.size(t);
+ assertTrue("size at " + t + " was " + s, s >= 0f && s <= 1f);
+ }
+ }
+
+ @Test
+ public void negativeElapsedCountsAsStart() {
+ assertEquals(0f, Breath.size(-500), EPS);
+ assertTrue(Breath.inhaling(-500));
+ assertEquals(4, Breath.secondsLeft(-500));
+ }
+
+ @Test
+ public void inhalingOnlyInTheFirstFourSeconds() {
+ assertTrue(Breath.inhaling(0));
+ assertTrue(Breath.inhaling(3999));
+ assertFalse(Breath.inhaling(4000));
+ assertFalse(Breath.inhaling(9999));
+ assertTrue(Breath.inhaling(10000));
+ }
+
+ @Test
+ public void secondsLeftCountsDownEachPhase() {
+ assertEquals(4, Breath.secondsLeft(0));
+ assertEquals(4, Breath.secondsLeft(999));
+ assertEquals(3, Breath.secondsLeft(1000));
+ assertEquals(1, Breath.secondsLeft(3999));
+ assertEquals(6, Breath.secondsLeft(4000));
+ assertEquals(5, Breath.secondsLeft(5000));
+ assertEquals(1, Breath.secondsLeft(9999));
+ assertEquals(4, Breath.secondsLeft(10000));
+ }
+}
diff --git a/addons/koi-pond/app/src/test/java/io/github/nottoobright/koipond/PondModelTest.java b/addons/koi-pond/app/src/test/java/io/github/nottoobright/koipond/PondModelTest.java
new file mode 100644
index 000000000..5d3b979b1
--- /dev/null
+++ b/addons/koi-pond/app/src/test/java/io/github/nottoobright/koipond/PondModelTest.java
@@ -0,0 +1,246 @@
+package io.github.nottoobright.koipond;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class PondModelTest {
+
+ private static final float DT = 1f / 30f;
+ private static final float W = PondModel.W, H = PondModel.H;
+
+ private final float[] xs = new float[256], ys = new float[256];
+ private final int[] strengths = new int[256];
+
+ /** Steps from frame `from` to `to` (exclusive) at 30 fps, with nowMs derived from the frame number. */
+ private static void run(PondModel m, int from, int to) {
+ for (int i = from; i < to; i++) m.step(DT, i * 1000L / 30L);
+ }
+
+ private int drainAll(PondModel m) {
+ int total = 0, n;
+ while ((n = m.drainDrops(xs, ys, strengths, xs.length)) > 0) total += n;
+ return total;
+ }
+
+ @Test
+ public void sameSeedGivesTheSameState() {
+ PondModel a = new PondModel(42), b = new PondModel(42);
+ run(a, 0, 300);
+ run(b, 0, 300);
+ for (int i = 0; i < a.koi.length; i++) {
+ PondModel.Koi ka = a.koi[i], kb = b.koi[i];
+ assertEquals(ka.x, kb.x, 0f);
+ assertEquals(ka.y, kb.y, 0f);
+ assertEquals(ka.heading, kb.heading, 0f);
+ assertEquals(ka.speed, kb.speed, 0f);
+ assertEquals(ka.depth, kb.depth, 0f);
+ assertEquals(ka.wiggle, kb.wiggle, 0f);
+ assertEquals(ka.pattern, kb.pattern);
+ assertArrayEquals(ka.spineX, kb.spineX, 0f);
+ assertArrayEquals(ka.spineY, kb.spineY, 0f);
+ }
+ for (int i = 0; i < a.fry.length; i++) {
+ assertEquals(a.fry[i].x, b.fry[i].x, 0f);
+ assertEquals(a.fry[i].y, b.fry[i].y, 0f);
+ assertEquals(a.fry[i].heading, b.fry[i].heading, 0f);
+ }
+ assertEquals(a.pads.length, b.pads.length);
+ for (int i = 0; i < a.pads.length; i++) {
+ assertEquals(a.pads[i].x, b.pads[i].x, 0f);
+ assertEquals(a.pads[i].y, b.pads[i].y, 0f);
+ }
+ assertArrayEquals(a.duckweed, b.duckweed);
+ for (int i = 0; i < a.fireflies.length; i++) {
+ assertEquals(a.fireflies[i].x, b.fireflies[i].x, 0f);
+ assertEquals(a.fireflies[i].y, b.fireflies[i].y, 0f);
+ }
+ assertEquals(drainAll(a), drainAll(b));
+
+ PondModel c = new PondModel(43);
+ run(c, 0, 300);
+ assertNotEquals(a.koi[0].x, c.koi[0].x, 0f);
+ }
+
+ @Test
+ public void populationMatchesTheContract() {
+ for (long seed = 1; seed <= 20; seed++) {
+ PondModel m = new PondModel(seed);
+ assertEquals(8, m.koi.length);
+ for (PondModel.Koi k : m.koi) {
+ assertTrue(k.length >= 26f && k.length <= 46f);
+ assertEquals(PondModel.SPINE, k.spineX.length);
+ }
+ assertEquals(24, m.fry.length);
+ assertTrue(m.pads.length >= 9 && m.pads.length <= 12);
+ for (PondModel.Pad p : m.pads) assertTrue(p.r >= 14f && p.r <= 30f);
+ assertEquals(16, m.fireflies.length);
+ assertTrue("several hundred duckweed points", m.duckweed.length >= 200);
+ }
+ }
+
+ @Test
+ public void allSixVarietiesAppear() {
+ for (long seed = 1; seed <= 20; seed++) {
+ boolean[] seen = new boolean[6];
+ for (PondModel.Koi k : new PondModel(seed).koi) seen[k.variety] = true;
+ for (int v = 0; v < 6; v++) assertTrue("seed " + seed + " variety " + v, seen[v]);
+ }
+ }
+
+ @Test
+ public void spineKeepsItsSpacing() {
+ PondModel m = new PondModel(7);
+ run(m, 0, 1000);
+ for (PondModel.Koi k : m.koi) {
+ float spacing = k.length / (PondModel.SPINE - 1);
+ for (int s = 1; s < PondModel.SPINE; s++) {
+ float dx = k.spineX[s] - k.spineX[s - 1], dy = k.spineY[s] - k.spineY[s - 1];
+ float d = (float) Math.sqrt(dx * dx + dy * dy);
+ assertEquals(spacing, d, spacing * 0.05f);
+ }
+ assertEquals(k.x, k.spineX[0], 0f);
+ assertEquals(k.y, k.spineY[0], 0f);
+ }
+ }
+
+ @Test
+ public void koiStayInsideThePondForHalfAnHour() {
+ PondModel m = new PondModel(3);
+ float tol = 2f;
+ for (int i = 0; i < 30 * 60 * 30; i++) {
+ m.step(DT, i * 1000L / 30L);
+ for (PondModel.Koi k : m.koi) {
+ assertTrue(k.x >= -tol && k.x <= W + tol && k.y >= -tol && k.y <= H + tol);
+ }
+ if ((i & 63) == 0) drainAll(m);
+ }
+ }
+
+ @Test
+ public void padsKeepOutOfTheCentre() {
+ for (long seed = 1; seed <= 20; seed++) {
+ PondModel m = new PondModel(seed);
+ assertNoPadInCentre(m);
+ run(m, 0, 3000);
+ assertNoPadInCentre(m);
+ }
+ }
+
+ private static void assertNoPadInCentre(PondModel m) {
+ for (PondModel.Pad p : m.pads) {
+ // The pad's rim, not only its centre, stays out of the central ellipse.
+ float dx = Math.abs(p.x - W / 2f) / (W * 0.32f + p.r), dy = Math.abs(p.y - H / 2f) / (H * 0.30f + p.r);
+ assertTrue(dx * dx + dy * dy >= 1f);
+ }
+ }
+
+ @Test
+ public void duckweedStaysInBounds() {
+ for (long seed = 1; seed <= 20; seed++) {
+ PondModel m = new PondModel(seed);
+ assertDuckweedInBounds(m);
+ run(m, 0, 2000);
+ assertDuckweedInBounds(m);
+ }
+ }
+
+ private static void assertDuckweedInBounds(PondModel m) {
+ for (int p : m.duckweed) {
+ int x = p >>> 16, y = p & 0xFFFF;
+ assertTrue(x >= 0 && x <= PondModel.W - 1 && y >= 0 && y <= PondModel.H - 1);
+ }
+ }
+
+ @Test
+ public void startRainFadesInAndDrops() {
+ PondModel m = new PondModel(5);
+ m.startRain(0);
+ int drops = 0;
+ for (int i = 0; i <= 40 * 30; i++) {
+ m.step(DT, i * 1000L / 30L);
+ drops += drainAll(m);
+ }
+ assertTrue(m.rainLevel() > 0.9f);
+ assertTrue(drops > 50);
+ }
+
+ @Test
+ public void firstShowerComesWithinFifteenMinutes() {
+ PondModel m = new PondModel(11);
+ float max = 0f;
+ for (int i = 0; i < 15 * 60 * 10; i++) {
+ m.step(0.1f, i * 100L);
+ if (i < 5 * 60 * 10) assertEquals(0f, m.rainLevel(), 0f);
+ max = Math.max(max, m.rainLevel());
+ drainAll(m);
+ }
+ assertTrue(max > 0.9f);
+ }
+
+ @Test
+ public void gatherDrawsKoiIntoALooseRing() {
+ PondModel m = new PondModel(9);
+ run(m, 0, 60);
+ float gx = W / 2f, gy = H / 2f;
+ m.setGather(true, gx, gy);
+ run(m, 60, 60 + 60 * 30);
+ int near = 0;
+ for (PondModel.Koi k : m.koi) {
+ float d = (float) Math.hypot(k.x - gx, k.y - gy);
+ if (d >= 30f && d <= 80f) near++;
+ }
+ assertTrue("koi on the ring: " + near, near >= 6);
+ }
+
+ @Test
+ public void scatterQueuesADropAndSpeedsUpNearbyKoi() {
+ PondModel m = new PondModel(13);
+ run(m, 0, 30);
+ drainAll(m);
+ PondModel.Koi k = m.koi[0];
+ float before = k.speed;
+ float px = k.x + 5f, py = k.y;
+ m.scatter(px, py);
+ int n = m.drainDrops(xs, ys, strengths, xs.length);
+ boolean strong = false;
+ for (int i = 0; i < n; i++) {
+ if (strengths[i] >= 500 && xs[i] == px && ys[i] == py) strong = true;
+ }
+ assertTrue(strong);
+ run(m, 30, 45);
+ assertTrue("speed " + before + " -> " + k.speed, k.speed > before + 5f);
+ }
+
+ @Test
+ public void drainDropsRespectsMax() {
+ PondModel m = new PondModel(17);
+ assertEquals(0, m.drainDrops(xs, ys, strengths, xs.length));
+ m.startRain(0);
+ run(m, 0, 30 * 30);
+ assertEquals(5, m.drainDrops(xs, ys, strengths, 5));
+ assertEquals(0, m.drainDrops(xs, ys, strengths, 0));
+ float[] smallX = new float[3], smallY = new float[3];
+ int[] smallS = new int[3];
+ assertEquals(3, m.drainDrops(smallX, smallY, smallS, 10));
+ int n = m.drainDrops(xs, ys, strengths, xs.length);
+ assertTrue(n > 0 && n <= 64);
+ for (int i = 0; i < n; i++) assertTrue(strengths[i] >= 80 && strengths[i] <= 200);
+ assertEquals(0, m.drainDrops(xs, ys, strengths, xs.length));
+ }
+
+ @Test
+ public void stepClampsDt() {
+ PondModel m = new PondModel(19);
+ PondModel.Koi k = m.koi[0];
+ float x = k.x, y = k.y;
+ m.step(-1f, 0);
+ assertEquals(x, k.x, 0f);
+ assertEquals(y, k.y, 0f);
+ m.step(10f, 10);
+ assertTrue(Math.hypot(k.x - x, k.y - y) <= 0.1 * 50);
+ }
+}
diff --git a/addons/koi-pond/app/src/test/java/io/github/nottoobright/koipond/RipplesTest.java b/addons/koi-pond/app/src/test/java/io/github/nottoobright/koipond/RipplesTest.java
new file mode 100644
index 000000000..0b2c6a5b6
--- /dev/null
+++ b/addons/koi-pond/app/src/test/java/io/github/nottoobright/koipond/RipplesTest.java
@@ -0,0 +1,134 @@
+package io.github.nottoobright.koipond;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Random;
+
+import org.junit.Test;
+
+public class RipplesTest {
+
+ private static final int W = 240, H = 135, CX = 120, CY = 67;
+
+ private static int maxAbs(Ripples r) {
+ int m = 0;
+ for (int v : r.heights()) {
+ m = Math.max(m, Math.abs(v));
+ }
+ return m;
+ }
+
+ private static void assertBordersZero(Ripples r) {
+ for (int x = 0; x < r.width(); x++) {
+ assertEquals(0, r.at(x, 0));
+ assertEquals(0, r.at(x, r.height() - 1));
+ }
+ for (int y = 0; y < r.height(); y++) {
+ assertEquals(0, r.at(0, y));
+ assertEquals(0, r.at(r.width() - 1, y));
+ }
+ }
+
+ @Test
+ public void dropRaisesTheCentre() {
+ Ripples r = new Ripples(W, H);
+ r.drop(CX, CY, 3, 256);
+ assertEquals(256, r.at(CX, CY));
+ assertEquals(0, r.at(CX + 3, CY));
+ Ripples down = new Ripples(W, H);
+ down.drop(CX, CY, 3, -256);
+ assertEquals(-256, down.at(CX, CY));
+ }
+
+ @Test
+ public void dropSpreads() {
+ Ripples r = new Ripples(W, H);
+ r.drop(CX, CY, 3, 256);
+ assertEquals(0, r.at(CX + 10, CY));
+ boolean reached = false;
+ for (int s = 0; s < 15 && !reached; s++) {
+ r.step();
+ reached = r.at(CX + 10, CY) != 0;
+ }
+ assertTrue("ring did not reach 10 cells within 15 steps", reached);
+ }
+
+ @Test
+ public void ringFadesWithinTwoSeconds() {
+ Ripples r = new Ripples(W, H);
+ r.drop(CX, CY, 3, 256);
+ for (int s = 0; s < 60; s++) {
+ r.step();
+ }
+ assertTrue("max " + maxAbs(r) + " after 60 steps", maxAbs(r) < 256 * 4 / 100);
+ }
+
+ @Test
+ public void energyDecaysToNearZero() {
+ Ripples r = new Ripples(W, H);
+ r.drop(CX, CY, 4, 512);
+ for (int s = 0; s < 120; s++) {
+ r.step();
+ }
+ assertTrue("max " + maxAbs(r) + " after 120 steps", maxAbs(r) <= 2);
+ }
+
+ @Test
+ public void bordersStayZero() {
+ Ripples r = new Ripples(W, H);
+ r.drop(3, 3, 6, 1000);
+ r.drop(W - 4, H - 4, 6, -1000);
+ r.drop(CX, 2, 8, 800);
+ assertBordersZero(r);
+ for (int s = 0; s < 50; s++) {
+ r.step();
+ assertBordersZero(r);
+ }
+ }
+
+ @Test
+ public void dropsAtOrOverTheEdgeDoNotThrow() {
+ Ripples r = new Ripples(W, H);
+ r.drop(0, 0, 5, 500);
+ r.drop(W - 1, H - 1, 5, 500);
+ r.drop(-20, -20, 5, 500);
+ r.drop(W + 20, H + 20, 5, 500);
+ r.drop(-3, CY, 6, 500);
+ r.drop(CX, H + 2, 6, -500);
+ r.drop(CX, CY, 0, 500);
+ r.step();
+ assertBordersZero(r);
+ assertEquals(0, r.at(-1, 0));
+ assertEquals(0, r.at(W, H));
+ }
+
+ @Test
+ public void clearZeroes() {
+ Ripples r = new Ripples(W, H);
+ r.drop(CX, CY, 5, 400);
+ for (int s = 0; s < 5; s++) {
+ r.step();
+ }
+ r.clear();
+ assertEquals(0, maxAbs(r));
+ r.step();
+ assertEquals(0, maxAbs(r));
+ }
+
+ @Test
+ public void heightsStayWithinClampUnderManyDrops() {
+ Ripples r = new Ripples(W, H);
+ Random rng = new Random(42);
+ for (int i = 0; i < 1000; i++) {
+ int strength = (64 + rng.nextInt(4000)) * (rng.nextBoolean() ? 1 : -1);
+ r.drop(rng.nextInt(W + 20) - 10, rng.nextInt(H + 20) - 10, 1 + rng.nextInt(8), strength);
+ if (i % 3 == 0) {
+ r.step();
+ }
+ assertTrue(maxAbs(r) <= Ripples.MAX_HEIGHT);
+ }
+ assertBordersZero(r);
+ assertEquals(W * H, r.heights().length);
+ }
+}
diff --git a/addons/koi-pond/app/src/test/java/io/github/nottoobright/koipond/TimeOfDayTest.java b/addons/koi-pond/app/src/test/java/io/github/nottoobright/koipond/TimeOfDayTest.java
new file mode 100644
index 000000000..f5c2b6296
--- /dev/null
+++ b/addons/koi-pond/app/src/test/java/io/github/nottoobright/koipond/TimeOfDayTest.java
@@ -0,0 +1,136 @@
+package io.github.nottoobright.koipond;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class TimeOfDayTest {
+
+ private static float hm(int h, int m) {
+ return h * 60 + m;
+ }
+
+ @Test
+ public void anchorsGiveThePureKeyPalette() {
+ assertEquals(TimeOfDay.palette(TimeOfDay.NIGHT), TimeOfDay.at(hm(4, 30)));
+ assertEquals(TimeOfDay.palette(TimeOfDay.DAWN), TimeOfDay.at(hm(6, 0)));
+ assertEquals(TimeOfDay.palette(TimeOfDay.DAY), TimeOfDay.at(hm(8, 0)));
+ assertEquals(TimeOfDay.palette(TimeOfDay.DAY), TimeOfDay.at(hm(12, 0)));
+ assertEquals(TimeOfDay.palette(TimeOfDay.DAY), TimeOfDay.at(hm(16, 0)));
+ assertEquals(TimeOfDay.palette(TimeOfDay.GOLDEN), TimeOfDay.at(hm(17, 30)));
+ assertEquals(TimeOfDay.palette(TimeOfDay.DUSK), TimeOfDay.at(hm(19, 0)));
+ assertEquals(TimeOfDay.palette(TimeOfDay.NIGHT), TimeOfDay.at(hm(20, 30)));
+ assertEquals(TimeOfDay.palette(TimeOfDay.NIGHT), TimeOfDay.at(0f));
+ assertEquals(TimeOfDay.palette(TimeOfDay.NIGHT), TimeOfDay.at(hm(2, 0)));
+ }
+
+ @Test
+ public void betweenAnchorsIsABlend() {
+ Palette p = TimeOfDay.at(hm(18, 15));
+ assertNotEquals(TimeOfDay.palette(TimeOfDay.GOLDEN), p);
+ assertNotEquals(TimeOfDay.palette(TimeOfDay.DUSK), p);
+ }
+
+ @Test
+ public void dominantKey() {
+ assertEquals(TimeOfDay.DAWN, TimeOfDay.key(hm(6, 0)));
+ assertEquals(TimeOfDay.DAY, TimeOfDay.key(hm(12, 0)));
+ assertEquals(TimeOfDay.GOLDEN, TimeOfDay.key(hm(17, 30)));
+ assertEquals(TimeOfDay.DUSK, TimeOfDay.key(hm(19, 0)));
+ assertEquals(TimeOfDay.NIGHT, TimeOfDay.key(hm(23, 0)));
+ assertEquals(TimeOfDay.NIGHT, TimeOfDay.key(hm(5, 0)));
+ assertEquals(TimeOfDay.DAWN, TimeOfDay.key(hm(5, 30)));
+ assertEquals(TimeOfDay.DAY, TimeOfDay.key(hm(7, 30)));
+ }
+
+ @Test
+ public void blendingIsContinuousAllDayIncludingMidnight() {
+ int maxStep = 4;
+ for (int m = 0; m < TimeOfDay.MINUTES; m++) {
+ int[] a = TimeOfDay.at(m).colors();
+ int[] b = TimeOfDay.at(m + 1).colors();
+ for (int i = 0; i < a.length; i++) {
+ for (int shift = 0; shift < 32; shift += 8) {
+ int d = Math.abs(((a[i] >>> shift) & 0xFF) - ((b[i] >>> shift) & 0xFF));
+ assertTrue("jump of " + d + " at minute " + m + ", colour " + i, d <= maxStep);
+ }
+ }
+ }
+ }
+
+ @Test
+ public void palettesAreOpaque() {
+ for (int k = TimeOfDay.DAWN; k <= TimeOfDay.NIGHT; k++) {
+ for (int c : TimeOfDay.palette(k).colors()) assertEquals(0xFF, c >>> 24);
+ }
+ for (int m = 0; m < TimeOfDay.MINUTES; m += 7) {
+ for (int c : TimeOfDay.at(m).colors()) assertEquals(0xFF, c >>> 24);
+ }
+ }
+
+ @Test
+ public void nightIsDarkerThanDay() {
+ assertTrue(luma(TimeOfDay.palette(TimeOfDay.NIGHT).ambient) < luma(TimeOfDay.palette(TimeOfDay.DUSK).ambient));
+ assertTrue(luma(TimeOfDay.palette(TimeOfDay.DUSK).ambient) < luma(TimeOfDay.palette(TimeOfDay.DAY).ambient));
+ assertTrue(luma(TimeOfDay.palette(TimeOfDay.NIGHT).caustic) < luma(TimeOfDay.palette(TimeOfDay.DAWN).caustic));
+ }
+
+ @Test
+ public void fireflies() {
+ assertEquals(0f, TimeOfDay.fireflies(hm(12, 0)), 0f);
+ assertEquals(0f, TimeOfDay.fireflies(hm(6, 0)), 0f);
+ assertEquals(0f, TimeOfDay.fireflies(hm(19, 0)), 0f);
+ assertEquals(1f, TimeOfDay.fireflies(hm(20, 30)), 0f);
+ assertEquals(1f, TimeOfDay.fireflies(hm(23, 0)), 0f);
+ assertEquals(1f, TimeOfDay.fireflies(hm(2, 0)), 0f);
+ assertEquals(1f, TimeOfDay.fireflies(0f), 0f);
+ float f = TimeOfDay.fireflies(hm(19, 45));
+ assertTrue(f > 0f && f < 1f);
+ float dawn = TimeOfDay.fireflies(hm(5, 15));
+ assertTrue(dawn > 0f && dawn < 1f);
+ }
+
+ @Test
+ public void lerpEndpointsAndClamping() {
+ int a = 0xFF102030, b = 0x80F0E0D0;
+ assertEquals(a, TimeOfDay.lerp(a, b, 0f));
+ assertEquals(b, TimeOfDay.lerp(a, b, 1f));
+ assertEquals(a, TimeOfDay.lerp(a, b, -3f));
+ assertEquals(b, TimeOfDay.lerp(a, b, 7f));
+ int mid = TimeOfDay.lerp(0xFF000000, 0xFFFFFFFF, 0.5f);
+ for (int shift = 0; shift < 24; shift += 8) {
+ int c = (mid >>> shift) & 0xFF;
+ assertTrue(c == 127 || c == 128);
+ }
+ assertEquals(0xFF, mid >>> 24);
+ }
+
+ @Test
+ public void paletteLerpEndpoints() {
+ Palette day = TimeOfDay.palette(TimeOfDay.DAY);
+ Palette night = TimeOfDay.palette(TimeOfDay.NIGHT);
+ assertEquals(day, Palette.lerp(day, night, 0f));
+ assertEquals(night, Palette.lerp(day, night, 1f));
+ assertEquals(day, Palette.lerp(day, night, -1f));
+ assertEquals(night, Palette.lerp(day, night, 2f));
+ }
+
+ @Test
+ public void minutesOutsideTheDayWrap() {
+ assertEquals(TimeOfDay.at(hm(12, 0)), TimeOfDay.at(hm(12, 0) + TimeOfDay.MINUTES));
+ assertEquals(TimeOfDay.at(hm(18, 15)), TimeOfDay.at(hm(18, 15) - TimeOfDay.MINUTES));
+ assertEquals(TimeOfDay.at(hm(23, 0)), TimeOfDay.at(-60f));
+ assertEquals(TimeOfDay.palette(TimeOfDay.NIGHT), TimeOfDay.at(1440f));
+ assertEquals(TimeOfDay.NIGHT, TimeOfDay.key(-60f));
+ assertEquals(TimeOfDay.DAY, TimeOfDay.key(hm(12, 0) + 3 * TimeOfDay.MINUTES));
+ assertEquals(1f, TimeOfDay.fireflies(hm(2, 0) + TimeOfDay.MINUTES), 0f);
+ assertEquals(0f, TimeOfDay.fireflies(hm(12, 0) - TimeOfDay.MINUTES), 0f);
+ assertEquals(TimeOfDay.fireflies(hm(19, 45)), TimeOfDay.fireflies(hm(19, 45) - 2 * TimeOfDay.MINUTES), 1e-4f);
+ }
+
+ private static int luma(int c) {
+ return ((c >> 16) & 0xFF) * 3 + ((c >> 8) & 0xFF) * 6 + (c & 0xFF);
+ }
+}
diff --git a/addons/koi-pond/build-and-install.ps1 b/addons/koi-pond/build-and-install.ps1
new file mode 100644
index 000000000..2b5b89148
--- /dev/null
+++ b/addons/koi-pond/build-and-install.ps1
@@ -0,0 +1,45 @@
+# Windows version of build-and-install.sh: build Koi Pond, install it on the TV and make it the screensaver.
+#
+# Usage: addons\koi-pond\build-and-install.ps1 -TvHost 192.168.1.50
+# addons\koi-pond\build-and-install.ps1 -TvHost 192.168.1.50 -Start
+# addons\koi-pond\build-and-install.ps1 -TvHost 192.168.1.50 -SkipBuild # the APK tools/docker-build.sh built
+# addons\koi-pond\build-and-install.ps1 -TvHost 192.168.1.50 -Uninstall
+param(
+ [string]$TvHost = $env:TV_HOST,
+ [switch]$Uninstall,
+ [switch]$SkipBuild,
+ [switch]$Start
+)
+$ErrorActionPreference = 'Stop'
+if (-not $TvHost) { throw 'pass -TvHost <tv ip> or set $env:TV_HOST' }
+$env:TV_HOST = $TvHost
+$here = $PSScriptRoot
+$tools = Join-Path (Split-Path (Split-Path $here -Parent) -Parent) 'tools'
+$py = Join-Path $tools 'venv\Scripts\python.exe'
+if (-not (Test-Path $py)) { throw 'run: python -m venv tools\venv; tools\venv\Scripts\python.exe -m pip install -r tools\requirements.txt' }
+$pkg = 'io.github.nottoobright.koipond'
+$dream = "$pkg/.PondDream"
+$before = '/data/local/tmp/cyt-koipond-before'
+function Tv([string]$cmd) { & $py -I (Join-Path $tools 'tv.py') $cmd; if ($LASTEXITCODE) { throw "tv.py failed: $cmd" } }
+
+if ($Uninstall) {
+ # Put the screensaver from before the first run back, then remove the app.
+ Tv "if [ -f $before ]; then { read c; read e; } < $before; if [ `"`$c`" = null ]; then settings delete secure screensaver_components >/dev/null; else settings put secure screensaver_components `"`$c`"; fi; [ `"`$e`" = null ] || settings put secure screensaver_enabled `"`$e`"; rm -f $before; fi; pm uninstall $pkg"
+ exit 0
+}
+
+if (-not $SkipBuild) {
+ Push-Location $here
+ try {
+ & .\gradlew.bat assembleRelease -q
+ if ($LASTEXITCODE) { throw 'build failed (JDK 17 and Android SDK 34 needed, or build in Docker: tools/docker-build.sh addons/koi-pond, then -SkipBuild)' }
+ } finally { Pop-Location }
+}
+$apk = Join-Path $here 'app\build\outputs\apk\release\app-release.apk'
+if (-not (Test-Path $apk)) { throw "no $apk; build it first (tools/docker-build.sh addons/koi-pond)" }
+& $py -I (Join-Path $tools 'b64push.py') $apk /data/local/tmp/koipond.apk | Out-Null
+if ($LASTEXITCODE) { throw 'sending the APK failed' }
+Tv 'pm install -r /data/local/tmp/koipond.apk; rm -f /data/local/tmp/koipond.apk'
+Tv "[ -f $before ] || { settings get secure screensaver_components; settings get secure screensaver_enabled; } > $before; settings put secure screensaver_components $dream; settings put secure screensaver_enabled 1"
+Write-Host 'Installed: Koi Pond is the screensaver. Undo with: addons\koi-pond\build-and-install.ps1 -Uninstall'
+if ($Start) { Tv 'am start -n com.android.systemui/.Somnambulator' }
diff --git a/addons/koi-pond/build-and-install.sh b/addons/koi-pond/build-and-install.sh
new file mode 100755
index 000000000..fd0df4f78
--- /dev/null
+++ b/addons/koi-pond/build-and-install.sh
@@ -0,0 +1,36 @@
+#!/usr/bin/env bash
+# Build Koi Pond, install it on the TV and make it the TV's screensaver.
+#
+# Usage: TV_HOST=192.168.1.50 addons/koi-pond/build-and-install.sh
+# TV_HOST=192.168.1.50 START=1 addons/koi-pond/build-and-install.sh # and show it now
+# TV_HOST=192.168.1.50 SKIP_BUILD=1 addons/koi-pond/build-and-install.sh # install the APK tools/docker-build.sh built
+# TV_HOST=192.168.1.50 addons/koi-pond/build-and-install.sh --uninstall # previous screensaver back, app removed
+set -euo pipefail
+HERE="$(cd "$(dirname "$0")" && (pwd -W 2>/dev/null || pwd))"
+TOOLS="$HERE/../../tools"
+: "${TV_HOST:?set TV_HOST to the TV IP address, e.g. TV_HOST=192.168.1.50 $0}"
+PY="$TOOLS/venv/bin/python"
+[ -x "$PY" ] || PY="$TOOLS/venv/Scripts/python.exe"
+[ -x "$PY" ] || { echo "run: python3 -m venv tools/venv && tools/venv/bin/pip install -r tools/requirements.txt" >&2; exit 1; }
+export MSYS_NO_PATHCONV=1
+PKG=io.github.nottoobright.koipond
+DREAM=$PKG/.PondDream
+APK="$HERE/app/build/outputs/apk/release/app-release.apk"
+# The screensaver the TV had before the first run, so --uninstall can put it back.
+BEFORE=/data/local/tmp/cyt-koipond-before
+tv() { "$PY" -I "$TOOLS/tv.py" "$@"; }
+
+if [ "${1:-}" = --uninstall ]; then
+ tv "if [ -f $BEFORE ]; then { read c; read e; } < $BEFORE; if [ \"\$c\" = null ]; then settings delete secure screensaver_components >/dev/null; else settings put secure screensaver_components \"\$c\"; fi; [ \"\$e\" = null ] || settings put secure screensaver_enabled \"\$e\"; rm -f $BEFORE; fi; pm uninstall $PKG; echo screensaver: \$(settings get secure screensaver_components)"
+ exit 0
+fi
+
+if [ "${SKIP_BUILD:-}" != 1 ]; then
+ (cd "$HERE" && ./gradlew assembleRelease -q) || { echo "build failed (JDK 17 and Android SDK 34 needed, or build in Docker: tools/docker-build.sh addons/koi-pond, then SKIP_BUILD=1)" >&2; exit 1; }
+fi
+[ -f "$APK" ] || { echo "ERROR: no $APK; build it first (tools/docker-build.sh addons/koi-pond)." >&2; exit 1; }
+"$PY" -I "$TOOLS/b64push.py" "$APK" /data/local/tmp/koipond.apk >/dev/null
+tv "pm install -r /data/local/tmp/koipond.apk; rm -f /data/local/tmp/koipond.apk"
+tv "[ -f $BEFORE ] || { settings get secure screensaver_components; settings get secure screensaver_enabled; } > $BEFORE; settings put secure screensaver_components $DREAM; settings put secure screensaver_enabled 1" >/dev/null
+echo "Installed: Koi Pond is the screensaver. Undo with: addons/koi-pond/build-and-install.sh --uninstall"
+[ -z "${START:-}" ] || tv "am start -n com.android.systemui/.Somnambulator >/dev/null; sleep 3; dumpsys dreams | grep mCurrentDreamName"
diff --git a/addons/koi-pond/build.gradle b/addons/koi-pond/build.gradle
new file mode 100644
index 000000000..48978475f
--- /dev/null
+++ b/addons/koi-pond/build.gradle
@@ -0,0 +1,3 @@
+plugins {
+ id 'com.android.application' version '8.5.2' apply false
+}
diff --git a/addons/koi-pond/gradle.properties b/addons/koi-pond/gradle.properties
new file mode 100644
index 000000000..1edaf2baa
--- /dev/null
+++ b/addons/koi-pond/gradle.properties
@@ -0,0 +1 @@
+org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
diff --git a/addons/koi-pond/gradle/wrapper/gradle-wrapper.jar b/addons/koi-pond/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 000000000..2c3521197
Binary files /dev/null and b/addons/koi-pond/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/addons/koi-pond/gradle/wrapper/gradle-wrapper.properties b/addons/koi-pond/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000..77f5d0ba6
--- /dev/null
+++ b/addons/koi-pond/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,8 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
+distributionSha256Sum=d725d707bfabd4dfdc958c624003b3c80accc03f7037b5122c4b1d0ef15cecab
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/addons/koi-pond/gradlew b/addons/koi-pond/gradlew
new file mode 100755
index 000000000..f5feea6d6
--- /dev/null
+++ b/addons/koi-pond/gradlew
@@ -0,0 +1,252 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
+' "$PWD" ) || exit
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ if ! command -v java >/dev/null 2>&1
+ then
+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/addons/koi-pond/gradlew.bat b/addons/koi-pond/gradlew.bat
new file mode 100644
index 000000000..9d21a2183
--- /dev/null
+++ b/addons/koi-pond/gradlew.bat
@@ -0,0 +1,94 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/addons/koi-pond/screenshot.jpg b/addons/koi-pond/screenshot.jpg
new file mode 100644
index 000000000..781b9ad33
Binary files /dev/null and b/addons/koi-pond/screenshot.jpg differ
diff --git a/addons/koi-pond/settings.gradle b/addons/koi-pond/settings.gradle
new file mode 100644
index 000000000..46ddcf145
--- /dev/null
+++ b/addons/koi-pond/settings.gradle
@@ -0,0 +1,16 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+rootProject.name = "koi-pond"
+include ':app'