EN
Cloud
R1BBIT · COMMUNITY

Projects

A question from the R1BBIT community

Vector graphics on an oscilloscope from an ESP32‑S3 — no DAC, no beam blanking, and it's all a BASIC script

The S3 has no real DAC, so this uses the two sigma‑delta outputs with a 10 MHz carrier and an RC filter on each pin (1 kΩ series, 10 nF to ground, ~16 kHz corner). That gives a crude 8‑bit DAC per channel: X to channel 1, Y to channel 2, scope in X‑Y mode. 19 figures cycle on it — Lissajous, a rose, Fay's butterfly, a perspective cube, a 5‑band equalizer, text, a clock, a live BTC price and its 24‑hour chart, cartoon outlines, a thumbs‑up and SUBSCRIBE.

The whole thing is a BASIC script running on the board's interpreter, not firmware. About 1700 lines.

No beam blanking changes every design decision. You cannot lift the pen — every jump between two points is drawn on screen. So:

  • Figures are built as a single continuous stroke wherever possible. The star is drawn by taking vertices every other one, so the pen never lifts.
  • The cube is an Euler circuit: all 8 vertices have odd degree, so a non‑repeating path would leave 3 edges stranded and need 3 smears across the body. Duplicating 4 edges that form a perfect matching makes every degree even — 16 segments in one closed stroke, 4 of them twice as bright. Cheaper than 3 smears and a dozen dwell dots.
  • The vector font has one rule: every glyph starts and ends on the baseline. Then the jump to the next letter runs along the bottom of the line and reads as an underscore. Where a letter's shape doesn't allow it (C, S, E, U), the pen retraces what it already drew — brighter stroke, no new line.
  • Internal detail (the equalizer's floor, the thumb's knuckle grooves) is drawn by branching and retracing, not by jumping.

Numbers, measured on the board:

  • one point costs 13.0 µs with the output loop unrolled 8‑way, vs 18.2 µs one point per iteration — the DAC writes are ~9 µs of that, the rest was FOR overhead
  • refresh runs 250–900 Hz depending on the figure; below ~220 Hz the flicker is visible
  • a figure that rebuilds every frame (cube, equalizer) spends 15–30% of its time not drawing

A couple of things that cost me time:

The interpreter holds exactly 32 named constants and silently turns the extras into zero‑valued variables. It does warn, and I was filtering the upload log for errors only.

The cube would go flat at certain angles with a bright vertical streak through it. Not clipping, as I first assumed — measured max excursion was 110 of 127. It was the tumble passing through orientations where two vertices project within 0.9 units of each other: the cube is seen edge‑on and the beam burns a zero‑length edge. Fixed by holding the tilt at 27° and making the second axis an in‑plane rotation, which cannot degenerate.
photo_2026-11-19_19-13-50
photo_2026-11-19_19-13-47
photo_2026-11-19_19-13-44

R1 BASIC
// =====================================================================
//  Oscilloscope in X-Y mode: shapes, volume and text
// =====================================================================
//  The S3 has no real DAC, so DAC1/DAC2 output a sigma-delta
//  modulator, a one-bit stream with a 1 MHz carrier. With an RC filter on the pin
//  this is a rough 8-bit DAC: 0...255 across the full supply swing.
//
//  Wiring on each pin: a 1 kOhm series resistor, a 10 nF capacitor
//  to ground. Cutoff is about 16 kHz — it suppresses the carrier and passes the picture.
//  DAC1 -> X (channel 1), DAC2 -> Y (channel 2), oscilloscope in X-Y,
//  both channels 0.5 V/div, DC coupling.
//
//  How it is computed. The points are NOT computed in the beam loop: the shape is
//  laid out once into an array of ready-made pairs, and the beam then runs that array
//  in a circle. Computing sines on the fly would cost four times as much
//  per point, and above all the traversal would be uneven, and the brightness would drift across
//  the shape.
//
//  Polylines are given by vertices with a pen flag: 0 — jump the beam, 1 —
//  draw a line. After a jump several points are placed in the same spot:
//  the filter cannot step instantly, and without a dwell the start of a stroke
//  would drift, and the jump trace would be brighter than the picture itself.
//
//  Text is drawn not with a separate vertex table for each caption, but with
//  a set of glyphs: the strokes of digits and letters sit in a shared table, and
//  draw_msg lays out any string from it. So "R1BBIT" and
//  the sensor reading go by one path, and a third caption will not need
//  a third table.
// =====================================================================

CONFIG
    FLASH_SIZE 8
    PSRAM_SIZE 8
    DAC1 7
    DAC2 8
    // Sigma-delta carrier. The noise after the filter is set by the ratio of the
    // carrier to the cutoff: the carrier divided by the cutoff is the ripple
    // suppression. At 1 MHz and a 16 kHz filter that is 62 times, i.e. about 50 mV
    // of ripple on a 3.3 V swing. At 10 MHz — 625 times, about 5 mV.
    // The modulator noise floor falls even faster, as frequency to
    // the power of one and a half. The driver limit is 80 MHz, but at such frequencies
    // the trace capacitance rounds the edges and the swing sags.
    DAC_FREQ 10000000
    // Without this directive HOUR()/MINUTE()/SECOND() return UTC, and the clock
    // would run smoothly, but not on local time — impossible to tell by looking.
    // The value is the same as in this board's music script.
    TIMEZONE "UTC-5"
END_CONFIG

// how many milliseconds to hold one shape
CONST SHOWMS = 3000

// ---- COST OF A POINT AND NUMBER OF POINTS ----
//  Measured on the board (a three-second run counting full traversals,
//  96 points in the shape):
//      loop with one point per iteration   18211 ns
//      unrolled by four points             13736 ns
//      unrolled by eight points            13004 ns
//  Two DAC commands are about 9 us, the rest was eaten by FOR
//  bookkeeping. Unrolling divides the overhead by eight and returns a third of the time;
//  beyond eight there is no point, the difference from four is already under a microsecond.
//  ⚠️ These numbers are NOT among the CONSTs, and that is not carelessness: the firmware
//  fits exactly 32 named constants (CONSTDEF_MAX), and the extra ones are
//  dropped and turn into variables with the value zero.
//
//  Going over the limit drops the LAST constants declared. With TXTW and
//  MIDY among the casualties the caption scale became zero and every
//  letter collapsed into a point, while MIDY dragged every figure to the
//  bottom of the screen.
//
//  The firmware does say so, and names the casualty:
//      WARNING: more than 32 CONST values — 'TXTW' ignored
//  It is a WARNING, not an ERROR, so an upload log filtered for errors
//  hides it. Read the whole upload log, not just the error lines, and
//  count the CONSTs before adding one.
//
//  Therefore everything that is computed rarely is written here as numbers right
//  in place: 13004 and 13736 are the cost of a point in unrolled loops, 18211 — in
//  the tail. They are needed once per shape change, in the report line.

//  Default number of points per shape.
//
//  Traversal frequency and curve smoothness pull in different directions: the period equals
//  the number of points times the cost of a point, and the cost of a point after loop unrolling is about
//  13 us. With 36 points it came to 2 kHz, but the circle and the rose degenerated into
//  a polygon — the RC filter rounds corners, it does not complete the arc.
//
//  96 was chosen: the curve reads well, the traversal is about 1.27 ms, i.e. roughly
//  790 Hz. The number is a multiple of eight, so the top unrolling stage
//  fits with no remainder and there is no per-point tail at all — for numbers not
//  a multiple of eight the remainder costs 18.2 us per point and eats
//  part of the gain.
//
//  Tune it like this: fewer — faster and more angular, more — smoother and
//  slower. Stick to multiples of eight: 72, 80, 88, 96, 104, 120.
//  And remember the oscilloscope capture window — it must cover more than
//  one traversal, otherwise part of the shape will not make it into the recording and
//  it will look as if the shape is not fully drawn and drifts.
CONST NPTS = 84

