l1vmet3s.av

typeGEN

Composicions tipogràfiques sobre fons transparent: 10 maquetes, text que recorre formes, paraules destacades i graelles de text.Composiciones tipográficas sobre fondo transparente: 10 maquetas, texto que recorre formas, palabras destacadas y rejillas de texto.Typographic compositions on transparent: 10 layouts, text running along shapes, highlighted words and text grids.

v1.2.1199 controlscontrolescontrols78 operadorsoperadoresoperators2217 línies de codilíneas de códigolines of code106 KB
typeGEN
  • in1CHOPaudio
typeGEN
  • out1TOPtype
  • out2CHOPstate

UsarUsarUse

Prova aixòPrueba estoTry this

Escriu *paraula* al text i activa Underline a Highlight 1: les marques viatgen dins del mateix text.Escribe *palabra* en el texto y activa Underline en Highlight 1: las marcas viajan dentro del propio texto.Type *word* in the text and turn on Underline in Highlight 1: the marks travel inside the text itself.

Aquesta part és en castellà.This part is in Spanish.

  1. Arrastrar tox/GEN/typeGEN.tox y poner out1 encima del visual (Composite / Over: sale premultiplicado).
  2. Text: escribir con | entre segmentos y marcar *destacados* / **destacados**. O un Text DAT (una línea por segmento), o textbankCTRL con Target = typeGEN (Next / Random / Auto cada N beats).
  3. Style: fuente (la del sistema o un archivo), tamaño (× alto), color, tracking, interlineado.
  4. Layout: composición, Align, Spread By, Diagonal, Margin, Rotate, Position. Con Path (shape), la página Path: forma, Fill, Start, Direction, Side, Letters, Show Path y el movimiento (Travel / Spin / Pulse a tempo).
  5. Highlight 1 / 2: activar lo que se quiera sumar (Color, Font, Size, Underline, Outline) y ajustar grosores y distancias (× tamaño de la letra). Pill: pastilla por palabra, segmento o bloque.
  6. Grid: Columns × Rows, Repeat o Distribute, Coverage (Manual, Audio Level, Beat Build, Beat Pulse; orden y Softness) y Change a beat o con el golpe (página Audio: in1 = nivel de audioCTRL o audio en bruto de setupCTRL). Llenar la pantalla de líneas: Composition Path, Shape Wave, Size Relative To = Canvas / Cell, Width 1,1–1,2; Grid con 1 columna, Rows Mode = Lines, Fill Canvas On, Line Distance ~0,9–1,1 y un Path Stagger pequeño (0,13). Con ondas altas las líneas se juntan en las pendientes: subir Line Distance o bajar Height.
  7. Mapear con midiCTRL lo que se toque en directo (Coverage, Travel, Change Now…).

Va bé ambVa bien conGoes well with

ParàmetresParámetrosParameters

El panell real del mòdul amb els seus valors per defecte. Prem una fila per saber què fa; les notes són en castellà.El panel real del módulo con sus valores por defecto. Pulsa una fila para saber qué hace.The module's real panel with its default values. Press a row to see what it does; notes are in Spanish.

EntendreEntenderUnderstand

Cada caràcter diferent es pinta un sol cop en un atles i cada lletra de la pantalla és una còpia amb la seva posició i gir. El recorregut per la forma el calcula el shader.Cada carácter distinto se pinta una sola vez en un atlas y cada letra de la pantalla es una copia con su posición y giro. El recorrido por la forma lo calcula el shader.Each distinct character is painted once into an atlas and every letter on screen is a copy with its own position and rotation. The shader works out the path along the shape.

Aquesta part és en castellà.This part is in Spanish.

Con más detalle

Cada letra es una pieza: un atlas pinta una vez cada carácter distinto (al tamaño al que se ve, igual de nítido que un texto normal) y todas las letras se dibujan en un solo render, con su posición, giro y color. El trazo de las formas y el movimiento viven en el shader, y los adornos (pastilla, subrayado, contornos) se curvan con la forma. Python solo trabaja al cambiar algo (1–5 ms, también con 16 × 16 celdas); quieto, la salida se congela y no gasta, y en movimiento cuesta ~0,3–0,4 ms aunque haya miles de letras. Para llenar la pantalla mide lo que ocupa una línea y pone solo las que se ven, sin cambiar el tamaño de la letra. Compatible con textbankCTRL.

La idea

La maqueta de textos de carouselGEN llevada a un módulo propio: rótulos, frases alrededor de un logo y mosaicos de palabras que respiran con la música y pantallas llenas de texto en movimiento, con las palabras clave subrayadas, rodeadas o sobre una pastilla.

Les idees que hi ha a sotaLas ideas que hay debajoThe ideas underneath

Per dinsPor dentroInside

Aquesta part és en castellà.This part is in Spanish.

El recorrido de la señal esquema en texto
TEXTO Y MAQUETA (util.compose, solo al cambiar un par, el texto, el Text DAT o el lienzo)
  parse (segmentos, tramos *…* / **…**) → atlas (2 pasadas) → layout (composición o Path, por celda con Grid)
  → transform (Rotate, Position) → to_arrays / decorations (copias por celda con numpy)

ATLAS (cada carácter distinto una vez, centrado en su celda; la 2.ª pasada al tamaño de la letra más grande)
  spec_atlas0 → atlas0 (Text TOP ≤ 1280 px)            fuente base
  spec_atlas1 → atlas1 · spec_atlas2 → atlas2          fuentes de Highlight 1 / 2 (Font On)
  metrics0..2 (Text TOP sin procesar, 200 px fijos)    medidas evalTextSize en caché (kerning incluido)
  spec_measure → text_measure                          altura de las mayúsculas por fuente (una H a 160 px)

INSTANCIAS
  glyph_chop (Script CHOP: una muestra por letra) → null_glyphs → glyph_geo (Rectangle 1 × 1) + glyph_mat
  deco_chop (una caja por adorno) → null_deco → deco_geo (Grid 64 × 1) + deco_mat (SDF: caja redondeada / elipse)
  path_tex (Script TOP 1024 × 1, 32f: trazo por longitud de arco) → path_geo (segmentos) + path_mat
  cell_tex (Script TOP N × 2, 32f: rango de Coverage de → a, beat de inicio, sentido; origen, periodo y desvío del recorrido)

RENDER  glyph_geo / path_geo / deco_geo (orden: trazo → adornos → letras) + cam → render
        → cache_out (Cache 1 frame: congelado salvo unos frames tras un cambio o con animación) → null_out → out1

RELOJ   beat_rate → beat_speed ┐
        beat_lib (libclock) ───┴→ beat_src → null_beats (Cook Always; lg_beats para textbankCTRL)
        rate_travel → speed_travel → null_travel · rate_spin → speed_spin → null_spin (bucle 0..1, reset en 0)
        motion (travel, spin, beats, nivel del audio) → null_motion_gl → uniform uMotion[1] de los tres MATs

AUDIO   in1 (o un audioCTRL sin cable) → red am_* de audiomod → am_level (4 bandas) · am_hitnull → am_exec_hit (golpes)

ESTADO  state (Constant CHOP que escribe compose) → out2

util · libclock · param_exec (cualquier par → compose) · param_exec4 (Change Now) · exec_frame (init / tick)
build1 … build5 (los scripts de construcción viajan en el .tox)

No hay Python por frame salvo util.tick (vigilante de 12–20 µs: Text DAT, lienzo, fin del rato en vivo, beat de Change).

Operador a operador configuración clave
OperadorConfiguración clave
atlas0..2Text TOP, specdat = spec_atlasN, text = '', resolución custom (columnas × celda, ≤ 1280), fontsizexunit = pixels, keepfontratio, bgalpha = 0, blanco, trackingx = 0, rgba8. Fuente, tamaño y resolución desde util.build_atlas
spec_atlasNTable DAT x y text: pluma de cada carácter en su celda (px enteros) y línea base a 0,3 × celda
metrics0..2Text TOP 16 × 16 que nunca se procesa: evalTextSize a 200 px fijos (la fuente la copia build_atlas)
text_measureText TOP 256², una H a 160 px en (20, 40): util.cap_ratio mide la altura de las mayúsculas
glyph_chopScript CHOP (glyph_cb → util.fill), isTimeSlice = False, una muestra por letra; solo cocina con cook(force=True) tras compose
glyph_geoGeometry COMP, Rectangle SOP 1 × 1, instancing, instanceop = null_glyphs, 4 bloques de custom attrib: gx gy ga gk · ux uy up uv · cr cg cb ca · st cl sg ix; drawpriority 0
glyph_matGLSL MAT: vectors uRes, uAtlas0..2 (celda, línea base, ancho, alto), uPathA/B/C, uCov, uCov2, uGrid; samplers sAtlas0..2 (mipmap), sPath, sCells (nearest); array uMotion (vec4, null_motion_gl); blending one / omsa, sin profundidad, sin culling
path_texScript TOP (path_cb → util.fill_path): 1 × 1024 rgba32f (x, y, tangente)
path_geo / path_matRectangle 1 × 1 instanciado numinstances = segmentos × celdas; render = Show Path y Composition Path; drawpriority 2; uniforms del trazo + uLine, uLineCol
deco_chop / deco_geo / deco_matScript CHOP (deco_cb → util.fill_deco) → Grid SOP 2 × 65 (tira) instanciado con dx dy da dm · dl dh dw dr · kr kg kb ka · dk d1 d2 d3; render = hay adornos; drawpriority 1
cell_texScript TOP (cell_cb → util.fill_cells): N × 2 rgba32f. Fila 0: rango de, rango a, beat de inicio, sentido del Travel (±1). Fila 1: origen x, y (px), periodo y desvío del recorrido del texto de esa celda
camCámara ortográfica (los shaders escriben gl_Position en clip desde px)
renderRender TOP, geometry = glyph_geo path_geo deco_geo, resolución = lienzo, bgcolor = Background premultiplicado
cache_outCache TOP cachesize 1; util.wake lo activa N frames y tick lo apaga tras cook(force=True)
beat_*, null_beatsReloj de beats común (libclock con Timeline; Speed CHOP con Manual / Free); Null Cook Always
speed_travel / speed_spinSpeed CHOP de vueltas por compás × bps / 4, Limit Loop 0..1, reset por expresión (velocidad 0 o no Path) → Null Cook Always
motionConstant CHOP de 4 canales por expresión (travel, spin, beats, nivel) → uMotion[1]
stateConstant CHOP: segments, glyphs, atlascell, atlasbl, pathlen, pathperiod, pathoff, pathclosed, pathsegs, atlascell1, atlasbl1, atlascell2, atlasbl2, highlights, decos, cells; lo escribe compose (los uniforms lo leen: dependencia)
Audio (in1, am_*, hit)Red común de audiomod (install en build4), ver su documentación
param_execParameter Execute sobre .., pars = *: cualquier par (salvo Status, About, Sync, Bpm) → util.compose; pulso Resync
param_exec4Parameter Execute: pulso Change Now → util.change(manual=True)
exec_frameExecute DAT: onStart / onCreate → util.init; onFrameStart → util.tick
COMPopviewer = ./out1; páginas nativas ocultas

TallerTallerWorkshop

El codiEl códigoThe code

util python · 1578 línieslíneaslines
# util de typeGEN: texto → segmentos / tramos destacados → atlas de glifos → maqueta → instancias.
# DATA[comp.path] = arrays por letra que lee glyph_chop (Script CHOP) al forzar su cook tras compose.
import math

import numpy as np

CAP = {}                  # altura de mayúsculas / tamaño, por (fuente, estilo, archivo)
DATA = {}                 # comp.path → dict de arrays (un valor por letra)
ATLAS = {}                # (comp.path, variante) → info del atlas: celda, tamaño de fuente, mapa de caracteres
ADV = {}                  # (comp.path, variante) → {carácter: avance al tamaño del atlas}
LAST = {}                 # comp.path → resumen de la última maqueta (para el Status)
ATLAS_MAX = 1280          # licencia no comercial: ningún TOP pasa de 1280 px por lado
FONT_K = 0.6              # tamaño de la fuente en el atlas = 0,6 × celda
BASE_K = 0.3              # línea base a 0,3 × celda desde abajo
CHANS = [['gx', 'gy', 'ga', 'gk'], ['ux', 'uy', 'up', 'uv'], ['cr', 'cg', 'cb', 'ca'], ['st', 'sg', 'wd', 'ix']]
NL = chr(10)
MSIZE = 200.0             # tamaño fijo de medida (metricsN): evalTextSize es ~100 veces más lento tras cambiar el tamaño
MW = {}                   # caché de anchos a MSIZE por (fuente, estilo, archivo, texto)


def mwidth(comp, v, s):
	"""Avance de un texto a MSIZE px, kerning incluido (Text TOP metricsN, siempre al mismo tamaño)."""
	fk = ATLAS.get((comp.path, v), {}).get('fkey')
	key = (fk, s)
	w = MW.get(key)
	if w is None:
		if len(MW) > 50000:
			MW.clear()
		w = MW[key] = float(comp.op('metrics%d' % v).evalTextSize(s)[0])
	return w


def pv(comp, name, default):
	p = getattr(comp.par, name, None)
	return p.eval() if p is not None else default


def set_ro(comp, name, val):
	p = getattr(comp.par, name, None)
	if p is None or p.eval() == val:
		return
	p.readOnly = False
	p.val = val
	p.readOnly = True


def canvas(comp):
	if pv(comp, 'Outres', 'project') == 'custom':
		return max(16, int(comp.par.Outsize1.eval())), max(16, int(comp.par.Outsize2.eval()))
	win = op('/perform')
	c = win.par.winop.eval() if win is not None else None
	if c is not None and hasattr(c.par, 'w'):
		return max(16, int(c.par.w.eval())), max(16, int(c.par.h.eval()))
	return 1280, 720


def rate(comp):
	"""Beats por segundo del reloj propio (Manual / Free; Timeline usa libclock)."""
	mode = pv(comp, 'Sync', 'timeline')
	if mode == 'manual':
		return max(float(pv(comp, 'Bpm', 120.0)), 1.0) / 60.0
	if mode == 'free':
		return 1.0
	t = op('/local/time')
	try:
		return float(t.par.tempo.eval()) / 60.0
	except Exception:
		return 2.0


# ---- texto ----
def source_text(comp):
	"""Text DAT (una línea o fila = un segmento) si está; si no, el par Text."""
	d = pv(comp, 'Textdat', None)
	if d is not None and hasattr(d, 'text'):
		if getattr(d, 'isTable', False):
			rows = [' '.join(c.val for c in d.row(r) if c.val.strip()) for r in range(d.numRows)]
		else:
			rows = d.text.split(NL)
		return ' | '.join(r.strip() for r in rows if r.strip())
	return str(pv(comp, 'Text', ''))


