Pixel-art science cross-section animation
Reference implementations (copy the closest one, then change layers / timeline / text):
| File | What it shows |
|---|---|
pixel_science/bruise_heal.py | skin cross-section, swelling field, macrophages, colour changes over days (EN) |
pixel_science/tooth_decay.py | molar cross-section with roots/gum/bone, sugar -> acid -> cavity -> pulp -> filling, pH HUD (EN) |
pixel_science/tooth_story.py | story wrapper: person with toothache -> zoom into mouth -> dither into cross-section -> VHS rewind -> decay story -> dentist -> happy face + tips (TH). Imports tooth_decay and reuses render_world |
pixel_science/tooth_story_narrated.py | narrated version (~2 min, TH): one SCRIPT table drives scenes, white subtitles, on-tooth labels, a pH (Stephan curve) chart, the .srt and the voice-over files; synced to tooth_story_narrated_voice.wav and muxed into the mp4. Start here for any "story + explanation + subtitles + voice-over" request |
pixel_science/align_voice.py | finds each cue's start/end in a generated voice WAV -> prints VOICE_CUES to paste into the script |
Run any of them with python3 X.py out.mp4, or --preview DIR to dump stills first.
tooth_story_narrated.py also takes --script DIR (writes .srt, _vo.txt, _vo.md).
Core recipe
- Tiny canvas, big pixels. Paint each frame at 180x320 with numpy, upscale 6x
with
Image.NEAREST-> 1080x1920. Never antialias. - Layers as functions of x. Each tissue is a band between boundary curves.
Complex silhouettes (a molar with two roots) = static boolean masks built once
from ellipses / half-width profiles
hw(y)(seeTOOTH,ENAMEL,PULPin tooth_decay.py). Keep a label map per pixel. - Deformation / growth fields.
h(x,t)lifts or dents layers (bruise); growing ellipses define lesions and cavities (tooth). Sample textures in undeformed coordinates so they move with the tissue. - Procedural textures (precompute): Voronoi for fat cells / dermis network, jittered dot grids for blood cells, bone marrow and plaque, stripes for muscle and enamel prisms, dashed lines for dentin tubules, wavy bands for vessels/nerves.
- Ink outline wherever the label map changes (near-black, e.g. (26,10,20)).
- Limited palette, 3 tones per material, light from top-left. Time-based
colour change = palette keys + smoothstep (
lerp_keys). - Actors: wobbly blobs (macrophages), 2px rods (bacteria), particles (acid, leaking blood), falling crystals (sugar), big sphere (impact).
- Camera: crop a slightly wider world and pan; shake + white/red flash for impact or pain throbs.
- Encode: pipe raw RGB to
ffmpeg -f rawvideo ... -c:v libx264 -pix_fmt yuv420p -crf 18. ~1 s of render per second of video.
Story layer (tooth_story.py)
- Character scene drawn analytically: every shape is an ellipse / segment
test on face-space coords
u = (px - W/2)/z + cu. Because it is re-rasterised each frame, zooming from z=1 to z=30 stays crisp pixel art (no blurry scaling). Zoom toward a target withw = (1 - 1/z)/(1 - 1/zmax), centre = target * w. - Pixel dissolve transition: tile a 4x4 Bayer matrix and show scene B where
bayer < k. Use it face -> cross-section and back. - VHS rewind: run story time backwards fast, roll rows by random offsets, add a bright moving band and darken every other row, show ◀◀.
- Story beats: symptom (caption box) -> zoom to the culprit -> "today" view of the damage -> rewind "ย้อนกลับไป 2 ปีก่อน" -> mechanism beats with stamps -> treatment -> happy character + prevention tips box. ~40-45 s total.
- Map global time -> (story time, mode) in one function (
story_time) so the cross-section renderer stays reusable.
Narrated workflow (tooth_story_narrated.py)
Typical request: "make it a story with a scientific explanation, white Thai subtitles, and write a voice-over script for TTS". Then the user generates the voice elsewhere and sends the WAV back for syncing.
- Write the script first, as data.
SCRIPT= list of scenes (kindface / zoom / now / rewind / story / happy,title,direction, story-time rangest, optionalchart), each with cuescue(sub, vo, labels=[(lines, hud_xy, world_target)], chart=n, tips=n).sub= subtitle text (" | "marks a preferred line break; join words that must not split with\u00a0, e.g.วันละ\u00a02\u00a0ครั้ง).vo= what the narrator says: spell out numbers and symbols for TTS ("pH" -> "พีเอช", "5.5" -> "ห้าจุดห้", "30-60" -> "สามสิบถึงหกสิบ").- One cue = one subtitle = one spoken sentence (about 3–6 s).
- Estimated timing (before a voice exists): cue length = Thai base
characters (skip combining marks,
unicodedatacategory M) /CHARS_PER_SEC(12.5) +GAP(0.4 s). Scenes take the length of their cues; story time is interpolated across the scene, so the cross-section animation stretches to fit the narration. - Export with
--script DIR:.srt;_vo.txtin thetools/tts_omnivoice.pyplain-text format (blank line = paragraph,---= scene break);_vo.mdwith scene directions, tone, and per-line times. - Sync to the real voice once the user sends the WAV: copy it next to the
script as
<stem>_voice.wavand runpython3 align_voice.py <module> <wav> [--check]. Paste the printedVOICE_CUES/VOICE_LENinto the script (VOICEset -> measured timing;None-> estimated timing). Scene starts snap to their first cue, dithers sit in the pause before "now"/"happy", subtitles stay up until the next cue starts, and the encoder muxes the WAV (-map 0:v -map 1:a -c:a aac). Real TTS ran ~30% longer than the estimate (126 s vs 98 s), so always re-sync.--checktranscribes each cue with faster-whisper (small,language="th") so you can compare it with the script. Whisper's Thai is rough (กรด -> โกรธ is usually an ASR error, not TTS), so match by meaning; on a hallucinated stretch, re-transcribe that slice alone, padded with 0.5 s of silence. Pass a float32 16 kHz numpy array decoded by ffmpeg, not a path (the installed PyAV rejectsmetadata_errors).
- Science beats that worked (tooth decay): layers -> plaque = biofilm of bacteria -> S. mutans ferments sugar to lactic acid -> Stephan curve (pH < 5.5 within minutes, saliva recovers in 30–60 min, snacking keeps it low) -> Ca/PO4 lost = white spot (reversible with fluoride) -> cavitation (irreversible) -> faster in softer dentin + sensitivity -> pulpitis (throbbing) -> drill + fill, root canal if the pulp is infected -> prevention tips. Keep claims hedged where the visuals simplify (e.g. "เกือบถึงโพรงประสาท").
Thai text
- The bitmap default font has no Thai. Use
ImageFont.truetype( "/usr/share/fonts/opentype/tlwg/Loma-Bold.otf", 14)(20 for headlines) and setImageDraw.fontmode = "1"so it stays aliased/pixelated. Raqm is available, so vowel/tone marks position correctly. - Draw the HUD on a 1.5x layer (270x480), upscale 4x. ~17 px line height.
Clamp label x so
x + text_width <= 264; keep labels to 2 short lines. - Captions: dark box with a 1px white border, centred near the bottom; labels: black 8-direction outline, typewriter reveal, white leader line + square marker.
- White subtitles (narrated version): white text + black 8-direction outline
on a soft band
(0,0,0,120)across the bottom, line height 20, up to 3 lines. Use a balanced wrap at spaces: the fewest lines that fitHW-16, then the most even split (greedy wrap leaves orphans like a lone "มิวแทนส์"). A Thai phrase with no spaces can't be wrapped, so check every line's width with a quick loop overSCRIPTbefore rendering, and add spaces or" | "where needed. - Gold
(255,232,150)for on-tooth labels so they read differently from the white subtitles.
Gotchas found the hard way
mask & some_intgives an int array; indexingimg[int_array]silently does row fancy-indexing (whole body vanished). Keep masks boolean (bool(flag)).- Slicing with a negative start (
img[y-1:y+s]when y < 0) selects a whole column -> long white streaks. Skip sprites that are off-canvas. - Plaque/particle fields defined over all x will float outside a silhouette; multiply by the silhouette's x-range.
--previewwhile a background render rewrites the same contact-sheet file -> you look at a stale sheet. Use a new filename for each check.- Always check
--previewstills as a contact sheet (ffmpeg -pattern_type glob -i 'dir/*.png' -vf "scale=240:-1,tile=7x2") before the full render.