//  Shapes for which thirty-six points are physically too few ask for their own
//  number via ntarget. Cube: twelve edges, a traversal of sixteen
//  segments — at 36 points that is two points per edge. Text: six
//  letters in 256 units of width, a stroke must remain a stroke.
//  Cube. Sixteen segments: at 77 points the step came out 20 units —
//  twice as coarse as for the curves, and the edges on screen fell apart into
//  dashes, although the geometry was right. At 115 the step was 14.4 against
//  8.3 for the circle, and in oscilloscope screenshots the cube lines were noticeably
//  furrier than the other shapes. 140 gives 11.8.
CONST CUBPTS = 140
//  Captions. The numbers were raised together with moving the set to glyphs with two
//  lower ends: retracing over what is already drawn lengthened the contour
//  by about one and a half times, and without adding points the step would have become sparser.
CONST TXTPTS = 265
CONST METPTS = 265
//  Characters need more points than curves: they have a long contour with
//  fine details (teeth, the cap band, the notch between the ears), and at
//  ninety-six points they fell apart into separate dashes.
//  The point count is set per character by name: they have different contour lengths
//  and different vertex counts, and each vertex costs the beam at least one
//  point. Mickey with the face is heavier than Goofy: six pieces and 164 vertices.
// Mickey has fewer points than he could: with the face he already ran at 229 Hz, i.e.
// had only nine hertz of margin, and any motion costs about ten
// percent, so some of his points went to the margin instead: without that
// the sway would have taken him below 220. The step between points grew
// from 5.0 to 5.7 units, which the eye does not catch — unlike flicker.
CONST MICPTS = 200
CONST GOOPTS = 200
// The thumb icon gets more points than the characters: it is bigger than them, and is also outlined
// by two shapes — the palm and the cuff.
// 260, not more: at 300 the measurement gave 223 Hz — right at the flicker
// boundary of 220. The contour of the grown icon is about 885 units, and at 260
// points the step comes to 3.4 units — like Mickey.
CONST THUPTS = 260
//  The clock is rebuilt four times a second, see CLKMS, so it is given as many points
//  as the weather: eight characters of the same length.
// The clock has slightly fewer points than the other captions, and this is a margin on
// frequency: the stroke length depends on which digits are showing — for
// "23:59:59" it is a quarter longer than for "09:05:07", and the number of points
// grows with it. At 265 the clock in some seconds landed exactly on
// the lower bound of 220 Hz.
CONST CLKPTS = 245
//  Clock rebuild interval. A shape lives three seconds, but the second must
//  change on time — otherwise the digits would stand still and jump every three.
//  250 ms: rebuilding the caption costs about 13 ms, i.e. 5% of the time.
// How often to ASK for the time. The rebuild itself is now done not on a
// timer but when the second changes, so polling can be frequent: it
// costs one comparison.
CONST CLKMS = 100

// Dwell after a beam jump, in points, by default. A closed
// shape may ask for less: see hold.
CONST DWELL = 3

// ---- ROTATION ----
// Two periods that are not multiples of each other: the cube turns around Y in five
// seconds and around X in eight. One axis is not enough — the cube then looks like
// a flat rectangle that rocks, not like a solid.
CONST SPINPER = 5000
CONST SPINPER2 = 8000
// How often to recompute a rotating shape. The recompute does not draw, i.e.
// it eats the whole frame, so it runs on a timer, not every traversal.
// 45 ms is 22 positions per second, already smooth to the eye.
CONST SPINMS = 45
// Motion recompute intervals for heavy shapes. The recompute stops
// drawing, and the more points in a shape, the longer the pause: at 300
// points it is 12 ms against 3 at 84. So the interval for captions and characters
// is increased — otherwise they could not hold 220 Hz.
//
// Less often is not always better. RARE pauses are visible as separate jerks, while
// frequent ones merge into an even dimming: the cube is interrupted 22 times a
// second for 11 ms, and that bothers nobody, while the clock was interrupted only
// 2.5 times — and that caught the eye. Hence the choice: no longer than
// needed for the frequency.
CONST TXTMS = 120
CONST TOONMS = 100

// ---- CUBE ----
// The camera is 3.4 half-edges from the center. Closer — the perspective becomes
// a caricature (the near face twice as large as the far one), farther — the cube
// degenerates into an orthographic projection and loses volume.
CONST CDIST = 3.4
// Chosen so that over a full tumble the cube occupies exactly the same
// 0...255 as the other shapes: the far corner gives 128 units.
CONST CSCALE = 216.2

// ---- EQUALIZER ----
// Fewer points than the captions, and the rebuild is rarer — the cost is the same as for
// any shape with a full rebuild: it stops drawing.
// 220 points is about 310 Hz of traversal, a rebuild every 70 ms eats
// a seventh of the time, and about 265 Hz remains — above the boundary of
// 220 beyond which flicker begins.
//
// Fourteen updates a second are enough for the bars: they
// move smoothly rather than jump. More often — and the shape would drop below the boundary.
CONST EQPTS = 220
CONST EQMS = 70

// ---- AXIS GAIN CALIBRATION ----
//  If the circle comes out as an oval, the gain differs between the axes. The cause
//  is always external: either the dividers are built from different parts
//  (a ten percent spread in capacitors gives a different
//  attenuation at the picture frequency), or the oscilloscope channels
//  are set to different V/div.
//
//  How to tune: look at the circle and reduce the gain of THAT
//  axis along which the oval is stretched. 0.86 is the full swing
//  of the shape across the whole field; less — the shape is narrower on that axis.
CONST GX = 0.86
CONST GY = 0.86
// field center: if the shape is not at the center of the screen
CONST MIDX = 128
CONST MIDY = 128

// ---- TEXT ----
// Glyph cell is 12 by 24; the gap between letters is in the same cells.
CONST GGAP = 3
// How many DAC units a string of any length is fitted into. Not 255:
// at the edge of the field the filters of both axes already visibly cut the swing.
CONST TXTW = 230

// Ready-made pairs for the beam. nu and nq are how far the main loop goes
// by eights and fours, computed once per shape.
VAR PX[900], PY[900], np, nu, nq
// Reference copy of a rotating flat shape: the same shape, but without rotation and without
// calibration, and with the center already subtracted. Rebuilding the star from scratch
// twenty-two times a second turned out to be prohibitively expensive —
// the measurement gave 29 ms per rebuild, the traversal dropped from 704 hertz to 246.
VAR QX[900], QY[900]
// Polyline vertices: X, Y and the pen flag. The longest demo shape is
// Mickey with the face, 164 vertices; the caption "23.5C 48%" takes 98.
VAR VX[192], VY[192], VP[192], nv
VAR i, j, k, n, nj, a, r, t0
VAR fig, lx, ly, sx, sy, dx, dy, dd, ns
// ntarget is how many points the CURRENT shape asks for, hold is its dwell
// on jumps, spinms is its recompute interval. All three return to
// defaults in make_fig, so that one shape's request does not leak into the next.
// pvx/pvy is the point a flat shape rotates around. By default it is the
// field center; the hand asks for a point far to the left, and you get an arm
// moving at the elbow rather than a picture jerked in place.
VAR pvx, pvy
VAR ntarget, hold, spin, spinms
VAR spindir, spinper, ramp, rper, pamp, pper, pul, ssprev
VAR ang, ang2, sn, rad, den, nout
VAR ax, bx, ay, by
VAR tr, sweeps

// ---- GLYPH TABLE ----
// A vertex is packed into one number x*1000 + y*10 + pen. One array instead of
// three: the table is written one line per glyph and reads by eye
// as a contour, not as three columns that are easy to get out of sync.
VAR GS[260]
// start, length and width of each glyph
VAR GOFF[25], GCNT[25], GADV[25]
// character code -> glyph number. Unfilled codes give zero, and glyph zero
// is a space, so an unknown character turns into a gap rather than
// garbage on the screen.
VAR GIDX[128]
VAR msg$, nm, m, g, gv, gu, gw, wsum, kx, ky, penx, peny
VAR hh, mi, ss

// ---- CHARACTER CONTOURS ----
// Same trick as with the glyphs: a vertex is packed into x*1000 + y*10 + pen.
// The contours were built and verified in preview (scratchpad/_toon2.py),
// and arrived here already fitted into the 0...255 field — so the code has not
// a single multiplier and not a single fudge in place.
VAR TOON[312], TOFF[3], TCNT[3]

// ---- CUBE: model and traversal ----
VAR CBX[8], CBY[8], CBZ[8], CPX[8], CPY[8]
VAR CBV[17], CBP[17]
// cr/sr — rotation of the finished projection, the cube's second axis of motion.
VAR ca, sa, cb, sb, cr, sr, x1, y1, z1, z2, pq
// ---- EQUALIZER ----
// EQH is the band heights; they LIVE BETWEEN FRAMES, and the smooth
// decay rests on that: the new height is computed from the previous one.
VAR EQH[5], eb, etg, ex0, ex1, ekick
// ---- PIZZA ----
// pof is the spread of the pieces, prt the overall rotation, pb the bisector of a piece,
// pax/pay its vertex, pa1/pa2 the angles of its two radii.
VAR pof, prt, pb, pax, pay, pa1, pa2, pf, pc1, ps1, pc2, ps2

// ---- READINGS ----
// There is no sensor in the demo, the values are set by hand. When a sensor appears,
// only these two lines will need changing: the caption is assembled from them
// anew each time, and does not sit ready-made.
VAR tC = 23.5
VAR hum = 48
// The BTC rate arrives via a web feed. There are no network passwords in CONFIG and none are needed:
// the connection is handled by the firmware, the script only takes the ready response.
//
// Zero means the response has not arrived yet. We keep the last successful
// value in btc, not zero: an empty price looks like a breakage, while the previous one
// looks like a delay, which is what it actually is.
VAR btc = 0
VAR bnew
// Daily price series: one point per hour. Kept between showings —
// if the feed did not respond, we draw the previous series, not zeros. Old data
// is a delay, zeros are a breakage.
VAR CHV[24], chn = 0
VAR cv, cmin, cmax, cspan, ci
VAR t10