def apply_case(s, case):
	if case == 'upper':
		return s.upper()
	if case == 'lower':
		return s.lower()
	return s


def parse(comp):
	"""→ lista de segmentos; cada segmento = lista de tramos (texto, estilo 0 / 1 / 2)."""
	raw = apply_case(source_text(comp), pv(comp, 'Case', 'astyped')).replace(chr(13), '').replace(NL, ' ')
	segs = []
	for part in raw.split('|'):
		runs, buf, s1, s2, i = [], '', False, False, 0

		def flush():
			if buf:
				st = 2 if s2 else (1 if s1 else 0)
				if runs and runs[-1][1] == st:
					runs[-1] = (runs[-1][0] + buf, st)
				else:
					runs.append((buf, st))

		while i < len(part):
			if part.startswith('**', i):
				flush()
				buf = ''
				s2 = not s2
				i += 2
				continue
			if part[i] == '*':
				flush()
				buf = ''
				s1 = not s1
				i += 1
				continue
			buf += part[i]
			i += 1
		flush()
		if runs:                                    # sin espacios al principio ni al final del segmento
			runs[0] = (runs[0][0].lstrip(), runs[0][1])
			runs[-1] = (runs[-1][0].rstrip(), runs[-1][1])
			runs = [r for r in runs if r[0]]
		if runs and any(r[0].strip() for r in runs):
			segs.append(runs)
	return segs


# ---- estilos (accesores que redefine la fase de destacados) ----
def style_var(comp, st):
	"""Atlas (fuente) de un estilo: 0 = la fuente base."""
	return 0


def style_size(comp, st):
	return 1.0


def style_color(comp, st):
	return (float(pv(comp, 'Colorr', 1.0)), float(pv(comp, 'Colorg', 1.0)), float(pv(comp, 'Colorb', 1.0)),
			float(pv(comp, 'Colora', 1.0)))


def font_prefix(v):
	return ''


# ---- atlas de glifos ----
def _font_to(t, comp, P):
	ff = str(pv(comp, P + 'Fontfile', '')).strip()
	if t.par.fontfile.eval() != ff:
		t.par.fontfile = ff
	font = str(pv(comp, P + 'Font', 'Arial')).strip() or 'Arial'
	if t.par.font.eval() != font:
		t.par.font = font
	tf = str(pv(comp, P + 'Typeface', 'Regular'))
	names = list(t.par.typeface.menuNames)
	if names and tf not in names:
		tf = 'Regular' if 'Regular' in names else names[0]
	if t.par.typeface.eval() != tf:
		t.par.typeface = tf


