powerCTRL
Adorm i desperta mòduls a mà o per escenes perquè el que no es veu no gasti, i diu quant costa cadascun.Duerme y despierta módulos a mano o por escenas para que lo que no se ve no gaste, y dice cuánto cuesta cada uno.Puts modules to sleep and wakes them, by hand or by scenes, so what isn't seen costs nothing, and tells you what each one costs.

- sense entradessin entradasno inputs
- out1CHOPstate
UsarUsarUse
Afegeix-hi tots els mòduls del projecte i mira la columna de ms: sovint el més car no és el que et pensaves.Añade todos los módulos del proyecto y mira la columna de ms: a menudo el más caro no es el que pensabas.Add every module in the project and look at the ms column: the most expensive one is often not the one you thought.
Aquesta part és en castellà.This part is in Spanish.
- Arrastrar
tox/CTRL/powerCTRL.toxa la misma red que los módulos (los objetivos son sus hermanos). - Add Module (o seleccionar COMPs y Add Selected). Cada fila: Mode (Auto suele bastar) y en qué escenas está despierto.
- Escenas: Scenes, nombres y Go 1…N (pads con midiCTRL), Prev / Next o los botones del tile. All On despierta todo.
- El tile: pulsar una fila la despierta / duerme; arriba lo que se ahorra; el coste de cada módulo a la derecha.
- Warnings: ámbar / rojo según Warn at / Alert at (% del frame; Limits da los ms).
↑pico= va bien de media pero a ratos se dispara; la franja TOP dice a quién dormir primero.out1level(0 / 1 / 2) para un LED. - Enable Off para trabajar con todo despierto sin perder la lista ni las escenas.
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
Un mòdul adormit no processa ni un sol operador. El cost es mesura mòdul a mòdul, per torns, perquè la mateixa mesura no pesi.Un módulo dormido no procesa ni un solo operador. El coste se mide módulo a módulo, por turnos, para que la propia medida no pese.A sleeping module doesn't process a single operator. Cost is measured one module at a time, in turns, so the measuring itself doesn't weigh.
Aquesta part és en castellà.This part is in Spanish.
Con más detalle
Un módulo dormido no procesa nada (comprobado en todo el proyecto: 0 operadores, 0 ms); también puede ir a su propio Bypass si está en mitad de una cadena. En automático decide según la familia y los cables: no duerme mixers, salidas ni controles, y avisa de a quién dejaría en negro. Mide un módulo por turno (~0,04 ms por frame) y no se deja engañar por las entradas, que cargaban a un módulo el trabajo del de delante.
La idea
Ganar frames en directo apagando lo que no se ve, y saber en todo momento qué módulo es el que pesa.
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
list_exec (Parameter Execute sobre los pars propios) → util.on_change / on_pulse → util.schedule (un frame después) → util.apply
start (Execute): onStart / onCreate → util.on_start · onFrameStart cada 30 frames → util.check (lista, cables, estado real)
util.apply → allowCooking / Bypass de cada módulo · Status · Info · state (Constant CHOP) → null_out → out1
→ tile_draw (APPLY_HOOKS): tile_spec (textos) + rects en el estado + tile_size (w, h, n, tick)
tile_exec (Execute, onFrameEnd) → util.cost_tick: un módulo por turno (apuntar un frame, leer el siguiente)
→ cada 60 frames: pw_cost (storage), Limits, out1 (niveles) y tile_draw
tile_size ─┬→ tile_data (Script TOP: N rects × 3 texels, rgba32f) ─┐
└→ tile_txt (Text TOP con Spec DAT tile_spec) ────────────┴→ tile_glsl → null_tile → tile (Container) = opviewer
tile_click (Panel Execute sobre tile, lselect) → util.tile_click: escena, fila (Awake), All OnOperador a operador configuración clave
| Operador | Configuración clave |
|---|---|
util | Texto Python: build1 + build2 (tras # ---- build2: tile ----) + build4 (tras # ---- build4: avisos ----) |
list_exec | Parameter Execute: op = .., pars = *, custom On, builtin Off, valuechange y onpulse → util.on_change / on_pulse |
start | Execute: onStart / onCreate → util.on_start; onFrameStart cada 30 frames → util.check |
state → null_out → out1 | Constant CHOP escrito por write_out (solo lo que cambia); out1 con label state |
tile_size | Constant CHOP w h n tick: ancho 480, alto, nº de rects, contador que cambia al redibujar |
tile_data | Script TOP rgba32f con tile_data_callbacks: util.tile_array (N × 3: caja, relleno, tinta); lee tick, cocina solo al redibujar |
tile_spec → tile_txt | Table x y text → Text TOP 480 × alto, Arial bold 15 px, blanco sobre transparente, alignx left, aligny bottom |
tile_glsl → null_tile | GLSL TOP con tile_shader, entradas rects + textos, inputfiltertype nearest, uniform uN |
tile | Container COMP top = null_tile, topfill best, w / h de tile_size; opviewer = ./tile |
tile_click | Panel Execute sobre tile, lselect, offtoon → util.tile_click(u, v) |
tile_exec | Execute onFrameEnd → util.cost_tick |
| COMP | Tag powerCTRL (otro powerCTRL no lo puede dormir); showCustomOnly |
TallerTallerWorkshop
El codiEl códigoThe code
util python · 941 línieslíneaslines
# powerCTRL util — fase 1: lista, Sleep / Bypass, escenas y out1. Todo por evento (cambio de un par, pulso) y una
# revisión cada 30 frames (bloques nuevos de la secuencia, cables, módulos renombrados o tocados a mano).
import re
NSC = 8
F = ['target', 'mode', 'awake'] + ['s%d' % i for i in range(1, NSC + 1)]
PROTECT = ('CTRL', 'OUT', 'XPORT', 'MIX') # Auto no los duerme: otros leen de ellos o son la salida
STATE = {} # por ruta del COMP: apply pendiente, última clave de check
APPLY_HOOKS = [] # funciones (comp) que corren al final de cada apply (build2: tile)
def state(comp):
return STATE.setdefault(comp.path, {})
def info(comp, msg):
if comp.par.Info.eval() != msg:
comp.par.Info.val = msg
# ---- la lista (secuencia Mod)
def nrows(comp):
n = comp.seq.Mod.numBlocks
if n == 1 and not comp.par.Mod0target.eval():
return 0
return n
def get_row(comp, k):
d = {}
for f in F:
p = getattr(comp.par, 'Mod%d%s' % (k, f), None)
d[f] = p.eval() if p is not None else None
return d
def set_row(comp, k, d):
for f, v in d.items():
p = getattr(comp.par, 'Mod%d%s' % (k, f), None)
if p is not None and v is not None and p.eval() != v:
p.val = v
def empty_row():
d = {'target': '', 'mode': 'auto', 'awake': True}
for i in range(1, NSC + 1):
d['s%d' % i] = True
return d
def base(comp):
return comp.parent()
def category(o):
m = re.findall('(XPORT|CTRL|GEN|MIX|OUT|FX|3D)', o.name)
return m[-1] if m else ''
def forbidden(comp, o):
"""Ni el propio powerCTRL ni un COMP que lo contenga (se dormiría a sí mismo)."""
return o.path == comp.path or comp.path.startswith(o.path + '/') or 'powerCTRL' in o.tags
def target_of(comp, name):
if not name:
return None
o = base(comp).op(name)
if o is None or not o.isCOMP or forbidden(comp, o):
return None
return o
def candidates(comp):
out = []
for o in base(comp).children:
if o.isCOMP and not forbidden(comp, o):
out.append(o)
out.sort(key=lambda o: (category(o) == '', o.name.lower())) # los de la librería primero
return out
def refresh_menu(comp):
listed = set(get_row(comp, k)['target'] for k in range(nrows(comp)))
names, labels = ['add'], ['Add…']
for o in candidates(comp):
if o.name in listed:
continue
names.append(o.name)
c = category(o)
labels.append(o.name + (' (protected in Auto)' if c in PROTECT else ''))
p = comp.par.Addmodule
if list(p.menuNames) != names or list(p.menuLabels) != labels:
p.menuNames, p.menuLabels = names, labels
if p.eval() != 'add':
p.val = 'add'
def labels(comp):
n = int(comp.par.Scenes.eval())
names = ['manual'] + [str(i) for i in range(1, n + 1)]
labs = ['Manual'] + ['%d · %s' % (i, getattr(comp.par, 'Scenename%d' % i).eval() or 'Scene %d' % i)
for i in range(1, n + 1)]
p = comp.par.Scene
cur = p.eval()
if list(p.menuNames) != names or list(p.menuLabels) != labs:
p.menuNames, p.menuLabels = names, labs
if cur not in names:
p.val = 'manual'
elif p.eval() != cur:
p.val = cur
def add_row(comp, o):
for k in range(nrows(comp)):
if get_row(comp, k)['target'] == o.name:
info(comp, 'already in the list: %s' % o.name)
return False
k = nrows(comp)
if k >= comp.seq.Mod.numBlocks:
comp.seq.Mod.numBlocks = k + 1 # si no, reutiliza el bloque vacío
d = empty_row()
d['target'] = o.name
set_row(comp, k, d)
return True
def add_selected(comp):
n = 0
for o in base(comp).selectedChildren:
if o.isCOMP and not forbidden(comp, o) and add_row(comp, o):
n += 1
info(comp, 'added %d selected module%s' % (n, '' if n == 1 else 's'))
schedule(comp)
def delete_row(comp, k):
n = nrows(comp)
for j in range(k, n - 1): # desplaza los de detrás y quita el último
set_row(comp, j, get_row(comp, j + 1))
if n > 1:
comp.seq.Mod.numBlocks = n - 1
else:
set_row(comp, 0, empty_row()) # el último: queda el bloque vacío
schedule(comp) # apply despierta lo que ya no está en la lista
def move_row(comp, k, dk):
j = k + dk
if k >= nrows(comp) or j < 0 or j >= nrows(comp):
return
a, b = get_row(comp, k), get_row(comp, j)
set_row(comp, k, b)
set_row(comp, j, a)
schedule(comp)
def clear_all(comp):
comp.seq.Mod.numBlocks = 1
set_row(comp, 0, empty_row())
info(comp, 'list cleared: all modules awake')
schedule(comp)
# ---- escenas
def cur_scene(comp):
s = comp.par.Scene.eval()
return 0 if s == 'manual' else int(s)
def go_scene(comp, n):
"""Pone Awake de cada fila según su casilla de la escena n (0 = Manual: no toca nada)."""
if n < 1 or n > int(comp.par.Scenes.eval()):
return
if comp.par.Scene.eval() != str(n):
comp.par.Scene.val = str(n)
for k in range(nrows(comp)):
v = bool(getattr(comp.par, 'Mod%ds%d' % (k, n)).eval())
p = getattr(comp.par, 'Mod%dawake' % k)
if bool(p.eval()) != v:
p.val = v
schedule(comp)
def step_scene(comp, d):
n = int(comp.par.Scenes.eval())
s = cur_scene(comp)
if s == 0:
s = 1 if d > 0 else n
else:
s = (s - 1 + d) % n + 1
go_scene(comp, s)
def all_on(comp):
comp.par.Scene.val = 'manual'
for k in range(nrows(comp)):
p = getattr(comp.par, 'Mod%dawake' % k)
if not p.eval():
p.val = True
info(comp, 'all on')
schedule(comp)
# ---- aplicar
def schedule(comp):
s = state(comp)
if s.get('pending'):
return
s['pending'] = True
run("args[0].op('util').module.apply(args[0])", comp, delayFrames=1)
def resolve(comp, o, mode):
"""Cómo se pone en reposo este módulo: ('sleep' | 'bypass' | 'none', motivo)."""
hasb = getattr(o.par, 'Bypass', None) is not None
if mode == 'sleep':
return 'sleep', ''
if mode == 'bypass':
return ('bypass', '') if hasb else ('none', 'no Bypass parameter')
c = category(o)
if c in PROTECT:
return 'none', 'protected (%s): use Mode Sleep to force' % c
feeds = [x for x in consumers(o) if category(x) != 'MIX']
if not feeds:
return 'sleep', '' # va a un MIX o a nada: dormido, la capa queda vacía
if hasb:
return 'bypass', '' # FX en mitad de una cadena: la imagen sigue pasando
return 'sleep', ''
def consumers(o):
out = []
for oc in o.outputConnectors:
for c in oc.connections:
x = c.owner
if x.path != o.path and x not in out:
out.append(x)
return out
def undo(o, prev):
if prev.get('how') == 'sleep':
o.allowCooking = True
elif prev.get('how') == 'bypass':
p = getattr(o.par, 'Bypass', None)
if p is not None and p.mode == ParMode.CONSTANT:
p.val = prev.get('orig', False)
def apply(comp):
s = state(comp)
s['pending'] = False
man = dict(comp.fetch('pw_managed', {}))
enabled = bool(comp.par.Enable.eval())
seen = {}
res = [] # (k, op o None, cómo, despierto, motivo)
for k in range(nrows(comp)):
d = get_row(comp, k)
o = target_of(comp, d['target'])
if o is None:
why = 'not found' if d['target'] else 'empty'
if d['target'] and base(comp).op(d['target']) is not None:
why = 'not allowed (powerCTRL or its parent)'
res.append((k, None, 'none', True, why))
continue
if o.path in seen:
res.append((k, o, 'none', True, 'duplicate of row %d' % (seen[o.path] + 1)))
continue
seen[o.path] = k
how, why = resolve(comp, o, d['mode'])
awake = (not enabled) or bool(d['awake']) or how == 'none'
if how == 'bypass' and not awake and o.par.Bypass.mode != ParMode.CONSTANT:
how, why, awake = 'none', 'Bypass is driven by an expression or export', True
prev = man.get(o.path)
if prev is not None and (awake or prev.get('how') != how):
undo(o, prev)
man.pop(o.path, None)
if not awake:
if how == 'sleep':
man[o.path] = {'how': 'sleep'}
if o.allowCooking:
o.allowCooking = False
elif how == 'bypass':
if o.path not in man:
man[o.path] = {'how': 'bypass', 'orig': bool(o.par.Bypass.eval())}
if not o.par.Bypass.eval():
o.par.Bypass.val = True
res.append((k, o, how, awake, why))
for path, prev in list(man.items()): # ya no están en la lista (borrados, renombrados): despertarlos
if path not in seen:
o = op(path)
if o is not None:
undo(o, prev)
man.pop(path, None)
comp.store('pw_managed', man)
write_status(comp, res)
write_out(comp, res)
s['key'] = key(comp)
s['res'] = [(k, None if o is None else o.path, how, awake, why) for k, o, how, awake, why in res]
for h in APPLY_HOOKS: # build2: el tile
h(comp)
def write_status(comp, res):
nawake = nsleep = nbyp = 0
for k, o, how, awake, why in res:
if o is None:
txt = why.upper() if why != 'empty' else ''
else:
if how == 'none':
txt = 'AWAKE'
elif awake:
txt = 'AWAKE · rests by %s' % how
elif how == 'sleep':
txt = 'ASLEEP'
else:
txt = 'BYPASSED'
if awake:
nawake += 1
elif how == 'sleep':
nsleep += 1
else:
nbyp += 1
if not awake and how == 'sleep':
black = [x.name for x in consumers(o) if x.allowCooking and category(x) != 'MIX']
if black:
why = (why + ' · ' if why else '') + 'black into ' + ', '.join(black)
if why:
txt += ' · ' + why
p = getattr(comp.par, 'Mod%dstatus' % k)
if p.eval() != txt:
p.val = txt
n = sum(1 for r in res if r[1] is not None)
if comp.par.Count.eval() != n:
comp.par.Count.val = n
sc = cur_scene(comp)
scene = 'Manual' if sc == 0 else (getattr(comp.par, 'Scenename%d' % sc).eval() or 'Scene %d' % sc)
off = '' if comp.par.Enable.eval() else ' · Enable Off: all awake'
info(comp, '%s · %d awake · %d asleep · %d bypassed%s' % (scene, nawake, nsleep, nbyp, off))
def chan_name(name, used):
c = re.sub('[^A-Za-z0-9_]', '_', name) or 'module'
if c[0].isdigit():
c = 'm_' + c
b, i = c, 2
while c in used:
c = '%s_%d' % (b, i)
i += 1
used.add(c)
return c
def write_out(comp, res):
chans = [('scene', float(cur_scene(comp)))]
used = set(['scene'])
for k, o, how, awake, why in res:
if o is None:
continue
chans.append((chan_name(o.name, used), 1.0 if awake else 0.0))
c = comp.op('state')
if c.seq.const.numBlocks != len(chans):
c.seq.const.numBlocks = len(chans)
for i, (n, v) in enumerate(chans):
pn, pv = getattr(c.par, 'const%dname' % i), getattr(c.par, 'const%dvalue' % i)
if pn.eval() != n:
pn.val = n
if pv.eval() != v:
pv.val = v
# ---- vigilancia (cada 30 frames): bloques nuevos (#462), cables, renombres y cambios a mano del cooking / Bypass
def key(comp):
parts = [comp.seq.Mod.numBlocks]
for k in range(nrows(comp)):
o = target_of(comp, get_row(comp, k)['target'])
if o is None:
parts.append(None)
continue
b = getattr(o.par, 'Bypass', None)
parts.append((o.path, o.allowCooking, None if b is None else bool(b.eval()),
tuple(x.path for x in consumers(o))))
return tuple(parts)
def check(comp):
refresh_menu(comp)
s = state(comp)
if not s.get('pending') and key(comp) != s.get('key'):
schedule(comp)
def on_start(comp):
refresh_menu(comp)
labels(comp)
if comp.par.Onstart.eval() == 'allon':
all_on(comp)
schedule(comp)
# ---- eventos de los pars propios (list_exec)
def on_change(comp, par, prev):
if par.readOnly:
return # Status, Info, Count: los escribe apply
n = par.name
if n == 'Addmodule':
v = par.eval()
if v != 'add':
o = target_of(comp, v)
if o is not None and add_row(comp, o):
info(comp, 'added: %s' % o.name)
par.val = 'add'
run("args[0].op('util').module.refresh_menu(args[0])", comp, delayFrames=1)
schedule(comp)
return
if n == 'Scene':
go_scene(comp, cur_scene(comp))
schedule(comp)
return
if n == 'Scenes' or n.startswith('Scenename'):
labels(comp)
schedule(comp)
return
b = par.sequenceBlock
if b is not None:
f = n[len('Mod%d' % b.index):]
sc = cur_scene(comp)
if sc and f == 's%d' % sc: # la casilla de la escena activa: se aplica al momento
p = getattr(comp.par, 'Mod%dawake' % b.index)
if bool(p.eval()) != bool(par.eval()):
p.val = bool(par.eval())
if f == 'target':
run("args[0].op('util').module.refresh_menu(args[0])", comp, delayFrames=1)
schedule(comp)
return
if n in ('Enable',):
schedule(comp)
def on_pulse(comp, par):
n = par.name
b = par.sequenceBlock
if b is not None:
k = b.index
what = n[len('Mod%d' % k):]
if what == 'delete':
delete_row(comp, k)
return # el par puede no existir ya (#311)
if what == 'up':
move_row(comp, k, -1)
elif what == 'down':
move_row(comp, k, 1)
return
if n == 'Allon':
all_on(comp)
elif n == 'Prev':
step_scene(comp, -1)
elif n == 'Next':
step_scene(comp, 1)
elif n.startswith('Go') and n[2:].isdigit():
go_scene(comp, int(n[2:]))
elif n == 'Addselected':
add_selected(comp)
elif n == 'Clearall':
clear_all(comp)
# ---- build2: tile ----
import numpy as np
TW = 480 # ancho del tile (px)
HEAD, SCN, ROWH, FOOT, PAD = 44, 44, 32, 48, 12
BG = (0.07, 0.07, 0.07)
ROWBG = (0.105, 0.105, 0.105)
BTN = (0.16, 0.16, 0.16)
LINE = (0.22, 0.22, 0.22)
ACC = (0.863, 1.0, 0.18) # flúor de la librería (#dcff2e)
INK = (0.05, 0.05, 0.05)
TXT = (0.92, 0.92, 0.92)
DIM = (0.5, 0.5, 0.5)
OFF = (0.3, 0.3, 0.3)
AMB = (1.0, 0.68, 0.0)
ERR = (1.0, 0.4, 0.33)
DOT = ' ' + chr(183) + ' '
MINUS = chr(8722)
def tstate(comp):
s = state(comp)
s.setdefault('tw', {})
return s
def text_w(comp, t):
cache = tstate(comp)['tw']
if t not in cache:
try:
cache[t] = float(comp.op('tile_txt').evalTextSize(t)[0])
except Exception:
cache[t] = 8.0 * len(t)
if len(cache) > 2000:
cache.clear()
return cache[t]
def fit(comp, t, w):
if text_w(comp, t) <= w:
return t
while len(t) > 1 and text_w(comp, t + chr(8230)) > w:
t = t[:-1]
return t + chr(8230)
# ---- coste: cada 60 frames, un frame de cada módulo que cocina (CPU + GPU de sus OPs, sin COMPs: no se cuenta dos veces)
# In / Select: solo CPU. Su reloj de GPU abarca la cocción del módulo de arriba cuando son los primeros en pedirle
# la imagen (la GPU parada esperando a la CPU de ese módulo): gridGEN → mixer6MIX/in3 sumaba ~11 ms que no eran del mixer.
NOGPU = ('in', 'select')
def cost_tick(comp, frame):
s = tstate(comp)
ph = s.get('cphase')
if ph is None:
if frame % 60 != 0:
return
mods = []
for k, path, how, awake, why in s.get('res', []):
o = op(path) if path else None
if o is not None and o.allowCooking:
ops = [x for x in o.findChildren() if not x.isCOMP]
mods.append((path, ops, [x.totalCooks for x in ops]))
s['cphase'] = (frame, mods)
return
f0, mods = ph
if frame == f0:
return
s['cphase'] = None
costs = dict(comp.fetch('pw_cost', {}))
man = comp.fetch('pw_managed', {})
for path, ops, counts in mods:
ms = 0.0
try:
for x, c in zip(ops, counts):
if x.totalCooks != c:
ms += x.cpuCookTime + (0.0 if x.type in NOGPU else x.gpuCookTime)
except Exception:
continue # un OP borrado entre los dos frames
e = dict(costs.get(path, {}))
kind = 'byp' if man.get(path, {}).get('how') == 'bypass' else 'full'
hist = (list(e.get(kind + '_s', [])) + [ms])[-5:] # mediana de las 5 últimas: sin los picos (compilar un shader)
e[kind + '_s'] = hist
if len(hist) >= 3:
e[kind] = sorted(hist)[len(hist) // 2]
costs[path] = e
comp.store('pw_cost', costs)
tile_draw(comp)
def cost_text(comp, path, how, awake):
e = comp.fetch('pw_cost', {}).get(path, {})
full, byp = e.get('full'), e.get('byp')
if awake:
return ('%.1f ms' % full) if full is not None else chr(8212), 0.0
if how == 'sleep':
return (MINUS + '%.1f ms' % full, full) if full is not None else (MINUS + ' ms', 0.0)
if byp is not None and full is not None:
return '%.1f ms (%s%.1f)' % (byp, MINUS, max(0.0, full - byp)), max(0.0, full - byp)
return ('%.1f ms' % byp) if byp is not None else chr(8212), 0.0
# ---- enganches del tile que redefine build4 (avisos de consumo); aquí no hacen nada
def cost_ink(comp, path, how, awake):
return DIM
def row_extra(comp, path, how, awake, yc, ctext, label):
return
def extra_h(comp, rows):
return 0
def extra_draw(comp, rows, y0, rect, label):
return
# ---- maqueta: rects (y hacia abajo) con relleno y tinta del texto; textos para el Text TOP (y desde abajo)
def tile_draw(comp):
s = tstate(comp)
res = s.get('res', [])
rows = [r for r in res if r[1] is not None or (r[4] and r[4] != 'empty')]
n = max(1, len(rows))
XH = extra_h(comp, rows)
H = HEAD + SCN + n * ROWH + 8 + XH + FOOT
rects, texts, hits = [], [], []
def rect(x0, y0, x1, y1, fill=None, ink=None):
rects.append((x0, y0, x1, y1, fill, ink))
def label(x, yc, t, ink=TXT, right=False):
w = text_w(comp, t)
x0 = x - w if right else x
texts.append((x0, H - yc - 5, t))
rect(x0 - 1, yc - 10, x0 + w + 2, yc + 10, None, ink)
rect(0, 0, TW, H, BG)
# cabecera: escena activa y ahorro
sc = cur_scene(comp)
scene = 'MANUAL' if sc == 0 else (getattr(comp.par, 'Scenename%d' % sc).eval() or 'Scene %d' % sc)
label(PAD, HEAD / 2, 'powerCTRL', DIM)
if not comp.par.Enable.eval():
label(PAD + 96, HEAD / 2, 'ENABLE OFF ' + chr(183) + ' all awake', AMB)
else:
label(PAD + 96, HEAD / 2, fit(comp, scene, 200), TXT)
saving = 0.0
ctexts = []
for r in rows:
k, path, how, awake, why = r
t, sv = cost_text(comp, path, how, awake) if path else ('', 0.0)
saving += sv
ctexts.append(t)
if saving > 0.05:
label(TW - PAD, HEAD / 2, 'saving ' + chr(8776) + ' %.1f ms' % saving, ACC, right=True)
rect(0, HEAD - 1, TW, HEAD, LINE)
# escenas: Manual + 1…N
ns = int(comp.par.Scenes.eval())
nb = ns + 1
gap = 6
bw = (TW - 2 * PAD - gap * (nb - 1)) / nb
y0, y1 = HEAD + 8, HEAD + SCN - 4
for i in range(nb):
x0 = PAD + i * (bw + gap)
x1 = x0 + bw
on = (i == sc)
rect(x0, y0, x1, y1, ACC if on else BTN)
if i == 0:
t = 'Manual'
else:
nm = getattr(comp.par, 'Scenename%d' % i).eval() or 'Scene %d' % i
t = '%d %s' % (i, nm) if nm != 'Scene %d' % i else str(i)
t = fit(comp, t, bw - 10)
label(x0 + (bw - text_w(comp, t)) / 2, (y0 + y1) / 2, t, INK if on else TXT)
hits.append((x0, y0, x1, y1, 'scene', i))
# módulos
top = HEAD + SCN + 4
if not rows:
label(PAD, top + ROWH / 2, 'No modules: Add Module on the Modules page', DIM)
for j, r in enumerate(rows):
k, path, how, awake, why = r
ya, yb = top + j * ROWH + 1, top + (j + 1) * ROWH - 1
yc = (ya + yb) / 2
rect(PAD, ya, TW - PAD, yb, ROWBG)
name = getattr(comp.par, 'Mod%dtarget' % k).eval()
if path is None:
word, led, nink = (why or '').split(':')[0].upper(), ERR, DIM
elif how == 'none':
word, led, nink = ('PROTECTED' if why.startswith('protected') else 'AWAKE'), ACC, TXT
if why and not why.startswith('protected'):
word = 'NO REST'
elif awake:
word, led, nink = 'AWAKE', ACC, TXT
elif how == 'sleep':
word, led, nink = 'ASLEEP', OFF, DIM
else:
word, led, nink = 'BYPASS', AMB, TXT
rect(PAD + 10, yc - 6, PAD + 22, yc + 6, led)
label(PAD + 32, yc, fit(comp, name, 180), nink)
label(PAD + 228, yc, word, led if word not in ('ASLEEP',) else DIM)
if ctexts[j]:
label(TW - PAD - 10, yc, ctexts[j], cost_ink(comp, path, how, awake), right=True)
row_extra(comp, path, how, awake, yc, ctexts[j], label)
if path is not None and how != 'none':
hits.append((PAD, ya, TW - PAD, yb, 'row', k))
if XH:
extra_draw(comp, rows, top + n * ROWH + 4, rect, label)
# pie: All On y resumen
fy0, fy1 = H - FOOT + 8, H - 10
rect(0, H - FOOT, TW, H - FOOT + 1, LINE)
rect(PAD, fy0, PAD + 104, fy1, BTN)
label(PAD + (104 - text_w(comp, 'ALL ON')) / 2, (fy0 + fy1) / 2, 'ALL ON', TXT)
hits.append((PAD, fy0, PAD + 104, fy1, 'allon', 0))
na = sum(1 for r in rows if r[1] and r[3])
nz = sum(1 for r in rows if r[1] and not r[3] and r[2] == 'sleep')
nby = sum(1 for r in rows if r[1] and not r[3] and r[2] == 'bypass')
label(TW - PAD, (fy0 + fy1) / 2, '%d awake%s%d asleep%s%d bypass' % (na, DOT, nz, DOT, nby), DIM, right=True)
# escribir solo lo que cambia
s['hits'] = hits
s['H'] = H
key = tuple(texts)
if s.get('tkey') != key:
s['tkey'] = key
d = comp.op('tile_spec')
d.clear()
d.appendRow(['x', 'y', 'text'])
for x, y, t in texts:
d.appendRow(['%.1f' % x, '%.1f' % y, t])
arr = np.zeros((3, max(1, len(rects)), 4), dtype=np.float32)
for i, (x0, y0, x1, y1, fill, ink) in enumerate(rects):
arr[0, i] = (x0, y0, x1, y1)
if fill is not None:
arr[1, i] = (fill[0], fill[1], fill[2], 1.0)
if ink is not None:
arr[2, i] = (ink[0], ink[1], ink[2], 1.0)
old = s.get('tarr')
if old is None or old.shape != arr.shape or not np.array_equal(old, arr):
s['tarr'] = arr
ts = comp.op('tile_size')
if ts.par.const1value.eval() != H:
ts.par.const1value = H
if ts.par.const2value.eval() != len(rects):
ts.par.const2value = len(rects)
ts.par.const3value = (ts.par.const3value.eval() + 1) % 100000
def tile_array(comp):
a = tstate(comp).get('tarr')
return a if a is not None else np.zeros((3, 1, 4), dtype=np.float32)
def tile_click(comp, u, v):
s = tstate(comp)
H = s.get('H')
if not H:
return
x, y = u * TW, (1.0 - v) * H
for x0, y0, x1, y1, kind, arg in s.get('hits', []):
if x0 <= x < x1 and y0 <= y < y1:
if kind == 'scene':
if arg == 0:
comp.par.Scene.val = 'manual'
else:
go_scene(comp, arg)
elif kind == 'row':
p = getattr(comp.par, 'Mod%dawake' % arg)
p.val = not bool(p.eval())
elif kind == 'allon':
all_on(comp)
schedule(comp)
return
if tile_draw not in APPLY_HOOKS:
APPLY_HOOKS.append(tile_draw)
# ---- build4: avisos ----
WIN_S = 3.0 # ventana de muestras por módulo (mediana y pico)
REFRESH = 60 # cada cuántos frames: pw_cost, Limits, out1 y tile
OPS_TTL = 600 # frames que vale la lista de OPs de un módulo
UP = chr(8593)
WPARS = ('Warnings', 'Warnlevel', 'Alertlevel')
def budget():
return 1000.0 / max(1.0, float(project.cookRate))
def limits(comp):
# (warn, alert) en ms, o None con Warnings Off
if not comp.par.Warnings.eval():
return None
b = budget()
w = b * float(comp.par.Warnlevel.eval()) / 100.0
return w, max(w, b * float(comp.par.Alertlevel.eval()) / 100.0)
def level_of(comp, ms, lim=None):
if lim is None:
lim = limits(comp)
if lim is None or ms is None:
return 0
return 2 if ms >= lim[1] else (1 if ms >= lim[0] else 0)
def costs_of(comp):
s = tstate(comp)
if 'costs' not in s:
s['costs'] = dict(comp.fetch('pw_cost', {}))
return s['costs']
def now_cost(comp, path, how, awake):
# (mediana, pico) del estado actual: despierto = full, en Bypass = byp, dormido = nada (no gasta)
if not path:
return None, None
kind = 'full' if awake else ('byp' if how == 'bypass' else None)
if kind is None:
return None, None
e = costs_of(comp).get(path, {})
return e.get(kind), e.get(kind + '_pk', e.get(kind))
def cost_tick(comp, frame):
s = tstate(comp)
rr = s.setdefault('rr', {'i': 0, 'pend': None, 'ops': {}})
costs = costs_of(comp)
man = comp.fetch('pw_managed', {})
live = []
for k, path, how, awake, why in s.get('res', []):
o = op(path) if path else None
if o is not None and o.allowCooking:
live.append(path)
pend = rr['pend']
if pend is not None:
# frame de leer: lo que cocinó el módulo desde el frame en que se apuntó (un frame entero)
if pend[4] != frame:
path, kind, ops, gpu, counts, f0 = pend[0], pend[1], pend[2], pend[3], pend[5], pend[4]
rr['pend'] = None
o = op(path)
now = 'byp' if man.get(path, {}).get('how') == 'bypass' else 'full'
if o is not None and o.allowCooking and now == kind: # si se durmió o cambió de modo, no vale
try:
ms = 0.0
for x, g, c in zip(ops, gpu, counts):
if x.totalCooks != c:
ms += x.cpuCookTime + (x.gpuCookTime if g else 0.0)
e = costs.setdefault(path, {})
n = max(5, int(WIN_S * float(project.cookRate) / (2 * max(1, len(live)))))
h = (list(e.get(kind + '_h', [])) + [ms])[-n:]
e[kind + '_h'] = h
if len(h) >= 3:
e[kind] = sorted(h)[len(h) // 2]
e[kind + '_pk'] = max(h)
except Exception:
rr['ops'].pop(path, None) # un OP borrado entre los dos frames: lista nueva en su turno
elif live:
# frame de apuntar (se alterna con el de leer: la mitad de coste por frame)
path = live[rr['i'] % len(live)]
rr['i'] = (rr['i'] + 1) % len(live)
c = rr['ops'].get(path)
if c is None or frame - c[0] > OPS_TTL or frame < c[0]:
ops = [x for x in op(path).findChildren() if not x.isCOMP]
c = (frame, ops, [x.type not in NOGPU for x in ops])
rr['ops'][path] = c
kind = 'byp' if man.get(path, {}).get('how') == 'bypass' else 'full'
try:
rr['pend'] = (path, kind, c[1], c[2], frame, [x.totalCooks for x in c[1]])
except Exception:
rr['ops'].pop(path, None)
if frame % REFRESH == 0:
comp.store('pw_cost', dict(costs))
refresh_warn(comp)
def refresh_warn(comp):
lim = limits(comp)
t = '' if lim is None else 'frame %.1f ms %s warn %.1f ms %s alert %.1f ms' % (
budget(), chr(183), lim[0], chr(183), lim[1])
p = comp.par.Limits
if p.eval() != t:
p.val = t
s = tstate(comp)
write_out(comp, [(k, op(path) if path else None, how, awake, why) for k, path, how, awake, why in s.get('res', [])])
tile_draw(comp)
def write_out(comp, res):
# build1 + niveles: scene, un canal por módulo (1 despierto / 0 en reposo) y, con Warnings, <módulo>_level y level
chans = [('scene', float(cur_scene(comp)))]
used = set(['scene'])
lim = limits(comp)
lv = []
for k, o, how, awake, why in res:
if o is None:
continue
nm = chan_name(o.name, used)
chans.append((nm, 1.0 if awake else 0.0))
if lim is not None:
lv.append((nm + '_level', float(level_of(comp, now_cost(comp, o.path, how, awake)[0], lim))))
if lim is not None:
for n, v in lv:
chans.append((chan_name(n, used), v))
chans.append((chan_name('level', used), max([v for n, v in lv] + [0.0])))
c = comp.op('state')
if c.seq.const.numBlocks != len(chans):
c.seq.const.numBlocks = len(chans)
for i, (n, v) in enumerate(chans):
pn, pv = getattr(c.par, 'const%dname' % i), getattr(c.par, 'const%dvalue' % i)
if pn.eval() != n:
pn.val = n
if pv.eval() != v:
pv.val = v
# ---- tile: tinta del coste, pico, franja TOP
INKS = (DIM, AMB, ERR)
def cost_ink(comp, path, how, awake):
return INKS[level_of(comp, now_cost(comp, path, how, awake)[0])]
def row_extra(comp, path, how, awake, yc, ctext, label):
if not awake:
return
lim = limits(comp)
med, pk = now_cost(comp, path, how, awake)
lv = level_of(comp, pk, lim)
if lv == 0 or med is None or pk < med * 1.25 + 0.05:
return
label(TW - PAD - 10 - text_w(comp, ctext) - 12, yc, UP + '%.1f' % pk, INKS[lv], right=True)
def heaviest(comp, rows):
items = []
for k, path, how, awake, why in rows:
med = now_cost(comp, path, how, awake)[0]
if med is not None and med > 0.0:
items.append((med, getattr(comp.par, 'Mod%dtarget' % k).eval()))
items.sort(reverse=True)
return items[:3]
def extra_h(comp, rows):
return 30 if limits(comp) is not None and heaviest(comp, rows) else 0
def extra_draw(comp, rows, y0, rect, label):
lim = limits(comp)
yc = y0 + 15
label(PAD + 10, yc, 'TOP', DIM)
x = PAD + 10 + text_w(comp, 'TOP') + 16
slot = (TW - PAD - 10 - x) / 3.0
for med, name in heaviest(comp, rows):
lv = level_of(comp, med, lim)
v = '%.1f' % med
nm = fit(comp, name, slot - text_w(comp, v) - 18)
label(x, yc, nm, TXT if lv else DIM)
label(x + text_w(comp, nm) + 6, yc, v, INKS[lv])
x += slot
# ---- los pars de Warnings redibujan al momento
_on_change_b1 = on_change
def on_change(comp, par, prev):
if par.name in WPARS:
refresh_warn(comp)
return
_on_change_b1(comp, par, prev)
start python · 32 línieslíneaslines
# start: al abrir el proyecto o soltar el .tox, y revisión cada 30 frames
def onStart():
op('util').module.on_start(me.parent())
return
def onCreate():
op('util').module.on_start(me.parent())
return
def onExit():
return
def onFrameStart(frame):
if frame % 30 == 0:
op('util').module.check(me.parent())
return
def onFrameEnd(frame):
return
def onPlayStateChange(state):
return
def onDeviceChange():
return
def onProjectPreSave():
return
def onProjectPostSave():
return
list_exec python · 21 línieslíneaslines
# list_exec: pars del propio powerCTRL → util
def onValueChange(par, prev):
op('util').module.on_change(me.parent(), par, prev)
return
def onPulse(par):
op('util').module.on_pulse(me.parent(), par)
return
def onExpressionChange(par, val, prev):
return
def onExportChange(par, val, prev):
return
def onEnableChange(par, val, prev):
return
def onModeChange(par, val, prev):
return
tile_exec python · 29 línieslíneaslines
# tile_exec: coste de los módulos (util.cost_tick: un frame de cada 60)
def onFrameEnd(frame):
op('util').module.cost_tick(me.parent(), frame)
return
def onStart():
return
def onCreate():
return
def onExit():
return
def onFrameStart(frame):
return
def onPlayStateChange(state):
return
def onDeviceChange():
return
def onProjectPreSave():
return
def onProjectPostSave():
return
tile_click python · 18 línieslíneaslines
# tile_click: un clic en el tile (escena, fila, All On)
def onOffToOn(panelValue):
t = me.parent().op('tile')
op('util').module.tile_click(me.parent(), float(t.panel.u), float(t.panel.v))
return
def whileOn(panelValue):
return
def onOnToOff(panelValue):
return
def whileOff(panelValue):
return
def onValueChange(panelValue, prev):
return
tile_shader glsl · 25 línieslíneaslines
// powerCTRL: tile. Entrada 0 = rects (N x 3: fila 0 caja x0 y0 x1 y1 en px con y hacia abajo, fila 1 relleno,
// fila 2 tinta del texto; alfa 0 = no cambia), entrada 1 = textos en blanco (Text TOP). El último rect manda.
uniform vec4 uN; // x: nº de rects
out vec4 fragColor;
void main() {
vec2 R = uTDOutputInfo.res.zw;
vec2 p = vUV.st * R;
float yd = R.y - p.y;
vec3 c = vec3(0.07);
vec3 ink = vec3(0.92);
int n = int(uN.x + 0.5);
for (int i = 0; i < n; i++) {
vec4 r = texelFetch(sTD2DInputs[0], ivec2(i, 0), 0);
if (p.x >= r.x && p.x < r.z && yd >= r.y && yd < r.w) {
vec4 f = texelFetch(sTD2DInputs[0], ivec2(i, 1), 0);
vec4 k = texelFetch(sTD2DInputs[0], ivec2(i, 2), 0);
if (f.a > 0.0) c = f.rgb;
if (k.a > 0.0) ink = k.rgb;
}
}
vec4 t = texture(sTD2DInputs[1], vUV.st);
c = mix(c, ink, t.a);
fragColor = TDOutputSwizzle(vec4(c, 1.0));
}
tile_data_callbacks python · 12 línieslíneaslines
# powerCTRL: rects del tile (util.tile_array) a la textura; solo cocina cuando cambia tile_size (tick)
def onSetupParameters(scriptOp):
return
def onPulse(par):
return
def onCook(scriptOp):
scriptOp.parent().op('tile_size')['tick'].eval()
scriptOp.copyNumpyArray(scriptOp.parent().op('util').module.tile_array(scriptOp.parent()))
return
Aquesta part és en castellà.This part is in Spanish.
Decisiones de diseño
- Sleep =
allowCookingOff del COMP: no cocina nada dentro (verificado en los 1070 OPs del proyecto: 0 OPs, 0 ms de CPU y de GPU dormido). No libera la memoria de sus texturas: dormir quita el trabajo, no la memoria. - Bypass = el par Bypass del propio módulo y se devuelve el valor que tenía al despertarlo (en
pw_managed, que sobrevive a reconstruir y al.toe). - Auto decide por la categoría y los cables: CTRL / OUT / XPORT / MIX no se duermen (otros leen de ellos o son la salida; Mode Sleep lo fuerza); si va a un MIX o a nada, Sleep (la capa queda vacía); un FX en mitad de una cadena con Bypass, Bypass (la imagen sigue pasando); si no, Sleep y Status avisa de a quién deja en negro.
- Todo por evento (un cambio de par, un pulso) y una revisión cada 30 frames que ve bloques nuevos de la secuencia, cables, renombres y a quien enciende a mano un módulo dormido (lo vuelve a dormir).
- Escenas como casillas por fila (S1…S8): elegir una escena pone Awake según su casilla; tocar Awake a mano vale hasta la siguiente escena; la casilla de la escena activa se aplica al momento.
- Tile clicable sin paneles por fila: rects en una textura + un Text TOP con todos los textos, coloreados por zona en el GLSL; los clics, por zonas guardadas al dibujar (nada que re-enganchar al reconstruir).
- Coste en el estado en que está: despierto =
full, en Bypass =byp; dormido enseña lo que ahorra (−X ms). - In / Select solo CPU (1.0.0 corregida): su reloj de GPU abarca la cocción del módulo de arriba cuando son los primeros en pedirle la imagen; con la GPU sumaba a un módulo el trabajo (y las esperas) de otro.
- Coste por turnos (1.1): un módulo por turno, apuntar un frame y leer el siguiente, en vez de todos en un frame cada segundo: el peor frame pasa de ~0,9 ms a ~0,1 ms, hay ~20 muestras por módulo en 3 s (mediana estable y pico) y no cae siempre en el mismo frame de cada segundo.
- Nivel con la mediana, el pico solo como texto: un pico suelto (compilar un shader) no debe encender un LED; se ve en la fila (↑pico) cuando pasa de Warn y de 1,25 × la mediana.
- Umbrales en % del frame (no en ms): valen a 30 y a 60 fps. Los ms reales, en Limits.
- Franja TOP con los 3 que más gastan: responde a "¿a quién duermo?" sin leer toda la lista.
Lo que falló y cómo se arregló
| Síntoma | Causa | Solución |
|---|---|---|
| mixer6MIX marcaba 7,4 ms (y timeMachineFX 4,7) con ~2 ms reales | El GPU de su In TOP (11–13 ms) era la cocción de gridGEN, que el In pedía primero: la GPU parada esperando a la CPU de arriba. A/B: cocinar gridGEN antes dejaba el In a 0 y el frame igual | In / Select solo CPU (NOGPU) |
| Un pico de compilar un shader (20 ms) disparaba el coste | La media se lo comía | Mediana (5 muestras en la 1.0; ~3 s de muestras en la 1.1) |
Leer childrenCPUCookTime del COMP cada frame (barato) no servía para los picos | childrenCPUCookAbsFrame no se actualiza en cada frame en la mayoría de módulos (119 de 120 frames sin dato) | Sumar los OPs del módulo, uno por turno |
| Medir por turnos en todos los frames costaba más por segundo que antes | Apuntar y leer en el mismo frame: ~0,08 ms cada frame | Alternar un frame de apuntar y otro de leer y guardar de antemano qué OPs son In / Select: ~0,04 ms de media |
| Un módulo de prueba "pesado" medía 0,004 ms | El Script CHOP que gastaba CPU solo cocinó una vez: leer absTime dentro del callback no lo hace depender del tiempo | Una entrada que cambia cada frame (Constant con absTime.frame), como #46 |
| El export no guardaba: "storage no vacío" | apply al final de build3 vuelve a guardar pw_managed (vacío) | Aceptar pw_managed = {}, como la 1.0 |
Cuánto cuesta
Medido a 60 fps (TouchDesigner 2025.33230, i7-10750H, RTX 3060 Laptop):
| Pieza | Coste |
|---|---|
| Medida por turnos (8 módulos, 40–60 OPs cada uno) | Peor frame ~0,11 ms, ~0,04 ms de media (la 1.0: ~0,9 ms de golpe una vez por segundo) |
apply | Solo con un cambio (un frame después) |
check | Cada 30 frames: lista, cables y estado real |
tile_draw | 0,22 ms; los TOPs del tile solo cocinan si cambia lo dibujado (2 redibujos en 300 frames con el coste estable) |
| Lo que ahorra dormir | blobtrackFX (copia, Noise 1280 × 720): 2,74 ms de CPU + 1,27 de GPU → 0 / 0 |
Medida verificada con módulos de prueba de CPU conocida: 4 ms → 4,04; 7 ms → 7,04; 0,5 ms con 12 ms cada 20 frames → mediana 0,53 y pico 12,06; 0,2 → 0,22.