GOSUB init_glyphs
GOSUB init_cube
GOSUB init_toon

PRINT "X-Y oscilloscope demo: DAC1=GPIO7 (X), DAC2=GPIO8 (Y)"
PRINT "RC on each pin: 1k series + 10nF to ground"

// Rate feed. Polled once every 30 seconds — no need more often, the carousel
// makes a full circle in 36 anyway. The first load happens immediately, so by
// the time the shape is shown the price is usually already there.
HTTP_GET("btc", "https://api.coinbase.com/v2/prices/BTC-USD/spot", 30)

// Daily chart feed. Once every ten minutes: in that time the daily
// curve does not change noticeably, and CoinGecko has a limit on request
// frequency. The response is about 288 [time, price] pairs at a five-minute step,
// roughly nine kilobytes against a limit of thirty-two.
HTTP_GET("btch", "https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=1", 600)

fig = 0
ang = 0
ang2 = 0
sweeps = 0
GOSUB make_fig
GOSUB report
t0 = MILLIS
tr = MILLIS

// =========================== main loop ================================
//  The beam runs the ready array. Eight points per iteration: the FOR overhead
//  is divided by eight and the cost of a point falls from 18.2 to 13.0 us.
//
//  Three stages, not one. A shape's point count is its own and need not be
//  a multiple of eight, and the remainder cannot be lost — without it the last points
//  would not be output and the contour would not close. A remainder up to four is taken by
//  the second stage at 13.7 us each, and only the last one to three points go
//  one at a time at 18.2. At 36 points that is exactly 1952 Hz against 1910 if
//  the tail is finished off one by one.
//
//  Checks are once per full traversal, not per point: otherwise they would cost
//  as much as the drawing itself.
WHILE 1
    FOR i = 0 TO nu - 8 STEP 8
        DAC1(PX[i])
        DAC2(PY[i])
        DAC1(PX[i + 1])
        DAC2(PY[i + 1])
        DAC1(PX[i + 2])
        DAC2(PY[i + 2])
        DAC1(PX[i + 3])
        DAC2(PY[i + 3])
        DAC1(PX[i + 4])
        DAC2(PY[i + 4])
        DAC1(PX[i + 5])
        DAC2(PY[i + 5])
        DAC1(PX[i + 6])
        DAC2(PY[i + 6])
        DAC1(PX[i + 7])
        DAC2(PY[i + 7])
    NEXT
    FOR i = nu TO nq - 4 STEP 4
        DAC1(PX[i])
        DAC2(PY[i])
        DAC1(PX[i + 1])
        DAC2(PY[i + 1])
        DAC1(PX[i + 2])
        DAC2(PY[i + 2])
        DAC1(PX[i + 3])
        DAC2(PY[i + 3])
    NEXT
    FOR i = nq TO np - 1
        DAC1(PX[i])
        DAC2(PY[i])
    NEXT
    sweeps = sweeps + 1
    IF spin > 0 THEN GOSUB turn
    IF MILLIS - t0 > SHOWMS THEN GOSUB next_fig
WEND

next_fig:
    GOSUB measured
    fig = (fig + 1) % 19
    t0 = MILLIS
    sweeps = 0
    GOSUB make_fig
    GOSUB report
RETURN

// The frequency by point count is computed: eights at 13.0 us, fours
// at 13.7, the tail at 18.2. It sees neither the rotation work nor the checks
// at the end of the traversal (which cost about 30 us). The second line measures
// traversals by the clock: that is the one to compare with the computed one.
report:
    PRINT "figure " + fig + ": " + np + " points, " + ROUND(1000000000 / (nu * 13004 + (nq - nu) * 13736 + (np - nq) * 18211)) + " Hz refresh"
RETURN

measured:
    PRINT "  measured " + ROUND(sweeps * 1000 / (MILLIS - t0)) + " Hz over " + sweeps + " sweeps"
RETURN

// ---------------------------------------------------------------------
//  Rotation
// ---------------------------------------------------------------------
turn:
    IF MILLIS - tr > spinms THEN GOSUB respin
RETURN

// Angles are taken from the clock, not as an increment to the previous ones. Two reasons:
// a missed interval does not lag (the shape is where it should be by
// time), and the rotation is always computed from the untouched source, so
// rounding error does not accumulate — otherwise the shape would drift within a minute.
// Three independent motions, each with its own switch. A shape
// enables what suits it: a curve — rotation, the heart —
// pulsation, a character — sway. Rotating a caption or Mickey
// would be absurd.
//
//   spindir  direction and presence of rotation: 0 — none, 1 and -1 — with and against
//   spinper  period of a full revolution, ms
//   ramp     sway amplitude in radians (0 — none)
//   rper     sway period, ms
//   pamp     pulsation amplitude as a fraction of size (0 — none)
//   pper     pulsation period, ms
clock:
    ang = 0
    IF spindir <> 0 THEN ang = spindir * (MILLIS % spinper) * 6.2832 / spinper
    IF ramp > 0 THEN ang = ang + ramp * SIN((MILLIS % rper) * 6.2832 / rper)
    pul = 1
    IF pamp > 0 THEN pul = 1 + pamp * SIN((MILLIS % pper) * 6.2832 / pper)
RETURN

// spin = 1 — a flat shape, rotating the reference copy is enough.
// spin = 2 — the cube: its form changes with the angle (perspective), the reference copy
// will not help, a full rebuild is needed.
// clock is called only by those who need it. The cube does not need it at all —
// it computes angles itself — and two extra calls on every rebuild
// cost it fifty hertz: it is rebuilt twenty-two times a
// second, and everything stuck to the rebuild is multiplied by that number.
respin:
    tr = MILLIS
    IF spin = 1 THEN GOSUB clock
    IF spin = 1 THEN GOSUB place
    IF spin = 2 THEN GOSUB make_fig
    IF spin = 3 THEN GOSUB tick3
RETURN

// spin = 3 — a shape with changing CONTENT (the clock). We rebuild it
// not on a timer but ON AN EVENT: only when the second has changed.
//
// Previously the clock was rebuilt every 400 ms, i.e. two and a half
// times a second, but changed once a second — one and a half rebuilds out of
// two and a half were superfluous. Each stops drawing for
// about twenty milliseconds, and the owner saw this as jerking at exactly
// the same frequency. Now the gap happens once a second AND exactly
// when the digit changes anyway: the digit change masks it.
// At the same time the caption stopped lagging — before, by up to 400 ms.
//
// Motion (sway) goes on as usual: place is cheap and
// works from the reference copy, it needs no rebuild.
tick3:
    IF SECOND() <> ssprev THEN GOSUB make_fig
    GOSUB clock
    GOSUB place
RETURN

// ---------------------------------------------------------------------
//  Building a shape: either a parametric curve directly into PX/PY, or
//  a polyline through vertices.
// ---------------------------------------------------------------------
make_fig:
    np = 0
    ntarget = NPTS
    hold = DWELL
    spin = 0
    spinms = SPINMS
    pvx = 128
    pvy = 128
    // Animation defaults: nothing moves until the shape asks.
    spindir = 0
    spinper = SPINPER
    ramp = 0
    rper = 3000
    pamp = 0
    pper = 1000
    IF fig = 0 THEN GOSUB fig_star
    IF fig = 1 THEN GOSUB fig_butterfly
    IF fig = 2 THEN GOSUB fig_cube
    IF fig = 3 THEN GOSUB fig_text
    IF fig = 4 THEN GOSUB fig_heart
    IF fig = 5 THEN GOSUB fig_esp32
    IF fig = 6 THEN GOSUB fig_clock
    IF fig = 7 THEN GOSUB fig_meter
    IF fig = 8 THEN GOSUB fig_btc
    IF fig = 9 THEN GOSUB fig_chart
    IF fig = 10 THEN GOSUB fig_mickey
    IF fig = 11 THEN GOSUB fig_thumb
    IF fig = 12 THEN GOSUB fig_subscribe
    IF fig = 13 THEN GOSUB fig_pizza
    IF fig = 14 THEN GOSUB fig_lissajous
    IF fig = 15 THEN GOSUB fig_rose
    IF fig = 16 THEN GOSUB fig_spiral
    IF fig = 17 THEN GOSUB fig_eq
    IF fig = 18 THEN GOSUB fig_goofy
    // The reference copy is taken from the CANONICAL shape, before calibration: the rotation
    // must happen in canonical coordinates, otherwise it would be mixed
    // with the axis gain correction.
    // The angle and size are computed AFTER assembly, not before: the shape
    // sets its motion parameters in its own subroutine, and before that
    // there was simply nowhere to get them. With the computation before assembly the first frame came out
    // static and the shape jumped into place on the next recompute.
    IF spin = 1 THEN GOSUB clock
    IF spin = 3 THEN GOSUB clock
    IF spin = 1 THEN GOSUB keep
    IF spin = 3 THEN GOSUB keep
    IF spin = 1 THEN GOSUB place
    IF spin = 3 THEN GOSUB place
    // The cube applies the axis gain directly in the projection, no need a second time.
    IF spin = 0 THEN GOSUB calib
    // How far the main loop goes by eights and fours. Computed
    // here, once per shape: in the beam it would be two FLOORs and two
    // multiplications on every traversal.
    nu = 8 * FLOOR(np / 8)
    nq = nu + 4 * FLOOR((np - nu) / 4)