def build_atlas(comp, v, chars, want=None):
	"""Cada carácter distinto una vez, centrado en su celda (rejilla cuadrada de hasta 1280 px).
	want = tamaño de la letra más grande en pantalla: la celda se ajusta a él (1 texel = 1 px, como un
	Text TOP directo); sin want, la celda más grande que cabe."""
	t, sp, mt = comp.op('atlas%d' % v), comp.op('spec_atlas%d' % v), comp.op('metrics%d' % v)
	_font_to(t, comp, font_prefix(v))
	_font_to(mt, comp, font_prefix(v))
	if mt.par.fontsizex.eval() != MSIZE:
		mt.par.fontsizex = MSIZE
	fkey = (mt.par.font.eval(), mt.par.typeface.eval(), mt.par.fontfile.eval())
	ATLAS.setdefault((comp.path, v), {})['fkey'] = fkey
	chars = sorted(set(c for c in chars if not c.isspace()))
	n = len(chars)
	cols = max(1, int(math.ceil(math.sqrt(max(n, 1)))))
	rows = max(1, int(math.ceil(max(n, 1) / float(cols))))
	cell = int(ATLAS_MAX // cols) if n else 16       # sin letras, un atlas mínimo
	f = cell * FONT_K
	if want:
		cell = max(16, min(cell, int(math.ceil(want / FONT_K)) + 2))
		f = min(want, cell * FONT_K)                # escala 1 exacta en pantalla para la letra más grande
	if t.par.fontsizex.eval() != f:
		t.par.fontsizex = f
	advm = {c: mwidth(comp, v, c) for c in chars}  # a MSIZE
	mx = max(advm.values()) * f / MSIZE if advm else 0.0
	if mx > 0.92 * cell:                            # fuentes muy anchas: que la letra quepa en su celda
		f *= 0.92 * cell / mx
		t.par.fontsizex = f
	adv = {c: a * f / MSIZE for c, a in advm.items()}
	bl = float(round(BASE_K * cell))                # en píxeles enteros: texel = píxel
	cmap = {}
	new = [['x', 'y', 'text']]
	for i, c in enumerate(chars):
		x0, y0 = (i % cols) * cell, (i // cols) * cell
		px = float(round((cell - adv[c]) / 2.0))
		cmap[c] = (x0, y0, px)
		new.append(['%.2f' % (x0 + px), '%.2f' % (y0 + bl), c])
	w, h = cols * cell, rows * cell
	if t.par.resolutionw.eval() != w:
		t.par.resolutionw = w
	if t.par.resolutionh.eval() != h:
		t.par.resolutionh = h
	old = [[c.val for c in sp.row(r)] for r in range(sp.numRows)]
	if new != old:
		sp.clear()
		for r in new:
			sp.appendRow(r)
	ATLAS[(comp.path, v)] = {'cell': cell, 'f': f, 'bl': bl, 'w': w, 'h': h, 'map': cmap, 'n': n, 'fkey': fkey}
	ADV[(comp.path, v)] = adv
	if t.errors():
		print('typeGEN: atlas%d' % v, t.errors())
	return ATLAS[(comp.path, v)]


def atlas_info(comp, v):
	return ATLAS.get((comp.path, v), {'cell': 16, 'f': 9.6, 'bl': 4.8, 'w': 16, 'h': 16, 'map': {}, 'n': 0})


def cap_ratio(comp, v=0):
	"""Altura de las mayúsculas / tamaño de la fuente, medida con una H (una vez por fuente)."""
	t = comp.op('atlas%d' % v)
	key = (t.par.font.eval(), t.par.typeface.eval(), t.par.fontfile.eval())
	if key in CAP:
		return CAP[key]
	m = comp.op('text_measure')
	m.par.fontfile = key[2]
	m.par.font = key[0]
	if key[1] in list(m.par.typeface.menuNames):
		m.par.typeface = key[1]
	r = 0.72
	try:
		m.cook(force=True)
		a = m.numpyArray(delayed=False)[..., 3]
		rows = np.nonzero((a > 0.5).any(axis=1))[0]
		if len(rows):
			r = (rows.max() - 40 + 1) / 160.0
	except Exception as e:
		print('typeGEN: medida de fuente', e)
	r = r if 0.3 < r < 1.2 else 0.72
	CAP[key] = r
	return r


# ---- maqueta ----
def build_line(comp, runs, size, track, seg):
	"""Tramos → letras con su x de pluma (px desde el inicio de la línea, kerning incluido) y el ancho."""
	g = []
	x = 0.0
	nch = 0
	word = 0
	prev_space = False
	for txt, st in runs:
		v = style_var(comp, st)
		info = atlas_info(comp, v)
		sz = size * style_size(comp, st)
		k = sz / max(info['f'], 1e-3)                # escala pantalla / atlas
		km = sz / MSIZE                              # escala pantalla / medida
		for i, c in enumerate(txt):
			if c.isspace():
				if not prev_space:
					word += 1
				prev_space = True
			else:
				prev_space = False
				ac = mwidth(comp, v, c)
				pen = mwidth(comp, v, txt[:i + 1]) - ac             # pluma = prefijo − su propio avance
				g.append({'c': c, 'st': st, 'v': v, 'x': x + pen * km + nch * track * size, 'k': k,
						  'adv': ac * km, 'word': word, 'seg': seg, 'size': sz, 'ci': nch})
			nch += 1
		x += mwidth(comp, v, txt) * km
	width = x + max(nch - 1, 0) * track * size
	return {'g': g, 'w': width, 'size': size, 'n': nch}


def split_words(runs):
	"""Tramos de un segmento → lista de palabras (cada una, sus tramos)."""
	words, cur = [], []
	for txt, st in runs:
		parts = txt.split(' ')
		for j, p in enumerate(parts):
			if j > 0 and cur:
				words.append(cur)
				cur = []
			if p:
				cur.append((p, st))
	if cur:
		words.append(cur)
	return words


def place(out, line, x, base, ang=0.0):
	"""Añade las letras de una línea con la pluma en (x, línea base) y giro ang alrededor de ese punto."""
	c, s = math.cos(ang), math.sin(ang)
	for g in line['g']:
		out.append(dict(g, X=x + g['x'] * c, Y=base + g['x'] * s, A=ang))


def scale_line(line, f):
	line = dict(line, g=[dict(g, x=g['x'] * f, k=g['k'] * f, adv=g['adv'] * f, size=g['size'] * f) for g in line['g']])
	line['w'] *= f
	line['size'] *= f
	return line


def layout(comp, segs, W, H):
	"""Segmentos → letras colocadas (X, Y = pluma y línea base en px, origen abajo-izquierda; A = giro)."""
	size = float(pv(comp, 'Size', 0.1)) * H
	track = float(pv(comp, 'Tracking', 0.0))
	ls = float(pv(comp, 'Linespacing', 1.2))
	m = float(pv(comp, 'Margin', 0.06)) * min(W, H)
	mode = pv(comp, 'Composition', 'center')
	al = pv(comp, 'Align', 'center')
	by = pv(comp, 'Spreadby', 'segments')
	capr = cap_ratio(comp, 0)
	cap = capr * size
	pitch = size * ls
	cx, cy = W / 2.0, H / 2.0
	top, bot = H - m - cap / 2.0, m + cap / 2.0      # centros de línea pegados a los márgenes
	out = []
	lines = [build_line(comp, r, size, track, i) for i, r in enumerate(segs)]
	n = len(lines)
	if n == 0:
		return out

	def put(line, x, yc):                           # yc = centro visual de la línea (mayúsculas)
		place(out, line, x, yc - cap / 2.0)

	def stacked(i, k):
		return cy + ((k - 1) / 2.0 - i) * pitch

	def ax(line):
		if al == 'left':
			return m
		if al == 'right':
			return W - m - line['w']
		return cx - line['w'] / 2.0

	def letters_spread(line, x0, x1, yc):          # letras de lado a lado (justificado forzado)
		if line['w'] > (x1 - x0):                   # no cabe: se reduce hasta caber
			line = scale_line(line, (x1 - x0) / line['w'])
		g = line['g']
		if len(g) == 1:
			put(line, cx - line['w'] / 2.0, yc)
			return
		last = g[-1]
		span = (last['x'] + last['adv']) - g[0]['x']
		extra = ((x1 - x0) - span) / (len(g) - 1.0)
		for j, gg in enumerate(g):
			out.append(dict(gg, X=x0 + (gg['x'] - g[0]['x']) + j * extra, Y=yc - cap / 2.0, A=0.0))

	if mode == 'flagleft':
		for i, L in enumerate(lines):
			put(L, m, stacked(i, n))
	elif mode == 'flagright':
		for i, L in enumerate(lines):
			put(L, W - m - L['w'], stacked(i, n))
	elif mode == 'corners':
		for c in range(4):
			grp = [i for i in range(n) if i % 4 == c]
			for r, i in enumerate(grp):
				L = lines[i]
				x = m if c in (0, 2) else W - m - L['w']
				yc = top - r * pitch if c < 2 else bot + (len(grp) - 1 - r) * pitch
				put(L, x, yc)
	elif mode == 'spread' and by == 'letters':
		for i, L in enumerate(lines):
			letters_spread(L, m, W - m, stacked(i, n))
	elif mode == 'spread':
		units = lines
		if by == 'words':
			units = [build_line(comp, w, size, track, i) for i, r in enumerate(segs) for w in split_words(r)]
		k = len(units)
		mingap = 0.5 * size                         # si no caben con medio cuerpo entre ellos, se reducen
		tot = sum(u['w'] for u in units)
		f = min(1.0, (W - 2.0 * m - mingap * (k - 1)) / max(tot, 1e-3))
		if f < 1.0:
			units = [scale_line(u, f) for u in units]
		if k == 1:
			put(units[0], cx - units[0]['w'] / 2.0, cy)
		else:
			gap = (W - 2.0 * m - sum(u['w'] for u in units)) / (k - 1)
			x = m
			for u in units:
				put(u, x, cy)
				x += u['w'] + gap
	elif mode == 'topbottom':
		put(lines[0], ax(lines[0]), top)
		rest = lines[1:]
		for r, L in enumerate(rest):
			put(L, ax(L), bot + (len(rest) - 1 - r) * pitch)
	elif mode == 'spreadv' and by == 'letters':
		most = max(L['n'] for L in lines)             # los espacios cuentan como hueco
		f = 1.0
		if most > 1:                                # letras que se tocarían en vertical: se reducen
			f = min(1.0, (H - 2.0 * m) / (cap * (1.15 * (most - 1) + 1.0)))
		if f < 1.0:
			lines = [scale_line(L, f) for L in lines]
			cap *= f
			top, bot = H - m - cap / 2.0, m + cap / 2.0
		colw = max([max([g['adv'] for g in L['g']] or [0.0]) for L in lines] or [0.0])
		for i, L in enumerate(lines):
			if n == 1:
				xc = m + colw / 2.0 if al == 'left' else (W - m - colw / 2.0 if al == 'right' else cx)
			else:
				xc = m + colw / 2.0 + (W - 2.0 * m - colw) * i / (n - 1.0)
			g = L['g']
			for gg in g:
				yc = cy if L['n'] == 1 else top + (bot - top) * gg['ci'] / (L['n'] - 1.0)
				out.append(dict(gg, X=xc - gg['adv'] / 2.0, Y=yc - cap / 2.0, A=0.0))
	elif mode == 'spreadv':
		units = lines
		if by == 'words':
			units = [build_line(comp, w, size, track, i) for i, r in enumerate(segs) for w in split_words(r)]
		k = len(units)
		for i, u in enumerate(units):
			yc = cy if k == 1 else top + (bot - top) * i / (k - 1.0)
			put(u, ax(u), yc)
	elif mode == 'staircase':
		for i, L in enumerate(lines):
			f = 0.5 if n == 1 else i / (n - 1.0)
			put(L, m + f * (W - 2.0 * m - L['w']), stacked(i, n))
	elif mode == 'justify':
		avail = W - 2.0 * m
		js = [scale_line(L, avail / max(L['w'], 1e-3)) for L in lines]
		caps = [capr * L['size'] for L in js]
		gaps = [max(ls - capr, 0.05) * min(js[i]['size'], js[i + 1]['size']) for i in range(n - 1)]
		total = sum(caps) + sum(gaps)
		f = min(1.0, (H - 2.0 * m) / max(total, 1e-3))
		ytop = cy + total * f / 2.0
		for i, L in enumerate(js):
			L = scale_line(L, f) if f < 1.0 else L
			base = ytop - caps[i] * f
			place(out, L, cx - L['w'] / 2.0, base)
			if i < n - 1:
				ytop = base - gaps[i] * f
	elif mode == 'diagonal':
		if pv(comp, 'Diagauto', True):
			ang = math.atan2(H - 2.0 * m, W - 2.0 * m)
		else:
			ang = math.radians(float(pv(comp, 'Diagangle', 30.0)))
		blockw = max(L['w'] for L in lines)
		c, s = math.cos(ang), math.sin(ang)
		for i, L in enumerate(lines):
			if al == 'left':
				lx = -blockw / 2.0
			elif al == 'right':
				lx = blockw / 2.0 - L['w']
			else:
				lx = -L['w'] / 2.0
			ly = ((n - 1) / 2.0 - i) * pitch - cap / 2.0          # línea base, relativo al centro del bloque
			place(out, L, cx + lx * c - ly * s, cy + lx * s + ly * c, ang)
	else:                                           # center (y path hasta la fase 2)
		for i, L in enumerate(lines):
			put(L, cx - L['w'] / 2.0, stacked(i, n))
	return out


def transform(comp, out, W, H):
	"""Rotate alrededor del centro del lienzo y Position X / Y (× lienzo)."""
	r = math.radians(float(pv(comp, 'Rotate', 0.0)))
	ox, oy = float(pv(comp, 'Posx', 0.0)) * W, float(pv(comp, 'Posy', 0.0)) * H
	cx, cy = W / 2.0, H / 2.0
	c, s = math.cos(r), math.sin(r)
	for g in out:
		if g.get('P'):                              # letras sobre un trazado: las coloca el shader
			continue
		dx, dy = g['X'] - cx, g['Y'] - cy
		g['X'] = cx + dx * c - dy * s + ox
		g['Y'] = cy + dx * s + dy * c + oy
		g['A'] = g.get('A', 0.0) + r
	return out


def to_arrays(comp, out):
	"""Letras colocadas → arrays por canal (CHANS) para glyph_chop."""
	n = max(len(out), 1)
	a = {ch: np.zeros(n, dtype=np.float32) for blk in CHANS for ch in blk}
	for i, g in enumerate(out):
		info = atlas_info(comp, g['v'])
		x0, y0, px = info['map'].get(g['c'], (0.0, 0.0, 0.0))
		col = style_color(comp, g['st'])
		a['gx'][i], a['gy'][i], a['ga'][i], a['gk'][i] = g['X'], g['Y'], g['A'], g['k']
		a['ux'][i], a['uy'][i], a['up'][i], a['uv'][i] = x0, y0, px, g['v']
		a['cr'][i], a['cg'][i], a['cb'][i], a['ca'][i] = col
		a['st'][i], a['sg'][i], a['wd'][i], a['ix'][i] = g['st'], g['seg'], g['word'], i
	snap = (np.abs(np.remainder(a['ga'] + math.pi, 2.0 * math.pi) - math.pi) < 1e-6) & (np.abs(a['gk'] - 1.0) < 0.02)
	if out and out[0].get('P'):                     # en un trazado, gx / gy / ga son posición a lo largo, desvío y avance
		snap[:] = False
	a['gx'] = np.where(snap, np.round(a['gx']), a['gx']).astype(np.float32)   # horizontal y a escala 1:
	a['gy'] = np.where(snap, np.round(a['gy']), a['gy']).astype(np.float32)   # cada texel en su píxel
	if not out:
		a['gk'][0] = 0.0
		a['ca'][0] = 0.0
	return a


def fill(scriptOp):
	"""onCook de glyph_chop: una muestra por letra."""
	comp = scriptOp.parent()
	a = DATA.get(comp.path)
	scriptOp.clear()
	scriptOp.isTimeSlice = False
	if a is None:
		scriptOp.numSamples = 1
		for blk in CHANS:
			for ch in blk:
				scriptOp.appendChan(ch)
		return
	scriptOp.numSamples = len(a['gx'])
	for blk in CHANS:
		for ch in blk:
			scriptOp.appendChan(ch).copyNumpyArray(a[ch])


def variants(comp, segs):
	"""Caracteres que necesita cada atlas (variante → conjunto)."""
	need = {0: set()}
	for runs in segs:
		for txt, st in runs:
			need.setdefault(style_var(comp, st), set()).update(txt)
	return need


def status(comp, nseg, nglyph, maxk=1.0):
	info = atlas_info(comp, 0)
	msg = '%d segments · %d letters · atlas cell %d px' % (nseg, nglyph, info['cell'])
	if nglyph and maxk > 1.3:
		msg += ' · large size + many characters: slightly soft'
	set_ro(comp, 'Status', msg)


def layout_size(comp):
	"""Lienzo en el que se maqueta la composición (la fase de Grid lo cambia por el tamaño de una celda)."""
	return canvas(comp)


def compose(comp):
	W, H = layout_size(comp)
	segs = parse(comp)
	need = variants(comp, segs)
	for v, chars in need.items():                   # 1.ª pasada: celda máxima para medir
		build_atlas(comp, v, chars)
	out = transform(comp, layout(comp, segs, W, H), W, H)
	for v, chars in need.items():                   # 2.ª: el atlas al tamaño de la letra más grande
		big = max([g['size'] for g in out if g['v'] == v] or [0.0])
		if big > 0.0 and big < atlas_info(comp, v)['f'] * 0.97:
			info = build_atlas(comp, v, chars, want=big)
			for g in out:
				if g['v'] == v:
					g['k'] = g['size'] / info['f']
	DATA[comp.path] = to_arrays(comp, out)
	gc = comp.op('glyph_chop')
	if gc is not None:
		gc.cook(force=True)
	st = comp.op('state')
	if st is not None:
		vals = (len(segs), len(out), atlas_info(comp, 0)['cell'], atlas_info(comp, 0)['bl'])
		for j, v in enumerate(vals):
			p = getattr(st.par, 'const%dvalue' % j)
			if p.eval() != v:
				p.val = v
	LAST[comp.path] = {'segs': len(segs), 'glyphs': len(out)}
	status(comp, len(segs), len(out), max([g['k'] for g in out] or [1.0]))
	comp.store('tg_key', watch_key(comp))
	wake(comp)
	return out


def moving(comp):
	"""¿Algo se anima? (la fase 2 lo redefine: recorrido, giro, pulso)."""
	return False


def wake(comp, frames=4):
	"""Render en vivo unos frames (los uniforms del GLSL MAT se evalúan una vez por frame) y luego congelado."""
	c = comp.op('cache_out')
	if c is not None and not c.par.active.eval():
		c.par.active = True
	cur = comp.fetch('tg_live', None, search=False)
	comp.store('tg_live', max(cur or 0, absTime.frame + frames))   # el plazo más largo (un fundido no se corta)


def watch_key(comp):
	"""Lo que no avisa al Parameter Execute: el contenido del Text DAT y el lienzo del proyecto."""
	d = pv(comp, 'Textdat', None)
	return (d.text if d is not None and hasattr(d, 'text') else None, canvas(comp))


def tick(comp):
	nb = comp.op('null_beats')
	if nb is not None and nb.numChans:
		comp.store('lg_beats', float(nb[0].eval()))  # textbankCTRL (Auto) lee el reloj de aquí
	if comp.fetch('tg_key', None, search=False) != watch_key(comp) or comp.path not in DATA:
		compose(comp)
	live = comp.fetch('tg_live', None, search=False)
	c = comp.op('cache_out')
	if moving(comp):
		if c is not None and not c.par.active.eval():
			c.par.active = True
	elif live is not None and absTime.frame >= live and c is not None:
		if c.par.active.eval():
			c.cook(force=True)                      # guarda la última imagen aunque nadie mire la salida
			c.par.active = False
		comp.unstore('tg_live')


def init(comp):
	CAP.clear()
	compose(comp)

# ---- build2: Path ----
PATHN = 1024
PATHS = {}                # comp.path → {'arr': (N, 4) x, y, tx, ty en px (centro de la forma = 0), 'L', 'closed', 'P', 'off'}
TAU = 2.0 * math.pi


def _ellipse(w, h, a):
	return np.stack([0.5 * w * np.cos(a), 0.5 * h * np.sin(a)], 1)


def _round_poly(V, rnd, seg=24):
	"""Polígono → contorno con las esquinas redondeadas (rnd 0–1 = fracción de media arista)."""
	if rnd <= 0.0:
		return np.asarray(V, dtype=np.float64)
	V = np.asarray(V, dtype=np.float64)
	n = len(V)
	out = []
	for i in range(n):
		a, v, b = V[i - 1], V[i], V[(i + 1) % n]
		ua, ub = a - v, b - v
		la, lb = np.linalg.norm(ua), np.linalg.norm(ub)
		ua, ub = ua / max(la, 1e-9), ub / max(lb, 1e-9)
		th = math.acos(max(-1.0, min(1.0, float(np.dot(ua, ub)))))
		bis = ua + ub
		bn = np.linalg.norm(bis)
		if bn < 1e-6 or th < 1e-3:
			out.append(v)
			continue
		bis /= bn
		d = rnd * 0.5 * min(la, lb)
		r = d * math.tan(th / 2.0)
		c = v + bis * (d / math.cos(th / 2.0))
		p1, p2 = v + ua * d, v + ub * d
		a1 = math.atan2(p1[1] - c[1], p1[0] - c[0])
		a2 = math.atan2(p2[1] - c[1], p2[0] - c[0])
		da = (a2 - a1 + math.pi) % TAU - math.pi
		t = np.linspace(0.0, 1.0, seg)
		out.extend(np.stack([c[0] + r * np.cos(a1 + da * t), c[1] + r * np.sin(a1 + da * t)], 1))
	return np.asarray(out)


def shape_points(comp, W, H):
	"""Contorno denso de la forma (px, centro = 0), en sentido horario desde arriba; (puntos, cerrada)."""
	S = float(min(W, H))
	sh = pv(comp, 'Pathshape', 'circle')
	SW, SH = (float(W), float(H)) if pv(comp, 'Pathsizeby', 'short') == 'cell' else (S, S)
	w = float(pv(comp, 'Pathw', 0.7)) * SW
	h = w if sh == 'circle' else float(pv(comp, 'Pathh', 0.5)) * SH
	M = 4096
	if sh in ('circle', 'ellipse'):
		a = 0.5 * math.pi - np.linspace(0.0, TAU, M, endpoint=False)
		return _ellipse(w, h, a), True
	if sh == 'arc':
		span = math.radians(float(pv(comp, 'Patharc', 180.0)))
		a = np.linspace(0.5 * math.pi + span / 2.0, 0.5 * math.pi - span / 2.0, M)
		return _ellipse(w, h, a), span >= TAU - 1e-6
	if sh in ('rectangle', 'polygon', 'star'):
		rnd = float(pv(comp, 'Pathround', 0.0))
		if sh == 'rectangle':
			V = [(-w / 2, h / 2), (w / 2, h / 2), (w / 2, -h / 2), (-w / 2, -h / 2)]
		elif sh == 'polygon':
			n = int(pv(comp, 'Pathsides', 6))
			V = _ellipse(w, h, 0.5 * math.pi - TAU * np.arange(n) / n)
		else:
			n = int(pv(comp, 'Pathsides', 6))
			k = np.arange(2 * n)
			r = np.where(k % 2 == 0, 1.0, float(pv(comp, 'Pathinner', 0.5)))
			a = 0.5 * math.pi - math.pi * k / n
			V = np.stack([0.5 * w * r * np.cos(a), 0.5 * h * r * np.sin(a)], 1)
		return _round_poly(V, rnd), True
	if sh == 'wave':
		x = np.linspace(-w / 2.0, w / 2.0, M)
		y = 0.5 * h * np.sin(TAU * float(pv(comp, 'Pathcycles', 2.0)) * (x / w + 0.5))
		return np.stack([x, y], 1), False
	if sh == 'spiral':
		t = np.linspace(0.0, 1.0, M)
		a = 0.5 * math.pi - TAU * float(pv(comp, 'Pathturns', 2.5)) * t
		r = 1.0 - (1.0 - float(pv(comp, 'Pathinner', 0.5))) * t
		return np.stack([0.5 * w * r * np.cos(a), 0.5 * h * r * np.sin(a)], 1), False
	t = np.linspace(0.0, TAU, M, endpoint=False)              # infinity (lemniscata de Gerono)
	return np.stack([0.5 * w * np.sin(t), h * np.sin(t) * np.cos(t)], 1), True


def build_path(comp, W, H):
	"""Muestreo uniforme por longitud de arco: N puntos con su tangente; empieza arriba en las cerradas."""
	pts, closed = shape_points(comp, W, H)
	P = np.vstack([pts, pts[:1]]) if closed else pts
	seg = np.linalg.norm(np.diff(P, axis=0), axis=1)
	cum = np.concatenate([[0.0], np.cumsum(seg)])
	L = float(cum[-1])
	N = PATHN
	s = np.linspace(0.0, L, N, endpoint=not closed)
	R = np.stack([np.interp(s, cum, P[:, 0]), np.interp(s, cum, P[:, 1])], 1)
	if closed and pv(comp, 'Pathshape', 'circle') != 'infinity':
		i0 = int(np.argmin(np.abs(np.arctan2(R[:, 0], R[:, 1]))))   # el punto más cercano a "arriba"
		R = np.roll(R, -i0, axis=0)
	if pv(comp, 'Pathdir', 'cw') == 'ccw':
		R = np.vstack([R[:1], R[1:][::-1]]) if closed else R[::-1]
	if closed:
		T = np.roll(R, -1, axis=0) - np.roll(R, 1, axis=0)
	else:
		T = np.gradient(R, axis=0)
	T /= np.maximum(np.linalg.norm(T, axis=1, keepdims=True), 1e-9)
	arr = np.concatenate([R, T], 1).astype(np.float32)
	PATHS[comp.path] = {'arr': arr, 'L': max(L, 1e-3), 'closed': closed, 'P': max(L, 1e-3), 'off': 0.0}
	return PATHS[comp.path]


def path_layout(comp, segs, W, H):
	"""Letras sobre el trazo: X = centro de la letra a lo largo del trazo (px), Y = desvío de la línea base,
	A = avance (el shader centra la letra en su punto)."""
	pd = build_path(comp, W, H)
	L, closed = pd['L'], pd['closed']
	size = float(pv(comp, 'Size', 0.1)) * H
	track = float(pv(comp, 'Tracking', 0.0))
	tr = track * size
	capr = cap_ratio(comp, 0)
	fill = pv(comp, 'Pathfill', 'natural')
	sep = str(pv(comp, 'Pathsep', ' · '))
	sepl = build_line(comp, [(sep, 0)], size, track, -1) if sep else {'g': [], 'w': 0.0, 'size': size, 'n': 0}
	# una tira: seg 1, sep, seg 2… (Fit y Repeat en una cerrada: separador también al final, en la junta)
	units = []
	for i, r in enumerate(segs):
		if i:
			units.append(sepl)
		units.append(build_line(comp, r, size, track, i))
	if not units:
		return []
	loop = fill == 'repeat' or (fill == 'fit' and closed)
	if loop and sep:
		units.append(sepl)
	g, x, gi, wd = [], 0.0, 0, 0
	for j, u in enumerate(units):
		for gg in u['g']:
			g.append(dict(gg, x=x + gg['x'], gi=gi + gg['ci'], word=wd + gg['word']))
		x += u['w'] + (tr if j < len(units) - 1 else 0.0)
		gi += u['n']
		wd += max([gg['word'] for gg in u['g']] or [0]) + 1
	Wt = x + (tr if loop else 0.0)                    # ancho de la tira (con la junta si da la vuelta)
	nch = max(gi, 1)

	def scale(f):
		for gg in g:
			gg['x'] *= f
			gg['k'] *= f
			gg['adv'] *= f
			gg['size'] *= f

	extra, copies, period, off = 0.0, 1, L, 0.0
	s0 = float(pv(comp, 'Pathstart', 0.0)) * L
	if fill == 'repeat':
		if Wt > L:
			scale(L / Wt)
			Wt = L
		if closed:
			copies = max(1, int(L // Wt))
			extra = (L - copies * Wt) / float(copies * nch)
			Wt += extra * nch
		else:
			copies = int(math.ceil(L / Wt)) + 1
			period = copies * Wt
	elif fill == 'fit':
		span = Wt if closed else (g[-1]['x'] + g[-1]['adv'] if g else Wt)
		if span > L:
			scale(L / span)
			span = L
		gaps = nch if closed else max(len(set(gg['gi'] for gg in g)) - 1, 1)
		if not closed:                                # de la primera letra (en 0) al final de la última (en L)
			idx = sorted(set(gg['gi'] for gg in g))
			rank = {v: k for k, v in enumerate(idx)}
			extra = (L - span) / float(max(len(idx) - 1, 1))
			for gg in g:
				gg['gi'] = rank[gg['gi']]
		else:
			extra = (L - span) / float(gaps)
		if not closed:
			period, off = L + span, span
	else:                                             # natural
		avail = L - (sepl['w'] + 2.0 * tr if closed else 0.0)
		if Wt > avail:
			scale(avail / Wt)
			Wt = avail
		al = pv(comp, 'Pathalign', 'center')
		if closed:
			s0 -= {'start': 0.0, 'center': Wt / 2.0, 'end': Wt}[al]
		else:
			s0 += {'start': 0.0, 'center': (L - Wt) / 2.0, 'end': L - Wt}[al]
			period, off = L + Wt, Wt
	pd['P'], pd['off'] = max(period, 1e-3), off
	side = pv(comp, 'Pathside', 'above')
	out = []
	for c in range(copies):
		base = s0 + c * Wt
		for gg in g:
			cap = capr * gg['size']
			y = 0.0 if side == 'above' else (-cap / 2.0 if side == 'center' else -cap)
			out.append(dict(gg, X=base + gg['x'] + gg['gi'] * extra + gg['adv'] / 2.0, Y=y, A=gg['adv'], P=True, cp=c))
	return out


_variants_b1 = variants


def variants(comp, segs):
	"""+ los caracteres del separador (también van al atlas de la fuente base)."""
	need = _variants_b1(comp, segs)
	if pv(comp, 'Composition', 'center') == 'path':
		need.setdefault(0, set()).update(str(pv(comp, 'Pathsep', '')))
	return need


_layout_b1 = layout


def layout(comp, segs, W, H):
	if pv(comp, 'Composition', 'center') == 'path':
		return path_layout(comp, segs, W, H)
	return _layout_b1(comp, segs, W, H)


def fill_path(scriptOp):
	"""onCook de path_tex: el trazo muestreado (1 fila × N, rgba32f)."""
	pd = PATHS.get(scriptOp.parent().path)
	arr = pd['arr'] if pd is not None else np.zeros((PATHN, 4), dtype=np.float32)
	scriptOp.copyNumpyArray(arr.reshape(1, PATHN, 4).astype(np.float32))


def path_state(comp):
	"""Longitud, periodo, desvío, cerrada y nº de segmentos a dibujar → state (los leen los uniforms)."""
	pd = PATHS.get(comp.path)
	if pd is None:
		W, H = layout_size(comp)
		pd = build_path(comp, W, H)
	st = comp.op('state')
	vals = {'pathlen': pd['L'], 'pathperiod': pd['P'], 'pathoff': pd['off'], 'pathclosed': float(pd['closed']),
			'pathsegs': float(PATHN if pd['closed'] else PATHN - 1)}
	for j in range(st.seq.const.numBlocks):
		n = getattr(st.par, 'const%dname' % j).eval()
		if n in vals:
			p = getattr(st.par, 'const%dvalue' % j)
			if abs(float(p.eval()) - vals[n]) > 1e-4:
				p.val = vals[n]
	pt = comp.op('path_tex')
	if pt is not None:
		pt.cook(force=True)


_compose_b1 = compose


def compose(comp):
	W, H = layout_size(comp)
	if pv(comp, 'Composition', 'center') != 'path':
		build_path(comp, W, H)                        # el trazo existe igual (Show Path lo ignora fuera de Path)
	out = _compose_b1(comp)
	path_state(comp)
	return out


def path_center(comp):
	W, H = layout_size(comp)
	return W / 2.0 + float(pv(comp, 'Posx', 0.0)) * W, H / 2.0 + float(pv(comp, 'Posy', 0.0)) * H


def motion_rate(comp, which):
	"""Vueltas por segundo de Travel / Spin (vueltas por compás de 4 beats)."""
	if pv(comp, 'Composition', 'center') != 'path':
		return 0.0
	v = float(pv(comp, 'Pathtravel' if which == 'travel' else 'Pathspin', 0.0))
	return v * rate(comp) / 4.0


def moving(comp):
	if pv(comp, 'Composition', 'center') != 'path':
		return False
	return (float(pv(comp, 'Pathtravel', 0.0)) != 0.0 or float(pv(comp, 'Pathspin', 0.0)) != 0.0
			or float(pv(comp, 'Pathpulse', 0.0)) > 0.0)

# ---- build3: Highlight / Pill ----
DECO = {}                 # comp.path → arrays de adornos (una caja por muestra)
DCHANS = [['dx', 'dy', 'da', 'dm'], ['dl', 'dh', 'dw', 'dr'], ['kr', 'kg', 'kb', 'ka'], ['dk', 'd1', 'd2', 'd3']]
LINE_ID = [0]
FILL, RECT, OVAL = 0.0, 1.0, 2.0


def font_prefix(v):
	return '' if v == 0 else 'H%d' % v


def _font_to(t, comp, P):
	"""Fuente del atlas: la base (Font / Typeface / Fontfile) o la del destacado (H1font / H1typeface…)."""
	nm = (lambda n: n) if not P else (lambda n: P + n.lower())
	ff = str(pv(comp, nm('Fontfile'), '')).strip()
	if t.par.fontfile.eval() != ff:
		t.par.fontfile = ff
	font = str(pv(comp, nm('Font'), 'Arial')).strip() or 'Arial'
	if t.par.font.eval() != font:
		t.par.font = font
	tf = str(pv(comp, nm('Typeface'), 'Regular'))
	names = list(t.par.typeface.menuNames)
	if names and tf not in names:
		tf = 'Regular' if 'Regular' in names else names[0]
	if t.par.typeface.eval() != tf:
		t.par.typeface = tf


def style_var(comp, st):
	return st if st in (1, 2) and pv(comp, 'H%dusefont' % st, False) else 0


def style_size(comp, st):
	if st in (1, 2) and pv(comp, 'H%dusesize' % st, False):
		return float(pv(comp, 'H%dsize' % st, 1.3))
	return 1.0


_style_color_b1 = style_color


def style_color(comp, st):
	if st in (1, 2) and pv(comp, 'H%dusecolor' % st, False):
		P = 'H%dcolor' % st
		return tuple(float(pv(comp, P + c, 1.0)) for c in 'rgba')
	return _style_color_b1(comp, st)


_build_line_b2 = build_line


def build_line(comp, runs, size, track, seg):
	"""+ un id por línea (lid): los adornos agrupan por línea, palabra y estilo."""
	L = _build_line_b2(comp, runs, size, track, seg)
	LINE_ID[0] += 1
	for g in L['g']:
		g['lid'] = LINE_ID[0]
	return L


# ---- adornos ----
def _rgba(comp, P):
	return tuple(float(pv(comp, P + c, 1.0)) for c in 'rgba')


def _groups(out, pred, unit):
	"""Grupos de letras: word / span (seguidas) o segment / block (aunque haya letras sin adorno entre medias)."""
	groups, cur, prev_key, prev_i = [], None, None, -2
	for i, g in enumerate(out):
		if g.get('seg', 0) < 0 or not pred(g):             # el separador de Path no lleva adornos
			continue
		cp, lid = g.get('cp', 0), g.get('lid', 0)
		if unit == 'block':
			key = (cp,)                               # una por copia de Repeat y por celda del Grid
		elif unit == 'segment':
			key = (cp, lid)
		elif unit == 'word':
			key = (cp, lid, g['word'], g['st'])
		else:
			key = (cp, lid, g['st'])
		together = unit in ('block', 'segment') or i == prev_i + 1
		if cur is not None and key == prev_key and together:
			cur.append(g)
		else:
			cur = [g]
			groups.append(cur)
		prev_key, prev_i = key, i
	return groups


def _box(comp, grp):
	"""Caja de un grupo en su marco local: x a lo largo de la línea (o del trazo), y desde la línea base."""
	cap = max(cap_ratio(comp, g['v']) * g['size'] for g in grp)
	size = max(g['size'] for g in grp)
	if grp[0].get('P'):
		x0 = min(g['X'] - g['adv'] / 2.0 for g in grp)
		x1 = max(g['X'] + g['adv'] / 2.0 for g in grp)
		y0 = min(g['Y'] for g in grp)
		return {'P': True, 'x0': x0, 'x1': x1, 'y0': y0, 'y1': y0 + cap, 'size': size}
	g0 = grp[0]
	a = g0.get('A', 0.0)
	c, s = math.cos(a), math.sin(a)
	xs = [(g['X'] - g0['X']) * c + (g['Y'] - g0['Y']) * s for g in grp]
	ys = [-(g['X'] - g0['X']) * s + (g['Y'] - g0['Y']) * c for g in grp]
	return {'P': False, 'ox': g0['X'], 'oy': g0['Y'], 'a': a, 'size': size,
			'x0': min(xs), 'x1': max(x + g['adv'] for x, g in zip(xs, grp)), 'y0': min(ys), 'y1': max(ys) + cap}


def _emit(D, b, cx, cy, hl, hh, w, rnd, col, kind):
	if b['P']:
		X, Y, A = cx, cy, 0.0
	else:
		c, s = math.cos(b['a']), math.sin(b['a'])
		X, Y, A = b['ox'] + cx * c - cy * s, b['oy'] + cx * s + cy * c, b['a']
	D.append((X, Y, A, 0.0, max(hl, 0.0), max(hh, 0.0), w, rnd) + tuple(col) + (kind, 0.0, 0.0, 0.0))


def decorations(comp, out):
	"""Pastillas (debajo), subrayados y contornos → una caja por muestra."""
	D = []
	if pv(comp, 'Pill', False):
		ap = pv(comp, 'Pillapply', 'all')
		pred = {'all': lambda g: True, 'hl': lambda g: g['st'] > 0, 'hl1': lambda g: g['st'] == 1,
				'hl2': lambda g: g['st'] == 2, 'plain': lambda g: g['st'] == 0}[ap]
		col = _rgba(comp, 'Pillcolor')
		for grp in _groups(out, pred, pv(comp, 'Pillunit', 'word')):
			b = _box(comp, grp)
			sz = b['size']
			_emit(D, b, (b['x0'] + b['x1']) / 2.0 + float(pv(comp, 'Pilloffx', 0.0)) * sz,
				  (b['y0'] + b['y1']) / 2.0 + float(pv(comp, 'Pilloffy', 0.0)) * sz,
				  (b['x1'] - b['x0']) / 2.0 + float(pv(comp, 'Pillpadx', 0.25)) * sz,
				  (b['y1'] - b['y0']) / 2.0 + float(pv(comp, 'Pillpady', 0.2)) * sz,
				  0.0, float(pv(comp, 'Pillround', 1.0)), col, FILL)
	for st in (1, 2):
		P = 'H%d' % st
		ul, ol = pv(comp, P + 'underline', False), pv(comp, P + 'outline', False)
		if not (ul or ol):
			continue
		for grp in _groups(out, lambda g, st=st: g['st'] == st, pv(comp, P + 'scope', 'span')):
			b = _box(comp, grp)
			sz = b['size']
			cx, hx = (b['x0'] + b['x1']) / 2.0, (b['x1'] - b['x0']) / 2.0
			if ul:
				w = float(pv(comp, P + 'ulwidth', 0.06)) * sz
				_emit(D, b, cx, b['y0'] - float(pv(comp, P + 'uloffset', 0.12)) * sz - w / 2.0,
					  hx + float(pv(comp, P + 'ulextend', 0.0)) * sz, w / 2.0, 0.0, 0.0, _rgba(comp, P + 'ulcolor'), FILL)
			if ol:
				oval = pv(comp, P + 'outshape', 'rect') == 'oval'
				hl = hx + float(pv(comp, P + 'outpadx', 0.2)) * sz
				hh = (b['y1'] - b['y0']) / 2.0 + float(pv(comp, P + 'outpady', 0.2)) * sz
				if oval:                                      # pasa por las esquinas de la caja, ceñido a lo ancho:
					rx = hl + 0.9 * hh                        # rx = semiancho + 0,9 × semialto; ry lo que haga falta
					hh = hh / math.sqrt(max(1.0 - (hl / rx) ** 2, 1e-4))
					hl = rx
				_emit(D, b, cx, (b['y0'] + b['y1']) / 2.0, hl, hh, float(pv(comp, P + 'outwidth', 0.04)) * sz,
					  float(pv(comp, P + 'outround', 0.0)), _rgba(comp, P + 'outcolor'), OVAL if oval else RECT)
	n = max(len(D), 1)
	a = {ch: np.zeros(n, dtype=np.float32) for blk in DCHANS for ch in blk}
	names = [ch for blk in DCHANS for ch in blk]
	for i, row in enumerate(D):
		for ch, v in zip(names, row):
			a[ch][i] = v
	DECO[comp.path] = a
	return len(D)


def fill_deco(scriptOp):
	"""onCook de deco_chop: una caja por muestra (sin adornos: una invisible)."""
	a = DECO.get(scriptOp.parent().path)
	scriptOp.clear()
	scriptOp.isTimeSlice = False
	scriptOp.numSamples = len(a['dx']) if a is not None else 1
	for blk in DCHANS:
		for ch in blk:
			c = scriptOp.appendChan(ch)
			if a is not None:
				c.copyNumpyArray(a[ch])


_compose_b2 = compose


def compose(comp):
	out = _compose_b2(comp)
	st = comp.op('state')
	vals = {'atlascell1': atlas_info(comp, 1)['cell'], 'atlasbl1': atlas_info(comp, 1)['bl'],
			'atlascell2': atlas_info(comp, 2)['cell'], 'atlasbl2': atlas_info(comp, 2)['bl'],
			'highlights': float(sum(1 for g in out if g['st'] > 0)), 'decos': float(decorations(comp, out))}
	for j in range(st.seq.const.numBlocks):
		n = getattr(st.par, 'const%dname' % j).eval()
		if n in vals:
			p = getattr(st.par, 'const%dvalue' % j)
			if abs(float(p.eval()) - vals[n]) > 1e-4:
				p.val = vals[n]
	dc = comp.op('deco_chop')
	if dc is not None:
		dc.cook(force=True)
	return out

# ---- build4: Grid ----
GRID = {}                 # comp.path → celdas, reparto y rangos de Coverage
LINES = {}                # comp.path → Rows Mode Lines: tamaño real de la letra y lo que ocupa una línea (lo, hi) en px
SEGL = {}                 # comp.path → maquetas en caché (Distribute: una por segmento; Repeat: la base)
MAXCELLS = 256
CHANS.append(['cl'])                                # celda de cada letra (el bloque 3 de la instancia: st, cl, sg, ix)


def grid_on(comp):
	return bool(pv(comp, 'Grid', False))


def gstate(comp):
	g = GRID.get(comp.path)
	if g is None:
		g = GRID[comp.path] = {'cov_seed': 0, 'origin': None, 'flip': False, 'text_seed': 0, 'shift': 0,
							   'from': None, 'to': None, 't0': -1e9, 'last_k': None, 'hits': 0, 'hit_t': -1.0}
	return g


def cell_rects(comp):
	"""Celdas (x0, y0, ancho, alto) en px, origen abajo-izquierda; la celda 0 arriba a la izquierda."""
	W, H = canvas(comp)
	if not grid_on(comp):
		return [(0.0, 0.0, float(W), float(H))]
	cols, rows = int(pv(comp, 'Gridcols', 3)), int(pv(comp, 'Gridrows', 3))
	S = float(min(W, H))
	m, gap, gapy = (float(pv(comp, n, 0.0)) * S for n in ('Gridmargin', 'Gridgap', 'Gridgapy'))
	cw = max((W - 2.0 * m - gap * (cols - 1)) / cols, 4.0)
	out = []
	if pv(comp, 'Gridrowsmode', 'divide') == 'lines':
		return [(m + c * (cw + gap), y - H / 2.0, cw, float(H)) for y in line_centers(comp, W, H, rows, cols) for c in range(cols)]
	ch = max((H - 2.0 * m - gapy * (rows - 1)) / rows, 4.0)
	for r in range(rows):
		for c in range(cols):
			out.append((m + c * (cw + gap), H - m - (r + 1) * ch - r * gapy, cw, ch))
	return out[:MAXCELLS]


def line_centers(comp, W, H, rows, cols):
	"""Rows Mode Lines: centro (y, px) de cada fila, de arriba abajo, a Line Distance × tamaño real de la letra.
	Fill Canvas: una fila en el centro del lienzo y todas las que asomen por arriba y por abajo."""
	L = LINES.get(comp.path)
	if L is None:
		s = float(pv(comp, 'Size', 0.1)) * H
		L = {'size': s, 'lo': -s, 'hi': s}
	step = max(float(pv(comp, 'Gridline', 0.9)) * L['size'], 2.0)
	top = max(MAXCELLS // max(cols, 1), 1)
	if pv(comp, 'Gridfillcanvas', True):
		k0 = int(math.ceil((-H / 2.0 - L['hi']) / step))      # fila k en y = H / 2 + k · step: se ve si lo … hi la cruza
		k1 = int(math.floor((H / 2.0 - L['lo']) / step))
		if k1 - k0 + 1 > top:
			k0 = -(top // 2)
			k1 = k0 + top - 1
		if k1 < k0:
			k0 = k1 = 0
		return [H / 2.0 + k * step for k in range(k1, k0 - 1, -1)]
	n = min(rows, top)
	return [H / 2.0 + ((n - 1) / 2.0 - r) * step for r in range(n)]


def line_metrics(comp, out):
	"""Tamaño real de la letra base (tras reducirse si no cabía) y alto que ocupa una línea respecto a su centro."""
	H = layout_size(comp)[1]
	base = [g for g in out if g['st'] == 0 and g.get('seg', 0) >= 0] or out
	if not base:
		LINES.pop(comp.path, None)
		return
	size = max(g['size'] for g in base)
	big = max(g['size'] for g in out)
	cap = max(cap_ratio(comp, g['v']) * g['size'] for g in out)
	y0, y1 = min(g['Y'] for g in out), max(g['Y'] for g in out)
	if out[0].get('P'):
		arr = PATHS[comp.path]['arr']
		d = comp.op('audiomod')
		md = (lambda n: d is not None and getattr(comp.par, 'M1src', None) is not None and d.module.modded(comp, n))
		if float(pv(comp, 'Pathspin', 0.0)) or md('Pathspin') or md('Pathrot'):     # gira: el radio
			r = float(np.hypot(arr[:, 0], arr[:, 1]).max())
			p0, p1 = -r, r
		else:
			a = math.radians(float(pv(comp, 'Pathrot', 0.0)) + float(pv(comp, 'Rotate', 0.0)))
			y = arr[:, 0] * math.sin(a) + arr[:, 1] * math.cos(a)
			p0, p1 = float(y.min()), float(y.max())
		k = 2.0 if md('Pathpulse') else 1.0 + max(float(pv(comp, 'Pathpulse', 0.0)), 0.0)
		off = float(pv(comp, 'Posy', 0.0)) * H
		lo, hi = p0 * k + off + y0 - 0.2 * big, p1 * k + off + y1 + cap
	else:
		lo, hi = y0 - H / 2.0 - 0.2 * big, y1 - H / 2.0 + cap
	LINES[comp.path] = {'size': size, 'lo': lo, 'hi': hi}


def layout_size(comp):
	if grid_on(comp) and pv(comp, 'Gridrowsmode', 'divide') == 'lines':
		W, H = canvas(comp)
		cols, S = int(pv(comp, 'Gridcols', 3)), float(min(W, H))
		m, gap = float(pv(comp, 'Gridmargin', 0.0)) * S, float(pv(comp, 'Gridgap', 0.0)) * S
		return max((W - 2.0 * m - gap * (cols - 1)) / cols, 4.0), float(H)
	r = cell_rects(comp)[0]
	return r[2], r[3]


def path_center(comp):
	W, H = layout_size(comp)
	return W / 2.0 + float(pv(comp, 'Posx', 0.0)) * W, H / 2.0 + float(pv(comp, 'Posy', 0.0)) * H


def assignment(comp, nseg, ncell):
	"""Segmento de cada celda (−1 = vacía)."""
	g = gstate(comp)
	if nseg == 0:
		return [-1] * ncell
	fill = pv(comp, 'Gridfill', 'cycle')
	if pv(comp, 'Gridorder', 'sequential') == 'random':
		rng = np.random.default_rng(int(pv(comp, 'Gridseed', 1)) * 7919 + g['text_seed'])
		if fill == 'empty':
			p = rng.permutation(max(nseg, ncell))
			return [int(x) if x < nseg else -1 for x in p[:ncell]]
		seq = []
		while len(seq) < ncell:                       # vueltas barajadas, sin repetir en la junta
			p = list(rng.permutation(nseg))
			if seq and nseg > 1 and p[0] == seq[-1]:
				p.append(p.pop(0))
			seq.extend(p)
		return [int(x) for x in seq[:ncell]]
	sh = g['shift']
	if fill == 'empty':
		return [(i + sh) % max(nseg, ncell) if (i + sh) % max(nseg, ncell) < nseg else -1 for i in range(ncell)]
	return [(i + sh) % nseg for i in range(ncell)]


_layout_b3 = layout


def layout(comp, segs, W, H):
	"""Con Grid: cada maqueta una sola vez (Repeat: la base; Distribute: una por segmento), en coordenadas de
	celda; las celdas se rellenan después copiando arrays (to_arrays / decorations → tile)."""
	if not grid_on(comp):
		out = _layout_b3(comp, segs, W, H)
		for gl in out:
			gl['cell'] = 0
			gl['unit'] = 0
		return out
	dist = pv(comp, 'Gridmode', 'repeat') == 'distribute'
	units, per = [], []
	for ss in ([[s] for s in segs] if dist else [segs]):
		units.append(fit_cell(comp, _layout_b3(comp, ss, W, H), W, H))
		pd = PATHS.get(comp.path, {})
		per.append((pd.get('P', 1.0), pd.get('off', 0.0)))    # cada texto da la vuelta en su propio periodo
	SEGL[comp.path] = {'mode': 'distribute' if dist else 'repeat', 'nunits': len(units), 'per': per}
	out = []
	for u, L in enumerate(units):
		for gl in L:
			seg = (u if gl.get('seg', 0) >= 0 else gl['seg']) if dist else gl.get('seg', 0)
			out.append(dict(gl, unit=u, cell=u, cp=(gl.get('cp', 0), u), seg=seg))
	return out


def fit_cell(comp, out, W, H):
	"""Fit Text to Cell: si las letras se salen de la celda (menos Margin), se reducen desde su centro."""
	if not out or out[0].get('P') or not pv(comp, 'Gridfit', True):
		return out
	xs, ys = [], []
	for gl in out:
		c, s = math.cos(gl.get('A', 0.0)), math.sin(gl.get('A', 0.0))
		cap = cap_ratio(comp, gl['v']) * gl['size']
		for u, v in ((0.0, 0.0), (gl['adv'], 0.0), (0.0, cap), (gl['adv'], cap)):
			xs.append(gl['X'] + u * c - v * s)
			ys.append(gl['Y'] + u * s + v * c)
	m = float(pv(comp, 'Margin', 0.06)) * min(W, H)
	f = min(1.0, (W - 2.0 * m) / max(max(xs) - min(xs), 1e-3), (H - 2.0 * m) / max(max(ys) - min(ys), 1e-3))
	if f >= 1.0:
		return out
	cx, cy = W / 2.0, H / 2.0
	return [dict(gl, X=cx + (gl['X'] - cx) * f, Y=cy + (gl['Y'] - cy) * f, k=gl['k'] * f, size=gl['size'] * f,
				 adv=gl['adv'] * f) for gl in out]


def cell_units(comp):
	"""Maqueta (unidad) de cada celda: Repeat = todas la 0; Distribute = el reparto (−1 = vacía)."""
	n = len(cell_rects(comp))
	c = SEGL.get(comp.path, {})
	if c.get('mode') == 'distribute':
		return assignment(comp, c.get('nunits', 0), n)
	return [0] * n


def cell_periods(comp, units):
	"""(periodo, desvío) del recorrido de cada celda: los de su texto."""
	per = SEGL.get(comp.path, {}).get('per') or [(1.0, 0.0)]
	return [per[u] if 0 <= u < len(per) else per[0] for u in units]


def _tile(comp, a, unit, xkey, cellkey):
	"""Arrays de las unidades → arrays de todas las celdas (numpy); Stagger suma a la posición en el trazo."""
	units = cell_units(comp)
	where = {}
	I, C = [], []
	for i, u in enumerate(units):
		if u < 0:
			continue
		if u not in where:
			where[u] = np.nonzero(unit == u)[0]
		if len(where[u]):
			I.append(where[u])
			C.append(np.full(len(where[u]), i, dtype=np.float32))
	if not I:
		b = {ch: v[:1].copy() for ch, v in a.items()}
		for ch in ('gk', 'ca', 'ka', 'dl', 'dh'):
			if ch in b:
				b[ch][:] = 0.0
		return b, 0
	I, C = np.concatenate(I), np.concatenate(C)
	b = {ch: v[I] for ch, v in a.items()}
	b[cellkey] = C
	stag = float(pv(comp, 'Gridstagger', 0.0))
	if stag and pv(comp, 'Composition', 'center') == 'path':
		per = cell_periods(comp, units)
		b[xkey] = b[xkey] + C * stag * np.array([q[0] for q in per], dtype=np.float32)[C.astype(np.int64)]
	return b, len(I)


_to_arrays_b1 = to_arrays


def to_arrays(comp, out):
	a = _to_arrays_b1(comp, out)
	a['cl'] = np.zeros_like(a['st'])
	if not grid_on(comp) or not out:
		return a
	line_metrics(comp, out)
	SEGL.setdefault(comp.path, {})['ga'] = (a, np.array([gl.get('unit', 0) for gl in out]))
	b, n = _tile(comp, a, SEGL[comp.path]['ga'][1], 'gx', 'cl')
	SEGL[comp.path]['nglyphs'] = n
	return b


_decorations_b3 = decorations


def decorations(comp, out):
	n = _decorations_b3(comp, out)
	if not grid_on(comp) or not n:
		SEGL.get(comp.path, {}).pop('da', None)       # sin adornos: que un nuevo reparto no traiga los viejos
		return n
	a = DECO[comp.path]
	SEGL.setdefault(comp.path, {})['da'] = (a, a['d1'].astype(np.int64))
	DECO[comp.path], m = _tile(comp, a, SEGL[comp.path]['da'][1], 'dx', 'd1')
	return m


_box_b3 = _box


def _box(comp, grp):
	b = _box_b3(comp, grp)
	b['cell'] = grp[0].get('cell', 0)
	return b


def _emit(D, b, cx, cy, hl, hh, w, rnd, col, kind):
	"""(build3 + la celda en el bloque 3: d1)"""
	if b['P']:
		X, Y, A = cx, cy, 0.0
	else:
		c, s = math.cos(b['a']), math.sin(b['a'])
		X, Y, A = b['ox'] + cx * c - cy * s, b['oy'] + cx * s + cy * c, b['a']
	D.append((X, Y, A, 0.0, max(hl, 0.0), max(hh, 0.0), w, rnd) + tuple(col) + (kind, float(b.get('cell', 0)), 0.0, 0.0))


# ---- Coverage: un rango 0–1 por celda (el shader compara con la cobertura) ----
def ranks(comp):
	rects = cell_rects(comp)
	n = len(rects)
	g = gstate(comp)
	order = pv(comp, 'Gridcovorder', 'center')
	cx = np.array([r[0] + r[2] / 2.0 for r in rects])
	cy = np.array([r[1] + r[3] / 2.0 for r in rects])
	jitter = np.random.default_rng(int(pv(comp, 'Gridseed', 1)) + 17 * g['cov_seed']).random(n) * 1e-3
	if order == 'random':
		key = np.random.default_rng(int(pv(comp, 'Gridseed', 1)) * 7919 + g['cov_seed']).random(n)
	elif order in ('center', 'edges'):
		W, H = canvas(comp)
		o = g['origin']
		ox, oy = (cx[o], cy[o]) if o is not None and o < n else (W / 2.0, H / 2.0)
		key = np.hypot(cx - ox, cy - oy) + jitter
		if order == 'edges':
			key = -key
	elif order == 'lr':
		key = cx * 1e3 - cy
	else:
		key = -cy * 1e3 + cx
	if order in ('lr', 'tb') and g['flip']:
		key = -key
	idx = np.argsort(key, kind='stable')
	r = np.zeros(n, dtype=np.float32)
	r[idx] = (np.arange(n, dtype=np.float32) + 0.5) / float(max(n, 1))   # centro de su tramo: se ven round(Coverage × n)
	return r


def cells_update(comp, t0=None):
	"""Rangos (de → a, desde el beat t0) y orígenes de las celdas → cell_tex."""
	g = gstate(comp)
	new = ranks(comp)
	if t0 is None or g['to'] is None or len(g['to']) != len(new):
		g['from'], g['to'], g['t0'] = new, new, -1e9
	else:
		g['from'], g['to'], g['t0'] = g['to'], new, t0
	ct = comp.op('cell_tex')
	if ct is not None:
		ct.cook(force=True)


def fill_cells(scriptOp):
	"""onCook de cell_tex: fila 0 = (rango de, rango a, beat de inicio, sentido del Travel ±1);
	fila 1 = (origen x0, y0 en px, periodo y desvío del recorrido de su texto)."""
	comp = scriptOp.parent()
	rects = cell_rects(comp)
	n = len(rects)
	g = gstate(comp)
	a = np.zeros((2, max(n, 1), 4), dtype=np.float32)
	if g['to'] is not None and len(g['to']) == n:
		a[0, :n, 0] = g['from']
		a[0, :n, 1] = g['to']
		a[0, :n, 2] = g['t0']
	per = cell_periods(comp, cell_units(comp)) if grid_on(comp) else [(1.0, 0.0)] * n
	cols = max(int(pv(comp, 'Gridcols', 3)), 1)
	alt = bool(pv(comp, 'Gridalt', False))
	for i, r in enumerate(rects):
		a[0, i, 3] = -1.0 if alt and (i // cols) % 2 else 1.0
		a[1, i] = (r[0], r[1], per[i][0], per[i][1])
	scriptOp.copyNumpyArray(a)


def grid_uniforms(comp):
	"""uCov = (fuente, Coverage, Min, Max); uCov2 = (Softness, Every, Cycle, fundido en beats);
	uGrid = (Grid, nº de celdas (CHOP state), segmentos del trazo, ·)."""
	src = ['manual', 'audio', 'build', 'pulse'].index(pv(comp, 'Gridcovsource', 'manual'))
	on = grid_on(comp)
	return ((float(src) if on else 0.0), (float(pv(comp, 'Gridcoverage', 1.0)) if on else 1.0),
			float(pv(comp, 'Gridcovmin', 0.0)), float(pv(comp, 'Gridcovmax', 1.0)),
			float(pv(comp, 'Gridcovsoft', 0.0)), float(pv(comp, 'Gridcovevery', '1')), float(pv(comp, 'Gridcovcycle', '4')),
			float(pv(comp, 'Gridfade', '0.5')), float(on))


# ---- cambios a beat / con el golpe ----
def beats_now(comp):
	nb = comp.op('null_beats')
	return float(nb[0].eval()) if nb is not None and nb.numChans else 0.0


def change(comp, manual=False):
	"""Change: otras celdas (semilla / origen / sentido, con fundido) y / o otro reparto de textos.
	Change Now con Change = Off hace las dos cosas."""
	if not grid_on(comp):
		return
	what = pv(comp, 'Gridchange', 'off')
	if manual and what == 'off':
		what = 'both'
	g = gstate(comp)
	n = len(cell_rects(comp))
	if what in ('cells', 'both'):
		order = pv(comp, 'Gridcovorder', 'center')
		if order == 'random':
			g['cov_seed'] += 1
		elif order in ('center', 'edges'):
			rng = np.random.default_rng(int(pv(comp, 'Gridseed', 1)) * 31 + g['cov_seed'])
			g['cov_seed'] += 1
			cand = [i for i in range(n) if i != g['origin']] or [0]
			g['origin'] = int(rng.choice(cand))
		else:
			g['flip'] = not g['flip']
		cells_update(comp, t0=beats_now(comp))
		fade = float(pv(comp, 'Gridfade', '0.5'))
		frames = int(fade / max(rate(comp), 1e-3) * project.cookRate) + 4
		wake(comp, frames)
	if what in ('text', 'both') and pv(comp, 'Gridmode', 'repeat') == 'distribute':
		if pv(comp, 'Gridorder', 'sequential') == 'random':
			g['text_seed'] += 1
		else:
			g['shift'] += 1
		reassign(comp)


def reassign(comp):
	"""Otro reparto de textos: solo se vuelven a rellenar las celdas desde los arrays de las maquetas."""
	c = SEGL.get(comp.path, {})
	if 'ga' not in c:
		compose(comp)
		return
	DATA[comp.path], n = _tile(comp, c['ga'][0], c['ga'][1], 'gx', 'cl')
	comp.op('glyph_chop').cook(force=True)
	nd = 0
	if 'da' in c:
		DECO[comp.path], nd = _tile(comp, c['da'][0], c['da'][1], 'dx', 'd1')
		comp.op('deco_chop').cook(force=True)
	comp.op('cell_tex').cook(force=True)              # el periodo de cada celda es el de su texto
	st = comp.op('state')
	st.par.const1value = n
	for j in range(st.seq.const.numBlocks):
		if getattr(st.par, 'const%dname' % j).eval() == 'decos':
			getattr(st.par, 'const%dvalue' % j).val = nd
	wake(comp)


def trig_has(comp, kind):
	t = pv(comp, 'Gridtrigger', 'beat')
	return t == kind or t == 'both'


def grid_tick(comp):
	"""Cada frame (µs): ¿ha empezado otro bloque de Every beats?"""
	if not grid_on(comp) or pv(comp, 'Gridchange', 'off') == 'off' or not trig_has(comp, 'beat'):
		return
	g = gstate(comp)
	k = int(beats_now(comp) // max(float(pv(comp, 'Gridevery', '4')), 1e-3))
	if g['last_k'] is None:
		g['last_k'] = k                               # al activar, espera al siguiente
	elif k != g['last_k']:
		g['last_k'] = k
		change(comp)


# ---- audio (1.1: audio común, audiomod) ----
def val(comp, name):
	"""El par o su Modulate: audiomod reescribe las lecturas de los destinos a val()."""
	d = comp.op('audiomod')
	return d.module.val(comp, name) if d is not None else comp.par[name].eval()


def am_moving(comp):
	"""¿Algún slot de Modulate actúa? (entonces el render no se congela)."""
	d = comp.op('audiomod')
	if d is None or getattr(comp.par, 'M1src', None) is None:
		return False
	m = d.module
	return any(val(comp, 'M%dsrc' % i) != 'off' and m._acts(comp, i) for i in range(1, m.SLOTS + 1))


def on_hit_extra(comp):
	"""Desde audiomod.on_hit (ya ha contado el golpe: CHOP hit, Hits, mínimo 0,12 s); cada Every N Hits, Change."""
	if not pv(comp, 'Audio', False):
		return
	g = gstate(comp)
	g['hits'] += 1
	if grid_on(comp) and pv(comp, 'Gridchange', 'off') != 'off' and trig_has(comp, 'hit'):
		if g['hits'] % max(int(pv(comp, 'Hitevery', 1)), 1) == 0:
			change(comp)


_moving_b2 = moving


def moving(comp):
	if _moving_b2(comp) or am_moving(comp):
		return True
	return grid_on(comp) and pv(comp, 'Gridcovsource', 'manual') != 'manual'


_tick_b1 = tick


def tick(comp):
	_tick_b1(comp)
	grid_tick(comp)


_compose_b3 = compose


def compose(comp):
	out = _compose_b3(comp)
	if grid_on(comp) and 'nglyphs' in SEGL.get(comp.path, {}):
		comp.op('state').par.const1value = SEGL[comp.path]['nglyphs']
	cells_update(comp)
	st = comp.op('state')
	for j in range(st.seq.const.numBlocks):
		if getattr(st.par, 'const%dname' % j).eval() == 'cells':
			getattr(st.par, 'const%dvalue' % j).val = len(cell_rects(comp))
	return out


# ---- audiomod: pv por val ----
def pv(comp, name, default=None):
	p = getattr(comp.par, name, None)
	return default if p is None else val(comp, name)
cell_cb python · 7 línieslíneaslines
def onSetupParameters(scriptOp):
	return

def onCook(scriptOp):
	op('util').module.fill_cells(scriptOp)
	return
deco_cb python · 10 línieslíneaslines
def onSetupParameters(scriptOp):
	return

def onPulse(par):
	return

def onCook(scriptOp):
	op('util').module.fill_deco(scriptOp)
	return
path_cb python · 7 línieslíneaslines
def onSetupParameters(scriptOp):
	return

def onCook(scriptOp):
	op('util').module.fill_path(scriptOp)
	return
glyph_cb python · 10 línieslíneaslines
def onSetupParameters(scriptOp):
	return

def onPulse(par):
	return

def onCook(scriptOp):
	op('util').module.fill(scriptOp)
	return
deco_pixel glsl · 40 línieslíneaslines
// deco_mat: relleno o contorno por SDF (caja redondeada / elipse) con antialias de 1 px; premultiplicado.
in Vertex {
	vec2 p;
	flat vec4 box;
	flat vec4 col;
	flat float kind;
} iVert;

out vec4 oFragColor;

float sdRoundBox(vec2 p, vec2 b, float r)
{
	vec2 q = abs(p) - b + r;
	return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
}

float sdEllipse(vec2 p, vec2 r)
{
	r = max(r, vec2(1e-3));
	float k0 = length(p / r);
	float k1 = length(p / (r * r));
	return k1 < 1e-6 ? -min(r.x, r.y) : k0 * (k0 - 1.0) / k1;
}

void main()
{
	TDCheckDiscard();
	vec2 b = iVert.box.xy;
	float a;
	if (iVert.kind > 1.5) {
		a = clamp(0.5 * iVert.box.z + 0.5 - abs(sdEllipse(iVert.p, b)), 0.0, 1.0);
	} else {
		float d = sdRoundBox(iVert.p, b, clamp(iVert.box.w, 0.0, 1.0) * min(b.x, b.y));
		a = iVert.kind > 0.5 ? clamp(0.5 * iVert.box.z + 0.5 - abs(d), 0.0, 1.0) : clamp(0.5 - d, 0.0, 1.0);
	}
	a *= iVert.col.a;
	if (a <= 0.0005) discard;
	oFragColor = TDOutputSwizzle(vec4(iVert.col.rgb * a, a));
}
exec_frame python · 30 línieslíneaslines
def onStart():
	op('util').module.init(parent())
	return

def onCreate():
	op('util').module.init(parent())
	return

def onExit():
	return

def onFrameStart(frame):
	op('util').module.tick(parent())
	return

def onFrameEnd(frame):
	return

def onPlayStateChange(state):
	return

def onDeviceChange():
	return

def onProjectPreSave():
	return

def onProjectPostSave():
	return
param_exec python · 28 línieslíneaslines
SKIP = ('Status', 'Version', 'Module', 'Docs', 'Sync', 'Bpm')

def onValueChange(par, prev):
	if par.name in SKIP or par.readOnly:
		return
	op('util').module.compose(parent())
	return

def onPulse(par):
	if par.name == 'Resync':
		if parent().par.Sync.eval() == 'timeline':
			op('libclock').module.resync()
		else:
			op('beat_speed').par.resetpulse.pulse()
	return

def onValuesChanged(changes):
	return

def onExpressionChange(par, val, prev):
	return

def onExportChange(par, val, prev):
	return

def onEnableChange(par, val, prev):
	return
path_pixel glsl · 19 línieslíneaslines
// path_mat: línea con antialias de 1 px; salida premultiplicada.
uniform vec4 uLine;
uniform vec4 uLineCol;   // RGBA (recto)

in Vertex {
	float d;
	float v;
} iVert;

out vec4 oFragColor;

void main()
{
	TDCheckDiscard();
	float a = clamp(0.5 * uLine.x + 0.5 - abs(iVert.d), 0.0, 1.0) * uLineCol.a * iVert.v;
	if (a <= 0.0005) discard;
	oFragColor = TDOutputSwizzle(vec4(uLineCol.rgb * a, a));
}
deco_vertex glsl · 153 línieslíneaslines
// deco_mat: una caja por instancia (pastilla, subrayado, contorno), en una tira de 64 tramos.
// Sin Path: attrib 0 = (centro x, y px, giro, ·). Con Path: (centro a lo largo del trazo, desvío, ·, ·) y la tira se curva.
// attrib 1 = (semilargo, semialto px, grosor del trazo px, redondeo 0–1), 2 = color RGBA, 3 = (tipo 0 relleno / 1 rect / 2 óvalo, ·, ·, ·).
uniform vec4 uRes;       // xy = lienzo (px)
uniform vec4 uPathA;     // modo Path (1), longitud, periodo, letras rectas (1)
uniform vec4 uPathB;     // centro x, y (px), giro (rad), cerrada (1)
uniform vec4 uPathC;     // Pulse, Every (beats), Decay, desvío del periodo (abiertas)
uniform vec4 uMotion[1]; // Travel (0–1), Spin (0–1), beats, ·
uniform sampler2D sPath; // trazo: x, y, tangente (px, centro de la forma = 0)

uniform vec4 uCov;       // fuente (0 Manual, 1 Audio, 2 Build, 3 Pulse), Coverage, Min, Max
uniform vec4 uCov2;      // Softness, Every (beats), Cycle (beats), fundido de las celdas (beats)
uniform vec4 uGrid;      // Grid (1), nº de celdas, segmentos del trazo, ·
uniform sampler2D sCells; // fila 0: rango de, rango a, beat de inicio, sentido; fila 1: origen (px), periodo, desvío

float covAmount()
{
	float src = uCov.x;
	if (src < 0.5) return uCov.y;
	if (src < 1.5) return mix(uCov.z, uCov.w, clamp(uMotion[0].w, 0.0, 1.0));
	float b = uMotion[0].z;
	float ev = max(uCov2.y, 1e-3);
	if (src < 2.5) {
		float cyc = max(uCov2.z, ev);
		float n = max(floor(cyc / ev + 0.5), 1.0);
		float k = floor(mod(b, cyc) / ev);
		return mix(uCov.z, uCov.w, min(k + 1.0, n) / n);
	}
	float k = max(1.0 - fract(b / ev), 0.0);
	return mix(uCov.z, uCov.w, k * k);
}

float cellVis(int ci)
{
	if (uGrid.x < 0.5) return 1.0;
	vec4 r = texelFetch(sCells, ivec2(ci, 0), 0);
	float c = covAmount();
	float s = max(uCov2.x, 1e-3);
	float vf = clamp((c * (1.0 + s) - r.x) / s, 0.0, 1.0);
	float vt = clamp((c * (1.0 + s) - r.y) / s, 0.0, 1.0);
	float f = uCov2.w <= 0.0 ? 1.0 : clamp((uMotion[0].z - r.z) / uCov2.w, 0.0, 1.0);
	return mix(vf, vt, f);
}

// posición a lo largo del trazo con el Travel: periodo, desvío y sentido son los de la celda
float cellPath(int ci, float x)
{
	float P = uPathA.z;
	float o = uPathC.w;
	float d = 1.0;
	if (uGrid.x > 0.5) {
		vec4 c = texelFetch(sCells, ivec2(ci, 1), 0);
		P = c.z;
		o = c.w;
		d = texelFetch(sCells, ivec2(ci, 0), 0).w;
	}
	P = max(P, 1e-3);
	return mod(x + o + d * uMotion[0].x * P, P) - o;
}

vec2 cellOrigin(int ci)
{
	return uGrid.x > 0.5 ? texelFetch(sCells, ivec2(ci, 1), 0).xy : vec2(0.0);
}

mat2 rot2(float a)
{
	float c = cos(a);
	float s = sin(a);
	return mat2(c, s, -s, c);
}

float pathPulse()
{
	if (uPathC.x <= 0.0) return 1.0;
	float ph = fract(uMotion[0].z / max(uPathC.y, 1e-3));
	float k = max(1.0 - ph / max(uPathC.z, 1e-3), 0.0);
	return 1.0 + uPathC.x * k * k;
}

float pathRot()
{
	return uPathB.z - uMotion[0].y * 6.28318530718;      // Spin positivo = horario (como carouselGEN)
}

vec4 pathAt(float s)
{
	int N = textureSize(sPath, 0).x;
	float L = max(uPathA.y, 1e-3);
	float f;
	int i0;
	int i1;
	if (uPathB.w > 0.5) {
		f = mod(s, L) / L * float(N);
		i0 = int(floor(f)) % N;
		i1 = (i0 + 1) % N;
	} else {
		f = clamp(s / L, 0.0, 1.0) * float(N - 1);
		i0 = min(int(floor(f)), N - 1);
		i1 = min(i0 + 1, N - 1);
	}
	float t = fract(f);
	vec4 a = texelFetch(sPath, ivec2(i0, 0), 0);
	vec4 b = texelFetch(sPath, ivec2(i1, 0), 0);
	vec2 tg = a.zw + (b.zw - a.zw) * t;
	return vec4(mix(a.xy, b.xy, t), tg / max(length(tg), 1e-6));
}

vec2 pathToCanvas(vec2 p)
{
	return uPathB.xy + rot2(pathRot()) * (p * pathPulse());
}


out Vertex {
	vec2 p;
	flat vec4 box;
	flat vec4 col;
	flat float kind;
} oVert;

void main()
{
	vec3 P = TDPos();
	vec2 q = P.xy + 0.5;
	vec4 a0 = TDInstanceCustomAttrib0();
	vec4 a1 = TDInstanceCustomAttrib1();
	vec4 a2 = TDInstanceCustomAttrib2();
	vec4 a3 = TDInstanceCustomAttrib3();
	int ci = int(a3.y + 0.5);
	float m = 0.5 * a1.z + 1.5;
	vec2 l = (q * 2.0 - 1.0) * (a1.xy + m);
	vec2 pos;
	float vis = 1.0;
	if (uPathA.x > 0.5) {
		float sc = cellPath(ci, a0.x);
		if (uPathB.w < 0.5 && (sc < 0.0 || sc > uPathA.y)) vis = 0.0;
		vec4 pt = pathAt(sc + l.x);
		vec2 t = rot2(pathRot()) * pt.zw;
		vec2 n = vec2(-t.y, t.x);
		pos = pathToCanvas(pt.xy) + n * (a0.y + l.y);
	} else {
		pos = a0.xy + rot2(a0.z) * l;
	}
	pos += cellOrigin(ci);
	vis *= cellVis(ci);
	oVert.p = l;
	oVert.box = a1;
	oVert.col = vec4(a2.rgb, a2.a * vis);
	oVert.kind = a3.x;
	gl_Position = vec4(pos / uRes.xy * 2.0 - 1.0, 0.0, 1.0);
}
glyph_pixel glsl · 22 línieslíneaslines
// glyph_mat: alfa del glifo en el atlas de su variante × color; salida premultiplicada.
uniform sampler2D sAtlas0;
uniform sampler2D sAtlas1;
uniform sampler2D sAtlas2;

in Vertex {
	vec2 uv;
	vec4 col;
	flat int var;
} iVert;

out vec4 oFragColor;

void main()
{
	TDCheckDiscard();
	float g = iVert.var == 1 ? texture(sAtlas1, iVert.uv).a : (iVert.var == 2 ? texture(sAtlas2, iVert.uv).a : texture(sAtlas0, iVert.uv).a);
	float a = g * iVert.col.a;
	if (a <= 0.0005) discard;
	oFragColor = TDOutputSwizzle(vec4(iVert.col.rgb * a, a));
}
param_exec4 python · 19 línieslíneaslines
def onValueChange(par, prev):
	return

def onPulse(par):
	op('util').module.change(parent(), manual=True)
	return

def onValuesChanged(changes):
	return

def onExpressionChange(par, val, prev):
	return

def onExportChange(par, val, prev):
	return

def onEnableChange(par, val, prev):
	return
path_vertex glsl · 138 línieslíneaslines
// path_mat: un segmento del trazo por instancia (entre la muestra i y la siguiente), ancho en px.
uniform vec4 uLine;      // ancho (px), ·, ·, ·
uniform vec4 uRes;       // xy = lienzo (px)
uniform vec4 uPathA;     // modo Path (1), longitud, periodo, letras rectas (1)
uniform vec4 uPathB;     // centro x, y (px), giro (rad), cerrada (1)
uniform vec4 uPathC;     // Pulse, Every (beats), Decay, desvío del periodo (abiertas)
uniform vec4 uMotion[1]; // Travel (0–1), Spin (0–1), beats, ·
uniform sampler2D sPath; // trazo: x, y, tangente (px, centro de la forma = 0)

uniform vec4 uCov;       // fuente (0 Manual, 1 Audio, 2 Build, 3 Pulse), Coverage, Min, Max
uniform vec4 uCov2;      // Softness, Every (beats), Cycle (beats), fundido de las celdas (beats)
uniform vec4 uGrid;      // Grid (1), nº de celdas, segmentos del trazo, ·
uniform sampler2D sCells; // fila 0: rango de, rango a, beat de inicio, sentido; fila 1: origen (px), periodo, desvío

float covAmount()
{
	float src = uCov.x;
	if (src < 0.5) return uCov.y;
	if (src < 1.5) return mix(uCov.z, uCov.w, clamp(uMotion[0].w, 0.0, 1.0));
	float b = uMotion[0].z;
	float ev = max(uCov2.y, 1e-3);
	if (src < 2.5) {
		float cyc = max(uCov2.z, ev);
		float n = max(floor(cyc / ev + 0.5), 1.0);
		float k = floor(mod(b, cyc) / ev);
		return mix(uCov.z, uCov.w, min(k + 1.0, n) / n);
	}
	float k = max(1.0 - fract(b / ev), 0.0);
	return mix(uCov.z, uCov.w, k * k);
}

float cellVis(int ci)
{
	if (uGrid.x < 0.5) return 1.0;
	vec4 r = texelFetch(sCells, ivec2(ci, 0), 0);
	float c = covAmount();
	float s = max(uCov2.x, 1e-3);
	float vf = clamp((c * (1.0 + s) - r.x) / s, 0.0, 1.0);
	float vt = clamp((c * (1.0 + s) - r.y) / s, 0.0, 1.0);
	float f = uCov2.w <= 0.0 ? 1.0 : clamp((uMotion[0].z - r.z) / uCov2.w, 0.0, 1.0);
	return mix(vf, vt, f);
}

// posición a lo largo del trazo con el Travel: periodo, desvío y sentido son los de la celda
float cellPath(int ci, float x)
{
	float P = uPathA.z;
	float o = uPathC.w;
	float d = 1.0;
	if (uGrid.x > 0.5) {
		vec4 c = texelFetch(sCells, ivec2(ci, 1), 0);
		P = c.z;
		o = c.w;
		d = texelFetch(sCells, ivec2(ci, 0), 0).w;
	}
	P = max(P, 1e-3);
	return mod(x + o + d * uMotion[0].x * P, P) - o;
}

vec2 cellOrigin(int ci)
{
	return uGrid.x > 0.5 ? texelFetch(sCells, ivec2(ci, 1), 0).xy : vec2(0.0);
}

mat2 rot2(float a)
{
	float c = cos(a);
	float s = sin(a);
	return mat2(c, s, -s, c);
}

float pathPulse()
{
	if (uPathC.x <= 0.0) return 1.0;
	float ph = fract(uMotion[0].z / max(uPathC.y, 1e-3));
	float k = max(1.0 - ph / max(uPathC.z, 1e-3), 0.0);
	return 1.0 + uPathC.x * k * k;
}

float pathRot()
{
	return uPathB.z - uMotion[0].y * 6.28318530718;      // Spin positivo = horario (como carouselGEN)
}

vec4 pathAt(float s)
{
	int N = textureSize(sPath, 0).x;
	float L = max(uPathA.y, 1e-3);
	float f;
	int i0;
	int i1;
	if (uPathB.w > 0.5) {
		f = mod(s, L) / L * float(N);
		i0 = int(floor(f)) % N;
		i1 = (i0 + 1) % N;
	} else {
		f = clamp(s / L, 0.0, 1.0) * float(N - 1);
		i0 = min(int(floor(f)), N - 1);
		i1 = min(i0 + 1, N - 1);
	}
	float t = fract(f);
	vec4 a = texelFetch(sPath, ivec2(i0, 0), 0);
	vec4 b = texelFetch(sPath, ivec2(i1, 0), 0);
	vec2 tg = a.zw + (b.zw - a.zw) * t;
	return vec4(mix(a.xy, b.xy, t), tg / max(length(tg), 1e-6));
}

vec2 pathToCanvas(vec2 p)
{
	return uPathB.xy + rot2(pathRot()) * (p * pathPulse());
}

out Vertex {
	float d;
	float v;
} oVert;

void main()
{
	vec3 p = TDPos();
	vec2 q = p.xy + 0.5;
	int N = textureSize(sPath, 0).x;
	int segN = max(int(uGrid.z + 0.5), 1);
	int ci = TDInstanceID() / segN;
	int i = TDInstanceID() % segN;
	int j = uPathB.w > 0.5 ? (i + 1) % N : min(i + 1, N - 1);
	vec2 a = pathToCanvas(texelFetch(sPath, ivec2(i, 0), 0).xy);
	vec2 b = pathToCanvas(texelFetch(sPath, ivec2(j, 0), 0).xy);
	vec2 dir = b - a;
	dir = dir / max(length(dir), 1e-6);
	vec2 n = vec2(-dir.y, dir.x);
	float hw = 0.5 * uLine.x + 1.0;
	oVert.d = (q.y - 0.5) * 2.0 * hw;
	vec2 pos = mix(a, b, q.x) + n * oVert.d + cellOrigin(ci);
	oVert.v = cellVis(ci);
	gl_Position = vec4(pos / uRes.xy * 2.0 - 1.0, 0.0, 1.0);
}
glyph_vertex glsl · 156 línieslíneaslines
// glyph_mat: un rectángulo 1 × 1 por letra = su celda del atlas.
// Sin Path: custom attrib 0 = (x, y de la pluma en px, giro, escala lienzo / atlas).
// Con Path: attrib 0 = (centro de la letra a lo largo del trazo en px, desvío de la línea base, avance, escala).
// attrib 1 = (celda x0, y0 en el atlas, pluma dentro de la celda, variante), 2 = color RGBA, 3 = (estilo, segmento, palabra, índice).
uniform vec4 uAtlas0;    // celda px, línea base en la celda, ancho y alto del atlas
uniform vec4 uAtlas1;    // atlas del destacado 1 (su fuente)
uniform vec4 uAtlas2;    // atlas del destacado 2
uniform vec4 uRes;       // xy = lienzo (px)
uniform vec4 uPathA;     // modo Path (1), longitud, periodo, letras rectas (1)
uniform vec4 uPathB;     // centro x, y (px), giro (rad), cerrada (1)
uniform vec4 uPathC;     // Pulse, Every (beats), Decay, desvío del periodo (abiertas)
uniform vec4 uMotion[1]; // Travel (0–1), Spin (0–1), beats, ·
uniform sampler2D sPath; // trazo: x, y, tangente (px, centro de la forma = 0)

uniform vec4 uCov;       // fuente (0 Manual, 1 Audio, 2 Build, 3 Pulse), Coverage, Min, Max
uniform vec4 uCov2;      // Softness, Every (beats), Cycle (beats), fundido de las celdas (beats)
uniform vec4 uGrid;      // Grid (1), nº de celdas, segmentos del trazo, ·
uniform sampler2D sCells; // fila 0: rango de, rango a, beat de inicio, sentido; fila 1: origen (px), periodo, desvío

float covAmount()
{
	float src = uCov.x;
	if (src < 0.5) return uCov.y;
	if (src < 1.5) return mix(uCov.z, uCov.w, clamp(uMotion[0].w, 0.0, 1.0));
	float b = uMotion[0].z;
	float ev = max(uCov2.y, 1e-3);
	if (src < 2.5) {
		float cyc = max(uCov2.z, ev);
		float n = max(floor(cyc / ev + 0.5), 1.0);
		float k = floor(mod(b, cyc) / ev);
		return mix(uCov.z, uCov.w, min(k + 1.0, n) / n);
	}
	float k = max(1.0 - fract(b / ev), 0.0);
	return mix(uCov.z, uCov.w, k * k);
}

float cellVis(int ci)
{
	if (uGrid.x < 0.5) return 1.0;
	vec4 r = texelFetch(sCells, ivec2(ci, 0), 0);
	float c = covAmount();
	float s = max(uCov2.x, 1e-3);
	float vf = clamp((c * (1.0 + s) - r.x) / s, 0.0, 1.0);
	float vt = clamp((c * (1.0 + s) - r.y) / s, 0.0, 1.0);
	float f = uCov2.w <= 0.0 ? 1.0 : clamp((uMotion[0].z - r.z) / uCov2.w, 0.0, 1.0);
	return mix(vf, vt, f);
}

// posición a lo largo del trazo con el Travel: periodo, desvío y sentido son los de la celda
float cellPath(int ci, float x)
{
	float P = uPathA.z;
	float o = uPathC.w;
	float d = 1.0;
	if (uGrid.x > 0.5) {
		vec4 c = texelFetch(sCells, ivec2(ci, 1), 0);
		P = c.z;
		o = c.w;
		d = texelFetch(sCells, ivec2(ci, 0), 0).w;
	}
	P = max(P, 1e-3);
	return mod(x + o + d * uMotion[0].x * P, P) - o;
}

vec2 cellOrigin(int ci)
{
	return uGrid.x > 0.5 ? texelFetch(sCells, ivec2(ci, 1), 0).xy : vec2(0.0);
}

mat2 rot2(float a)
{
	float c = cos(a);
	float s = sin(a);
	return mat2(c, s, -s, c);
}

float pathPulse()
{
	if (uPathC.x <= 0.0) return 1.0;
	float ph = fract(uMotion[0].z / max(uPathC.y, 1e-3));
	float k = max(1.0 - ph / max(uPathC.z, 1e-3), 0.0);
	return 1.0 + uPathC.x * k * k;
}

float pathRot()
{
	return uPathB.z - uMotion[0].y * 6.28318530718;      // Spin positivo = horario (como carouselGEN)
}

vec4 pathAt(float s)
{
	int N = textureSize(sPath, 0).x;
	float L = max(uPathA.y, 1e-3);
	float f;
	int i0;
	int i1;
	if (uPathB.w > 0.5) {
		f = mod(s, L) / L * float(N);
		i0 = int(floor(f)) % N;
		i1 = (i0 + 1) % N;
	} else {
		f = clamp(s / L, 0.0, 1.0) * float(N - 1);
		i0 = min(int(floor(f)), N - 1);
		i1 = min(i0 + 1, N - 1);
	}
	float t = fract(f);
	vec4 a = texelFetch(sPath, ivec2(i0, 0), 0);
	vec4 b = texelFetch(sPath, ivec2(i1, 0), 0);
	vec2 tg = a.zw + (b.zw - a.zw) * t;
	return vec4(mix(a.xy, b.xy, t), tg / max(length(tg), 1e-6));
}

vec2 pathToCanvas(vec2 p)
{
	return uPathB.xy + rot2(pathRot()) * (p * pathPulse());
}

out Vertex {
	vec2 uv;
	vec4 col;
	flat int var;
} oVert;

void main()
{
	vec3 p = TDPos();
	vec2 q = p.xy + 0.5;
	vec4 a0 = TDInstanceCustomAttrib0();
	vec4 a1 = TDInstanceCustomAttrib1();
	vec4 a2 = TDInstanceCustomAttrib2();
	vec4 a3 = TDInstanceCustomAttrib3();
	int ci = int(a3.y + 0.5);
	int vi = int(a1.w + 0.5);
	vec4 at = vi == 1 ? uAtlas1 : (vi == 2 ? uAtlas2 : uAtlas0);
	vec2 loc = (q * at.x - vec2(a1.z, at.y)) * a0.w;
	vec2 pos;
	float vis = 1.0;
	if (uPathA.x > 0.5) {
		float s = cellPath(ci, a0.x);
		if (uPathB.w < 0.5 && (s < 0.0 || s > uPathA.y)) vis = 0.0;
		vec4 pt = pathAt(s);
		vec2 t = rot2(pathRot()) * pt.zw;
		vec2 n = vec2(-t.y, t.x);
		float ang = uPathA.w > 0.5 ? 0.0 : atan(t.y, t.x);
		pos = pathToCanvas(pt.xy) + n * a0.y + rot2(ang) * (loc - vec2(0.5 * a0.z, 0.0));
	} else {
		pos = a0.xy + rot2(a0.z) * loc;
	}
	pos += cellOrigin(ci);
	vis *= cellVis(ci);
	oVert.uv = (a1.xy + q * at.x) / at.zw;
	oVert.col = vec4(a2.rgb, a2.a * vis);
	oVert.var = vi;
	gl_Position = vec4(pos / uRes.xy * 2.0 - 1.0, 0.0, 1.0);
}

Aquesta part és en castellà.This part is in Spanish.

Decisiones de diseño
  • Cada letra es una instancia en vez de líneas en un Text TOP (como carouselGEN): es lo único que permite que el texto siga un trazo con cada letra girada, adornos que se curvan y rejillas de cientos de copias sin repetir la maqueta. El coste de pintar es el de un Render TOP; la maqueta solo corre al cambiar algo.
  • Atlas de glifos con dos pasadas: la 1.ª con la celda más grande que cabe (para medir); la 2.ª pinta el atlas al tamaño de la letra más grande en pantalla (escala 1) y las letras horizontales se colocan en píxeles enteros: igual de nítido que un Text TOP directo. Solo se suaviza si las letras en pantalla son más grandes que su celda (muchos caracteres distintos y un tamaño grande); el Status lo avisa.
  • Kerning real midiendo prefijos con evalTextSize (pluma = prefijo − avance propio), en un Text TOP de medida a tamaño fijo con caché (rápido aunque el atlas cambie de tamaño).
  • Dos estilos de destacado con marcas en el propio texto (* / **): textbankCTRL los manda tal cual. Cada opción se suma a las demás; Font tiene su propio atlas y Size entra en la maqueta.
  • Adornos como cajas con SDF (no geometría): un relleno o un contorno con antialias en cualquier forma (caja redondeada, elipse) y, en Path, curvados sobre el trazo con una tira de 64 tramos. Medidas en × tamaño de la letra: escalan con Justify, Spread, Fit y el Grid.
  • Path en el shader: el trazo es una textura (posición + tangente por longitud de arco) y Travel / Spin / Pulse son uniforms. En las formas abiertas el texto sale por un extremo y entra por el otro.
  • Grid sin copias en Python: una maqueta por unidad (Repeat: la base; Distribute: un segmento) y celdas por copia de arrays; el origen de cada celda y su Coverage en una textura. Un nuevo reparto de textos (a beat) cuesta ~1 ms.
  • Coverage en el shader con rango por celda (centrado en su tramo: celdas exactas) y fuentes que leen el reloj y el nivel del audio desde el array de uniforms: sin Python por frame.
  • Salida congelada: el Render TOP se procesaría cada frame que se mira aunque nada cambie; cache_out lo congela y solo se activa unos frames tras un cambio, durante un fundido o con algo animado (Travel, Spin, Pulse, Coverage con audio o a beat). Antes de congelar se fuerza a guardar la última imagen (aunque nadie mire la salida).
  • Composiciones de carouselGEN con los mismos nombres de menú, más Diagonal, Justify y Spread por palabras / letras; cuando algo no cabe (Spread, letras en vertical, celdas), se reduce en vez de pisarse.
  • Lines (1.2): la celda mide columna × alto del lienzo, no una fila. Así Size no depende del número de filas, Path y las demás maquetas funcionan sin tocarlas y las filas son solo orígenes separados Line Distance × letra: solaparlas no cuesta nada, porque nada se recorta a su celda. El tamaño real de la letra y lo que ocupa una línea (lo … hi: trazo girado, Pulse, Spin, altura de las mayúsculas) se miden en la maqueta ya hecha (line_metrics) y de ahí salen las filas que se ven (line_centers), con una siempre en el centro del lienzo.
  • Size Relative To en vez de subir el máximo de Width: con × lado corto, una fila ancha y baja necesitaba Width ≈ 11 para cruzar la pantalla, y el valor cambiaba con cada número de filas.
  • El periodo del recorrido va por celda (cell_tex), no en un uniform: en Distribute cada texto mide distinto y da la vuelta en su sitio. El sentido (Alternate Direction) va en el mismo texel.
  • Export: fuentes que no vienen con Windows → Arial Bold (también las de los destacados), Audio Off, rutas vacías.
Lo que falló y cómo se arregló
SíntomaCausaSolución
Letras más blandas que con un Text TOP (bordes 1,8 × más anchos)Atlas a tamaño fijo reducido con mipmap + posiciones fraccionarias (doble remuestreo)Atlas al tamaño de la letra más grande (escala 1) y pluma en px enteros: 0,178 frente a 0,198
El Render TOP se procesaba cada frame con el texto quieto (0,26 ms CPU)El Render TOP cocina siempre que alguien lo mira (también uno vacío)cache_out congelado; wake lo activa unos frames tras cada cambio
El .tox en frío salía vacíoLa caché solo guarda si alguien mira la salida en los frames en vivocache_out.cook(force=True) justo antes de congelar
Un fundido de celdas se congelaba a mediasEl Reroll (4 frames en vivo) pisaba los 34 del fundidowake se queda con el plazo más largo
Spread: segmentos pisándoseNo cabían en el ancho (igual en carouselGEN)Se reducen con medio cuerpo de hueco mínimo
Spread Vertical por letras: letras pegadas y sin espaciosPaso menor que la altura de las mayúsculas; los espacios no eran letrasReducir a 1,15 × cap por paso; los espacios cuentan como hueco (ci)
El separador de Path salía como otra letraSus caracteres no estaban en el atlas (map.get daba la celda 0)variants añade los caracteres del separador
Travel iba un 20 % lento (0,05 en vez de 0,0625 cada 15 frames)El Speed CHOP solo avanzaba cuando alguien miraba la salidaNull del movimiento en Cook Always (#357)
Spin positivo giraba antihorario; con Spin 0 la forma se quedaba giradaSigno del ángulo; fase integrada sin volver− spin; reset del Speed CHOP con velocidad 0
Óvalo que pisaba la palabra de al ladoRadios × √2 en los dos ejesrx = semiancho + 0,9 × semialto y ry el que pase por las esquinas
Coverage: una celda a media opacidad en el límiteRango k / n: la celda del borde quedaba a alfa = CoverageRango (k + 0,5) / n: se ven round(Coverage × n) exactas
Grid: compose de 170–315 ms (8 × 8, 16 × 16)Una copia en Python por letra y celdaUna maqueta por unidad + copias por celda con numpy: 2–5 ms
compose de ~110 ms en rejillas con celdas pequeñasevalTextSize ~1 ms por llamada tras cambiar el tamaño del Text TOP (la 2.ª pasada lo cambia)Medir en metricsN a 200 px fijos con caché
Distribute: palabras que invadían la celda de al ladoLa maqueta no conocía el tamaño de la celdaFit Text to Cell (reduce desde el centro)
KeyError: 'wd' al reconstruir con build4Renombrar canales de un bloque que build1 escribe por nombreAñadir un bloque (cl) en vez de renombrar
Aviso «Position table x column does not exist» en atlas1 / 2Un Table DAT nuevo trae una celda vacía (numRows 1) y no se ponía la cabeceraComprobar la cabecera, no numRows == 0
Nodos solapados (cell_cb / beat_src)Posiciones de build4Recolocados
(1.1) Con Distribute, varios segmentos, Repeat to Fill y Travel, unos textos se montaban sobre otros al dar la vueltaUn solo pathperiod para todas las celdas: el del último segmento maquetadoPeriodo y desvío por celda en cell_tex (1.2)
(1.1) Wave en 1 columna: las ondas se quedaban en el centro y no llegaban a los bordesWidth × lado corto de la celda (el alto de la fila)Size Relative To = Canvas / Cell (1.2)
En la prueba faltaban filas por abajo con Fill CanvasCopia y cambios de pars en la misma llamada: el Parameter Execute no avisa (#315) y seguía la maqueta anterior (12 filas con otro paso)No era del módulo: util.compose tras copiar + cambiar
Cuánto cuesta

Medido a 1280 × 720, 60 fps, TouchDesigner 2025.33230:

PiezaCoste
Texto quietoRender 0 cooks (salida congelada; 5 cooks en 204 frames tras un cambio)
Render en vivo, 24–31 letras0,26–0,30 ms CPU, 0,13–0,16 ms GPU
Path con Travel (9 letras)0,34 ms CPU, 0,20 ms GPU
Grid 8 × 8 Path con Travel (2688 letras, 128 adornos, 64 trazos)0,33 ms CPU, 0,48 ms GPU
Cambio de un par / texto (compose)1–5 ms una vez (también Grid 16 × 16)
Lines con Fill Canvas, onda con Travel (1.2; 12 filas, 540 letras, lienzo 1024 × 384)0,41 ms CPU, 0,08 ms GPU; compose 6,7 ms una vez
Nuevo reparto de textos (Reroll, a beat)~1 ms
Vigilante por frame (util.tick)12–20 µs
Medida de una letraevalTextSize 8 µs (en caché después)
MemoriaAtlas ≤ 1280² × 4 B (6,5 MB) por fuente usada