Files
lintunes/lintunes/gui/visualizer_lint.py
T
trav 2b59ea02da v0.88.1: Lint Oontz is one ball — it sits when nothing plays and falls asleep later; the wheel's modes for it are colour, gray, black
The visualizer keeps its clock with nothing playing for a style that idles
(fed silence), so the ball can sit, blink and fall asleep while paused.
2026-11-06 02:24:59 -08:00

372 lines
14 KiB
Python

"""Lint Oontz: a ball of lint in headphones, dancing (Round 122).
A very rough line drawing, animated like stop motion: the renderer steps at
``FPS`` (8) on its own clock and each step is a new pose with every line
re-wobbled, never an in-between — no tweening. Each step costs one repaint;
the widget's 60 Hz timer only feeds it audio (silence while nothing plays:
``idles``, so it keeps its clock and can fall asleep).
What the music does to it:
- **bass** → the head bob. A bass onset (energy well over its own recent
average) dips the ball and bends the knees; between beats it springs back.
- **busy** → the arms. When the beats come fast (``BUSY_BPM`` or more,
counted from the onsets themselves) *and* the spectrum is full
(``BUSY_FULLNESS``), every beat throws a new arm pose and the feet step.
Otherwise the arms hang and only the head bobs.
- **quiet** (or nothing playing) → it sits down after ``SIT_AFTER_S``, and
after ``SLEEP_AFTER_S`` lies down to sleep (closed eyes, rising z's),
until the music comes back.
The lines are the colour the wheel picks — highlight, gray or black
(``black_mode``: this style adds black to the wheel) — on the panel's gray.
"""
import math
import numpy as np
from PyQt6.QtCore import QPointF, QRectF, Qt
from PyQt6.QtGui import QColor, QPainterPath, QPen
STYLE = "lint"
FPS = 8 # stop motion: a new drawing this often
STEP_S = 1.0 / FPS
INSET = 3
BASS_HZ = (40.0, 160.0)
FFT = 2048
ONSET_RATIO = 1.45 # bass this far over its average is a beat
ONSET_GAP_S = 0.26 # no two beats closer than this (~230 BPM)
AVERAGE_S = 0.6 # how long the bass average remembers
TEMPO_WINDOW_S = 5.0 # beats counted over this long for the tempo
BUSY_BPM = 108
BUSY_FULLNESS = 0.28 # mean band level (0..1) of a "full" spectrum:
# pink noise at -20 dB RMS reads 0.31, a sparse
# mix of a few tones 0.12-0.14
CALM_AFTER_S = 2.0 # busy has to be gone this long to stop dancing
QUIET_DB = -48.0 # RMS under this is quiet
SIT_AFTER_S = 1.5
SLEEP_AFTER_S = 20.0
WAKE_AFTER_S = 0.3
FULLNESS_BANDS = 16
# Arm poses as (left, right) shoulder angles in degrees from straight down,
# outward positive, plus each elbow's extra bend.
HANG = ((18, 8), (18, 8))
LYING = ((4, 0), (4, 0)) # asleep: arms along the body
SITTING = ((48, -20), (48, -20)) # hands down on the floor beside it
BLINK_EVERY = 29 # steps; one closed-eye drawing each time
STAND, SIT, SLEEP = "stand", "sit", "sleep"
DANCE = (
((150, -30), (30, 20)), # left up
((140, -20), (140, -20)), # both up
((30, 20), (150, -30)), # right up
((90, 40), (90, 40)), # both out, bent
)
class _Figure:
"""One lint ball: its fixed fuzz profile and its own pose."""
def __init__(self, index: int):
rng = np.random.default_rng(7919 * (index + 1))
self.index = index
self.radii = 1.0 + rng.uniform(-0.09, 0.09, 26)
self.hairs = rng.uniform(0, 2 * math.pi, 9)
self.hair_len = rng.uniform(0.12, 0.3, 9)
self.pose = 0
class LintRenderer:
name = STYLE
black_mode = True # the wheel offers black for this style
idles = True # keep the clock running with nothing playing
dimmed = False # set by the widget (unused: colour is given)
panel = QColor(200, 200, 200) # set by the widget: the background
def __init__(self, config=None):
self._fig = _Figure(0)
self._behind = 0.0
self._clock = 0.0
self.step = 1 # 0 would be a blink
self._bass_avg = 0.0
self._last_beat = -1.0
self._beats = []
self._beat_pending = False
self.bob = 0.0
self.fullness = 0.0
self.busy = False
self._calm_for = 0.0
self._quiet_for = SIT_AFTER_S # nothing has played yet: sitting
self._loud_for = 0.0
self.posture = SIT
self.feet = 0
# ---- the renderer contract ----
def configure(self, config):
pass # no settings yet
@property
def asleep(self) -> bool:
return self.posture == SLEEP
def clear(self):
"""Stopped or paused: it sits down (and sleeps, given time)."""
self._quiet_for = max(self._quiet_for, SIT_AFTER_S)
self._loud_for = 0.0
if self.posture == STAND:
self.posture = SIT
self.busy = False
self.bob = 0.0
self._beats.clear()
self.step += 1
@property
def tempo(self) -> float:
"""Beats per minute, from the onsets heard in the last few seconds."""
recent = [t for t in self._beats if self._clock - t <= TEMPO_WINDOW_S]
if len(recent) < 3:
return 0.0
return 60.0 * (len(recent) - 1) / max(1e-6, recent[-1] - recent[0])
def advance(self, frame) -> bool:
dt = max(0.0, frame.dt)
self._clock += dt
self._listen(frame, dt)
self._behind = min(self._behind + dt, STEP_S * 2)
if self._behind < STEP_S:
return False
self._behind -= STEP_S
self._pose()
return True
# ---- listening (every tick) ----
def _listen(self, frame, dt):
pending = frame.pending if len(frame.pending) else frame.samples[-512:]
rms = float(np.sqrt(np.mean(np.square(pending, dtype=np.float64))))
db = 20 * math.log10(rms + 1e-10)
if db < QUIET_DB:
self._quiet_for += dt
self._loud_for = 0.0
else:
self._loud_for += dt
self._quiet_for = 0.0
if self.posture != STAND and self._loud_for >= WAKE_AFTER_S:
self.posture = STAND
elif self._quiet_for >= SLEEP_AFTER_S:
self.posture = SLEEP
elif self.posture == STAND and self._quiet_for >= SIT_AFTER_S:
self.posture = SIT
from lintunes.gui.visualizer_styles import (
band_edges, band_levels, spectrum_of)
spectrum, freqs = spectrum_of(frame.samples, FFT, frame.rate)
lo, hi = np.searchsorted(freqs, BASS_HZ)
bass = float(np.sum(np.square(spectrum[lo:hi])))
keep = math.exp(-dt / AVERAGE_S) if dt > 0 else 1.0
if (db >= QUIET_DB and bass > ONSET_RATIO * self._bass_avg
and bass > 1e-5
and self._clock - self._last_beat >= ONSET_GAP_S):
self._last_beat = self._clock
self._beats.append(self._clock)
self._beat_pending = True
self._beats = [t for t in self._beats
if self._clock - t <= TEMPO_WINDOW_S]
self._bass_avg = keep * self._bass_avg + (1 - keep) * bass
levels = band_levels(spectrum, freqs,
band_edges(FULLNESS_BANDS, frame.rate))
self.fullness = keep * self.fullness + (1 - keep) * float(levels.mean())
wants = self.tempo >= BUSY_BPM and self.fullness >= BUSY_FULLNESS
if wants:
self.busy = True
self._calm_for = 0.0
elif self.busy:
self._calm_for += dt
if self._calm_for >= CALM_AFTER_S:
self.busy = False
# ---- posing (every stop-motion step) ----
def _pose(self):
self.step += 1
if self.posture != STAND:
self.bob = 0.0
self._beat_pending = False
return
if self._beat_pending:
self._beat_pending = False
self.bob = 1.0
if self.busy:
self.feet ^= 1
self._fig.pose = (self._fig.pose + 1) % len(DANCE)
else:
self.bob = 0.35 if self.bob >= 1.0 else 0.0
# ---- drawing ----
def paint(self, painter, rect, color: QColor, gray: QColor = None):
area = QRectF(rect).adjusted(INSET, INSET, -INSET, -INSET)
if area.width() < 6 or area.height() < 6:
return
painter.save()
painter.setRenderHint(painter.RenderHint.Antialiasing)
self._paint_figure(painter, area, self._fig, QColor(color))
painter.restore()
def _paint_figure(self, painter, cell, fig, ink):
# The ball's radius: room for headphones either side and legs below,
# or (asleep) lying full length.
r = min(cell.width() / 3.9, cell.height() / 4.2)
if self.posture == SLEEP:
r = min(r, cell.width() / 4.6, cell.height() / 2.8)
rng = np.random.default_rng(self.step * 31 + fig.index)
wob = max(0.4, r * 0.06)
def j(x, y):
return QPointF(x + rng.uniform(-wob, wob), y + rng.uniform(-wob, wob))
pen = QPen(ink, max(1.0, r * 0.11))
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
painter.setPen(pen)
painter.setBrush(Qt.BrushStyle.NoBrush)
ground = cell.bottom() - pen.widthF()
cx = cell.center().x()
painter.save()
if self.posture == SLEEP:
# Lying on its back, feet to the right: the standing drawing
# turned a quarter (rotate(-90) sends "down" to "right").
head = cx - r * 0.75
painter.translate(head, ground - r * 1.4)
painter.rotate(-90)
self._body(painter, fig, r, 0.0, j, SLEEP)
painter.restore()
self._zzz(painter, head + r * 0.5, ground - r * 3.0, r, fig, j)
return
if self.posture == SIT:
painter.translate(cx, ground - r * 1.1) # the ball on the floor
self._body(painter, fig, r, 0.0, j, SIT)
painter.restore()
return
legs = r * 1.25
dip = self.bob * r * 0.22
painter.translate(cx, ground - legs - r + dip)
self._body(painter, fig, r, dip, j, STAND)
painter.restore()
def _body(self, painter, fig, r, dip, j, posture):
"""The figure drawn around its ball's centre (0, 0), feet at +y."""
asleep = posture == SLEEP
blink = posture == SIT and self.step % BLINK_EVERY == 0
# The fuzzy ball: a wobbly ring plus a few loose hairs.
n = len(fig.radii)
ring = QPainterPath()
for i in range(n + 1):
a = 2 * math.pi * (i % n) / n
p = j(math.cos(a) * r * fig.radii[i % n],
math.sin(a) * r * fig.radii[i % n])
ring.moveTo(p) if i == 0 else ring.lineTo(p)
painter.drawPath(ring)
for a, length in zip(fig.hairs, fig.hair_len):
if abs(math.cos(a)) > 0.8 or math.sin(a) > 0.5:
continue # where the headphone cups and the legs are
painter.drawLine(j(math.cos(a) * r, math.sin(a) * r),
j(math.cos(a) * r * (1 + length),
math.sin(a) * r * (1 + length)))
# Face.
eye_y, eye_x = -r * 0.18, r * 0.32
if asleep or blink:
for s in (-1, 1):
painter.drawLine(j(s * eye_x - r * 0.13, eye_y),
j(s * eye_x + r * 0.13, eye_y))
if asleep:
painter.drawLine(j(-r * 0.12, r * 0.32), j(r * 0.12, r * 0.32))
elif posture == SIT:
if not blink:
dot = max(0.8, r * 0.07)
for s in (-1, 1):
painter.drawEllipse(j(s * eye_x, eye_y), dot, dot)
painter.drawLine(j(-r * 0.18, r * 0.32), j(r * 0.18, r * 0.3))
else:
dot = max(0.8, r * 0.07)
for s in (-1, 1):
c = j(s * eye_x, eye_y)
painter.drawEllipse(c, dot, dot)
smile = QPainterPath(j(-r * 0.3, r * 0.22))
depth = r * (0.5 if self.busy else 0.32)
smile.quadTo(j(0, r * 0.22 + depth), j(r * 0.3, r * 0.22))
painter.drawPath(smile)
# Big headphones: a band over the top, a cup over each side.
band = QPainterPath(j(-r * 1.12, -r * 0.1))
band.cubicTo(j(-r * 1.25, -r * 1.75), j(r * 1.25, -r * 1.75),
j(r * 1.12, -r * 0.1))
painter.drawPath(band)
for s in (-1, 1):
c = j(s * r * 1.08, 0)
painter.drawEllipse(c, r * 0.24, r * 0.42)
# Arms from the shoulders, two sticks each.
if asleep:
pose = LYING
elif posture == SIT:
pose = SITTING
elif self.busy:
pose = DANCE[fig.pose]
else:
pose = HANG
upper, lower = r * 0.75, r * 0.6
for s, (shoulder, bend) in zip((-1, 1), pose):
if posture == STAND and not self.busy:
shoulder += 6 * self.bob # a hanging arm swings with the bob
start = (s * r * 0.92, r * 0.3)
a = math.radians(shoulder)
elbow = (start[0] + s * math.sin(a) * upper,
start[1] + math.cos(a) * upper)
b = math.radians(shoulder + bend)
hand = (elbow[0] + s * math.sin(b) * lower,
elbow[1] + math.cos(b) * lower)
painter.drawPolyline([j(*start), j(*elbow), j(*hand)])
if posture == SIT:
# Splayed out along the floor, feet turned up.
for s in (-1, 1):
hip = (s * r * 0.45, r * 0.85)
knee = (s * r * 1.0, r * 1.08)
foot = (s * r * 1.6, r * 1.08)
painter.drawPolyline([j(*hip), j(*knee), j(*foot),
j(foot[0] + s * r * 0.05, r * 0.78)])
return
# Legs: straight, or bent at the knee by the bob; the feet step
# apart when dancing.
legs = r * 1.25
knee_out = dip * 0.9
spread = r * (0.5 if (self.busy and self.feet) else 0.35)
for s in (-1, 1):
hip = (s * r * 0.35, r * 0.93)
foot_y = r + legs - dip
out = spread + (r * 0.15 if self.busy and self.feet == (s > 0) else 0)
foot = (s * out, foot_y)
knee = ((hip[0] + foot[0]) / 2 + s * knee_out,
(hip[1] + foot_y) / 2)
painter.drawPolyline([j(*hip), j(*knee), j(*foot),
j(foot[0] + s * r * 0.25, foot_y)])
def _zzz(self, painter, x, y, r, fig, j):
"""Little z's rising, a new one every few frames."""
phase = self.step % 12
for k in range(3):
age = (phase / 4 + k) % 3 # 0..3, how far it has risen
size = r * (0.18 + 0.08 * age)
zx = x + age * r * 0.3
zy = y - age * r * 0.4
painter.drawPolyline([j(zx, zy), j(zx + size, zy),
j(zx, zy + size), j(zx + size, zy + size)])