RETURN

// ---------------------------------------------------------------------
//  Pizza: four pieces fly apart and converge, and all of it rotates
// ---------------------------------------------------------------------
// A circle cut into four 90-degree sectors. Each piece is a
// closed shape: from the vertex at the center out along the radius, an arc,
// back along the second radius to the vertex.
//
// Spread: a piece moves away along its bisector by pof, and pof goes
// as a sine from zero to thirty. At zero the pieces converge into a whole pizza.
//
// TRANSITIONS BETWEEN PIECES. The pen is led THROUGH THE VERTICES: a whole piece,
// a transition from its vertex to the vertex of the next. When the pizza is folded,
// all four vertices lie at the center and the transitions have zero length — there are none
// at all. At maximum spread the vertices of neighboring pieces are separated by
// pof*sqrt(2), that is 42 units at radius 99 — half the radius, and
// on screen they hide in the cross of converged radii.
//
// The spread is deliberately no larger: the farther the pieces, the longer the transitions, and
// at fifty units they would become spokes across the picture.
//
// Rotation is built straight into the rebuild, not left to place: the spread
// changes the shape itself, it cannot be made a reference copy, a rebuild is needed
// anyway — and there the angle costs one addition, whereas place is
// an extra pass over all points.
fig_pizza:
    spin = 2
    pof = 30 * (0.5 + 0.5 * SIN((MILLIS % 3000) * 6.2832 / 3000))
    prt = (MILLIS % 7000) * 6.2832 / 7000
    np = 0
    FOR k = 0 TO 3
        pb = prt + k * 1.5708 + 0.7854
        pax = MIDX + pof * COS(pb) * GX
        pay = MIDY + pof * SIN(pb) * GY
        pa1 = pb - 0.7854
        pa2 = pb + 0.7854
        // The sine and cosine of the radii are computed ONCE per piece, not
        // at each point: the angle along a radius does not change, and in the loops
        // below that would be thirty-six extra calls per piece.
        pc1 = COS(pa1) * GX
        ps1 = SIN(pa1) * GY
        pc2 = COS(pa2) * GX
        ps2 = SIN(pa2) * GY
        // vertex: the piece starts at it and ends at it,
        // so the transition to the next goes vertex-to-vertex
        PX[np] = pax
        PY[np] = pay
        np = np + 1
        // radius outward
        FOR i = 1 TO 9
            pf = 115 * i / 9
            PX[np] = pax + pf * pc1
            PY[np] = pay + pf * ps1
            np = np + 1
        NEXT
        // 90-degree arc
        FOR i = 1 TO 14
            a = pa1 + 1.5708 * i / 14
            PX[np] = pax + 115 * COS(a) * GX
            PY[np] = pay + 115 * SIN(a) * GY
            np = np + 1
        NEXT
        // second radius back; the last point is the vertex again
        FOR i = 1 TO 9
            pf = 115 * (9 - i) / 9
            PX[np] = pax + pf * pc2
            PY[np] = pay + pf * ps2
            np = np + 1
        NEXT
    NEXT
RETURN

// Circle. Pizza took its place in the carousel, but the shape itself
// was kept: it is a test circle that immediately shows whether
// the axis gains match. The folded pizza shows the same thing, but if
// a clean check is needed — it is enough to give it a number back in
// make_fig and raise the modulus in next_fig.
//
// The circle is given breathing, not rotation: a rotated circle
// looks exactly the same as an unrotated one, and the motion would vanish.
fig_circle:
    spin = 1
    pamp = 0.12
    pper = 2600
    FOR i = 0 TO ntarget - 1
        a = i * 6.2832 / ntarget
        PX[i] = 128 + 128 * COS(a)
        PY[i] = 128 + 128 * SIN(a)
    NEXT
    np = ntarget
RETURN

// A three-to-two Lissajous figure — what X-Y mode was invented for.
fig_lissajous:
    spin = 1
    spindir = -1
    spinper = 4500
    FOR i = 0 TO ntarget - 1
        a = i * 6.2832 / ntarget
        // Amplitude 104, not 128: the shape fills the whole square of the field, and its
        // CORNERS are 181 units from the center — on rotation they
        // stuck out past the edge (measured: -20 and 276 against the allowed 0...255).
        // What rotates is not the bounding box but the circumscribed circle, and the amplitude follows it.
        PX[i] = 128 + 104 * COS(a * 3)
        PY[i] = 128 + 104 * SIN(a * 2)
    NEXT
    np = ntarget
RETURN

// Heart x = sin³t. One factor for both axes (8 at the original curve
// swing of 32 by 29), otherwise the heart comes out stretched: fitting each
// axis to the field separately means losing the proportions. The shift of 2.5 in Y is
// the center of the curve swing, which is itself not at zero.
// The heart does not rotate but pulses: the size goes as a sine with a period of
// 900 ms, that is about 67 beats per minute. The amplitude 0.14 was chosen by the edge
// of the field — at 0.16 the shape at its peak already hit 255.
fig_heart:
    spin = 1
    pamp = 0.14
    pper = 900
    FOR i = 0 TO ntarget - 1
        a = i * 6.2832 / ntarget
        sn = SIN(a)
        PX[i] = 128 + 128 * sn * sn * sn
        PY[i] = 128 + 8 * (13 * COS(a) - 5 * COS(2 * a) - 2 * COS(3 * a) - COS(4 * a) + 2.5)
    NEXT
    np = ntarget
RETURN


RETURN

// Rose r = cos(3t). Three petals, not eight: at forty points there are
// thirteen points per petal and it remains a curve, whereas
// an eight-petal rose would have five each — it would come out a tangle.
// The angle is shifted by a quarter turn so that a petal points up, and
// the shape center is lowered by 32: the rose by itself hangs above the middle.
fig_rose:
    spin = 1
    spindir = -1
    spinper = 5500
    FOR i = 0 TO ntarget - 1
        a = i * 3.1416 / ntarget
        rad = 128 * COS(3 * a)
        PX[i] = 128 + rad * COS(a + 1.5708)
        PY[i] = 96 + rad * SIN(a + 1.5708)
    NEXT
    np = ntarget
RETURN

// Fay's butterfly r = e^sin(t) - 2cos(4t). The exponential gives it the asymmet-
// rical wings: without it you get an even four-petal rosette.
// The factor 44 and the shift of the X center 29 to the left are fitted to the swing
// of the curve itself — it is not symmetric about zero.
fig_butterfly:
    spin = 1
    spindir = 1
    spinper = 8000
    FOR i = 0 TO ntarget - 1
        a = i * 6.2832 / ntarget
        // Factor 40 instead of 44 and shift 102 instead of 99 — for the same
        // reason as for the Lissajous: on rotation the far wing point
        // went 158 units from the center, while 147 fits.
        rad = 40 * (EXP(SIN(a)) - 2 * COS(4 * a))
        PX[i] = 102 + rad * SIN(a)
        PY[i] = 128 - rad * COS(a)
    NEXT
    np = ntarget
RETURN

// Archimedean spiral, two and a half turns. The radius and angle go by the
// SQUARE ROOT of the path fraction, not by the fraction itself: for an Archimedean spiral the arc
// length grows as the square of the angle, and with a uniform angle the outer turns
// would become polygons and the center a stuck-together lump.
//
// The last seventh of the points is the return to the center along the radius. It is
// drawn on purpose: leave it to a jump, and the filter still would not
// leap across the field in one point — you would get the same trace, only
// as a bright smear with uneven brightness.
// The spiral spins faster than the others and in the other direction: it has a
// "beginning" at the center, and in rotation it reads as screwing in.
fig_spiral:
    spin = 1
    spindir = 1
    spinper = 3500
    nout = ROUND(ntarget * 0.86)
    FOR i = 0 TO nout - 1
        r = SQRT(i / nout)
        rad = 128 * r
        a = 15.708 * r
        PX[i] = 128 + rad * COS(a)
        PY[i] = 128 + rad * SIN(a)
    NEXT
    FOR i = nout TO ntarget - 1
        rad = 128 * (ntarget - 1 - i) / (ntarget - nout)
        PX[i] = 128 - rad
        PY[i] = 128
    NEXT
    np = ntarget
