Add 2D canvas mode compacted to the steps, ocean-chaos and reef-2d shaders

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
April John 2026-10-16 15:28:41 +02:00
commit d917860201

View file

@ -11,6 +11,7 @@ An optional debug window shows the shader at full resolution and the
import argparse
import os
import re
import signal
import socket
import sys
@ -31,6 +32,7 @@ FLAG_RGBA = 0x02
FLAG_BITS_16 = 0x08
WHITE_MODES = ("extract", "alpha", "off")
COMPACT_MODES = ("mean", "max", "row")
# --- Protocol --------------------------------------------------------------
@ -68,6 +70,58 @@ def encode_frame(rgbw):
BLACK_FRAME = encode_frame(np.zeros((STEPS, 4), dtype=np.float32))
# --- 2D canvas ------------------------------------------------------------
CANVAS_RE = re.compile(
r"^\s*//\s*canvas:\s*(\d+)x(\d+)(?:\s+compact:\s*(\w+))?", re.M)
def parse_canvas(text):
"""Parse '256x32' into (256, 32); the width must fit the 16 steps."""
m = re.fullmatch(r"(\d+)x(\d+)", text.strip())
if not m:
raise ValueError("canvas must look like 256x32, got {!r}".format(text))
w, h = int(m.group(1)), int(m.group(2))
if w < STEPS or h < 1 or w % STEPS != 0:
raise ValueError(
"canvas width must be a multiple of {}, got {}x{}".format(
STEPS, w, h))
return (w, h)
def directive(source):
"""
Read '// canvas: 256x32 compact: mean' from the top of a shader.
Returns (canvas or None, compact or None).
"""
m = CANVAS_RE.search("\n".join(source.splitlines()[:15]))
if not m:
return None, None
compact = m.group(3)
if compact is not None and compact not in COMPACT_MODES:
raise ValueError("unknown compact mode: {}".format(compact))
return parse_canvas("{}x{}".format(m.group(1), m.group(2))), compact
def compact_canvas(pixels, mode="mean"):
"""
Compact a 2D canvas (H x W x 4 floats) to STEPS x 4, one step per
W/STEPS wide group of columns.
mean: average of the whole column group
max: brightest value per channel in the group
row: average of the middle row only
"""
h, w, _ = pixels.shape
cols = w // STEPS
if mode == "row":
return pixels[h // 2].reshape(STEPS, cols, 4).mean(axis=1)
groups = pixels.reshape(h, STEPS, cols, 4)
if mode == "max":
return groups.max(axis=(0, 2))
return groups.mean(axis=(0, 2))
# --- Shaders ---------------------------------------------------------------
VERTEX = """
@ -193,30 +247,53 @@ class Renderer:
self.quad = ctx.buffer(
np.array([-1, -1, 3, -1, -1, 3], dtype="f4").tobytes())
self.size = size
self.canvas = None
self.compact = "mean"
self.strip_tex = ctx.texture((STEPS, 1), 4, dtype="f4")
self.strip_tex.filter = (moderngl.NEAREST, moderngl.NEAREST)
self.strip_fbo = ctx.framebuffer([self.strip_tex])
self.full_tex = None
self.full_fbo = None
self.resize(size)
self._make_full(size, "f1")
self.program = None
self.vao_strip = None
self.vao_full = None
self.time = 0.0
self.frame = 0
def resize(self, size):
size = (max(1, int(size[0])), max(1, int(size[1])))
if self.full_fbo is not None and size == self.size:
return
self.size = size
def _make_full(self, size, dtype):
if self.full_tex is not None:
self.full_fbo.release()
self.full_tex.release()
self.full_tex = self.ctx.texture(size, 4, dtype="f1")
self.full_tex.filter = (moderngl.LINEAR, moderngl.LINEAR)
self.size = size
self.full_tex = self.ctx.texture(size, 4, dtype=dtype)
self.full_tex.filter = (moderngl.NEAREST if self.canvas
else moderngl.LINEAR,) * 2
self.full_fbo = self.ctx.framebuffer([self.full_tex])
def resize(self, size):
"""Resize the preview. In 2D canvas mode the canvas size is fixed."""
if self.canvas:
return
size = (max(1, int(size[0])), max(1, int(size[1])))
if size != self.size:
self._make_full(size, "f1")
def configure(self, canvas=None, compact="mean"):
"""Use a 2D canvas (W, H) compacted to the steps, or None for 1D."""
if canvas is not None:
canvas = parse_canvas("{}x{}".format(*canvas))
if compact not in COMPACT_MODES:
raise ValueError("unknown compact mode: {}".format(compact))
self.compact = compact
if canvas == self.canvas:
return
self.canvas = canvas
if canvas:
self._make_full(canvas, "f4")
else:
self._make_full((512, 288), "f1")
def load(self, source):
"""Compile a shader. Raises on error and keeps the old one."""
program = self.ctx.program(
@ -243,11 +320,22 @@ class Renderer:
def render_strip(self, t, dt=0.0, frame=0):
"""Render the 16x1 strip, returns STEPS x 4 float pixels."""
if self.canvas:
# Render the 2D canvas and compact it down to the steps.
self._draw(self.full_fbo, self.canvas, t, dt, frame)
raw = self.full_fbo.read(components=4, dtype="f4")
w, h = self.canvas
pixels = np.frombuffer(raw, dtype="f4").reshape(h, w, 4)
strip = compact_canvas(pixels, self.compact).astype("f4")
self.strip_tex.write(strip.tobytes())
return strip
self._draw(self.strip_fbo, (STEPS, 1), t, dt, frame)
raw = self.strip_fbo.read(components=4, dtype="f4")
return np.frombuffer(raw, dtype="f4").reshape(STEPS, 4).copy()
def render_full(self, t, dt=0.0, frame=0):
if self.canvas:
return # already rendered by render_strip
self._draw(self.full_fbo, self.size, t, dt, frame)
@ -371,7 +459,12 @@ def run(args):
source = shader.poll()
if source is not None:
try:
canvas, compact = directive(source)
if args.canvas:
canvas = parse_canvas(args.canvas)
renderer.load(source)
renderer.configure(
canvas, args.compact or compact or "mean")
print("loaded {}".format(args.shader), file=sys.stderr)
except Exception as err:
print("shader error:\n{}".format(err), file=sys.stderr)
@ -417,6 +510,11 @@ def parse_args(argv=None):
p.add_argument("--port", type=int, default=PORT_DEFAULT)
p.add_argument("--fps", type=float, default=60.0)
p.add_argument("--white", choices=WHITE_MODES, default="extract")
p.add_argument("--canvas", metavar="WxH",
help="render a 2D canvas and compact it to the steps "
"(overrides '// canvas: WxH' in the shader)")
p.add_argument("--compact", choices=COMPACT_MODES,
help="how the canvas is compacted (default mean)")
p.add_argument("--brightness", type=float, default=100.0,
help="0..100 percent, scales what is sent (default 100)")
p.add_argument("--dry-run", action="store_true",