From 59355909f2de9236af8168a26c70bcf6caa3b285 Mon Sep 17 00:00:00 2001 From: Elvis Claros Castro Date: Sat, 26 Sep 2026 20:21:47 -0300 Subject: Import video pipeline as it was --- .gitignore | 10 + README.md | 252 +++++++++++++++++ blender/base.py | 659 ++++++++++++++++++++++++++++++++++++++++++++ blender/bloques.py | 279 +++++++++++++++++++ blender/bolapeluda.py | 260 +++++++++++++++++ blender/caos.py | 219 +++++++++++++++ blender/diferencial.py | 304 ++++++++++++++++++++ blender/domino.py | 539 ++++++++++++++++++++++++++++++++++++ blender/galton.py | 316 +++++++++++++++++++++ brand/README.md | 50 ++++ brand/avatar-1024.png | Bin 0 -> 88757 bytes brand/avatar-plano-1024.png | Bin 0 -> 87007 bytes brand/avatar-plano.svg | 5 + brand/avatar.svg | 3 + brand/banner-1920.png | Bin 0 -> 58751 bytes brand/banner.svg | 4 + brand/make_logo.py | 235 ++++++++++++++++ brand/wordmark-2400.png | Bin 0 -> 57299 bytes brand/wordmark-claro.svg | 3 + brand/wordmark-mono.svg | 3 + brand/wordmark-plano.svg | 5 + brand/wordmark.svg | 3 + godot/project.godot | 13 + godot/sim.gd | 223 +++++++++++++++ godot/sim.tscn | 6 + scenes/overlay.py | 43 +++ scenes/tiktok.py | 156 +++++++++++ scenes/v10_buffon.py | 150 ++++++++++ scenes/v11_collatz.py | 171 ++++++++++++ scenes/v12_simpson.py | 188 +++++++++++++ scenes/v13_cuerda.py | 161 +++++++++++ scenes/v14_gabriel.py | 172 ++++++++++++ scenes/v15_mobius.py | 241 ++++++++++++++++ scenes/v16_bayes.py | 160 +++++++++++ scenes/v17_cicloide.py | 275 ++++++++++++++++++ scenes/v18_dados.py | 189 +++++++++++++ scenes/v1_montyhall.py | 166 +++++++++++ scenes/v2_nueves.py | 121 ++++++++ scenes/v3_cumple.py | 143 ++++++++++ scenes/v4_luna.py | 178 ++++++++++++ scenes/v5_japones.py | 160 +++++++++++ scenes/v6_benford.py | 131 +++++++++ scenes/v7_hilbert.py | 135 +++++++++ scenes/v8_reuleaux.py | 158 +++++++++++ scenes/v9_regla72.py | 124 +++++++++ scripts/build_blender.py | 58 ++++ scripts/build_video.py | 93 +++++++ scripts/gen_audio.py | 119 ++++++++ scripts/music.py | 166 +++++++++++ scripts/narration.py | 431 +++++++++++++++++++++++++++++ scripts/numspell.py | 57 ++++ scripts/regen.py | 46 ++++ scripts/repick.py | 48 ++++ scripts/verify.py | 53 ++++ scripts/verify_final.py | 50 ++++ 55 files changed, 7734 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 blender/base.py create mode 100644 blender/bloques.py create mode 100644 blender/bolapeluda.py create mode 100644 blender/caos.py create mode 100644 blender/diferencial.py create mode 100644 blender/domino.py create mode 100644 blender/galton.py create mode 100644 brand/README.md create mode 100644 brand/avatar-1024.png create mode 100644 brand/avatar-plano-1024.png create mode 100644 brand/avatar-plano.svg create mode 100644 brand/avatar.svg create mode 100644 brand/banner-1920.png create mode 100644 brand/banner.svg create mode 100644 brand/make_logo.py create mode 100644 brand/wordmark-2400.png create mode 100644 brand/wordmark-claro.svg create mode 100644 brand/wordmark-mono.svg create mode 100644 brand/wordmark-plano.svg create mode 100644 brand/wordmark.svg create mode 100644 godot/project.godot create mode 100644 godot/sim.gd create mode 100644 godot/sim.tscn create mode 100644 scenes/overlay.py create mode 100644 scenes/tiktok.py create mode 100644 scenes/v10_buffon.py create mode 100644 scenes/v11_collatz.py create mode 100644 scenes/v12_simpson.py create mode 100644 scenes/v13_cuerda.py create mode 100644 scenes/v14_gabriel.py create mode 100644 scenes/v15_mobius.py create mode 100644 scenes/v16_bayes.py create mode 100644 scenes/v17_cicloide.py create mode 100644 scenes/v18_dados.py create mode 100644 scenes/v1_montyhall.py create mode 100644 scenes/v2_nueves.py create mode 100644 scenes/v3_cumple.py create mode 100644 scenes/v4_luna.py create mode 100644 scenes/v5_japones.py create mode 100644 scenes/v6_benford.py create mode 100644 scenes/v7_hilbert.py create mode 100644 scenes/v8_reuleaux.py create mode 100644 scenes/v9_regla72.py create mode 100644 scripts/build_blender.py create mode 100644 scripts/build_video.py create mode 100644 scripts/gen_audio.py create mode 100644 scripts/music.py create mode 100644 scripts/narration.py create mode 100644 scripts/numspell.py create mode 100644 scripts/regen.py create mode 100644 scripts/repick.py create mode 100644 scripts/verify.py create mode 100644 scripts/verify_final.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7da0c69 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +# Generated output: renders, audio, final videos and scratch space +/render/ +/out/ +/media/ +/tmp/ +/audio/ +/godot/trabajo/ +/godot/.godot/ +__pycache__/ +*.pyc diff --git a/README.md b/README.md new file mode 100644 index 0000000..bcced52 --- /dev/null +++ b/README.md @@ -0,0 +1,252 @@ +# 24 videos verticales para TikTok — 100% generados localmente + +Todo corre offline: **Manim** para la animación 2D, **Blender** (EEVEE, headless) para +las escenas 3D, **Godot** (motor de física Jolt, headless) para la física de +rígidos, **qwentts.cpp** (voz clonada rioplatense) para la locución y las +muestras de piano de `keysound` para la música. + +## Los videos (`out/`) + +| Archivo | Tema | Duración | Gancho | +|---|---|---|---| +| `montyhall.mp4` | Problema de Monty Hall | 39,5 s | genera debate en comentarios | +| `nueves.mp4` | 0,999… = 1 | 38,8 s | genera debate en comentarios | +| `cumple.mp4` | Paradoja del cumpleaños | 38,6 s | dato que sorprende | +| `luna.mp4` | Doblar un papel hasta la Luna | 38,4 s | dato que sorprende | +| `japones.mp4` | Multiplicar con líneas | 38,8 s | útil, se guarda y se comparte | +| `benford.mp4` | Ley de Benford (detectar fraude) | 42,8 s | dato que sorprende + útil | +| `hilbert.mp4` | El hotel infinito | 37,1 s | genera debate en comentarios | +| `reuleaux.mp4` | Por qué las tapas son redondas | 36,0 s | satisfactorio de mirar | +| `regla72.mp4` | La regla del 72 | 35,5 s | útil, se guarda | +| `buffon.mp4` | Sacar π tirando agujas | 36,7 s | belleza matemática | +| `collatz.mp4` | Conjetura de Collatz (3n+1) | 46,2 s | misterio sin resolver | +| `simpson.mp4` | Paradoja de Simpson | 53,0 s | genera debate + útil | +| `cuerda.mp4` | Una cuerda alrededor de la Tierra | 45,4 s | dato que sorprende | +| `gabriel.mp4` | El cuerno de Gabriel | 40,5 s | belleza matemática | +| `mobius.mp4` | Cinta de Möbius | 46,3 s | para hacer en casa | +| `bayes.mp4` | Falso positivo (test médico) | 46,9 s | genera debate + útil | +| `cicloide.mp4` | Braquistócrona: la curva más rápida | 47,6 s | satisfactorio de mirar | +| `dados.mp4` | Dados no transitivos | 50,6 s | genera debate en comentarios | +| `bolapeluda.mp4` | Teorema de la bola peluda (3D) | 41,9 s | satisfactorio de mirar | +| `caos.mp4` | Tres péndulos dobles y 1 mm (3D) | 40,6 s | hipnótico, se mira entero | +| `diferencial.mp4` | Cómo funciona el diferencial (3D) | 44,1 s | útil, se guarda y se comparte | +| `galton.mp4` | Tablero de Galton: 500 bolitas forman la campana (Blender + Godot) | 45,7 s | satisfactorio + pregunta en comentarios | +| `bloques.mp4` | Pila armónica: bloques que sobresalen de la mesa (Blender + Godot) | 48,0 s | para hacer en casa + dato que sorprende | +| `domino.mp4` | Dominó ×1,5: de 5 mm al Aconcagua (Blender + Godot) | 66,7 s | exponencial + pregunta en comentarios (más de 1 min) | + +Formato: 1080×1920, 30 fps, H.264 + AAC 48 kHz estéreo, **−13,8 a −15,3 LUFS** +medidos (el objetivo de TikTok es −14, así no te lo bajan ni te lo suben), +pico real por debajo de −1 dBTP. +Subtítulos quemados: el 80 % mira sin audio. + +## Textos sugeridos para publicar + +**montyhall** — ¿Te quedás o cambiás? El 87% se equivoca 🚪 +`#matematica #montyhall #datocurioso #probabilidad #argentina` + +**nueves** — 0,999… es EXACTAMENTE 1. Peleame en los comentarios 🧮 +`#matematica #mindblown #datocurioso #numeros #viral` + +**cumple** — Con 23 personas ya hay 50% de que dos cumplan el mismo día 🎂 +`#paradoja #datocurioso #matematica #probabilidad #sabiasque` + +**luna** — Doblá un papel 42 veces y llegás a la Luna 🌙 +`#exponencial #datocurioso #ciencia #mindblown #sabiasque` + +**japones** — Así multiplican en Japón, sin tablas ✏️ +`#trucosmatematicos #japon #escuela #tarea #aprendeentiktok` + +**benford** — Los números inventados se notan. Así agarran fraudes 🕵️ +`#benford #fraude #estadistica #datocurioso #sabiasque` + +**hilbert** — Un hotel lleno con infinitas habitaciones… y entran infinitos más 🏨 +`#infinito #matematica #paradoja #mindblown #hilbert` + +**reuleaux** — Por qué las tapas de alcantarilla son redondas 🛞 +`#datocurioso #geometria #ingenieria #sabiasque #reuleaux` + +**regla72** — La cuenta que te dice cuándo se duplica tu plata 💸 +`#finanzaspersonales #inversiones #interescompuesto #inflacion #argentina` + +**buffon** — Tiro agujas al piso y sale π. Sin ningún círculo 🎲 +`#pi #matematica #azar #datocurioso #mindblown` + +**collatz** — Elegí cualquier número. Nadie pudo demostrar por qué siempre cae al 1 🌀 +`#collatz #matematica #misterio #datocurioso #mindblown` + +**simpson** — Gana en los dos grupos y pierde en el total. Así te miente un promedio 📊 +`#estadistica #paradoja #datos #sabiasque #matematica` + +**cuerda** — Le agrego 1 metro a una cuerda que rodea la Tierra. ¿Cuánto se levanta? 🌍 +`#datocurioso #matematica #mindblown #sabiasque #ciencia` + +**gabriel** — Lo podés llenar de pintura, pero no lo podés pintar 🎺 +`#infinito #matematica #paradoja #calculo #mindblown` + +**mobius** — Cortá esta cinta al medio y NO van a salir dos ✂️📄 +`#mobius #topologia #experimento #hacelovos #datocurioso` + +**bayes** — El test acierta el 99% y te dio positivo. La chance de estar enfermo es 9% 🧪 +`#probabilidad #estadistica #salud #sabiasque #bayes` + +**cicloide** — La recta es el camino más corto… y pierde la carrera 🎢 +`#fisica #matematica #satisfying #mindblown #cicloide` + +**dados** — Elegí el dado que quieras. Elijo después y te gano igual 🎲 +`#probabilidad #dados #juegos #datocurioso #matematica` + +**bolapeluda** — No podés peinar una esfera sin dejar un remolino. Es un teorema 🌀 +`#topologia #matematica #3d #datocurioso #mindblown` + +**caos** — Tres péndulos idénticos salvo 1 milímetro. A los 5 segundos no se parecen en nada 🎲 +`#caos #fisica #simulacion #mindblown #efectomariposa` + +**diferencial** — Por qué tu auto puede doblar sin que una rueda patine ⚙️ +`#mecanica #autos #ingenieria #sabiasque #comofunciona` + +**galton** — 500 bolitas, cada una al azar… y todas juntas dibujan una campana 🔔 +`#probabilidad #estadistica #galton #satisfying #matematica` + +**bloques** — Apilé bloques hasta que el de arriba quedó en el aire. ¿Hasta dónde llegás vos? 📚 +`#fisica #experimento #matematica #paraHacerEnCasa #sabiasque` + +**domino** — Una ficha de 5 mm puede tirar un edificio. ¿En qué ficha se cae tu casa? 🏠 +`#domino #fisica #exponencial #satisfying #sabiasque` + +Subí uno por día, mismo horario, y alterná los tres tipos: + +- **debate** (comentarios, que es lo que más empuja el alcance): montyhall, nueves, + hilbert, simpson, cuerda, dados +- **útil** (se guarda y se comparte): japones, regla72, benford, bayes, diferencial, bloques +- **espectáculo** (se mira hasta el final): reuleaux, buffon, mobius, gabriel, collatz, + luna, cumple, cicloide, bolapeluda, caos, galton, domino + +Los tres últimos (`bolapeluda`, `caos`, `diferencial`) están hechos en Blender: sirven +para cortar la monotonía visual de Manim sin cambiar el estilo del canal, porque la +capa de interfaz (chip, barra y subtítulos) es la misma. + +`mobius` es el único con llamado a la acción físico ("hacelo con una hoja"): +esos suelen traer videos-respuesta, que valen doble. + +### Blender + Godot (`galton`, `bloques`) + +Blender diseña y Godot calcula la física: + +1. `MODO=sim blender -b -P blender/.py` arma la escena y exporta a glTF solo + los objetos físicos. El prefijo del nombre dice qué es cada uno para Godot + (`fijo_` malla estática, `caja_` caja estática, `compuerta_` estática que se saca + con un evento, `bola_` esfera rígida, `bloque_` caja rígida). Después corre + `godot --headless --fixed-fps 240 -- godot/trabajo/.json`. +2. `godot/sim.gd` carga el glb en tiempo de ejecución, crea los cuerpos, aplica los + eventos del guion (soltar, sacar la compuerta) en el segundo exacto del timeline + y graba la pose de cada cuerpo a 30 fps en coordenadas de Blender + (`godot/trabajo/.bin`). +3. `blender -b -P blender/.py` lee esas poses y renderiza con los materiales + de verdad (madera procedural, latón, acero). + +Nada del movimiento está animado a mano. Algunos números que salen de la simulación: + +- **galton**: casilleros `[0 1 7 29 70 104 96 83 65 35 10 0 0]` (desvío de 1,82 + casilleros; el binomial ideal de 12 filas da 1,73). La columna del medio tiene + **96**: es la respuesta a la pregunta del final. +- **bloques**: la pila de 5 con corrimientos armónicos ×0,95 se sostiene con el de + arriba entero en el aire (8,5 % de bloque). La torre de 16 no se mueve hasta que + se le apoya un bloque más en la punta izquierda de arriba: se caen 10 de 17. + +Dos ajustes que hicieron falta en Godot: + +- **galton**: una amortiguación lineal de 6/s, que hace de roce contra el vidrio. + Sin ella las bolitas toman demasiada velocidad lateral y el reparto sale plano. +- **bloques**: física a 1920 Hz y mundo ×5 (`"hz"` y `"escala"` en el config). Jolt + tolera 2 cm de penetración y a 240 Hz la torre de 16 se hundía y se volcaba sola. + +Ojo: con la notebook Optimus, EEVEE usa la Intel salvo que se lance con +`__NV_PRIME_RENDER_OFFLOAD=1 __GLX_VENDOR_LIBRARY_NAME=nvidia`, y así es 3,6 veces +más rápido (1,5 s/frame contra 5,5 en galton). + +## Cómo regenerar + +```bash +conda run -n manim python scripts/gen_audio.py montyhall # voz + verificación +conda run -n manim manim render -v ERROR --disable_caching \ + --format=mp4 -o montyhall scenes/v1_montyhall.py MontyHall +conda run -n manim python scripts/build_video.py montyhall # música + mezcla + mux +conda run -n manim python scripts/verify_final.py montyhall # QA sobre el MP4 final +``` + +`DRAFT=1` antes del render baja a 540×960 para iterar rápido. + +## Cómo está armado + +``` +scripts/narration.py guiones: (texto que se locuta, subtítulo en pantalla) +scripts/gen_audio.py sintetiza cada frase y la verifica transcribiéndola con Whisper +scripts/numspell.py pasa "99,9%" a "noventa y nueve coma nueve por ciento" + para poder comparar la transcripción contra el guion +scripts/regen.py regenera una frase probando 5 semillas +scripts/repick.py reelige la mejor toma ya sintetizada +scripts/verify.py QA: transcribe todos los WAV y marca los dudosos +scripts/verify_final.py QA final: saca el audio del MP4 ya mezclado y lo transcribe, + así se prueba que la voz se entiende por encima del piano +scripts/music.py cama de piano (progresión propia) + ducking bajo la voz +scripts/build_video.py arma la pista siguiendo el timeline y la pega al video +scenes/tiktok.py base: 9:16, subtítulos, barra de progreso, "beats" +scenes/v*.py una escena por video (Manim) +scenes/overlay.py capa de interfaz para los videos 3D: la misma barra, el mismo + chip y los mismos subtítulos, renderizados con alfa +blender/base.py base de las escenas 3D: paleta, cámara, primitivas, tiempo +blender/*.py una escena por video 3D +scripts/build_blender.py compone fondo + 3D + overlay + audio en una sola pasada +``` + +### Los videos 3D + +Se renderizan headless con Blender 5.2 y EEVEE: + +```bash +conda run -n manim manim -s --disable_caching -o fondo scenes/overlay.py Fondo # trama de puntos +NAME=caos CHIP=Caos CHIPCOL=rosa conda run -n manim manim --transparent \ + --disable_caching -o caos scenes/overlay.py Overlay # capa + timeline +blender -b --factory-startup --python blender/caos.py # secuencia PNG con alfa +conda run -n manim python scripts/build_blender.py caos # composicion + audio +``` + +Dos decisiones que se pagaron solas: + +- **Sin keyframes.** El render recorre los frames uno por uno y antes de cada uno + llama a `actualizar(f)`, que coloca todo. Así la física se calcula exacta en cada + cuadro, se pueden renderizar frames salteados para revisar el encuadre, y no hay + que pelear con la API de acciones por capas de Blender 5.x. +- **El fondo no está en la escena 3D.** Blender renderiza con `film_transparent` y el + fondo punteado se compone abajo con ffmpeg, así es pixel por pixel el mismo que el + de los 18 videos de Manim. +- **El metal necesita algo que reflejar.** `mundo_estudio()` pone un gradiente de + horizonte en el mundo: no se ve (el film es transparente) pero es lo único que + separa el acero del plástico gris. Sin eso, un material metálico queda plano. + +`blender/base.py` genera las piezas mecánicas por código: + +| Función | Qué hace | +|---|---| +| `engranaje_conico` | Engranaje cónico con semiángulo de cono y dientes en espiral. Dos engranan a 90° cuando sus γ suman 90: 45+45 para los del diferencial, 72+18 para corona y piñón (y ahí la relación de dientes queda fijada por sin72/sin18 = 3,07, que es por qué son 43 y 14) | +| `rueda_completa` | Neumático con tacos y canales + llanta de aleación con radios + disco de freno | +| `sector_anillo` | Pared curva: con dos de estas y dos bridas sale una caja de diferencial con ventanas, que es lo que deja ver los engranajes de adentro | +| `anillo_plano`, `tornillos` | Bridas y coronas de bulones | + +Los PNG intermedios quedan en `render//` (unos 4 GB los tres). Sirven para +recomponer con otro audio o subtítulos sin volver a renderizar, que son entre 30 y +55 minutos por video; si no hacen falta, se borran. + +`MUESTRAS=8` baja las muestras de EEVEE (16 por defecto, 64 de fábrica: eso son +10 s/frame en una GTX 1050 y 1,6 s/frame con 8). `SALTO=55` renderiza un frame de +cada 55 para armar la hoja de contacto sin esperar el render entero. + +La sincronía no se estima: la escena escribe `out/_timeline.json` con el +tiempo real de cada bloque y el audio se coloca en esas marcas exactas. + +## Sobre la música + +Las progresiones (Am–F–C–G, Em–C–G–D, Am–Em–Dm–E, Cm–G#–A#–Gm, A–E–F#m–D, etc.) son propias y están tocadas con muestras +de piano sueltas, así que el audio es tuyo y no te lo va a marcar el Content ID. +Si preferís un audio en tendencia de TikTok, subilo igual y agregalo desde la app: +la voz ya está mezclada a −14 LUFS y se sigue entendiendo por encima. diff --git a/blender/base.py b/blender/base.py new file mode 100644 index 0000000..385eb0c --- /dev/null +++ b/blender/base.py @@ -0,0 +1,659 @@ +# -*- coding: utf-8 -*- +"""Base comun para las escenas 3D del canal (Blender 5.2, EEVEE, headless). + +Idea central: no se usan keyframes. El render recorre los frames uno por uno y +antes de cada uno llama a una funcion actualizar(f) que coloca todo. Asi la +fisica y la geometria se calculan exactas en cada cuadro y no hay que pelear +con la API de acciones por capas de Blender 5.x. + +El tiempo sale de out/_timeline.json, el mismo archivo que usa +build_video.py para colocar el audio: la sincronia es por construccion. +""" +import json, math, os, sys +import bpy + +ROOT = os.environ.get("PROY", "/tmp/Firefox/videos-t") +FPS = 30 +W, H = 1080, 1920 + +# --- paleta del canal (sRGB) -------------------------------------------------- +HEX = {"ambar": "FFD166", "verde": "06D6A0", "rosa": "EF476F", "celeste": "4CC9F0", + "gris": "8D99AE", "fondo": "0B0F1A", "azul": "1D3B6E", "riel": "1B2233", + "blanco": "FFFFFF", "punto": "243050"} + + +def srgb(h): + """Hex sRGB -> lineal, que es lo que espera Blender en los materiales.""" + def c(v): + v /= 255.0 + return v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4 + h = HEX.get(h, h).lstrip("#") + return tuple(c(int(h[i:i + 2], 16)) for i in (0, 2, 4)) + + +def escena(muestras=None): + """Escena limpia, vertical, EEVEE, fondo transparente y color sin tonemap.""" + bpy.ops.wm.read_factory_settings(use_empty=True) + sc = bpy.context.scene + sc.render.engine = 'BLENDER_EEVEE' + sc.eevee.taa_render_samples = int(muestras or os.environ.get("MUESTRAS", 16)) + sc.render.resolution_x, sc.render.resolution_y = W, H + sc.render.resolution_percentage = int(os.environ.get("PCT", 100)) + sc.render.fps = FPS + sc.render.film_transparent = True # el fondo punteado se compone aparte + sc.render.image_settings.file_format = 'PNG' + sc.render.image_settings.color_mode = 'RGBA' + sc.render.image_settings.compression = 25 + # 'Standard' deja los colores tal cual se escriben; AgX los lavaria y el + # canal quedaria con otra paleta que los videos de Manim. + for prop, val in (("view_transform", 'Standard'), ("look", 'None')): + try: + setattr(sc.view_settings, prop, val) + except Exception as e: + print(f" aviso: view_settings.{prop} -> {e}") + mundo = bpy.data.worlds.new("mundo") + mundo.use_nodes = True + mundo.node_tree.nodes["Background"].inputs[0].default_value = (*srgb("fondo"), 1) + mundo.node_tree.nodes["Background"].inputs[1].default_value = 0.45 + sc.world = mundo + return sc + + +def poner(nodo, nombre, valor): + """setattr/socket tolerante: avisa en vez de romper si cambio el nombre.""" + try: + if nombre in nodo.inputs: + nodo.inputs[nombre].default_value = valor + return True + except Exception: + pass + print(f" aviso: no existe la entrada '{nombre}'") + return False + + +def material(nombre, color, rug=0.35, metal=0.0, emis=0.0, alpha=1.0): + m = bpy.data.materials.new(nombre) + m.use_nodes = True + b = m.node_tree.nodes.get("Principled BSDF") + col = (*(color if isinstance(color, tuple) else srgb(color)), 1.0) + poner(b, "Base Color", col) + poner(b, "Roughness", rug) + poner(b, "Metallic", metal) + if emis: + poner(b, "Emission Color", col) + poner(b, "Emission Strength", emis) + if alpha < 1.0: + poner(b, "Alpha", alpha) + m.blend_method = 'BLEND' if hasattr(m, "blend_method") else m.blend_method + return m + + +def objeto(nombre, malla, mat=None, coleccion=None): + ob = bpy.data.objects.new(nombre, malla) + (coleccion or bpy.context.collection).objects.link(ob) + if mat is not None: + ob.data.materials.append(mat) + return ob + + +def malla_de(nombre, verts, faces, suave=True): + me = bpy.data.meshes.new(nombre) + me.from_pydata(verts, [], faces) + me.update() + if suave: + for p in me.polygons: + p.use_smooth = True + return me + + +def curva_poly(nombre, splines, grosor=0.01, radios=None, mat=None): + """Una curva con varias splines POLY; radios opcional por punto.""" + cu = bpy.data.curves.new(nombre, 'CURVE') + cu.dimensions = '3D' + cu.bevel_depth = grosor + cu.bevel_resolution = 1 + cu.use_fill_caps = True + for k, pts in enumerate(splines): + sp = cu.splines.new('POLY') + sp.points.add(len(pts) - 1) + for i, p in enumerate(pts): + sp.points[i].co = (p[0], p[1], p[2], 1.0) + if radios is not None: + sp.points[i].radius = radios[k][i] + return objeto(nombre, cu, mat) + + +def rehacer_curva(ob, splines, radios=None): + """Reescribe los puntos de una curva ya creada (misma cantidad de puntos).""" + for sp, pts, k in zip(ob.data.splines, splines, range(len(splines))): + for i, p in enumerate(pts): + sp.points[i].co = (p[0], p[1], p[2], 1.0) + if radios is not None: + sp.points[i].radius = radios[k][i] + + +def camara(loc, mira=(0, 0, 0), lente=50): + cd = bpy.data.cameras.new("cam") + cd.lens = lente + cam = bpy.data.objects.new("cam", cd) + bpy.context.collection.objects.link(cam) + bpy.context.scene.camera = cam + apuntar(cam, loc, mira) + return cam + + +def apuntar(ob, loc, mira): + """Coloca ob en loc mirando a 'mira' (convencion de camara: -Z adelante).""" + from mathutils import Vector + ob.location = loc + d = Vector(mira) - Vector(loc) + ob.rotation_euler = d.to_track_quat('-Z', 'Y').to_euler() + + +def luz(nombre, tipo, loc, energia, color="blanco", tam=2.0, mira=None): + ld = bpy.data.lights.new(nombre, tipo) + ld.energy = energia + ld.color = srgb(color) + if tipo == 'AREA': + ld.size = tam + if tipo == 'POINT': + ld.shadow_soft_size = tam + ob = bpy.data.objects.new(nombre, ld) + bpy.context.collection.objects.link(ob) + if mira is not None: + apuntar(ob, loc, mira) + else: + ob.location = loc + return ob + + +# --- tiempo ------------------------------------------------------------------- +class Tiempo: + """Traduce el timeline del canal a frames.""" + + def __init__(self, nombre): + with open(os.path.join(ROOT, "out", f"{nombre}_timeline.json")) as f: + self.tl = json.load(f) + self.beats = self.tl["beats"] + self.total = self.tl["total"] + self.n_frames = int(round(self.total * FPS)) + + def rango(self, i): + """(frame inicial, frame final) del beat i, 1-based inclusive.""" + b = self.beats[i] + a = int(round(b["start"] * FPS)) + 1 + z = int(round((b["start"] + b["dur"]) * FPS)) + return a, z + + def t(self, f): + return (f - 1) / FPS + + def p(self, f, i): + """Progreso 0..1 dentro del beat i (fuera del beat: 0 antes, 1 despues).""" + a, z = self.rango(i) + if f <= a: + return 0.0 + if f >= z: + return 1.0 + return (f - a) / max(1, z - a) + + +def suave(x): + x = max(0.0, min(1.0, x)) + return x * x * (3 - 2 * x) + + +def mezcla(a, b, x): + return a + (b - a) * suave(x) + + +# --- render ------------------------------------------------------------------- +def render_secuencia(nombre, tiempo, actualizar, desde=None, hasta=None): + sc = bpy.context.scene + carpeta = os.path.join(ROOT, "render", nombre) + os.makedirs(carpeta, exist_ok=True) + a = int(desde or os.environ.get("DESDE", 1)) + z = int(hasta or os.environ.get("HASTA", tiempo.n_frames)) + salto = os.environ.get("SALTO") # para pruebas: 1 de cada N + frames = range(a, z + 1, int(salto) if salto else 1) + import time + t0 = time.time() + hechos = 0 + for f in frames: + destino = os.path.join(carpeta, f"f{f:04d}.png") + if os.environ.get("SEGUIR") and os.path.exists(destino): + continue + sc.frame_set(f) + actualizar(f) + sc.render.filepath = destino + bpy.ops.render.render(write_still=True) + hechos += 1 + if hechos % 25 == 0: + d = time.time() - t0 + print(f" [{nombre}] frame {f}/{z} {d / hechos:.2f}s/frame " + f"faltan {(len(frames) - hechos) * d / hechos / 60:.1f} min", flush=True) + print(f"[{nombre}] {hechos} frames en {(time.time() - t0) / 60:.1f} min", flush=True) + + +# --- texto 3D ----------------------------------------------------------------- +FUENTE_RUTA = "/usr/share/fonts/TTF/Roboto-Bold.ttf" +_fuente = None + + +def texto(cuerpo, tam=0.18, color="blanco", align='CENTER', emis=1.8, plano_xz=True): + """Texto plano, emisivo, en el plano XZ (para camaras que miran por -Y).""" + global _fuente + if _fuente is None: + _fuente = bpy.data.fonts.load(FUENTE_RUTA) + cu = bpy.data.curves.new("txt", 'FONT') + cu.body = cuerpo + cu.font = _fuente + cu.size = tam + cu.align_x = align + cu.align_y = 'CENTER' + ob = objeto("txt", cu, material(f"m_txt_{color}", color, emis=emis, rug=0.6)) + if plano_xz: + ob.rotation_euler = (math.pi / 2, 0, 0) + return ob + + +def cilindro(nombre, radio, largo, mat=None, lados=20): + """Cilindro centrado en el origen, eje +Z, para reubicar por frame.""" + verts, faces = [], [] + for i in range(lados): + a = 2 * math.pi * i / lados + verts.append((radio * math.cos(a), radio * math.sin(a), -largo / 2)) + verts.append((radio * math.cos(a), radio * math.sin(a), largo / 2)) + for i in range(lados): + j = (i + 1) % lados + faces.append((2 * i, 2 * j, 2 * j + 1, 2 * i + 1)) + tapa_a = [2 * i for i in range(lados)][::-1] + tapa_b = [2 * i + 1 for i in range(lados)] + faces += [tuple(tapa_a), tuple(tapa_b)] + me = malla_de(nombre, verts, faces, suave=False) + for p in me.polygons[:lados]: + p.use_smooth = True + return objeto(nombre, me, mat) + + +def esfera(nombre, radio, mat=None, seg=24, anillos=14): + verts, faces = [], [] + for i in range(1, anillos): + phi = math.pi * i / anillos + for j in range(seg): + th = 2 * math.pi * j / seg + verts.append((radio * math.sin(phi) * math.cos(th), + radio * math.sin(phi) * math.sin(th), + radio * math.cos(phi))) + norte = len(verts); verts.append((0, 0, radio)) + sur = len(verts); verts.append((0, 0, -radio)) + for i in range(anillos - 2): + for j in range(seg): + a = i * seg + j + b = i * seg + (j + 1) % seg + faces.append((a, b, b + seg, a + seg)) + for j in range(seg): + faces.append((norte, (j + 1) % seg, j)) + faces.append((sur, (anillos - 2) * seg + j, (anillos - 2) * seg + (j + 1) % seg)) + return objeto(nombre, malla_de(nombre, verts, faces), mat) + + +def orientar(ob, desde, hasta): + """Coloca un cilindro creado con cilindro() entre dos puntos.""" + from mathutils import Vector + a, b = Vector(desde), Vector(hasta) + ob.location = (a + b) / 2 + d = b - a + ob.rotation_euler = d.to_track_quat('Z', 'Y').to_euler() + + +def toro(nombre, R, r, mat=None, u=64, v=24): + verts, faces = [], [] + for i in range(u): + a = 2 * math.pi * i / u + ca, sa = math.cos(a), math.sin(a) + for j in range(v): + b = 2 * math.pi * j / v + rr = R + r * math.cos(b) + verts.append((rr * ca, rr * sa, r * math.sin(b))) + for i in range(u): + i2 = (i + 1) % u + for j in range(v): + j2 = (j + 1) % v + faces.append((i * v + j, i2 * v + j, i2 * v + j2, i * v + j2)) + return objeto(nombre, malla_de(nombre, verts, faces), mat) + + +HOLGURA = 0.55 # 0.5 = sin juego; un poco mas deja luz entre flancos + + +def engranaje_conico(nombre, eje, N=18, gamma=45.0, d_i=0.50, d_o=0.70, + alto=0.055, mat=None, nd=10, por_diente=10, fase=0.0, + espiral=0.0, espesor=0.10, hueco=0.0): + """Engranaje conico con el apice en el origen y eje 'eje'. + + gamma = semiangulo del cono de paso. Dos engranajes engranan a 90 grados + cuando sus gammas suman 90: 45+45 para los del diferencial, + 72+18 para corona y pinon. + espiral = torsion del diente a lo largo de la generatriz (conico espiral, + que es lo que se usa de verdad; en recto se ve de juguete). + espesor = cuanto se extruye el cuerpo hacia atras, para que sea un solido + y no una cascara. + """ + from mathutils import Vector + a = Vector(eje).normalized() + u = Vector((0, 0, 1)) if abs(a.z) < 0.9 else Vector((1, 0, 0)) + u = (u - a * u.dot(a)).normalized() + v = a.cross(u) + cg, sg = math.cos(math.radians(gamma)), math.sin(math.radians(gamma)) + nphi = N * por_diente + verts, faces = [], [] + + def perfil(x): + return max(0.0, min(1.0, (math.cos(x) + 0.30) / 0.60)) + + def punto(d, phi, h): + rad = u * math.cos(phi) + v * math.sin(phi) + base = (a * cg + rad * sg) * d + nrm = rad * cg - a * sg + return base + nrm * h + + for i in range(nd + 1): + s_ = i / nd + d = d_i + (d_o - d_i) * s_ + for j in range(nphi): + phi = 2 * math.pi * j / nphi + # el diente arranca bajo en el extremo interior y crece hacia afuera + # el diente se apaga en el borde interior: si no, el cierre del + # cuerpo queda como un abanico de aletas + # el diente va mitad por encima y mitad por debajo del cono de paso: + # asi el de enfrente entra en el hueco en vez de atravesar el cuerpo + h = alto * (perfil(N * phi + fase + espiral * s_) - HOLGURA) * (s_ ** 0.8) + p = punto(d, phi, h) + verts.append((p.x, p.y, p.z)) + for i in range(nd): + for j in range(nphi): + j2 = (j + 1) % nphi + faces.append((i * nphi + j, i * nphi + j2, (i + 1) * nphi + j2, (i + 1) * nphi + j)) + + # cuerpo: se extruye el borde exterior hacia atras y se cierra con el fondo + o_ext = nd * nphi + base_ext = len(verts) + for j in range(nphi): + phi = 2 * math.pi * j / nphi + # se extruye desde el diente, no desde el cono: asi el perfil llega a la + # cara exterior como en un engranaje de verdad + h = alto * (perfil(N * phi + fase + espiral) - HOLGURA) + # el cuerpo va del lado de atras (lejos del apice), no hacia el engranaje + # de enfrente + p = punto(d_o, phi, h) + a * espesor + verts.append((p.x, p.y, p.z)) + for j in range(nphi): + j2 = (j + 1) % nphi + faces.append((o_ext + j, o_ext + j2, base_ext + j2, base_ext + j)) + base_int = len(verts) + r_h = max(hueco, 0.02) + for j in range(nphi): + phi = 2 * math.pi * j / nphi + rad = u * math.cos(phi) + v * math.sin(phi) + p = rad * r_h + a * (d_i * cg) + a * espesor * 0.35 + verts.append((p.x, p.y, p.z)) + for j in range(nphi): + j2 = (j + 1) % nphi + faces.append((base_ext + j, base_ext + j2, base_int + j2, base_int + j)) + faces.append((j2, j, base_int + j, base_int + j2)) + me = malla_de(nombre, verts, faces, suave=False) + import bmesh + bm = bmesh.new() + bm.from_mesh(me) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces) + bm.to_mesh(me) + bm.free() + ob = objeto(nombre, me, mat) + # la cara dentada suave (es una superficie continua, como un engranaje + # mecanizado); el cuerpo plano, para que se lean los cantos + for k, pol in enumerate(me.polygons): + pol.use_smooth = k < nd * nphi + return ob + + +def anillo_plano(nombre, r_int, r_ext, espesor, mat=None, lados=64): + """Anillo macizo (brida, corona de tornillos, llanta).""" + verts, faces = [], [] + for j in range(lados): + ang = 2 * math.pi * j / lados + c, s_ = math.cos(ang), math.sin(ang) + for (r, z) in ((r_int, -espesor / 2), (r_ext, -espesor / 2), + (r_ext, espesor / 2), (r_int, espesor / 2)): + verts.append((r * c, r * s_, z)) + for j in range(lados): + j2 = (j + 1) % lados + for k in range(4): + k2 = (k + 1) % 4 + faces.append((j * 4 + k, j2 * 4 + k, j2 * 4 + k2, j * 4 + k2)) + return objeto(nombre, malla_de(nombre, verts, faces, suave=False), mat) + + +def neumatico(nombre, R, r, mat=None, nu=72, nv=28, tacos=26, prof=0.055): + """Toro con banda de rodadura: tacos y dos canales longitudinales.""" + verts, faces = [], [] + for i in range(nu): + aa = 2 * math.pi * i / nu + ca, sa = math.cos(aa), math.sin(aa) + for j in range(nv): + b = 2 * math.pi * j / nv + cb, sb = math.cos(b), math.sin(b) + rr = r + if abs(sb) < 0.72: # zona de rodadura + taco = 0.5 + 0.5 * math.cos(tacos * aa + 3.0 * b) + canal = 1.0 if abs(sb) > 0.22 and abs(sb) < 0.5 else 0.0 + rr -= prof * (0.45 * (taco < 0.45) + 0.55 * canal) + verts.append(((R + rr * cb) * ca, (R + rr * cb) * sa, rr * sb)) + for i in range(nu): + i2 = (i + 1) % nu + for j in range(nv): + j2 = (j + 1) % nv + faces.append((i * nv + j, i2 * nv + j, i2 * nv + j2, i * nv + j2)) + return objeto(nombre, malla_de(nombre, verts, faces), mat) + + +def mundo_estudio(fuerza=0.55, arriba="#8FA6C4", abajo="#10141F"): + """Gradiente de horizonte en el mundo. No se ve (el film es transparente) + pero es lo que el metal refleja: sin esto el acero queda plano.""" + w = bpy.data.worlds.new("estudio") + w.use_nodes = True + nt = w.node_tree + for n in list(nt.nodes): + if n.type != 'OUTPUT_WORLD': + nt.nodes.remove(n) + sal = next(n for n in nt.nodes if n.type == 'OUTPUT_WORLD') + fondo = nt.nodes.new("ShaderNodeBackground") + geo = nt.nodes.new("ShaderNodeNewGeometry") + sep = nt.nodes.new("ShaderNodeSeparateXYZ") + mapa = nt.nodes.new("ShaderNodeMapRange") + rampa = nt.nodes.new("ShaderNodeValToRGB") + mapa.inputs[1].default_value = -0.45 + mapa.inputs[2].default_value = 0.85 + rampa.color_ramp.elements[0].color = (*srgb(abajo), 1) + rampa.color_ramp.elements[1].color = (*srgb(arriba), 1) + rampa.color_ramp.elements[0].position = 0.15 + rampa.color_ramp.elements[1].position = 0.92 + nt.links.new(geo.outputs["Incoming"], sep.inputs[0]) + nt.links.new(sep.outputs["Z"], mapa.inputs[0]) + nt.links.new(mapa.outputs[0], rampa.inputs[0]) + nt.links.new(rampa.outputs["Color"], fondo.inputs[0]) + fondo.inputs[1].default_value = fuerza + nt.links.new(fondo.outputs[0], sal.inputs[0]) + bpy.context.scene.world = w + return w + + +def metal(nombre, color="#B9C0CC", rug=0.26, met=1.0): + return material(nombre, color, rug=rug, metal=met) + + +def rueda_completa(nombre, mats, R=0.36, r=0.135, ancho=0.20, radios=5): + """Neumatico con tacos + llanta de aleacion con radios + disco de freno. + Devuelve el grupo, con el eje de giro en X.""" + g = bpy.data.objects.new(nombre, None) + bpy.context.collection.objects.link(g) + goma = neumatico(f"{nombre}_goma", R, r, mats["goma"]) + goma.rotation_euler = (0, math.pi / 2, 0) + goma.parent = g + r_int = R - r * 0.72 + aro = anillo_plano(f"{nombre}_aro", r_int - 0.045, r_int + 0.02, ancho, mats["alu"]) + aro.rotation_euler = (0, math.pi / 2, 0) + aro.parent = g + cubo = cilindro(f"{nombre}_cubo", 0.085, ancho * 0.9, mats["alu"], lados=24) + cubo.rotation_euler = (0, math.pi / 2, 0) + cubo.parent = g + for k in range(radios): + ang = 2 * math.pi * k / radios + d = (0.0, math.cos(ang), math.sin(ang)) + rad = cilindro(f"{nombre}_r{k}", 0.040, 1.0, mats["alu"], lados=12) + orientar(rad, tuple(c * 0.075 for c in d), tuple(c * (r_int - 0.02) for c in d)) + rad.scale = (1, 1, (r_int - 0.02) - 0.075) + rad.parent = g + disco = cilindro(f"{nombre}_disco", r_int - 0.09, 0.035, mats["freno"], lados=40) + disco.rotation_euler = (0, math.pi / 2, 0) + disco.location = (-ancho * 0.55, 0, 0) + disco.parent = g + return g + + +def tornillos(nombre, n, radio, eje_x, largo=0.05, r_t=0.028, mat=None, padre=None): + """Corona de bulones sobre una brida.""" + g = bpy.data.objects.new(nombre, None) + bpy.context.collection.objects.link(g) + for k in range(n): + ang = 2 * math.pi * k / n + t = cilindro(f"{nombre}_{k}", r_t, largo, mat, lados=8) + t.rotation_euler = (0, math.pi / 2, 0) + t.location = (eje_x, radio * math.cos(ang), radio * math.sin(ang)) + t.parent = g + if padre: + g.parent = padre + return g + + +def sector_anillo(nombre, r_int, r_ext, espesor, ang0, ang1, mat=None, lados=28): + """Pared curva: un sector de corona, con espesor a lo largo de su eje. + Sirve para armar una caja de diferencial con ventanas.""" + verts, faces = [], [] + n = max(3, lados) + for j in range(n + 1): + ang = ang0 + (ang1 - ang0) * j / n + c, s_ = math.cos(ang), math.sin(ang) + for (r, z) in ((r_int, -espesor / 2), (r_ext, -espesor / 2), + (r_ext, espesor / 2), (r_int, espesor / 2)): + verts.append((r * c, r * s_, z)) + for j in range(n): + for k in range(4): + k2 = (k + 1) % 4 + faces.append((j * 4 + k, (j + 1) * 4 + k, (j + 1) * 4 + k2, j * 4 + k2)) + faces.append((0, 3, 2, 1)) + o = n * 4 + faces.append((o, o + 1, o + 2, o + 3)) + return objeto(nombre, malla_de(nombre, verts, faces, suave=False), mat) + + +# --- madera procedural ---------------------------------------------------------- +def madera(nombre, claro="#9A6A40", oscuro="#4E2E17", escala=4.0, rug=0.42, veta=(1, 1, 9)): + """Veta de madera: ondas distorsionadas por ruido, estiradas en un eje.""" + m = bpy.data.materials.new(nombre) + m.use_nodes = True + nt = m.node_tree + b = nt.nodes.get("Principled BSDF") + tc = nt.nodes.new("ShaderNodeTexCoord") + mp = nt.nodes.new("ShaderNodeMapping") + mp.inputs["Scale"].default_value = veta + ola = nt.nodes.new("ShaderNodeTexWave") + ola.wave_type = 'RINGS' + ola.inputs["Scale"].default_value = escala + ola.inputs["Distortion"].default_value = 7.0 + ola.inputs["Detail"].default_value = 4.0 + ola.inputs["Detail Scale"].default_value = 1.6 + rampa = nt.nodes.new("ShaderNodeValToRGB") + rampa.color_ramp.elements[0].color = (*srgb(oscuro), 1) + rampa.color_ramp.elements[1].color = (*srgb(claro), 1) + rampa.color_ramp.elements[0].position = 0.25 + rampa.color_ramp.elements[1].position = 0.85 + nt.links.new(tc.outputs["Object"], mp.inputs["Vector"]) + nt.links.new(mp.outputs["Vector"], ola.inputs["Vector"]) + nt.links.new(ola.outputs["Fac"], rampa.inputs["Fac"]) + nt.links.new(rampa.outputs["Color"], b.inputs["Base Color"]) + poner(b, "Roughness", rug) + bump = nt.nodes.new("ShaderNodeBump") + bump.inputs["Strength"].default_value = 0.08 + nt.links.new(ola.outputs["Fac"], bump.inputs["Height"]) + nt.links.new(bump.outputs["Normal"], b.inputs["Normal"]) + return m + + +def caja(nombre, tam, loc=(0, 0, 0), mat=None, rot=(0, 0, 0)): + """Prisma con el origen en su centro (asi Godot saca la caja de colision + directamente del tamano de la malla).""" + sx, sy, sz = (t / 2 for t in tam) + verts = [(x, y, z) for x in (-sx, sx) for y in (-sy, sy) for z in (-sz, sz)] + faces = [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)] + ob = objeto(nombre, malla_de(nombre, verts, faces, suave=False), mat) + ob.location = loc + ob.rotation_euler = rot + return ob + + +# --- puente con Godot: Blender disena, Godot simula ------------------------------ +GODOT = os.environ.get("GODOT", "godot") +GODOT_PROY = os.path.join(ROOT, "godot") + + +def exportar_fisica(nombre, objetos, cfg): + """Exporta a .glb solo los objetos que participan de la fisica (el nombre + define el tipo de cuerpo, ver godot/sim.gd) y escribe el config.""" + carpeta = os.path.join(GODOT_PROY, "trabajo") + os.makedirs(carpeta, exist_ok=True) + glb = os.path.join(carpeta, f"{nombre}.glb") + for ob in bpy.context.scene.objects: + ob.select_set(False) + for ob in objetos: + ob.select_set(True) + bpy.context.view_layer.objects.active = objetos[0] + bpy.ops.export_scene.gltf(filepath=glb, export_format='GLB', use_selection=True, + export_yup=True, export_apply=True, + export_materials='NONE', export_animations=False) + cfg = dict(cfg, glb=glb, salida=os.path.join(carpeta, nombre)) + ruta = os.path.join(carpeta, f"{nombre}.json") + with open(ruta, "w") as f: + json.dump(cfg, f, indent=1) + print(f"[{nombre}] {len(objetos)} objetos -> {glb}", flush=True) + return ruta + + +def correr_godot(ruta_cfg): + import subprocess, time + t0 = time.time() + r = subprocess.run([GODOT, "--headless", "--path", GODOT_PROY, "--fixed-fps", "240", + "--", ruta_cfg], capture_output=True, text=True) + for l in (r.stdout + r.stderr).splitlines(): + if "[sim]" in l or "ERROR" in l or "SCRIPT" in l: + print(" godot:", l, flush=True) + if r.returncode != 0: + raise SystemExit(f"godot fallo ({r.returncode})") + print(f" godot tardo {time.time() - t0:.1f}s", flush=True) + + +def cargar_sim(nombre): + """-> (dict nombre->indice, array [frames, cuerpos, 7]) en coords de Blender.""" + import numpy as np + base_ = os.path.join(GODOT_PROY, "trabajo", nombre) + cab = json.load(open(base_ + ".cab.json")) + datos = np.fromfile(base_ + ".bin", dtype=np.float32) + n = len(cab["nombres"]) + datos = datos.reshape(-1, n, 7) + return {k: i for i, k in enumerate(cab["nombres"])}, datos + + +def poner_pose(ob, fila): + ob.rotation_mode = 'QUATERNION' + ob.location = (float(fila[0]), float(fila[1]), float(fila[2])) + ob.rotation_quaternion = (float(fila[3]), float(fila[4]), float(fila[5]), float(fila[6])) diff --git a/blender/bloques.py b/blender/bloques.py new file mode 100644 index 0000000..19e9991 --- /dev/null +++ b/blender/bloques.py @@ -0,0 +1,279 @@ +# -*- coding: utf-8 -*- +"""BLOQUES - la pila armonica que sobresale de la mesa sin limite. + +Blender disena (mesa, piso, bloques de madera) y exporta a glTF; Godot (Jolt) +decide que se sostiene y que se cae. Hay tres experimentos, cada uno en su +propio carril de la mesa (Y distinta) para que no se toquen; al renderizar se +trae al frente el que toca y se ocultan los otros. + + A: la escalera "obvia", cada bloque corrido medio largo -> se cae + B: 5 bloques armonicos (1/2, 1/4, 1/6, 1/8, 1/10) -> se sostiene + C: 16 bloques armonicos; en el beat 8 se le apoya uno mas -> se cae todo + +Los corrimientos armonicos se escalan por C_SEG = 0,95: asi el centro de masa +de cada subpila queda (1-C)/2 = 2,5 % de largo adentro del borde que la +sostiene, en todos los pisos. Sin ese margen, el solver decide al azar. +""" +import math, os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import bpy +from base import * + +NOMBRE = "bloques" +L, H, P = 1.0, 0.16, 0.50 # largo, alto, profundidad del bloque +C_SEG = 0.95 +C_TORRE = float(os.environ.get("T_C", C_SEG)) # la torre alta necesita mas margen con el solver +Z_PISO = -3.5 # mesa de 70 cm con bloques de 20 cm +GRAV = 49.0 # 9,81 / 0,2: bloques de 20 cm de verdad +CARRIL = {"a": 0.0, "b": 3.0, "c": 6.0, "x": 6.0} +N_B, N_C = 5, 16 +DX_EXTRA = float(os.environ.get("T_DX", -0.45)) # donde se apoya el bloque de mas + + +def pila(n, c=C_SEG): + """Centros x de una pila armonica de n bloques (indice 0 = el de arriba).""" + xs = [0.0] * n + x = -L / 2 # la mesa hace de bloque n+1 + for k in range(n, 0, -1): + x += c * L / (2 * k) + xs[k - 1] = x + return xs + + +def z_de(n, k): + """Altura del centro del bloque k (0 = arriba) en una pila de n.""" + return (n - 1 - k) * H + H / 2 + + +def construir(): + escena(muestras=int(os.environ.get("MUESTRAS", 24))) + mundo_estudio(fuerza=0.55) + M = { + "bloque": madera("bloque", claro="#E2B880", oscuro="#B07A45", escala=5.0, rug=0.5), + "arriba": material("arriba", "ambar", rug=0.35), + "mesa": madera("mesa", claro="#6B4426", oscuro="#2E1A0C", escala=2.5, rug=0.35, + veta=(0.4, 1, 1)), + "piso": madera("piso", claro="#3A3F4B", oscuro="#1E222B", escala=1.5, rug=0.6, + veta=(0.3, 1, 1)), + "invisible": material("inv", "gris"), + } + fis = [] + mesa = caja("caja_mesa", (6.0, 9.0, 0.3), (-3.0, 3.0, -0.15), M["invisible"]) + piso = caja("caja_piso", (30.0, 30.0, 0.2), (0.0, 3.0, Z_PISO - 0.1), M["invisible"]) + mesa.hide_render = piso.hide_render = True + fis += [mesa, piso] + # lo que se ve de la mesa y el piso: solo el carril del frente + caja("mesa_v", (6.0, 2.4, 0.3), (-3.0, 0.4, -0.15), M["mesa"]) + m_pata = metal("pata", "#2A2F3A", rug=0.4) + caja("pata", (0.14, 0.14, -Z_PISO - 0.3), (-0.35, -0.55, (Z_PISO - 0.3) / 2), m_pata) + caja("pata2", (0.14, 0.14, -Z_PISO - 0.3), (-0.35, 1.3, (Z_PISO - 0.3) / 2), m_pata) + caja("piso_v", (14.0, 5.0, 0.2), (1.0, 1.0, Z_PISO - 0.1), M["piso"]) + + bl = {} + # A: escalera "obvia" + for k in range(5): + x = -0.25 + 0.5 * (4 - k) + bl[f"a{k}"] = caja(f"bloque_a{k}", (L, P, H), (x, CARRIL["a"], z_de(5, k)), M["bloque"]) + # B: armonica de 5 + for k, x in enumerate(pila(N_B)): + bl[f"b{k}"] = caja(f"bloque_b{k}", (L, P, H), (x, CARRIL["b"], z_de(N_B, k)), + M["arriba"] if k == 0 else M["bloque"]) + # C: armonica de 16 y el bloque de mas, esperando arriba + xc = pila(N_C, C_TORRE) + for k, x in enumerate(xc): + bl[f"c{k:02d}"] = caja(f"bloque_c{k:02d}", (L, P, H), (x, CARRIL["c"], z_de(N_C, k)), + M["arriba"] if k == 0 else M["bloque"]) + bl["x"] = caja("bloque_x", (L, P, H), (xc[0] + DX_EXTRA, CARRIL["x"], z_de(N_C, 0) + H + 0.005), + M["bloque"]) + fis += list(bl.values()) + return dict(fis=fis, bl=bl, M=M) + + +def eventos(T): + t = lambda f: (f - 1) / FPS + fa = T.rango(1)[0] + int(0.55 * (T.rango(1)[1] - T.rango(1)[0])) + fx = T.rango(8)[0] + int(0.70 * (T.rango(8)[1] - T.rango(8)[0])) + return {"a": fa, "b": T.rango(4)[0], "c": T.rango(7)[0], "x": fx}, [ + {"t": t(fa), "accion": "soltar", "prefijo": "bloque_a"}, + {"t": t(T.rango(4)[0]), "accion": "soltar", "prefijo": "bloque_b"}, + {"t": t(T.rango(7)[0]), "accion": "soltar", "prefijo": "bloque_c"}, + {"t": t(fx), "accion": "soltar", "prefijo": "bloque_x"}, + ] + + +def simular(T, obj): + _, ev = eventos(T) + cfg = { + "duracion": T.n_frames / FPS + 0.2, + "gravedad": GRAV, + "escala": float(os.environ.get("T_ESC", 5.0)), + "hz": int(os.environ.get("T_HZ", 1920)), + "congelados": ["bloque_"], + "reglas": { + "bloque_": {"friccion": 0.55, "rebote": 0.08, "densidad": 600}, + "caja_": {"friccion": 0.6, "rebote": 0.05}, + }, + "eventos": ev, + } + correr_godot(exportar_fisica(NOMBRE, obj["fis"], cfg)) + + +def main(): + T = Tiempo(NOMBRE) + obj = construir() + if os.environ.get("MODO") == "sim": + simular(T, obj) + return + idx, D = cargar_sim(NOMBRE) + bl, M = obj["bl"], obj["M"] + suelta, _ = eventos(T) + xc = pila(N_C, C_TORRE) + + # reporte: que quedo en pie + for g, n in (("a", 5), ("b", N_B), ("c", N_C)): + nom = [k for k in bl if k.startswith(g) and k != "x"] + zmin = min(D[-1, idx[bl[k].name], 2] for k in nom) + zmin_antes = min(D[min(len(D) - 1, suelta["x"] - 5), idx[bl[k].name], 2] for k in nom) + print(f"[{NOMBRE}] pila {g}: z minima al final {zmin:+.2f} " + f"(antes del bloque extra {zmin_antes:+.2f})") + print(f"[{NOMBRE}] B: el de arriba arranca en x={pila(N_B)[0] - L / 2:+.3f} " + f"(sobresale {pila(N_B)[0] + L / 2:.3f}); C sobresale {xc[0] + L / 2:.3f}") + + # --- dibujos ------------------------------------------------------------- + m_borde = material("borde", "celeste", emis=2.5) + borde = curva_poly("borde", [[(0, -0.30, z0), (0, -0.30, z0 + 0.09)] + for z0 in [0.02 + 0.16 * i for i in range(18)]], + grosor=0.012, mat=m_borde) + etiquetas = [] + xb = pila(N_B) + for k in range(N_B): + num = texto(f"1/{2 * (k + 1)}", tam=0.15, color="ambar") + # el corrimiento de este bloque respecto del de abajo, a su derecha + num.location = (xb[k] + L / 2 + 0.16, -0.30, z_de(N_B, k)) + etiquetas.append(num) + aire = curva_poly("aire", [[(0, -0.3, 0.9), (xb[0] - L / 2, -0.3, 0.9)]], + grosor=0.02, mat=material("aire", "rosa", emis=3.0)) + aire_t = texto("en el aire", tam=0.16, color="rosa") + aire_t.location = (0.45, -0.3, 1.08) + # centros de masa de cada subpila, sobre el borde que la sostiene + cms = [] + for k in range(1, N_B + 1): + x_cm = sum(xb[:k]) / k + e = esfera(f"cm{k}", 0.045, material(f"mcm{k}", "ambar", emis=3.0)) + e.location = (x_cm, -0.30, z_de(N_B, k - 1) - H / 2) + cms.append(e) + cuenta = texto("16 bloques", tam=0.22, color="blanco") + sobre = texto("sobresale 1,6 bloques", tam=0.18, color="ambar") + regla = curva_poly("regla", [[(0, -0.3, 2.78), (xc[0] + L / 2, -0.3, 2.78)]], + grosor=0.018, mat=material("regla", "ambar", emis=3.0)) + + lente = 50.0 + cam = camara((0, -8, 1), (0, 0, 0), lente=lente) + cam.data.sensor_fit = 'VERTICAL' + cam.data.sensor_height = 36.0 + luz("key", 'AREA', (-3.0, -4.0, 5.0), 1400, "blanco", tam=4.0, mira=(0.5, 0, 0.8)) + luz("fill", 'AREA', (4.0, -3.0, 0.5), 350, "blanco", tam=4.0, mira=(0.5, 0, 0.5)) + luz("rim", 'AREA', (1.0, 4.0, 4.0), 600, "blanco", tam=3.0, mira=(0.5, 0, 1.0)) + + # (frame, x centro, z del contenido, alto visible) + r = T.rango + tomas = [ + (1, 0.55, 0.40, 5.6), + (suelta["a"] + 5, 0.55, 0.40, 5.6), + (r(1)[1] + 10, 0.9, -1.7, 7.4), + (r(2)[0] + 18, 0.45, 0.45, 4.8), + (r(5)[1], 0.45, 0.45, 4.8), + (r(6)[0] + 10, 0.50, 0.9, 5.6), + (r(6)[1], 0.55, 1.35, 6.4), + (r(8)[1] - 4, 0.55, 1.35, 6.4), + (r(9)[0] + 30, 1.2, -1.3, 8.4), + (T.n_frames, 1.2, -1.4, 8.6), + ] + + def camara_en(f): + for (f0, *a), (f1, *b) in zip(tomas, tomas[1:]): + if f0 <= f <= f1: + u = suave((f - f0) / max(1, f1 - f0)) + return [p + (q - p) * u for p, q in zip(a, b)] + return tomas[-1][1:] + + def n_c(f): + """Cuantos bloques tiene la pila C mientras se arma (beat 6).""" + return 5 + (N_C - 5) * suave(T.p(f, 6) / 0.8) + + def actualizar(f): + i = min(f - 1, len(D) - 1) + grupo = "a" if f < r(2)[0] + 10 else "b" if f < r(6)[0] else "c" + for k, ob in bl.items(): + g = "x" if k == "x" else k[0] + vis = (g == grupo) or (g == "x" and grupo == "c") + ob.hide_render = not vis + if not vis: + continue + fila = list(D[i, idx[ob.name]]) + fila[1] -= CARRIL[g] + poner_pose(ob, fila) + if g == "a" and f < suelta["a"]: + # de la pila prolija a la escalera, antes de soltarla + kk = int(k[1:]) + u = suave(T.p(f, 1) / 0.45) + ob.location.x = mezcla(-0.45, fila[0], u) + elif g == "b" and f < suelta["b"]: + # se arma desde arriba: cada bloque entra desde la izquierda + kk = int(k[1:]) + u = suave((T.p(f, 3) - kk * 0.17) / 0.16) if f >= r(3)[0] else 0.0 + if f < r(3)[0]: + u = suave(T.p(f, 2) / 0.6) if kk == 0 else 0.0 + ob.location.x = mezcla(fila[0] - 3.5, fila[0], u) + ob.hide_render = u <= 0.001 + elif g == "c" and f < suelta["c"]: + kk = int(k[1:]) + n = n_c(f) + n0 = int(math.floor(n)) + u = n - n0 + def pos(nn): + if kk >= nn: + return None + return pila(nn, C_TORRE)[kk], z_de(nn, kk) + p0, p1 = pos(n0), pos(min(N_C, n0 + 1)) + if p0 is None and p1 is None: + ob.hide_render = True + continue + if p0 is None: # el bloque nuevo entra por abajo desde la izquierda + p0 = (p1[0] - 3.0, p1[1]) + x = p0[0] + (p1[0] - p0[0]) * u if p1 else p0[0] + z = p0[1] + (p1[1] - p0[1]) * u if p1 else p0[1] + ob.location = (x, 0.0, z) + elif g == "x" and f < suelta["x"]: + u = suave((T.p(f, 8) - 0.15) / 0.45) + ob.hide_render = u <= 0.001 + ob.location.z = fila[2] + 2.0 * (1 - u) + + # dibujos + v_borde = T.p(f, 3) > 0 and f < r(9)[0] + borde.hide_render = not v_borde + for k, t in enumerate(etiquetas): + t.hide_render = not (r(3)[0] + (k * 0.17 + 0.08) * (r(3)[1] - r(3)[0]) <= f < r(6)[0]) + v_aire = r(4)[0] + 20 <= f < r(6)[0] + aire.hide_render = aire_t.hide_render = not v_aire + for k, e in enumerate(cms): + e.hide_render = not (r(5)[0] + k * 8 <= f < r(6)[0]) + v_c = r(6)[0] + 5 <= f < r(8)[1] + cuenta.hide_render = not v_c + n = n_c(f) + cuenta.data.body = f"{int(round(n))} bloques" + top_z = z_de(int(round(n)), 0) + H / 2 + cuenta.location = (-0.45, -0.3, top_z + 0.35) + v_regla = r(7)[0] <= f < r(8)[1] + regla.hide_render = sobre.hide_render = not v_regla + sobre.location = (1.2, -0.3, 2.98) + + cx, cz, h = camara_en(f) + dist = h * lente / 36.0 + zc = cz - 0.10 * h # el contenido queda arriba de los subtitulos + apuntar(cam, (cx - 0.16 * h, -dist, zc + 0.16 * h), (cx, 0, zc)) + + render_secuencia(NOMBRE, T, actualizar) + + +main() diff --git a/blender/bolapeluda.py b/blender/bolapeluda.py new file mode 100644 index 0000000..a260784 --- /dev/null +++ b/blender/bolapeluda.py @@ -0,0 +1,260 @@ +# -*- coding: utf-8 -*- +"""BOLA PELUDA - el teorema de la bola peluda (Brouwer, 1912). + +Cada pelo se acuesta en la direccion del campo tangente v(p) = A x p, y lo hace +tanto como el campo sea fuerte: donde |v| se anula (los dos polos del eje A) el +pelo no tiene hacia donde acostarse y queda parado. O sea que el remolino no +esta dibujado a mano, sale de la misma cuenta que peina el resto. +""" +import math, os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import bpy +from mathutils import Vector, Matrix +from base import * + +NOMBRE = "bolapeluda" +R = 1.15 # radio de la esfera +LARGO = 0.34 # largo del pelo +K = 7 # puntos por pelo +N = 1500 # cantidad de pelos +UMBRAL = 0.42 # |v| por debajo de esto, el pelo no llega a acostarse +CZ = 0.50 # altura del centro en el cuadro + +# Peinados: (eje, tipo). Los ejes viven casi en el plano de la pantalla (XZ) +# para que los DOS ceros caigan sobre la silueta y se vean juntos. +# rot -> campo v = A x p (peina en circulos, como las latitudes) +# mer -> campo v = A - (A.p) p (peina de un polo al otro, por meridianos) +# Los dos se anulan exactamente donde p es paralelo a A: ahi esta el remolino. +PEINADOS = [((0.80, -0.05, 0.60), "rot"), + ((-0.58, -0.05, 0.82), "mer"), + ((0.97, -0.08, -0.22), "rot"), + ((0.12, -0.05, 0.99), "mer"), + ((-0.86, -0.06, -0.50), "rot"), + ((0.80, -0.05, 0.60), "rot")] + + +def normaliza(v): + n = math.sqrt(sum(c * c for c in v)) + return tuple(c / n for c in v) if n > 1e-9 else (0.0, 0.0, 1.0) + + +def cruz(a, b): + return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]) + + +def puntos_esfera(n): + """Espiral de Fibonacci: reparte n puntos casi parejos sobre la esfera.""" + pts, ga = [], math.pi * (3 - math.sqrt(5)) + for i in range(n): + z = 1 - 2 * (i + 0.5) / n + r = math.sqrt(max(0.0, 1 - z * z)) + th = ga * i + pts.append((r * math.cos(th), r * math.sin(th), z)) + return pts + + +def campo(p, eje, tipo): + if tipo == "mer": + d = sum(a * b for a, b in zip(eje, p)) + return tuple(eje[i] - d * p[i] for i in range(3)) + return cruz(eje, p) + + +def pelo(p, eje, peinado, tipo="rot", radio=R, largo=LARGO): + """Devuelve los K puntos del pelo nacido en p y cuanto vale |v| ahi.""" + v = campo(p, eje, tipo) + m = math.sqrt(sum(c * c for c in v)) + if m > 1e-6: + t = tuple(c / m for c in v) + else: # en el cero no hay direccion: queda parado + t = normaliza(cruz(p, (0.0, 0.0, 1.0)) if abs(p[2]) < 0.9 else (1.0, 0.0, 0.0)) + b = peinado * min(1.0, m / UMBRAL) + pos = [tuple(c * radio for c in p)] + paso = largo / (K - 1) + for j in range(1, K): + s = j / (K - 1.0) + phi = b * (math.pi / 2) * s ** 0.85 + cs, sn = math.cos(phi), math.sin(phi) + d = (p[0] * cs + t[0] * sn, p[1] * cs + t[1] * sn, p[2] * cs + t[2] * sn) + a = pos[-1] + pos.append((a[0] + d[0] * paso, a[1] + d[1] * paso, a[2] + d[2] * paso)) + return pos, m + + +def pelos_toro(nu=60, nv=24, RT=0.90, rt=0.34, largo=0.22): + """Pelos de la rosquilla, peinados por el tangente toroidal: nunca se anula.""" + splines, radios = [], [] + for i in range(nu): + u = 2 * math.pi * i / nu + cu, su = math.cos(u), math.sin(u) + for j in range(nv): + w = 2 * math.pi * j / nv + cw, sw = math.cos(w), math.sin(w) + p = ((RT + rt * cw) * cu, (RT + rt * cw) * su, rt * sw) + n = (cw * cu, cw * su, sw) # normal + t = (-su, cu, 0.0) # tangente toroidal, |t| = 1 + pos = [p] + paso = largo / (K - 1) + for k in range(1, K): + s = k / (K - 1.0) + phi = (math.pi / 2) * s ** 0.85 + cs, sn = math.cos(phi), math.sin(phi) + d = (n[0] * cs + t[0] * sn, n[1] * cs + t[1] * sn, n[2] * cs + t[2] * sn) + a = pos[-1] + pos.append((a[0] + d[0] * paso, a[1] + d[1] * paso, a[2] + d[2] * paso)) + splines.append(pos) + radios.append([1.0 - 0.72 * (k / (K - 1.0)) for k in range(K)]) + return splines, radios + + +def construir(T): + sc = escena() + lente, ALTO = 70.0, 6.0 + camara((0.0, -lente / 36.0 * ALTO, 0.0), (0.0, 0.0, 0.0), lente=lente) + bpy.context.scene.camera.data.sensor_fit = 'VERTICAL' + bpy.context.scene.camera.data.sensor_height = 36.0 + + luz("key", 'AREA', (-3.2, -4.6, 3.8), 800, "blanco", tam=5.0, mira=(0, 0, CZ)) + luz("fill", 'AREA', (3.8, -3.6, -1.2), 260, "celeste", tam=5.0, mira=(0, 0, CZ)) + luz("rim", 'AREA', (0.4, 4.2, 2.6), 620, "ambar", tam=4.0, mira=(0, 0, CZ)) + + rig = bpy.data.objects.new("rig", None) + bpy.context.collection.objects.link(rig) + rig.location = (0, 0, CZ) + + m_piel = material("piel", "azul", rug=0.55, metal=0.1) + bola = esfera("bola", R * 0.985, m_piel, seg=64, anillos=36) + bola.parent = rig + + base_pts = puntos_esfera(N) + splines = [pelo(p, PEINADOS[0][0], 0.0)[0] for p in base_pts] + radios = [[1.0 - 0.70 * (j / (K - 1.0)) for j in range(K)] for _ in base_pts] + pel_a = curva_poly("pelo_a", splines, grosor=0.0135, radios=radios, + mat=material("m_pelo", "ambar", rug=0.42, emis=0.55)) + pel_b = curva_poly("pelo_b", splines, grosor=0.0135, radios=radios, + mat=material("m_remol", "rosa", rug=0.42, emis=1.9)) + pel_a.parent = pel_b.parent = rig + + # marcas de los ceros + marcas = [] + for k in range(2): + g = bpy.data.objects.new(f"marca{k}", None) + bpy.context.collection.objects.link(g) + g.parent = rig + anillo = toro(f"anillo{k}", 0.34, 0.024, + material(f"mm{k}", "rosa", emis=3.2), u=48, v=10) + anillo.parent = g + marcas.append(g) + + # la rosquilla, peinada de una + sp_t, ra_t = pelos_toro() + rig_t = bpy.data.objects.new("rig_toro", None) + bpy.context.collection.objects.link(rig_t) + rig_t.location = (0, 0, CZ) + rosquilla = toro("rosquilla", 0.90, 0.335, material("piel_t", "azul", rug=0.55)) + rosquilla.parent = rig_t + pelo_t = curva_poly("pelo_toro", sp_t, grosor=0.0125, radios=ra_t, + mat=material("m_pelo_t", "verde", rug=0.42, emis=0.8)) + pelo_t.parent = rig_t + rig_t.rotation_mode = 'ZYX' # primero gira sobre su eje, despues se inclina + rig_t.scale = (0, 0, 0) + + etq = {"esf": texto("2", tam=0.52, color="ambar"), + "ros": texto("0", tam=0.52, color="verde"), + "pie": texto("agujeros que cuentan", tam=0.19, color="gris")} + for o in etq.values(): + o.scale = (0, 0, 0) + return dict(rig=rig, rig_t=rig_t, bola=bola, pel_a=pel_a, pel_b=pel_b, + marcas=marcas, base=base_pts, etq=etq, piel=m_piel, rosq=rosquilla) + + +def main(): + T = Tiempo(NOMBRE) + ob = construir(T) + base, pel_a, pel_b = ob["base"], ob["pel_a"], ob["pel_b"] + cache = {"clave": None} + + def peinar(idx_eje, peinado): + clave = (idx_eje, round(peinado, 3)) + if cache["clave"] == clave: + return + cache["clave"] = clave + eje = normaliza(PEINADOS[idx_eje][0]) + tipo = PEINADOS[idx_eje][1] + sp, ra_a, ra_b = [], [], [] + for p in base: + pos, m = pelo(p, eje, peinado, tipo) + sp.append(pos) + tap = [1.0 - 0.70 * (j / (K - 1.0)) for j in range(K)] + remolino = m < UMBRAL * 0.62 and peinado > 0.25 + ra_a.append([0.0 if remolino else t for t in tap]) + ra_b.append([t * 1.25 if remolino else 0.0 for t in tap]) + rehacer_curva(pel_a, sp, ra_a) + rehacer_curva(pel_b, sp, ra_b) + + def actualizar(f): + t = T.t(f) + # se mece en vez de girar: asi los dos ceros no se van al fondo + ob["rig"].rotation_euler = (0.0, 0.0, 0.26 * math.sin(0.42 * t)) + ob["rig_t"].rotation_euler = (0.56, 0.0, 0.5 + 0.22 * t) + + # que peinado toca y cuanto esta peinado + if f < T.rango(2)[0]: + idx, peinado = 0, 0.0 + elif f < T.rango(4)[0]: + idx, peinado = 0, suave(T.p(f, 2) * 1.35) + elif f < T.rango(6)[0]: + p4 = T.p(f, 4) + idx = 0 if p4 < 0.35 else 1 + peinado = 1.0 - suave(p4 / 0.35) if p4 < 0.35 else suave((p4 - 0.35) / 0.5) + elif f < T.rango(7)[0]: + idx, peinado = 1, 1.0 + elif f < T.rango(8)[0]: # desfile de peinados + q = T.p(f, 7) * 3.0 + idx = 1 + min(3, int(q)) + sub = q - int(q) + peinado = min(1.0, sub * 2.6) + else: + idx, peinado = 4, 1.0 + peinar(idx, peinado) + + # marcas en los dos ceros del campo + eje = normaliza(PEINADOS[idx][0]) + vis = suave((T.p(f, 3) - 0.1) / 0.4) if f >= T.rango(3)[0] else 0.0 + if f >= T.rango(9)[0]: + vis *= 1.0 - suave(T.p(f, 9) / 0.4) + for k, g in enumerate(ob["marcas"]): + s = 1 if k == 0 else -1 + d = tuple(c * s for c in eje) + # el aro flota por encima del pelo, si no queda enterrado + g.location = tuple(c * (R + LARGO * 0.62) for c in d) + g.rotation_euler = Vector(d).to_track_quat('Z', 'Y').to_euler() + pul = 1.0 + 0.10 * math.sin(t * 4.2) + g.scale = (vis * pul,) * 3 + + # el planeta: el pelo se vuelve viento + pl = suave(T.p(f, 8)) + ob["piel"].node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = \ + (*tuple(a + (b - a) * pl for a, b in zip(srgb("azul"), srgb("#0E5A73"))), 1) + + # la rosquilla entra en el beat 9 + ent = suave((T.p(f, 9) - 0.15) / 0.5) + sal = suave((T.p(f, 10) - 0.05) / 0.35) + s_esf = (1.0 - ent) + sal * 0.60 + ob["rig"].scale = (s_esf,) * 3 + ob["rig"].location = (0.0 - 1.00 * sal, 0.0, CZ + 0.22 * sal) + s_ros = ent * (1.0 - 0.38 * sal) + ob["rig_t"].scale = (s_ros,) * 3 + ob["rig_t"].location = (0.0 + 1.02 * sal, 0.0, CZ + 0.22 * sal) + + e = ob["etq"] + e["esf"].location = (-1.02, 0.0, CZ - 0.98) + e["ros"].location = (1.05, 0.0, CZ - 0.98) + e["pie"].location = (0.0, 0.0, CZ - 1.42) + for o in e.values(): + o.scale = (sal,) * 3 + + render_secuencia(NOMBRE, T, actualizar) + + +main() diff --git a/blender/caos.py b/blender/caos.py new file mode 100644 index 0000000..99ef9db --- /dev/null +++ b/blender/caos.py @@ -0,0 +1,219 @@ +# -*- coding: utf-8 -*- +"""CAOS - tres pendulos dobles con 1 mm de diferencia inicial. + +La fisica es un RK4 sobre las ecuaciones exactas del pendulo doble, en unidades +SI (L1 = L2 = 1 m), integrada antes de renderizar y muestreada por frame. El +milimetro del guion es literal: 0,001 rad sobre una varilla de 1 m. +""" +import math, os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import bpy +from base import * + +NOMBRE = "caos" +G, L1, L2, M1, M2 = 9.81, 1.0, 1.0, 1.0, 1.0 +TH0 = 2.4 # 138 grados: regimen caotico, separacion visible a los ~2,5 s +DELTA = 0.001 # radianes = 1 mm en la punta de la primera varilla +ESC = 0.80 # escala de dibujo (la fisica sigue en metros) +ALTO = 6.0 # metros visibles de alto en el encuadre +PZ_A, PZ_B = 0.47, 1.11 # altura del pivote antes / despues del beat 8 +K_B = 0.66 # el rig se achica para dejar lugar al grafico +# banda util medida sobre el overlay: el chip llega a z=+2,27 y la caja de +# subtitulos arranca en z=-1,09 (tres lineas) / -1,25 (dos lineas) +GX0, GZ0, GW, GH = -1.45, -0.92, 2.90, 0.80 +COLS = ["ambar", "rosa", "celeste"] +ESTELA = 34 # frames de cola +BEAT_SUELTA = 4 # se sueltan al empezar este beat + + +# --- integrador --------------------------------------------------------------- +def deriv(s): + t1, t2, w1, w2 = s + d = t1 - t2 + den = 2 * M1 + M2 - M2 * math.cos(2 * d) + a1 = (-G * (2 * M1 + M2) * math.sin(t1) - M2 * G * math.sin(t1 - 2 * t2) + - 2 * math.sin(d) * M2 * (w2 * w2 * L2 + w1 * w1 * L1 * math.cos(d))) / (L1 * den) + a2 = (2 * math.sin(d) * (w1 * w1 * L1 * (M1 + M2) + G * (M1 + M2) * math.cos(t1) + + w2 * w2 * L2 * M2 * math.cos(d))) / (L2 * den) + return (w1, w2, a1, a2) + + +def rk4(s, h): + k1 = deriv(s) + k2 = deriv(tuple(s[i] + h / 2 * k1[i] for i in range(4))) + k3 = deriv(tuple(s[i] + h / 2 * k2[i] for i in range(4))) + k4 = deriv(tuple(s[i] + h * k3[i] for i in range(4))) + return tuple(s[i] + h / 6 * (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]) for i in range(4)) + + +def articulaciones(s): + """(codo, punta) en metros, relativo al pivote.""" + t1, t2, _, _ = s + cx, cz = L1 * math.sin(t1), -L1 * math.cos(t1) + return (cx, cz), (cx + L2 * math.sin(t2), cz - L2 * math.cos(t2)) + + +def integrar(n_frames, sub=20): + """Estados de los tres pendulos, muestreados por frame.""" + est = [(TH0 + k * DELTA, TH0, 0.0, 0.0) for k in range(3)] + h = 1.0 / (FPS * sub) + tray = [[articulaciones(s) for s in est]] + for _ in range(n_frames): + for _ in range(sub): + est = [rk4(s, h) for s in est] + tray.append([articulaciones(s) for s in est]) + return tray + + +# --- escena ------------------------------------------------------------------- +def construir(T): + sc = escena() + lente = 70.0 + dist = lente / 36.0 * ALTO # distancia para ver ALTO metros de alto + # la camara se centra en z=0: asi las coordenadas coinciden con el cuadro + # y se puede ubicar todo respecto del chip y de los subtitulos + cam = camara((0.0, -dist, 0.0), (0.0, 0.0, 0.0), lente=lente) + cam.data.sensor_fit = 'VERTICAL' + cam.data.sensor_height = 36.0 + + luz("key", 'AREA', (-3.6, -5.2, 4.6), 900, "blanco", tam=5.0, mira=(0, 0, PZ_A)) + luz("fill", 'AREA', (4.2, -4.6, -0.6), 300, "celeste", tam=5.0, mira=(0, 0, PZ_A)) + luz("rim", 'AREA', (0.8, 4.6, 2.6), 520, "blanco", tam=4.0, mira=(0, 0, PZ_A)) + + # cubo del pivote: un disco metalico mirando a camara, sin soporte que tape + m_hub = material("hub", "riel", rug=0.35, metal=0.9) + hub = cilindro("hub", 0.105, 0.10, m_hub) + hub.rotation_euler = (math.pi / 2, 0, 0) + aro = cilindro("aro", 0.145, 0.05, material("aro", "gris", rug=0.25, metal=1.0, emis=0.5)) + aro.rotation_euler = (math.pi / 2, 0, 0) + + pend = [] + for k, c in enumerate(COLS): + m = material(f"p{k}", c, rug=0.28, metal=0.55, emis=0.25) + m_bola = material(f"b{k}", c, rug=0.18, metal=0.2, emis=0.9) + pend.append({ + "y": -0.035 * (k - 1), "col": c, + "v1": cilindro(f"v1_{k}", 0.034, 1.0, m), + "v2": cilindro(f"v2_{k}", 0.029, 1.0, m), + "codo": esfera(f"codo_{k}", 0.055, m_bola), + "punta": esfera(f"punta_{k}", 0.090, m_bola), + "estela": curva_poly(f"estela_{k}", [[(0, 0, 0)] * ESTELA], grosor=0.032, + radios=[[0.0] * ESTELA], + mat=material(f"e{k}", c, rug=0.5, emis=2.4)), + }) + + leyenda = [] + for k, (c, txt) in enumerate(zip(COLS, ("arranca +0 mm", "arranca +1 mm", "arranca +2 mm"))): + t = texto(txt, tam=0.23, color=c, align='LEFT') + t.location = (-1.25, -0.6, -0.28 - 0.38 * k) + p = esfera(f"pt_{k}", 0.075, material(f"pm{k}", c, emis=2.2)) + p.location = (-1.42, -0.6, -0.28 - 0.38 * k) + leyenda.append((t, p)) + + m_ejes = material("ejes", "gris", rug=0.6, emis=0.9) + graf = { + "x": cilindro("gx", 0.014, GW, m_ejes), + "y": cilindro("gy", 0.014, GH, m_ejes), + "curva": curva_poly("gcurva", [[(0, 0, 0)] * 2], grosor=0.030, + radios=[[1.0] * 2], mat=material("gc", "rosa", emis=2.8)), + "arr": texto("2 metros", tam=0.20, color="gris", align='LEFT'), + "aba": texto("1 mm", tam=0.20, color="gris", align='RIGHT'), + } + graf["x"].rotation_euler = (0, math.pi / 2, 0) + graf["x"].location = (GX0 + GW / 2, 0.25, GZ0) + graf["y"].location = (GX0, 0.25, GZ0 + GH / 2) + # las etiquetas van donde la curva no pasa: arriba a la izquierda y abajo a + # la derecha (la curva sale de abajo-izquierda y termina arriba-derecha) + graf["arr"].location = (GX0 + 0.12, 0.25, GZ0 + GH + 0.02) + graf["aba"].location = (GX0 + GW - 0.10, 0.25, GZ0 + 0.13) + return dict(cam=cam, pend=pend, leyenda=leyenda, graf=graf, hub=hub, aro=aro) + + +def main(): + T = Tiempo(NOMBRE) + f_suelta = T.rango(BEAT_SUELTA)[0] + n_sim = T.n_frames - f_suelta + 2 + print(f"[{NOMBRE}] integrando {n_sim} frames de fisica...", flush=True) + tray = integrar(n_sim) + obj = construir(T) + pend, graf = obj["pend"], obj["graf"] + + # separacion entre la punta 0 y la punta 2, en metros, por frame + sep = [math.dist(p[0][1], p[2][1]) for p in tray] + LMIN, LMAX = math.log10(0.001), math.log10(2.0) + + # separacion maxima alcanzada: monotona, se lee de un vistazo + sep, mx = [], 0.0 + for p in tray: + mx = max(mx, math.dist(p[0][1], p[2][1])) + sep.append(mx) + LMIN, LMAX = math.log10(0.001), math.log10(2.0) + + def actualizar(f): + idx = max(0, min(f - f_suelta, len(tray) - 1)) + # el rig se achica y sube en el beat 8 para dejarle lugar al grafico + m = suave(T.p(f, 8)) + pz = PZ_A + (PZ_B - PZ_A) * m + k_esc = ESC * (1.0 + (K_B - 1.0) * m) + obj["hub"].location = (0, 0.06, pz) + obj["aro"].location = (0, 0.02, pz) + obj["hub"].scale = obj["aro"].scale = (1 - 0.3 * m,) * 3 + + abanico = (1.0 - suave(T.p(f, 0))) * 0.34 if f < f_suelta else 0.0 + for k, g in enumerate(pend): + (cx, cz), (px, pz2) = tray[idx][k] + if abanico: + ang = TH0 + (k - 1) * abanico + cx, cz = L1 * math.sin(ang), -L1 * math.cos(ang) + px, pz2 = cx + L2 * math.sin(ang), cz - L2 * math.cos(ang) + y = g["y"] + o = (0.0, y, pz) + codo = (cx * k_esc, y, pz + cz * k_esc) + punta = (px * k_esc, y, pz + pz2 * k_esc) + orientar(g["v1"], o, codo) + orientar(g["v2"], codo, punta) + g["v1"].scale = (1, 1, L1 * k_esc) + g["v2"].scale = (1, 1, L2 * k_esc) + g["codo"].location = codo + g["punta"].location = punta + g["codo"].scale = g["punta"].scale = (1 - 0.3 * m,) * 3 + # la estela sale de la trayectoria, no se acumula: vale con frames salteados + pts, rad = [], [] + for j in range(ESTELA): + i2 = idx - (ESTELA - 1 - j) + q = tray[max(0, i2)][k][1] + pts.append((q[0] * k_esc, y, pz + q[1] * k_esc)) + vivo = 1.0 if (i2 > 0 and f >= f_suelta) else 0.0 + rad.append(vivo * (j / (ESTELA - 1.0)) ** 2.2) + rehacer_curva(g["estela"], [pts], [rad]) + + vis = suave(T.p(f, 1)) * (1.0 - suave(T.p(f, 3))) + for t, p in obj["leyenda"]: + t.scale = p.scale = (vis, vis, vis) + + gv = suave(T.p(f, 8)) + for k in ("x", "y", "arr", "aba"): + graf[k].scale = (gv, gv, gv) + n_g = min(len(sep), int(8.0 * FPS)) # ventana: los primeros 8 s + avance = suave((T.p(f, 8) - 0.12) / 0.6) * n_g + pts, rad = [], [] + for i in range(n_g): + x = GX0 + GW * i / (n_g - 1.0) + v = (math.log10(max(sep[i], 1e-3)) - LMIN) / (LMAX - LMIN) + pts.append((x, 0.25, GZ0 + GH * max(0.0, min(1.0, v)))) + rad.append(1.0 if i <= avance else 0.0) + if len(graf["curva"].data.splines[0].points) != len(pts): + graf["curva"].data.splines.clear() + sp = graf["curva"].data.splines.new('POLY') + sp.points.add(len(pts) - 1) + rehacer_curva(graf["curva"], [pts], [[r * gv for r in rad]]) + + if os.environ.get("MODO") == "sim": + for s in (0, 1, 2, 2.5, 3, 4, 5, 6, 8): + i = min(int(s * FPS), len(sep) - 1) + print(f" t={s:4.1f}s separacion = {sep[i]*100:8.2f} cm") + return + render_secuencia(NOMBRE, T, actualizar) + + +main() diff --git a/blender/diferencial.py b/blender/diferencial.py new file mode 100644 index 0000000..015444a --- /dev/null +++ b/blender/diferencial.py @@ -0,0 +1,304 @@ +# -*- coding: utf-8 -*- +"""DIFERENCIAL - por que las dos ruedas pueden girar a distinta velocidad. + +Todas las piezas se generan por codigo y se mueven con la cinematica exacta del +mecanismo: w_izq + w_der = 2 * w_jaula, y el satelite gira sobre su eje a +(w_der - w_izq)/2 respecto de la jaula. El pinon y la corona respetan su +relacion: 14 y 43 dientes, con semiangulos de cono que suman 90 grados. +""" +import math, os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import bpy +from mathutils import Vector +from base import * + +NOMBRE = "diferencial" +EJE_X = 1.32 # donde van las ruedas +R_RUEDA = 0.52 +OMEGA = 1.45 # rad/s de la jaula +RADIO_GIRO = 3.9 +TROCHA = 1.70 +INCL = -0.72 # bien diagonal: en 9:16 es lo que aprovecha el alto + +N_COR, N_PIN = 43, 14 # relacion 3,07:1, como un diferencial de calle +G_COR, G_PIN = 72.0, 18.0 # los semiangulos suman 90: es la condicion de engrane +N_LAT = 16 +X_COR = -0.50 # apice comun de corona y pinon: lejos de los satelites +D_I, D_O = 0.70, 1.00 # la cara dentada, igual en los dos +P_FASE = math.pi / 2 # para que el diente caiga en el hueco +P_ESP = -0.62 # mano contraria a la corona +P_SIG = 1.0 + +# el conjunto mide 3,68 de punta a punta; inclinado 41 grados eso son 2,77 de +# ancho y 2,41 de alto, que es lo que fija estos numeros +ENCUADRE = [(0, 6.2), (2, 5.0), (3, 4.2), (4, 5.6), (5, 4.6), + (6, 5.0), (7, 5.6), (8, 5.6), (9, 5.8), (10, 5.2)] +DIR_CAM = Vector((0.30, -0.93, 0.21)).normalized() + + +def alto_en(T, f): + tabla, altos, v = dict(ENCUADRE), [], ENCUADRE[0][1] + for i in range(len(T.beats)): + v = tabla.get(i, v) + altos.append(v) + i = 0 + for k in range(len(T.beats)): + if f >= T.rango(k)[0]: + i = k + ini, fin = T.rango(i) + p = min(1.0, (f - ini) / max(1.0, (fin - ini) * 0.55)) + return mezcla(altos[i - 1] if i else altos[0], altos[i], p) + + +def construir(T): + sc = escena() + mundo_estudio(0.65) # lo que refleja el acero + cam = camara((0, -6, 0), (0, 0, 0), lente=50) + cam.data.sensor_fit = 'VERTICAL' + cam.data.sensor_height = 36.0 + + luz("key", 'AREA', (-3.4, -4.6, 4.4), 1400, "blanco", tam=6.0, mira=(0, 0, 0)) + luz("fill", 'AREA', (4.2, -3.2, -1.6), 420, "#BFD4FF", tam=5.0, mira=(0, 0, 0)) + luz("rim", 'AREA', (-0.8, 4.6, 2.8), 900, "blanco", tam=4.0, mira=(0, 0, 0)) + + M = { + "acero": metal("acero", "#B7BEC9", rug=0.22), + "acero2": metal("acero2", "#9BA3B0", rug=0.30), + "fundido": metal("fundido", "#5E6774", rug=0.62, met=0.85), + "eje_i": metal("eje_i", "#C2C8D2", rug=0.24), + "eje_d": metal("eje_d", "#C2C8D2", rug=0.24), + "goma": material("goma", "#1E222C", rug=0.52), + "alu": metal("alu", "#CBD3DE", rug=0.15), + "freno": metal("freno", "#79818E", rug=0.45, met=0.9), + } + + # --- vista de arriba: el auto doblando -------------------------------- + piso = bpy.data.objects.new("suelo_g", None) + bpy.context.collection.objects.link(piso) + arcos, ruedas_a = [], [] + for k, (rr, c) in enumerate(((RADIO_GIRO - TROCHA / 2, "rosa"), + (RADIO_GIRO + TROCHA / 2, "verde"))): + pts = [] + for i in range(120): + th = -0.62 + 1.24 * i / 119.0 + pts.append((-RADIO_GIRO + rr * math.cos(th), rr * math.sin(th), 0.0)) + cu = curva_poly(f"arco{k}", [pts], grosor=0.045, radios=[[0.0] * 120], + mat=material(f"m_arco{k}", c, emis=2.4, rug=0.5)) + cu.parent = piso + arcos.append((cu, pts)) + r = rueda_completa(f"ra{k}", M, R=R_RUEDA, r=0.185, ancho=0.28) + r.parent = piso + ruedas_a.append(r) + eje_a = cilindro("eje_a", 0.075, TROCHA, M["acero2"]) + eje_a.parent = piso + patina = curva_poly("patina", [[(0, 0, 0)] * 60], grosor=0.11, + radios=[[0.0] * 60], mat=material("m_pat", "blanco", emis=3.4)) + patina.parent = piso + + # --- el diferencial ---------------------------------------------------- + dif = bpy.data.objects.new("dif", None) + bpy.context.collection.objects.link(dif) + dif.scale = (0, 0, 0) + + jaula = bpy.data.objects.new("jaula", None) + bpy.context.collection.objects.link(jaula) + jaula.parent = dif + # caja de la jaula: dos bridas anulares y dos paredes curvas sobre el eje del + # perno. Los lados +-Y quedan abiertos: por ahi se ven los engranajes, que es + # como se ve una caja de diferencial de verdad + # todo lo de la jaula queda por dentro de r=0.52: el pinon nunca baja de + # r=0.59, y asi la jaula puede girar sin pasarle por encima + for sx in (0.58, -0.58): + br = anillo_plano(f"brida{sx}", 0.13, 0.52, 0.08, M["fundido"]) + br.rotation_euler = (0, math.pi / 2, 0) + br.location = (sx, 0, 0) + br.parent = jaula + for k, centro in enumerate((math.pi / 2, -math.pi / 2)): + pared = sector_anillo(f"pared{k}", 0.43, 0.52, 1.16, + centro - 0.62, centro + 0.62, M["fundido"]) + pared.rotation_euler = (0, math.pi / 2, 0) + pared.parent = jaula + perno = cilindro("perno", 0.062, 1.00, M["acero2"]) + perno.parent = jaula + + corona = engranaje_conico("corona", (1, 0, 0), N=N_COR, gamma=G_COR, + d_i=D_I, d_o=D_O, alto=0.042, mat=M["acero"], + espiral=0.62, espesor=0.14, hueco=0.58, + por_diente=24) + corona.location = (X_COR, 0, 0) + corona.parent = jaula + tornillos("bulones", 10, 0.78, -0.11, largo=0.10, r_t=0.035, + mat=M["acero2"], padre=jaula) + + lat = {} + for nom, eje, sx in (("izq", (-1, 0, 0), -1), ("der", (1, 0, 0), 1)): + g = bpy.data.objects.new(f"lat_{nom}", None) + bpy.context.collection.objects.link(g) + g.parent = dif + eng = engranaje_conico(f"eng_{nom}", eje, N=N_LAT, gamma=45.0, + d_i=0.26, d_o=0.50, alto=0.042, mat=M["acero"], + espiral=0.30, espesor=0.12, hueco=0.09) + eng.parent = g + # semieje escalonado + brida + for (largo, radio, x0) in ((0.48, 0.110, 0.50), (EJE_X - 0.82, 0.080, 0.95)): + se = cilindro(f"se_{nom}_{radio}", radio, largo, M[f"eje_{nom[0]}"]) + se.rotation_euler = (0, math.pi / 2, 0) + se.location = (sx * x0, 0, 0) + se.parent = g + brida = anillo_plano(f"bw_{nom}", 0.09, 0.22, 0.07, M["acero2"]) + brida.rotation_euler = (0, math.pi / 2, 0) + brida.location = (sx * (EJE_X - 0.20), 0, 0) + brida.parent = g + rue = rueda_completa(f"rue_{nom}", M, R=R_RUEDA, r=0.185, ancho=0.28) + rue.location = (sx * EJE_X, 0, 0) + rue.parent = g + lat[nom] = g + + sat = [] + for k, eje in enumerate(((0, 0, 1), (0, 0, -1))): + g = bpy.data.objects.new(f"sat{k}", None) + bpy.context.collection.objects.link(g) + g.parent = jaula + eng = engranaje_conico(f"eng_s{k}", eje, N=N_LAT, gamma=45.0, + d_i=0.26, d_o=0.50, alto=0.042, mat=M["acero2"], + espiral=-0.30, espesor=0.12, hueco=0.09, fase=math.pi) + eng.parent = g + if k == 0: + p = esfera(f"testigo{k}", 0.050, material("m_test", "ambar", emis=3.0)) + p.location = (0.30, 0.0, 0.42) + p.parent = g + sat.append(g) + + entrada = bpy.data.objects.new("entrada", None) + bpy.context.collection.objects.link(entrada) + entrada.parent = dif + # misma cara que la corona, espiral de mano contraria y fase para que el + # diente caiga en el hueco + pinon = engranaje_conico("pinon", (0, -1, 0), N=N_PIN, gamma=G_PIN, + d_i=D_I, d_o=D_O, alto=0.042, mat=M["acero"], + espiral=P_ESP, espesor=0.12, hueco=0.07, + fase=P_FASE, por_diente=24) + pinon.location = (X_COR, 0, 0) + pinon.parent = entrada + cardan = cilindro("cardan", 0.095, 1.30, M["acero2"]) + cardan.rotation_euler = (math.pi / 2, 0, 0) + cardan.location = (X_COR, -1.50, 0) + cardan.parent = entrada + horquilla = anillo_plano("horquilla", 0.10, 0.24, 0.10, M["acero2"]) + horquilla.location = (X_COR, -1.20, 0) + horquilla.rotation_euler = (math.pi / 2, 0, 0) + horquilla.parent = entrada + + barras = {} + for nom, c, z in (("izq", "rosa", -0.92), ("der", "verde", -0.60)): + riel = cilindro(f"riel_{nom}", 0.038, 1.50, material(f"mr_{nom}", "riel", rug=0.6)) + riel.rotation_euler = (0, math.pi / 2, 0) + riel.location = (0.90, -0.6, z) + b = cilindro(f"bar_{nom}", 0.060, 1.0, material(f"mb_{nom}", c, emis=2.6)) + b.rotation_euler = (0, math.pi / 2, 0) + barras[nom] = (riel, b, z) + riel.scale = b.scale = (0, 0, 0) + fecha = texto("1827", tam=0.44, color="ambar") + fecha.scale = (0, 0, 0) + + def emision(mat, v, col=None): + n = mat.node_tree.nodes["Principled BSDF"] + n.inputs["Emission Strength"].default_value = v + if col is not None: + n.inputs["Emission Color"].default_value = (*srgb(col), 1) + + return dict(cam=cam, M=M, emision=emision, piso=piso, arcos=arcos, + ruedas_a=ruedas_a, eje_a=eje_a, patina=patina, dif=dif, lat=lat, + jaula=jaula, sat=sat, entrada=entrada, pinon=pinon, + barras=barras, fecha=fecha) + + +def main(): + T = Tiempo(NOMBRE) + ob = construir(T) + M, barras = ob["M"], ob["barras"] + + def actualizar(f): + t = T.t(f) + baja = suave(T.p(f, 2) / 0.62) + dist = 50.0 / 36.0 * alto_en(T, f) + apuntar(ob["cam"], Vector((0.0, -1.1, 8.6)).lerp(DIR_CAM * dist, baja), + Vector((0.0, 0.0, 0.0)).lerp(Vector((0.0, 0.0, -0.50)), baja)) + + # ---- vista de arriba + vis_g = 1.0 - suave(T.p(f, 2) / 0.45) + ob["piso"].scale = (vis_g, vis_g, vis_g) + if vis_g > 0.001: + av = suave(T.p(f, 0) * 0.62) if f < T.rango(1)[0] else \ + mezcla(0.62, 1.0, T.p(f, 1)) + th = -0.60 + 1.20 * av + centros = [] + for k, (cu, pts) in enumerate(ob["arcos"]): + rr = RADIO_GIRO + (TROCHA / 2) * (1 if k else -1) + c = Vector((-RADIO_GIRO + rr * math.cos(th), rr * math.sin(th), R_RUEDA)) + centros.append(c) + n = max(2, int(120 * av)) + rehacer_curva(cu, [pts], [[1.0 if i <= n else 0.30 for i in range(120)]]) + giro = (rr * (th + 0.60)) / R_RUEDA + if f >= T.rango(1)[0]: + rig = (RADIO_GIRO + TROCHA / 2) * (th + 0.60) / R_RUEDA + giro = mezcla(giro, rig, suave(T.p(f, 1) / 0.35)) + r = ob["ruedas_a"][k] + r.location = c + r.rotation_euler = (giro, 0, th) # rueda sobre su eje y apunta al centro + medio = (centros[0] + centros[1]) / 2 + ob["piso"].location = (-medio.x, -medio.y - 0.30, 0.0) + ob["eje_a"].location = medio + ob["eje_a"].rotation_euler = (0, math.pi / 2, th) + pv = suave(T.p(f, 1) / 0.4) + rr = RADIO_GIRO - TROCHA / 2 + pts, rad = [], [] + for i in range(60): + a2 = -0.60 + (th + 0.60) * i / 59.0 + pts.append((-RADIO_GIRO + rr * math.cos(a2), rr * math.sin(a2), 0.04)) + rad.append(pv * min(1.0, (i / 59.0) * 2.4)) + rehacer_curva(ob["patina"], [pts], [rad]) + + # ---- el diferencial + ap = suave((T.p(f, 2) - 0.35) / 0.5) + ob["dif"].scale = (ap, ap, ap) + ob["dif"].rotation_euler = (0, INCL, 0) + arranca = T.rango(6)[0] + tt = max(0.0, t - T.t(arranca)) + k_giro = mezcla(0.0, 0.42, T.p(f, 8) / 0.7) + ang_j = OMEGA * tt if f >= arranca else 0.0 + ang_i = ang_j * (1.0 - k_giro) + ang_d = ang_j * (1.0 + k_giro) + ob["jaula"].rotation_euler = (ang_j, 0, 0) + ob["lat"]["izq"].rotation_euler = (ang_i, 0, 0) + ob["lat"]["der"].rotation_euler = (ang_d, 0, 0) + for k, g in enumerate(ob["sat"]): + g.rotation_euler = (0, 0, (ang_i - ang_d) / 2 * (1 if k == 0 else -1)) + ob["pinon"].rotation_euler = (0, P_SIG * ang_j * N_COR / N_PIN, 0) + + # ---- resaltados en los colores del canal, sobre el acero + def pico(i): + p = T.p(f, i) + return 0.85 * math.sin(math.pi * p) ** 2 if 0.0 < p < 1.0 else 0.0 + ob["emision"](M["eje_i"], pico(4), "rosa") + ob["emision"](M["eje_d"], pico(4), "verde") + ob["emision"](M["acero2"], pico(5), "celeste") + ob["emision"](M["fundido"], pico(5), "ambar") + ob["emision"](M["acero"], pico(6), "ambar") + + # ---- barras de velocidad + bv = suave(T.p(f, 9) / 0.4) * (1.0 - suave(T.p(f, 10) / 0.3)) + for nom, (riel, bar, z) in barras.items(): + riel.scale = (bv, bv, bv) + rel = (1.0 - k_giro) if nom == "izq" else (1.0 + k_giro) + L = 1.50 * rel / 1.5 + bar.scale = (bv, bv, bv * L) + bar.location = (0.15 + L / 2, -0.6, z) + fv = suave((T.p(f, 10) - 0.25) / 0.4) + ob["fecha"].location = (0.90, 0.0, -0.80) + ob["fecha"].scale = (fv, fv, fv) + + render_secuencia(NOMBRE, T, actualizar) + + +main() diff --git a/blender/domino.py b/blender/domino.py new file mode 100644 index 0000000..bf5f681 --- /dev/null +++ b/blender/domino.py @@ -0,0 +1,539 @@ +# -*- coding: utf-8 -*- +"""DOMINO - una ficha de 5 mm, cada una 1,5 veces mas grande que la anterior. + +Parte real: 13 fichas (5 mm a 65 cm) simuladas en Godot (Jolt), a escala real. +Parte imaginada: las fichas 14 a 36 en pie, comparadas con una persona, el +Obelisco, el Empire State y el Aconcagua. Las alturas son exactas: + h(n) = 5 mm * 1,5^(n-1) + + MODO=sim blender -b -P blender/domino.py # exporta y corre Godot + PRUEBA=1 (con MODO=sim) simula sin timeline, para ajustar la separacion + blender -b -P blender/domino.py # renderiza +""" +import math, os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import bpy +from base import * + +NOMBRE = "domino" +H0 = 0.005 # la primera ficha +R = 1.5 # cada una, 1,5 veces la anterior +N_REAL = 13 +N_TOTAL = 36 +ANCHO, GROSOR = 0.50, float(os.environ.get("T_GR", 0.10)) # proporciones de la ficha respecto del alto +SEP = float(os.environ.get("T_SEP", 0.70)) # hueco entre fichas, en altos de la anterior +FRIC = float(os.environ.get("T_FR", 0.7)) +FPS_SIM = 240 # se graba a 240 fps: permite la camara lenta x8 + + +def alto(n): + return H0 * R ** (n - 1) + + +def posiciones(n_max=N_TOTAL): + """Centro en x de cada ficha (1-based: xs[1] es la primera).""" + xs = [0.0, 0.0] + for n in range(1, n_max): + h, h2 = alto(n), alto(n + 1) + xs.append(xs[-1] + GROSOR * h / 2 + SEP * h + GROSOR * h2 / 2) + return xs + + +def construir(): + escena(muestras=int(os.environ.get("MUESTRAS", 24))) + mundo_estudio(fuerza=0.6) + xs = posiciones() + M = { + "ficha": material("ficha", "#15171C", rug=0.18), + "punto": material("punto", "#F2F2F2", rug=0.3), + "piso": madera("piso", claro="#8C6239", oscuro="#4A2E18", escala=3.0, rug=0.75, + veta=(0.5, 1, 1)), + "inv": material("inv", "gris"), + } + fichas = {} + for n in range(1, N_TOTAL + 1): + h = alto(n) + nombre = f"bloque_d{n:02d}" if n <= N_REAL else f"ficha_{n:02d}" + ob = caja(nombre, (GROSOR * h, ANCHO * h, h), (xs[n], 0, h / 2), M["ficha"]) + # los puntos del domino, en la cara que mira a la camara (-X) y la opuesta + for lado in (-1, 1): + for (py, pz) in pips(n): + p = esfera(f"pip_{n}_{lado}_{py}_{pz}", 0.055 * h, M["punto"], seg=12, anillos=6) + p.scale = (0.35, 1, 1) + p.location = (lado * GROSOR * h / 2, py * h, pz * h) + p.parent = ob + raya = caja(f"raya_{n}", (GROSOR * h * 1.02, ANCHO * h * 0.8, 0.012 * h), (0, 0, 0), + M["punto"]) + raya.parent = ob + fichas[n] = ob + inclinar(fichas[1], xs[1], INCL) + piso = caja("caja_piso", (4.0, 3.0, 0.2), (1.0, 0, -0.1), M["inv"]) + piso.hide_render = True + return dict(fichas=fichas, xs=xs, M=M, piso=piso) + + +INCL = math.radians(12.0) # la primera arranca pasada su inclinacion de vuelco (9 grados) + + +def inclinar(ob, x, ang): + """Gira la ficha sobre su canto delantero de abajo (el que mira a +X).""" + h = ob.dimensions.z + t = ob.dimensions.x + c, s_ = math.cos(ang), math.sin(ang) + ob.rotation_euler = (0, ang, 0) + ob.location = (x + t / 2 - c * t / 2 + s_ * h / 2, 0, s_ * t / 2 + c * h / 2) + + +def pips(n): + """Puntos (y, z relativos al alto) de un domino: dos mitades con 0..6.""" + pat = {0: [], 1: [(0, 0)], 2: [(-1, 1), (1, -1)], 3: [(-1, 1), (0, 0), (1, -1)], + 4: [(-1, 1), (1, 1), (-1, -1), (1, -1)], + 5: [(-1, 1), (1, 1), (0, 0), (-1, -1), (1, -1)], + 6: [(-1, 1), (1, 1), (-1, 0), (1, 0), (-1, -1), (1, -1)]} + a, b = (n * 5) % 7, (n * 3 + 2) % 7 + out = [] + for (cy, cz), val in (((0, 0.25), a), ((0, -0.25), b)): + for (dy, dz) in pat[val]: + out.append((cy + dy * 0.13, cz + dz * 0.13)) + return out + + +def cuadro_suelta(T): + """El lapiz la empuja al final del beat 3 ("le doy un toquecito...").""" + a, z = T.rango(3) + return a + int(0.78 * (z - a)) + + +def simular(t_suelta, duracion, obj): + reales = [obj["fichas"][n] for n in range(1, N_REAL + 1)] + cfg = { + "duracion": duracion, + "gravedad": 9.81, + "escala": 40.0, + "hz": 7680, + "fps": FPS_SIM, + "congelados": ["bloque_"], + "reglas": {"bloque_": {"friccion": FRIC, "rebote": 0.0, "densidad": 1100}, + "caja_": {"friccion": FRIC, "rebote": 0.0}}, + "eventos": [{"t": t_suelta, "accion": "soltar", "prefijo": "bloque_"}], + } + correr_godot(exportar_fisica(NOMBRE, reales + [obj["piso"]], cfg)) + + +# --- escenografia visual (no participa de la fisica) --------------------------- +def gris(nombre, col, rug=0.6): + return material(nombre, col, rug=rug) + + +def persona(x, y): + m = gris("persona", "#C9D1DC") + g = bpy.data.objects.new("persona", None) + bpy.context.collection.objects.link(g) + partes = [] + for sx in (-0.1, 0.1): + c = cilindro(f"pierna{sx}", 0.075, 0.85, m); c.location = (0, sx, 0.425); partes.append(c) + t = cilindro("torso", 0.19, 0.62, m); t.location = (0, 0, 1.17); partes.append(t) + for sy in (-0.26, 0.26): + b = cilindro(f"brazo{sy}", 0.055, 0.62, m); b.location = (0, sy, 1.15); partes.append(b) + cab = esfera("cabeza", 0.12, m); cab.location = (0, 0, 1.62); partes.append(cab) + for p_ in partes: + p_.parent = g + g.location = (x, y, 0) + return g + + +def obelisco(x, y): + m = gris("obelisco", "#EDEFF2", 0.5) + b0, b1, h = 6.8 / 2, 3.5 / 2, 63.5 + v = [(sx * b0, sy * b0, 0) for sx, sy in ((-1, -1), (1, -1), (1, 1), (-1, 1))] + v += [(sx * b1, sy * b1, h) for sx, sy in ((-1, -1), (1, -1), (1, 1), (-1, 1))] + v += [(0, 0, 67.5)] + f = [(0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7), (4, 5, 8), (5, 6, 8), + (6, 7, 8), (7, 4, 8), (3, 2, 1, 0)] + ob = objeto("obelisco", malla_de("obelisco", v, f, suave=False), m) + ob.location = (x, y, 0) + return ob + + +def empire(x, y): + m = gris("empire", "#AEB6C2", 0.45) + g = bpy.data.objects.new("empire", None) + bpy.context.collection.objects.link(g) + for (w, d, z0, z1) in ((130, 58, 0, 25), (95, 50, 25, 250), (70, 42, 250, 290), + (48, 34, 290, 330), (26, 26, 330, 381)): + c = caja(f"es{z0}", (w, d, z1 - z0), (0, 0, (z0 + z1) / 2), m) + c.parent = g + a = cilindro("antena", 2.5, 62, m); a.location = (0, 0, 381 + 31); a.parent = g + g.location = (x, y, 0) + return g + + +def montana(x, y, alto_m=6961.0, radio=9000.0): + """Cono con ruido; nieve arriba por un material que depende de la altura.""" + import random + rnd = random.Random(5) + n_r, n_a = 40, 96 + v, f = [(0, 0, alto_m)], [] + fase = [rnd.uniform(0, 6.28) for _ in range(4)] + for i in range(1, n_r + 1): + r = radio * i / n_r + for j in range(n_a): + a = 2 * math.pi * j / n_a + ruido = sum(0.10 / (k + 1) * math.sin((k + 2) * a + fase[k] + 0.0007 * r * (k + 1)) + for k in range(4)) + z = alto_m * max(0.0, 1 - r / radio) ** 1.25 * (1 + ruido * (i / n_r)) + v.append((r * math.cos(a), r * math.sin(a), max(0.0, z))) + for j in range(n_a): + f.append((0, 1 + j, 1 + (j + 1) % n_a)) + for i in range(n_r - 1): + for j in range(n_a): + a0 = 1 + i * n_a + j + a1 = 1 + i * n_a + (j + 1) % n_a + f.append((a0, a0 + n_a, a1 + n_a, a1)) + m = bpy.data.materials.new("roca") + m.use_nodes = True + nt = m.node_tree + b = nt.nodes.get("Principled BSDF") + tc = nt.nodes.new("ShaderNodeTexCoord") + sep = nt.nodes.new("ShaderNodeSeparateXYZ") + mr = nt.nodes.new("ShaderNodeMapRange") + mr.inputs[1].default_value = alto_m * 0.62 + mr.inputs[2].default_value = alto_m * 0.72 + rampa = nt.nodes.new("ShaderNodeValToRGB") + rampa.color_ramp.elements[0].color = (*srgb("#5A5048"), 1) + rampa.color_ramp.elements[1].color = (*srgb("#F4F6FA"), 1) + nt.links.new(tc.outputs["Object"], sep.inputs[0]) + nt.links.new(sep.outputs["Z"], mr.inputs[0]) + nt.links.new(mr.outputs[0], rampa.inputs[0]) + nt.links.new(rampa.outputs["Color"], b.inputs["Base Color"]) + poner(b, "Roughness", 0.8) + ob = objeto("montana", malla_de("montana", v, f), m) + ob.location = (x, y, 0) + return ob + + +def casa(x, y): + m = gris("casa", "#D8C7A8", 0.7) + mt = gris("techo", "#8C3B2E", 0.6) + g = bpy.data.objects.new("casa", None) + bpy.context.collection.objects.link(g) + c = caja("casa_c", (9, 7, 5), (0, 0, 2.5), m); c.parent = g + v = [(-4.8, -3.8, 5), (4.8, -3.8, 5), (4.8, 3.8, 5), (-4.8, 3.8, 5), (-4.8, 0, 8), (4.8, 0, 8)] + f = [(0, 1, 5, 4), (2, 3, 4, 5), (0, 4, 3), (1, 2, 5), (3, 2, 1, 0)] + t = objeto("techo", malla_de("techo", v, f, suave=False), mt); t.parent = g + g.location = (x, y, 0) + return g + + +def moneda(x, y): + m = metal("moneda", "#D8B45A", rug=0.25) + c = cilindro("moneda", 0.0115, 0.0022, m, lados=48) + c.location = (x, y, 0.0011) + return c + + +def lapiz(): + g = bpy.data.objects.new("lapiz", None) + bpy.context.collection.objects.link(g) + cu = cilindro("lapiz_cuerpo", 0.0035, 0.12, material("amarillo", "#F2B61B", rug=0.4), lados=6) + cu.location = (0, 0, 0.06 + 0.012) + cu.parent = g + # punta: cono de madera con grafito + v = [(0.0035 * math.cos(2 * math.pi * k / 12), 0.0035 * math.sin(2 * math.pi * k / 12), 0.012) + for k in range(12)] + [(0, 0, 0)] + f = [(k, (k + 1) % 12, 12) for k in range(12)] + pt = objeto("lapiz_punta", malla_de("lapiz_punta", v, f), material("madera_l", "#E8C79A")) + pt.parent = g + return g + + +def main(): + obj = construir() + if os.environ.get("MODO") == "sim" and os.environ.get("PRUEBA"): + simular(0.2, 7.0, obj) + return + T = Tiempo(NOMBRE) + if os.environ.get("MODO") == "sim": + simular((cuadro_suelta(T) - 1) / FPS, T.n_frames / FPS + 0.5, obj) + return + render(T, obj) + + +def render(T, obj): + import numpy as np + idx, D = cargar_sim(NOMBRE) + fichas, xs = obj["fichas"], obj["xs"] + r = T.rango + fr = cuadro_suelta(T) + t_suelta = (fr - 1) / FPS + i0 = int(round(t_suelta * FPS_SIM)) + + # cuando cae cada ficha (inclinacion > 30 grados), en segundos desde la suelta + caida = {} + for n in range(1, N_REAL + 1): + qw = np.abs(D[:, idx[f"bloque_d{n:02d}"], 3]) + ang = 2 * np.degrees(np.arccos(np.clip(qw, 0, 1))) + k = int(np.argmax(ang > 30)) if (ang > 30).any() else len(D) - 1 + caida[n] = (k - i0) / FPS_SIM + t_cadena = caida[N_REAL] + 0.6 + print(f"[{NOMBRE}] caidas: " + " ".join(f"{n}:{caida[n]:.2f}" for n in caida)) + + # las imaginarias arrancan despues de donde quedo acostada la 13 + x_img = {N_REAL + 1: xs[N_REAL] + 1.25 * alto(N_REAL) + GROSOR * alto(N_REAL + 1)} + for n in range(N_REAL + 1, N_TOTAL): + h, h2 = alto(n), alto(n + 1) + x_img[n + 1] = x_img[n] + GROSOR * h / 2 + SEP * h + GROSOR * h2 / 2 + for n in range(N_REAL + 1, N_TOTAL + 1): + fichas[n].location.x = x_img[n] + X = dict(xs=xs) + X.update({n: xs[n] for n in range(1, N_REAL + 1)}) + X.update(x_img) + + # escenografia + mesa = caja("mesa", (6.0, 3.0, 0.02), (1.2, 0.0, -0.01), obj["M"]["piso"]) + mesa.visible_shadow = False # si no, su sombra cae sobre el suelo 2 mm mas abajo + # el suelo se escala cada cuadro segun la distancia de la camara: un plano de + # 200 km fijo tiene triangulos tan grandes que la profundidad pierde + # precision y tapa a la mesa (que esta 2 mm mas arriba) + suelo = caja("suelo", (1.0, 1.0, 0.02), (0, 0, -0.012), + material("suelo", "#2B2622", rug=0.9)) + lap = lapiz() + # comparaciones: la camara mira en la direccion VH (del lado de la cara con + # puntos) y cada referencia va al costado de su ficha, perpendicular a la + # mirada: asi estan a la misma distancia de la camara y la perspectiva no + # agranda a ninguna de las dos. + VH = (0.857, 0.514) + DER = (0.514, -0.857) # "a la derecha" en pantalla + L = {} + for n, gap, wl, hl in ((16, 0.30, 0.25, 1.75), (25, 12.0, 3.4, 67.5), + (29, 60.0, 65.0, 443.0), (36, 600.0, 4500.0, 6961.0), + (20, 2.5, 4.8, 8.0)): + dd = 0.3 * alto(n) + gap + wl + L[n] = (X[n] + DER[0] * dd, DER[1] * dd, dd, wl, hl) + pers = persona(L[16][0], L[16][1]) + obe = obelisco(L[25][0], L[25][1]) + emp = empire(L[29][0], L[29][1]) + mon_t = montana(L[36][0], L[36][1], radio=4500.0) + cas = casa(L[20][0], L[20][1]) + for ob_ in (pers, emp, cas): + ob_.rotation_euler = (0, 0, math.atan2(VH[1], VH[0])) # de frente a la camara + + def etiqueta(txt, col, tam, loc, giro=-0.5): + t = texto(txt, tam=tam, color=col) + t.location = loc + t.rotation_euler = (math.pi / 2, 0, giro) + t.visible_shadow = False + return t + + E = { + "5mm": etiqueta("5 mm", "ambar", 0.0035, (xs[1], -0.006, alto(1) + 0.004)), + "x15": etiqueta("×1,5", "ambar", 0.005, ((xs[1] + xs[2]) / 2, -0.01, alto(2) + 0.006)), + "65": etiqueta("65 cm", "ambar", 0.08, (xs[13], -0.1, alto(13) + 0.09)), + "16": etiqueta("16", "ambar", 0.40, (X[16], 0, 1.07 * alto(16) + 0.40 * 0.5), -1.03), + "vos": etiqueta("vos", "blanco", 0.26, (L[16][0], L[16][1], 2.0), -1.03), + "25": etiqueta("25", "ambar", 11, (X[25], 0, 1.07 * alto(25) + 11 * 0.5), -1.03), + "obe": etiqueta("Obelisco", "blanco", 7, (L[25][0], L[25][1], 75), -1.03), + "29": etiqueta("29", "ambar", 55, (X[29], 0, 1.07 * alto(29) + 55 * 0.5), -1.03), + "emp": etiqueta("Empire State", "blanco", 38, (L[29][0], L[29][1], 490), -1.03), + "36": etiqueta("36", "ambar", 900, (X[36], 0, 1.07 * alto(36) + 900 * 0.5), -1.03), + "aco": etiqueta("Aconcagua", "blanco", 700, (L[36][0], L[36][1], 7700), -1.03), + "casa": etiqueta("casa: 8 m", "blanco", 1.1, (L[20][0], L[20][1], 9.3), -1.03), + } + xs15 = [etiqueta("×1,5", "ambar", 0.35 * alto(n), (xs[n], -0.1 * alto(n), 0.22 * alto(n) + 0.02)) + for n in range(2, N_REAL + 1)] + + lente = 50.0 + cam = camara((0, -1, 0.3), (0, 0, 0), lente=lente) + cam.data.sensor_fit = 'VERTICAL' + cam.data.sensor_height = 36.0 + sol = bpy.data.lights.new("sol", 'SUN') + sol.energy = 3.2 + sol.angle = math.radians(3) + so = bpy.data.objects.new("sol", sol) + bpy.context.collection.objects.link(so) + so.rotation_euler = (math.radians(50), math.radians(-18), math.radians(-35)) + + def frente(t): + """Indice continuo de la ficha que esta cayendo a los t s de soltar.""" + if t <= 0: + return 1.0 + for n in range(1, N_REAL): + if t < caida[n + 1]: + a, b = caida[n], caida[n + 1] + return n + max(0.0, min(1.0, (t - a) / max(1e-6, b - a))) + return float(N_REAL) + + def cam_frente(t): + u = frente(t) + n = int(u) + w = u - n + n2 = min(N_REAL, n + 1) + x = X[n] + (X[n2] - X[n]) * w + 0.9 * alto(n) * (1 + 0.5 * w) + hh = alto(n) * R ** w + return x, 0.45 * hh, 5.5 * hh + + VISTA13 = ((xs[1] + xs[13]) / 2 + 0.25, 0.32, 2.3) + + def toma_ref(n): + """Encuadre de la ficha n con su referencia a la derecha: (x, z, alto, y).""" + h = alto(n) + _, _, dd, wl, hl = L[n] + izq = -(1.0 if n == 20 else 0.7) * h # algo de las fichas anteriores + der = dd + wl + c = (izq + der) / 2 + alto_v = max(max(h, hl) * 1.75, (der - izq) / 0.5625 * 1.3) + return (X[n] + DER[0] * c, max(h, hl) * 0.50, alto_v, DER[1] * c) + + tomas = [ + (1, (xs[1] + 0.003, 0.004, 0.032)), + (r(0)[1], (xs[1] + 0.004, 0.004, 0.034)), + (r(1)[0] + 20, ((xs[1] + xs[2]) / 2, 0.0055, 0.05)), + (r(1)[1], ((xs[1] + xs[2]) / 2 + 0.002, 0.006, 0.055)), + (r(2)[1] - 10, VISTA13), + (r(3)[0] + int(0.45 * (r(3)[1] - r(3)[0])), VISTA13), + (fr - 6, (xs[1] + 0.003, 0.004, 0.032)), + ] + f_rep0 = r(5)[0] + f_rep1 = r(6)[1] + tomas2 = [ + (f_rep1 + 1, VISTA13), + (r(8)[1], (VISTA13[0] + 0.1, 0.3, 2.0)), + (r(9)[1], (X[15] - 1.0, 1.0, 6.0)), + (r(10)[0] + 10, toma_ref(16)), + (r(10)[1], toma_ref(16)), + (r(11)[0] + 12, toma_ref(25)), + (r(11)[1], toma_ref(25)), + (r(12)[0] + 12, toma_ref(29)), + (r(12)[1], toma_ref(29)), + (r(13)[0] + 14, toma_ref(36)), + (r(13)[1], toma_ref(36)), + (r(14)[1] - 5, (xs[1] + 0.003, 0.004, 0.032)), + (r(15)[1], VISTA13), + (r(16)[1], (VISTA13[0], 0.3, 1.9)), + (r(17)[0] + 15, toma_ref(20)), + (T.n_frames, toma_ref(20)), + ] + + def interp(lista, f): + for (f0, a), (f1, b) in zip(lista, lista[1:]): + if f0 <= f <= f1: + u = suave((f - f0) / max(1, f1 - f0)) + ha, hb = a[2], b[2] + if max(ha, hb) / min(ha, hb) > 3: + # zoom grande: alto en escala log, el blanco se mueve con el alto + h = math.exp(math.log(ha) + (math.log(hb) - math.log(ha)) * u) + w = (h - ha) / (hb - ha) + else: + h = ha + (hb - ha) * u + w = u + ya = a[3] if len(a) > 3 else 0.0 + yb = b[3] if len(b) > 3 else 0.0 + return (a[0] + (b[0] - a[0]) * w, a[1] + (b[1] - a[1]) * w, h, ya + (yb - ya) * w) + ult = lista[-1][1] if f > lista[-1][0] else lista[0][1] + return tuple(ult) + ((0.0,) if len(ult) == 3 else ()) + + def t_sim(f): + """Segundos de simulacion desde la suelta que se muestran en el cuadro f.""" + if f < fr: + return 0.0 + if f < f_rep0: + return (f - fr) / FPS + if f <= f_rep1: + u = (f - f_rep0) / max(1, f_rep1 - f_rep0) + return t_cadena * u * u # rampa: lenta al principio + return t_cadena + 2.0 + + def actualizar(f): + ts = t_sim(f) + i = max(0, min(len(D) - 1, i0 + int(round(ts * FPS_SIM)))) + for n in range(1, N_REAL + 1): + poner_pose(fichas[n], D[i, idx[f"bloque_d{n:02d}"]]) + # antes de soltar, la primera esta derecha y el lapiz la inclina + f_emp = fr - 22 + if f < fr: + u = suave((f - f_emp) / 22.0) if f >= f_emp else 0.0 + fichas[1].rotation_mode = 'XYZ' + inclinar(fichas[1], xs[1], INCL * u) + h1 = alto(1) + lap_vis = (fr - 60) <= f <= fr + 25 + lap.hide_render = not lap_vis + for c in lap.children: + c.hide_render = not lap_vis + if lap_vis: + llega = suave((f - (fr - 60)) / 38.0) + vuelve = suave((f - fr) / 20.0) + u = suave((f - f_emp) / 22.0) if f >= f_emp else 0.0 + tip_x = xs[1] - GROSOR * h1 / 2 + h1 * math.sin(INCL * u) - 0.02 * (1 - llega) - 0.01 * vuelve + lap.location = (tip_x, 0.0, 0.9 * h1 + 0.02 * (1 - llega) + 0.01 * vuelve) + lap.rotation_euler = (0, math.radians(-62), 0) + + # imaginarias + # hasta que ficha se ve: crece con la narracion + if f < r(9)[0]: + n_vis = N_REAL + elif f < r(10)[0]: + n_vis = N_REAL + 3 * T.p(f, 9) + elif f < r(11)[0]: + n_vis = 16 + elif f < r(12)[0]: + n_vis = 16 + 9 * suave(T.p(f, 11) / 0.2) + elif f < r(13)[0]: + n_vis = 25 + 4 * suave(T.p(f, 12) / 0.2) + elif f < r(17)[0]: + n_vis = 29 + 7 * suave(T.p(f, 13) / 0.2) + else: + n_vis = 20 + for n in range(N_REAL + 1, N_TOTAL + 1): + fichas[n].hide_render = n > n_vis + 1e-6 + for c in fichas[n].children: + c.hide_render = fichas[n].hide_render + for ob_, beat in ((pers, 10), (obe, 11), (emp, 12), (mon_t, 13), (cas, 17)): + vis = f >= r(beat)[0] - 6 if beat != 17 else f >= r(17)[0] - 10 + ob_.hide_render = not vis + for c in ob_.children: + c.hide_render = not vis + vis_lab = { + "5mm": r(0)[0] <= f < r(2)[0] + 10, "x15": r(1)[0] + 15 <= f < r(2)[0] + 10, + "65": r(3)[0] <= f < fr - 30, "16": r(10)[0] <= f < r(11)[0], + "vos": r(10)[0] + 8 <= f < r(11)[0], "25": r(11)[0] <= f < r(12)[0], + "obe": r(11)[0] + 8 <= f < r(12)[0], "29": r(12)[0] <= f < r(13)[0], + "emp": r(12)[0] + 8 <= f < r(13)[0], "36": r(13)[0] <= f < r(14)[0], + "aco": r(13)[0] + 8 <= f < r(14)[0], "casa": f >= r(17)[0] + 10, + } + for k, t in E.items(): + t.hide_render = not vis_lab[k] + for j, t in enumerate(xs15): + t.hide_render = not (r(7)[0] + j * 4 <= f < r(9)[0]) + + # camara + y = 0.0 + if fr - 6 <= f < f_rep0 or f_rep0 <= f <= f_rep1: + x, z, h = cam_frente(ts) + if f < fr + 4: + a = interp(tomas, f) + w = suave((f - (fr - 6)) / 10.0) + x, z, h = (a[0] + (x - a[0]) * w, a[1] + (z - a[1]) * w, a[2] + (h - a[2]) * w) + elif f < fr - 6: + x, z, h, y = interp(tomas, f) + else: + x, z, h, y = interp(tomas2, f) + dist = h * lente / 36.0 + # angulo: alto y cruzado para las fichas chicas, mas de frente para las comparaciones + k = suave((f - r(9)[0]) / 20.0) * (1 - suave(T.p(f, 14))) + suave((f - r(17)[0]) / 15.0) + k = max(0.0, min(1.0, k)) + da, db = (-0.447, -0.894, 0.32), (-VH[0], -VH[1], 0.10) + d = tuple(da[j] + (db[j] - da[j]) * k for j in range(3)) + nd = math.sqrt(sum(c * c for c in d)) + zc = z - 0.08 * h # deja lugar a los subtitulos + pos = (x + d[0] / nd * dist, y + d[1] / nd * dist, zc + d[2] / nd * dist) + apuntar(cam, pos, (x, y, zc)) + lado = max(12.0, dist * 60.0) + suelo.scale = (lado, lado, 1.0) + suelo.location = (x, y, -0.012) + cam.data.clip_start = max(1e-5, dist * 0.002) + cam.data.clip_end = dist * 400 + + render_secuencia(NOMBRE, T, actualizar) + + +main() diff --git a/blender/galton.py b/blender/galton.py new file mode 100644 index 0000000..522bc81 --- /dev/null +++ b/blender/galton.py @@ -0,0 +1,316 @@ +# -*- coding: utf-8 -*- +"""GALTON - 500 bolitas de acero contra 12 filas de clavos. + +Reparto del trabajo: + * Blender disena el tablero (clavos, tolva, compuerta, casilleros, bolitas) + y lo exporta a glTF: el nombre de cada objeto le dice a Godot que es. + * Godot (Jolt) simula los rebotes, a 240 Hz, y devuelve la pose de cada + bolita a 30 fps (godot/sim.gd). + * Blender vuelve a leer esas poses y renderiza con los materiales de verdad. + + MODO=sim blender -b -P blender/galton.py # exporta y corre Godot + blender -b -P blender/galton.py # renderiza +""" +import math, os, random, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import bpy +from base import * + +NOMBRE = "galton" +N_BOLAS = 500 +RB = 0.012 # radio de la bolita +DX = 0.12 # paso entre clavos +DY = DX * math.sqrt(3) / 2 +RP = 0.015 # radio del clavo +FILAS = 12 +NB = FILAS + 1 # casilleros +W2 = NB * DX / 2 # medio ancho interior +ALTO_CAS = 0.65 # alto de los separadores +Z_ULT = ALTO_CAS + 0.07 # ultima fila de clavos +Z_FILA = [Z_ULT + (FILAS - 1 - i) * DY for i in range(FILAS)] +Z_SAL = Z_FILA[0] + 0.10 # boca de la tolva +BOCA = float(os.environ.get("T_BOCA", 0.04)) # media boca +TOLVA_X, TOLVA_H, TOLVA_V = 0.33, 0.48, 0.62 +PROF = 0.08 # profundidad del canal (Y) +GRAV = float(os.environ.get("T_G", 12.0)) +PRE = 2.5 # segundos de fisica antes del frame 1: las bolitas se asientan +BEAT_UNA = 1 # cae una sola bolita +BEAT_SUELTA = 3 # se abre la compuerta +REB = float(os.environ.get("T_REB", 0.10)) +AMORT = float(os.environ.get("T_AM", 6.0)) + + +def x_clavos(i): + off = 0.5 if (FILAS - 1 - i) % 2 == 0 else 0.0 + xs = [] + j = -10 + while True: + x = (j + off) * DX + j += 1 + if x > W2 - 0.04: + break + if x >= -W2 + 0.04: + xs.append(x) + return xs + + +# --- diseno ------------------------------------------------------------------- +def construir(): + sc = escena(muestras=int(os.environ.get("MUESTRAS", 24))) + mundo_estudio(fuerza=0.6) + M = { + "laton": metal("laton", "#D9A441", rug=0.22), + "acero": metal("acero", "#E4E8EE", rug=0.10), + "chapa": metal("chapa", "#A9B2BF", rug=0.30), + "panel": material("panel", "#070B14", rug=0.75), + "madera": madera("madera"), + "base": madera("base", claro="#7A5230", oscuro="#3A2211", escala=3.0), + } + fis = [] # lo que va a Godot + + # clavos: cilindros a lo largo de Y, del panel del fondo al vidrio + for i, z in enumerate(Z_FILA): + for k, x in enumerate(x_clavos(i)): + c = cilindro(f"fijo_clavo_{i:02d}_{k:02d}", RP, PROF, M["laton"], lados=24) + c.rotation_euler = (math.pi / 2, 0, 0) + c.location = (x, 0, z) + fis.append(c) + + # separadores de los casilleros y paredes + for k in range(NB + 1): + x = (k - NB / 2) * DX + ext = k in (0, NB) + grosor = 0.02 if ext else 0.006 + alto = (Z_SAL + 0.02) if ext else ALTO_CAS + xo = x + (-grosor / 2 if k == 0 else grosor / 2 if k == NB else 0) + fis.append(caja(f"caja_sep_{k:02d}", (grosor, PROF, alto), (xo, 0, alto / 2), + M["chapa"])) + fis.append(caja("caja_piso", (2 * W2 + 0.04, PROF, 0.02), (0, 0, -0.01), M["chapa"])) + + # tolva: dos planos a 60 grados y un tramo vertical + dx_t, dz_t = TOLVA_X - BOCA, TOLVA_H + largo = math.hypot(dx_t, dz_t) + ang = math.atan2(dz_t, dx_t) + for s in (-1, 1): + cx = s * (BOCA + dx_t / 2) + cz = Z_SAL + dz_t / 2 + # el espesor va hacia afuera de la tolva + nx, nz = s * math.sin(ang), -math.cos(ang) + w = caja(f"caja_tolva_{'i' if s < 0 else 'd'}", (largo, PROF, 0.016), + (cx + nx * 0.008, 0, cz + nz * 0.008), M["chapa"]) + w.rotation_euler = (0, -s * ang, 0) + fis.append(w) + v = caja(f"caja_tolva_v{'i' if s < 0 else 'd'}", (0.016, PROF, TOLVA_V), + (s * (TOLVA_X + 0.008), 0, Z_SAL + TOLVA_H + TOLVA_V / 2), M["chapa"]) + fis.append(v) + compuerta = caja("compuerta_0", (2 * BOCA + 0.04, PROF, 0.012), + (0, 0, Z_SAL - 0.008), M["chapa"]) + fis.append(compuerta) + + # bolitas: una grilla arriba de la tolva; caen y se acomodan antes del frame 1 + me_bola = esfera("bola_malla", RB, M["acero"], seg=20, anillos=12).data + bpy.data.objects.remove(bpy.data.objects["bola_malla"]) + bolas = [] + rnd = random.Random(7) + paso = 2 * RB * 1.08 + por_fila = int((2 * (TOLVA_X - 0.02)) / paso) + sola = objeto("bola_000", me_bola, None) # la que cae sola, retenida bajo la compuerta + sola.location = (0.004, 0, Z_SAL - 0.032) + bolas.append(sola) + for n in range(1, N_BOLAS): + fila, col = divmod(n - 1, por_fila) + x = (col - (por_fila - 1) / 2) * paso + (paso / 2 if fila % 2 else 0) * 0.5 + x += rnd.uniform(-0.002, 0.002) + z = Z_SAL + TOLVA_H + 0.03 + fila * paso * 0.95 + ob = objeto(f"bola_{n:03d}", me_bola, None) + ob.location = (x, 0, z) + bolas.append(ob) + fis += bolas + + # --- lo que es solo visual --- + panel = caja("panel", (2 * W2 + 0.10, 0.02, Z_SAL + TOLVA_H + TOLVA_V + 0.10), + (0, PROF / 2 + 0.01, (Z_SAL + TOLVA_H + TOLVA_V) / 2), M["panel"]) + for s in (-1, 1): + caja(f"marco_{s}", (0.07, PROF + 0.06, Z_SAL + 0.12), + (s * (W2 + 0.055), 0.0, (Z_SAL + 0.12) / 2 - 0.02), M["madera"]) + caja("base", (2 * W2 + 0.40, 0.36, 0.10), (0, 0.05, -0.07), M["base"]) + caja("pie", (2 * W2 + 0.60, 0.50, 0.04), (0, 0.05, -0.14), M["base"]) + return dict(fis=fis, bolas=bolas, M=M, compuerta=compuerta) + + +def simular(T, obj): + f_suelta = T.rango(BEAT_SUELTA)[0] + f_una = T.rango(BEAT_UNA)[0] + 8 + cfg = { + "congelados": ["bola_000"], + "duracion": PRE + T.n_frames / FPS + 0.2, + "gravedad": GRAV, + "reglas": { + "bola_": {"friccion": 0.10, "rebote": REB, "densidad": 7800, "ccd": True, + "plano": True, "amortiguar": AMORT, "dormir": False}, + "fijo_": {"friccion": 0.10, "rebote": REB}, + "caja_": {"friccion": 0.25, "rebote": 0.20}, + "compuerta_": {"friccion": 0.25, "rebote": 0.0}, + }, + "eventos": [{"t": PRE + (f_una - 1) / FPS, "accion": "soltar", "prefijo": "bola_000"}, + {"t": PRE + (f_suelta - 1) / FPS, "accion": "quitar", "prefijo": "compuerta_"}], + } + correr_godot(exportar_fisica(NOMBRE, obj["fis"], cfg)) + + +# --- trazos para explicar ----------------------------------------------------- +def camino(movs): + """Polilinea de un camino por la grilla: movs = lista de -1/+1.""" + pts = [(0.0, -0.05, Z_SAL - 0.02)] + x = 0.0 + for i, m in enumerate(movs): + pts.append((x, -0.05, Z_FILA[i] + RP + RB)) + x += m * DX / 2 + pts.append((x, -0.05, 0.35)) + return pts + + +def recortar(pts, u): + """Primeros u (0..1) del largo de la polilinea.""" + L = [0.0] + for a, b in zip(pts, pts[1:]): + L.append(L[-1] + math.dist(a, b)) + obj_L = u * L[-1] + out = [pts[0]] + for i in range(1, len(pts)): + if L[i] <= obj_L: + out.append(pts[i]) + else: + a, b = pts[i - 1], pts[i] + s = (obj_L - L[i - 1]) / max(1e-9, L[i] - L[i - 1]) + out.append(tuple(a[k] + (b[k] - a[k]) * s for k in range(3))) + break + while len(out) < len(pts): + out.append(out[-1]) + return out + + +def main(): + T = Tiempo(NOMBRE) + obj = construir() + if os.environ.get("MODO") == "sim": + simular(T, obj) + return + idx, D = cargar_sim(NOMBRE) + pre = int(round(PRE * FPS)) + bolas = obj["bolas"] + ib = [idx[b.name] for b in bolas] + import numpy as np + xs_fin = D[-1, ib, 0] + zs_fin = D[-1, ib, 2] + cas = np.clip(np.round(xs_fin / DX).astype(int) + FILAS // 2, 0, NB - 1) + cuenta = np.bincount(cas, minlength=NB) + print(f"[{NOMBRE}] casilleros: {cuenta.tolist()} (en el tablero: {int((zs_fin < ALTO_CAS).sum())})") + + # la bolita que se destaca: la que cae sola en el beat 1 + i_una = idx["bola_000"] + una = next(b for b in bolas if b.name == "bola_000") + f_sale = int(np.argmax(D[:, i_una, 2] < Z_SAL - 0.05)) - pre + 1 + f_llega = int(np.argmax(D[:, i_una, 2] < 0.6)) - pre + 1 + m_una = material("una", "rosa", rug=0.2, metal=0.3, emis=1.6) + estela = curva_poly("estela", [[(0, 0, 0)] * 24], grosor=0.006, + radios=[[0.0] * 24], mat=material("estela", "rosa", emis=2.5)) + + # caminos: el de la punta (beat 5) y varios al medio (beat 6) + punta = curva_poly("c_punta", [camino([-1] * FILAS)], grosor=0.010, + mat=material("cp", "rosa", emis=3.0)) + rnd = random.Random(3) + medios = [] + for k in range(10): + m = [-1] * 6 + [1] * 6 + rnd.shuffle(m) + medios.append(camino(m)) + c_medios = curva_poly("c_medios", medios, grosor=0.006, + mat=material("cm", "verde", emis=2.6)) + + # campana: normal ajustada a las alturas finales de cada casillero + alturas = [] + for k in range(NB): + sel = zs_fin[cas == k] + alturas.append(float(sel.max() + RB) if len(sel) else 0.0) + mu = float(np.mean(xs_fin[zs_fin < ALTO_CAS])) + sd = float(np.std(xs_fin[zs_fin < ALTO_CAS])) + area = sum(alturas) * DX + xs_c = [(-W2 + 2 * W2 * i / 120) for i in range(121)] + campana_pts = [(x, -0.05, 0.004 + area / (sd * math.sqrt(2 * math.pi)) + * math.exp(-0.5 * ((x - mu) / sd) ** 2)) for x in xs_c] + campana = curva_poly("campana", [campana_pts], grosor=0.012, + mat=material("cc", "ambar", emis=3.2)) + print(f"[{NOMBRE}] mu={mu:.3f} sd={sd:.3f} (= {sd / (DX / 2):.2f} medios pasos; " + f"binomial ideal: {math.sqrt(FILAS) / 2 * 2:.2f})") + + # marco del casillero del medio (beat 10) + m_marco = material("marco_medio", "verde", emis=2.8) + h_med = alturas[NB // 2] + 0.03 + marco = curva_poly("marco_medio", [[(-DX / 2, -0.05, 0.0), (-DX / 2, -0.05, h_med), + (DX / 2, -0.05, h_med), (DX / 2, -0.05, 0.0)]], + grosor=0.008, mat=m_marco) + + # camara: de la tolva al tablero entero + lente = 50.0 + cam = camara((0, -5, 1), (0, 0, 1), lente=lente) + cam.data.sensor_fit = 'VERTICAL' + cam.data.sensor_height = 36.0 + A = (2.10, 2.0) # (z centro, alto visible) + B = (0.60, 3.10) + luz("key", 'AREA', (-1.8, -3.0, 3.2), 520, "blanco", tam=3.0, mira=(0, 0, 1.2)) + luz("fill", 'AREA', (2.4, -2.6, 0.6), 110, "blanco", tam=3.0, mira=(0, 0, 0.8)) + luz("top", 'AREA', (0.0, -0.8, 3.6), 220, "blanco", tam=2.0, mira=(0, 0, 1.5)) + + def actualizar(f): + i = min(f - 1 + pre, len(D) - 1) + for b, j in zip(bolas, ib): + poner_pose(b, D[i, j]) + + # camara + m = suave((f - f_sale) / max(1, f_llega - f_sale + 10)) + zc = mezcla(A[0], B[0], m) + h = mezcla(A[1], B[1], m) + deriva = 0.03 * math.sin(f / 90.0) + dist = h * lente / 36.0 + apuntar(cam, (deriva, -dist, zc + 0.08), (deriva * 0.5, 0, zc)) + + # la bolita destacada + vis = 1.0 if (T.rango(1)[0] <= f <= T.rango(4)[0]) else 0.0 + if vis: + if una.material_slots and una.material_slots[0].link != 'OBJECT': + una.material_slots[0].link = 'OBJECT' + if una.material_slots: + una.material_slots[0].material = m_una + elif una.material_slots: + una.material_slots[0].link = 'DATA' + pts, rad = [], [] + for k in range(24): + q = D[max(0, i - (23 - k)), i_una] + pts.append((q[0], -0.03, q[2])) + rad.append(vis * (k / 23.0) ** 1.5) + rehacer_curva(estela, [pts], [rad]) + + # caminos + up = suave(T.p(f, 5) / 0.7) * (1.0 - suave((T.p(f, 7) - 0.0) / 0.2)) + rehacer_curva(punta, [recortar(camino([-1] * FILAS), up)]) + punta.scale = (1, 1, 1) if 0 < up else (0, 0, 0) + cm = [] + for k, c in enumerate(medios): + u = suave((T.p(f, 6) - k * 0.06) / 0.35) + cm.append(recortar(c, u)) + rehacer_curva(c_medios, cm) + fuera = 1.0 - suave(T.p(f, 7) / 0.2) + c_medios.scale = (1, 1, 1) if (T.p(f, 6) > 0 and fuera > 0.01) else (0, 0, 0) + + # campana + uc = suave(T.p(f, 7) / 0.6) + rehacer_curva(campana, [recortar(campana_pts, uc)]) + campana.scale = (1, 1, 1) if uc > 0 else (0, 0, 0) + + marco.scale = (1, 1, 1) if T.p(f, 10) > 0.02 else (0, 0, 0) + + render_secuencia(NOMBRE, T, actualizar) + + +main() diff --git a/brand/README.md b/brand/README.md new file mode 100644 index 0000000..498efca --- /dev/null +++ b/brand/README.md @@ -0,0 +1,50 @@ +# Marca 100cIA + +El nombre se lee **"ciencia"** (100 = cien, + c + IA) y a la vez deja a la vista +que los videos los hace una IA. El logo apoya las dos lecturas: `100c` en blanco y el `IA` dentro de un chip ámbar +—el mismo recurso que usan los videos—, con un pelín de aire entre medio para que la I +no se lea como barra. + +## Archivos + +| Archivo | Para qué | +|---|---| +| `avatar.svg` / `avatar-1024.png` | **foto de perfil** | +| `avatar-plano.svg` / `avatar-plano-1024.png` | alternativa sin chip | +| `wordmark.svg` / `wordmark-2400.png` | logotipo sobre fondo oscuro | +| `wordmark-claro.svg` | logotipo sobre fondo claro | +| `wordmark-mono.svg` | una sola tinta con el `IA` calado — marca de agua sobre video | +| `wordmark-plano.svg` | logotipo sin chip | +| `banner.svg` / `banner-1920.png` | placa de cierre del video y miniatura | + +El chip alrededor del `IA` es la marca y va en todas las piezas. La versión mono +usa una máscara: el chip es de un solo color y las letras quedan caladas, así que +funciona encima de cualquier fondo. + +**TikTok e Instagram no aceptan SVG para la foto de perfil**: subí los `.png`. +Los `.svg` son para imprimir, escalar o editar. + +## Paleta (la misma de los videos) + +| | | +|---|---| +| fondo | `#0B0F1A` | +| puntitos | `#243050` | +| texto | `#FFFFFF` | +| ámbar (IA, barra de progreso) | `#FFD166` | +| ámbar oscuro (sobre fondo claro) | `#D98C00` | +| track de la barra | `#1B2233` | +| verde | `#06D6A0` · rosa `#EF476F` · celeste `#4CC9F0` | + +Tipografía: **Roboto Black**, tracking −3,5 %. En los SVG el texto ya está +convertido a curvas, así que se ven igual en cualquier máquina. + +El anillo del avatar es la barra de progreso de los videos, curvada: mismo ámbar, +misma proporción (62 %). Es lo que hace reconocible la miniatura a 44 px, donde +el texto ya no se lee. + +## Regenerar + +```bash +python3 brand/make_logo.py # necesita Inkscape y Roboto Black instalados +``` diff --git a/brand/avatar-1024.png b/brand/avatar-1024.png new file mode 100644 index 0000000..997cae4 Binary files /dev/null and b/brand/avatar-1024.png differ diff --git a/brand/avatar-plano-1024.png b/brand/avatar-plano-1024.png new file mode 100644 index 0000000..b68b861 Binary files /dev/null and b/brand/avatar-plano-1024.png differ diff --git a/brand/avatar-plano.svg b/brand/avatar-plano.svg new file mode 100644 index 0000000..e8c778b --- /dev/null +++ b/brand/avatar-plano.svg @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/brand/avatar.svg b/brand/avatar.svg new file mode 100644 index 0000000..0b5783a --- /dev/null +++ b/brand/avatar.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/brand/banner-1920.png b/brand/banner-1920.png new file mode 100644 index 0000000..cc270b0 Binary files /dev/null and b/brand/banner-1920.png differ diff --git a/brand/banner.svg b/brand/banner.svg new file mode 100644 index 0000000..06c35ae --- /dev/null +++ b/brand/banner.svg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/brand/make_logo.py b/brand/make_logo.py new file mode 100644 index 0000000..dac08b5 --- /dev/null +++ b/brand/make_logo.py @@ -0,0 +1,235 @@ +# -*- coding: utf-8 -*- +"""Genera el kit de marca de 100cIA. El texto se convierte a curvas con Inkscape, +asi que los SVG no dependen de que la fuente este instalada.""" +import os, re, subprocess, tempfile +import xml.etree.ElementTree as ET + +HERE = os.path.dirname(os.path.abspath(__file__)) + +BG = "#0B0F1A" +PUNTOS = "#243050" +BLANCO = "#FFFFFF" +AMBAR = "#FFD166" +TRACK = "#1B2233" +GRIS = "#8D99AE" + +FUENTE = "Roboto Black" +TRACKING = -0.035 # em + + +def curvas(partes, size=400, tracking=TRACKING): + """partes = [(texto, color), ...] -> (svg_interno, x, y, w, h) ya en curvas.""" + tspans = "".join( + f'{t}' + for i, (t, c) in enumerate(partes)) + src = (f'{tspans}') + with tempfile.TemporaryDirectory() as d: + a, b = os.path.join(d, "a.svg"), os.path.join(d, "b.svg") + open(a, "w", encoding="utf-8").write(src) + subprocess.run(["inkscape", "--export-text-to-path", "--export-plain-svg", + f"--export-filename={b}", a], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True) + raw = open(b, encoding="utf-8").read() + q = {k: float(subprocess.run(["inkscape", "--query-id=w", f"--query-{k}", b], + capture_output=True, text=True).stdout.strip()) + for k in ("x", "y", "width", "height")} + + NS = "http://www.w3.org/2000/svg" + ET.register_namespace("", NS) + root = ET.fromstring(raw) + nodo = next(e for e in root.iter() if e.get("id") == "w") + for e in nodo.iter(): + e.attrib.pop("id", None) + e.attrib.pop("aria-label", None) + cuerpo = ET.tostring(nodo, encoding="unicode") + cuerpo = cuerpo.replace(f' xmlns="{NS}"', "") + if not cuerpo.lstrip().startswith("{cuerpo}" + return cuerpo, q["x"], q["y"], q["width"], q["height"] + + +def colocar(g, bx, by, bw, bh, cx, cy, ancho): + s = ancho / bw + tx = cx - s * (bx + bw / 2) + ty = cy - s * (by + bh / 2) + return f'{g}' + + +def puntos(id_, sep=118, r=4.2, color=PUNTOS, op=0.55): + return (f'' + f'') + + +def arco(cx, cy, r, desde, hasta, color, w): + """Arco en grados, 0 = arriba, sentido horario.""" + import math + def p(a): + t = math.radians(a - 90) + return cx + r * math.cos(t), cy + r * math.sin(t) + x0, y0 = p(desde) + x1, y1 = p(hasta) + largo = 1 if (hasta - desde) % 360 > 180 else 0 + return (f'') + + +# ---------------------------------------------------------------- avatar +def avatar(archivo, chip=False, pct=0.62): + D = 1024 + R = D / 2 + anillo_r, anillo_w = R - 26, 20 + if chip: + g1, x1, y1, w1, h1 = curvas([("100c", BLANCO)]) + g2, x2, y2, w2, h2 = curvas([("IA", "#0B0F1A")]) + else: + g1, x1, y1, w1, h1 = curvas([("100c", BLANCO), ("IA", AMBAR)]) + + cuerpo = [ + f'', + f'', + f'', + arco(R, R, anillo_r, 0, 360 * pct, AMBAR, anillo_w), + ] + if chip: + ancho_total = 760 + # el chip de "IA" ocupa ~38% del ancho, como los chips de los videos + w_txt = ancho_total * 0.60 + cuerpo.append(colocar(g1, x1, y1, w1, h1, R - ancho_total / 2 + w_txt / 2, R, w_txt)) + esc = w_txt / w1 + cw, ch = w2 * esc * 1.0 + 70, h1 * esc + 62 + cxc = R - ancho_total / 2 + w_txt + 26 + cw / 2 + cuerpo.append(f'') + cuerpo.append(colocar(g2, x2, y2, w2, h2, cxc, R, w2 * esc)) + else: + cuerpo.append(colocar(g1, x1, y1, w1, h1, R, R, 740)) + + svg = (f'{puntos("dots")}' + + "".join(cuerpo) + '') + open(os.path.join(HERE, archivo), "w", encoding="utf-8").write(svg) + return archivo + + +# ---------------------------------------------------------------- logotipo +# El chip alrededor del "IA" es la marca: va en todas las variantes menos en la +# "plana", que queda como alternativa. +MODOS = { + # tinta fondo del chip letra del chip + "oscuro": (BLANCO, AMBAR, "#0B0F1A"), + "claro": ("#0B0F1A", "#D98C00", "#FFFFFF"), + "mono": (BLANCO, BLANCO, None), # letras caladas +} + + +def _lockup(modo, alto=520): + """Devuelve (piezas_svg, ancho, alto) del lockup '100c' + chip 'IA'.""" + tinta, fondo_chip, letra = MODOS[modo] + g1, x1, y1, w1, h1 = curvas([("100c", tinta)]) + g2, x2, y2, w2, h2 = curvas([("IA", letra or "#000000")]) + + esc = alto / h1 + wt = w1 * esc + cw = w2 * esc + 0.68 * alto + ch = alto + 0.60 * alto + hueco = 0.13 * alto + W = wt + hueco + cw + cy = ch / 2 + rx = ch * 0.28 + cx_chip = wt + hueco + cw / 2 + chip_x = wt + hueco + + piezas = [colocar(g1, x1, y1, w1, h1, wt / 2, cy, wt)] + if letra is None: # una sola tinta: el IA se cala + mascara = (f'' + f'' + + colocar(g2, x2, y2, w2, h2, cx_chip, cy, w2 * esc) + + '') + piezas.append(f'{mascara}') + piezas.append(f'') + else: + piezas.append(f'') + piezas.append(colocar(g2, x2, y2, w2, h2, cx_chip, cy, w2 * esc)) + return piezas, W, ch + + +def wordmark(archivo, modo="oscuro", margen=0.10): + piezas, W0, H0 = _lockup(modo) + m = margen * H0 + W, H = int(round(W0 + 2 * m)), int(round(H0 + 2 * m)) + svg = (f'' + + "".join(piezas) + '') + open(os.path.join(HERE, archivo), "w", encoding="utf-8").write(svg) + return archivo + + +def wordmark_plano(archivo): + """Alternativa sin chip: '100cIA' de corrido, el IA en ambar.""" + g, x, y, w, h = curvas([("100c", BLANCO), ("IA", AMBAR)]) + W = 2400 + ancho = W * 0.88 + H = int(round(h / w * ancho + 2 * 0.06 * W)) + svg = (f'' + + colocar(g, x, y, w, h, W / 2, H / 2, ancho) + '') + open(os.path.join(HERE, archivo), "w", encoding="utf-8").write(svg) + return archivo + + +# ---------------------------------------------------------------- banner +def banner(archivo, tagline="ciencia en 40 segundos"): + W, H = 1920, 1080 + g, x, y, w, h = curvas([("100c", BLANCO)]) + t, tx, ty, tw, th = curvas([(tagline, "#C9D3E5")], size=200, tracking=0.012) + cuerpo = [ + f'', + f'', + f'', + f'', + None, # el lockup se arma abajo (con chip, igual que el avatar) + colocar(t, tx, ty, tw, th, W / 2, H / 2 + 205, 830), + ] + # lockup con chip, centrado, a 1150 px de ancho total + g2, x2, y2, w2, h2 = curvas([("IA", "#0B0F1A")]) + ANCHO, cy = 1150, H / 2 - 95 + alto = 210 + esc = alto / h + wt = w * esc + cw, ch = w2 * esc + 0.68 * alto, alto + 0.60 * alto + hueco = 0.13 * alto + total = wt + hueco + cw + k = ANCHO / total + wt, cw, ch, hueco = wt * k, cw * k, ch * k, hueco * k + izq = W / 2 - ANCHO / 2 + cuerpo[cuerpo.index(None)] = ( + colocar(g, x, y, w, h, izq + wt / 2, cy, wt) + + f'' + + colocar(g2, x2, y2, w2, h2, izq + wt + hueco + cw / 2, cy, w2 * esc * k)) + + svg = (f'{puntos("dots", sep=140, r=5)}' + + "".join(cuerpo) + '') + open(os.path.join(HERE, archivo), "w", encoding="utf-8").write(svg) + return archivo + + +if __name__ == "__main__": + # la variante con chip es la marca: se queda con los nombres principales + for f in (avatar("avatar.svg", chip=True), avatar("avatar-plano.svg"), + wordmark("wordmark.svg", "oscuro"), + wordmark("wordmark-claro.svg", "claro"), + wordmark("wordmark-mono.svg", "mono"), + wordmark_plano("wordmark-plano.svg"), + banner("banner.svg")): + print(" ->", f) diff --git a/brand/wordmark-2400.png b/brand/wordmark-2400.png new file mode 100644 index 0000000..3bf76d5 Binary files /dev/null and b/brand/wordmark-2400.png differ diff --git a/brand/wordmark-claro.svg b/brand/wordmark-claro.svg new file mode 100644 index 0000000..01331b9 --- /dev/null +++ b/brand/wordmark-claro.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/brand/wordmark-mono.svg b/brand/wordmark-mono.svg new file mode 100644 index 0000000..94f1ea3 --- /dev/null +++ b/brand/wordmark-mono.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/brand/wordmark-plano.svg b/brand/wordmark-plano.svg new file mode 100644 index 0000000..a2bb29b --- /dev/null +++ b/brand/wordmark-plano.svg @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/brand/wordmark.svg b/brand/wordmark.svg new file mode 100644 index 0000000..beb5ff8 --- /dev/null +++ b/brand/wordmark.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/godot/project.godot b/godot/project.godot new file mode 100644 index 0000000..c45c053 --- /dev/null +++ b/godot/project.godot @@ -0,0 +1,13 @@ +; Simulador de fisica del canal: carga un .glb disenado en Blender, arma los +; cuerpos rigidos segun el prefijo de cada objeto y graba las trayectorias. +config_version=5 + +[application] +config/name="fisica-videos" +run/main_scene="res://sim.tscn" + +[physics] +3d/physics_engine="Jolt Physics" +common/physics_ticks_per_second=240 +common/max_physics_steps_per_frame=1 +common/physics_jitter_fix=0.0 diff --git a/godot/sim.gd b/godot/sim.gd new file mode 100644 index 0000000..7e860dc --- /dev/null +++ b/godot/sim.gd @@ -0,0 +1,223 @@ +extends Node3D +## Simulador generico: Blender disena, Godot (Jolt) hace la fisica. +## +## godot --headless --path godot --fixed-fps 240 -- +## +## El .glb exportado por Blender se carga en tiempo de ejecucion y cada objeto +## se convierte en cuerpo segun el prefijo de su nombre: +## fijo_* estatico, malla exacta (ConcavePolygonShape3D) +## caja_* estatico, caja con el tamano de la malla +## compuerta_* estatico, caja que un evento "quitar" saca del mundo +## bola_* rigido, esfera +## bloque_* rigido, caja +## Las trayectorias se graban a 30 fps en coordenadas de Blender (Z arriba), +## asi el script de render las usa sin convertir nada. + +var hz := 240 # pasos de fisica por segundo +var pasos_por_frame := 8 # hz / 30 fps de video + +var cfg: Dictionary +var dinamicos: Array[RigidBody3D] = [] +var removibles := {} # nombre -> CollisionObject3D +var tick := 0 +var frames: Array = [] +var eventos: Array = [] +var esc := 1.0 # el mundo se simula esc veces mas grande + + +func _ready() -> void: + var args := OS.get_cmdline_user_args() + if args.is_empty(): + push_error("falta el config.json") + get_tree().quit(1) + return + cfg = JSON.parse_string(FileAccess.get_file_as_string(args[0])) + # Jolt tiene tolerancias en metros (penetracion admitida 2 cm): con piezas + # chicas conviene simular a mayor escala. Gravedad y posiciones se escalan + # igual, asi la dinamica es la misma y la salida vuelve a la escala original. + esc = float(cfg.get("escala", 1.0)) + # mas pasos por segundo = contactos mas rigidos (pilas altas); el proceso + # corre con --fixed-fps 240, asi que cada frame hace hz/240 pasos + hz = int(cfg.get("hz", 240)) + # fps de grabacion: 30 para tiempo real, mas para camara lenta + pasos_por_frame = hz / int(cfg.get("fps", 30)) + Engine.physics_ticks_per_second = hz + Engine.max_physics_steps_per_frame = maxi(1, hz / 240) + PhysicsServer3D.area_set_param(get_world_3d().space, PhysicsServer3D.AREA_PARAM_GRAVITY, + float(cfg.get("gravedad", 9.81)) * esc) + eventos = cfg.get("eventos", []) + eventos.sort_custom(func(a, b): return a["t"] < b["t"]) + + var doc := GLTFDocument.new() + var st := GLTFState.new() + if doc.append_from_file(cfg["glb"], st) != OK: + push_error("no pude leer " + cfg["glb"]) + get_tree().quit(1) + return + var raiz := doc.generate_scene(st) + add_child(raiz) + var mallas: Array[MeshInstance3D] = [] + _juntar(raiz, mallas) + for mi in mallas: + _crear_cuerpo(mi) + raiz.queue_free() + print("[sim] %d dinamicos, %d mallas, g=%.2f" % [dinamicos.size(), mallas.size(), + float(cfg.get("gravedad", 9.81))]) + _grabar() + + +func _juntar(n: Node, out: Array[MeshInstance3D]) -> void: + if n is MeshInstance3D: + out.append(n) + for c in n.get_children(): + _juntar(c, out) + + +func _regla(nombre: String) -> Dictionary: + var r: Dictionary = {} + var largo := -1 + for pre in cfg.get("reglas", {}): + if nombre.begins_with(pre) and pre.length() > largo: + r = cfg["reglas"][pre] + largo = pre.length() + return r + + +func _crear_cuerpo(mi: MeshInstance3D) -> void: + var nombre := String(mi.name) + var aabb := mi.get_aabb() + aabb = AABB(aabb.position * esc, aabb.size * esc) + var r := _regla(nombre) + var mat := PhysicsMaterial.new() + mat.friction = float(r.get("friccion", 0.5)) + mat.bounce = float(r.get("rebote", 0.0)) + var cuerpo: CollisionObject3D + var forma := CollisionShape3D.new() + + if nombre.begins_with("fijo_"): + cuerpo = StaticBody3D.new() + var tri := ConcavePolygonShape3D.new() + var caras := mi.mesh.get_faces() + for n in caras.size(): + caras[n] *= esc + tri.set_faces(caras) + forma.shape = tri + elif nombre.begins_with("caja_") or nombre.begins_with("compuerta_"): + cuerpo = StaticBody3D.new() + var b := BoxShape3D.new() + b.size = aabb.size + forma.shape = b + forma.position = aabb.get_center() + elif nombre.begins_with("bola_") or nombre.begins_with("bloque_"): + var rb := RigidBody3D.new() + var vol: float + if nombre.begins_with("bola_"): + var s := SphereShape3D.new() + s.radius = aabb.size.x * 0.5 + forma.shape = s + vol = 4.0 / 3.0 * PI * pow(s.radius, 3) + else: + var b := BoxShape3D.new() + b.size = aabb.size + forma.shape = b + vol = aabb.size.x * aabb.size.y * aabb.size.z + forma.position = aabb.get_center() + rb.mass = vol * float(r.get("densidad", 1000.0)) + rb.continuous_cd = bool(r.get("ccd", false)) + rb.can_sleep = bool(r.get("dormir", true)) + rb.linear_damp = float(r.get("amortiguar", 0.0)) + rb.angular_damp = float(r.get("amortiguar_giro", 0.0)) + if r.get("plano", false): + # movimiento en el plano del tablero (Blender XZ = Godot XY) + rb.axis_lock_linear_z = true + rb.axis_lock_angular_x = true + rb.axis_lock_angular_y = true + for pre in cfg.get("congelados", []): + if nombre.begins_with(pre): + rb.freeze = true + rb.freeze_mode = RigidBody3D.FREEZE_MODE_KINEMATIC + cuerpo = rb + dinamicos.append(rb) + else: + return + + cuerpo.name = nombre + if cuerpo is StaticBody3D: + cuerpo.physics_material_override = mat + else: + (cuerpo as RigidBody3D).physics_material_override = mat + cuerpo.add_child(forma) + add_child(cuerpo) + var tr := mi.global_transform + tr.origin *= esc + cuerpo.global_transform = tr + removibles[nombre] = cuerpo + + +func _physics_process(_delta: float) -> void: + tick += 1 + var t := tick / float(hz) + while not eventos.is_empty() and eventos[0]["t"] <= t: + _aplicar(eventos.pop_front()) + if tick % pasos_por_frame == 0: + _grabar() + if t >= float(cfg["duracion"]): + _guardar() + get_tree().quit() + + +func _aplicar(ev: Dictionary) -> void: + var pre: String = ev["prefijo"] + var n := 0 + for nombre in removibles.keys(): + if not String(nombre).begins_with(pre): + continue + var c: CollisionObject3D = removibles[nombre] + if not is_instance_valid(c): + continue + n += 1 + match ev["accion"]: + "quitar": + c.queue_free() + "soltar": + var rb := c as RigidBody3D + rb.freeze = false + rb.sleeping = false + if ev.has("velocidad"): + var v: Array = ev["velocidad"] # en coordenadas de Blender + rb.linear_velocity = Vector3(v[0], v[2], -v[1]) * esc + if ev.has("giro"): + var w: Array = ev["giro"] # rad/s, ejes de Blender + rb.angular_velocity = Vector3(w[0], w[2], -w[1]) + # un cuerpo dormido no se entera de que le sacaron el apoyo: se despiertan todos + for rb in dinamicos: + if not rb.freeze: + rb.sleeping = false + print("[sim] t=%.2f %s %s (%d)" % [tick / float(hz), ev["accion"], pre, n]) + + +func _grabar() -> void: + var fila := PackedFloat32Array() + for rb in dinamicos: + var p := rb.global_position / esc + var q := rb.global_transform.basis.get_rotation_quaternion() + # Godot (Y arriba) -> Blender (Z arriba): (x, y, z) -> (x, -z, y) + fila.append_array([p.x, -p.z, p.y, q.w, q.x, -q.z, q.y]) + frames.append(fila) + + +func _guardar() -> void: + # binario: cabecera JSON en un archivo aparte + float32 crudos + var sal: String = cfg["salida"] + var nombres := [] + for rb in dinamicos: + nombres.append(String(rb.name)) + var f := FileAccess.open(sal + ".cab.json", FileAccess.WRITE) + f.store_string(JSON.stringify({"nombres": nombres, "frames": frames.size(), + "fps": int(cfg.get("fps", 30)), "campos": ["x", "y", "z", "qw", "qx", "qy", "qz"]})) + f.close() + var b := FileAccess.open(sal + ".bin", FileAccess.WRITE) + for fila in frames: + b.store_buffer(fila.to_byte_array()) + b.close() + print("[sim] %d frames -> %s.bin" % [frames.size(), sal]) diff --git a/godot/sim.tscn b/godot/sim.tscn new file mode 100644 index 0000000..3973f97 --- /dev/null +++ b/godot/sim.tscn @@ -0,0 +1,6 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://sim.gd" id="1"] + +[node name="Sim" type="Node3D"] +script = ExtResource("1") diff --git a/scenes/overlay.py b/scenes/overlay.py new file mode 100644 index 0000000..0a3eb71 --- /dev/null +++ b/scenes/overlay.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +"""Capa de interfaz del canal (chip, barra de progreso y subtitulos) para los +videos renderizados en Blender. Se renderiza con --transparent y se compone +encima del 3D, asi el estilo sale del mismo codigo que los videos de Manim. + + NAME=bolapeluda CHIP=Topología CHIPCOL=celeste manim --transparent ... + +Tambien escribe out/_timeline.json, que es lo que despues leen el script +de Blender (para animar) y build_video.py (para colocar el audio). +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +COLORES = {"ambar": AMBAR, "verde": VERDE, "rosa": ROSA, "celeste": CELESTE} + + +class Overlay(TikTok): + NAME = os.environ.get("NAME", "") + + def backdrop(self): + return VGroup() # el fondo punteado va aparte, debajo del 3D + + def construct(self): + self.prepare() + chip = self.chip(os.environ.get("CHIP", ""), + COLORES[os.environ.get("CHIPCOL", "ambar")]) + self.add(chip) + for i in range(len(self.segs)): + with self.beat(i) as b: + b.wait(b.floor) + self.finish() + + +class Fondo(TikTok): + """Un solo frame con la trama de puntos, para usar de fondo.""" + NAME = "fondo" + + def construct(self): + self._sub = None + TikTok.backdrop(self) + self.wait(0.1) diff --git a/scenes/tiktok.py b/scenes/tiktok.py new file mode 100644 index 0000000..7e2ad2d --- /dev/null +++ b/scenes/tiktok.py @@ -0,0 +1,156 @@ +# -*- coding: utf-8 -*- +"""Base comun para los videos verticales: formato 9:16, subtitulos, +barra de progreso y un sistema de 'beats' sincronizados con el audio.""" +import json, os +from contextlib import contextmanager +from manim import * + +# --- formato TikTok 1080x1920 ------------------------------------------------- +if os.environ.get("DRAFT"): + config.pixel_width, config.pixel_height = 540, 960 +else: + config.pixel_width, config.pixel_height = 1080, 1920 +config.frame_width = 9.0 +config.frame_height = 16.0 +config.frame_rate = 30 +config.background_color = "#0B0F1A" + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +FONT = "Roboto" +AMBAR = "#FFD166" +VERDE = "#06D6A0" +ROSA = "#EF476F" +CELESTE = "#4CC9F0" +GRIS = "#8D99AE" + +GAP = 0.30 # silencio entre segmentos +SUB_Y = -4.25 # los subtitulos van arriba de la UI de TikTok +TOP_Y = 6.45 + + +class _Beat: + """Acumula el tiempo usado dentro de un segmento para poder rellenar el resto.""" + def __init__(self, scene, floor): + self.s, self.floor, self.used = scene, floor, 0.0 + + def play(self, *anims, run_time=1.0, **kw): + self.s.play(*anims, run_time=run_time, **kw) + self.used += run_time + + def wait(self, t): + if t > 0.02: + self.s.wait(t) + self.used += t + + def add(self, *m): + self.s.add(*m) + + def remove(self, *m): + self.s.remove(*m) + + def close(self): + rest = self.floor - self.used + if rest > 0.02: + self.s.wait(rest) + self.used += rest + if GAP > 0.02: + self.s.wait(GAP) + self.used += GAP + return self.used + + +class TikTok(Scene): + NAME = "" + + # -- infraestructura ------------------------------------------------------ + def prepare(self): + with open(os.path.join(ROOT, "audio", self.NAME, "segments.json"), encoding="utf-8") as f: + self.data = json.load(f) + self.segs = self.data["segments"] + self.timeline, self.clock = [], 0.0 + self._sub = None + self._expected = sum(s["dur"] + GAP for s in self.segs) + self.backdrop() + self._progress_bar() + + def backdrop(self): + dots = VGroup(*[ + Dot(radius=0.035, color="#243050", fill_opacity=0.55).move_to([x, y, 0]) + for x in np.arange(-4.2, 4.3, 1.05) + for y in np.arange(-7.5, 7.6, 1.05) + ]) + self.add(dots) + return dots + + def _progress_bar(self): + w = config.frame_width + track = Rectangle(width=w, height=0.075, stroke_width=0, + fill_color="#1B2233", fill_opacity=1).move_to(UP * (TOP_Y + 1.15)) + bar = Rectangle(width=0.002, height=0.075, stroke_width=0, + fill_color=AMBAR, fill_opacity=1).move_to(track.get_left(), LEFT) + self.elapsed = 0.0 + total, left, y = self._expected, -w / 2, track.get_y() + + def upd(m, dt): + self.elapsed += dt + frac = min(self.elapsed / total, 1.0) + nw = max(frac * w, 0.002) + m.stretch_to_fit_width(nw) + m.move_to([left + nw / 2, y, 0]) + + bar.add_updater(upd) + self.add(track, bar) + + def subtitle(self, text): + """Cambia el subtitulo sin consumir tiempo de animacion.""" + if self._sub: + self.remove(self._sub) + t = Text(text, font=FONT, font_size=44, weight=BOLD, color=WHITE, + line_spacing=0.8).move_to(UP * SUB_Y) + if t.width > 8.0: + t.scale(8.0 / t.width) + box = RoundedRectangle(corner_radius=0.18, stroke_width=0, + fill_color="#000000", fill_opacity=0.55, + width=t.width + 0.55, height=t.height + 0.42).move_to(t) + self._sub = VGroup(box, t) + self.add(self._sub) + + @contextmanager + def beat(self, i, sub=True): + """Bloque sincronizado con el segmento i de audio.""" + if sub: + self.subtitle(self.segs[i]["sub"]) + b = _Beat(self, self.segs[i]["dur"]) + yield b + used = b.close() + self.timeline.append({"i": i, "start": round(self.clock, 3), + "dur": round(used, 3), "audio": self.segs[i]["dur"]}) + self.clock += used + + def finish(self): + if self._sub: + self.play(FadeOut(self._sub), run_time=0.4) + self.clock += 0.4 + self.wait(0.5) + self.clock += 0.5 + os.makedirs(os.path.join(ROOT, "out"), exist_ok=True) + with open(os.path.join(ROOT, "out", f"{self.NAME}_timeline.json"), "w") as f: + json.dump({"name": self.NAME, "gap": GAP, "total": round(self.clock, 3), + "beats": self.timeline}, f, indent=2) + + # -- helpers visuales ----------------------------------------------------- + def chip(self, text, color=AMBAR): + t = Text(text, font=FONT, font_size=34, weight=BOLD, color="#0B0F1A") + box = RoundedRectangle(corner_radius=0.3, stroke_width=0, fill_color=color, + fill_opacity=1, width=t.width + 0.7, height=t.height + 0.45) + g = VGroup(box, t).move_to(UP * TOP_Y) + return g + + def fit(self, m, w=8.3): + if m.width > w: + m.scale(w / m.width) + return m + + def big(self, text, size=76, color=WHITE): + return Text(text, font=FONT, font_size=size, weight=BOLD, color=color) diff --git a/scenes/v10_buffon.py b/scenes/v10_buffon.py new file mode 100644 index 0000000..35ee4e0 --- /dev/null +++ b/scenes/v10_buffon.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +import sys, os, math +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +D = 1.1 # separacion entre rayas = largo de la aguja +Y0 = 0.35 # raya mas baja +NLIN = 5 +SEED, N1, N2 = 36, 60, 200 + + +def tirar(n): + rng = np.random.default_rng(SEED) + x = rng.uniform(-3.9, 3.9, n) + y = rng.uniform(Y0 + 0.1, Y0 + (NLIN - 1) * D - 0.1, n) + th = rng.uniform(0, PI, n) + dx, dy = D / 2 * np.cos(th), D / 2 * np.sin(th) + p1 = np.stack([x - dx, y - dy, np.zeros(n)], axis=1) + p2 = np.stack([x + dx, y + dy, np.zeros(n)], axis=1) + cruza = np.floor((p1[:, 1] - Y0) / D) != np.floor((p2[:, 1] - Y0) / D) + return p1, p2, cruza + + +class Buffon(TikTok): + NAME = "buffon" + + def construct(self): + self.prepare() + chip = self.chip("π sin círculos", ROSA) + p1, p2, cruza = tirar(N2) + + rayas = VGroup(*[Line([-4.2, Y0 + k * D, 0], [4.2, Y0 + k * D, 0], + stroke_width=4, color="#33405C") for k in range(NLIN)]) + + with self.beat(0) as b: + hook = VGroup( + self.fit(Text("tiro agujas al piso", font=FONT, font_size=52, + weight=BOLD, color=WHITE), 8.2), + self.fit(Text("y sale π", font=FONT, font_size=64, + weight=BOLD, color=AMBAR), 8.2), + ).arrange(DOWN, buff=0.32).move_to(UP * 2.4) + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.45) + b.play(FadeIn(hook[0], shift=UP * 0.15), run_time=0.6) + b.play(Write(hook[1]), run_time=0.8) + + with self.beat(1) as b: + b.play(FadeOut(hook), run_time=0.35) + b.play(LaggedStart(*[Create(r) for r in rayas], lag_ratio=0.12), run_time=0.9) + demo = Line([-1.0, Y0 + D, 0], [-1.0, Y0 + 2 * D, 0], + stroke_width=9, color=AMBAR) + med = DoubleArrow([0.2, Y0 + D, 0], [0.2, Y0 + 2 * D, 0], buff=0, + color=VERDE, stroke_width=6, tip_length=0.2) + lab = Text("mismo largo", font=FONT, font_size=32, weight=BOLD, color=VERDE) + lab.next_to(med, RIGHT, buff=0.25) + b.play(Create(demo), run_time=0.5) + b.play(GrowArrow(med), FadeIn(lab), run_time=0.6) + + agujas = VGroup(*[Line(p1[i], p2[i], stroke_width=4.5, color="#7C8AA8") + for i in range(N2)]) + + with self.beat(2) as b: + b.play(FadeOut(VGroup(demo, med, lab)), run_time=0.3) + b.play(LaggedStart(*[FadeIn(agujas[i]) for i in range(N1)], + lag_ratio=0.012), run_time=max(1.1, b.floor - 0.5)) + + with self.beat(3) as b: + hit = [agujas[i] for i in range(N1) if cruza[i]] + miss = [agujas[i] for i in range(N1) if not cruza[i]] + b.play(*[a.animate.set_stroke(AMBAR, 6) for a in hit], + *[a.animate.set_stroke("#46526E", 3.5) for a in miss], run_time=1.0) + + c1 = int(cruza[:N1].sum()) + + def marcador(n, c, y=-0.75): + g = VGroup( + VGroup(Text("tiradas", font=FONT, font_size=30, color=GRIS), + Text(str(n), font=FONT, font_size=62, weight=BOLD, color=WHITE) + ).arrange(DOWN, buff=0.1), + VGroup(Text("cruzan", font=FONT, font_size=30, color=GRIS), + Text(str(c), font=FONT, font_size=62, weight=BOLD, color=AMBAR) + ).arrange(DOWN, buff=0.1), + ).arrange(RIGHT, buff=1.5).move_to([0, y, 0]) + return g + + marc = marcador(N1, c1) + with self.beat(4) as b: + b.play(FadeIn(marc, shift=UP * 0.15), run_time=0.8) + + with self.beat(5) as b: + f = MathTex(r"\frac{2 \times \text{tiradas}}{\text{cruces}}", + color=CELESTE).scale(1.25).move_to(DOWN * 2.45) + b.play(Write(f), run_time=1.1) + + with self.beat(6) as b: + est = 2 * N1 / c1 + res = MathTex(r"= %s" % f"{est:.4f}".replace(".", "{,}"), + color=VERDE).scale(1.45) + res.next_to(f, RIGHT, buff=0.4) + grp = VGroup(f, res) + b.play(Write(res), run_time=0.8) + b.play(grp.animate.move_to(DOWN * 2.45), run_time=0.4) + b.play(Flash(res, color=VERDE, line_length=0.5, num_lines=16, + flash_radius=1.4), run_time=0.6) + + c2 = int(cruza.sum()) + with self.beat(7) as b: + hit = [agujas[i] for i in range(N1, N2) if cruza[i]] + miss = [agujas[i] for i in range(N1, N2) if not cruza[i]] + for a in hit: + a.set_stroke(AMBAR, 6) + for a in miss: + a.set_stroke("#46526E", 3.5) + b.play(LaggedStart(*[FadeIn(agujas[i]) for i in range(N1, N2)], + lag_ratio=0.004), run_time=max(1.0, b.floor - 1.3)) + est2 = 2 * N2 / c2 + nm = marcador(N2, c2) + nres = MathTex(r"= %s" % f"{est2:.4f}".replace(".", "{,}"), + color=VERDE).scale(1.45).next_to(f, RIGHT, buff=0.4) + b.play(Transform(marc, nm), Transform(res, nres), run_time=0.9) + + with self.beat(8) as b: + pi = MathTex(r"\pi = 3{,}14159\ldots", color=AMBAR).scale(1.5) + pi.move_to(UP * 5.5) + b.play(Write(pi), run_time=1.0) + b.play(Circumscribe(pi, color=AMBAR, buff=0.25, stroke_width=6), run_time=0.8) + + with self.beat(9) as b: + b.play(FadeOut(VGroup(marc, pi, f, res)), run_time=0.45) + t = VGroup( + self.fit(Text("no hay ningún círculo", font=FONT, font_size=48, + weight=BOLD, color=WHITE), 8.2), + self.fit(Text("y π aparece igual", font=FONT, font_size=48, + weight=BOLD, color=AMBAR), 8.2), + ).arrange(DOWN, buff=0.35).move_to(DOWN * 1.5) + b.play(FadeIn(t[0], shift=UP * 0.15), run_time=0.6) + b.play(FadeIn(t[1], shift=UP * 0.15), run_time=0.7) + + with self.beat(10) as b: + b.play(FadeOut(t), run_time=0.35) + cta = VGroup( + self.fit(Text("aguja de Buffon", font=FONT, font_size=58, + weight=BOLD, color=AMBAR), 8.0), + self.fit(Text("hacelo con fósforos", font=FONT, font_size=44, + weight=BOLD, color=WHITE), 8.0), + ).arrange(DOWN, buff=0.35).move_to(DOWN * 1.5) + b.play(Write(cta[0]), run_time=0.8) + b.play(FadeIn(cta[1], shift=UP * 0.15), run_time=0.6) + + self.finish() diff --git a/scenes/v11_collatz.py b/scenes/v11_collatz.py new file mode 100644 index 0000000..49436b8 --- /dev/null +++ b/scenes/v11_collatz.py @@ -0,0 +1,171 @@ +# -*- coding: utf-8 -*- +import sys, os, math +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +X0, X1 = -3.75, 3.75 +Y0, Y1 = -1.30, 3.30 + + +def seq(n): + s = [n] + while n != 1: + n = n // 2 if n % 2 == 0 else 3 * n + 1 + s.append(n) + return s + + +def curva(sq, color=AMBAR, sw=5, mx=None, nx=None, log=False): + """Trayectoria como poligonal. mx/nx permiten compartir escala entre curvas.""" + mx = mx or max(sq) + nx = nx or len(sq) + if log: + f = lambda v: math.log(v) / math.log(mx) + else: + f = lambda v: v / mx + pts = [[X0 + (X1 - X0) * i / (nx - 1), Y0 + (Y1 - Y0) * f(sq[i]), 0] + for i in range(len(sq))] + m = VMobject(stroke_color=color, stroke_width=sw) + m.set_points_as_corners(pts) + return m, pts + + +def tile(v, col): + t = Text(str(v), font=FONT, font_size=44, weight=BOLD, color="#0B0F1A") + box = RoundedRectangle(corner_radius=0.16, width=max(0.95, t.width + 0.45), + height=0.88, stroke_width=0, fill_color=col, fill_opacity=1) + return VGroup(box, t) + + +class Collatz(TikTok): + NAME = "collatz" + + def construct(self): + self.prepare() + chip = self.chip("Abierto desde 1937", ROSA) + + with self.beat(0) as b: + n = self.big("27", 150, AMBAR).move_to(UP * 1.9) + cap = self.fit(Text("agarrá cualquier número", font=FONT, font_size=50, + weight=BOLD, color=WHITE), 8.2).move_to(DOWN * 0.3) + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.45) + b.play(FadeIn(n, scale=0.6), run_time=0.45) + for v in ("6", "19", "41"): + b.play(Transform(n, self.big(v, 150, AMBAR).move_to(UP * 1.9)), run_time=0.26) + b.play(FadeIn(cap, shift=UP * 0.15), run_time=0.5) + + def regla(txt, op, col): + a = Text(txt, font=FONT, font_size=46, weight=BOLD, color=col) + fl = Arrow(ORIGIN, RIGHT * 0.85, buff=0, color=GRIS, stroke_width=6, + max_tip_length_to_length_ratio=0.35) + c = Text(op, font=FONT, font_size=52, weight=BOLD, color=WHITE) + return VGroup(a, fl, c).arrange(RIGHT, buff=0.35) + + with self.beat(1) as b: + b.play(FadeOut(VGroup(n, cap)), run_time=0.3) + r1 = regla("es PAR", "÷ 2", CELESTE) + r2 = regla("es IMPAR", "× 3 + 1", AMBAR) + rr = VGroup(r1, r2).arrange(DOWN, buff=0.7).move_to(UP * 1.6) + self.fit(rr, 8.2) + b.play(FadeIn(r1, shift=UP * 0.2), run_time=0.7) + b.play(FadeIn(r2, shift=UP * 0.2), run_time=0.7) + + s6 = seq(6) + with self.beat(2) as b: + b.play(rr.animate.scale(0.72).move_to(UP * 5.2), run_time=0.5) + seis = self.big("6", 140, VERDE).move_to(UP * 1.0) + b.play(FadeIn(seis, scale=0.6), run_time=0.6) + + with self.beat(3) as b: + b.play(FadeOut(seis), run_time=0.25) + tiles = VGroup(*[tile(v, VERDE if v == 1 else (CELESTE if v % 2 == 0 else AMBAR)) + for v in s6]) + fila1 = VGroup(*tiles[:5]).arrange(RIGHT, buff=0.28) + fila2 = VGroup(*tiles[5:]).arrange(RIGHT, buff=0.28) + grid = VGroup(fila1, fila2).arrange(DOWN, buff=0.45).move_to(UP * 1.4) + self.fit(grid, 8.2) + b.play(LaggedStart(*[FadeIn(t, scale=0.6) for t in tiles], + lag_ratio=0.5), run_time=max(1.4, b.floor - 0.4)) + + with self.beat(4) as b: + b.play(Circumscribe(tiles[-1], color=VERDE, buff=0.12, stroke_width=6), + run_time=0.7) + b.play(FadeOut(grid), run_time=0.35) + siete = self.big("7", 140, AMBAR).move_to(UP * 1.0) + b.play(FadeIn(siete, scale=0.6), run_time=0.5) + + base = Line([X0 - 0.25, Y0, 0], [X1 + 0.25, Y0, 0], stroke_width=4, color="#33405C") + uno = Text("1", font=FONT, font_size=32, weight=BOLD, color=VERDE) + uno.next_to(base.get_start(), LEFT, buff=0.12) + + s7 = seq(7) + with self.beat(5) as b: + b.play(FadeOut(siete), run_time=0.25) + c7, p7 = curva(s7, AMBAR, 6) + pico = Text("52", font=FONT, font_size=34, weight=BOLD, color=AMBAR) + pico.next_to([p7[s7.index(max(s7))][0], Y1, 0], UP, buff=0.12) + b.play(FadeIn(base), FadeIn(uno), run_time=0.35) + b.play(Create(c7), run_time=max(1.2, b.floor - 1.1)) + b.play(FadeIn(pico), run_time=0.4) + + s27 = seq(27) + with self.beat(6) as b: + b.play(FadeOut(VGroup(c7, pico)), run_time=0.3) + c27, p27 = curva(s27, ROSA, 5) + k = s27.index(max(s27)) + top = Text("9.232", font=FONT, font_size=40, weight=BOLD, color=ROSA) + top.next_to([p27[k][0], Y1, 0], UP, buff=0.12) + lab = Text("27", font=FONT, font_size=40, weight=BOLD, color=ROSA) + lab.move_to([X0 - 0.05, Y1 + 0.45, 0]) + b.play(FadeIn(lab), run_time=0.3) + b.play(Create(c27), run_time=max(1.3, b.floor - 1.0)) + b.play(FadeIn(top), run_time=0.4) + + with self.beat(7) as b: + fin = Dot([p27[-1][0], Y0, 0], radius=0.14, color=VERDE) + pasos = self.fit(Text("111 pasos y cae al 1", font=FONT, font_size=48, + weight=BOLD, color=VERDE), 8.0).move_to(DOWN * 2.6) + b.play(FadeIn(fin, scale=0.4), run_time=0.4) + b.play(Flash(fin, color=VERDE, line_length=0.35, num_lines=14, + flash_radius=0.8), run_time=0.6) + b.play(FadeIn(pasos, shift=UP * 0.15), run_time=0.6) + + with self.beat(8) as b: + b.play(FadeOut(VGroup(c27, top, lab, fin, pasos)), run_time=0.4) + todos = [seq(k) for k in range(2, 80)] + MX = max(max(s) for s in todos) + NX = max(len(s) for s in todos) + cols = [AMBAR, CELESTE, ROSA, VERDE] + gr = VGroup(*[curva(s, cols[i % 4], 2.4, mx=MX, nx=NX, log=True)[0] + for i, s in enumerate(todos)]) + gr.set_stroke(opacity=0.65) + b.play(LaggedStart(*[Create(c) for c in gr], lag_ratio=0.02), + run_time=max(1.6, b.floor - 0.9)) + marca = self.fit(Text("todos terminan en 1", font=FONT, font_size=46, + weight=BOLD, color=VERDE), 8.0).move_to(DOWN * 2.6) + b.play(FadeIn(marca, shift=UP * 0.15), run_time=0.6) + + with self.beat(9) as b: + b.play(FadeOut(VGroup(gr, marca, base, uno, rr)), run_time=0.45) + t = VGroup( + self.fit(Text("nadie pudo demostrar", font=FONT, font_size=50, + weight=BOLD, color=WHITE), 8.2), + self.fit(Text("que pasa SIEMPRE", font=FONT, font_size=54, + weight=BOLD, color=ROSA), 8.2), + ).arrange(DOWN, buff=0.35).move_to(UP * 1.2) + b.play(FadeIn(t[0], shift=UP * 0.15), run_time=0.6) + b.play(FadeIn(t[1], scale=0.8), run_time=0.7) + + with self.beat(10) as b: + b.play(FadeOut(t), run_time=0.35) + cta = VGroup( + self.fit(Text("conjetura de Collatz", font=FONT, font_size=56, + weight=BOLD, color=AMBAR), 8.0), + self.fit(Text("dejá tu número abajo", font=FONT, font_size=46, + weight=BOLD, color=WHITE), 8.0), + ).arrange(DOWN, buff=0.38).move_to(UP * 0.8) + b.play(Write(cta[0]), run_time=0.9) + b.play(FadeIn(cta[1], shift=UP * 0.15), run_time=0.6) + + self.finish() diff --git a/scenes/v12_simpson.py b/scenes/v12_simpson.py new file mode 100644 index 0000000..6092924 --- /dev/null +++ b/scenes/v12_simpson.py @@ -0,0 +1,188 @@ +# -*- coding: utf-8 -*- +import sys, os +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +# datos reales (Charig et al., 1986): tratamiento A vs B para calculos renales +LEV = (("A", 81, 87), ("B", 234, 270)) +GRA = (("A", 192, 263), ("B", 55, 80)) +TOT = (("A", 81 + 192, 87 + 263), ("B", 234 + 55, 270 + 80)) + +BARW = 4.05 # ancho de barra al 100% +XL = -1.55 # borde izquierdo de las barras + + +class Simpson(TikTok): + NAME = "simpson" + + def barra(self, letra, num, den, y, gana): + pct = 100.0 * num / den + col = VERDE if gana else GRIS + lab = Text(letra, font=FONT, font_size=50, weight=BOLD, + color=CELESTE if letra == "A" else ROSA) + lab.move_to([-3.65, y, 0]) + track = RoundedRectangle(corner_radius=0.12, width=BARW, height=0.62, + stroke_width=0, fill_color="#1B2233", fill_opacity=1) + track.move_to([XL, y, 0], LEFT) + fill = RoundedRectangle(corner_radius=0.12, width=max(pct / 100 * BARW, 0.2), + height=0.62, stroke_width=0, fill_color=col, fill_opacity=1) + fill.move_to([XL, y, 0], LEFT) + val = Text(f"{pct:.0f}%", font=FONT, font_size=42, weight=BOLD, color=col) + val.next_to(track, RIGHT, buff=0.22) + return VGroup(lab, track, fill, val) + + def bloque(self, titulo, datos, ytop, ganador): + t = Text(titulo, font=FONT, font_size=40, weight=BOLD, color=WHITE) + t.move_to([-3.85, ytop, 0], LEFT) + b1 = self.barra(datos[0][0], datos[0][1], datos[0][2], ytop - 0.85, + datos[0][0] == ganador) + b2 = self.barra(datos[1][0], datos[1][1], datos[1][2], ytop - 1.70, + datos[1][0] == ganador) + return VGroup(t, b1, b2) + + def construct(self): + self.prepare() + chip = self.chip("Estadística que engaña", ROSA) + + with self.beat(0) as b: + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.45) + cab = VGroup( + self.fit(Text("dos tratamientos", font=FONT, font_size=52, + weight=BOLD, color=WHITE), 8.2), + VGroup( + Text("A", font=FONT, font_size=90, weight=BOLD, color=CELESTE), + Text("vs", font=FONT, font_size=44, color=GRIS), + Text("B", font=FONT, font_size=90, weight=BOLD, color=ROSA), + ).arrange(RIGHT, buff=0.7), + ).arrange(DOWN, buff=0.45).move_to(UP * 3.0) + b.play(FadeIn(cab[0], shift=UP * 0.15), run_time=0.6) + b.play(FadeIn(cab[1][0], scale=0.6), run_time=0.35) + b.play(FadeIn(cab[1][1]), run_time=0.2) + b.play(FadeIn(cab[1][2], scale=0.6), run_time=0.35) + + lev = self.bloque("casos LEVES", LEV, 2.55, "A") + with self.beat(1) as b: + b.play(cab.animate.scale(0.5).move_to(UP * 5.4), run_time=0.5) + b.play(FadeIn(lev[0], shift=RIGHT * 0.2), run_time=0.4) + for bb in (lev[1], lev[2]): + b.play(FadeIn(bb[0]), FadeIn(bb[1]), + GrowFromEdge(bb[2], LEFT), FadeIn(bb[3]), run_time=0.55) + + gra = self.bloque("casos GRAVES", GRA, -0.35, "A") + with self.beat(2) as b: + b.play(FadeIn(gra[0], shift=RIGHT * 0.2), run_time=0.4) + for bb in (gra[1], gra[2]): + b.play(FadeIn(bb[0]), FadeIn(bb[1]), + GrowFromEdge(bb[2], LEFT), FadeIn(bb[3]), run_time=0.55) + + def tilde(col=VERDE): + m = VMobject(stroke_color=col, stroke_width=9) + m.set_points_as_corners([[-0.20, 0.02, 0], [-0.05, -0.18, 0], [0.24, 0.26, 0]]) + return m + + with self.beat(3) as b: + tick = VGroup(*[tilde() for _ in range(2)]) + tick[0].next_to(lev[1][3], RIGHT, buff=0.25) + tick[1].next_to(gra[1][3], RIGHT, buff=0.25) + b.play(FadeIn(tick[0], scale=0.5), run_time=0.4) + b.play(FadeIn(tick[1], scale=0.5), run_time=0.4) + pre = self.fit(Text("A gana 2 de 2", font=FONT, font_size=48, + weight=BOLD, color=CELESTE), 8.0).move_to(DOWN * 2.80) + b.play(FadeIn(pre, shift=UP * 0.15), run_time=0.5) + + tot = self.bloque("TODOS juntos", TOT, 2.55, "B") + with self.beat(4) as b: + b.play(FadeOut(VGroup(lev, gra, tick, pre)), run_time=0.45) + b.play(FadeIn(tot[0], shift=RIGHT * 0.2), run_time=0.4) + for bb in (tot[1], tot[2]): + b.play(FadeIn(bb[0]), FadeIn(bb[1]), + GrowFromEdge(bb[2], LEFT), FadeIn(bb[3]), run_time=0.6) + + with self.beat(5) as b: + b.play(Circumscribe(tot[2], color=VERDE, buff=0.18, stroke_width=6), + run_time=0.8) + g = self.fit(Text("gana B", font=FONT, font_size=70, weight=BOLD, + color=ROSA), 8.0).move_to(DOWN * 0.75) + ne = self.fit(Text("y no hay ningún error", font=FONT, font_size=44, + weight=BOLD, color=WHITE), 8.0).next_to(g, DOWN, buff=0.4) + b.play(FadeIn(g, scale=0.7), run_time=0.6) + b.play(FadeIn(ne, shift=UP * 0.15), run_time=0.5) + + with self.beat(6) as b: + b.play(FadeOut(VGroup(tot, g, ne, cab)), run_time=0.4) + nom = VGroup( + self.fit(Text("PARADOJA", font=FONT, font_size=72, weight=BOLD, + color=AMBAR), 8.2), + self.fit(Text("DE SIMPSON", font=FONT, font_size=72, weight=BOLD, + color=AMBAR), 8.2), + ).arrange(DOWN, buff=0.2).move_to(UP * 2.6) + b.play(FadeIn(nom, scale=0.75), run_time=0.8) + b.play(Flash(nom, color=AMBAR, line_length=0.6, num_lines=20, + flash_radius=3.0), run_time=0.7) + + def reparto(letra, col, leves, graves, y): + lab = Text(letra, font=FONT, font_size=50, weight=BOLD, color=col) + lab.move_to([-3.65, y, 0]) + n = leves + graves + wl = leves / n * BARW + a = Rectangle(width=max(wl, 0.05), height=0.7, stroke_width=0, + fill_color=VERDE, fill_opacity=1).move_to([XL, y, 0], LEFT) + c = Rectangle(width=max(BARW - wl, 0.05), height=0.7, stroke_width=0, + fill_color=ROSA, fill_opacity=1).next_to(a, RIGHT, buff=0) + nl = Text(str(leves), font=FONT, font_size=30, weight=BOLD, color="#0B0F1A").move_to(a) + ng = Text(str(graves), font=FONT, font_size=30, weight=BOLD, color="#0B0F1A").move_to(c) + return VGroup(lab, a, c, nl, ng) + + leyenda = VGroup( + VGroup(Square(0.34, stroke_width=0, fill_color=VERDE, fill_opacity=1), + Text("leves", font=FONT, font_size=32, color=WHITE)).arrange(RIGHT, buff=0.18), + VGroup(Square(0.34, stroke_width=0, fill_color=ROSA, fill_opacity=1), + Text("graves", font=FONT, font_size=32, color=WHITE)).arrange(RIGHT, buff=0.18), + ).arrange(RIGHT, buff=0.8).move_to(UP * 0.55) + + rA = reparto("A", CELESTE, 87, 263, -0.65) + rB = reparto("B", ROSA, 270, 80, -1.75) + + with self.beat(7) as b: + b.play(nom.animate.scale(0.55).move_to(UP * 5.3), run_time=0.5) + b.play(FadeIn(leyenda), run_time=0.4) + b.play(FadeIn(rA[0]), GrowFromEdge(VGroup(rA[1], rA[2]), LEFT), + FadeIn(VGroup(rA[3], rA[4])), run_time=0.8) + b.play(Circumscribe(rA[2], color=ROSA, buff=0.1, stroke_width=5), run_time=0.7) + + with self.beat(8) as b: + b.play(FadeIn(rB[0]), GrowFromEdge(VGroup(rB[1], rB[2]), LEFT), + FadeIn(VGroup(rB[3], rB[4])), run_time=0.8) + b.play(Circumscribe(rB[1], color=VERDE, buff=0.1, stroke_width=5), run_time=0.7) + + with self.beat(9) as b: + b.play(FadeOut(VGroup(rA, rB, leyenda)), run_time=0.4) + t = VGroup( + self.fit(Text("el promedio mezcla", font=FONT, font_size=48, + weight=BOLD, color=WHITE), 8.2), + self.fit(Text("dos grupos distintos", font=FONT, font_size=48, + weight=BOLD, color=AMBAR), 8.2), + self.fit(Text("(datos de un estudio real)", font=FONT, font_size=34, + color=GRIS), 8.2), + ).arrange(DOWN, buff=0.35).move_to(UP * 1.6) + b.play(FadeIn(t[0], shift=UP * 0.15), run_time=0.55) + b.play(FadeIn(t[1], shift=UP * 0.15), run_time=0.55) + b.play(FadeIn(t[2]), run_time=0.45) + + with self.beat(10) as b: + b.play(FadeOut(t), run_time=0.35) + cta = VGroup( + self.fit(Text("cuando te muestren", font=FONT, font_size=44, + weight=BOLD, color=WHITE), 8.0), + self.fit(Text("un promedio, preguntá:", font=FONT, font_size=44, + weight=BOLD, color=WHITE), 8.0), + self.fit(Text("¿de quiénes?", font=FONT, font_size=64, + weight=BOLD, color=AMBAR), 8.0), + ).arrange(DOWN, buff=0.3).move_to(UP * 1.4) + b.play(FadeIn(cta[0], shift=UP * 0.12), run_time=0.45) + b.play(FadeIn(cta[1], shift=UP * 0.12), run_time=0.45) + b.play(Write(cta[2]), run_time=0.8) + b.play(Circumscribe(cta[2], color=AMBAR, buff=0.25, stroke_width=6), run_time=0.8) + + self.finish() diff --git a/scenes/v13_cuerda.py b/scenes/v13_cuerda.py new file mode 100644 index 0000000..5ca224d --- /dev/null +++ b/scenes/v13_cuerda.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- +import sys, os, math +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +CEN = UP * 1.75 +RT = 2.05 # radio de la Tierra en pantalla +HUECO = 0.72 # separacion dibujada (exagerada) + + +def gato(h=0.55, color="#E8EDF7"): + """Silueta simple de gato de perfil, alto total = h.""" + body = Ellipse(width=0.90, height=0.34, stroke_width=0, fill_color=color, + fill_opacity=1).move_to([0, 0.12, 0]) + head = Circle(radius=0.17, stroke_width=0, fill_color=color, + fill_opacity=1).move_to([0.46, 0.26, 0]) + e1 = Triangle(stroke_width=0, fill_color=color, fill_opacity=1).scale(0.09) + e1.move_to([0.39, 0.42, 0]) + e2 = e1.copy().shift(RIGHT * 0.15) + tail = ArcBetweenPoints([-0.44, 0.16, 0], [-0.62, 0.52, 0], angle=-1.6, + stroke_width=5, color=color) + legs = VGroup(*[Line([x, 0.02, 0], [x, -0.16, 0], stroke_width=6, color=color) + for x in (-0.28, -0.08, 0.18, 0.36)]) + g = VGroup(tail, body, legs, head, e1, e2) + g.scale(h / g.height) + return g + + +class Cuerda(TikTok): + NAME = "cuerda" + + def planeta(self, r, center, col="#1D3B6E"): + p = Circle(radius=r, stroke_width=4, stroke_color=CELESTE, + fill_color=col, fill_opacity=1).move_to(center) + return p + + def construct(self): + self.prepare() + chip = self.chip("Intuición rota", CELESTE) + + tierra = self.planeta(RT, CEN) + cuerda = Circle(radius=RT + 0.03, stroke_width=7, color=AMBAR).move_to(CEN) + + with self.beat(0) as b: + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.45) + b.play(GrowFromCenter(tierra), run_time=0.7) + b.play(Create(cuerda), run_time=max(0.8, b.floor - 1.6)) + + with self.beat(1) as b: + km = Text("40.000 km", font=FONT, font_size=50, weight=BOLD, color=AMBAR) + km.move_to(CEN + DOWN * 0.0) + box = RoundedRectangle(corner_radius=0.16, stroke_width=0, fill_color="#0B0F1A", + fill_opacity=0.78, width=km.width + 0.5, + height=km.height + 0.35).move_to(km) + b.play(FadeIn(VGroup(box, km), scale=0.7), run_time=0.8) + + with self.beat(2) as b: + b.play(FadeOut(VGroup(box, km)), run_time=0.3) + seg = Line(LEFT * 0.6, RIGHT * 0.6, stroke_width=9, color=VERDE) + tip = VGroup(*[Line(UP * 0.16, DOWN * 0.16, stroke_width=6, color=VERDE) + .move_to(p) for p in (seg.get_start(), seg.get_end())]) + lab = Text("+ 1 metro", font=FONT, font_size=48, weight=BOLD, color=VERDE) + g = VGroup(VGroup(seg, tip), lab).arrange(DOWN, buff=0.3).move_to(DOWN * 2.15) + b.play(GrowFromCenter(VGroup(seg, tip)), run_time=0.5) + b.play(FadeIn(lab, shift=UP * 0.15), run_time=0.6) + + with self.beat(3) as b: + alta = Circle(radius=RT + HUECO, stroke_width=7, color=AMBAR).move_to(CEN) + radios = VGroup(*[ + DashedLine(CEN + RT * np.array([math.cos(a), math.sin(a), 0]), + CEN + (RT + HUECO) * np.array([math.cos(a), math.sin(a), 0]), + stroke_width=4, color="#7C8AA8", dash_length=0.07) + for a in np.linspace(0, TAU, 16, endpoint=False)]) + b.play(FadeOut(g), run_time=0.25) + b.play(Transform(cuerda, alta), run_time=1.0) + b.play(FadeIn(radios), run_time=0.5) + esc = Text("(dibujo exagerado)", font=FONT, font_size=28, color=GRIS) + esc.move_to(DOWN * 2.6) + b.play(FadeIn(esc), run_time=0.35) + + with self.beat(4) as b: + q = VGroup( + self.fit(Text("¿cuánto se separa?", font=FONT, font_size=52, + weight=BOLD, color=WHITE), 8.0), + VGroup( + Text("«nada»", font=FONT, font_size=40, color=GRIS), + Text("«un pelo»", font=FONT, font_size=40, color=GRIS), + ).arrange(RIGHT, buff=0.7), + ).arrange(DOWN, buff=0.35).move_to(CEN) + bx = RoundedRectangle(corner_radius=0.2, stroke_width=0, fill_color="#0B0F1A", + fill_opacity=0.82, width=q.width + 0.6, + height=q.height + 0.5).move_to(q) + b.play(FadeIn(VGroup(bx, q), scale=0.85), run_time=0.8) + + with self.beat(5) as b: + b.play(FadeOut(VGroup(bx, q)), run_time=0.3) + gt = gato(HUECO * 0.92).move_to(CEN + UP * (RT + HUECO / 2)) + med = DoubleArrow(CEN + LEFT * RT, CEN + LEFT * (RT + HUECO), buff=0, + color=VERDE, stroke_width=6, tip_length=0.18) + val = Text("15,9 cm", font=FONT, font_size=42, weight=BOLD, color=VERDE) + val.next_to(med, UP, buff=0.22) + b.play(GrowArrow(med), FadeIn(val), run_time=0.7) + b.play(FadeIn(gt, shift=RIGHT * 0.3), run_time=0.7) + + with self.beat(6) as b: + b.play(FadeOut(VGroup(radios, gt, med, val, esc)), run_time=0.4) + b.play(VGroup(tierra, cuerda).animate.scale(0.52).move_to(UP * 4.6), + run_time=0.6) + f1 = MathTex(r"r = \frac{P}{2\pi}", color=WHITE).scale(1.6).move_to(UP * 1.5) + b.play(Write(f1), run_time=1.0) + + with self.beat(7) as b: + f2 = MathTex(r"\Delta r = \frac{1\,\text{m}}{2\pi}", color=AMBAR) + f2.scale(1.6).move_to(DOWN * 0.5) + b.play(Write(f2), run_time=1.1) + + with self.beat(8) as b: + f3 = MathTex(r"= 0{,}159\ \text{m} = 15{,}9\ \text{cm}", color=VERDE) + f3.scale(1.25).move_to(DOWN * 2.15) + b.play(Write(f3), run_time=0.9) + nota = self.fit(Text("el tamaño del planeta no aparece", font=FONT, + font_size=40, weight=BOLD, color=ROSA), 8.2) + nota.move_to(DOWN * 3.05) + b.play(FadeIn(nota, shift=UP * 0.15), run_time=0.6) + + with self.beat(9) as b: + b.play(FadeOut(VGroup(f1, f2, f3, nota, tierra, cuerda)), run_time=0.45) + def par(r, etiqueta, x, col): + c0 = [x, 1.75, 0] + p = self.planeta(r, c0, col) + c = Circle(radius=r + 0.30, stroke_width=6, color=AMBAR).move_to(c0) + lab = Text(etiqueta, font=FONT, font_size=36, weight=BOLD, color=WHITE) + lab.move_to([x, -0.55, 0]) + v = Text("15,9 cm", font=FONT, font_size=38, weight=BOLD, color=VERDE) + v.move_to([x, -1.25, 0]) + return VGroup(p, c, lab, v) + iz = par(1.25, "la Tierra", -2.05, "#1D3B6E") + de = par(0.55, "una pelota de tenis", 2.05, "#2F7A3C") + self.fit(de[2], 3.9) + b.play(FadeIn(iz), run_time=0.6) + b.play(FadeIn(de), run_time=0.6) + ig = Text("=", font=FONT, font_size=64, weight=BOLD, color=AMBAR) + ig.move_to([0, 1.75, 0]) + b.play(FadeIn(ig, scale=0.6), run_time=0.5) + esc2 = Text("(no está a escala)", font=FONT, font_size=28, color=GRIS) + esc2.move_to(DOWN * 2.35) + b.play(FadeIn(esc2), run_time=0.35) + + with self.beat(10) as b: + b.play(FadeOut(VGroup(iz, de, ig, esc2)), run_time=0.4) + cta = VGroup( + self.fit(Text("el tamaño no importa", font=FONT, font_size=56, + weight=BOLD, color=AMBAR), 8.0), + self.fit(Text("mandáselo al que dudó", font=FONT, font_size=44, + weight=BOLD, color=WHITE), 8.0), + ).arrange(DOWN, buff=0.38).move_to(UP * 1.4) + b.play(Write(cta[0]), run_time=0.9) + b.play(FadeIn(cta[1], shift=UP * 0.15), run_time=0.6) + + self.finish() diff --git a/scenes/v14_gabriel.py b/scenes/v14_gabriel.py new file mode 100644 index 0000000..24a9621 --- /dev/null +++ b/scenes/v14_gabriel.py @@ -0,0 +1,172 @@ +# -*- coding: utf-8 -*- +import sys, os, math +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +XA, XB = 1.0, 7.4 # dominio de 1/x +KX, KY = 1.00, 2.00 # escala a pantalla +X0S, CY = -3.75, 1.70 + + +def sx(x): + return X0S + (x - XA) * KX + + +def sy(x): + return KY / x + + +def rama(sig, n=160, **kw): + xs = np.linspace(XA, XB, n) + pts = [[sx(x), CY + sig * sy(x), 0] for x in xs] + m = VMobject(**kw) + m.set_points_as_corners(pts) + return m + + +def cuerpo(fill="#1E4E8C", op=0.55): + xs = np.linspace(XA, XB, 160) + up = [[sx(x), CY + sy(x), 0] for x in xs] + dn = [[sx(x), CY - sy(x), 0] for x in reversed(xs)] + m = VMobject(stroke_width=0, fill_color=fill, fill_opacity=op) + m.set_points_as_corners(up + dn + [up[0]]) + return m + + +def aros(n=9, col=CELESTE, op=0.55): + xs = np.linspace(XA + 0.35, XB, n) + return VGroup(*[ + Ellipse(width=0.34, height=2 * sy(x), stroke_width=3, stroke_opacity=op, + color=col).move_to([sx(x), CY, 0]) for x in xs]) + + +class Gabriel(TikTok): + NAME = "gabriel" + + def construct(self): + self.prepare() + chip = self.chip("Paradoja del infinito", CELESTE) + + with self.beat(0) as b: + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.45) + t = VGroup( + self.fit(Text("el cuerno de", font=FONT, font_size=50, + weight=BOLD, color=WHITE), 8.0), + self.fit(Text("GABRIEL", font=FONT, font_size=86, + weight=BOLD, color=AMBAR), 8.0), + ).arrange(DOWN, buff=0.25).move_to(UP * 2.6) + b.play(FadeIn(t[0], shift=UP * 0.15), run_time=0.5) + b.play(FadeIn(t[1], scale=0.7), run_time=0.8) + + eje = Line([sx(XA) - 0.5, CY, 0], [sx(XB) + 0.35, CY, 0], + stroke_width=3, color="#33405C") + + with self.beat(1) as b: + b.play(t.animate.scale(0.5).move_to(UP * 5.3), run_time=0.5) + f = MathTex(r"y = \frac{1}{x}", color=AMBAR).scale(1.35).move_to(DOWN * 2.4) + up = rama(+1, stroke_color=AMBAR, stroke_width=6) + b.play(FadeIn(eje), run_time=0.3) + b.play(Create(up), run_time=0.9) + b.play(Write(f), run_time=0.7) + + body = cuerpo() + low = rama(-1, stroke_color=AMBAR, stroke_width=6) + ar = aros() + boca = Ellipse(width=0.42, height=2 * sy(XA), stroke_width=6, + color=AMBAR).move_to([sx(XA), CY, 0]) + + with self.beat(2) as b: + b.play(Create(low), run_time=0.6) + b.play(FadeIn(body), FadeIn(boca), run_time=0.5) + b.play(LaggedStart(*[Create(a) for a in ar], lag_ratio=0.15), run_time=0.9) + inf = MathTex(r"\cdots \infty", color=GRIS).scale(1.0) + inf.next_to([sx(XB), CY, 0], RIGHT, buff=0.2) + b.play(FadeIn(inf), run_time=0.4) + + horn = VGroup(eje, body, up, low, ar, boca, inf) + + with self.beat(3) as b: + b.play(FadeOut(f), run_time=0.25) + q = self.fit(Text("¿cuánta pintura entra?", font=FONT, font_size=52, + weight=BOLD, color=WHITE), 8.2).move_to(DOWN * 2.3) + b.play(FadeIn(q, shift=UP * 0.15), run_time=0.7) + + with self.beat(4) as b: + b.play(FadeOut(q), run_time=0.25) + lleno = cuerpo(fill=VERDE, op=0.85) + b.play(FadeIn(lleno), run_time=0.7) + v = MathTex(r"V = \pi\int_1^{\infty}\frac{dx}{x^2} = \pi", + color=VERDE).scale(1.15).move_to(DOWN * 2.05) + b.play(Write(v), run_time=1.1) + + with self.beat(5) as b: + lt = self.fit(Text("≈ 3,14 litros y te sobra", font=FONT, font_size=48, + weight=BOLD, color=VERDE), 8.2).move_to(DOWN * 2.90) + b.play(FadeIn(lt, shift=UP * 0.15), run_time=0.7) + + with self.beat(6) as b: + b.play(FadeOut(VGroup(v, lt, lleno)), run_time=0.4) + q2 = self.fit(Text("¿y pintarlo por fuera?", font=FONT, font_size=52, + weight=BOLD, color=WHITE), 8.2).move_to(DOWN * 2.3) + b.play(up.animate.set_stroke(ROSA, 8), low.animate.set_stroke(ROSA, 8), + run_time=0.6) + b.play(FadeIn(q2, shift=UP * 0.15), run_time=0.6) + + with self.beat(7) as b: + b.play(FadeOut(q2), run_time=0.25) + a = MathTex(r"A > 2\pi\int_1^{\infty}\frac{dx}{x} = \infty", + color=ROSA).scale(1.15).move_to(DOWN * 2.15) + b.play(Write(a), run_time=1.1) + b.play(Flash(a, color=ROSA, line_length=0.5, num_lines=18, + flash_radius=2.4), run_time=0.7) + + with self.beat(8) as b: + b.play(FadeOut(VGroup(a, horn)), run_time=0.45) + def fila(txt, val, col): + t1 = Text(txt, font=FONT, font_size=44, weight=BOLD, color=WHITE) + t2 = Text(val, font=FONT, font_size=56, weight=BOLD, color=col) + return VGroup(t1, t2).arrange(DOWN, buff=0.18) + cmp = VGroup(fila("volumen", "π (finito)", VERDE), + fila("superficie", "∞ (infinita)", ROSA) + ).arrange(DOWN, buff=0.75).move_to(UP * 2.4) + self.fit(cmp, 8.2) + b.play(FadeIn(cmp[0], shift=UP * 0.15), run_time=0.55) + b.play(FadeIn(cmp[1], shift=UP * 0.15), run_time=0.55) + golpe = VGroup( + self.fit(Text("lo llenás de pintura", font=FONT, font_size=48, + weight=BOLD, color=WHITE), 8.2), + self.fit(Text("pero no lo podés pintar", font=FONT, font_size=48, + weight=BOLD, color=AMBAR), 8.2), + ).arrange(DOWN, buff=0.3).move_to(DOWN * 0.6) + b.play(FadeIn(golpe, scale=0.85), run_time=0.8) + + with self.beat(9) as b: + b.play(FadeOut(VGroup(cmp, golpe)), run_time=0.4) + tr = VGroup( + self.fit(Text("la trampa:", font=FONT, font_size=48, + weight=BOLD, color=ROSA), 8.2), + self.fit(Text("la pintura real tiene", font=FONT, font_size=46, + weight=BOLD, color=WHITE), 8.2), + self.fit(Text("espesor. El cuerno", font=FONT, font_size=46, + weight=BOLD, color=WHITE), 8.2), + self.fit(Text("se hace más fino que eso.", font=FONT, font_size=46, + weight=BOLD, color=WHITE), 8.2), + ).arrange(DOWN, buff=0.3).move_to(UP * 1.8) + for k in range(4): + b.play(FadeIn(tr[k], shift=UP * 0.12), run_time=0.45) + + with self.beat(10) as b: + b.play(FadeOut(tr), run_time=0.35) + cta = VGroup( + self.fit(Text("con el infinito", font=FONT, font_size=52, + weight=BOLD, color=WHITE), 8.0), + self.fit(Text("la intuición se rompe", font=FONT, font_size=56, + weight=BOLD, color=AMBAR), 8.0), + ).arrange(DOWN, buff=0.35).move_to(UP * 1.4) + b.play(FadeIn(cta[0], shift=UP * 0.15), run_time=0.55) + b.play(Write(cta[1]), run_time=0.9) + b.play(Circumscribe(cta[1], color=AMBAR, buff=0.25, stroke_width=6), + run_time=0.8) + + self.finish() diff --git a/scenes/v15_mobius.py b/scenes/v15_mobius.py new file mode 100644 index 0000000..a921c6b --- /dev/null +++ b/scenes/v15_mobius.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +"""Cinta de Mobius renderizada como superficie reglada: se generan quads en 3D, +se proyectan con una camara fija y se dibujan de atras hacia adelante.""" +import sys, os, math +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +TILT, YAW = 1.02, 0.0 +CARA_A, CARA_B = "#FFD166", "#2F6FD0" + + +def geom(tau, beta, L=9.4, w=0.62, nu=170, smax=1.0): + """Punto central y direccion transversal de la cinta para s en [0, smax].""" + s = np.linspace(0.0, smax, max(int(nu * smax), 2) + 1) + th = max(beta * TAU, 1e-3) + Rr = L / th + ang = th * (s - 0.5) + p = np.stack([Rr * np.sin(ang), Rr * np.cos(ang) - Rr, np.zeros_like(ang)], axis=1) + N = np.stack([np.sin(ang), np.cos(ang), np.zeros_like(ang)], axis=1) + B = np.zeros_like(N) + B[:, 2] = 1.0 + phi = tau * PI * s + d = np.cos(phi)[:, None] * N + np.sin(phi)[:, None] * B + return p, d, s + + +def proj(P): + x, y, z = P[..., 0], P[..., 1], P[..., 2] + c, sn = math.cos(YAW), math.sin(YAW) + x2, y2 = x * c - y * sn, x * sn + y * c + ct, st = math.cos(TILT), math.sin(TILT) + return x2, y2 * ct - z * st, y2 * st + z * ct # X, Y, profundidad + + +def quads(tau, beta, L=9.4, w=0.62, nu=170, scale=1.0, center=ORIGIN): + """Lista de (poligono_screen, profundidad, color) sin ordenar.""" + p, d, _ = geom(tau, beta, L, w, nu) + A = p - w * d + Bv = p + w * d + XA, YA, DA = proj(A) + XB, YB, DB = proj(Bv) + out = [] + for i in range(len(p) - 1): + n = np.cross(Bv[i] - A[i], A[i + 1] - A[i]) + ln = np.linalg.norm(n) + 1e-12 + _, _, nd = proj(n / ln) + front = nd < 0 + bright = 0.42 + 0.58 * abs(nd) + col = interpolate_color(BLACK, ManimColor(CARA_A if front else CARA_B), bright) + pts = [[XA[i], YA[i], 0], [XB[i], YB[i], 0], + [XB[i + 1], YB[i + 1], 0], [XA[i + 1], YA[i + 1], 0]] + pts = [list(np.array(q) * scale + center) for q in pts] + out.append((pts, (DA[i] + DB[i] + DA[i + 1] + DB[i + 1]) / 4.0, col)) + return out + + +def draw(items): + """Painter's algorithm: lo mas lejos (profundidad mayor) se dibuja primero.""" + items = sorted(items, key=lambda t: -t[1]) + return VGroup(*[Polygon(*pts, stroke_width=0, fill_color=col, fill_opacity=1) + for pts, _, col in items]) + + +def cinta(tau, beta, **kw): + return draw(quads(tau, beta, **kw)) + + +def camino(tau, beta, off, smax=1.0, L=9.4, w=0.62, nu=170, scale=1.0, + center=ORIGIN, **kw): + """Poligonal sobre la cinta a distancia 'off' del centro (off en [-w, w]).""" + p, d, _ = geom(tau, beta, L, w, nu, smax=smax) + P = p + off * d + X, Y, _ = proj(P) + m = VMobject(**kw) + m.set_points_as_corners([list(np.array([X[i], Y[i], 0]) * scale + center) + for i in range(len(X))]) + return m + + +class Mobius(TikTok): + NAME = "mobius" + + def construct(self): + self.prepare() + chip = self.chip("Hacelo en casa", VERDE) + C = UP * 1.85 + SC = 1.30 + P = dict(L=9.4, w=0.62, nu=130, scale=SC, center=C) + + tau = ValueTracker(0.0) + beta = ValueTracker(0.0) + sc = ValueTracker(0.60) # la tira plana mide L*scale: tiene que entrar + + def actual(): + return cinta(tau.get_value(), beta.get_value(), + **{**P, "scale": sc.get_value()}) + + banda = actual() + + with self.beat(0) as b: + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.45) + b.play(FadeIn(banda, shift=UP * 0.2), run_time=0.7) + + with self.beat(1) as b: + banda.add_updater(lambda m: m.become(actual())) + b.play(tau.animate.set_value(1.0), run_time=max(1.0, b.floor * 0.45), + rate_func=smooth) + b.play(beta.animate.set_value(1.0), sc.animate.set_value(SC), + run_time=max(1.0, b.floor * 0.45), rate_func=smooth) + banda.clear_updaters() + banda.become(cinta(1.0, 1.0, **P)) + + with self.beat(2) as b: + nom = VGroup( + self.fit(Text("cinta de M\u00f6bius", font=FONT, font_size=58, + weight=BOLD, color=AMBAR), 8.0), + self.fit(Text("una sola cara", font=FONT, font_size=50, + weight=BOLD, color=WHITE), 8.0), + ).arrange(DOWN, buff=0.3).move_to(DOWN * 2.6) + b.play(Write(nom[0]), run_time=0.8) + b.play(FadeIn(nom[1], shift=UP * 0.15), run_time=0.6) + + def recorrido(off, color, prog): + m = camino(1.0, 1.0, off, smax=max(prog.get_value(), 0.004), + stroke_color=color, stroke_width=9, **P) + return m + + with self.beat(3) as b: + b.play(FadeOut(nom), run_time=0.25) + prog = ValueTracker(0.004) + traza = recorrido(0.72 * P["w"], ROSA, prog) + traza.add_updater(lambda m: m.become(recorrido(0.72 * P["w"], ROSA, prog))) + punta = Dot(radius=0.16, color=ROSA) + punta.add_updater(lambda m: m.move_to(traza.get_end())) + b.add(traza, punta) + b.play(prog.animate.set_value(2.0), run_time=max(1.6, b.floor - 0.5), + rate_func=linear) + traza.clear_updaters(); punta.clear_updaters() + + with self.beat(4) as b: + b.play(FadeOut(VGroup(traza, punta)), run_time=0.3) + prog2 = ValueTracker(0.004) + borde = recorrido(P["w"], VERDE, prog2) + borde.add_updater(lambda m: m.become(recorrido(P["w"], VERDE, prog2))) + b.add(borde) + b.play(prog2.animate.set_value(2.0), run_time=max(1.4, b.floor - 0.9), + rate_func=linear) + borde.clear_updaters() + uno = self.fit(Text("un solo borde", font=FONT, font_size=50, + weight=BOLD, color=VERDE), 8.0).move_to(DOWN * 2.6) + b.play(FadeIn(uno, shift=UP * 0.15), run_time=0.6) + + with self.beat(5) as b: + b.play(FadeOut(VGroup(borde, uno)), run_time=0.3) + corte = camino(1.0, 1.0, 0.0, smax=1.0, stroke_color=ROSA, + stroke_width=8, **P) + corte = DashedVMobject(corte, num_dashes=90, color=ROSA) + b.play(Create(corte), run_time=max(1.2, b.floor - 0.8)) + tij = self.fit(Text("cortala al medio", font=FONT, font_size=50, + weight=BOLD, color=ROSA), 8.0).move_to(DOWN * 2.6) + b.play(FadeIn(tij, shift=UP * 0.15), run_time=0.6) + + with self.beat(6) as b: + b.play(FadeOut(VGroup(corte, tij)), run_time=0.3) + b.remove(banda) + larga = cinta(4.0, 1.0, L=18.0, w=0.30, nu=260, scale=0.92, center=C) + b.play(FadeIn(larga), run_time=0.7) + t = VGroup( + self.fit(Text("no salen dos", font=FONT, font_size=50, + weight=BOLD, color=WHITE), 8.0), + self.fit(Text("sale UNA, el doble de larga", font=FONT, font_size=46, + weight=BOLD, color=AMBAR), 8.2), + ).arrange(DOWN, buff=0.3).move_to(DOWN * 2.6) + b.play(FadeIn(t[0], shift=UP * 0.15), run_time=0.5) + b.play(FadeIn(t[1], shift=UP * 0.15), run_time=0.6) + + with self.beat(7) as b: + b.play(FadeOut(t), run_time=0.3) + dc = VGroup( + self.fit(Text("y esa ya tiene", font=FONT, font_size=48, + weight=BOLD, color=WHITE), 8.0), + self.fit(Text("DOS caras", font=FONT, font_size=62, + weight=BOLD, color=CELESTE), 8.0), + ).arrange(DOWN, buff=0.28).move_to(DOWN * 2.7) + b.play(FadeIn(dc[0], shift=UP * 0.15), run_time=0.5) + b.play(FadeIn(dc[1], scale=0.75), run_time=0.7) + + with self.beat(8) as b: + b.play(FadeOut(VGroup(larga, dc)), run_time=0.35) + c1 = DashedVMobject(camino(1.0, 1.0, P["w"] / 3, stroke_color=VERDE, + stroke_width=7, **P), + num_dashes=80, color=VERDE) + c2 = DashedVMobject(camino(1.0, 1.0, -P["w"] / 3, stroke_color=VERDE, + stroke_width=7, **P), + num_dashes=80, color=VERDE) + b.play(FadeIn(banda), run_time=0.35) + b.play(Create(c1), Create(c2), run_time=max(1.1, b.floor - 1.1)) + tt = self.fit(Text("ahora cortá a 1/3 del borde", font=FONT, font_size=44, + weight=BOLD, color=VERDE), 8.2).move_to(DOWN * 2.7) + b.play(FadeIn(tt, shift=UP * 0.15), run_time=0.55) + + with self.beat(9) as b: + b.play(FadeOut(VGroup(c1, c2, tt)), run_time=0.3) + b.remove(banda) + q1 = quads(1.0, 1.0, L=9.4, w=0.22, nu=170, scale=0.95, + center=C + LEFT * 1.15) + q2 = quads(4.0, 1.0, L=18.0, w=0.22, nu=260, scale=0.72, + center=C + RIGHT * 1.15) + r1, r2 = draw(q1), draw(q2) + dep = np.array([q[1] for q in q1]) + med = float(np.median(dep)) + frente = draw([q for q in q1 # eslabon que pasa encima + if np.mean([pt[0] for pt in q[0]]) > C[0] - 1.15 + and q[1] < med]) + cadena = VGroup(r1, r2, frente) + b.play(FadeIn(cadena), run_time=0.8) + t2 = VGroup( + self.fit(Text("dos cintas distintas", font=FONT, font_size=48, + weight=BOLD, color=WHITE), 8.2), + self.fit(Text("y quedan enganchadas", font=FONT, font_size=48, + weight=BOLD, color=AMBAR), 8.2), + ).arrange(DOWN, buff=0.3).move_to(DOWN * 2.7) + b.play(FadeIn(t2[0], shift=UP * 0.15), run_time=0.5) + b.play(FadeIn(t2[1], shift=UP * 0.15), run_time=0.6) + + with self.beat(10) as b: + b.play(FadeOut(VGroup(cadena, t2)), run_time=0.4) + cta = VGroup( + self.fit(Text("una hoja y cinta", font=FONT, font_size=52, + weight=BOLD, color=WHITE), 8.0), + self.fit(Text("hacelo ahora", font=FONT, font_size=66, + weight=BOLD, color=VERDE), 8.0), + self.fit(Text("contame cómo te fue", font=FONT, font_size=42, + weight=BOLD, color=WHITE), 8.0), + ).arrange(DOWN, buff=0.32).move_to(UP * 1.4) + b.play(FadeIn(cta[0], shift=UP * 0.12), run_time=0.5) + b.play(Write(cta[1]), run_time=0.8) + b.play(FadeIn(cta[2], shift=UP * 0.12), run_time=0.5) + + self.finish() diff --git a/scenes/v16_bayes.py b/scenes/v16_bayes.py new file mode 100644 index 0000000..311dd01 --- /dev/null +++ b/scenes/v16_bayes.py @@ -0,0 +1,160 @@ +# -*- coding: utf-8 -*- +import sys, os +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +COLS, ROWS = 25, 40 +PX, PY = 0.27, 0.175 +GY = 1.65 # centro vertical de la grilla +RAD = 0.062 +APAGADO = "#2B3A5C" +ENFERMA = 437 # fila 17, columna 12 (queda centrada) +FALSOS = [63, 147, 232, 318, 389, 476, 551, 668, 742, 861] + + +def pos(i): + r, c = divmod(i, COLS) + return np.array([(c - (COLS - 1) / 2) * PX, + GY + ((ROWS - 1) / 2 - r) * PY, 0.0]) + + +class Bayes(TikTok): + NAME = "bayes" + + def construct(self): + self.prepare() + chip = self.chip("Probabilidad", CELESTE) + + # --- la tarjeta del test --------------------------------------------- + marco = RoundedRectangle(corner_radius=0.32, width=6.4, height=3.4, stroke_width=5, + stroke_color=CELESTE, fill_color="#121C33", + fill_opacity=1).move_to(UP * 3.5) + et = Text("TEST", font=FONT, font_size=40, weight=BOLD, color=GRIS) + num = Text("99%", font=FONT, font_size=118, weight=BOLD, color=AMBAR) + pie = Text("de precisión", font=FONT, font_size=38, weight=BOLD, color=WHITE) + VGroup(et, num, pie).arrange(DOWN, buff=0.18).move_to(marco) + tarjeta = VGroup(marco, et, num, pie) + + with self.beat(0) as b: + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.4) + b.play(GrowFromCenter(tarjeta), run_time=0.8) + b.play(Flash(num, color=AMBAR, line_length=0.35, num_lines=14, + flash_radius=1.7), run_time=0.9) + + sello = VGroup( + RoundedRectangle(corner_radius=0.18, width=4.7, height=1.25, stroke_width=8, + stroke_color=ROSA, fill_color="#2A0E18", fill_opacity=0.94), + Text("POSITIVO", font=FONT, font_size=60, weight=BOLD, color=ROSA)) + sello.rotate(-0.09).move_to(marco.get_bottom() + DOWN * 0.05) + + with self.beat(1) as b: + b.play(FadeIn(sello, scale=2.4), run_time=0.55) + b.play(Wiggle(sello, scale_value=1.07), run_time=1.0) + + preg = Text("La mayoría contesta:", font=FONT, font_size=40, + weight=BOLD, color=GRIS).move_to(UP * 0.45) + mal = Text("99%", font=FONT, font_size=106, weight=BOLD, color=GRIS) + mal.next_to(preg, DOWN, buff=0.28) + + with self.beat(2) as b: + b.play(FadeIn(preg, shift=UP * 0.2), run_time=0.5) + b.play(FadeIn(mal, scale=0.7), run_time=0.7) + + tacha = Line(mal.get_left() + LEFT * 0.28, mal.get_right() + RIGHT * 0.28, + stroke_width=11, color=ROSA) + bien = Text("9%", font=FONT, font_size=150, weight=BOLD, + color=VERDE).move_to(DOWN * 2.05) + + with self.beat(3) as b: + b.play(Create(tacha), run_time=0.45) + b.play(FadeIn(bien, scale=0.6), run_time=0.7) + b.play(Flash(bien, color=VERDE, flash_radius=1.7, num_lines=16), run_time=0.9) + + # --- las mil personas ------------------------------------------------- + puntos = VGroup(*[Dot(radius=RAD, color=APAGADO, fill_opacity=1).move_to(pos(i)) + for i in range(COLS * ROWS)]) + rotulo = Text("1.000 personas", font=FONT, font_size=40, weight=BOLD, + color=WHITE).move_to(UP * 5.55) + + with self.beat(4) as b: + b.play(FadeOut(VGroup(tarjeta, sello, preg, mal, tacha, bien)), run_time=0.5) + b.play(FadeIn(puntos, lag_ratio=0), FadeIn(rotulo, shift=DOWN * 0.2), + run_time=1.1) + + enf = puntos[ENFERMA] + anillo = Circle(radius=0.30, stroke_width=6, color=ROSA).move_to(pos(ENFERMA)) + cajita = RoundedRectangle(corner_radius=0.14, width=2.45, height=0.7, stroke_width=0, + fill_color="#0B0F1A", fill_opacity=0.92) + txt = Text("1 enferma", font=FONT, font_size=34, weight=BOLD, color=ROSA) + etiq = VGroup(cajita, txt).move_to(pos(ENFERMA) + RIGHT * 1.95) + guia = Line(anillo.get_right(), etiq.get_left(), stroke_width=4, color=ROSA) + + with self.beat(5) as b: + b.play(enf.animate.set_color(ROSA).scale(2.2), run_time=0.5) + b.play(Create(anillo), run_time=0.4) + b.play(Create(guia), FadeIn(etiq), run_time=0.5) + + # --- el barrido del test ---------------------------------------------- + barrido = Line(LEFT * 3.6, RIGHT * 3.6, stroke_width=6, color=CELESTE) + barrido.move_to([0, pos(0)[1] + 0.22, 0]) + ley1 = VGroup(Dot(radius=0.12, color=ROSA), + Text("1 positivo verdadero", font=FONT, font_size=36, + weight=BOLD, color=WHITE)).arrange(RIGHT, buff=0.26) + ley1.move_to(DOWN * 2.15) + + with self.beat(6) as b: + b.play(FadeIn(barrido), run_time=0.25) + b.play(barrido.animate.move_to([0, pos(COLS * ROWS - 1)[1] - 0.22, 0]), + run_time=max(0.9, b.floor - 1.5), rate_func=linear) + b.play(FadeOut(barrido), + Flash(anillo, color=VERDE, flash_radius=0.65, num_lines=12), + run_time=0.5) + b.add(ley1) + + # --- los falsos positivos --------------------------------------------- + falsos = VGroup(*[puntos[i] for i in FALSOS]) + + with self.beat(7) as b: + b.play(LaggedStart(*[p.animate.set_color(AMBAR).scale(2.2) for p in falsos], + lag_ratio=0.2), run_time=max(1.3, b.floor - 0.7)) + + ley2 = VGroup(Dot(radius=0.12, color=AMBAR), + Text("10 falsos positivos", font=FONT, font_size=36, + weight=BOLD, color=WHITE)).arrange(RIGHT, buff=0.26) + ley2.move_to(DOWN * 2.78) + + with self.beat(8) as b: + b.play(FadeIn(ley2, shift=UP * 0.2), run_time=0.45) + b.play(*[Indicate(p, color=AMBAR, scale_factor=1.7) for p in falsos], + run_time=1.1) + + # --- los once positivos, en fila -------------------------------------- + marcados = set(FALSOS) | {ENFERMA} + resto = VGroup(*[p for j, p in enumerate(puntos) if j not in marcados]) + elegidos = [puntos[ENFERMA]] + [puntos[i] for i in FALSOS] + cuenta = Text("11 positivos", font=FONT, font_size=52, weight=BOLD, + color=WHITE).move_to(UP * 2.2) + frac = Text("1 de 11 = 9%", font=FONT, font_size=90, weight=BOLD, + color=VERDE).move_to(UP * 0.7) + + with self.beat(9) as b: + b.play(resto.animate.set_opacity(0.12), + FadeOut(VGroup(anillo, guia, etiq, rotulo, ley1, ley2)), run_time=0.5) + b.play(*[p.animate.move_to([(k - 5) * 0.62, 3.35, 0]).scale(2.4) + for k, p in enumerate(elegidos)], run_time=0.9) + b.play(FadeIn(cuenta, shift=UP * 0.2), run_time=0.4) + b.play(FadeIn(frac, scale=0.7), run_time=0.6) + + cierre = VGroup( + Text("Si la enfermedad es rara,", font=FONT, font_size=42, weight=BOLD, color=GRIS), + Text("un positivo suelto", font=FONT, font_size=50, weight=BOLD, color=WHITE), + Text("casi siempre es falso", font=FONT, font_size=50, weight=BOLD, color=AMBAR), + ).arrange(DOWN, buff=0.32).move_to(DOWN * 1.75) + + with self.beat(10) as b: + b.play(FadeOut(resto), run_time=0.4) + b.play(FadeIn(cierre, shift=UP * 0.25), run_time=0.8) + b.play(Flash(frac, color=VERDE, flash_radius=2.2, num_lines=18), run_time=0.9) + + self.finish() diff --git a/scenes/v17_cicloide.py b/scenes/v17_cicloide.py new file mode 100644 index 0000000..5e6d4b9 --- /dev/null +++ b/scenes/v17_cicloide.py @@ -0,0 +1,275 @@ +# -*- coding: utf-8 -*- +"""La braquistocrona: la recta pierde contra la cicloide. +Todo el movimiento sale de la fisica real (caida libre sin rozamiento).""" +import sys, os, math +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +TH1 = 4.0553 # angulo final: da D/H = 3, la curva pasa por debajo +DX = 7.0 +RR = DX / (TH1 - math.sin(TH1)) +HH = RR * (1 - math.cos(TH1)) +X0, Y0 = -3.5, 3.15 +T_C = 1.55 # lo que tarda la cicloide en pantalla +G = RR * (TH1 / T_C) ** 2 # gravedad ajustada a ese tiempo +LL = math.hypot(DX, HH) +AA = G * HH / LL +T_L = math.sqrt(2 * LL / AA) # 2,18 s: la recta llega 40% mas tarde +P0 = np.array([X0, Y0, 0.0]) +P1 = np.array([X0 + DX, Y0 - HH, 0.0]) +UU = (P1 - P0) / LL +VMAX = math.sqrt(4 * G * RR) + +RW = 1.12 # rueda de la bici +XW = -PI * RW +YW = 0.55 +R2, BX, BY = 1.22, 0.0, 0.30 # cuenco de la tautocrona +T_TAU = 2.0 +WW = PI / (2 * T_TAU) + + +def cyc(th): + return np.array([X0 + RR * (th - math.sin(th)), Y0 - RR * (1 - math.cos(th)), 0.0]) + + +def marca(th): + return np.array([XW + RW * (th - math.sin(th)), YW + RW * (1 - math.cos(th)), 0.0]) + + +def cuenco(th): + return np.array([BX + R2 * (th - math.sin(th)) - R2 * PI, + BY + 2 * R2 - R2 * (1 - math.cos(th)), 0.0]) + + +def poli(f, a, b, col, w=8, n=200): + m = VMobject(stroke_color=col, stroke_width=w) + m.set_points_as_corners([f(t) for t in np.linspace(a, b, n)]) + return m + + +class Cicloide(TikTok): + NAME = "cicloide" + + def construct(self): + self.prepare() + chip = self.chip("¿Cuál gana?", AMBAR) + + plata = DashedLine([X0 - 0.8, Y0 + 0.66, 0], [X0 + 1.7, Y0 + 0.66, 0], + stroke_width=3, color=GRIS, dash_length=0.1) + pc = Dot(radius=0.19, color=AMBAR).move_to([X0 - 0.4, Y0 + 0.66, 0]) + pr = Dot(radius=0.19, color=CELESTE).move_to([X0 + 0.08, Y0 + 0.66, 0]) + meta = DashedLine(P1 + UP * 1.35, P1 + DOWN * 0.95, stroke_width=6, + color=VERDE, dash_length=0.14) + rotm = Text("META", font=FONT, font_size=32, weight=BOLD, color=VERDE) + rotm.next_to(meta, UP, buff=0.14) + + leyenda = VGroup( + VGroup(Dot(radius=0.15, color=AMBAR), + Text("curva", font=FONT, font_size=38, weight=BOLD, + color=AMBAR)).arrange(RIGHT, buff=0.22), + VGroup(Dot(radius=0.15, color=CELESTE), + Text("recta", font=FONT, font_size=38, weight=BOLD, + color=CELESTE)).arrange(RIGHT, buff=0.22), + ).arrange(RIGHT, buff=1.3).move_to([0, -1.3, 0]) + + with self.beat(0) as b: + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.4) + b.play(Create(plata), run_time=0.4) + b.play(FadeIn(pc, scale=0.4), FadeIn(pr, scale=0.4), run_time=0.5) + b.play(Create(meta), FadeIn(rotm), FadeIn(leyenda), run_time=0.7) + + recta = Line(P0, P1, stroke_width=8, color=CELESTE) + curva = poli(cyc, 0, TH1, AMBAR) + + with self.beat(1) as b: + b.play(Create(recta), run_time=0.9) + b.play(Create(curva), run_time=max(0.9, b.floor - 1.4)) + + inter = Text("?", font=FONT, font_size=115, weight=BOLD, + color=WHITE).move_to([0.0, 1.62, 0]) + + with self.beat(2) as b: + b.play(FadeIn(inter, scale=0.5), run_time=0.5) + b.play(Indicate(inter, scale_factor=1.25, color=AMBAR), run_time=0.9) + + rot = Text("el más corto", font=FONT, font_size=40, weight=BOLD, + color=CELESTE).move_to([-0.15, 3.02, 0]) + + with self.beat(3) as b: + b.play(FadeOut(inter), run_time=0.3) + b.play(recta.animate.set_stroke(width=12), FadeIn(rot, shift=UP * 0.2), + run_time=0.55) + b.play(ShowPassingFlash(recta.copy().set_stroke(WHITE, 13), time_width=0.5), + run_time=1.0) + b.play(recta.animate.set_stroke(width=8), run_time=0.3) + + # --- la carrera -------------------------------------------------------- + T = ValueTracker(0.0) + + def up_c(m): + t = min(T.get_value(), T_C) + m.move_to(cyc(min(t * math.sqrt(G / RR), TH1))) + + def up_r(m): + t = min(T.get_value(), T_L) + m.move_to(P0 + UU * (0.5 * AA * t * t)) + + med = VGroup(Circle(radius=0.34, stroke_width=0, fill_color=AMBAR, fill_opacity=1), + Text("1º", font=FONT, font_size=34, weight=BOLD, color="#0B0F1A")) + med.move_to(P1 + UP * 0.72).set_opacity(0) + med.add_updater(lambda m: m.set_opacity(1.0 if T.get_value() >= T_C else 0.0)) + + with self.beat(4) as b: + b.play(FadeOut(rot), FadeOut(plata), pc.animate.move_to(P0), + pr.animate.move_to(P0), run_time=0.5) + ya = Text("¡LARGA!", font=FONT, font_size=66, weight=BOLD, + color=VERDE).move_to([0, 1.7, 0]) + b.play(FadeIn(ya, scale=1.7), run_time=0.3) + b.play(FadeOut(ya), run_time=0.22) + pc.add_updater(up_c) + pr.add_updater(up_r) + b.add(med) + b.play(T.animate.set_value(T_L), run_time=T_L, rate_func=linear) + pc.clear_updaters(); pr.clear_updaters(); med.clear_updaters() + + nivel = DashedLine([X0 - 0.2, Y0 - HH, 0], [X0 + DX + 0.2, Y0 - HH, 0], + stroke_width=4, color=GRIS, dash_length=0.12) + fondo = cyc(PI) + nota = Text("pasa por debajo de la meta", font=FONT, font_size=36, weight=BOLD, + color=ROSA).move_to([0.3, -0.95, 0]) + flecha = Arrow(nota.get_top() + RIGHT * 0.9, fondo + DOWN * 0.22, buff=0.06, + color=ROSA, stroke_width=6, max_tip_length_to_length_ratio=0.2) + gap = VGroup( + Text("la recta tardó", font=FONT, font_size=38, weight=BOLD, color=WHITE), + Text("40% más", font=FONT, font_size=64, weight=BOLD, color=CELESTE), + ).arrange(RIGHT, buff=0.3).move_to([0.0, -2.15, 0]) + + with self.beat(5) as b: + b.play(FadeOut(leyenda), Create(nivel), run_time=0.45) + b.play(FadeIn(nota, shift=UP * 0.2), GrowArrow(flecha), run_time=0.6) + b.play(FadeIn(gap, shift=UP * 0.2), run_time=0.55) + + # --- por que gana: velocidad temprana ---------------------------------- + riel_c = Rectangle(width=6.2, height=0.32, stroke_width=0, fill_color="#1B2233", + fill_opacity=1).move_to([0.0, -1.30, 0]) + riel_r = riel_c.copy().move_to([0.0, -2.20, 0]) + bar_c = Rectangle(width=0.02, height=0.32, stroke_width=0, fill_color=AMBAR, + fill_opacity=1).move_to(riel_c.get_left(), LEFT) + bar_r = Rectangle(width=0.02, height=0.32, stroke_width=0, fill_color=CELESTE, + fill_opacity=1).move_to(riel_r.get_left(), LEFT) + lab_c = Text("curva", font=FONT, font_size=30, weight=BOLD, color=AMBAR) + lab_r = Text("recta", font=FONT, font_size=30, weight=BOLD, color=CELESTE) + lab_c.next_to(riel_c, LEFT, buff=0.18) + lab_r.next_to(riel_r, LEFT, buff=0.18) + izq_c, izq_r = riel_c.get_left()[0], riel_r.get_left()[0] + + def barra(m, v, x0, y): + w = max(0.02, 6.2 * v / VMAX) + m.stretch_to_fit_width(w) + m.move_to([x0 + w / 2, y, 0]) + + def ub_c(m): + t = min(T.get_value(), T_C) + th = t * math.sqrt(G / RR) + barra(m, math.sqrt(max(0.0, 2 * G * RR * (1 - math.cos(th)))), izq_c, -1.30) + + def ub_r(m): + barra(m, AA * min(T.get_value(), T_L), izq_r, -2.20) + + with self.beat(6) as b: + b.play(FadeOut(VGroup(nivel, flecha, nota, gap, med)), run_time=0.35) + T.set_value(0.0) + b.play(pc.animate.move_to(P0), pr.animate.move_to(P0), + FadeIn(VGroup(riel_c, riel_r, lab_c, lab_r, bar_c, bar_r)), run_time=0.45) + pc.add_updater(up_c); pr.add_updater(up_r) + bar_c.add_updater(ub_c); bar_r.add_updater(ub_r) + b.play(T.animate.set_value(T_L), run_time=max(1.8, b.floor - 1.1), + rate_func=linear) + for m in (pc, pr, bar_c, bar_r): + m.clear_updaters() + + # --- la rueda de la bici ------------------------------------------------ + viejo = VGroup(recta, curva, meta, rotm, pc, pr, + riel_c, riel_r, lab_c, lab_r, bar_c, bar_r) + piso = Line([-3.7, YW, 0], [3.7, YW, 0], stroke_width=6, color="#3A5487") + TH = ValueTracker(0.0) + + def dibujar_rueda(): + th = TH.get_value() + c = np.array([XW + RW * th, YW + RW, 0.0]) + g = VGroup(Circle(radius=RW, stroke_width=6, color=CELESTE).move_to(c)) + for k in range(3): + a = -th - PI / 2 + k * TAU / 3 + g.add(Line(c, c + RW * np.array([math.cos(a), math.sin(a), 0.0]), + stroke_width=4, color="#3A5487")) + return g + + rueda = always_redraw(dibujar_rueda) + clavo = always_redraw(lambda: Dot(radius=0.14, color=AMBAR).move_to(marca(TH.get_value()))) + rastro = TracedPath(lambda: marca(TH.get_value()), stroke_color=AMBAR, stroke_width=8) + nom = Text("CICLOIDE", font=FONT, font_size=66, weight=BOLD, + color=AMBAR).move_to([0, -1.15, 0]) + + with self.beat(7) as b: + b.play(FadeOut(viejo), run_time=0.4) + b.play(Create(piso), run_time=0.3) + b.add(rastro, rueda, clavo) + b.play(TH.animate.set_value(TAU), run_time=max(1.6, b.floor - 1.5), + rate_func=linear) + b.remove(rueda, clavo, rastro) + arco = poli(marca, 0, TAU, AMBAR) + b.add(arco) + b.play(FadeIn(nom, shift=UP * 0.2), run_time=0.45) + + # --- la tautocrona ------------------------------------------------------ + tazon = poli(cuenco, 0, TAU, AMBAR) + TH0 = [0.30 * PI, 0.56 * PI, 0.82 * PI] + cols = [ROSA, CELESTE, VERDE] + bolas = VGroup(*[Dot(radius=r, color=c).move_to(cuenco(t)) + for t, c, r in zip(TH0, cols, (0.22, 0.175, 0.13))]) + guias = VGroup(*[DashedLine([-4.1, cuenco(t)[1], 0], cuenco(t), stroke_width=3, + color=c, dash_length=0.1) + for t, c in zip(TH0, cols)]) + + with self.beat(8) as b: + b.play(FadeOut(VGroup(nom, piso)), run_time=0.3) + b.play(Transform(arco, tazon), run_time=0.9) + b.play(LaggedStart(*[FadeIn(d, scale=0.5) for d in bolas], lag_ratio=0.25), + run_time=0.8) + b.play(Create(guias), run_time=0.5) + + TT = ValueTracker(0.0) + + def soltar(th0): + def u(m): + c = math.cos(th0 / 2) * math.cos(WW * TT.get_value()) + m.move_to(cuenco(2 * math.acos(max(-1.0, min(1.0, c))))) + return u + + with self.beat(9) as b: + b.play(FadeOut(guias), run_time=0.25) + for d, t0 in zip(bolas, TH0): + d.add_updater(soltar(t0)) + b.play(TT.animate.set_value(T_TAU), run_time=T_TAU, rate_func=linear) + for d in bolas: + d.clear_updaters() + juntas = Text("las tres, juntas", font=FONT, font_size=58, weight=BOLD, + color=VERDE).move_to([0, -1.5, 0]) + b.play(Flash(bolas[0], color=WHITE, flash_radius=0.9, num_lines=18), + FadeIn(juntas, shift=UP * 0.25), run_time=0.7) + + cierre = VGroup( + Text("1696", font=FONT, font_size=76, weight=BOLD, color=AMBAR), + Text("Bernoulli desafía", font=FONT, font_size=44, weight=BOLD, color=WHITE), + Text("a los matemáticos", font=FONT, font_size=44, weight=BOLD, color=WHITE), + Text("Newton lo resuelve", font=FONT, font_size=46, weight=BOLD, color=VERDE), + Text("esa misma noche", font=FONT, font_size=46, weight=BOLD, color=VERDE), + ).arrange(DOWN, buff=0.26).move_to(UP * 0.75) + + with self.beat(10) as b: + b.play(FadeOut(VGroup(arco, bolas, juntas)), run_time=0.4) + b.play(FadeIn(cierre[:3], shift=UP * 0.25), run_time=0.7) + b.play(FadeIn(cierre[3:], shift=UP * 0.25), run_time=0.7) + + self.finish() diff --git a/scenes/v18_dados.py b/scenes/v18_dados.py new file mode 100644 index 0000000..f0c2940 --- /dev/null +++ b/scenes/v18_dados.py @@ -0,0 +1,189 @@ +# -*- coding: utf-8 -*- +"""Dados no transitivos: A gana a B, B gana a C y C gana a A, siempre 5 de 9.""" +import sys, os +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +ROJO = ROSA +CARAS = {"rojo": [2, 4, 9], "celeste": [1, 6, 8], "verde": [3, 5, 7]} +COL = {"rojo": ROJO, "celeste": CELESTE, "verde": VERDE} +CELL = 1.30 + + +def dado(nombre, s=0.62): + vals = CARAS[nombre] * 2 + col = COL[nombre] + caras = VGroup() + for v in vals: + f = RoundedRectangle(corner_radius=0.11, width=s, height=s, stroke_width=3, + stroke_color=col, fill_color="#121C33", fill_opacity=1) + caras.add(VGroup(f, Text(str(v), font=FONT, font_size=32, weight=BOLD, + color=col).move_to(f))) + caras.arrange_in_grid(rows=2, cols=3, buff=0.08) + rot = Text(nombre, font=FONT, font_size=30, weight=BOLD, color=col) + rot.next_to(caras, DOWN, buff=0.18) + return VGroup(caras, rot) + + +def duelo(na, nb, centro): + """Tabla 3x3 con los nueve duelos. Cada celda pintada del que gana.""" + av, bv = CARAS[na], CARAS[nb] + ca, cb = COL[na], COL[nb] + celdas, gana = VGroup(), 0 + for i, a in enumerate(av): + for j, bq in enumerate(bv): + ok = a > bq + gana += ok + r = RoundedRectangle(corner_radius=0.1, width=CELL, height=CELL, stroke_width=4, + stroke_color="#0B0F1A", fill_color=ca if ok else cb, + fill_opacity=0.92) + t = Text(str(max(a, bq)), font=FONT, font_size=42, weight=BOLD, color="#0B0F1A") + c = VGroup(r, t.move_to(r)) + c.move_to(centro + np.array([(j - 1) * (CELL + 0.07), + -(i - 1) * (CELL + 0.07), 0.0])) + celdas.add(c) + d = CELL + 0.07 + fuera = d + CELL / 2 + 0.36 # el rotulo va por fuera de la tabla + cab = VGroup(*[Text(str(v), font=FONT, font_size=38, weight=BOLD, color=cb) + .move_to(centro + np.array([(j - 1) * d, fuera, 0.0])) + for j, v in enumerate(bv)]) + lat = VGroup(*[Text(str(v), font=FONT, font_size=38, weight=BOLD, color=ca) + .move_to(centro + np.array([-fuera, -(i - 1) * d, 0.0])) + for i, v in enumerate(av)]) + return celdas, cab, lat, gana + + +class Dados(TikTok): + NAME = "dados" + + def construct(self): + self.prepare() + chip = self.chip("Intuición rota", ROJO) + + dds = VGroup(*[dado(n) for n in ("rojo", "celeste", "verde")]) + dds.arrange(RIGHT, buff=0.55).move_to(UP * 4.15) + + with self.beat(0) as b: + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.4) + b.play(LaggedStart(*[FadeIn(d, shift=DOWN * 0.3) for d in dds], + lag_ratio=0.25), run_time=1.1) + dedo = Triangle(stroke_width=0, fill_color=WHITE, fill_opacity=1).scale(0.22) + dedo.rotate(PI).next_to(dds[1], DOWN, buff=0.35) + b.play(FadeIn(dedo, shift=UP * 0.3), run_time=0.5) + + vos = Text("vos", font=FONT, font_size=34, weight=BOLD, color=WHITE) + vos.next_to(dedo, DOWN, buff=0.15) + yo = Text("yo elijo después", font=FONT, font_size=40, weight=BOLD, color=AMBAR) + yo.move_to(UP * 1.45) + + with self.beat(1) as b: + b.play(FadeIn(vos), run_time=0.35) + b.play(FadeIn(yo, shift=UP * 0.2), run_time=0.6) + + gran = Text("56%", font=FONT, font_size=190, weight=BOLD, color=AMBAR) + gran.move_to(DOWN * 0.55) + pie = Text("gano yo", font=FONT, font_size=46, weight=BOLD, color=WHITE) + pie.next_to(gran, DOWN, buff=0.25) + + with self.beat(2) as b: + b.play(FadeOut(VGroup(dedo, vos, yo)), run_time=0.3) + b.play(FadeIn(gran, scale=0.6), run_time=0.7) + b.play(FadeIn(pie, shift=UP * 0.2), run_time=0.4) + b.play(Flash(gran, color=AMBAR, flash_radius=2.6, num_lines=20), run_time=0.8) + + with self.beat(3) as b: + b.play(FadeOut(VGroup(gran, pie)), run_time=0.35) + b.play(dds[1].animate.set_opacity(0.25), dds[2].animate.set_opacity(0.25), + run_time=0.4) + grande = dds[0].copy().scale(2.0).move_to(UP * 1.2) + b.play(TransformFromCopy(dds[0], grande), run_time=0.8) + + with self.beat(4) as b: + b.play(FadeOut(grande), dds[1].animate.set_opacity(1), + dds[2].animate.set_opacity(1), run_time=0.5) + g2 = dds[1].copy().scale(1.7).move_to(UP * 1.5 + LEFT * 1.9) + g3 = dds[2].copy().scale(1.7).move_to(UP * 1.5 + RIGHT * 1.9) + b.play(TransformFromCopy(dds[1], g2), run_time=0.6) + b.play(TransformFromCopy(dds[2], g3), run_time=0.6) + + # --- los tres cruces ---------------------------------------------------- + centro = np.array([0.0, 0.42, 0.0]) + + def cruce(beat, na, nb, previo): + celdas, cab, lat, gana = duelo(na, nb, centro) + marca = VGroup( + Text(na, font=FONT, font_size=42, weight=BOLD, color=COL[na]), + Text(f"gana {gana} de 9", font=FONT, font_size=42, weight=BOLD, color=WHITE), + ).arrange(RIGHT, buff=0.25).move_to(DOWN * 2.45) + if previo: + beat.play(FadeOut(previo), run_time=0.3) + beat.play(FadeIn(VGroup(cab, lat)), run_time=0.35) + beat.play(LaggedStart(*[FadeIn(c, scale=0.6) for c in celdas], + lag_ratio=0.09), run_time=max(1.0, beat.floor - 1.5)) + beat.play(FadeIn(marca, shift=UP * 0.2), run_time=0.45) + return VGroup(celdas, cab, lat, marca) + + with self.beat(5) as b: + b.play(FadeOut(VGroup(g2, g3)), run_time=0.3) + t1 = cruce(b, "rojo", "celeste", None) + + with self.beat(6) as b: + t2 = cruce(b, "celeste", "verde", t1) + + with self.beat(7) as b: + b.play(FadeOut(t2), run_time=0.35) + preg = VGroup( + Text("rojo", font=FONT, font_size=54, weight=BOLD, color=ROJO), + Text("→", font=FONT, font_size=54, weight=BOLD, color=WHITE), + Text("verde", font=FONT, font_size=54, weight=BOLD, color=VERDE), + Text("?", font=FONT, font_size=70, weight=BOLD, color=AMBAR), + ).arrange(RIGHT, buff=0.3).move_to(UP * 1.6) + b.play(FadeIn(preg, shift=UP * 0.25), run_time=0.6) + b.play(Indicate(preg[3], color=AMBAR, scale_factor=1.4), run_time=0.7) + + with self.beat(8) as b: + no = Text("NO", font=FONT, font_size=96, weight=BOLD, color=ROSA).move_to(UP * 1.6) + b.play(FadeOut(preg), run_time=0.25) + b.play(FadeIn(no, scale=1.8), run_time=0.4) + b.play(FadeOut(no), run_time=0.3) + t3 = cruce(b, "verde", "rojo", None) + + # --- el circulo ---------------------------------------------------------- + with self.beat(9) as b: + b.play(FadeOut(t3), FadeOut(dds), run_time=0.4) + vert = {"rojo": np.array([0.0, 4.1, 0.0]), + "celeste": np.array([-2.55, 0.5, 0.0]), + "verde": np.array([2.55, 0.5, 0.0])} + nodos = VGroup() + for n, p in vert.items(): + nodos.add(VGroup( + Circle(radius=0.86, stroke_width=6, color=COL[n], + fill_color="#121C33", fill_opacity=1).move_to(p), + Text(n, font=FONT, font_size=27, weight=BOLD, color=COL[n]).move_to(p))) + flechas = VGroup() + for a, c in (("rojo", "celeste"), ("celeste", "verde"), ("verde", "rojo")): + pa, pb = vert[a], vert[c] + d = (pb - pa) / np.linalg.norm(pb - pa) + f = CurvedArrow(pa + d * 1.02, pb - d * 1.02, angle=-0.55, + color=COL[a], stroke_width=7, tip_length=0.26) + flechas.add(f) + b.play(LaggedStart(*[GrowFromCenter(n) for n in nodos], lag_ratio=0.2), + run_time=0.8) + b.play(LaggedStart(*[Create(f) for f in flechas], lag_ratio=0.3), + run_time=max(0.9, b.floor - 1.6)) + cinco = Text("5 de 9 siempre", font=FONT, font_size=44, weight=BOLD, color=AMBAR) + cinco.move_to(DOWN * 1.35) + b.play(FadeIn(cinco, shift=UP * 0.2), run_time=0.45) + + with self.beat(10) as b: + cierre = VGroup( + Text("El truco:", font=FONT, font_size=44, weight=BOLD, color=WHITE), + Text("elegí SEGUNDO", font=FONT, font_size=66, weight=BOLD, color=AMBAR), + ).arrange(DOWN, buff=0.26).move_to(DOWN * 1.65) + b.play(FadeOut(cinco), run_time=0.3) + b.play(FadeIn(cierre, shift=UP * 0.25), run_time=0.7) + b.play(*[Indicate(f, color=WHITE, scale_factor=1.05) for f in flechas], + run_time=0.9) + + self.finish() diff --git a/scenes/v1_montyhall.py b/scenes/v1_montyhall.py new file mode 100644 index 0000000..bdaf6c5 --- /dev/null +++ b/scenes/v1_montyhall.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +import sys, os +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +DOOR_Y, DW, DH = 4.0, 2.5, 3.7 +XS = [-2.85, 0.0, 2.85] + + +class MontyHall(TikTok): + NAME = "montyhall" + + def door(self, n, x): + face = RoundedRectangle(corner_radius=0.18, width=DW, height=DH, + stroke_color="#2E3A55", stroke_width=6, + fill_color="#16203A", fill_opacity=1) + num = Text(str(n), font=FONT, font_size=104, weight=BOLD, color="#5B6B8C") + knob = Dot(radius=0.1, color="#5B6B8C").move_to(face.get_right() + LEFT * 0.36) + d = VGroup(face, num, knob).move_to([x, DOOR_Y, 0]) + d.face, d.num, d.knob = face, num, knob + return d + + def badge(self, text, color, fs=30): + t = Text(text, font=FONT, font_size=fs, weight=BOLD, color="#0B0F1A") + box = RoundedRectangle(corner_radius=0.2, width=t.width + 0.5, height=t.height + 0.42, + stroke_width=0, fill_color=color, fill_opacity=1) + return VGroup(box, t) + + def car_icon(self, color=VERDE): + body = RoundedRectangle(corner_radius=0.14, width=1.6, height=0.6, + stroke_width=0, fill_color=color, fill_opacity=1) + roof = RoundedRectangle(corner_radius=0.12, width=0.92, height=0.48, + stroke_width=0, fill_color=color, fill_opacity=1) + roof.next_to(body, UP, buff=-0.08) + w1 = Dot(radius=0.19, color="#0B0F1A").move_to(body.get_bottom() + LEFT * 0.48) + w2 = Dot(radius=0.19, color="#0B0F1A").move_to(body.get_bottom() + RIGHT * 0.48) + return VGroup(roof, body, w1, w2) + + def goat_icon(self, color="#94A3B8"): + head = Ellipse(width=1.05, height=0.72, stroke_width=0, fill_color=color, fill_opacity=1) + snout = Ellipse(width=0.5, height=0.36, stroke_width=0, fill_color=color, fill_opacity=1) + snout.move_to(head.get_bottom() + DOWN * 0.1) + h1 = ArcBetweenPoints(head.get_top() + LEFT * 0.26, head.get_top() + LEFT * 0.62 + UP * 0.42, + angle=-1.1, stroke_width=8, color=color) + h2 = ArcBetweenPoints(head.get_top() + RIGHT * 0.26, head.get_top() + RIGHT * 0.62 + UP * 0.42, + angle=1.1, stroke_width=8, color=color) + e1 = Dot(radius=0.07, color="#0B0F1A").move_to(head.get_center() + LEFT * 0.22 + UP * 0.06) + e2 = Dot(radius=0.07, color="#0B0F1A").move_to(head.get_center() + RIGHT * 0.22 + UP * 0.06) + return VGroup(h1, h2, head, snout, e1, e2) + + def prize(self, kind, x): + if kind == "auto": + g = VGroup(self.car_icon(), self.badge("AUTO", VERDE)) + else: + g = VGroup(self.goat_icon(), self.badge("CABRA", "#94A3B8")) + g.arrange(DOWN, buff=0.3) + return g.move_to([x, DOOR_Y, 0]) + + def construct(self): + self.prepare() + chip = self.chip("¿Cambiarías de puerta?") + doors = VGroup(*[self.door(i + 1, XS[i]) for i in range(3)]) + + with self.beat(0) as b: + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.5) + b.play(LaggedStart(*[GrowFromCenter(d) for d in doors], lag_ratio=0.25), run_time=1.2) + h1 = VGroup(self.car_icon().scale(0.85), + Text("×1", font=FONT, font_size=46, weight=BOLD, color=VERDE) + ).arrange(RIGHT, buff=0.35).move_to(UP * 1.3) + b.play(FadeIn(h1, shift=UP * 0.2), run_time=0.5) + + with self.beat(1) as b: + h2 = VGroup(self.goat_icon().scale(0.85), + Text("×2", font=FONT, font_size=46, weight=BOLD, color="#94A3B8") + ).arrange(RIGHT, buff=0.35) + h2.next_to(h1, DOWN, buff=0.55) + b.play(FadeIn(h2, shift=UP * 0.2), run_time=0.6) + b.wait(0.5) + b.play(FadeOut(VGroup(h1, h2)), run_time=0.4) + + with self.beat(2) as b: + pick = Text("TU ELECCIÓN", font=FONT, font_size=38, weight=BOLD, color=AMBAR) + arrow = Arrow(doors[0].get_bottom() + DOWN * 1.3, doors[0].get_bottom() + DOWN * 0.12, + buff=0, color=AMBAR, stroke_width=10) + pick.next_to(arrow, DOWN, buff=0.18) + b.play(doors[0].face.animate.set_stroke(AMBAR, 11), + doors[0].num.animate.set_color(AMBAR), run_time=0.5) + b.play(GrowArrow(arrow), FadeIn(pick), run_time=0.5) + picked = VGroup(pick, arrow) + + with self.beat(3) as b: + goat = self.prize("cabra", XS[2]) + b.play(doors[2].face.animate.set_fill("#0E1526", 1).set_stroke("#2E3A55", 4), + FadeOut(doors[2].num), FadeOut(doors[2].knob), run_time=0.7) + b.play(FadeIn(goat, scale=0.75), run_time=0.7) + doors[2].remove(doors[2].num, doors[2].knob) + b.play(VGroup(doors[2], goat).animate.set_opacity(0.35), run_time=0.5) + + with self.beat(4) as b: + q = Text("¿1 o 2?", font=FONT, font_size=82, weight=BOLD, color=WHITE).move_to(UP * 1.0) + b.play(FadeOut(picked), run_time=0.3) + b.play(Write(q), doors[1].face.animate.set_stroke(CELESTE, 10), + doors[1].num.animate.set_color(CELESTE), run_time=1.0) + + with self.beat(5) as b: + fifty = Text("50% / 50%", font=FONT, font_size=68, weight=BOLD, color=GRIS) + fifty.move_to(DOWN * 1.5) + cross = VGroup( + Line(fifty.get_corner(UL), fifty.get_corner(DR), stroke_width=14, color=ROSA), + Line(fifty.get_corner(DL), fifty.get_corner(UR), stroke_width=14, color=ROSA), + ) + b.play(FadeIn(fifty), run_time=0.5) + b.wait(0.6) + b.play(Create(cross), run_time=0.6) + b.play(FadeOut(VGroup(fifty, cross, q)), run_time=0.5) + + with self.beat(6) as b: + f1 = MathTex(r"\tfrac{1}{3}", color=AMBAR).scale(2.6).next_to(doors[0], DOWN, buff=0.7) + cap1 = Text("lo que tenías al elegir", font=FONT, font_size=34, color=GRIS) + cap1.next_to(f1, DOWN, buff=0.45).set_x(0) + b.play(Write(f1), run_time=0.8) + b.play(FadeIn(cap1), run_time=0.5) + + with self.beat(7) as b: + brace = Brace(VGroup(doors[1], doors[2]), DOWN, color=CELESTE, buff=0.28) + f2 = MathTex(r"\tfrac{2}{3}", color=CELESTE).scale(2.6).next_to(brace, DOWN, buff=0.25) + b.play(FadeOut(cap1), run_time=0.25) + b.play(GrowFromCenter(brace), run_time=0.5) + b.play(Write(f2), run_time=0.7) + + with self.beat(8) as b: + dest = f1.get_center() + RIGHT * (XS[1] - XS[0]) + b.play(FadeOut(brace), run_time=0.3) + b.play(f2.animate.move_to(dest), run_time=1.2) + b.play(Flash(f2, color=CELESTE, line_length=0.6, num_lines=18, flash_radius=1.4), + doors[1].face.animate.set_fill("#123A57", 1), run_time=0.9) + + with self.beat(9) as b: + b.play(FadeOut(VGroup(doors, f1, f2, goat)), run_time=0.5) + rows = [] + for lbl, pct, col in (("QUEDARSE", 0.333, ROSA), ("CAMBIAR", 0.667, VERDE)): + name = Text(lbl, font=FONT, font_size=46, weight=BOLD, color=col) + track = RoundedRectangle(corner_radius=0.12, width=7.0, height=0.85, stroke_width=0, + fill_color="#1B2233", fill_opacity=1) + fill = RoundedRectangle(corner_radius=0.12, width=7.0 * pct, height=0.85, + stroke_width=0, fill_color=col, fill_opacity=1) + fill.move_to(track.get_left(), LEFT) + val = Text(f"{round(pct*100)}%", font=FONT, font_size=58, weight=BOLD, color=col) + rows.append(VGroup(name, VGroup(track, fill), val).arrange(DOWN, buff=0.25)) + board = VGroup(*rows).arrange(DOWN, buff=1.0).move_to(UP * 2.2) + b.play(*[FadeIn(r[0]) for r in rows], *[FadeIn(r[1][0]) for r in rows], run_time=0.5) + for r in rows: + f, w = r[1][1], r[1][1].width + f.stretch_to_fit_width(0.002).move_to(r[1][0].get_left(), LEFT) + b.play(f.animate.stretch_to_fit_width(w).move_to(r[1][0].get_left(), LEFT), + FadeIn(r[2]), run_time=0.8) + b.wait(0.3) + + with self.beat(10) as b: + cta = self.fit(Text("CAMBIÁ SIEMPRE", font=FONT, font_size=70, + weight=BOLD, color=AMBAR), 7.9).move_to(DOWN * 1.9) + b.play(Write(cta), run_time=0.9) + b.play(Circumscribe(cta, color=AMBAR, buff=0.35, stroke_width=8), run_time=1.1) + + self.finish() diff --git a/scenes/v2_nueves.py b/scenes/v2_nueves.py new file mode 100644 index 0000000..eb9f198 --- /dev/null +++ b/scenes/v2_nueves.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- +import sys, os +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + + +class Nueves(TikTok): + NAME = "nueves" + + def construct(self): + self.prepare() + chip = self.chip("Matemática que enoja", ROSA) + + # --- el numero --- + with self.beat(0) as b: + head = Text("0,", font=FONT, font_size=110, weight=BOLD, color=WHITE) + nines = VGroup(*[Text("9", font=FONT, font_size=110, weight=BOLD, color=AMBAR) + for _ in range(6)]) + dots = Text("…", font=FONT, font_size=110, weight=BOLD, color=AMBAR) + num = VGroup(head, *nines, dots).arrange(RIGHT, buff=0.06) + self.fit(num, 8.0).move_to(UP * 4.5) + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.45) + b.play(FadeIn(head), run_time=0.3) + b.play(LaggedStart(*[FadeIn(n, shift=DOWN * 0.25) for n in nines], + lag_ratio=0.5), run_time=1.1) + b.play(Write(dots), run_time=0.4) + + # --- es igual a 1 --- + with self.beat(1) as b: + eq = MathTex("=", color=WHITE).scale(2.2).move_to(UP * 2.4) + one = MathTex("1", color=VERDE).scale(3.2).next_to(eq, DOWN, buff=0.35) + b.play(Write(eq), run_time=0.4) + b.play(FadeIn(one, scale=0.5), run_time=0.5) + b.play(Flash(one, color=VERDE, line_length=0.5, num_lines=16, flash_radius=1.1), + run_time=0.7) + equals = VGroup(eq, one) + + # --- la objecion --- + with self.beat(2) as b: + bubble = RoundedRectangle(corner_radius=0.35, width=7.4, height=1.5, + stroke_color=GRIS, stroke_width=4, + fill_color="#151C2E", fill_opacity=1).move_to(UP * 0.9) + obj = self.fit(Text("«pero le falta un poquito»", font=FONT, font_size=42, + weight=BOLD, color=GRIS), 6.9).move_to(bubble) + b.play(FadeOut(equals), run_time=0.3) + b.play(FadeIn(bubble), Write(obj), run_time=1.0) + + # --- decime cuanto --- + with self.beat(3) as b: + q = MathTex(r"1 - 0{,}999\ldots \;=\; ?", color=WHITE).scale(1.6).move_to(UP * 1.5) + q[0][-1].set_color(ROSA) + b.play(FadeOut(VGroup(bubble, obj)), run_time=0.3) + b.play(Write(q), run_time=1.1) + b.play(Indicate(q[0][-1], color=ROSA, scale_factor=1.6), run_time=0.8) + + # --- la recta: no hay lugar en el medio --- + line = Line(LEFT * 3.4, RIGHT * 3.4, stroke_width=7, color="#3A4766").move_to(UP * 0.55) + dA = Dot(line.get_left() + RIGHT * 1.4, radius=0.15, color=AMBAR) + dB = Dot(line.get_right(), radius=0.15, color=VERDE) + lA = MathTex("0{,}999\\ldots", color=AMBAR).scale(1.0).next_to(dA, DOWN, buff=0.45) + lB = MathTex("1", color=VERDE).scale(1.4).next_to(dB, DOWN, buff=0.45) + with self.beat(4) as b: + b.play(FadeOut(q), run_time=0.25) + b.play(Create(line), run_time=0.5) + b.play(FadeIn(dA), FadeIn(dB), Write(lA), Write(lB), run_time=0.8) + brace = Brace(Line(dA.get_center(), dB.get_center()), UP, color=ROSA, buff=0.15) + ask = Text("¿qué número entra acá?", font=FONT, font_size=34, + weight=BOLD, color=ROSA).next_to(brace, UP, buff=0.2) + self.fit(ask, 7.5) + b.play(GrowFromCenter(brace), FadeIn(ask), run_time=0.8) + gap = VGroup(brace, ask) + + with self.beat(5) as b: + b.play(dA.animate.move_to(dB.get_center()), + lA.animate.next_to(dB, DOWN, buff=0.45).shift(LEFT * 1.3), + FadeOut(gap), run_time=1.2) + none = Text("nada: es el mismo punto", font=FONT, font_size=40, + weight=BOLD, color=VERDE).move_to(DOWN * 1.9) + b.play(Flash(dB, color=VERDE, line_length=0.6, num_lines=18, flash_radius=1.2), + FadeIn(self.fit(none, 7.8), shift=UP * 0.2), run_time=0.9) + recta = VGroup(line, dA, dB, lA, lB, none) + + # --- la demostracion --- + with self.beat(6) as b: + p1 = MathTex(r"\frac{1}{3} = 0{,}333\ldots", color=WHITE).scale(1.9).move_to(UP * 3.7) + b.play(FadeOut(VGroup(recta, num, head, dots, *nines)), run_time=0.45) + b.play(Write(p1), run_time=1.1) + + with self.beat(7) as b: + x3 = Text("× 3", font=FONT, font_size=60, weight=BOLD, color=AMBAR).move_to(UP * 1.75) + ar = VGroup( + Arrow(UP * 2.75 + LEFT * 2.1, UP * 0.75 + LEFT * 2.1, buff=0, color=AMBAR, stroke_width=8), + Arrow(UP * 2.75 + RIGHT * 2.1, UP * 0.75 + RIGHT * 2.1, buff=0, color=AMBAR, stroke_width=8), + ) + b.play(FadeIn(x3, scale=0.6), run_time=0.5) + b.play(*[GrowArrow(a) for a in ar], run_time=0.7) + + with self.beat(8) as b: + p2 = MathTex(r"\frac{3}{3} = 0{,}999\ldots", color=WHITE).scale(1.9).move_to(DOWN * 0.55) + p2[0][0].set_color(VERDE); p2[0][2].set_color(VERDE) + b.play(Write(p2), run_time=1.3) + b.play(Circumscribe(p2, color=CELESTE, buff=0.3, stroke_width=6), run_time=0.9) + + with self.beat(9) as b: + final = MathTex(r"1 = 0{,}999\ldots", color=VERDE).scale(2.3).move_to(DOWN * 2.6) + b.play(FadeOut(VGroup(x3, ar)), run_time=0.3) + b.play(TransformFromCopy(p2, final), run_time=1.2) + b.play(Flash(final, color=VERDE, line_length=0.7, num_lines=22, flash_radius=2.2), + run_time=0.9) + + with self.beat(10) as b: + b.play(FadeOut(VGroup(p1, p2)), run_time=0.4) + cta = self.fit(Text("¿te convencí?", font=FONT, font_size=72, weight=BOLD, + color=AMBAR), 7.9).move_to(UP * 2.2) + sub = Text("escribilo en los comentarios", font=FONT, font_size=40, + color=GRIS).next_to(cta, DOWN, buff=0.4) + b.play(Write(cta), run_time=0.8) + b.play(FadeIn(sub, shift=UP * 0.2), run_time=0.5) + + self.finish() diff --git a/scenes/v3_cumple.py b/scenes/v3_cumple.py new file mode 100644 index 0000000..ba9dd79 --- /dev/null +++ b/scenes/v3_cumple.py @@ -0,0 +1,143 @@ +# -*- coding: utf-8 -*- +import sys, os, itertools +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +N = 23 +CX, CY, R = 0.0, 2.95, 2.78 + + +def prob(n): + p = 1.0 + for k in range(n): + p *= (365 - k) / 365 + return 1 - p + + +class Cumple(TikTok): + NAME = "cumple" + + def construct(self): + self.prepare() + chip = self.chip("Paradoja del cumpleaños", CELESTE) + + pts = [np.array([CX + R * np.cos(a), CY + R * np.sin(a), 0]) + for a in np.linspace(PI / 2, PI / 2 + TAU, N, endpoint=False)] + people = VGroup(*[Dot(p, radius=0.17, color="#8FB8FF") for p in pts]) + + with self.beat(0) as b: + q = self.fit(Text("¿cuánta gente hace falta?", font=FONT, font_size=50, + weight=BOLD, color=WHITE), 8.0).move_to(UP * 3.3) + q2 = self.fit(Text("para que dos cumplan el mismo día", font=FONT, + font_size=36, color=GRIS), 8.0).next_to(q, DOWN, buff=0.35) + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.45) + b.play(Write(q), run_time=0.9) + b.play(FadeIn(q2, shift=UP * 0.15), run_time=0.6) + + with self.beat(1) as b: + guess = Text("¿180?", font=FONT, font_size=62, weight=BOLD, color=GRIS).move_to(UP * 0.4) + cross = Cross(guess, stroke_color=ROSA, stroke_width=11, scale_factor=0.75) + ans = Text("23", font=FONT, font_size=170, weight=BOLD, color=AMBAR).move_to(DOWN * 2.2) + b.play(FadeOut(VGroup(q, q2)), run_time=0.3) + b.play(FadeIn(guess), run_time=0.4) + b.play(Create(cross), run_time=0.45) + b.play(FadeIn(ans, scale=0.55), run_time=0.7) + b.play(Flash(ans, color=AMBAR, line_length=0.8, num_lines=20, flash_radius=2.0), + run_time=0.6) + + with self.beat(2) as b: + b.play(FadeOut(VGroup(guess, cross)), + ans.animate.scale(0.40).move_to(DOWN * 2.8), run_time=0.6) + lbl = Text("personas → 50%", font=FONT, font_size=38, weight=BOLD, color=VERDE) + lbl.next_to(ans, RIGHT, buff=0.35) + grp = VGroup(ans, lbl) + grp.move_to(DOWN * 2.8) + b.play(LaggedStart(*[GrowFromCenter(d) for d in people], lag_ratio=0.06), + run_time=1.1) + b.play(FadeIn(lbl, shift=LEFT * 0.2), run_time=0.5) + + # --- el error: uno contra todos --- + with self.beat(3) as b: + hero = people[0] + spokes = VGroup(*[Line(pts[0], pts[k], stroke_width=3.5, color=AMBAR) + for k in range(1, N)]) + cnt = Text("22 comparaciones", font=FONT, font_size=40, weight=BOLD, + color=AMBAR).move_to(DOWN * 1.3) + b.play(hero.animate.set_color(AMBAR).scale(1.6), run_time=0.4) + b.play(LaggedStart(*[Create(s) for s in spokes], lag_ratio=0.05), run_time=1.3) + b.play(FadeIn(cnt, shift=UP * 0.15), run_time=0.5) + + # --- todos contra todos --- + pairs = list(itertools.combinations(range(N), 2)) + with self.beat(4) as b: + chords = VGroup(*[Line(pts[i], pts[j], stroke_width=1.7, + color="#4CC9F0", stroke_opacity=0.5) + for i, j in pairs]) + b.play(FadeOut(spokes), FadeOut(cnt), + hero.animate.set_color("#8FB8FF").scale(1 / 1.6), run_time=0.5) + b.play(LaggedStart(*[Create(c) for c in chords], lag_ratio=0.004), + run_time=max(1.4, b.floor - 0.9)) + + with self.beat(5) as b: + big = Text("253", font=FONT, font_size=112, weight=BOLD, color=CELESTE) + cap = Text("parejas posibles", font=FONT, font_size=38, weight=BOLD, color=WHITE) + box = VGroup(big, cap).arrange(DOWN, buff=0.18).move_to(DOWN * 1.1) + b.play(FadeIn(big, scale=0.6), run_time=0.6) + b.play(FadeIn(cap, shift=UP * 0.15), run_time=0.5) + + with self.beat(6) as b: + b.play(Circumscribe(box, color=CELESTE, buff=0.35, stroke_width=6), run_time=1.0) + b.wait(0.3) + + # --- la curva --- + axes = Axes(x_range=[0, 70, 10], y_range=[0, 100, 25], + x_length=7.4, y_length=5.0, + axis_config=dict(color="#4A5878", stroke_width=4, + include_tip=False, font_size=26), + y_axis_config=dict(include_numbers=True, + numbers_to_include=[0, 50, 100])) + axes.move_to(UP * 2.15) + xlab = Text("personas", font=FONT, font_size=30, color=GRIS).next_to(axes, DOWN, buff=0.3) + curve = axes.plot(lambda n: prob(int(n)) * 100, x_range=[1, 70, 1], + color=AMBAR, stroke_width=8) + + with self.beat(7) as b: + b.play(FadeOut(VGroup(people, chords, box, grp)), run_time=0.5) + b.play(Create(axes), FadeIn(xlab), run_time=0.8) + b.play(Create(curve), run_time=max(0.9, b.floor - 1.5)) + + marks = VGroup() + + def mark(n, txt, col): + d = Dot(axes.c2p(n, prob(n) * 100), radius=0.13, color=col) + t = Text(txt, font=FONT, font_size=34, weight=BOLD, color=col) + t.next_to(d, DOWN, buff=0.28) + return VGroup(d, t) + + with self.beat(7 if False else 8) as b: + m50 = mark(50, "97%", VERDE) + m50[1].next_to(m50[0], DOWN, buff=0.35).shift(LEFT * 0.35) + m30 = mark(30, "70%", CELESTE) + m30[1].next_to(m30[0], RIGHT, buff=0.3).shift(DOWN * 0.35) + b.play(FadeIn(m30[0], scale=0.5), Write(m30[1]), run_time=0.7) + b.wait(0.2) + marks.add(m30) + b.play(FadeIn(m50[0], scale=0.5), Write(m50[1]), run_time=0.7) + marks.add(m50) + + with self.beat(9) as b: + m70 = mark(70, "99,9%", AMBAR) + m70[1].next_to(m70[0], UP, buff=0.3).shift(LEFT * 0.55) + b.play(FadeIn(m70[0], scale=0.5), Write(m70[1]), run_time=0.8) + b.play(Flash(m70[0], color=AMBAR, line_length=0.5, num_lines=16, + flash_radius=1.0), run_time=0.7) + marks.add(m70) + + with self.beat(10) as b: + cta = self.fit(Text("probalo en tu grupo", font=FONT, font_size=64, + weight=BOLD, color=AMBAR), 7.9).move_to(DOWN * 2.1) + b.play(Write(cta), run_time=0.9) + b.play(Circumscribe(cta, color=AMBAR, buff=0.3, stroke_width=7), run_time=1.0) + + self.finish() diff --git a/scenes/v4_luna.py b/scenes/v4_luna.py new file mode 100644 index 0000000..f69f99a --- /dev/null +++ b/scenes/v4_luna.py @@ -0,0 +1,178 @@ +# -*- coding: utf-8 -*- +import sys, os, math +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +Y0, Y1 = -3.25, 4.20 # extremos del eje logaritmico +L0, L1 = -1.0, 11.8 # log10 del espesor en mm +BAR_X, BAR_W = -3.15, 1.0 +MOON_MM = 3.844e11 + + +def ypos(mm): + L = max(min(math.log10(mm), L1), L0) + return Y0 + (L - L0) / (L1 - L0) * (Y1 - Y0) + + +def espesor(n): + return 0.1 * (2 ** n) + + +def humano(mm): + if mm < 10: + return f"{mm:.1f} mm".replace(".", ",") + if mm < 1e4: + return f"{mm/10:.0f} cm" + if mm < 1e7: + return f"{mm/1000:,.0f} m".replace(",", ".") + return f"{mm/1e6:,.0f} km".replace(",", ".") + + +class Luna(TikTok): + NAME = "luna" + + def moon(self, r=0.62): + m = Circle(radius=r, stroke_width=0, fill_color="#D9DEE8", fill_opacity=1) + cr = VGroup( + Dot(m.get_center() + LEFT * 0.2 * r + UP * 0.3 * r, radius=0.16 * r, color="#AEB6C6"), + Dot(m.get_center() + RIGHT * 0.35 * r + DOWN * 0.1 * r, radius=0.11 * r, color="#AEB6C6"), + Dot(m.get_center() + LEFT * 0.1 * r + DOWN * 0.42 * r, radius=0.09 * r, color="#AEB6C6"), + ) + return VGroup(m, cr) + + def construct(self): + self.prepare() + chip = self.chip("Crecimiento exponencial", CELESTE) + + # ---------- hook ---------- + with self.beat(0) as b: + sheet = Rectangle(width=1.9, height=2.5, stroke_color="#C9D2E3", stroke_width=5, + fill_color="#1A2440", fill_opacity=1).move_to(LEFT * 2.3 + UP * 2.6) + fold = Line(sheet.get_corner(UL) + RIGHT * 0.55, sheet.get_corner(DL) + RIGHT * 0.55, + stroke_width=3, color="#5E6B87") + mo = self.moon(0.95).move_to(RIGHT * 2.4 + UP * 2.6) + ar = Arrow(sheet.get_right() + RIGHT * 0.15, mo.get_left() + LEFT * 0.15, + buff=0, color=AMBAR, stroke_width=9) + tag = self.fit(Text("42 dobleces", font=FONT, font_size=46, weight=BOLD, + color=AMBAR), 7.5).next_to(ar, UP, buff=0.3) + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.45) + b.play(FadeIn(sheet), Create(fold), run_time=0.5) + b.play(GrowArrow(ar), FadeIn(tag), run_time=0.6) + b.play(FadeIn(mo, scale=0.6), run_time=0.6) + hook = VGroup(sheet, fold, mo, ar, tag) + + # ---------- el eje ---------- + axis = Line([BAR_X, Y0, 0], [BAR_X, Y1 + 0.3, 0], stroke_width=5, color="#3A4766") + base = Line([BAR_X - 0.75, Y0, 0], [4.2, Y0, 0], stroke_width=5, color="#3A4766") + + hitos = [(1e2, "10 cm"), (1e5, "100 m"), (1e8, "100 km")] + marks = VGroup() + for mm, txt in hitos: + y = ypos(mm) + ln = DashedLine([BAR_X - 0.5, y, 0], [3.9, y, 0], stroke_width=3, + color="#33405C", dash_length=0.12) + lb = Text(txt, font=FONT, font_size=30, color=GRIS) + lb.next_to(ln, UP, buff=0.08).align_to(ln, RIGHT) + marks.add(VGroup(ln, lb)) + + ym = ypos(MOON_MM) + moon_line = DashedLine([BAR_X - 0.5, ym, 0], [3.4, ym, 0], stroke_width=4, + color="#D9DEE8", dash_length=0.14) + moon_ic = self.moon(0.42).move_to([3.85, ym, 0]) + moon_lb = Text("LUNA 384.000 km", font=FONT, font_size=30, weight=BOLD, color="#D9DEE8") + moon_lb.next_to(moon_line, UP, buff=0.1).align_to(moon_line, RIGHT).shift(LEFT * 0.1) + + readout = VGroup( + Text("0", font=FONT, font_size=68, weight=BOLD, color=AMBAR), + Text("dobleces", font=FONT, font_size=28, color=GRIS), + Text("0,1 mm", font=FONT, font_size=44, weight=BOLD, color=WHITE), + ) + readout[0:2].arrange(RIGHT, buff=0.25, aligned_edge=DOWN) + readout.arrange(RIGHT, buff=0.5, aligned_edge=DOWN).move_to(UP * 5.6) + + bar = Rectangle(width=BAR_W, height=0.02, stroke_width=0, + fill_color=AMBAR, fill_opacity=1) + bar.move_to([BAR_X + BAR_W / 2 + 0.06, Y0, 0], DOWN + LEFT) + + with self.beat(1) as b: + b.play(FadeOut(hook), run_time=0.4) + b.play(Create(axis), Create(base), run_time=0.5) + b.play(LaggedStart(*[FadeIn(m) for m in marks], lag_ratio=0.2), run_time=0.8) + b.play(Create(moon_line), FadeIn(moon_ic), FadeIn(moon_lb), run_time=0.6) + + state = {"n": 0} + + def goto(bt, n, rt=0.9, extra=None): + mm = espesor(n) + h = max(ypos(mm) - Y0, 0.02) + new_bar = bar.copy().stretch_to_fit_height(h).move_to( + [BAR_X + BAR_W / 2 + 0.06, Y0, 0], DOWN + LEFT) + nr = VGroup( + Text(str(n), font=FONT, font_size=68, weight=BOLD, color=AMBAR), + Text("dobleces" if n != 1 else "doblez", font=FONT, font_size=28, color=GRIS), + Text(humano(mm), font=FONT, font_size=44, weight=BOLD, color=WHITE), + ) + nr[0:2].arrange(RIGHT, buff=0.25, aligned_edge=DOWN) + nr.arrange(RIGHT, buff=0.5, aligned_edge=DOWN).move_to(UP * 5.6) + self.fit(nr, 8.2) + anims = [Transform(bar, new_bar), Transform(readout, nr)] + if extra: + anims += extra + bt.play(*anims, run_time=rt) + state["n"] = n + + with self.beat(2) as b: + b.play(FadeIn(readout), FadeIn(bar), run_time=0.5) + b.play(Indicate(readout[2], color=AMBAR, scale_factor=1.3), run_time=0.7) + + with self.beat(3) as b: + goto(b, 1, 0.7) + goto(b, 2, 0.7) + + with self.beat(4) as b: + goto(b, 10, 1.1, [Flash(marks[0][1], color=AMBAR, line_length=0.3, + num_lines=12, flash_radius=0.8)]) + + with self.beat(5) as b: + goto(b, 20, 1.1, [Flash(marks[1][1], color=AMBAR, line_length=0.3, + num_lines=12, flash_radius=0.8)]) + + with self.beat(6) as b: + goto(b, 30, 1.1, [Flash(marks[2][1], color=AMBAR, line_length=0.3, + num_lines=12, flash_radius=0.8)]) + atm = Text("fuera de la atmósfera", font=FONT, font_size=32, + weight=BOLD, color=CELESTE).move_to([0.9, ypos(1e8) - 0.6, 0]) + b.play(FadeIn(atm, shift=UP * 0.1), run_time=0.5) + + with self.beat(7) as b: + b.play(FadeOut(atm), run_time=0.25) + goto(b, 40, 1.2) + + with self.beat(8) as b: + goto(b, 42, 1.3) + b.play(Flash(moon_ic, color="#D9DEE8", line_length=0.55, + num_lines=18, flash_radius=1.1), run_time=0.8) + + with self.beat(9) as b: + over = Text("te pasaste de largo", font=FONT, font_size=44, weight=BOLD, color=VERDE) + over.move_to([0.75, ym - 0.95, 0]) + self.fit(over, 5.6) + b.play(FadeIn(over, shift=UP * 0.15), run_time=0.6) + b.play(Circumscribe(over, color=VERDE, buff=0.22, stroke_width=6), run_time=0.9) + + with self.beat(10) as b: + b.play(FadeOut(VGroup(axis, base, marks, moon_line, moon_ic, moon_lb, + bar, over, readout)), run_time=0.6) + t1 = self.fit(Text("crecimiento", font=FONT, font_size=74, weight=BOLD, + color=WHITE), 8.0) + t2 = self.fit(Text("EXPONENCIAL", font=FONT, font_size=90, weight=BOLD, + color=AMBAR), 8.2) + g = VGroup(t1, t2).arrange(DOWN, buff=0.3).move_to(UP * 1.6) + t3 = self.fit(Text("por eso nadie lo ve venir", font=FONT, font_size=40, + color=GRIS), 7.6).next_to(g, DOWN, buff=0.7) + b.play(FadeIn(t1, shift=UP * 0.2), run_time=0.5) + b.play(FadeIn(t2, scale=0.7), run_time=0.6) + b.play(FadeIn(t3), run_time=0.5) + + self.finish() diff --git a/scenes/v5_japones.py b/scenes/v5_japones.py new file mode 100644 index 0000000..9b617d5 --- /dev/null +++ b/scenes/v5_japones.py @@ -0,0 +1,160 @@ +# -*- coding: utf-8 -*- +import sys, os +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +M = 0.6 # pendiente de las familias de rectas +XA, XB = -3.2, 3.7 # extremos de los segmentos +C_TENS, C_UNITS = [1.2, 1.8], [-1.2] # 21 -> rectas "/" +D_TENS, D_UNITS = [-1.2], [1.2, 1.8, 2.4] # 13 -> rectas "\" + + +def pline(c): + return Line([XA, M * XA + c, 0], [XB, M * XB + c, 0]) + + +def qline(d): + return Line([XA, -M * XA + d, 0], [XB, -M * XB + d, 0]) + + +def cross(c, d): + x = (d - c) / (2 * M) + return np.array([x, M * x + c, 0]) + + +class Japones(TikTok): + NAME = "japones" + + def construct(self): + self.prepare() + chip = self.chip("Multiplicar sin tablas", VERDE) + + P = [pline(c) for c in C_TENS + C_UNITS] + Q = [qline(d) for d in D_TENS + D_UNITS] + for l in P: + l.set_stroke(AMBAR, 7) + for l in Q: + l.set_stroke(CELESTE, 7) + + zonas = { + "izq": [cross(c, d) for c in C_TENS for d in D_TENS], + "med": [cross(c, d) for c in C_TENS for d in D_UNITS] + + [cross(c, d) for c in C_UNITS for d in D_TENS], + "der": [cross(c, d) for c in C_UNITS for d in D_UNITS], + } + dots = {k: VGroup(*[Dot(p, radius=0.13, color=WHITE) for p in v]) + for k, v in zonas.items()} + + fig = VGroup(*P, *Q, *dots.values()) + fig.scale(6.15 / fig.height).move_to(UP * 2.35) + + with self.beat(0) as b: + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.45) + hook = self.fit(Text("así se multiplica en Japón", font=FONT, font_size=50, + weight=BOLD, color=WHITE), 8.0).move_to(UP * 2.6) + b.play(Write(hook), run_time=1.0) + + with self.beat(1) as b: + op = MathTex(r"21 \times 13", color=WHITE).scale(2.6).move_to(UP * 0.6) + op[0][0:2].set_color(AMBAR) + op[0][3:5].set_color(CELESTE) + b.play(FadeOut(hook), run_time=0.3) + b.play(Write(op), run_time=1.0) + + with self.beat(2) as b: + b.play(op.animate.scale(0.44).move_to(DOWN * 2.75), run_time=0.6) + b.play(LaggedStart(*[Create(P[i]) for i in range(len(C_TENS))], + lag_ratio=0.35), run_time=0.85) + b.play(Create(P[len(C_TENS)]), run_time=0.5) + d2 = Text("2", font=FONT, font_size=44, weight=BOLD, color=AMBAR) + d2.move_to(P[0].get_end() + RIGHT * 0.45 + UP * 0.12) + d1 = Text("1", font=FONT, font_size=44, weight=BOLD, color=AMBAR) + d1.move_to(P[2].get_end() + RIGHT * 0.45 + UP * 0.12) + b.play(FadeIn(d2), FadeIn(d1), run_time=0.4) + + with self.beat(3) as b: + b.play(Create(Q[0]), run_time=0.5) + b.play(LaggedStart(*[Create(Q[i]) for i in range(1, len(Q))], + lag_ratio=0.3), run_time=0.95) + e1 = Text("1", font=FONT, font_size=44, weight=BOLD, color=CELESTE) + e1.move_to(Q[0].get_start() + LEFT * 0.45 + UP * 0.12) + e3 = Text("3", font=FONT, font_size=44, weight=BOLD, color=CELESTE) + e3.move_to(Q[2].get_start() + LEFT * 0.45 + UP * 0.12) + b.play(FadeIn(e1), FadeIn(e3), run_time=0.4) + + digs = VGroup(d2, d1, e1, e3) + res = {} + prev = [] + + def zona(bt, key, col, valor, texto): + box = SurroundingRectangle(dots[key], color=col, buff=0.34, + corner_radius=0.3, stroke_width=7) + bt.play(Create(box), run_time=0.5) + bt.play(LaggedStart(*[FadeIn(dd, scale=0.4) for dd in dots[key]], + lag_ratio=0.18), run_time=0.7) + lab = Text(texto, font=FONT, font_size=42, weight=BOLD, color=col) + lab.next_to(box, DOWN, buff=0.28) + self.fit(lab, 4.6) + if lab.get_left()[0] < -3.9: + lab.shift(RIGHT * (-3.9 - lab.get_left()[0])) + if lab.get_right()[0] > 3.9: + lab.shift(LEFT * (lab.get_right()[0] - 3.9)) + anim = [FadeIn(lab, shift=UP * 0.12)] + if prev: + anim.append(FadeOut(prev[-1])) + bt.play(*anim, run_time=0.5) + prev.append(lab) + res[key] = (box, lab, valor) + return box, lab + + with self.beat(4) as b: + bz, lz = zona(b, "izq", VERDE, 2, "2 cruces") + + with self.beat(5) as b: + bm, lm = zona(b, "med", ROSA, 7, "6 + 1 = 7") + + with self.beat(6) as b: + bd, ld = zona(b, "der", CELESTE, 3, "3 cruces") + + with self.beat(7) as b: + nums = VGroup( + Text("2", font=FONT, font_size=96, weight=BOLD, color=VERDE), + Text("7", font=FONT, font_size=96, weight=BOLD, color=ROSA), + Text("3", font=FONT, font_size=96, weight=BOLD, color=CELESTE), + ).arrange(RIGHT, buff=0.55).move_to(DOWN * 1.35) + b.play(FadeOut(VGroup(ld, op)), run_time=0.3) + b.play(TransformFromCopy(dots["izq"], nums[0]), + TransformFromCopy(dots["med"], nums[1]), + TransformFromCopy(dots["der"], nums[2]), run_time=1.1) + total = Text("273", font=FONT, font_size=112, weight=BOLD, color=WHITE) + total.move_to(DOWN * 2.9) + b.play(TransformFromCopy(nums, total), run_time=0.9) + + with self.beat(8) as b: + b.play(FadeOut(VGroup(*P, *Q, *dots.values(), bz, bm, bd, digs, nums)), + run_time=0.5) + check = MathTex(r"21 \times 13 = 273", color=VERDE).scale(1.9).move_to(UP * 2.4) + b.play(total.animate.move_to(UP * 0.2).scale(0.9), run_time=0.5) + b.play(Write(check), run_time=0.9) + b.play(Flash(check, color=VERDE, line_length=0.6, num_lines=20, + flash_radius=2.4), run_time=0.8) + + with self.beat(9) as b: + b.play(FadeOut(total), run_time=0.3) + tip = VGroup( + self.fit(Text("¿una zona da más de 9?", font=FONT, font_size=46, + weight=BOLD, color=WHITE), 8.0), + self.fit(Text("llevás una a la de al lado", font=FONT, font_size=46, + weight=BOLD, color=AMBAR), 8.0), + ).arrange(DOWN, buff=0.35).move_to(DOWN * 0.6) + b.play(FadeIn(tip[0], shift=UP * 0.15), run_time=0.6) + b.play(FadeIn(tip[1], shift=UP * 0.15), run_time=0.6) + + with self.beat(10) as b: + cta = self.fit(Text("guardalo para la tarea", font=FONT, font_size=60, + weight=BOLD, color=AMBAR), 8.0).move_to(DOWN * 2.6) + b.play(Write(cta), run_time=0.9) + b.play(Circumscribe(cta, color=AMBAR, buff=0.3, stroke_width=7), run_time=1.0) + + self.finish() diff --git a/scenes/v6_benford.py b/scenes/v6_benford.py new file mode 100644 index 0000000..cbb8dcc --- /dev/null +++ b/scenes/v6_benford.py @@ -0,0 +1,131 @@ +# -*- coding: utf-8 -*- +import sys, os, math +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +BENF = [math.log10(1 + 1 / d) for d in range(1, 10)] # ley de Benford +PLANO = [1 / 9] * 9 # lo que uno esperaria +BASE_Y, MAXH, BW = -0.9, 4.6, 0.72 +XS = [-3.52 + i * 0.88 for i in range(9)] + + +class Benford(TikTok): + NAME = "benford" + + def bar(self, i, frac, color): + h = max(frac / 0.31 * MAXH, 0.02) + r = Rectangle(width=BW, height=h, stroke_width=0, fill_color=color, fill_opacity=1) + r.move_to([XS[i], BASE_Y, 0], DOWN) + return r + + def construct(self): + self.prepare() + chip = self.chip("Estadística forense", VERDE) + + # ---- lista de numeros ---- + raw = ["1.243", "87", "2.910", "146", "3.502", "1.078", "254", "19.640"] + lista = VGroup(*[Text(n, font=FONT, font_size=46, weight=BOLD, color=WHITE) + for n in raw]).arrange_in_grid(4, 2, buff=(1.1, 0.42)) + lista.move_to(UP * 2.4) + + with self.beat(0) as b: + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.45) + b.play(LaggedStart(*[FadeIn(t, shift=UP * 0.15) for t in lista], + lag_ratio=0.12), run_time=1.3) + + with self.beat(1) as b: + firsts = VGroup(*[t[0].copy().set_color(AMBAR) for t in lista]) + b.play(LaggedStart(*[t[0].animate.set_color(AMBAR) for t in lista], + lag_ratio=0.1), run_time=1.0) + b.play(*[Indicate(t[0], color=AMBAR, scale_factor=1.5) for t in lista], + run_time=0.8) + + # ---- lo que uno esperaria ---- + labels = VGroup(*[Text(str(d), font=FONT, font_size=38, weight=BOLD, color=GRIS) + .move_to([XS[d - 1], BASE_Y - 0.42, 0]) for d in range(1, 10)]) + floor = Line([-4.1, BASE_Y, 0], [4.1, BASE_Y, 0], stroke_width=5, color="#3A4766") + bars = VGroup(*[self.bar(i, PLANO[i], "#44506E") for i in range(9)]) + + with self.beat(2) as b: + b.play(FadeOut(lista), run_time=0.4) + b.play(Create(floor), FadeIn(labels), run_time=0.5) + b.play(LaggedStart(*[GrowFromEdge(x, DOWN) for x in bars], + lag_ratio=0.07), run_time=1.0) + exp = Text("11% cada uno", font=FONT, font_size=40, weight=BOLD, color=GRIS) + exp.move_to(UP * 4.6) + b.play(FadeIn(exp), run_time=0.45) + + # ---- la realidad ---- + with self.beat(3) as b: + nb = self.bar(0, BENF[0], AMBAR) + b.play(FadeOut(exp), run_time=0.25) + b.play(Transform(bars[0], nb), labels[0].animate.set_color(AMBAR), run_time=1.0) + pct = Text("30%", font=FONT, font_size=42, weight=BOLD, color=AMBAR) + pct.next_to(nb, UP, buff=0.18) + b.play(FadeIn(pct, shift=UP * 0.15), run_time=0.5) + + with self.beat(4) as b: + news = [self.bar(i, BENF[i], CELESTE) for i in range(1, 9)] + b.play(LaggedStart(*[Transform(bars[i + 1], news[i]) for i in range(8)], + lag_ratio=0.1), run_time=1.4) + p2 = Text("17%", font=FONT, font_size=34, weight=BOLD, color=CELESTE) + p2.next_to(news[0], UP, buff=0.15) + p9 = Text("4%", font=FONT, font_size=34, weight=BOLD, color=CELESTE) + p9.next_to(news[7], UP, buff=0.15) + b.play(FadeIn(p2), FadeIn(p9), run_time=0.5) + + with self.beat(5) as b: + name = self.fit(Text("LEY DE BENFORD", font=FONT, font_size=62, + weight=BOLD, color=WHITE), 8.0).move_to(UP * 4.7) + b.play(Write(name), run_time=1.0) + + with self.beat(6) as b: + words = VGroup(*[Text(w, font=FONT, font_size=34, color=GRIS) + for w in ("poblaciones", "precios", "likes", "ríos")]) + words.arrange(RIGHT, buff=0.45).move_to(DOWN * 1.9) + self.fit(words, 8.2) + b.play(LaggedStart(*[FadeIn(w, shift=UP * 0.15) for w in words], + lag_ratio=0.25), run_time=1.1) + + # ---- los numeros inventados ---- + with self.beat(7) as b: + b.play(FadeOut(words), run_time=0.3) + fake = VGroup(*[Rectangle(width=BW, height=PLANO[i] / 0.31 * MAXH, + stroke_color=ROSA, stroke_width=5, + fill_opacity=0).move_to([XS[i], BASE_Y, 0], DOWN) + for i in range(9)]) + lbl = Text("inventados", font=FONT, font_size=42, weight=BOLD, color=ROSA) + lbl.move_to(DOWN * 2.0) + b.play(LaggedStart(*[Create(f) for f in fake], lag_ratio=0.07), run_time=1.1) + b.play(FadeIn(lbl, shift=UP * 0.15), run_time=0.5) + + with self.beat(8) as b: + b.play(*[Indicate(fake[i], color=ROSA, scale_factor=1.06) for i in (0, 1)], + run_time=0.8) + gap = DoubleArrow(fake[0].get_top() + UP * 0.08, bars[0].get_top() + DOWN * 0.08, + buff=0, color=ROSA, stroke_width=7, + tip_length=0.22).shift(RIGHT * 0.0) + b.play(GrowArrow(gap), run_time=0.7) + b.play(Flash(gap, color=ROSA, line_length=0.4, num_lines=14, + flash_radius=1.0), run_time=0.6) + + with self.beat(9) as b: + b.play(FadeOut(VGroup(fake, gap, lbl)), run_time=0.4) + txt = VGroup( + self.fit(Text("así agarraron", font=FONT, font_size=46, + weight=BOLD, color=WHITE), 8.0), + self.fit(Text("fraudes contables reales", font=FONT, font_size=46, + weight=BOLD, color=ROSA), 8.0), + ).arrange(DOWN, buff=0.3).move_to(DOWN * 2.1) + b.play(FadeIn(txt[0], shift=UP * 0.15), run_time=0.5) + b.play(FadeIn(txt[1], shift=UP * 0.15), run_time=0.6) + + with self.beat(10) as b: + cta = self.fit(Text("probá con tu tarjeta", font=FONT, font_size=58, + weight=BOLD, color=AMBAR), 7.9).move_to(DOWN * 3.15) + b.play(FadeOut(txt), run_time=0.3) + b.play(Write(cta), run_time=0.9) + b.play(Circumscribe(cta, color=AMBAR, buff=0.28, stroke_width=7), run_time=1.0) + + self.finish() diff --git a/scenes/v7_hilbert.py b/scenes/v7_hilbert.py new file mode 100644 index 0000000..4df4c2c --- /dev/null +++ b/scenes/v7_hilbert.py @@ -0,0 +1,135 @@ +# -*- coding: utf-8 -*- +import sys, os +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +NR = 7 +PITCH, RW, RH, RY = 1.05, 0.92, 1.3, 3.15 +XS = [-3.15 + i * PITCH for i in range(NR)] + + +class Hilbert(TikTok): + NAME = "hilbert" + + def room(self, i): + r = RoundedRectangle(corner_radius=0.12, width=RW, height=RH, + stroke_color="#2E3A55", stroke_width=5, + fill_color="#131C33", fill_opacity=1).move_to([XS[i], RY, 0]) + n = Text(str(i + 1), font=FONT, font_size=34, weight=BOLD, color=GRIS) + n.next_to(r, DOWN, buff=0.16) + return VGroup(r, n) + + def guest(self, color=CELESTE, s=1.0): + head = Dot(radius=0.12, color=color) + body = RoundedRectangle(corner_radius=0.1, width=0.36, height=0.34, + stroke_width=0, fill_color=color, fill_opacity=1) + body.next_to(head, DOWN, buff=0.05) + return VGroup(head, body).scale(s) + + def construct(self): + self.prepare() + chip = self.chip("El hotel infinito", CELESTE) + + rooms = VGroup(*[self.room(i) for i in range(NR)]) + dots3 = Text("· · ·", font=FONT, font_size=52, weight=BOLD, color=GRIS) + dots3.move_to([XS[-1] + 0.85, RY, 0]) + guests = VGroup(*[self.guest().move_to([XS[i], RY, 0]) for i in range(NR)]) + + with self.beat(0) as b: + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.45) + b.play(LaggedStart(*[FadeIn(r, shift=DOWN * 0.2) for r in rooms], + lag_ratio=0.1), run_time=1.0) + b.play(FadeIn(dots3), run_time=0.3) + b.play(LaggedStart(*[FadeIn(g, scale=0.5) for g in guests], + lag_ratio=0.08), run_time=0.9) + full = Text("COMPLETO", font=FONT, font_size=44, weight=BOLD, color=ROSA) + full.move_to(UP * 5.15) + b.play(FadeIn(full), run_time=0.4) + + nuevo = self.guest(AMBAR).move_to([-4.05, 1.25, 0]) + with self.beat(1) as b: + q = Text("¿hay lugar?", font=FONT, font_size=46, weight=BOLD, color=AMBAR) + q.move_to(DOWN * 0.15) + b.play(FadeIn(nuevo, shift=RIGHT * 0.3), run_time=0.6) + b.play(Write(q), run_time=0.7) + + with self.beat(2) as b: + b.play(FadeOut(q), FadeOut(full), run_time=0.3) + movs = [] + for i in range(NR - 1): + movs.append(guests[i].animate.move_to([XS[i + 1], RY, 0])) + movs.append(guests[NR - 1].animate.move_to(dots3.get_center()).set_opacity(0)) + b.play(LaggedStart(*movs, lag_ratio=0.09), run_time=max(1.2, b.floor - 0.6)) + + with self.beat(3) as b: + libre = rooms[0][0].copy().set_stroke(AMBAR, 8).set_fill("#2A2410", 1) + b.play(Transform(rooms[0][0], libre), run_time=0.5) + b.play(nuevo.animate.move_to([XS[0], RY, 0]), run_time=0.8) + b.play(rooms[0][0].animate.set_stroke("#2E3A55", 5).set_fill("#131C33", 1), + run_time=0.4) + guests = VGroup(nuevo, *[guests[i] for i in range(NR - 1)]) + + # ---- llegan infinitos ---- + with self.beat(4) as b: + horda = VGroup(*[self.guest(AMBAR, 0.55).move_to([-3.9 + i * 0.62, 0.7, 0]) + for i in range(11)]) + inf = MathTex(r"\infty", color=AMBAR).scale(2.2).next_to(horda, RIGHT, buff=0.3) + b.play(LaggedStart(*[FadeIn(g, shift=UP * 0.2) for g in horda], + lag_ratio=0.06), run_time=1.1) + b.play(Write(inf), run_time=0.6) + + with self.beat(5) as b: + rule = self.fit(Text("cada uno → al doble", font=FONT, font_size=50, + weight=BOLD, color=VERDE), 8.0).move_to(DOWN * 1.35) + b.play(FadeIn(rule, shift=UP * 0.15), run_time=0.7) + + with self.beat(6) as b: + movs = [] + for i in range(NR): + t = 2 * (i + 1) - 1 + if t < NR: + movs.append(guests[i].animate.move_to([XS[t], RY, 0])) + else: + movs.append(guests[i].animate.move_to(dots3.get_center()).set_opacity(0)) + b.play(LaggedStart(*movs, lag_ratio=0.12), run_time=max(1.3, b.floor - 0.5)) + + with self.beat(7) as b: + impares = [0, 2, 4, 6] + b.play(FadeOut(rule), run_time=0.25) + b.play(*[rooms[i][0].animate.set_stroke(AMBAR, 8).set_fill("#2A2410", 1) + for i in impares], run_time=0.8) + lbl = self.fit(Text("libres: 1, 3, 5, 7…", font=FONT, font_size=46, + weight=BOLD, color=AMBAR), 8.0).move_to(DOWN * 1.35) + b.play(FadeIn(lbl, shift=UP * 0.15), run_time=0.6) + + with self.beat(8) as b: + b.play(FadeOut(VGroup(horda, inf, lbl)), run_time=0.4) + t = VGroup( + self.fit(Text("estaba lleno", font=FONT, font_size=50, + weight=BOLD, color=WHITE), 8.0), + self.fit(Text("y entraron infinitos más", font=FONT, font_size=50, + weight=BOLD, color=AMBAR), 8.2), + ).arrange(DOWN, buff=0.3).move_to(DOWN * 0.7) + b.play(FadeIn(t[0], shift=UP * 0.15), run_time=0.5) + b.play(FadeIn(t[1], shift=UP * 0.15), run_time=0.7) + + with self.beat(9) as b: + b.play(FadeOut(t), run_time=0.3) + t2 = VGroup( + MathTex(r"\infty", color=CELESTE).scale(3.4), + self.fit(Text("no es un número grande.\nes otra cosa.", font=FONT, + font_size=44, weight=BOLD, color=WHITE, + line_spacing=0.8), 8.0), + ).arrange(DOWN, buff=0.45).move_to(DOWN * 0.9) + b.play(FadeIn(t2[0], scale=0.6), run_time=0.7) + b.play(FadeIn(t2[1], shift=UP * 0.15), run_time=0.7) + + with self.beat(10) as b: + b.play(FadeOut(t2), run_time=0.3) + cta = self.fit(Text("hotel de Hilbert", font=FONT, font_size=62, + weight=BOLD, color=AMBAR), 7.9).move_to(DOWN * 0.9) + b.play(Write(cta), run_time=0.9) + b.play(Circumscribe(cta, color=AMBAR, buff=0.3, stroke_width=7), run_time=1.0) + + self.finish() diff --git a/scenes/v8_reuleaux.py b/scenes/v8_reuleaux.py new file mode 100644 index 0000000..66b686c --- /dev/null +++ b/scenes/v8_reuleaux.py @@ -0,0 +1,158 @@ +# -*- coding: utf-8 -*- +import sys, os, math +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +W = 2.9 # ancho constante de las figuras +FLOOR = -0.6 # piso de la animacion de rodado + + +def reuleaux(w, bulge=1, **kw): + """Triangulo de Reuleaux: 3 arcos de radio w centrados en el vertice opuesto.""" + R = w / math.sqrt(3) + V = [R * np.array([math.cos(a), math.sin(a), 0]) + for a in (PI / 2, PI / 2 + TAU / 3, PI / 2 + 2 * TAU / 3)] + arcs = [ArcBetweenPoints(V[i], V[(i + 1) % 3], angle=bulge * PI / 3) for i in range(3)] + m = VMobject(**kw) + m.set_points(arcs[0].points) + for a in arcs[1:]: + m.append_points(a.points) + return m + + +class Reuleaux(TikTok): + NAME = "reuleaux" + + def construct(self): + self.prepare() + chip = self.chip("Geometría de la calle", AMBAR) + + with self.beat(0) as b: + tapa = VGroup( + Circle(radius=1.6, stroke_color="#7A879F", stroke_width=12, + fill_color="#1B2438", fill_opacity=1), + Circle(radius=1.25, stroke_color="#4A5878", stroke_width=5), + VGroup(*[Line(ORIGIN, RIGHT * 1.1, stroke_width=5, color="#4A5878") + .rotate(a, about_point=ORIGIN) for a in np.arange(0, TAU, TAU / 8)]), + ).move_to(UP * 3.4) + q = self.fit(Text("¿por qué son redondas?", font=FONT, font_size=52, + weight=BOLD, color=WHITE), 8.0).move_to(UP * 0.7) + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.45) + b.play(FadeIn(tapa, scale=0.7), run_time=0.8) + b.play(Write(q), run_time=0.9) + + with self.beat(1) as b: + ans = self.fit(Text("no se pueden caer adentro", font=FONT, font_size=46, + weight=BOLD, color=VERDE), 8.2).move_to(DOWN * 0.7) + b.play(FadeIn(ans, shift=UP * 0.15), run_time=0.7) + + # ---- la cuadrada se cae ---- + with self.beat(2) as b: + b.play(FadeOut(VGroup(tapa, q, ans)), run_time=0.4) + hole = Square(side_length=2.6, stroke_color="#4A5878", stroke_width=6, + fill_color="#05070D", fill_opacity=1).move_to(UP * 3.2) + cover = Square(side_length=2.5, stroke_color=ROSA, stroke_width=8, + fill_color="#2A1220", fill_opacity=1).move_to(UP * 3.2) + b.play(FadeIn(hole), FadeIn(cover), run_time=0.5) + b.play(Rotate(cover, PI / 4), run_time=0.7) + b.play(cover.animate.shift(DOWN * 2.3).scale(0.82).set_opacity(0.35), + run_time=0.9) + cae = Text("se cae", font=FONT, font_size=44, weight=BOLD, color=ROSA) + cae.move_to(UP * 0.35) + b.play(FadeIn(cae), run_time=0.4) + + with self.beat(3) as b: + b.play(FadeOut(VGroup(cover, cae)), run_time=0.3) + lado = Line(hole.get_corner(DL), hole.get_corner(DR), + stroke_width=8, color=CELESTE).shift(DOWN * 0.35) + diag = Line(hole.get_corner(DL), hole.get_corner(UR), stroke_width=8, color=ROSA) + l1 = Text("lado", font=FONT, font_size=34, weight=BOLD, + color=CELESTE).next_to(lado, DOWN, buff=0.12) + l2 = Text("diagonal = 1,41 × lado", font=FONT, font_size=36, weight=BOLD, + color=ROSA).move_to(UP * 0.9) + self.fit(l2, 8.0) + b.play(Create(lado), FadeIn(l1), run_time=0.6) + b.play(Create(diag), run_time=0.6) + b.play(FadeIn(l2, shift=UP * 0.15), run_time=0.6) + + # ---- el circulo mide igual en toda direccion ---- + with self.beat(4) as b: + b.play(FadeOut(VGroup(hole, lado, diag, l1, l2)), run_time=0.4) + circ = Circle(radius=W / 2, stroke_color=CELESTE, stroke_width=9, + fill_color="#0E2233", fill_opacity=1).move_to(UP * 3.0) + tr = ValueTracker(0) + cal = always_redraw(lambda: DoubleArrow( + circ.get_center() + rotate_vector(RIGHT * W / 2, tr.get_value()), + circ.get_center() - rotate_vector(RIGHT * W / 2, tr.get_value()), + buff=0, color=AMBAR, stroke_width=7, tip_length=0.22)) + b.play(FadeIn(circ, scale=0.8), run_time=0.5) + b.play(FadeIn(cal), run_time=0.3) + b.play(tr.animate.set_value(PI), run_time=max(1.0, b.floor - 1.1), + rate_func=linear) + same = Text("mide igual en toda dirección", font=FONT, font_size=38, + weight=BOLD, color=AMBAR).move_to(UP * 0.55) + self.fit(same, 8.2) + b.play(FadeIn(same), run_time=0.4) + + with self.beat(5) as b: + no = self.fit(Text("y no es la única", font=FONT, font_size=50, + weight=BOLD, color=WHITE), 8.0).move_to(DOWN * 0.7) + b.play(FadeIn(no, shift=UP * 0.15), run_time=0.7) + + # ---- aparece el Reuleaux ---- + tri = reuleaux(W, stroke_color=VERDE, stroke_width=9, + fill_color="#0C2A22", fill_opacity=1).move_to(UP * 3.0) + with self.beat(6) as b: + b.play(FadeOut(VGroup(cal, same, no)), run_time=0.3) + b.play(Transform(circ, tri), run_time=1.2) + + with self.beat(7) as b: + nom = self.fit(Text("TRIÁNGULO DE REULEAUX", font=FONT, font_size=46, + weight=BOLD, color=VERDE), 8.2).move_to(UP * 0.75) + b.play(Write(nom), run_time=1.0) + + # ---- rueda entre dos paredes ---- + with self.beat(8) as b: + b.play(FadeOut(VGroup(circ, nom)), run_time=0.4) + base = reuleaux(W, stroke_color=VERDE, stroke_width=9, + fill_color="#0C2A22", fill_opacity=1) + spin = ValueTracker(0) + + def rodando(): + s = base.copy().rotate(spin.get_value()) + s.shift(UP * (FLOOR - s.get_bottom()[1])) + return s + + rolling = always_redraw(rodando) + suelo = Line([-4.2, FLOOR, 0], [4.2, FLOOR, 0], stroke_width=7, color="#4A5878") + techo = Line([-4.2, FLOOR + W, 0], [4.2, FLOOR + W, 0], + stroke_width=7, color=AMBAR) + b.play(Create(suelo), Create(techo), run_time=0.5) + b.play(FadeIn(rolling), run_time=0.3) + b.play(spin.animate.set_value(TAU), run_time=max(1.4, b.floor - 0.8), + rate_func=linear) + + with self.beat(9) as b: + carga = RoundedRectangle(corner_radius=0.12, width=3.4, height=0.55, + stroke_width=0, fill_color=AMBAR, fill_opacity=1) + carga.move_to([0, FLOOR + W + 0.32, 0]) + nivel = self.fit(Text("la carga no sube ni baja", font=FONT, font_size=42, + weight=BOLD, color=AMBAR), 8.0).move_to(UP * 4.3) + b.play(FadeIn(carga, shift=DOWN * 0.15), FadeIn(nivel), run_time=0.6) + b.play(spin.animate.set_value(TAU * 2), run_time=max(1.2, b.floor - 0.7), + rate_func=linear) + + with self.beat(10) as b: + b.play(FadeOut(VGroup(rolling, suelo, techo, carga, nivel)), run_time=0.5) + cta = VGroup( + self.fit(Text("ahora ya sabés", font=FONT, font_size=50, + weight=BOLD, color=WHITE), 8.0), + self.fit(Text("por qué son redondas", font=FONT, font_size=54, + weight=BOLD, color=AMBAR), 8.2), + ).arrange(DOWN, buff=0.32).move_to(UP * 1.6) + b.play(FadeIn(cta[0], shift=UP * 0.15), run_time=0.5) + b.play(Write(cta[1]), run_time=0.9) + b.play(Circumscribe(cta[1], color=AMBAR, buff=0.28, stroke_width=7), run_time=0.9) + + self.finish() diff --git a/scenes/v9_regla72.py b/scenes/v9_regla72.py new file mode 100644 index 0000000..9811ff4 --- /dev/null +++ b/scenes/v9_regla72.py @@ -0,0 +1,124 @@ +# -*- coding: utf-8 -*- +import sys, os, math +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manim import * +from tiktok import * + +BAR_X0, BAR_MAX = -2.35, 3.3 # barra proporcional a los años + + +class Regla72(TikTok): + NAME = "regla72" + + def fila(self, tasa, anios, y, color, maxa=12.0): + t = Text(f"{tasa}%", font=FONT, font_size=46, weight=BOLD, color=color) + t.move_to([-3.95, y, 0], LEFT) + w = max(anios / maxa * BAR_MAX, 0.05) + bar = RoundedRectangle(corner_radius=0.1, width=w, height=0.46, stroke_width=0, + fill_color=color, fill_opacity=1) + bar.move_to([BAR_X0, y, 0], LEFT) + lab = Text(f"{anios:g} años".replace(".", ","), font=FONT, font_size=40, + weight=BOLD, color=WHITE) + lab.next_to(bar, RIGHT, buff=0.25) + return VGroup(t, bar, lab) + + def construct(self): + self.prepare() + chip = self.chip("Finanzas en 40 segundos", VERDE) + + with self.beat(0) as b: + q = VGroup( + self.fit(Text("¿cuánto tarda tu plata", font=FONT, font_size=52, + weight=BOLD, color=WHITE), 8.2), + self.fit(Text("en duplicarse?", font=FONT, font_size=52, + weight=BOLD, color=AMBAR), 8.2), + ).arrange(DOWN, buff=0.3).move_to(UP * 3.4) + b.play(FadeIn(chip, shift=DOWN * 0.3), run_time=0.45) + b.play(FadeIn(q[0], shift=UP * 0.15), run_time=0.6) + b.play(Write(q[1]), run_time=0.8) + + with self.beat(1) as b: + name = self.fit(Text("LA REGLA DEL 72", font=FONT, font_size=66, + weight=BOLD, color=VERDE), 8.2).move_to(UP * 1.4) + b.play(FadeIn(name, scale=0.7), run_time=0.8) + b.play(Flash(name, color=VERDE, line_length=0.6, num_lines=20, + flash_radius=2.6), run_time=0.7) + + with self.beat(2) as b: + f = MathTex(r"\frac{72}{\text{tasa anual}} = \text{años}", + color=WHITE).scale(1.5).move_to(DOWN * 0.6) + f[0][0:2].set_color(VERDE) + b.play(FadeOut(q), name.animate.scale(0.62).move_to(UP * 5.35), run_time=0.6) + b.play(Write(f), run_time=1.1) + + rows = [] + for i, (tasa, anios, col, yy) in enumerate( + [(6, 12, AMBAR, -2.6), (9, 8, CELESTE, -3.7), (12, 6, VERDE, -4.8)]): + rows.append(self.fila(tasa, anios, yy, col)) + + with self.beat(3) as b: + b.play(f.animate.scale(0.72).move_to(UP * 3.6), run_time=0.5) + for r in rows: + r.shift(UP * 4.3) + cuenta = MathTex(r"72 \div 6 = 12", color=AMBAR).scale(1.35).move_to(UP * 1.75) + b.play(Write(cuenta), run_time=0.8) + b.play(FadeIn(rows[0][0]), GrowFromEdge(rows[0][1], LEFT), + FadeIn(rows[0][2]), run_time=0.8) + + with self.beat(4) as b: + c2 = MathTex(r"72 \div 9 = 8", color=CELESTE).scale(1.35).move_to(UP * 1.75) + b.play(Transform(cuenta, c2), run_time=0.6) + b.play(FadeIn(rows[1][0]), GrowFromEdge(rows[1][1], LEFT), + FadeIn(rows[1][2]), run_time=0.8) + + with self.beat(5) as b: + c3 = MathTex(r"72 \div 12 = 6", color=VERDE).scale(1.35).move_to(UP * 1.75) + b.play(Transform(cuenta, c3), run_time=0.6) + b.play(FadeIn(rows[2][0]), GrowFromEdge(rows[2][1], LEFT), + FadeIn(rows[2][2]), run_time=0.8) + + tabla = VGroup(*rows) + with self.beat(6) as b: + inv = self.fit(Text("y también al revés", font=FONT, font_size=50, + weight=BOLD, color=ROSA), 8.0).move_to(DOWN * 1.1) + b.play(FadeOut(cuenta), run_time=0.3) + b.play(FadeIn(inv, shift=UP * 0.15), run_time=0.7) + + with self.beat(7) as b: + b.play(FadeOut(VGroup(tabla, inv)), run_time=0.45) + infl = VGroup( + self.fit(Text("30% de inflación anual", font=FONT, font_size=48, + weight=BOLD, color=ROSA), 8.2), + self.fit(Text("tu plata vale la mitad", font=FONT, font_size=44, + weight=BOLD, color=WHITE), 8.2), + self.fit(Text("en 2,4 años", font=FONT, font_size=56, + weight=BOLD, color=ROSA), 8.2), + ).arrange(DOWN, buff=0.35).move_to(UP * 0.35) + b.play(FadeIn(infl[0], shift=UP * 0.15), run_time=0.6) + b.play(FadeIn(infl[1], shift=UP * 0.15), run_time=0.6) + b.play(FadeIn(infl[2], scale=0.7), run_time=0.7) + + with self.beat(8) as b: + c4 = MathTex(r"72 \div 30 = 2{,}4", color=ROSA).scale(1.45).move_to(DOWN * 2.5) + b.play(Write(c4), run_time=1.0) + + with self.beat(9) as b: + b.play(FadeOut(VGroup(infl, c4)), run_time=0.4) + cmp = VGroup( + Text("exacto: 11,9 años", font=FONT, font_size=42, color=GRIS), + Text("regla: 12 años", font=FONT, font_size=42, weight=BOLD, color=VERDE), + ).arrange(DOWN, buff=0.3, aligned_edge=LEFT).move_to(UP * 0.4) + ok = self.fit(Text("es aproximada, pero se clava", font=FONT, font_size=42, + weight=BOLD, color=WHITE), 8.2).next_to(cmp, DOWN, buff=0.6) + b.play(FadeIn(cmp[0]), run_time=0.5) + b.play(FadeIn(cmp[1]), run_time=0.5) + b.play(FadeIn(ok, shift=UP * 0.15), run_time=0.6) + + with self.beat(10) as b: + b.play(FadeOut(VGroup(cmp, ok)), run_time=0.35) + cta = self.fit(Text("guardate esta cuenta", font=FONT, font_size=60, + weight=BOLD, color=AMBAR), 8.0).move_to(UP * 0.4) + b.play(Write(cta), run_time=0.9) + b.play(Circumscribe(cta, color=AMBAR, buff=0.3, stroke_width=7), run_time=1.0) + + self.finish() diff --git a/scripts/build_blender.py b/scripts/build_blender.py new file mode 100644 index 0000000..41731cf --- /dev/null +++ b/scripts/build_blender.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +"""Arma el video final de las escenas hechas en Blender. + +Compone en una sola pasada de ffmpeg: + fondo punteado + secuencia PNG con alfa (3D) + overlay de Manim + audio +El overlay trae chip, barra de progreso y subtitulos, o sea que el estilo sale +del mismo codigo que los videos de Manim. +""" +import glob, os, subprocess, sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "scripts")) +import build_video + +FPS = 30 + + +def componer(name, con_musica=True): + fondo = os.path.join(ROOT, "media", "images", "overlay", "fondo.png") + carpeta = os.path.join(ROOT, "render", name) + seq = os.path.join(carpeta, "f%04d.png") + overlay = os.path.join(ROOT, "media", "videos", "overlay", "1920p30", f"{name}.mov") + for p in (fondo, overlay): + if not os.path.exists(p): + raise SystemExit(f"falta {p}") + n = len(glob.glob(os.path.join(carpeta, "f*.png"))) + if n < 30: + raise SystemExit(f"[{name}] solo hay {n} frames renderizados") + + wav = build_video.build_track(name, con_musica) + out = os.path.join(ROOT, "out", f"{name}.mp4") + cmd = [ + "ffmpeg", "-v", "error", "-y", + "-loop", "1", "-framerate", str(FPS), "-i", fondo, + "-framerate", str(FPS), "-start_number", "1", "-i", seq, + "-i", overlay, + "-i", wav, + "-filter_complex", + "[0:v][1:v]overlay=format=auto[a];[a][2:v]overlay=format=auto,format=yuv420p[v]", + "-map", "[v]", "-map", "3:a", + "-filter:a", "loudnorm=I=-14:TP=-1.5:LRA=11,aresample=48000", + "-frames:v", str(n), + "-c:v", "libx264", "-profile:v", "high", "-pix_fmt", "yuv420p", + "-preset", "slow", "-crf", "20", "-r", str(FPS), + "-c:a", "aac", "-b:a", "192k", "-ac", "2", + "-movflags", "+faststart", "-shortest", out, + ] + subprocess.run(cmd, check=True) + d = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", + "-of", "csv=p=0", out], capture_output=True, text=True).stdout.strip() + print(f"[{name}] {out} {float(d):.1f}s {os.path.getsize(out)/1e6:.1f} MB " + f"({n} frames 3D)", flush=True) + return out + + +if __name__ == "__main__": + for n in (sys.argv[1:] or ["bolapeluda", "caos", "diferencial"]): + componer(n) diff --git a/scripts/build_video.py b/scripts/build_video.py new file mode 100644 index 0000000..572e3b5 --- /dev/null +++ b/scripts/build_video.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +"""Arma la pista final (voz + piano con ducking) siguiendo el timeline de Manim +y la pega al video renderizado.""" +import json, os, subprocess, sys, wave +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "scripts")) +import music + +SR = 44100 +SCENE_DIR = {"montyhall": "v1_montyhall", "nueves": "v2_nueves", "cumple": "v3_cumple", + "luna": "v4_luna", "japones": "v5_japones", + "benford": "v6_benford", "hilbert": "v7_hilbert", "reuleaux": "v8_reuleaux", + "regla72": "v9_regla72", "buffon": "v10_buffon", + "collatz": "v11_collatz", "simpson": "v12_simpson", + "cuerda": "v13_cuerda", "gabriel": "v14_gabriel", + "mobius": "v15_mobius", "bayes": "v16_bayes", + "cicloide": "v17_cicloide", "dados": "v18_dados"} + + +def read_wav(p): + with wave.open(p) as w: + a = np.frombuffer(w.readframes(w.getnframes()), dtype=np.int16) + ch, sr = w.getnchannels(), w.getframerate() + a = a.astype(np.float32) / 32768.0 + if ch > 1: + a = a.reshape(-1, ch).mean(axis=1) + return a, sr + + +def to_sr(a, sr_in, sr_out=SR): + if sr_in == sr_out: + return a + n = int(round(len(a) * sr_out / sr_in)) + return np.interp(np.linspace(0, len(a) - 1, n), np.arange(len(a)), a).astype(np.float32) + + +def build_track(name, with_music=True): + tl = json.load(open(os.path.join(ROOT, "out", f"{name}_timeline.json"))) + segs = json.load(open(os.path.join(ROOT, "audio", name, "segments.json")))["segments"] + total = tl["total"] + 0.25 + speech = np.zeros(int(total * SR), dtype=np.float32) + + for beat in tl["beats"]: + a, sr = read_wav(segs[beat["i"]]["wav"]) + a = to_sr(a, sr) + off = int(beat["start"] * SR) + end = min(off + len(a), len(speech)) + speech[off:end] += a[:end - off] + + speech *= min(1.0, 0.90 / (np.abs(speech).max() + 1e-9)) + st = np.stack([speech, speech], axis=1) + + if with_music: + bed = music.bed(name, total, gain=0.32, seed=abs(hash(name)) % 9999) + if len(bed) < len(st): + bed = np.pad(bed, ((0, len(st) - len(bed)), (0, 0))) + bed = music.duck(bed[:len(st)], st) + mix = st * 0.96 + bed + else: + mix = st + + mix = np.clip(mix / max(1.0, np.abs(mix).max() / 0.97), -1, 1) + path = os.path.join(ROOT, "tmp", f"{name}_mix.wav") + with wave.open(path, "w") as w: + w.setnchannels(2); w.setsampwidth(2); w.setframerate(SR) + w.writeframes((mix * 32767).astype(np.int16).tobytes()) + return path + + +def mux(name, video=None, with_music=True): + if video is None: + video = os.path.join(ROOT, "media", "videos", SCENE_DIR[name], "1920p30", f"{name}.mp4") + wav = build_track(name, with_music) + out = os.path.join(ROOT, "out", f"{name}.mp4") + subprocess.run([ + "ffmpeg", "-v", "error", "-y", "-i", video, "-i", wav, + "-filter:a", "loudnorm=I=-14:TP=-1.5:LRA=11,aresample=48000", + "-map", "0:v:0", "-map", "1:a:0", + "-c:v", "libx264", "-profile:v", "high", "-pix_fmt", "yuv420p", + "-preset", "slow", "-crf", "20", "-r", "30", + "-c:a", "aac", "-b:a", "192k", "-ac", "2", + "-movflags", "+faststart", "-shortest", out], check=True) + d = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", + "-of", "csv=p=0", out], capture_output=True, text=True).stdout.strip() + print(f"[{name}] {out} {float(d):.1f}s {os.path.getsize(out)/1e6:.1f} MB", flush=True) + return out + + +if __name__ == "__main__": + for n in (sys.argv[1:] or list(SCENE_DIR)): + mux(n) diff --git a/scripts/gen_audio.py b/scripts/gen_audio.py new file mode 100644 index 0000000..9dbbb47 --- /dev/null +++ b/scripts/gen_audio.py @@ -0,0 +1,119 @@ +# -*- coding: utf-8 -*- +"""Genera un WAV por segmento con qwen-tts (voz clonada rioplatense), +verifica cada uno transcribiendo con whisper y reintenta los que salen mal.""" +import json, os, re, shutil, subprocess, sys, unicodedata, wave +from difflib import SequenceMatcher + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from narration import SCRIPTS +from numspell import expand + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TTS = os.path.expanduser("~/GIT-MIRRO/qwentts.cpp/build/qwen-tts") +MODEL = os.path.expanduser("~/GIT-MIRRO/qwentts.cpp/models/qwen-talker-1.7b-base-Q8_0.gguf") +CODEC = os.path.expanduser("~/GIT-MIRRO/qwentts.cpp/models/qwen-tokenizer-12hz-Q8_0.gguf") +REF = dict(spk="/tmp/Firefox/output.spk", rvq="/tmp/Firefox/output.rvq", txt="/tmp/Firefox/output.txt") + +MIN_RATIO = 0.90 # similitud minima aceptada contra la transcripcion +TIMEOUT = 150 # segundos por segmento; mas que eso es generacion desbocada +MAX_ROUNDS = 4 + +def norm(s): + s = expand(s) + s = unicodedata.normalize("NFD", s.lower()) + s = "".join(c for c in s if unicodedata.category(c) != "Mn") + s = re.sub(r"[^a-z0-9ñ ]+", " ", s) + return " ".join(s.split()) + +def dur(path): + with wave.open(path) as w: + return w.getnframes() / w.getframerate() + +def synth(text, out, seed, timeout=TIMEOUT): + cmd = [TTS, "--model", MODEL, "--codec", CODEC, + "--ref-spk", REF["spk"], "--ref-rvq", REF["rvq"], "--ref-text", REF["txt"], + "--lang", "spanish", "--seed", str(seed), "--temp", "0.85", "--top-p", "0.95", + "-o", out] + subprocess.run(cmd, input=text.encode(), stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, check=True, timeout=timeout) + + +def synth_seguro(text, out, seed, etiqueta=""): + """A veces el modelo no emite fin y genera hasta el infinito: corto y cambio semilla.""" + for k in range(3): + try: + synth(text, out, seed + 7919 * k) + return seed + 7919 * k + except (subprocess.TimeoutExpired, subprocess.CalledProcessError): + print(f" {etiqueta} se colgo con semilla {seed + 7919 * k}, reintento", flush=True) + raise RuntimeError(f"{etiqueta}: tres intentos colgados") + +def transcribe(files, workdir): + """Una sola invocacion de whisper para todos los archivos (carga el modelo una vez).""" + if not files: + return {} + subprocess.run(["conda", "run", "-n", "stt", "--no-capture-output", + "whisper-ctranslate2", "--language", "es", "--model", "small", + "--output_dir", workdir, "--output_format", "txt", *files], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True) + out = {} + for f in files: + t = os.path.join(workdir, os.path.splitext(os.path.basename(f))[0] + ".txt") + out[f] = open(t, encoding="utf-8").read().strip() if os.path.exists(t) else "" + return out + +def build(name): + spec = SCRIPTS[name] + outdir = os.path.join(ROOT, "audio", name) + work = os.path.join(ROOT, "tmp", name) + os.makedirs(outdir, exist_ok=True); os.makedirs(work, exist_ok=True) + + segs = spec["segments"] + paths = [os.path.join(outdir, f"{i:02d}.wav") for i in range(len(segs))] + seeds = [1000 + i for i in range(len(segs))] + pend = list(range(len(segs))) + score = {} + best = {} # i -> (ratio, ruta del mejor intento) + keep = os.path.join(work, "best") + os.makedirs(keep, exist_ok=True) + + for rnd in range(MAX_ROUNDS): + if not pend: + break + for i in pend: + seeds[i] = synth_seguro(segs[i][0], paths[i], seeds[i], f"[{name}] {i:02d}") + tr = transcribe([paths[i] for i in pend], work) + nxt = [] + for i in pend: + r = SequenceMatcher(None, norm(segs[i][0]), norm(tr[paths[i]])).ratio() + score[i] = r + if i not in best or r > best[i][0]: + b = os.path.join(keep, f"{i:02d}.wav") + shutil.copy(paths[i], b) + best[i] = (r, b) + flag = "ok " if r >= MIN_RATIO else "RE " + print(f" [{name}] {i:02d} r={r:.2f} {flag}{dur(paths[i]):5.2f}s | {tr[paths[i]][:60]}", flush=True) + if r < MIN_RATIO: + seeds[i] += 7919 + nxt.append(i) + pend = nxt + if pend: + print(f" [{name}] ronda {rnd+2}: reintentando {pend}", flush=True) + + for i, (r, b) in best.items(): # me quedo con el mejor intento, no el ultimo + shutil.copy(b, paths[i]) + score[i] = r + + data = {"name": name, "title": spec["title"], "segments": [ + {"i": i, "tts": segs[i][0], "sub": segs[i][1], "wav": paths[i], + "dur": round(dur(paths[i]), 3), "score": round(score.get(i, 0), 3)} + for i in range(len(segs))]} + data["total_audio"] = round(sum(s["dur"] for s in data["segments"]), 2) + with open(os.path.join(outdir, "segments.json"), "w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, indent=2) + bad = [s["i"] for s in data["segments"] if s["score"] < MIN_RATIO] + print(f"[{name}] listo. audio={data['total_audio']}s sin_verificar={bad}", flush=True) + +if __name__ == "__main__": + for n in (sys.argv[1:] or list(SCRIPTS)): + build(n) diff --git a/scripts/music.py b/scripts/music.py new file mode 100644 index 0000000..a3aee16 --- /dev/null +++ b/scripts/music.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +"""Cama musical original hecha con las muestras de piano de keysound. + +Muestra NN => nota MIDI NN+20 (01-A-大字2组 = A0 = MIDI 21) +Las progresiones son propias, para que el audio sea libre de derechos. +""" +import glob, os, wave +import numpy as np + +PIANO_DIR = "/mnt/Data/GitHub/keysound/audio/piano" +SR = 44100 + +_paths, _cache = {}, {} +for _p in glob.glob(os.path.join(PIANO_DIR, "*.wav")): + _paths[int(os.path.basename(_p).split("-")[0]) + 20] = _p + +NOTE = {"C": 0, "C#": 1, "D": 2, "D#": 3, "E": 4, "F": 5, + "F#": 6, "G": 7, "G#": 8, "A": 9, "A#": 10, "B": 11} +TRIAD = {"maj": [0, 4, 7], "min": [0, 3, 7]} + + +def midi(name, octave): + return 12 * (octave + 1) + NOTE[name] + + +def load(m): + m = max(21, min(108, m)) + if m not in _cache: + with wave.open(_paths[m], "rb") as w: + d = np.frombuffer(w.readframes(w.getnframes()), dtype=np.int16) + d = d.reshape(-1, w.getnchannels()).astype(np.float32) / 32768.0 + if d.shape[1] == 1: + d = np.repeat(d, 2, axis=1) + _cache[m] = d + return _cache[m] + + +def chord(sym): + """'Am' -> (bajo, triada). Soporta sostenidos y sufijo m.""" + q = "min" if sym.endswith("m") else "maj" + root = sym[:-1] if sym.endswith("m") else sym + r = NOTE[root] + bass = 12 * (2 + 1) + r # octava 2 + triad = [12 * (4 + 1) + r + i for i in TRIAD[q]] + return bass, triad + + +# progresion + tempo por video +BEDS = { + "montyhall": (["Am", "F", "C", "G"], 92), + "nueves": (["Em", "C", "G", "D"], 88), + "cumple": (["C", "G", "Am", "F"], 96), + "luna": (["Dm", "A#", "F", "C"], 82), + "japones": (["G", "D", "Em", "C"], 100), + "benford": (["Am", "Em", "F", "G"], 94), + "hilbert": (["C", "Em", "Am", "F"], 80), + "reuleaux": (["F", "C", "Dm", "A#"], 98), + "regla72": (["G", "Em", "C", "D"], 104), + "buffon": (["Am", "G", "F", "E"], 86), + "collatz": (["Am", "Em", "Dm", "E"], 90), + "simpson": (["Cm", "G#", "A#", "Gm"], 96), + "cuerda": (["F", "Am", "Dm", "C"], 84), + "gabriel": (["Em", "Bm", "C", "G"], 76), + "mobius": (["D", "A", "Bm", "G"], 102), + "bayes": (["Dm", "Gm", "A#", "A"], 86), + "cicloide": (["A", "E", "F#m", "D"], 106), + "dados": (["Em", "Am", "D", "G"], 94), + "bolapeluda": (["C", "Am", "Dm", "G"], 100), + "caos": (["Am", "F", "Dm", "E"], 88), + "diferencial": (["Bm", "G", "D", "A"], 112, "motor"), + "galton": (["D", "Bm", "G", "A"], 96), + "bloques": (["E", "C#m", "A", "B"], 100), + "domino": (["G", "D", "Em", "C"], 104, "motor"), +} + +# melodias propias: por compas, (tiempo en negras, nota MIDI, duracion en negras) +MELODIAS = { + "motor": [ + [(0, 78, 1.5), (1.5, 74, 0.5), (2, 76, 1), (3, 78, 1)], # Bm + [(0, 79, 1.5), (1.5, 78, 0.5), (2, 76, 1), (3, 74, 1)], # G + [(0, 78, 1), (1, 81, 1), (2, 78, 0.5), (2.5, 76, 0.5), (3, 74, 1)], # D + [(0, 73, 2), (2, 76, 1), (3, 69, 1)], # A + ], +} + + +def bed(name, total_s, gain=0.30, seed=0): + prog, bpm = BEDS[name][:2] + estilo = BEDS[name][2] if len(BEDS[name]) > 2 else None + beat = 60.0 / bpm + measure = 4 * beat + eighth = beat / 2 + n = int((total_s + 3.0) * SR) + buf = np.zeros((n, 2), dtype=np.float32) + rng = np.random.default_rng(seed) + + def hit(m, t, g, max_len=None): + s = load(m) * g + if max_len is not None: + k = min(len(s), int(max_len * SR)) + s = s[:k].copy() + f = min(int(0.06 * SR), k) + s[-f:] *= np.linspace(1, 0, f)[:, None] + i = int(t * SR) + if i >= n: + return + buf[i:i + len(s)] += s[:n - i] + + k = 0 + t = 0.0 + while t < total_s + 0.5: + sym = prog[k % len(prog)] + bass, triad = chord(sym) + if estilo == "motor": + # bajo en corcheas, como un motor; acorde en 1 y 3; melodia arriba + for j in range(8): + hit(bass + (12 if j % 2 else 0), t + j * eighth, + 0.34 if j % 2 == 0 else 0.20, max_len=eighth * 0.9) + for b_ in (0, 2): + for nota in triad: + hit(nota - 12, t + b_ * beat, 0.13, max_len=beat * 1.8) + vuelta = (k // 4) % 2 # la segunda vuelta, una octava arriba + for (b_, nota, d) in MELODIAS[estilo][k % 4]: + hit(nota + 12 * vuelta, t + b_ * beat, 0.30, max_len=d * beat * 1.05) + t += measure + k += 1 + continue + hit(bass, t, 0.50, max_len=measure * 0.95) + hit(bass + 12, t + 2 * beat, 0.26, max_len=beat * 1.6) + pattern = [triad[0], triad[1], triad[2], triad[1], + triad[2], triad[1], triad[2], triad[0]] + for j, note in enumerate(pattern): + g = 0.30 if j % 2 == 0 else 0.20 + hit(note, t + j * eighth, g, max_len=beat * 1.15) + if k % 4 == 3: # brillito al cerrar la vuelta + hit(triad[2] + 12, t + 3.5 * beat, 0.16, max_len=beat) + t += measure + k += 1 + + buf = buf[:int(total_s * SR)] + peak = np.abs(buf).max() + 1e-9 + buf *= gain / peak + # entrada y salida suaves + fi, fo = int(1.2 * SR), int(2.0 * SR) + buf[:fi] *= np.linspace(0, 1, fi)[:, None] + buf[-fo:] *= np.linspace(1, 0, fo)[:, None] + return buf + + +def duck(music, speech, sr=SR, floor_db=-11.0, block=512, release=0.45): + """Baja la musica cuando hay voz (sidechain simple).""" + mono = np.abs(speech).mean(axis=1) if speech.ndim > 1 else np.abs(speech) + nb = len(mono) // block + env = mono[:nb * block].reshape(nb, block).max(axis=1) + rel = np.exp(-block / (release * sr)) + out = np.zeros(nb, dtype=np.float32) + acc = 0.0 + for i, v in enumerate(env): + acc = v if v > acc else acc * rel + v * (1 - rel) + out[i] = acc + g_floor = 10 ** (floor_db / 20) + active = np.clip(out / 0.03, 0, 1) + gain = 1.0 - (1.0 - g_floor) * active + idx = np.linspace(0, nb - 1, len(music)) + g = np.interp(idx, np.arange(nb), gain).astype(np.float32) + return music * g[:, None] diff --git a/scripts/narration.py b/scripts/narration.py new file mode 100644 index 0000000..d151fa8 --- /dev/null +++ b/scripts/narration.py @@ -0,0 +1,431 @@ +# -*- coding: utf-8 -*- +"""Guiones de los 5 videos. 'tts' = texto que se locuta (numeros en letras), +'sub' = subtitulo en pantalla (mas corto y legible).""" + +SCRIPTS = { + +"montyhall": { + "title": "El juego que casi todos pierden", + "segments": [ + ("Tres puertas. Atras de una hay un auto cero kilometro.", "3 puertas.\nAtrás de una: un auto 0 km."), + ("Atras de las otras dos, una cabra.", "Atrás de las otras dos:\nuna cabra."), + ("Vos elegis la puerta uno.", "Elegís la puerta 1."), + ("El conductor, que sabe donde esta el auto, abre la puerta tres. Cabra.", "El conductor abre la 3.\nCabra."), + ("Y te pregunta: te quedas con la uno, o cambias a la dos?", "¿Te quedás con la 1\no cambiás a la 2?"), + ("Casi todos dicen que da igual. Cincuenta y cincuenta. Y estan mal.", "Casi todos dicen 50 y 50.\nEstán mal."), + ("Cuando elegiste, tenias un tercio de chance de acertar. Eso nunca cambio.", "Cuando elegiste tenías 1/3.\nEso no cambió."), + ("O sea que las otras dos puertas juntas suman dos tercios.", "Las otras dos juntas: 2/3."), + ("El conductor te saco la mala. Todo ese dos tercios se mudo a la puerta dos.", "Él te sacó la mala.\nLos 2/3 se mudan a la 2."), + ("Si cambias, ganas el sesenta y siete por ciento de las veces. El doble.", "Cambiando ganás el 67%.\nEl doble."), + ("Cambia siempre. Y escribi abajo si vos tambien decias cincuenta y cincuenta.", "Cambiá siempre.\n¿Vos qué decías?"), + ], +}, + +"nueves": { + "title": "0.999... es igual a 1", + "segments": [ + ("Cero coma nueve, nueve, nueve, infinitos nueves.", "0,999999...\ninfinitos nueves"), + ("Eso es exactamente igual a uno. Y te vas a enojar.", "Eso es exactamente = 1.\nY te vas a enojar."), + ("Ya se lo que pensas: le falta un poquito.", "«Le falta un poquito»"), + ("Perfecto. Decime cuanto le falta. Escribi ese numero.", "Decime cuánto le falta.\nEscribilo."), + ("No podes. Porque si existiera un numero en el medio, yo le agrego mas nueves y te lo paso.", "No podés.\nSiempre agrego otro 9."), + ("Y dos numeros sin nada en el medio son el mismo numero.", "Dos números sin nada\nen el medio son el mismo."), + ("Mira la prueba mas linda. Un tercio es cero coma tres periodico.", "1/3 = 0,3333..."), + ("Multiplicamos los dos lados por tres.", "×3 de los dos lados"), + ("Tres tercios es uno. Y cero coma tres periodico por tres es cero coma nueve periodico.", "3/3 = 1\n0,333... × 3 = 0,999..."), + ("Listo. Son el mismo numero. No se acerca a uno: es uno.", "Son el mismo número.\nNo se acerca: ES 1."), + ("Deci en los comentarios si te convenci o si me queres pelear.", "¿Te convencí\no me querés pelear?"), + ], +}, + +"cumple": { + "title": "La paradoja del cumpleaños", + "segments": [ + ("Cuanta gente necesitas en una pieza para que dos cumplan el mismo dia?", "¿Cuánta gente para que dos\ncumplan el mismo día?"), + ("La mayoria dice ciento ochenta y pico. La respuesta es veintitres.", "La mayoría dice 180.\nLa respuesta: 23."), + ("Con veintitres personas ya tenes cincuenta por ciento de chance. Mitad y mitad.", "Con 23 personas: 50%.\nMitad y mitad."), + ("El error es pensar que te comparas vos contra todos los demas.", "El error: pensar que sos\nvos contra todos."), + ("Pero no. Se comparan todos contra todos.", "Se comparan\ntodos contra todos."), + ("Con veintitres personas hay doscientos cincuenta y tres parejas posibles.", "23 personas =\n253 parejas posibles."), + ("Cada pareja tiene una chance chiquita. Pero doscientas cincuenta y tres veces.", "Chance chica,\npero 253 veces."), + ('Con treinta personas, ya es el setenta por ciento.', '30 personas → 70%'), + ('Con cincuenta personas, el noventa y siete por ciento.', '50 personas → 97%'), + ('Con setenta personas, el noventa y nueve coma nueve. Practicamente seguro.', '70 personas → 99,9%'), + ("Probalo en tu grupo del trabajo. Despues me contas.", "Probalo en tu grupo.\nDespués contame."), + ], +}, + +"luna": { + "title": "Doblar un papel hasta la Luna", + "segments": [ + ("Agarra una hoja de papel y doblala cuarenta y dos veces. Llegas a la Luna.", "Doblá una hoja 42 veces\ny llegás a la Luna."), + ("Suena a mentira. Hagamos la cuenta juntos.", "Suena a mentira.\nHagamos la cuenta."), + ("Una hoja mide un decimo de milimetro de espesor.", "1 hoja = 0,1 mm"), + ("Un doblez, dos decimos. Dos dobleces, cuatro decimos.", "1 doblez: 0,2 mm\n2 dobleces: 0,4 mm"), + ("Con diez dobleces tenes diez centimetros. Un ladrillo.", "10 dobleces → 10 cm"), + ("Con veinte dobleces, cien metros. Un edificio de treinta pisos.", "20 dobleces → 100 m"), + ("Con treinta dobleces, cien kilometros. Ya saliste de la atmosfera.", "30 dobleces → 100 km\n(fuera de la atmósfera)"), + ("Con cuarenta dobleces, cien mil kilometros.", "40 dobleces → 100.000 km"), + ("Con cuarenta y dos, cuatrocientos cuarenta mil kilometros.", "42 dobleces →\n440.000 km"), + ("Y la Luna esta a trescientos ochenta y cuatro mil. Te pasaste de largo.", "La Luna está a 384.000 km.\nTe pasaste."), + ("Eso es crecimiento exponencial. Por eso nadie lo ve venir.", "Eso es crecimiento\nexponencial."), + ], +}, + +"japones": { + "title": "Multiplicar con líneas", + "segments": [ + ("Asi multiplican en Japon y no necesitas saberte las tablas.", "Así multiplican en Japón.\nSin tablas."), + ("Vamos con veintiuno por trece.", "21 × 13"), + ("El veintiuno lo dibujas asi: dos lineas, espacio, una linea.", "21 → 2 líneas\ny 1 línea"), + ('El trece va cruzado. Una linea, y despues tres lineas.', '13 → 1 línea\ny 3 líneas'), + ('Ahora contas los cruces por zona. La zona izquierda tiene dos cruces.', 'Zona izquierda:\n2 cruces'), + ("Zona del medio: seis mas uno. Siete cruces.", "Zona del medio:\n6 + 1 = 7"), + ("Zona derecha: tres cruces.", "Zona derecha:\n3 cruces"), + ("Dos, siete, tres. Doscientos setenta y tres.", "2 | 7 | 3\n= 273"), + ('Y efectivamente, veintiuno por trece da doscientos setenta y tres.', '21 × 13 = 273 ✓'), + ("Si una zona te da mas de nueve, llevas una a la de al lado. Igual que siempre.", "¿Más de 9?\nLlevás una al lado."), + ("Guardalo para cuando tus hijos te pidan ayuda con la tarea.", "Guardalo para\nla tarea de tus hijos."), + ], +}, + + +"benford": { + "title": 'Así se detecta el fraude', + "segments": [ + ('Agarra cualquier lista de numeros reales. Facturas, poblaciones, sueldos.', 'Cualquier lista real:\nfacturas, sueldos, ciudades'), + ('Fijate con que digito empiezan. Uno, dos, tres.', '¿Con qué dígito\nempiezan?'), + ('Vos dirias que todos aparecen mas o menos lo mismo. Once por ciento cada uno.', 'Dirías: 11% cada uno.'), + ('Y no. El uno aparece el treinta por ciento de las veces.', 'El 1 aparece el 30%\nde las veces.'), + ('El dos, el diecisiete. Y va bajando hasta el nueve, que aparece el cuatro por ciento.', 'El 2: 17%.\nEl 9: apenas 4%.'), + ('Se llama ley de Benford, y pasa en casi todo lo que crece.', 'Ley de Benford'), + ('Poblaciones, precios, likes, el largo de los rios.', 'Poblaciones, precios,\nlikes, ríos…'), + ('Y aca viene lo bueno. Cuando alguien inventa numeros, los inventa parejos.', 'El que inventa números\nlos inventa parejos.'), + ('Entonces el patron se rompe, y eso se ve de lejos.', 'El patrón se rompe.'), + ('Asi agarraron fraudes contables y elecciones dibujadas, de verdad.', 'Así agarraron fraudes\ncontables reales.'), + ('Proba con los gastos de tu tarjeta. Te va a dar.', 'Probá con tu\nresumen de tarjeta.'), + ], +}, + +"hilbert": { + "title": 'El hotel infinito', + "segments": [ + ('Un hotel con infinitas habitaciones, y todas ocupadas.', 'Hotel con infinitas\nhabitaciones. Lleno.'), + ('Llega un huesped mas. Hay lugar?', 'Llega uno más.\n¿Hay lugar?'), + ('Si. El de la uno se pasa a la dos, el de la dos a la tres, y asi.', 'El 1 pasa a la 2,\nel 2 a la 3…'), + ('Todos se corren uno. La habitacion uno queda libre.', 'Todos se corren uno.\nLa 1 queda libre.'), + ('Ahora llegan infinitos huespedes de golpe. Ahi ya no entra nadie, no?', 'Ahora llegan INFINITOS.\n¿Ahí sí no entran?'), + ('Entran. Cada uno se pasa a la habitacion del doble de su numero.', 'Cada uno pasa\nal doble de su número.'), + ('El uno va a la dos, el dos a la cuatro, el tres a la seis.', '1→2, 2→4, 3→6…'), + ('Quedan libres todas las impares. Infinitas habitaciones vacias.', 'Quedan libres\ntodas las impares.'), + ('El hotel estaba lleno y le entraron infinitas personas mas.', 'Estaba lleno y entraron\ninfinitos más.'), + ('Eso es el infinito. No es un numero grande, es otra cosa.', 'El infinito no es\nun número grande.'), + ('Se llama hotel de Hilbert. Contaselo a alguien y mirale la cara.', 'Hotel de Hilbert.\nContáselo a alguien.'), + ], +}, + +"reuleaux": { + "title": 'Por qué son redondas', + "segments": [ + ('Por que las tapas de alcantarilla son redondas?', '¿Por qué las tapas\nson redondas?'), + ('Porque son las unicas que no se pueden caer adentro del pozo.', 'Porque no se pueden\ncaer adentro.'), + ('Una tapa cuadrada, girada en diagonal, se cae.', 'La cuadrada,\nen diagonal, se cae.'), + ('Porque la diagonal del cuadrado es mas larga que el lado.', 'La diagonal es más\nlarga que el lado.'), + ('El circulo no tiene ese problema. Mide lo mismo en todas las direcciones.', 'El círculo mide igual\nen toda dirección.'), + ('Pero ojo, que no es la unica figura que cumple eso.', 'No es la única\nque lo cumple.'), + ('Mira este triangulo con los lados curvos.', 'Mirá este triángulo\nde lados curvos.'), + ('Se llama triangulo de Reuleaux, y tambien mide lo mismo en todas las direcciones.', 'Triángulo de Reuleaux'), + ('Rueda perfecto entre dos paredes, aunque no sea redondo.', 'Rueda perfecto,\naunque no sea redondo.'), + ('Si lo usas de rueda, la carga de arriba no sube ni baja.', 'De rueda: la carga\nno sube ni baja.'), + ('Ahora ya sabes por que son redondas. Contalo en el proximo asado.', 'Contalo en\nel próximo asado.'), + ], +}, + +"regla72": { + "title": 'La regla del 72', + "segments": [ + ('Cuanto tarda tu plata en duplicarse? Hay una cuenta que te lo dice en dos segundos.', '¿Cuánto tarda tu plata\nen duplicarse?'), + ('Se llama la regla del setenta y dos.', 'La regla del 72'), + ('Dividis setenta y dos por la tasa anual, y te da los años.', '72 ÷ tasa anual\n= años'), + ('Al seis por ciento anual: setenta y dos dividido seis, doce años.', '6% anual →\n72 ÷ 6 = 12 años'), + ('Al nueve por ciento: ocho años.', '9% anual →\n8 años'), + ('Al doce por ciento: seis años.', '12% anual →\n6 años'), + ('Y lo mejor es que funciona para el otro lado tambien.', 'También funciona\nal revés.'), + ('Con treinta por ciento de inflacion anual, tu plata vale la mitad en dos años y medio.', '30% de inflación:\nvale la mitad en 2,4 años'), + ('Setenta y dos dividido treinta: dos coma cuatro.', '72 ÷ 30 = 2,4'), + ('Es una aproximacion, pero se clava.', 'Es aproximada,\npero se clava.'), + ('Guardate esta. Es la cuenta que mas veces vas a usar en tu vida.', 'Guardala.\nLa vas a usar siempre.'), + ], +}, + +"buffon": { + "title": 'Sacar pi tirando agujas', + "segments": [ + ('Te tiro agujas al piso y te saco el numero pi. En serio.', 'Tiro agujas al piso\ny sale π.'), + ('Piso rayado. La distancia entre rayas es igual al largo de la aguja.', 'Rayas separadas\nel largo de la aguja.'), + ('Ahora tiras agujas al azar. Muchas.', 'Tirás agujas\nal azar.'), + ('Algunas van a cruzar una raya. Otras no.', 'Algunas cruzan.\nOtras no.'), + ('Contas cuantas tiraste, y cuantas cruzaron.', 'Contás cuántas\ny cuántas cruzan.'), + ('Y dividis el doble del total por las que cruzaron.', '2 × total ÷ cruces'), + ('Y el resultado que te da es el numero pi.', '= π'), + ('Con sesenta agujas ya se acerca. Con doscientas, se acerca mucho mas.', '60 agujas: se acerca.\n200: mucho más.'), + ('Tres coma uno cuatro uno cinco.', '3,1415…'), + ('Y no hay ningun circulo en la escena. Igual aparece pi.', 'No hay ningún círculo.\nY aparece π.'), + ('Se llama aguja de Buffon. Lo podes hacer en tu casa con fosforos.', 'Aguja de Buffon.\nHacelo con fósforos.'), + ], +}, +"collatz": { + "title": "El problema que nadie pudo resolver", + "segments": [ + ('Agarra cualquier numero entero. El que se te ocurra.', 'Agarrá cualquier número.'), + ('Si es par, lo dividis por dos. Si es impar, lo multiplicas por tres y le sumas uno.', 'Par → ÷2\nImpar → ×3+1'), + ('Y repetis para siempre. Probemos con el seis.', 'Y repetís.\nProbemos con el 6.'), + ('Seis, tres, diez, cinco, dieciseis, ocho, cuatro, dos, uno.', '6 → 3 → 10 → 5 → 16\n→ 8 → 4 → 2 → 1'), + ('Cayo al uno. Probemos ahora con el siete.', 'Cayó al 1.\nAhora el 7.'), + ('Sube, baja, vuelve a subir mucho mas alto, y al final tambien termina en uno.', 'Sube, baja, sube más...\ny termina en 1.'), + ('El veintisiete es el mas rebelde. Trepa hasta nueve mil doscientos treinta y dos.', 'El 27 trepa\nhasta 9.232.'), + ('Pero despues de ciento once pasos, tambien se cae al uno.', 'Y en 111 pasos\ncae al 1.'), + ('Lo probaron con computadoras hasta numeros de veinte cifras. Todos, absolutamente todos, caen al uno.', 'Probado hasta\n20 cifras. Todos caen.'), + ('Pero nadie en el mundo consiguio demostrarlo. Hace casi noventa años que el problema sigue abierto.', 'Nadie pudo demostrarlo.\n90 años abierto.'), + ('Se llama conjetura de Collatz. Deja tu numero en los comentarios y lo probamos.', 'Conjetura de Collatz.\nDejá tu número.'), + ], +}, + +"simpson": { + "title": "El promedio te está mintiendo", + "segments": [ + ('Dos tratamientos para la misma enfermedad. Les decimos A y B.', 'Dos tratamientos: A y B.'), + ('En los casos leves, el A cura al noventa y tres por ciento. El B, al ochenta y siete.', 'Casos leves:\nA 93% · B 87%'), + ('Gana el A. Y en los casos graves, el A cura al setenta y tres por ciento. El B, al sesenta y nueve.', 'Gana A.\nGraves: A 73% · B 69%'), + ('Tambien gana el A. Entonces el A es mejor siempre, no?', 'Gana A otra vez.\nA es mejor, ¿no?'), + ('Sumamos todos los pacientes. El A cura al setenta y ocho por ciento. El B, al ochenta y tres.', 'Todos juntos:\nA 78% · B 83%'), + ('Gana el B. Y no hay ningun error en las cuentas.', 'Gana B.\nY no hay ningún error.'), + ('Esto se llama la paradoja de Simpson, y pasa por como estan repartidos los pacientes.', 'Paradoja de Simpson.'), + ('Casi todos los casos graves, que son los dificiles de curar, se los dieron al tratamiento A.', 'A recibió casi todos\nlos casos graves.'), + ('Al B le mandaron casi todos los leves, que son faciles. Por eso su promedio sube.', 'B recibió los leves.\nPor eso su promedio sube.'), + ('El promedio total esta mezclando dos grupos distintos. Y esos numeros son reales, salen de un estudio medico.', 'El promedio mezcla\ndos grupos distintos.'), + ('Cada vez que te muestren un promedio, pregunta: promedio de quienes? Mandaselo al que te tira estadisticas.', 'Preguntá siempre:\n¿promedio de quiénes?'), + ], +}, + +"cuerda": { + "title": "Una cuerda alrededor de la Tierra", + "segments": [ + ('Imaginate una cuerda que da toda la vuelta a la Tierra, pegadita al suelo, por el ecuador.', 'Una cuerda que rodea\nla Tierra entera.'), + ('Son unos cuarenta mil kilometros de cuerda.', '40.000 km de cuerda.'), + ('Ahora le agregamos un metro. Un metro solo.', 'Le agregamos 1 metro.'), + ('Y la levantamos pareja, a la misma altura en todo el planeta.', 'Y la levantamos pareja\nen todo el planeta.'), + ('Cuanto se separa del suelo? Casi todos dicen que nada, un pelo.', '¿Cuánto se separa?\nCasi nadie acierta.'), + ('Se separa quince coma nueve centimetros. Te pasa un gato caminando por abajo.', '15,9 cm.\nPasa un gato por abajo.'), + ('La cuenta es de una sola linea. El radio de un circulo es su perimetro dividido dos pi.', 'radio = perímetro ÷ 2π'), + ('Si al perimetro le sumas un metro, el radio crece un metro dividido dos pi.', '+1 m de perímetro\n→ +1÷2π de radio'), + ('Eso da quince coma nueve centimetros. Y fijate bien: el tamaño de la Tierra no aparece en la cuenta.', '= 15,9 cm\nLa Tierra ni aparece.'), + ('O sea que si haces lo mismo con una pelota de tenis, la cuerda tambien se levanta quince coma nueve centimetros.', 'Con una pelota de tenis:\ntambién 15,9 cm.'), + ('El tamaño no importa. Mandaselo al que te dijo que no se levantaba nada.', 'El tamaño no importa.\nMandáselo al que dudó.'), + ], +}, + +"gabriel": { + "title": "La figura que no se puede pintar", + "segments": [ + ('Esta figura rompe la cabeza. Se llama el cuerno de Gabriel.', 'El cuerno de Gabriel.'), + ('Agarras la curva uno dividido equis, y la haces girar como en un torno.', 'Tomás y = 1÷x\ny la hacés girar.'), + ('Te queda un cuerno infinito, cada vez mas finito, que nunca termina.', 'Un cuerno infinito,\ncada vez más fino.'), + ('Primera pregunta: cuanta pintura entra adentro?', '¿Cuánta pintura\nentra adentro?'), + ('El volumen da exactamente pi. Un numero finito. Tres litros y monedas.', 'Volumen = π\n≈ 3,14 litros'), + ('Lo llenas con un balde chico y te sobra.', 'Lo llenás con un balde\ny te sobra.'), + ('Segunda pregunta: y si lo queres pintar por fuera?', '¿Y si lo pintás\npor fuera?'), + ('La superficie es infinita. No te alcanza toda la pintura del universo.', 'La superficie\nes INFINITA.'), + ('O sea: podes llenarlo de pintura por dentro, pero no podes pintarlo.', 'Podés llenarlo,\npero no pintarlo.'), + ('La trampa es que la pintura de verdad tiene espesor, y el cuerno se hace mas fino que cualquier espesor.', 'La trampa: la pintura\nreal tiene espesor.'), + ('Con el infinito, la intuicion se rompe. Segui para mas matematica rara.', 'Con el infinito\nla intuición se rompe.'), + ], +}, + +"mobius": { + "title": "Cortá esto y no vas a creer", + "segments": [ + ('Agarra una tira de papel. Cualquiera sirve.', 'Agarrá una tira de papel.'), + ('Le das media vuelta a una punta, y recien ahi pegas los dos extremos.', 'Media vuelta\ny pegá las puntas.'), + ('Eso es una cinta de Mobius, y tiene una sola cara.', 'Cinta de Möbius.\nUna sola cara.'), + ('Si apoyas el dedo y lo arrastras sin levantarlo, pintas todo. El adentro y el afuera son lo mismo.', 'Pintás todo\nsin levantar el dedo.'), + ('Tambien tiene un solo borde. Es un camino unico que da dos vueltas enteras.', 'Y un solo borde.'), + ('Ahora hace esto: cortala al medio, a lo largo, hasta volver al principio.', 'Cortala al medio,\na lo largo.'), + ('Esperarias que queden dos cintas. Pero no. Queda una sola, el doble de larga.', 'No salen dos.\nSale una, el doble de larga.'), + ('Y esa cinta nueva ya tiene dos caras. Perdio la magia.', 'Y esa ya tiene\ndos caras.'), + ('Probemos de nuevo, con otra cinta. Pero ahora cortando a un tercio del borde.', 'Otra vez, pero cortando\na 1/3 del borde.'), + ('Salen dos cintas de distinto tamaño, y quedan enganchadas una con la otra.', 'Salen 2 cintas,\nenganchadas entre sí.'), + ('Agarra una hoja y la cinta de embalar y hacelo ahora. Te espero en los comentarios.', 'Hacelo en casa.\nContame cómo te fue.'), + ], +}, + + +"bayes": { + "title": "Tu test dio positivo", + "segments": [ + ('Te haces un analisis para detectar una enfermedad. El test acierta el noventa y nueve por ciento de las veces.', 'Un test que acierta\nel 99% de las veces.'), + ('Te da positivo. Que chance hay de que estes enfermo de verdad?', 'Te da POSITIVO.\n¿Qué chance hay\nde estar enfermo?'), + ('Casi todos contestan noventa y nueve por ciento. Un monton de medicos tambien.', 'Casi todos dicen 99%.\nMuchos médicos también.'), + ('Es nueve por ciento. Y el test no fallo: esta funcionando perfecto.', 'Es 9%.\nY el test no falló.'), + ('Mira. Esta enfermedad la tiene una persona de cada mil.', 'La enfermedad la tiene\n1 de cada 1000.'), + ('Juntamos mil personas. Una sola esta enferma.', '1000 personas.\nUna está enferma.'), + ('Les hacemos el test a todas. A la enferma la encuentra.', 'El test la encuentra.\n1 positivo verdadero.'), + ('Pero con las novecientas noventa y nueve sanas se equivoca en el uno por ciento.', 'Con las 999 sanas\nse equivoca en el 1%.'), + ('Son diez personas sanas que dieron positivo.', '10 personas sanas\ncon test positivo.'), + ('Once positivos en total, y una sola enferma. Uno sobre once es nueve por ciento.', '11 positivos.\n1 enferma. 1/11 = 9%'), + ('Si la enfermedad es rara, el primer positivo casi siempre es falso. Por eso el test se repite. Mandaselo a alguien que se asusta con los numeros.', 'Si es rara, el 1er positivo\ncasi siempre es falso.'), + ], +}, + +"cicloide": { + "title": "¿Cuál pelota llega primero?", + "segments": [ + ('Dos pelotas. Salen de la misma altura y llegan al mismo punto.', 'Dos pelotas.\nMisma altura, misma meta.'), + ('Una baja por la recta. La otra por esta curva rara.', 'Una por la recta.\nLa otra por esta curva.'), + ('Cual llega primero? Decidilo antes de que largue.', '¿Cuál llega primero?'), + ('La recta es el camino mas corto entre dos puntos. Eso no se discute.', 'La recta es el camino\nmás CORTO.'), + ('Pero el mas corto no es el mas rapido. Largamos.', 'Corto no es lo mismo\nque rápido.'), + ('Gano la curva, y por bastante. Encima baja mas abajo que la meta y vuelve a subir.', 'Ganó la curva.\nY hasta baja de más.'), + ('El truco es que cae de una al principio, agarra velocidad temprano y la usa todo el resto del camino.', 'Cae fuerte al principio\ny agarra velocidad.'), + ('La curva se llama cicloide, y es la que dibuja un clavito clavado en la rueda de una bici.', 'Se llama CICLOIDE.'), + ('Y tiene un regalo aparte. Soltamos tres pelotas desde tres alturas distintas.', 'Bonus: 3 pelotas,\n3 alturas distintas.'), + ('Llegan al fondo exactamente al mismo tiempo. Siempre.', 'Llegan al fondo\nAL MISMO TIEMPO.'), + ('Bernoulli tiro este problema en mil seiscientos noventa y seis. Newton lo resolvio esa misma noche. Vos le habias pegado?', '1696: Bernoulli desafía.\nNewton lo resuelve\nen una noche.'), + ], +}, + + + +"dados": { + "title": "Elegí primero y perdés igual", + "segments": [ + ('Mira estos tres dados. Elegis el que quieras, y despues elijo yo.', 'Tres dados raros.\nElegís primero.'), + ('Tiramos los dos y gana el numero mas alto. Suena a que te di ventaja.', 'Tiramos.\nGana el número más alto.'), + ('Elijas el que elijas, yo agarro otro y te gano el cincuenta y seis por ciento de las veces.', 'Elijas el que elijas,\nte gano el 56%.'), + ('Mira las caras. El rojo tiene dos, cuatro y nueve, cada numero repetido en dos caras.', 'Rojo: 2, 4 y 9.'), + ('El celeste tiene uno, seis y ocho. Y el verde, tres, cinco y siete.', 'Celeste: 1, 6 y 8.\nVerde: 3, 5 y 7.'), + ('Cruzamos rojo contra celeste. Nueve duelos posibles, y el rojo gana cinco.', 'Rojo vs celeste:\ngana rojo, 5 de 9.'), + ('Ahora celeste contra verde. Otra vez cinco de nueve, esta vez para el celeste.', 'Celeste vs verde:\ngana celeste, 5 de 9.'), + ('Entonces el rojo le tiene que ganar al verde, no? No.', 'Entonces rojo le gana\nal verde, ¿no?'), + ('El verde le gana al rojo, tambien cinco de nueve. La cadena se muerde la cola.', 'NO.\nVerde le gana al rojo.'), + ('No existe un dado invencible. Se ganan en circulo, como piedra, papel o tijera.', 'No hay dado invencible.\nSe ganan en círculo.'), + ('Por eso lo mejor es elegir segundo. Deci en los comentarios cual hubieses agarrado vos.', 'Por eso lo mejor\nes elegir SEGUNDO.'), + ], +}, + + + +"bolapeluda": { + "title": "No podés peinar una esfera", + "segments": [ + ('Esta esfera esta llena de pelos. Uno en cada punto.', 'Una esfera\nllena de pelos.'), + ('Tu mision es peinarlos todos, sin dejar ni uno parado.', 'Peinalos todos.\nNinguno parado.'), + ('Arrancamos. Todos para el mismo lado, dando la vuelta.', 'Todos para\nel mismo lado.'), + ('Mira los polos. Ahi quedaron dos remolinos.', 'Arriba y abajo:\ndos remolinos.') + , + ('Probemos otro peinado, de arriba hacia abajo.', 'Probamos otro\npeinado.'), + ('Otra vez. Quedan dos puntos donde el pelo queda parado.', 'Otra vez quedan\npuntos parados.'), + ('No sos vos. Es un teorema, y lo probo Brouwer en mil novecientos doce.', 'No sos vos:\nes un teorema.'), + ('Peines como peines una esfera, siempre queda al menos un remolino.', 'Siempre queda\nal menos uno.'), + ('Por eso ahora mismo hay un punto del planeta sin nada de viento horizontal.', 'Por eso siempre hay\nun punto sin viento.'), + ('Y en una rosquilla? Ahi si se puede peinar todo, sin un solo remolino.', 'En una rosquilla\nSÍ se puede.'), + ('El numero que las separa cuenta agujeros: la esfera da dos, la rosquilla da cero. Contame si vos le encontras la vuelta.', 'Esfera 2, rosquilla 0.\n¿Le encontrás la vuelta?'), + ], +}, + +"caos": { + "title": "Un milímetro cambia todo", + "segments": [ + ('Tres pendulos dobles, exactamente iguales.', 'Tres péndulos dobles\nexactamente iguales.'), + ('Bueno, casi. El rosa arranca un milimetro mas arriba que el amarillo.', 'Casi: el rosa arranca\n1 mm más arriba.'), + ('Y el celeste, un milimetro mas que el rosa.', 'Y el celeste, 1 mm\nmás que el rosa.'), + ('Los soltamos a los tres en el mismo instante.', 'Los soltamos\nal mismo tiempo.'), + ('Al principio se mueven como si fueran uno solo.', 'Al principio\nse mueven juntos.'), + ('A los dos segundos ya se empiezan a separar.', 'A los 2 segundos\nse separan.'), + ('Y a los cinco no tienen nada que ver entre si.', 'A los 5 ya no\ntienen nada que ver.'), + ('Nadie los toco. La ecuacion es la misma para los tres.', 'Nadie los tocó.\nMisma ecuación.'), + ('Eso es caos: el error del arranque se multiplica solo, cada vez mas rapido.', 'Eso es CAOS:\nel error se multiplica.'), + ('Por eso el pronostico del tiempo se cae despues de una semana. No faltan datos: falta precision infinita.', 'Por eso el clima\nno se predice a 15 días.'), + ('Para acertarle al mes que viene habria que medir hoy con infinitos decimales. Volve al principio y fijate en que segundo se separan.', 'Volvé al principio:\n¿en qué segundo\nse separan?'), + ], +}, + +"diferencial": { + "title": "Por qué tu auto puede doblar", + "segments": [ + ('Cuando un auto dobla, la rueda de afuera recorre mas camino que la de adentro.', 'Al doblar, la rueda de afuera\nrecorre más camino.'), + ('Si las dos estuvieran clavadas al mismo eje, una tendria que patinar.', 'Con un eje rígido,\nuna tiene que patinar.'), + ('El invento que lo arregla lo tenes abajo del auto: el diferencial.', 'Eso lo arregla\nel DIFERENCIAL.'), + ('Son cuatro engranajes conicos metidos en una jaula.', 'Cuatro engranajes cónicos\nen una jaula.'), + ('Dos van a las ruedas, uno de cada lado.', 'Dos van a las ruedas.'), + ('Los otros dos los conectan, y viajan montados en la jaula.', 'Otros dos\nlos conectan.'), + ('El motor hace girar la jaula entera. Eso es lo unico que entra.', 'El motor hace girar\nla jaula.'), + ('En recta, los del medio no giran sobre si mismos, y las dos ruedas van igual.', 'En recta: las dos\nruedas van igual.'), + ('Cuando doblas, la rueda de adentro se frena, los del medio empiezan a girar y le pasan esa vuelta a la de afuera.', 'Al doblar: una frena\ny la otra acelera.'), + ('Lo que pierde una lo gana la otra. La suma siempre da lo mismo.', 'Lo que pierde una,\nlo gana la otra.'), + ('Lo patentaron en mil ochocientos veintisiete y lo tenes abajo del auto ahora mismo. Guardatelo para la proxima charla de asado.', 'Patentado en 1827.\nLo tenés abajo del auto.'), + ], +}, + + + +"galton": { + "title": "La campana que nadie dibuja", + "segments": [ + ('Quinientas bolitas de acero contra un tablero lleno de clavos.', '500 bolitas de acero\ncontra un tablero de clavos.'), + ('En cada clavo, la bolita rebota para un lado o para el otro. Al azar.', 'En cada clavo rebota\npara un lado o el otro.'), + ('Nadie puede adivinar donde va a caer una sola.', 'Nadie adivina dónde\ncae UNA bolita.'), + ('Pero mira lo que forman todas juntas.', 'Pero mirá lo que forman\ntodas juntas.'), + ('Una campana. Y sale siempre la misma forma, tires las veces que tires.', 'Una campana.\nSiempre la misma forma.'), + ('Para terminar en una punta, la bolita tiene que rebotar para el mismo lado doce veces seguidas.', 'Para caer en la punta:\n12 rebotes al mismo lado.'), + ('Para caer en el medio hay novecientos veinticuatro caminos distintos. Por eso se amontonan ahi.', 'Para caer al medio:\n924 caminos distintos.'), + ('Sumar muchas cosas chiquitas al azar siempre da esta campana. Se llama distribucion normal.', 'Muchas cosas al azar:\ndistribución NORMAL.'), + ('Por eso la altura de la gente o los errores de una medicion tienen la misma forma.', 'Alturas, errores de medición:\nla misma campana.'), + ('Ninguna bolita esta animada a mano. Cada rebote que ves es fisica pura.', 'Nada animado a mano:\ncada rebote es física.'), + ('Fijate la columna del medio y comenta cuantas bolitas pensas que tiene.', '¿Cuántas bolitas tiene\nla columna del medio?'), + ], +}, + +"bloques": { + "title": "Bloques que flotan fuera de la mesa", + "segments": [ + ('Bloques iguales y una mesa. Se pueden apilar para que el de arriba quede entero en el aire?', '¿Se puede apilar para que\nel de arriba quede en el aire?'), + ('Lo obvio es correr cada uno la mitad. Y se viene abajo.', 'Lo obvio: correr cada uno\nla mitad. Y se cae.'), + ('El truco es armarla desde arriba.', 'El truco: armarla\ndesde arriba.'), + ('El de arriba sobresale medio bloque. El siguiente, un cuarto. Despues un sexto, un octavo y un decimo.', '1/2, 1/4, 1/6,\n1/8, 1/10...'), + ('Con cinco bloques, el de arriba ya quedo entero afuera de la mesa. Y no se cae.', 'Con 5 bloques, el de arriba\nya está en el aire.'), + ('Cada bloque sostiene el centro de todo lo que tiene encima justo en su borde.', 'Cada uno sostiene lo de arriba\njusto en su borde.'), + ('Si seguis agregando, sobresale cada vez mas, sin limite. Es la serie armonica, que nunca deja de crecer.', 'Crece sin límite:\nla serie armónica.'), + ('Pero muy despacio: para sobresalir tres bloques enteros necesitas doscientos veintisiete.', 'Para sobresalir 3 bloques:\n¡227 bloques!'), + ('Eso si, esta al limite. Le apoyo un solo bloque mas arriba y...', 'Está al límite.\nUn bloque más y...'), + ('Y se derrumba. Un solo bloque de mas alcanza para tirarla.', 'Se derrumba.\nUn bloque de más alcanza.'), + ('Proba con libros en tu casa y conta en los comentarios hasta donde llegaste.', 'Probalo con libros\ny contá hasta dónde llegaste.'), + ], +}, + + +"domino": { + "title": "Una ficha de 5 mm que tira un edificio", + "segments": [ + ('Esta ficha de domino mide cinco milimetros. Y puede tirar un edificio.', 'Esta ficha mide 5 mm.\nY puede tirar un edificio.'), + ('El truco: una ficha puede voltear a otra una vez y media mas grande que ella.', 'Una ficha puede tirar\na otra 1,5 veces más grande.'), + ('Asi que armo trece fichas, cada una una vez y media mas grande que la anterior.', '13 fichas, cada una\n1,5 veces más grande.'), + ('La ultima ya mide sesenta y cinco centimetros. Le doy un toquecito a la primera.', 'La última mide 65 cm.\nUn toquecito a la primera...'), + ('Y mira como se cae todo.', 'Y mirá.'), + ('Otra vez, en camara lenta: cada ficha cae con mas fuerza que la anterior, y el empujon se multiplica.', 'En cámara lenta:\ncada caída empuja más fuerte.'), + ('La primera pesa menos que un grano de arroz. La ultima, quince kilos.', 'La primera: menos que un arroz.\nLa última: 15 kilos.'), + ('Eso es crecimiento exponencial: multiplicar por uno coma cinco, una y otra vez.', 'Crecimiento EXPONENCIAL:\n×1,5 una y otra vez.'), + ('Un fisico lo probo en mil novecientos ochenta y tres, con fichas de verdad. Y funciona.', 'Probado en 1983\ncon fichas de verdad.'), + ('Ahora imaginate que seguimos agregando fichas.', 'Ahora imaginá\nque seguimos.'), + ('La ficha dieciseis ya es mas alta que vos.', 'La ficha 16:\nmás alta que vos.'), + ('La veinticinco es mas alta que el Obelisco.', 'La 25: más alta\nque el Obelisco.'), + ('La veintinueve pasa al Empire State.', 'La 29: más alta\nque el Empire State.'), + ('Y la treinta y seis es mas alta que el Aconcagua.', 'La 36: más alta\nque el Aconcagua.'), + ('Treinta y seis fichas. Y a la primera la tiras con un soplido.', '36 fichas.\nLa primera, con un soplido.'), + ('Asi es una reaccion en cadena: algo chiquito que se multiplica sin parar.', 'Reacción en cadena:\nalgo chico que se multiplica.'), + ('Guardalo para cuando alguien te diga que un empujoncito no cambia nada.', 'Guardalo para cuando digan\nque un empujón no cambia nada.'), + ('Una casa mide unos ocho metros. Comenta en que ficha pensas que se cae.', 'Una casa: 8 metros.\n¿En qué ficha se cae?'), + ], +}, + +} diff --git a/scripts/numspell.py b/scripts/numspell.py new file mode 100644 index 0000000..2e416e3 --- /dev/null +++ b/scripts/numspell.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +"""Pasa los numeros de una transcripcion a palabras, para poder compararla +con el guion (que escribe todo en letras).""" +import re + +U = ["cero", "uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", + "diez", "once", "doce", "trece", "catorce", "quince", "dieciseis", "diecisiete", + "dieciocho", "diecinueve", "veinte", "veintiuno", "veintidos", "veintitres", + "veinticuatro", "veinticinco", "veintiseis", "veintisiete", "veintiocho", "veintinueve"] +D = {3: "treinta", 4: "cuarenta", 5: "cincuenta", 6: "sesenta", + 7: "setenta", 8: "ochenta", 9: "noventa"} +C = {1: "ciento", 2: "doscientos", 3: "trescientos", 4: "cuatrocientos", 5: "quinientos", + 6: "seiscientos", 7: "setecientos", 8: "ochocientos", 9: "novecientos"} + + +def _lt1000(n): + if n < 30: + return U[n] + if n < 100: + d, u = divmod(n, 10) + return D[d] + (" y " + U[u] if u else "") + if n == 100: + return "cien" + c, r = divmod(n, 100) + return C[c] + (" " + _lt1000(r) if r else "") + + +def spell_int(n): + if n < 1000: + return _lt1000(n) + if n < 1000000: + m, r = divmod(n, 1000) + pre = "mil" if m == 1 else _lt1000(m) + " mil" + return pre + (" " + _lt1000(r) if r else "") + m, r = divmod(n, 1000000) + pre = "un millon" if m == 1 else _lt1000(m) + " millones" + return pre + (" " + spell_int(r) if r else "") + + +def _tok(m): + s = m.group(0) + s = re.sub(r"\.(?=\d{3}\b)", "", s) # 384.000 -> 384000 + if "," in s: + a, b = s.split(",", 1) + ent = spell_int(int(a or 0)) + dec = " ".join(U[int(c)] for c in b if c.isdigit()) + return f"{ent} coma {dec}" + if "." in s: # 0.5 estilo ingles + a, b = s.split(".", 1) + return f"{spell_int(int(a or 0))} coma " + " ".join(U[int(c)] for c in b if c.isdigit()) + return spell_int(int(s)) + + +def expand(text): + t = text.replace("%", " por ciento ").replace("º", "") + t = re.sub(r"\d+(?:[.,]\d+)*", _tok, t) + return re.sub(r"\s+", " ", t).strip() diff --git a/scripts/regen.py b/scripts/regen.py new file mode 100644 index 0000000..7ff69a8 --- /dev/null +++ b/scripts/regen.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +"""Regenera segmentos puntuales probando varias semillas y quedandose con la mejor.""" +import json, os, subprocess, sys, shutil +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from narration import SCRIPTS +from gen_audio import synth_seguro, transcribe, dur, ROOT +from verify import norm +from difflib import SequenceMatcher + +TRIES = 5 + + +def main(name, idxs): + outdir = os.path.join(ROOT, "audio", name) + work = os.path.join(ROOT, "tmp", name + "_rg") + os.makedirs(work, exist_ok=True) + data = json.load(open(os.path.join(outdir, "segments.json"), encoding="utf-8")) + segs = SCRIPTS[name]["segments"] + + for i in idxs: + text = segs[i][0] + cands = [] + for k in range(TRIES): + c = os.path.join(work, f"{i:02d}_{k}.wav") + synth_seguro(text, c, 4242 + 977 * k, f"[{name}] {i:02d}") + cands.append(c) + tr = transcribe(cands, work) + scored = sorted(((SequenceMatcher(None, norm(text, False), + norm(tr[c], False)).ratio(), c) for c in cands), + reverse=True) + for r, c in scored: + print(f" {i:02d} seed{cands.index(c)} r={r:.2f} {dur(c):.2f}s | {tr[c][:70]}") + best_r, best = scored[0] + shutil.copy(best, os.path.join(outdir, f"{i:02d}.wav")) + data["segments"][i].update(tts=text, sub=segs[i][1], + dur=round(dur(best), 3), score=round(best_r, 3)) + print(f" -> {i:02d} elegido r={best_r:.2f}\n") + + data["total_audio"] = round(sum(s["dur"] for s in data["segments"]), 2) + json.dump(data, open(os.path.join(outdir, "segments.json"), "w", encoding="utf-8"), + ensure_ascii=False, indent=2) + print(f"[{name}] actualizado, audio={data['total_audio']}s") + + +if __name__ == "__main__": + main(sys.argv[1], [int(x) for x in sys.argv[2:]]) diff --git a/scripts/repick.py b/scripts/repick.py new file mode 100644 index 0000000..5f75bcf --- /dev/null +++ b/scripts/repick.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +"""Vuelve a elegir el mejor candidato ya sintetizado, comparando numeros en palabras.""" +import json, os, shutil, sys, wave +from difflib import SequenceMatcher + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "scripts")) +from narration import SCRIPTS +from verify import norm + + +def dur(p): + with wave.open(p) as w: + return w.getnframes() / w.getframerate() + + +def main(name, idxs): + work = os.path.join(ROOT, "tmp", name + "_rg") + outdir = os.path.join(ROOT, "audio", name) + data = json.load(open(os.path.join(outdir, "segments.json"), encoding="utf-8")) + segs = SCRIPTS[name]["segments"] + for i in idxs: + cands = [] + for k in range(10): + w = os.path.join(work, f"{i:02d}_{k}.wav") + t = os.path.join(work, f"{i:02d}_{k}.txt") + if os.path.exists(w) and os.path.exists(t): + got = open(t, encoding="utf-8").read().strip() + r = SequenceMatcher(None, norm(segs[i][0]), norm(got)).ratio() + cands.append((r, k, w, got)) + if not cands: + print(f" {i:02d} sin candidatos"); continue + cands.sort(reverse=True) + for r, k, w, got in cands: + print(f" {i:02d} seed{k} r={r:.2f} {dur(w):.2f}s | {got[:72]}") + r, k, w, got = cands[0] + shutil.copy(w, os.path.join(outdir, f"{i:02d}.wav")) + data["segments"][i].update(tts=segs[i][0], sub=segs[i][1], + dur=round(dur(w), 3), score=round(r, 3)) + print(f" -> {i:02d} elegido seed{k} r={r:.2f}\n") + data["total_audio"] = round(sum(s["dur"] for s in data["segments"]), 2) + json.dump(data, open(os.path.join(outdir, "segments.json"), "w", encoding="utf-8"), + ensure_ascii=False, indent=2) + print(f"[{name}] audio={data['total_audio']}s") + + +if __name__ == "__main__": + main(sys.argv[1], [int(x) for x in sys.argv[2:]]) diff --git a/scripts/verify.py b/scripts/verify.py new file mode 100644 index 0000000..b35eb44 --- /dev/null +++ b/scripts/verify.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +"""Transcribe los WAV finales y compara ignorando la forma de escribir numeros.""" +import json, os, re, subprocess, sys, unicodedata +from difflib import SequenceMatcher + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "scripts")) +from narration import SCRIPTS +from numspell import expand + +NUM = set("""cero uno una dos tres cuatro cinco seis siete ocho nueve diez once doce trece +catorce quince dieciseis diecisiete dieciocho diecinueve veinte veintiuno veintidos veintitres +treinta cuarenta cincuenta sesenta setenta ochenta noventa cien ciento doscientos trescientos +cuatrocientos quinientos mil millon millones coma periodico por ciento y tercio tercios +primero segundo""".split()) + + +def norm(s, drop_numbers=False): + s = expand(s) + s = unicodedata.normalize("NFD", s.lower()) + s = "".join(c for c in s if unicodedata.category(c) != "Mn") + s = re.sub(r"[^a-z0-9ñ ]+", " ", s) + toks = s.split() + if drop_numbers: + toks = [t for t in toks if not t.isdigit() and t not in NUM] + return " ".join(toks) + + +def main(names): + for name in names: + d = json.load(open(os.path.join(ROOT, "audio", name, "segments.json"))) + wavs = [s["wav"] for s in d["segments"]] + work = os.path.join(ROOT, "tmp", name + "_v") + os.makedirs(work, exist_ok=True) + subprocess.run(["conda", "run", "-n", "stt", "--no-capture-output", + "whisper-ctranslate2", "--language", "es", "--model", "small", + "--output_dir", work, "--output_format", "txt", *wavs], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True) + print(f"\n=== {name} ===") + bad = [] + for s in d["segments"]: + t = os.path.join(work, os.path.splitext(os.path.basename(s["wav"]))[0] + ".txt") + got = open(t, encoding="utf-8").read().strip() if os.path.exists(t) else "" + r = SequenceMatcher(None, norm(s["tts"]), norm(got)).ratio() + flag = "OK " if r >= 0.88 else "REV" + if r < 0.88: + bad.append(s["i"]) + print(f" {s['i']:02d} {flag} {r:.2f} | {got}") + print(f" -> revisar: {bad}") + + +if __name__ == "__main__": + main(sys.argv[1:] or list(SCRIPTS)) diff --git a/scripts/verify_final.py b/scripts/verify_final.py new file mode 100644 index 0000000..7be410b --- /dev/null +++ b/scripts/verify_final.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +"""QA sobre el MP4 terminado: extrae el audio ya mezclado con la musica, +lo corta segun el timeline y lo transcribe. Prueba que se entiende la voz +por encima de la cama, no solo que el WAV suelto estaba bien.""" +import json, os, subprocess, sys +from difflib import SequenceMatcher + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "scripts")) +from narration import SCRIPTS +from verify import norm +from gen_audio import transcribe + +LIMITE = 0.88 + + +def main(names): + peor = [] + for name in names: + mp4 = os.path.join(ROOT, "out", f"{name}.mp4") + tl = json.load(open(os.path.join(ROOT, "out", f"{name}_timeline.json"))) + segs = json.load(open(os.path.join(ROOT, "audio", name, "segments.json")))["segments"] + work = os.path.join(ROOT, "tmp", name + "_fin") + os.makedirs(work, exist_ok=True) + entero = os.path.join(work, "todo.wav") + subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", mp4, "-vn", + "-ac", "1", "-ar", "16000", entero], check=True) + + trozos = [] + for bt in tl["beats"]: + p = os.path.join(work, f"{bt['i']:02d}.wav") + subprocess.run(["ffmpeg", "-v", "error", "-y", "-ss", f"{bt['start']:.3f}", + "-t", f"{segs[bt['i']]['dur'] + 0.25:.3f}", "-i", entero, + "-c", "copy", p], check=True) + trozos.append(p) + tr = transcribe(trozos, work) + + print(f"\n=== {name} (mezcla final) ===") + for bt, p in zip(tl["beats"], trozos): + i = bt["i"] + got = tr[p] + r = SequenceMatcher(None, norm(segs[i]["tts"]), norm(got)).ratio() + if r < LIMITE: + peor.append((name, i, r)) + print(f" {i:02d} {'OK ' if r >= LIMITE else 'REV'} {r:.2f} | {got}") + print("\n>> a revisar:", peor if peor else "nada") + + +if __name__ == "__main__": + main(sys.argv[1:] or list(SCRIPTS)) -- cgit v1.2.3