RETURN


// Five-pointed star in one continuous line: the vertices are taken every
// other one, so the pen is never lifted and there are no jump traces.
// spin = 1 — this shape rotates. The flag works for any flat
// shape: it is enough to raise it in the builder, make_fig does
// the rest.
//
// hold = 1 — because the shape is closed: the last vertex coincides with
// the first, and the "jump" to the start has zero length. A full dwell
// put extra points into this vertex, and on the rotating star they
// read as a bright dot running around in a circle.
fig_star:
    spin = 1
    spindir = 1
    spinper = SPINPER
    hold = 1
    nv = 6
    FOR i = 0 TO 5
        a = (i * 2) * 6.2832 / 5 - 1.5708
        VX[i] = 128 + 128 * COS(a)
        VY[i] = 128 + 128 * SIN(a)
        VP[i] = 1
    NEXT
    VP[0] = 0
    GOSUB walk
RETURN

// The little house — the same "draw it without lifting your hand" task. The traversal was not chosen
// by eye: for a square with two diagonals and a roof only two base
// corners have odd degree, and the path must start at one of
// them and end at the other. Hence the order: bottom left — top left —
// ridge — top right — top left — bottom right — top right — bottom
// left — bottom right. Not a single line twice, not a single jump.
// This shape is no longer in the carousel — removed on request. The traversal
// itself was kept: it is a verified Eulerian path in which no line
// is drawn twice and there is not a single beam jump, and it is a pity to lose it
// over one dispatcher line. To bring it back, it is enough to
// add its number in make_fig and raise the modulus in next_fig.
fig_house:
    VX[0] = 50
    VY[0] = 30
    VP[0] = 0
    VX[1] = 50
    VY[1] = 186
    VP[1] = 1
    VX[2] = 128
    VY[2] = 230
    VP[2] = 1
    VX[3] = 206
    VY[3] = 186
    VP[3] = 1
    VX[4] = 50
    VY[4] = 186
    VP[4] = 1
    VX[5] = 206
    VY[5] = 30
    VP[5] = 1
    VX[6] = 206
    VY[6] = 186
    VP[6] = 1
    VX[7] = 50
    VY[7] = 30
    VP[7] = 1
    VX[8] = 206
    VY[8] = 30
    VP[8] = 1
    nv = 9
    GOSUB walk
RETURN

// ---------------------------------------------------------------------
//  Cube
// ---------------------------------------------------------------------
// Eight vertices of the unit cube and the traversal of its edges.
//
// The traversal is chosen so that there are NO JUMPS AT ALL. In a cube all eight
// vertices have degree three, i.e. odd, and a continuous walk without
// repeats can take at most nine edges out of twelve —
// the remaining three would have to be drawn separately, and they share no
// endpoints, so that is three jumps across the body of the cube. On screen this is
// three smeared diagonals over the picture plus twelve bright dwell
// points.
//
// So a closed traversal with repeats is taken: if four edges forming a
// perfect matching are duplicated, all degrees become
// even and an Eulerian CYCLE appears — sixteen segments in one walk,
// ending at the start. The duplicated ones are 0-1, 2-3, 5-6 and 7-4: they are spread across
// both faces and two directions, so the doubled brightness does not
// gather into one band. Four edges are brighter than the rest — a price
// noticeably smaller than three smears and a dozen points.
init_cube:
    CBX[0-7] = {-1, 1, 1, -1, -1, 1, 1, -1}
    CBY[0-7] = {-1, -1, 1, 1, -1, -1, 1, 1}
    CBZ[0-7] = {-1, -1, -1, -1, 1, 1, 1, 1}
    CBV[0-16] = {0, 1, 2, 3, 0, 4, 5, 6, 7, 4, 7, 3, 2, 6, 5, 1, 0}
    CBP[0-16] = {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
RETURN

// Rotation around Y, then around X, then perspective. Two rotations, not
// one: around a single axis the cube goes round in a circle with the same
// sweep and reads as a flat frame that rocks.
//
// Perspective, not orthography: the divisor (CDIST + z) makes the near
// face larger than the far one, and only by this does the eye understand which face is
// nearer. An orthographic cube is ambiguous — it turns itself inside
// out, like a Necker cube.
//
// The axis gains GX/GY are applied directly in the projection. This is exactly the calib
// done three lines earlier: the vertices come out already in screen
// coordinates, walk puts intermediate points between them linearly, and
// linear interpolation commutes with an affine calibration. So
// make_fig does not call calib for the cube — there is nothing to squeeze a second time.
fig_cube:
    spin = 2
    ntarget = CUBPTS
    hold = 1
    // The cube computes its own angles rather than taking the common ang: it rotates
    // about two axes with different periods, and that does not fit the common mechanism of flat
    // shapes (one axis, rotating the reference copy).
    ang = (MILLIS % SPINPER) * 6.2832 / SPINPER
    ang2 = (MILLIS % SPINPER2) * 6.2832 / SPINPER2
    sa = SIN(ang)
    ca = COS(ang)
    // The tilt is CONSTANT. Rotating the cube about this axis is not allowed: it passes
    // through the corners where two vertices converge to 0.9 units — it is seen almost
    // edge-on, reads as a flat little house, and the beam burns an edge of zero length
    // as a bright line. Computed over all corners and confirmed on screen.
    // The safe band is only 0.40…0.55, the nod in it is almost invisible.
    //
    // 0.475 rad (27°) is the calmest tilt: over all angles the nearest
    // vertices are 30 units apart. The sine and cosine are written in as numbers:
    // the rebuild runs twenty-two times a second, and there is no point
    // computing them anew each time.
    sb = 0.4573
    cb = 0.8893
    // The second axis of motion is a rotation of the FINISHED projection about the middle
    // of the field. There is nothing to collapse here: it is a rigid rotation of the picture, it does not
    // change distances between vertices. Together with the rotation about
    // the vertical the cube looks like it is tumbling.
    cr = COS(ang2)
    sr = SIN(ang2)
    FOR i = 0 TO 7
        x1 = CBX[i] * ca + CBZ[i] * sa
        z1 = CBZ[i] * ca - CBX[i] * sa
        y1 = CBY[i] * cb - z1 * sb
        z2 = CBY[i] * sb + z1 * cb
        pq = CSCALE / (CDIST + z2)
        // The picture rotation goes BEFORE axis calibration: the gains GX and GY
        // correct the differing gain of the physical axes, they do not
        // rotate with the shape.
        dx = x1 * pq
        dy = y1 * pq
        CPX[i] = MIDX + (dx * cr - dy * sr) * GX
        CPY[i] = MIDY + (dy * cr + dx * sr) * GY
    NEXT
    FOR j = 0 TO 16
        g = CBV[j]
        VX[j] = CPX[g]
        VY[j] = CPY[g]
        VP[j] = CBP[j]
    NEXT
    nv = 17
    GOSUB walk
RETURN

// ---------------------------------------------------------------------
//  Equalizer
// ---------------------------------------------------------------------
// Five bars outlined with ONE continuous line: the base
// right to left in full, then left to right across the bars — up, along
// the top, down, along the floor to the next, — and a return to the start. Five
// separate rectangles would cost five jumps, and there is no beam blanking,
// so lines would run across the picture.
//
// With such a traversal the base is passed twice and comes out brighter than the
// bars. For an equalizer this is fitting: you can see the floor they
// grow from. It sticks out eight units wider than the outer bars — otherwise
// the first vertex of the traversal would coincide with the left edge of the first bar, and an
// extra pair of points would land there as a bright spot.
//
// There is deliberately no spark on top (a hanging peak marker): each marker is
// a separate short stroke, i.e. a jump, and five of them would spoil the
// picture more than they would decorate it.
//
// The script does not hear sound, the bars are drawn. So it does not look like
// a running wave, each band has its own pair of incommensurate periods — no
// single frame repeats exactly. On top of this a common "kick" every
// half second, which hits the low bands harder: without it the motion
// read as swaying, not as music.
//
// But what makes the picture look like an instrument is something else — DIFFERENT speed up and
// down: the rise is instant, the fall is smooth. A real equalizer
// does exactly this, and the eye recognizes precisely that.
fig_eq:
    spin = 2
    ntarget = EQPTS
    spinms = EQMS
    hold = 1
    // Kick: a sawtooth decaying over half a second. The low bands get
    // more — the energy of the kick drum and bass is exactly there.
    ekick = 1 - (MILLIS % 500) / 500
    // The base in full, right to left. It also closes the contour, so the
    // jump to the start has zero length and hold = 1.
    VX[0] = 244
    VY[0] = 30
    VP[0] = 0
    VX[1] = 12
    VY[1] = 30
    VP[1] = 1
    nv = 2
    FOR eb = 0 TO 4
        // Two incommensurate periods per band, 1.6-3.0 and 2.5-5.3 s, with
        // a spread by band number. The angle is taken via the remainder, as with
        // all motions in the script: this way it does not grow without bound and at
        // the period seam it does not jump.
        ex0 = 1600 + eb * 340
        ex1 = 2500 + eb * 560
        etg = 0.35 + 0.35 * SIN((MILLIS % ex0) * 6.2832 / ex0) + 0.3 * SIN((MILLIS % ex1) * 6.2832 / ex1)
        etg = 20 + 150 * etg + 60 * ekick * (1 - eb * 0.18)
        IF etg > 170 THEN etg = 170
        IF etg < 6 THEN etg = 6
        // Up instantly, down smoothly — this is what everything rests on.
        IF etg >= EQH[eb] THEN EQH[eb] = etg
        IF etg < EQH[eb] THEN EQH[eb] = EQH[eb] * 0.82 + etg * 0.18
        ex0 = 20 + eb * 46
        ex1 = ex0 + 32
        VX[nv] = ex0
        VY[nv] = 30
        VP[nv] = 1
        nv = nv + 1
        VX[nv] = ex0
        VY[nv] = 30 + EQH[eb]
        VP[nv] = 1
        nv = nv + 1
        VX[nv] = ex1
        VY[nv] = 30 + EQH[eb]
        VP[nv] = 1
        nv = nv + 1
        VX[nv] = ex1
        VY[nv] = 30
        VP[nv] = 1
        nv = nv + 1
    NEXT
    VX[nv] = 244
    VY[nv] = 30
    VP[nv] = 1
    nv = nv + 1
    GOSUB walk
RETURN


// ---------------------------------------------------------------------
//  Text
// ---------------------------------------------------------------------
// Rotation is contraindicated for captions — text must be readable. So
// they are given the most restrained motion: a sway of less than two
// degrees and a slow breathing of five percent in size over seven
// seconds. The letters stay in place and upright.
fig_text:
    ntarget = TXTPTS
    GOSUB txt_move
    msg$ = "R1BBIT"
    GOSUB draw_msg
RETURN

// Common motion setup for all captions: one for all five, so that
// they move the same way and are tuned in one place.
txt_move:
    spin = 1
    spinms = TXTMS
    ramp = 0.03
    rper = 5000
    pamp = 0.05
    pper = 7000
RETURN

// The ESP32 caption. It used to say "r/ESP32" — the name of a Reddit
// section — and for the sake of its prefix glyphs of lowercase "r" and the
// slash were added to the set. They stayed there: it is a font, and throwing letters
// out of it for a couple of dozen bytes would mean renumbering the whole table.
fig_esp32:
    ntarget = TXTPTS
    GOSUB txt_move
    msg$ = "ESP32"
    GOSUB draw_msg
RETURN

// A clock with seconds. spin = 3 is the flag "rebuild on a timer, without
// rotating": the shape holds for three seconds, and the second must change
// on time, otherwise the digits stand still and jump by three at once.
//
// Leading zeros are appended by hand: concatenating a number with a string gives
// "9", not "09", and the caption would jerk in width every time the
// hour or minute crosses ten — draw_msg picks the scale
// by string length.
fig_clock:
    ntarget = CLKPTS
    GOSUB txt_move
    // spin = 3 on top of the common caption motion: the sway goes as for
    // everyone, but in addition the clock is rebuilt when the second changes.
    spin = 3
    spinms = CLKMS
    hh = HOUR()
    mi = MINUTE()
    ss = SECOND()
    msg$ = ""
    IF hh < 10 THEN msg$ = "0"
    msg$ = msg$ + hh + ":"
    IF mi < 10 THEN msg$ = msg$ + "0"
    msg$ = msg$ + mi + ":"
    IF ss < 10 THEN msg$ = msg$ + "0"
    msg$ = msg$ + ss
    // Remember which second is already drawn: tick3 uses it to decide
    // whether a rebuild is needed.
    ssprev = ss
    GOSUB draw_msg
RETURN

// ---------------------------------------------------------------------
//  Characters
// ---------------------------------------------------------------------
// Mickey — a silhouette of three circles, outlined along the OUTER boundary of
// their union with one continuous line. Three separate circles
// would cost two extra jumps and give extra arcs inside the
// silhouette, whereas this way there is not a single jump except the starting one.
//
// The arc boundaries are not by eye: for circles of radii R and r with centers at
// distance d the intersection points are seen from the head center at the angle
// ±acos((d²+R²-r²)/(2dR)), and from the ear center at ±acos((d²+r²-R²)/(2dr)).
// There is no ACOS in the language, so the angles were computed when building the contour.
//
// Face: two tall oval eyes, a wide oval muzzle, a nose on it and
// a mouth as an arc. An inner detail can only be tied to the contour
// by a jump, so what matters is not the number of jumps but their LENGTH: a short one
// inside the face is almost invisible, a long diagonal across the picture is seen
// at once. The chain is chosen by length: contour -> mouth -> nose -> left
// eye -> right eye -> muzzle, and the frame closure returns the pen to the
// start of the contour. The longest transition is 48 units of 256, the total 174.
//
// The key to the whole layout is the muzzle. Its oval passes five
// units under the right eye at the top, and seventeen from the circle of
// the head at the right, so both the entry into the face and the return to the contour are almost free.
// It is traced as a full circle and a RETURN along itself to the right point:
// the repeated pass only makes the arc brighter, but the exit is carried
// where it is needed.
//
// hold = 1 — the contour is closed, and the "jump" to the start has zero length.
fig_mickey:
    ntarget = MICPTS
    GOSUB toon_move
    hold = 1
    g = 0
    GOSUB draw_toon
RETURN

// Characters get a light sway: 0.12 radian is seven degrees
// there and back in three seconds. A full turn here would be absurd:
// a head is not a wheel.
toon_move:
    spin = 1
    spinms = TOONMS
    ramp = 0.12
    rper = 3000
RETURN


RETURN

// Goofy: a hat with flat wide brims, a round skull, a long
// drooping muzzle with a ball nose, a hanging ear — and TWO DIFFERENT MASSES
// at the bottom of the head instead of one.
//
// The upper mass is the muzzle itself; its bottom is the line of the upper lip, and from it
// two front teeth hang down. The lower one is the jaw: rounded, it sits UNDER the
// muzzle and behind it (the chin at 62 in X against 20 for the nose), and it goes down
// noticeably below the teeth. Between the lip and the upper edge of the jaw
// a GAP is left — the mouth line, widening toward the front.
//
// Earlier this was one line with little teeth on it: the jaw as a part of
// the head did not exist, and the bite did not read.
//
// At the back the jaw passes straight into the neck and on into the skull, so it
// entered the common silhouette traversal and cost not a single jump: Goofy
// still has two of them, both 22 units.
// The "thumbs up" icon, 180 by 162 field units. The only shape
// that rotates NOT about the field middle: the pivot is moved
// far BEYOND the left edge, two icon widths away, and a swing of 0.11 radian
// raises and lowers it by about ±40 units. The result is the motion of an arm
// at the elbow.
//
// It cannot be made bigger: the lift equals twice the width times the angle, so
// the bigger the icon, the more it is thrown about. At 240 units there would be
// no room left for the swing at all — the icon would stand still.
//
// It is outside the field because there is no reason to keep it inside — there is nothing to draw around
// it — and while it was inside, the icon had to be made half
// the size so that it would not stick out at the swing.
//
// The swing is larger than for the characters (0.12 there), and the period is shorter: this is not
// a sway for liveliness, it is the gesture itself — "give a thumbs up".
fig_thumb:
    ntarget = THUPTS
    spin = 1
    spinms = TOONMS
    ramp = 0.11
    rper = 1800
    pvx = -232
    pvy = 128
    hold = 1
    g = 2
    GOSUB draw_toon
RETURN

// Subscribe — right after the thumbs up: first the like, then SUBSCRIBE.
// Nine characters, and the layout picks the scale for the field width itself.
fig_subscribe:
    // Fewer points than the other captions: nine characters, and in U, S, C
    // and E the sides are traversed twice, so with the common TXTPTS it came to
    // 331 points and 231 Hz by calculation — below the flicker boundary after
    // overhead. 230 gives about 290 points and 245 Hz.
    ntarget = 230
    GOSUB txt_move
    msg$ = "SUBSCRIBE"
    GOSUB draw_msg
RETURN

fig_goofy:
    ntarget = GOOPTS
    GOSUB toon_move
    g = 1
    GOSUB draw_toon
RETURN

// Unpacking a character contour into polyline vertices. Exactly the same trick
// as draw_msg with glyphs, only without scale: the coordinates are already
// fitted to the field at build time.
draw_toon:
    nv = 0
    FOR j = TOFF[g] TO TOFF[g] + TCNT[g] - 1
        gv = TOON[j]
        gu = FLOOR(gv / 10000)
        gv = gv - gu * 10000
        gw = FLOOR(gv / 10)
        VX[nv] = gu
        VY[nv] = gw
        VP[nv] = gv - gw * 10
        nv = nv + 1
    NEXT
    GOSUB walk
RETURN

// The readings are assembled into a string anew each time — so that swapping in
// a real sensor comes down to assigning tC and hum.
//
// The fractional part is taken via tenths as an integer, not by
// subtracting the integer part: at 23.95 subtraction would give "23.10",
// because rounding the tenths would roll over ten. We compute the tenths
// once and split them into the integer part and the remainder.
fig_meter:
    ntarget = METPTS
    GOSUB txt_move
    t10 = ROUND(tC * 10)
    msg$ = "" + FLOOR(t10 / 10) + "." + (t10 - FLOOR(t10 / 10) * 10) + "C " + hum + "%"
    GOSUB draw_msg
RETURN

fig_btc:
    ntarget = METPTS
    GOSUB txt_move
    
    JSON_GET("btc", "data.amount", bnew)
    IF bnew > 0 THEN btc = ROUND(bnew)
    msg$ = "BTC"
    IF btc > 0 THEN msg$ = "BTC " + btc
    GOSUB draw_msg
RETURN


fig_chart:
    ntarget = 170
    GOSUB txt_move
    GOSUB chart_read
    IF chn > 1 THEN GOSUB chart_plot
    IF chn < 2 THEN GOSUB chart_wait
RETURN

chart_read:
    JSON_GET("btch", "prices[0][1]", cv)
    IF cv > 0 THEN GOSUB chart_fill
RETURN

// We take every twelfth pair: the response step is five minutes, so after
// twelve it is an hour. The number of pairs in the response is not guaranteed, so we go
// to the first zero and draw as many as were actually read.
chart_fill:
    chn = 0
    FOR i = 0 TO 23
        JSON_GET("btch", "prices[" + (i * 12) + "][1]", cv)
        IF cv <= 0 THEN BREAK
        CHV[i] = cv
        chn = i + 1
    NEXT
    PRINT "  chart: " + chn + " prices from feed"
RETURN


chart_plot:
    // Scale by the series MINIMUM AND MAXIMUM, not from zero: the daily
    // swing of bitcoin is two to three percent, and from zero the chart would degenerate
    // into a straight line.
    cmin = CHV[0]
    cmax = CHV[0]
    FOR i = 1 TO chn - 1
        IF CHV[i] < cmin THEN cmin = CHV[i]
        IF CHV[i] > cmax THEN cmax = CHV[i]
    NEXT
    cspan = cmax - cmin
    IF cspan < 1 THEN cspan = 1
    VX[0] = 10
    VY[0] = 28
    VP[0] = 0
    VX[1] = 246
    VY[1] = 28
    VP[1] = 1
    nv = 2
    FOR i = 0 TO chn - 1
        ci = chn - 1 - i
        VX[nv] = 10 + 236 * ci / (chn - 1)
        // The series is fitted into 48...218, and the bottom line runs at 28: without this
        // gap the series minimum would lie exactly on it and merge.
        VY[nv] = 48 + 170 * (CHV[ci] - cmin) / cspan
        VP[nv] = 1
        nv = nv + 1
    NEXT
    VX[nv] = 10
    VY[nv] = 28
    VP[nv] = 1
    nv = nv + 1
    GOSUB walk
RETURN

// There is no feed yet. A flat line at zero must not be drawn — it looks
// like a breakage, not like "data has not arrived". So one honest
// line in the middle of the field.
chart_wait:
    VX[0] = 10
    VY[0] = 128
    VP[0] = 0
    VX[1] = 246
    VY[1] = 128
    VP[1] = 1
    nv = 2
    GOSUB walk
RETURN


draw_msg:
    nm = STRLEN(msg$)
    wsum = 0
    FOR m = 0 TO nm - 1
        g = GIDX[ASC(msg$, m)]
        wsum = wsum + GADV[g] + GGAP
    NEXT
    wsum = wsum - GGAP
    kx = TXTW / wsum
    // The height follows the width at a constant ratio: a letter must
    // remain a letter, not stretch to the string length. 1.25 is
    // the same ratio as the hand-typed "R1BBIT" had.
    ky = kx * 1.25
    penx = 128 - wsum * kx / 2
    peny = 128 - 12 * ky
    nv = 0
    FOR m = 0 TO nm - 1
        g = GIDX[ASC(msg$, m)]
        FOR j = GOFF[g] TO GOFF[g] + GCNT[g] - 1
            gv = GS[j]
            gu = FLOOR(gv / 1000)
            gv = gv - gu * 1000
            gw = FLOOR(gv / 10)
            VX[nv] = penx + gu * kx
            VY[nv] = peny + gw * ky
            VP[nv] = gv - gw * 10
            nv = nv + 1
        NEXT
        penx = penx + (GADV[g] + GGAP) * kx
    NEXT
    GOSUB walk
RETURN

init_glyphs:
    // Glyph table. 
    GS[0-6] = {6000, 61, 181, 6241, 12181, 12061, 6001}
    GS[7-13] = {2000, 6001, 6241, 3191, 6241, 6001, 10001}
    GS[14-25] = {0, 12151, 12191, 9241, 3241, 191, 3241, 9241, 12191, 12151, 1, 12001}
    GS[26-42] = {30, 3001, 9001, 12071, 8131, 12201, 9241, 3241, 211, 3241, 9241, 12201, 8131, 12071, 9001, 3001, 31}
    GS[43-48] = {9000, 9241, 81, 12081, 9081, 9001}
    GS[49-65] = {30, 2001, 8001, 12041, 12111, 8151, 1141, 2241, 12241, 2241, 1141, 8151, 12111, 12041, 8001, 2001, 31}
    GS[66-80] = {3000, 9001, 12041, 12081, 9121, 3121, 81, 51, 161, 4241, 10231, 4241, 161, 51, 3001}
    GS[81-85] = {4000, 12241, 241, 12241, 4001}
    GS[86-98] = {6000, 10031, 10091, 6131, 10161, 10211, 6241, 2211, 2161, 6131, 2091, 2031, 6001}
    GS[99-112] = {2010, 8001, 12081, 12191, 9241, 3241, 201, 161, 3121, 9121, 12161, 12081, 8001, 2011}
    GS[113-117] = {0, 3001, 3031, 31, 1}
    GS[118-130] = {1000, 11241, 5240, 241, 171, 5171, 5241, 7070, 12071, 12001, 7001, 7071, 7001}
    GS[131-145] = {12040, 9001, 3001, 51, 191, 3241, 9241, 12201, 9241, 3241, 191, 51, 3001, 9001, 12041}
    GS[146-153] = {0, 241, 8241, 12201, 8131, 131, 4131, 12001}
    GS[154-165] = {0, 241, 8241, 12211, 12171, 8131, 131, 8131, 12091, 12041, 8001, 1}
    GS[166-174] = {0, 7001, 3001, 3241, 241, 7241, 3241, 3001, 7001}
    GS[175-180] = {6000, 6241, 241, 12241, 6241, 6001}
    GS[181-190] = {12000, 1, 131, 9131, 131, 241, 12241, 241, 1, 12001}
    GS[191-198] = {0, 241, 8241, 12211, 12161, 8131, 131, 1}
    GS[199-227] = {40, 2011, 6001, 10021, 12061, 11091, 9121, 6131, 2141, 171, 201, 2231, 6241, 10231, 12201, 10231, 6241, 2231, 201, 171, 2141, 6131, 9121, 11091, 12061, 10021, 6001, 2011, 41}
    GS[228-235] = {0, 141, 111, 3141, 7131, 3141, 111, 1}
    GS[236-238] = {0, 9241, 1}
    GS[239-248] = {60, 3061, 3101, 101, 61, 140, 3141, 3181, 181, 141}
    // U for the SUBSCRIBE caption: up the left side and back, the bottom,
    // up the right and back. Both ends at the bottom of the row.
    GS[249-257] = {1020, 1241, 1021, 2001, 6001, 10001, 11021, 11241, 11021}
    GOFF[0-24] = {0, 0, 7, 14, 26, 43, 49, 66, 81, 86, 99, 113, 118, 131, 146, 154, 166, 175, 181, 191, 199, 228, 236, 239, 249}
    GCNT[0-24] = {0, 7, 7, 12, 17, 6, 17, 15, 5, 13, 14, 5, 13, 15, 8, 12, 9, 6, 10, 8, 29, 8, 3, 10, 9}
    GADV[0-24] = {8, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 5, 12, 12, 12, 12, 7, 12, 12, 12, 12, 9, 9, 5, 12}
    GIDX[48] = 1
    GIDX[49] = 2
    GIDX[50] = 3
    GIDX[51] = 4
    GIDX[52] = 5
    GIDX[53] = 6
    GIDX[54] = 7
    GIDX[55] = 8
    GIDX[56] = 9
    GIDX[57] = 10
    GIDX[46] = 11
    GIDX[37] = 12
    GIDX[67] = 13
    GIDX[82] = 14
    GIDX[66] = 15
    GIDX[73] = 16
    GIDX[84] = 17
    GIDX[69] = 18
    GIDX[80] = 19
    GIDX[83] = 20
    GIDX[114] = 21
    GIDX[47] = 22
    GIDX[58] = 23
    GIDX[85] = 24
RETURN

init_toon:
   
    TOFF[0-2] = {0, 164, 281}
    TCNT[0-2] = {164, 117, 31}
    TOON[0-9] = {2090580, 2150721, 2190861, 2201011, 2201151, 2171301, 2111441, 2201481, 2271551, 2341621}
    TOON[10-19] = {2381711, 2411801, 2431891, 2431991, 2402091, 2372171, 2312261, 2242331, 2162381, 2072421}
    TOON[20-29] = {1982441, 1882451, 1792441, 1692411, 1612361, 1532301, 1472231, 1422141, 1392051, 1371951}
    TOON[30-39] = {1281961, 1191951, 1172051, 1142141, 1092231, 1032301, 952361, 872411, 772441, 682451}
    TOON[40-49] = {582441, 492421, 402381, 322331, 252261, 192171, 162091, 131991, 131891, 151801}
    TOON[50-59] = {181711, 221621, 291551, 361481, 451441, 391281, 361121, 360951, 390781, 450631}
    TOON[60-69] = {540481, 650361, 780261, 930181, 1090131, 1260111, 1420121, 1580161, 1740231, 1870331}
    TOON[70-79] = {1990451, 2090581, 2090581, 1730560, 1710501, 1640451, 1540411, 1420381, 1280371, 1140381}
    TOON[80-89] = {1020411, 920451, 850501, 830561, 1070770, 1130711, 1220671, 1330671, 1430701, 1490761}
    TOON[90-99] = {1500841, 1470911, 1390961, 1280981, 1180961, 1100911, 1060841, 1070771, 1041130, 1101141}
    TOON[100-109] = {1151181, 1191241, 1211321, 1211401, 1201481, 1171551, 1121601, 1071631, 1011631, 961601}
    TOON[110-119] = {921551, 881481, 871401, 881321, 901241, 941181, 991141, 1041131, 1521130, 1571141}
    TOON[120-129] = {1621181, 1661241, 1681321, 1691401, 1681481, 1641551, 1601601, 1551631, 1491631, 1441601}
    TOON[130-139] = {1391551, 1361481, 1351401, 1351321, 1371241, 1411181, 1461141, 1521131, 1521080, 1331111}
    TOON[140-149] = {1131101, 951051, 790971, 680861, 630731, 630601, 690471, 800361, 950271, 1140231}
    TOON[150-159] = {1330221, 1520251, 1690311, 1830411, 1910531, 1940671, 1910801, 1820921, 1691021, 1521081}
    TOON[160-169] = {1691021, 1820921, 1910801, 1940661, 1321510, 1131401, 941291, 741191, 581131, 561171}
    TOON[170-179] = {521201, 471231, 431241, 381251, 331241, 281231, 241201, 201171, 171121, 151081}
    TOON[180-189] = {141031, 140981, 160931, 180881, 210841, 250811, 300791, 440751, 570721, 620721}
    TOON[190-199] = {620531, 740531, 740711, 810711, 810521, 930521, 930701, 1020731, 1130781, 1240841}
    TOON[200-209] = {1090671, 960541, 850441, 720371, 610291, 590201, 680131, 850111, 1020141, 1170221}
    TOON[210-219] = {1300341, 1410501, 1510751, 1571021, 1581271, 1641261, 1701251, 1771251, 1831261, 1891281}
    TOON[220-229] = {1951301, 2001341, 2051381, 2091431, 2131491, 2151541, 2121381, 2111201, 2171091, 2281041}
    TOON[230-239] = {2371121, 2421291, 2401511, 2331701, 2221831, 2141891, 2111941, 2071991, 2032041, 1982071}
    TOON[240-249] = {2222051, 2202171, 2032171, 1972451, 1492451, 1432171, 1262171, 1242051, 1482071, 1442041}
    TOON[250-259] = {1392001, 1361951, 1331901, 1311851, 1291791, 1281731, 1281681, 1291621, 1301561, 1321511}
    TOON[260-269] = {1321511, 1411710, 1441721, 1471741, 1501771, 1511811, 1521861, 1511901, 1491941, 1461971}
    TOON[270-279] = {1431991, 1391991, 1361971, 1331941, 1311901, 1301861, 1301811, 1321771, 1341741, 1371721}
    TOON[280-280] = {1411711}
    TOON[281-290] = {990500, 991321, 1101581, 1231841, 1332021, 1392091, 1532091, 1622011, 1661841, 1621651}
    TOON[291-300] = {1591481, 1621441, 1821441, 2021441, 2111391, 2151291, 2031191, 2181091, 2030991, 2180901}
    TOON[301-310] = {2030801, 2130701, 2050581, 1920501, 1360501, 990501, 950470, 380471, 381301, 951301}
    TOON[311-311] = {950471}
RETURN

keep:
    FOR i = 0 TO np - 1
        QX[i] = PX[i] - pvx
        QY[i] = PY[i] - pvy
    NEXT
RETURN

place:
    ax = COS(ang) * GX * pul
    bx = SIN(ang) * GX * pul
    ay = SIN(ang) * GY * pul
    by = COS(ang) * GY * pul
    // Pivot offset. The reference copy is stored relative to it, so the
    // shape must be returned there: at pvx = pvy = 128 both corrections are zero and
    // everything works exactly as before.
    sx = MIDX + (pvx - 128) * GX
    sy = MIDY + (pvy - 128) * GY
    FOR i = 0 TO np - 1
        PX[i] = sx + QX[i] * ax - QY[i] * bx
        PY[i] = sy + QX[i] * ay + QY[i] * by
    NEXT
RETURN

calib:
    FOR i = 0 TO np - 1
        PX[i] = MIDX + (PX[i] - 128) * GX
        PY[i] = MIDY + (PY[i] - 128) * GY
    NEXT
RETURN

walk:
    dd = 0
    n = 0
    FOR j = 1 TO nv - 1
        IF VP[j] = 1 THEN dd = dd + SQRT((VX[j] - VX[j - 1]) * (VX[j] - VX[j - 1]) + (VY[j] - VY[j - 1]) * (VY[j] - VY[j - 1]))
    NEXT
    FOR j = 0 TO nv - 1
        IF VP[j] = 0 THEN n = n + 1
    NEXT
    r = ntarget - n * hold
    IF r < 8 THEN r = 8
    a = dd / r
    IF a < 1 THEN a = 1

    FOR j = 0 TO nv - 1
        sx = VX[j]
        sy = VY[j]
        IF VP[j] = 0 THEN GOSUB pen_jump
        IF VP[j] = 1 THEN GOSUB pen_line
        lx = sx
        ly = sy
    NEXT
RETURN
pen_jump:
    nj = hold
    IF np + nj > 899 THEN nj = 899 - np
    FOR k = 1 TO nj
        PX[np] = sx
        PY[np] = sy
        np = np + 1
    NEXT
RETURN

// Line: divided into segments of a units. The step is given in DAC units, not
// in a number of points, so long and short strokes glow the same —
// the beam goes along them at one speed.
pen_line:
    dx = sx - lx
    dy = sy - ly
    dd = SQRT(dx * dx + dy * dy)
    ns = FLOOR(dd / a) + 1
    IF np + ns > 899 THEN ns = 899 - np
    FOR k = 1 TO ns
        PX[np] = lx + dx * k / ns
        PY[np] = ly + dy * k / ns
        np = np + 1
    NEXT
RETURN

Hardware. You need an ESP32‑S3 with PSRAM

The script is written for the 8 MB flash / 8 MB PSRAM variant — that is declared in the CONFIG block at the top of the file, along with the DAC pins: GPIO 7 for X, GPIO 8 for Y. Per pin: 1 kΩ in series, 10 nF to ground. Scope in X‑Y, both channels 0.5 V/div, DC coupled.

A different board or different free pins — only the CONFIG block changes, the rest of the script does not care.

Getting it onto a board:

  1. Sign up at r1bbit.com.
  2. Go to Devices, add a device and flash it. The board connects over USB straight from the browser (Web Serial, so Chrome or Edge).
  3. The board type is detected automatically. All you fill in is your Wi‑Fi SSID and password — they are written during flashing, so there is no separate provisioning step afterwards.
  4. Flash it and wait for the board to come online; the page shows the boot log.
  5. Open the editor, pick your device, paste the script, upload it and hit run.

The script's own output — figure number, point count and the measured refresh rate — goes to the editor's terminal.

1
0 replies

Sign in to reply