Gendle commited on
Commit
74b0422
·
verified ·
1 Parent(s): e9ff83a

Hermes Agent backup - 2026-11-06 05:00:48

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. logs/agent.log +3 -0
  3. logs/curator/20261106-045959/REPORT.md +28 -0
  4. logs/curator/20261106-045959/run.json +41 -0
  5. logs/gateway.log +2 -0
  6. metadata.json +1 -1
  7. skills/.archive/airtable/SKILL.md +229 -0
  8. skills/.archive/apple-notes/SKILL.md +90 -0
  9. skills/.archive/apple-reminders/SKILL.md +130 -0
  10. skills/.archive/architecture-diagram/SKILL.md +148 -0
  11. skills/.archive/architecture-diagram/templates/template.html +319 -0
  12. skills/.archive/arxiv/SKILL.md +282 -0
  13. skills/.archive/arxiv/scripts/__pycache__/search_arxiv.cpython-311.pyc +0 -0
  14. skills/.archive/arxiv/scripts/search_arxiv.py +114 -0
  15. skills/.archive/ascii-art/SKILL.md +322 -0
  16. skills/.archive/ascii-video/README.md +290 -0
  17. skills/.archive/ascii-video/SKILL.md +241 -0
  18. skills/.archive/ascii-video/references/architecture.md +802 -0
  19. skills/.archive/ascii-video/references/composition.md +892 -0
  20. skills/.archive/ascii-video/references/effects.md +1865 -0
  21. skills/.archive/ascii-video/references/inputs.md +685 -0
  22. skills/.archive/ascii-video/references/optimization.md +688 -0
  23. skills/.archive/ascii-video/references/scenes.md +1011 -0
  24. skills/.archive/ascii-video/references/shaders.md +1385 -0
  25. skills/.archive/ascii-video/references/troubleshooting.md +367 -0
  26. skills/.archive/audiocraft/SKILL.md +568 -0
  27. skills/.archive/audiocraft/references/advanced-usage.md +666 -0
  28. skills/.archive/audiocraft/references/troubleshooting.md +504 -0
  29. skills/.archive/baoyu-article-illustrator/PORT_NOTES.md +48 -0
  30. skills/.archive/baoyu-article-illustrator/SKILL.md +207 -0
  31. skills/.archive/baoyu-article-illustrator/prompts/system.md +32 -0
  32. skills/.archive/baoyu-article-illustrator/references/palettes/macaron.md +33 -0
  33. skills/.archive/baoyu-article-illustrator/references/palettes/mono-ink.md +42 -0
  34. skills/.archive/baoyu-article-illustrator/references/palettes/neon.md +33 -0
  35. skills/.archive/baoyu-article-illustrator/references/palettes/warm.md +32 -0
  36. skills/.archive/baoyu-article-illustrator/references/prompt-construction.md +426 -0
  37. skills/.archive/baoyu-article-illustrator/references/style-presets.md +80 -0
  38. skills/.archive/baoyu-article-illustrator/references/styles.md +224 -0
  39. skills/.archive/baoyu-article-illustrator/references/styles/blueprint.md +57 -0
  40. skills/.archive/baoyu-article-illustrator/references/styles/chalkboard.md +62 -0
  41. skills/.archive/baoyu-article-illustrator/references/styles/editorial.md +59 -0
  42. skills/.archive/baoyu-article-illustrator/references/styles/elegant.md +56 -0
  43. skills/.archive/baoyu-article-illustrator/references/styles/fantasy-animation.md +58 -0
  44. skills/.archive/baoyu-article-illustrator/references/styles/flat-doodle.md +61 -0
  45. skills/.archive/baoyu-article-illustrator/references/styles/flat.md +59 -0
  46. skills/.archive/baoyu-article-illustrator/references/styles/ink-notes.md +90 -0
  47. skills/.archive/baoyu-article-illustrator/references/styles/intuition-machine.md +57 -0
  48. skills/.archive/baoyu-article-illustrator/references/styles/minimal.md +58 -0
  49. skills/.archive/baoyu-article-illustrator/references/styles/nature.md +58 -0
  50. skills/.archive/baoyu-article-illustrator/references/styles/notion.md +58 -0
.gitattributes CHANGED
@@ -62,3 +62,6 @@ skills/research/research-paper-writing/templates/colm2025/colm2025_conference.pd
62
  skills/research/research-paper-writing/templates/iclr2026/iclr2026_conference.pdf filter=lfs diff=lfs merge=lfs -text
63
  skills/research/research-paper-writing/templates/icml2026/example_paper.pdf filter=lfs diff=lfs merge=lfs -text
64
  state/state.db filter=lfs diff=lfs merge=lfs -text
 
 
 
 
62
  skills/research/research-paper-writing/templates/iclr2026/iclr2026_conference.pdf filter=lfs diff=lfs merge=lfs -text
63
  skills/research/research-paper-writing/templates/icml2026/example_paper.pdf filter=lfs diff=lfs merge=lfs -text
64
  state/state.db filter=lfs diff=lfs merge=lfs -text
65
+ skills/.archive/research-paper-writing/templates/colm2025/colm2025_conference.pdf filter=lfs diff=lfs merge=lfs -text
66
+ skills/.archive/research-paper-writing/templates/iclr2026/iclr2026_conference.pdf filter=lfs diff=lfs merge=lfs -text
67
+ skills/.archive/research-paper-writing/templates/icml2026/example_paper.pdf filter=lfs diff=lfs merge=lfs -text
logs/agent.log CHANGED
@@ -2331,3 +2331,6 @@
2331
  2026-11-06 04:00:58,756 INFO gateway.run: Press Ctrl+C to stop
2332
  2026-11-06 04:00:58,761 INFO gateway.run: Cron ticker started (interval=60s)
2333
  2026-11-06 04:01:03,773 INFO gateway.run: kanban dispatcher: embedded in gateway (interval=60.0s)
 
 
 
 
2331
  2026-11-06 04:00:58,756 INFO gateway.run: Press Ctrl+C to stop
2332
  2026-11-06 04:00:58,761 INFO gateway.run: Cron ticker started (interval=60s)
2333
  2026-11-06 04:01:03,773 INFO gateway.run: kanban dispatcher: embedded in gateway (interval=60.0s)
2334
+ 2026-11-06 04:59:59,372 INFO agent.curator_backup: Curator snapshot created: 2026-11-06T04-59-59Z (pre-curator-run)
2335
+ 2026-11-06 04:59:59,373 INFO gateway.run: curator: curator: snapshot created (2026-11-06T04-59-59Z)
2336
+ 2026-11-06 05:00:00,535 INFO gateway.run: curator: curator: auto: 90 archived; llm: skipped (no candidates)
logs/curator/20261106-045959/REPORT.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Curator run — 2026-11-06T04:59:59.003704+00:00
2
+
3
+ Model: `(not resolved)` via `(not resolved)` · Duration: 1s · Agent-created skills: 0 → 0 (+0)
4
+
5
+ ## Auto-transitions (pure, no LLM)
6
+
7
+ - checked: 90
8
+ - marked stale: 0
9
+ - archived (no LLM, pure time-based staleness): 90
10
+ - reactivated: 0
11
+
12
+ ## LLM consolidation pass
13
+
14
+ - tool calls: **0** (by name: none)
15
+ - consolidated into umbrellas: **0**
16
+ - pruned (archived for staleness): **0**
17
+ - new skills this run: **0**
18
+ - state transitions (active ↔ stale ↔ archived): **0**
19
+
20
+ ## LLM summary
21
+
22
+ skipped (no candidates)
23
+
24
+ ## Recovery
25
+
26
+ - Restore an archived skill: `hermes curator restore <name>`
27
+ - All archives live under `~/.hermes/skills/.archive/` and are recoverable by `mv`
28
+ - See `run.json` in this directory for the full machine-readable record.
logs/curator/20261106-045959/run.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "started_at": "2026-11-06T04:59:59.003704+00:00",
3
+ "duration_seconds": 1.52,
4
+ "model": "",
5
+ "provider": "",
6
+ "auto_transitions": {
7
+ "marked_stale": 0,
8
+ "archived": 90,
9
+ "reactivated": 0,
10
+ "checked": 90,
11
+ "seeded": 0
12
+ },
13
+ "counts": {
14
+ "before": 0,
15
+ "after": 0,
16
+ "delta": 0,
17
+ "archived_this_run": 0,
18
+ "added_this_run": 0,
19
+ "consolidated_this_run": 0,
20
+ "pruned_this_run": 0,
21
+ "state_transitions": 0,
22
+ "cron_jobs_rewritten": 0,
23
+ "tool_calls_total": 0
24
+ },
25
+ "tool_call_counts": {},
26
+ "archived": [],
27
+ "consolidated": [],
28
+ "pruned": [],
29
+ "pruned_names": [],
30
+ "added": [],
31
+ "state_transitions": [],
32
+ "cron_rewrites": {
33
+ "rewrites": [],
34
+ "jobs_updated": 0,
35
+ "jobs_scanned": 0
36
+ },
37
+ "llm_final": "",
38
+ "llm_summary": "skipped (no candidates)",
39
+ "llm_error": null,
40
+ "tool_calls": []
41
+ }
logs/gateway.log CHANGED
@@ -724,3 +724,5 @@
724
  2026-11-06 04:00:58,756 INFO gateway.run: Press Ctrl+C to stop
725
  2026-11-06 04:00:58,761 INFO gateway.run: Cron ticker started (interval=60s)
726
  2026-11-06 04:01:03,773 INFO gateway.run: kanban dispatcher: embedded in gateway (interval=60.0s)
 
 
 
724
  2026-11-06 04:00:58,756 INFO gateway.run: Press Ctrl+C to stop
725
  2026-11-06 04:00:58,761 INFO gateway.run: Cron ticker started (interval=60s)
726
  2026-11-06 04:01:03,773 INFO gateway.run: kanban dispatcher: embedded in gateway (interval=60.0s)
727
+ 2026-11-06 04:59:59,373 INFO gateway.run: curator: curator: snapshot created (2026-11-06T04-59-59Z)
728
+ 2026-11-06 05:00:00,535 INFO gateway.run: curator: curator: auto: 90 archived; llm: skipped (no candidates)
metadata.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "timestamp": "2026-11-06T04:59:47.545620",
3
  "version": "0.10.0",
4
  "hermes_home": "/data/.hermes"
5
  }
 
1
  {
2
+ "timestamp": "2026-11-06T05:00:48.632211",
3
  "version": "0.10.0",
4
  "hermes_home": "/data/.hermes"
5
  }
skills/.archive/airtable/SKILL.md ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: airtable
3
+ description: Airtable REST API via curl. Records CRUD, filters, upserts.
4
+ version: 1.1.0
5
+ author: community
6
+ license: MIT
7
+ platforms: [linux, macos, windows]
8
+ prerequisites:
9
+ env_vars: [AIRTABLE_API_KEY]
10
+ commands: [curl]
11
+ metadata:
12
+ hermes:
13
+ tags: [Airtable, Productivity, Database, API]
14
+ homepage: https://airtable.com/developers/web/api/introduction
15
+ ---
16
+
17
+ # Airtable — Bases, Tables & Records
18
+
19
+ Work with Airtable's REST API directly via `curl` using the `terminal` tool. No MCP server, no OAuth flow, no Python SDK — just `curl` and a personal access token.
20
+
21
+ ## Prerequisites
22
+
23
+ 1. Create a **Personal Access Token (PAT)** at https://airtable.com/create/tokens (tokens start with `pat...`).
24
+ 2. Grant these scopes (minimum):
25
+ - `data.records:read` — read rows
26
+ - `data.records:write` — create / update / delete rows
27
+ - `schema.bases:read` — list bases and tables
28
+ 3. **Important:** in the same token UI, add each base you want to access to the token's **Access** list. PATs are scoped per-base — a valid token on the wrong base returns `403`.
29
+ 4. Store the token in `~/.hermes/.env` (or via `hermes setup`):
30
+ ```
31
+ AIRTABLE_API_KEY=pat_your_token_here
32
+ ```
33
+
34
+ > Note: legacy `key...` API keys were deprecated Feb 2024. Only PATs and OAuth tokens work now.
35
+
36
+ ## API Basics
37
+
38
+ - **Endpoint:** `https://api.airtable.com/v0`
39
+ - **Auth header:** `Authorization: Bearer $AIRTABLE_API_KEY`
40
+ - **All requests** use JSON (`Content-Type: application/json` for any POST/PATCH/PUT body).
41
+ - **Object IDs:** bases `app...`, tables `tbl...`, records `rec...`, fields `fld...`. IDs never change; names can. Prefer IDs in automations.
42
+ - **Rate limit:** 5 requests/sec/base. `429` → back off. Burst on a single base will be throttled.
43
+
44
+ Base curl pattern:
45
+ ```bash
46
+ curl -s "https://api.airtable.com/v0/$BASE_ID/$TABLE?maxRecords=5" \
47
+ -H "Authorization: Bearer $AIRTABLE_API_KEY" | python3 -m json.tool
48
+ ```
49
+
50
+ `-s` suppresses curl's progress bar — keep it set for every call so the tool output stays clean for Hermes. Pipe through `python3 -m json.tool` (always present) or `jq` (if installed) for readable JSON.
51
+
52
+ ## Field Types (request body shapes)
53
+
54
+ | Field type | Write shape |
55
+ |---|---|
56
+ | Single line text | `"Name": "hello"` |
57
+ | Long text | `"Notes": "multi\nline"` |
58
+ | Number | `"Score": 42` |
59
+ | Checkbox | `"Done": true` |
60
+ | Single select | `"Status": "Todo"` (name must already exist unless `typecast: true`) |
61
+ | Multi-select | `"Tags": ["urgent", "bug"]` |
62
+ | Date | `"Due": "2026-04-01"` |
63
+ | DateTime (UTC) | `"At": "2026-04-01T14:30:00.000Z"` |
64
+ | URL / Email / Phone | `"Link": "https://…"` |
65
+ | Attachment | `"Files": [{"url": "https://…"}]` (Airtable fetches + rehosts) |
66
+ | Linked record | `"Owner": ["recXXXXXXXXXXXXXX"]` (array of record IDs) |
67
+ | User | `"AssignedTo": {"id": "usrXXXXXXXXXXXXXX"}` |
68
+
69
+ Pass `"typecast": true` at the top level of a create/update body to let Airtable auto-coerce values (e.g. create a new select option on the fly, convert `"42"` → `42`).
70
+
71
+ ## Common Queries
72
+
73
+ ### List bases the token can see
74
+ ```bash
75
+ curl -s "https://api.airtable.com/v0/meta/bases" \
76
+ -H "Authorization: Bearer $AIRTABLE_API_KEY" | python3 -m json.tool
77
+ ```
78
+
79
+ ### List tables + schema for a base
80
+ ```bash
81
+ curl -s "https://api.airtable.com/v0/meta/bases/$BASE_ID/tables" \
82
+ -H "Authorization: Bearer $AIRTABLE_API_KEY" | python3 -m json.tool
83
+ ```
84
+ Use this BEFORE mutating — confirms exact field names and IDs, surfaces `options.choices` for select fields, and shows primary-field names.
85
+
86
+ ### List records (first 10)
87
+ ```bash
88
+ curl -s "https://api.airtable.com/v0/$BASE_ID/$TABLE?maxRecords=10" \
89
+ -H "Authorization: Bearer $AIRTABLE_API_KEY" | python3 -m json.tool
90
+ ```
91
+
92
+ ### Get a single record
93
+ ```bash
94
+ curl -s "https://api.airtable.com/v0/$BASE_ID/$TABLE/$RECORD_ID" \
95
+ -H "Authorization: Bearer $AIRTABLE_API_KEY" | python3 -m json.tool
96
+ ```
97
+
98
+ ### Filter records (filterByFormula)
99
+ Airtable formulas must be URL-encoded. Let Python stdlib do it — never hand-encode:
100
+ ```bash
101
+ FORMULA="{Status}='Todo'"
102
+ ENC=$(python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1], safe=""))' "$FORMULA")
103
+ curl -s "https://api.airtable.com/v0/$BASE_ID/$TABLE?filterByFormula=$ENC&maxRecords=20" \
104
+ -H "Authorization: Bearer $AIRTABLE_API_KEY" | python3 -m json.tool
105
+ ```
106
+
107
+ Useful formula patterns:
108
+ - Exact match: `{Email}='user@example.com'`
109
+ - Contains: `FIND('bug', LOWER({Title}))`
110
+ - Multiple conditions: `AND({Status}='Todo', {Priority}='High')`
111
+ - Or: `OR({Owner}='alice', {Owner}='bob')`
112
+ - Not empty: `NOT({Assignee}='')`
113
+ - Date comparison: `IS_AFTER({Due}, TODAY())`
114
+
115
+ ### Sort + select specific fields
116
+ ```bash
117
+ curl -s "https://api.airtable.com/v0/$BASE_ID/$TABLE?sort%5B0%5D%5Bfield%5D=Priority&sort%5B0%5D%5Bdirection%5D=asc&fields%5B%5D=Name&fields%5B%5D=Status" \
118
+ -H "Authorization: Bearer $AIRTABLE_API_KEY" | python3 -m json.tool
119
+ ```
120
+ Square brackets in query params MUST be URL-encoded (`%5B` / `%5D`).
121
+
122
+ ### Use a named view
123
+ ```bash
124
+ curl -s "https://api.airtable.com/v0/$BASE_ID/$TABLE?view=Grid%20view&maxRecords=50" \
125
+ -H "Authorization: Bearer $AIRTABLE_API_KEY" | python3 -m json.tool
126
+ ```
127
+ Views apply their saved filter + sort server-side.
128
+
129
+ ## Common Mutations
130
+
131
+ ### Create a record
132
+ ```bash
133
+ curl -s -X POST "https://api.airtable.com/v0/$BASE_ID/$TABLE" \
134
+ -H "Authorization: Bearer $AIRTABLE_API_KEY" \
135
+ -H "Content-Type: application/json" \
136
+ -d '{"fields":{"Name":"New task","Status":"Todo","Priority":"High"}}' | python3 -m json.tool
137
+ ```
138
+
139
+ ### Create up to 10 records in one call
140
+ ```bash
141
+ curl -s -X POST "https://api.airtable.com/v0/$BASE_ID/$TABLE" \
142
+ -H "Authorization: Bearer $AIRTABLE_API_KEY" \
143
+ -H "Content-Type: application/json" \
144
+ -d '{
145
+ "typecast": true,
146
+ "records": [
147
+ {"fields": {"Name": "Task A", "Status": "Todo"}},
148
+ {"fields": {"Name": "Task B", "Status": "In progress"}}
149
+ ]
150
+ }' | python3 -m json.tool
151
+ ```
152
+ Batch endpoints are capped at **10 records per request**. For larger inserts, loop in batches of 10 with a short sleep to respect 5 req/sec/base.
153
+
154
+ ### Update a record (PATCH — merges, preserves unchanged fields)
155
+ ```bash
156
+ curl -s -X PATCH "https://api.airtable.com/v0/$BASE_ID/$TABLE/$RECORD_ID" \
157
+ -H "Authorization: Bearer $AIRTABLE_API_KEY" \
158
+ -H "Content-Type: application/json" \
159
+ -d '{"fields":{"Status":"Done"}}' | python3 -m json.tool
160
+ ```
161
+
162
+ ### Upsert by a merge field (no ID needed)
163
+ ```bash
164
+ curl -s -X PATCH "https://api.airtable.com/v0/$BASE_ID/$TABLE" \
165
+ -H "Authorization: Bearer $AIRTABLE_API_KEY" \
166
+ -H "Content-Type: application/json" \
167
+ -d '{
168
+ "performUpsert": {"fieldsToMergeOn": ["Email"]},
169
+ "records": [
170
+ {"fields": {"Email": "user@example.com", "Status": "Active"}}
171
+ ]
172
+ }' | python3 -m json.tool
173
+ ```
174
+ `performUpsert` creates records whose merge-field values are new, patches records whose merge-field values already exist. Great for idempotent syncs.
175
+
176
+ ### Delete a record
177
+ ```bash
178
+ curl -s -X DELETE "https://api.airtable.com/v0/$BASE_ID/$TABLE/$RECORD_ID" \
179
+ -H "Authorization: Bearer $AIRTABLE_API_KEY" | python3 -m json.tool
180
+ ```
181
+
182
+ ### Delete up to 10 records in one call
183
+ ```bash
184
+ curl -s -X DELETE "https://api.airtable.com/v0/$BASE_ID/$TABLE?records%5B%5D=rec1&records%5B%5D=rec2" \
185
+ -H "Authorization: Bearer $AIRTABLE_API_KEY" | python3 -m json.tool
186
+ ```
187
+
188
+ ## Pagination
189
+
190
+ List endpoints return at most **100 records per page**. If the response includes `"offset": "..."`, pass it back on the next call. Loop until the field is absent:
191
+
192
+ ```bash
193
+ OFFSET=""
194
+ while :; do
195
+ URL="https://api.airtable.com/v0/$BASE_ID/$TABLE?pageSize=100"
196
+ [ -n "$OFFSET" ] && URL="$URL&offset=$OFFSET"
197
+ RESP=$(curl -s "$URL" -H "Authorization: Bearer $AIRTABLE_API_KEY")
198
+ echo "$RESP" | python3 -c 'import json,sys; d=json.load(sys.stdin); [print(r["id"], r["fields"].get("Name","")) for r in d["records"]]'
199
+ OFFSET=$(echo "$RESP" | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("offset",""))')
200
+ [ -z "$OFFSET" ] && break
201
+ done
202
+ ```
203
+
204
+ ## Typical Hermes Workflow
205
+
206
+ 1. **Confirm auth.** `curl -s -o /dev/null -w "%{http_code}\n" https://api.airtable.com/v0/meta/bases -H "Authorization: Bearer $AIRTABLE_API_KEY"` — expect `200`.
207
+ 2. **Find the base.** List bases (step above) OR ask the user for the `app...` ID directly if the token lacks `schema.bases:read`.
208
+ 3. **Inspect the schema.** `GET /v0/meta/bases/$BASE_ID/tables` — cache the exact field names and primary-field name locally in the session before mutating anything.
209
+ 4. **Read before you write.** For "update X where Y", `filterByFormula` first to resolve the `rec...` ID, then `PATCH /v0/$BASE_ID/$TABLE/$RECORD_ID`. Never guess record IDs.
210
+ 5. **Batch writes.** Combine related creates into one 10-record POST to stay under the 5 req/sec budget.
211
+ 6. **Destructive ops.** Deletions can't be undone via API. If the user says "delete all Xs", echo back the filter + record count and confirm before firing.
212
+
213
+ ## Pitfalls
214
+
215
+ - **`filterByFormula` MUST be URL-encoded.** Field names with spaces or non-ASCII also need encoding (`{My Field}` → `%7BMy%20Field%7D`). Use Python stdlib (pattern above) — never hand-escape.
216
+ - **Empty fields are omitted from responses.** A missing `"Assignee"` key doesn't mean the field doesn't exist — it means this record's value is empty. Check the schema (step 3) before concluding a field is missing.
217
+ - **PATCH vs PUT.** `PATCH` merges supplied fields into the record. `PUT` replaces the record entirely and clears any field you didn't include. Default to `PATCH`.
218
+ - **Single-select options must exist.** Writing `"Status": "Shipping"` when `Shipping` isn't in the field's option list errors with `INVALID_MULTIPLE_CHOICE_OPTIONS` unless you pass `"typecast": true` (which auto-creates the option).
219
+ - **Per-base token scoping.** A `403` on one base while another works means the token's Access list doesn't include that base — not a scope or auth issue. Send the user to https://airtable.com/create/tokens to grant it.
220
+ - **Rate limits are per base, not per token.** 5 req/sec on `baseA` and 5 req/sec on `baseB` is fine; 6 req/sec on `baseA` alone will throttle. Monitor the `Retry-After` header on `429`.
221
+
222
+ ## Important Notes for Hermes
223
+
224
+ - **Always use the `terminal` tool with `curl`.** Do NOT use `web_extract` (it can't send auth headers) or `browser_navigate` (needs UI auth and is slow).
225
+ - **`AIRTABLE_API_KEY` flows from `~/.hermes/.env` into the subprocess automatically** when this skill is loaded — no need to re-export it before each `curl` call.
226
+ - **Escape curly braces in formulas carefully.** In a heredoc body, `{Status}` is literal. In a shell argument, `{Status}` is safe outside `{...}` brace-expansion context — but pass dynamic strings through `python3 urllib.parse.quote` before splicing into a URL.
227
+ - **Pretty-print with `python3 -m json.tool`** (always present) rather than `jq` (optional). Only reach for `jq` when you need filtering/projection.
228
+ - **Pagination is per-page, not global.** Airtable's 100-record cap is a hard limit; there is no way to bump it. Loop with `offset` until the field is absent.
229
+ - **Read the `errors` array** on non-2xx responses — Airtable returns structured error codes like `AUTHENTICATION_REQUIRED`, `INVALID_PERMISSIONS`, `MODEL_ID_NOT_FOUND`, `INVALID_MULTIPLE_CHOICE_OPTIONS` that tell you exactly what's wrong.
skills/.archive/apple-notes/SKILL.md ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: apple-notes
3
+ description: "Manage Apple Notes via memo CLI: create, search, edit."
4
+ version: 1.0.0
5
+ author: Hermes Agent
6
+ license: MIT
7
+ platforms: [macos]
8
+ metadata:
9
+ hermes:
10
+ tags: [Notes, Apple, macOS, note-taking]
11
+ related_skills: [obsidian]
12
+ prerequisites:
13
+ commands: [memo]
14
+ ---
15
+
16
+ # Apple Notes
17
+
18
+ Use `memo` to manage Apple Notes directly from the terminal. Notes sync across all Apple devices via iCloud.
19
+
20
+ ## Prerequisites
21
+
22
+ - **macOS** with Notes.app
23
+ - Install: `brew tap antoniorodr/memo && brew install antoniorodr/memo/memo`
24
+ - Grant Automation access to Notes.app when prompted (System Settings → Privacy → Automation)
25
+
26
+ ## When to Use
27
+
28
+ - User asks to create, view, or search Apple Notes
29
+ - Saving information to Notes.app for cross-device access
30
+ - Organizing notes into folders
31
+ - Exporting notes to Markdown/HTML
32
+
33
+ ## When NOT to Use
34
+
35
+ - Obsidian vault management → use the `obsidian` skill
36
+ - Bear Notes → separate app (not supported here)
37
+ - Quick agent-only notes → use the `memory` tool instead
38
+
39
+ ## Quick Reference
40
+
41
+ ### View Notes
42
+
43
+ ```bash
44
+ memo notes # List all notes
45
+ memo notes -f "Folder Name" # Filter by folder
46
+ memo notes -s "query" # Search notes (fuzzy)
47
+ ```
48
+
49
+ ### Create Notes
50
+
51
+ ```bash
52
+ memo notes -a # Interactive editor
53
+ memo notes -a "Note Title" # Quick add with title
54
+ ```
55
+
56
+ ### Edit Notes
57
+
58
+ ```bash
59
+ memo notes -e # Interactive selection to edit
60
+ ```
61
+
62
+ ### Delete Notes
63
+
64
+ ```bash
65
+ memo notes -d # Interactive selection to delete
66
+ ```
67
+
68
+ ### Move Notes
69
+
70
+ ```bash
71
+ memo notes -m # Move note to folder (interactive)
72
+ ```
73
+
74
+ ### Export Notes
75
+
76
+ ```bash
77
+ memo notes -ex # Export to HTML/Markdown
78
+ ```
79
+
80
+ ## Limitations
81
+
82
+ - Cannot edit notes containing images or attachments
83
+ - Interactive prompts require terminal access (use pty=true if needed)
84
+ - macOS only — requires Apple Notes.app
85
+
86
+ ## Rules
87
+
88
+ 1. Prefer Apple Notes when user wants cross-device sync (iPhone/iPad/Mac)
89
+ 2. Use the `memory` tool for agent-internal notes that don't need to sync
90
+ 3. Use the `obsidian` skill for Markdown-native knowledge management
skills/.archive/apple-reminders/SKILL.md ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: apple-reminders
3
+ description: "Apple Reminders via remindctl: add, list, complete."
4
+ version: 1.0.0
5
+ author: Hermes Agent
6
+ license: MIT
7
+ platforms: [macos]
8
+ metadata:
9
+ hermes:
10
+ tags: [Reminders, tasks, todo, macOS, Apple]
11
+ prerequisites:
12
+ commands: [remindctl]
13
+ ---
14
+
15
+ # Apple Reminders
16
+
17
+ Use `remindctl` to manage Apple Reminders directly from the terminal. Tasks sync across all Apple devices via iCloud.
18
+
19
+ ## Prerequisites
20
+
21
+ - **macOS** with Reminders.app
22
+ - Install: `brew install steipete/tap/remindctl`
23
+ - Grant Reminders permission when prompted
24
+ - Check: `remindctl status` / Request: `remindctl authorize`
25
+
26
+ ## When to Use
27
+
28
+ - User mentions "reminder" or "Reminders app"
29
+ - Creating personal to-dos with due dates that sync to iOS
30
+ - Managing Apple Reminders lists
31
+ - User wants tasks to appear on their iPhone/iPad
32
+
33
+ ## When NOT to Use
34
+
35
+ - Scheduling agent alerts → use the cronjob tool instead
36
+ - Calendar events → use Apple Calendar or Google Calendar
37
+ - Project task management → use GitHub Issues, Notion, etc.
38
+ - If user says "remind me" but means an agent alert → clarify first
39
+
40
+ ## Quick Reference
41
+
42
+ ### View Reminders
43
+
44
+ ```bash
45
+ remindctl # Today's reminders
46
+ remindctl today # Today
47
+ remindctl tomorrow # Tomorrow
48
+ remindctl week # This week
49
+ remindctl overdue # Past due
50
+ remindctl all # Everything
51
+ remindctl 2026-01-04 # Specific date
52
+ ```
53
+
54
+ ### Manage Lists
55
+
56
+ ```bash
57
+ remindctl list # List all lists
58
+ remindctl list Work # Show specific list
59
+ remindctl list Projects --create # Create list
60
+ remindctl list Work --delete # Delete list
61
+ ```
62
+
63
+ ### Create Reminders
64
+
65
+ ```bash
66
+ remindctl add "Buy milk"
67
+ remindctl add --title "Call mom" --list Personal --due tomorrow
68
+ remindctl add --title "Meeting prep" --due "2026-02-15 09:00"
69
+ ```
70
+
71
+ ### Due Time vs Alarm / Early Nudge
72
+
73
+ `--due` and `--alarm` are different fields:
74
+
75
+ - `--due` sets the reminder's due date/time.
76
+ - `--alarm` sets the EventKit alarm/notification trigger. Timed due reminders may default to an alarm at the due time, but pass `--alarm` explicitly when the user asks for an earlier nudge.
77
+
78
+ For a reminder due at 2:00 PM with a notification 30 minutes earlier:
79
+
80
+ ```bash
81
+ remindctl add --title "Hairdresser" --due "2026-05-15 14:00" --alarm "2026-05-15 13:30"
82
+ ```
83
+
84
+ To edit an existing reminder:
85
+
86
+ ```bash
87
+ remindctl edit 87354 --due "2026-05-15 14:00" --alarm "2026-05-15 13:30"
88
+ ```
89
+
90
+ The Reminders UI may show or group the item by the alarm time because that is when the notification fires. Verify with JSON instead of assuming the due time moved:
91
+
92
+ ```bash
93
+ remindctl today --json
94
+ ```
95
+
96
+ Expected shape:
97
+
98
+ - `dueDate`: actual due time
99
+ - `alarmDate`: notification / early nudge time
100
+
101
+ Apple's public `EKReminder` docs list only reminder-specific properties. Alarm support comes from inherited `EKCalendarItem` behavior exposed by remindctl's `--alarm` flag.
102
+
103
+ ### Complete / Delete
104
+
105
+ ```bash
106
+ remindctl complete 1 2 3 # Complete by ID
107
+ remindctl delete 4A83 --force # Delete by ID
108
+ ```
109
+
110
+ ### Output Formats
111
+
112
+ ```bash
113
+ remindctl today --json # JSON for scripting
114
+ remindctl today --plain # TSV format
115
+ remindctl today --quiet # Counts only
116
+ ```
117
+
118
+ ## Date Formats
119
+
120
+ Accepted by `--due` and date filters:
121
+ - `today`, `tomorrow`, `yesterday`
122
+ - `YYYY-MM-DD`
123
+ - `YYYY-MM-DD HH:mm`
124
+ - ISO 8601 (`2026-01-04T12:34:56Z`)
125
+
126
+ ## Rules
127
+
128
+ 1. When user says "remind me", clarify: Apple Reminders (syncs to phone) vs agent cronjob alert
129
+ 2. Always confirm reminder content and due date before creating
130
+ 3. Use `--json` for programmatic parsing
skills/.archive/architecture-diagram/SKILL.md ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: architecture-diagram
3
+ description: "Dark-themed SVG architecture/cloud/infra diagrams as HTML."
4
+ version: 1.0.0
5
+ author: Cocoon AI (hello@cocoon-ai.com), ported by Hermes Agent
6
+ license: MIT
7
+ dependencies: []
8
+ platforms: [linux, macos, windows]
9
+ metadata:
10
+ hermes:
11
+ tags: [architecture, diagrams, SVG, HTML, visualization, infrastructure, cloud]
12
+ related_skills: [concept-diagrams, excalidraw]
13
+ ---
14
+
15
+ # Architecture Diagram Skill
16
+
17
+ Generate professional, dark-themed technical architecture diagrams as standalone HTML files with inline SVG graphics. No external tools, no API keys, no rendering libraries — just write the HTML file and open it in a browser.
18
+
19
+ ## Scope
20
+
21
+ **Best suited for:**
22
+ - Software system architecture (frontend / backend / database layers)
23
+ - Cloud infrastructure (VPC, regions, subnets, managed services)
24
+ - Microservice / service-mesh topology
25
+ - Database + API map, deployment diagrams
26
+ - Anything with a tech-infra subject that fits a dark, grid-backed aesthetic
27
+
28
+ **Look elsewhere first for:**
29
+ - Physics, chemistry, math, biology, or other scientific subjects
30
+ - Physical objects (vehicles, hardware, anatomy, cross-sections)
31
+ - Floor plans, narrative journeys, educational / textbook-style visuals
32
+ - Hand-drawn whiteboard sketches (consider `excalidraw`)
33
+ - Animated explainers (consider an animation skill)
34
+
35
+ If a more specialized skill is available for the subject, prefer that. If none fits, this skill can also serve as a general SVG diagram fallback — the output will just carry the dark tech aesthetic described below.
36
+
37
+ Based on [Cocoon AI's architecture-diagram-generator](https://github.com/Cocoon-AI/architecture-diagram-generator) (MIT).
38
+
39
+ ## Workflow
40
+
41
+ 1. User describes their system architecture (components, connections, technologies)
42
+ 2. Generate the HTML file following the design system below
43
+ 3. Save with `write_file` to a `.html` file (e.g. `~/architecture-diagram.html`)
44
+ 4. User opens in any browser — works offline, no dependencies
45
+
46
+ ### Output Location
47
+
48
+ Save diagrams to a user-specified path, or default to the current working directory:
49
+ ```
50
+ ./[project-name]-architecture.html
51
+ ```
52
+
53
+ ### Preview
54
+
55
+ After saving, suggest the user open it:
56
+ ```bash
57
+ # macOS
58
+ open ./my-architecture.html
59
+ # Linux
60
+ xdg-open ./my-architecture.html
61
+ ```
62
+
63
+ ## Design System & Visual Language
64
+
65
+ ### Color Palette (Semantic Mapping)
66
+
67
+ Use specific `rgba` fills and hex strokes to categorize components:
68
+
69
+ | Component Type | Fill (rgba) | Stroke (Hex) |
70
+ | :--- | :--- | :--- |
71
+ | **Frontend** | `rgba(8, 51, 68, 0.4)` | `#22d3ee` (cyan-400) |
72
+ | **Backend** | `rgba(6, 78, 59, 0.4)` | `#34d399` (emerald-400) |
73
+ | **Database** | `rgba(76, 29, 149, 0.4)` | `#a78bfa` (violet-400) |
74
+ | **AWS/Cloud** | `rgba(120, 53, 15, 0.3)` | `#fbbf24` (amber-400) |
75
+ | **Security** | `rgba(136, 19, 55, 0.4)` | `#fb7185` (rose-400) |
76
+ | **Message Bus** | `rgba(251, 146, 60, 0.3)` | `#fb923c` (orange-400) |
77
+ | **External** | `rgba(30, 41, 59, 0.5)` | `#94a3b8` (slate-400) |
78
+
79
+ ### Typography & Background
80
+ - **Font:** JetBrains Mono (Monospace), loaded from Google Fonts
81
+ - **Sizes:** 12px (Names), 9px (Sublabels), 8px (Annotations), 7px (Tiny labels)
82
+ - **Background:** Slate-950 (`#020617`) with a subtle 40px grid pattern
83
+
84
+ ```svg
85
+ <!-- Background Grid Pattern -->
86
+ <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
87
+ <path d="M 40 0 L 0 0 0 40" fill="none" stroke="#1e293b" stroke-width="0.5"/>
88
+ </pattern>
89
+ ```
90
+
91
+ ## Technical Implementation Details
92
+
93
+ ### Component Rendering
94
+ Components are rounded rectangles (`rx="6"`) with 1.5px strokes. To prevent arrows from showing through semi-transparent fills, use a **double-rect masking technique**:
95
+ 1. Draw an opaque background rect (`#0f172a`)
96
+ 2. Draw the semi-transparent styled rect on top
97
+
98
+ ### Connection Rules
99
+ - **Z-Order:** Draw arrows *early* in the SVG (after the grid) so they render behind component boxes
100
+ - **Arrowheads:** Defined via SVG markers
101
+ - **Security Flows:** Use dashed lines in rose color (`#fb7185`)
102
+ - **Boundaries:**
103
+ - *Security Groups:* Dashed (`4,4`), rose color
104
+ - *Regions:* Large dashed (`8,4`), amber color, `rx="12"`
105
+
106
+ ### Spacing & Layout Logic
107
+ - **Standard Height:** 60px (Services); 80-120px (Large components)
108
+ - **Vertical Gap:** Minimum 40px between components
109
+ - **Message Buses:** Must be placed *in the gap* between services, not overlapping them
110
+ - **Legend Placement:** **CRITICAL.** Must be placed outside all boundary boxes. Calculate the lowest Y-coordinate of all boundaries and place the legend at least 20px below it.
111
+
112
+ ## Document Structure
113
+
114
+ The generated HTML file follows a four-part layout:
115
+ 1. **Header:** Title with a pulsing dot indicator and subtitle
116
+ 2. **Main SVG:** The diagram contained within a rounded border card
117
+ 3. **Summary Cards:** A grid of three cards below the diagram for high-level details
118
+ 4. **Footer:** Minimal metadata
119
+
120
+ ### Info Card Pattern
121
+ ```html
122
+ <div class="card">
123
+ <div class="card-header">
124
+ <div class="card-dot cyan"></div>
125
+ <h3>Title</h3>
126
+ </div>
127
+ <ul>
128
+ <li>• Item one</li>
129
+ <li>• Item two</li>
130
+ </ul>
131
+ </div>
132
+ ```
133
+
134
+ ## Output Requirements
135
+ - **Single File:** One self-contained `.html` file
136
+ - **No External Dependencies:** All CSS and SVG must be inline (except Google Fonts)
137
+ - **No JavaScript:** Use pure CSS for any animations (like pulsing dots)
138
+ - **Compatibility:** Must render correctly in any modern web browser
139
+
140
+ ## Template Reference
141
+
142
+ Load the full HTML template for the exact structure, CSS, and SVG component examples:
143
+
144
+ ```
145
+ skill_view(name="architecture-diagram", file_path="templates/template.html")
146
+ ```
147
+
148
+ The template contains working examples of every component type (frontend, backend, database, cloud, security), arrow styles (standard, dashed, curved), security groups, region boundaries, and the legend — use it as your structural reference when generating diagrams.
skills/.archive/architecture-diagram/templates/template.html ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>[PROJECT NAME] Architecture Diagram</title>
7
+ <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">
8
+ <style>
9
+ * {
10
+ margin: 0;
11
+ padding: 0;
12
+ box-sizing: border-box;
13
+ }
14
+
15
+ body {
16
+ font-family: 'JetBrains Mono', monospace;
17
+ background: #020617;
18
+ min-height: 100vh;
19
+ padding: 2rem;
20
+ color: white;
21
+ }
22
+
23
+ .container {
24
+ max-width: 1200px;
25
+ margin: 0 auto;
26
+ }
27
+
28
+ .header {
29
+ margin-bottom: 2rem;
30
+ }
31
+
32
+ .header-row {
33
+ display: flex;
34
+ align-items: center;
35
+ gap: 1rem;
36
+ margin-bottom: 0.5rem;
37
+ }
38
+
39
+ .pulse-dot {
40
+ width: 12px;
41
+ height: 12px;
42
+ background: #22d3ee;
43
+ border-radius: 50%;
44
+ animation: pulse 2s infinite;
45
+ }
46
+
47
+ @keyframes pulse {
48
+ 0%, 100% { opacity: 1; }
49
+ 50% { opacity: 0.5; }
50
+ }
51
+
52
+ h1 {
53
+ font-size: 1.5rem;
54
+ font-weight: 700;
55
+ letter-spacing: -0.025em;
56
+ }
57
+
58
+ .subtitle {
59
+ color: #94a3b8;
60
+ font-size: 0.875rem;
61
+ margin-left: 1.75rem;
62
+ }
63
+
64
+ .diagram-container {
65
+ background: rgba(15, 23, 42, 0.5);
66
+ border-radius: 1rem;
67
+ border: 1px solid #1e293b;
68
+ padding: 1.5rem;
69
+ overflow-x: auto;
70
+ }
71
+
72
+ svg {
73
+ width: 100%;
74
+ min-width: 900px;
75
+ display: block;
76
+ }
77
+
78
+ .cards {
79
+ display: grid;
80
+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
81
+ gap: 1rem;
82
+ margin-top: 2rem;
83
+ }
84
+
85
+ .card {
86
+ background: rgba(15, 23, 42, 0.5);
87
+ border-radius: 0.75rem;
88
+ border: 1px solid #1e293b;
89
+ padding: 1.25rem;
90
+ }
91
+
92
+ .card-header {
93
+ display: flex;
94
+ align-items: center;
95
+ gap: 0.5rem;
96
+ margin-bottom: 0.75rem;
97
+ }
98
+
99
+ .card-dot {
100
+ width: 8px;
101
+ height: 8px;
102
+ border-radius: 50%;
103
+ }
104
+
105
+ .card-dot.cyan { background: #22d3ee; }
106
+ .card-dot.emerald { background: #34d399; }
107
+ .card-dot.violet { background: #a78bfa; }
108
+ .card-dot.amber { background: #fbbf24; }
109
+ .card-dot.rose { background: #fb7185; }
110
+
111
+ .card h3 {
112
+ font-size: 0.875rem;
113
+ font-weight: 600;
114
+ }
115
+
116
+ .card ul {
117
+ list-style: none;
118
+ color: #94a3b8;
119
+ font-size: 0.75rem;
120
+ }
121
+
122
+ .card li {
123
+ margin-bottom: 0.375rem;
124
+ }
125
+
126
+ .footer {
127
+ text-align: center;
128
+ margin-top: 1.5rem;
129
+ color: #475569;
130
+ font-size: 0.75rem;
131
+ }
132
+ </style>
133
+ </head>
134
+ <body>
135
+ <div class="container">
136
+ <!-- Header -->
137
+ <div class="header">
138
+ <div class="header-row">
139
+ <div class="pulse-dot"></div>
140
+ <h1>[PROJECT NAME] Architecture</h1>
141
+ </div>
142
+ <p class="subtitle">[Subtitle description]</p>
143
+ </div>
144
+
145
+ <!-- Main Diagram -->
146
+ <div class="diagram-container">
147
+ <svg viewBox="0 0 1000 680">
148
+ <!-- Definitions -->
149
+ <defs>
150
+ <marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
151
+ <polygon points="0 0, 10 3.5, 0 7" fill="#64748b" />
152
+ </marker>
153
+ <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
154
+ <path d="M 40 0 L 0 0 0 40" fill="none" stroke="#1e293b" stroke-width="0.5"/>
155
+ </pattern>
156
+ </defs>
157
+
158
+ <!-- Background Grid -->
159
+ <rect width="100%" height="100%" fill="url(#grid)" />
160
+
161
+ <!-- =================================================================
162
+ COMPONENT EXAMPLES - Copy and customize these patterns
163
+ ================================================================= -->
164
+
165
+ <!-- External/Generic Component -->
166
+ <rect x="30" y="280" width="100" height="50" rx="6" fill="rgba(30, 41, 59, 0.5)" stroke="#94a3b8" stroke-width="1.5"/>
167
+ <text x="80" y="300" fill="white" font-size="11" font-weight="600" text-anchor="middle">Users</text>
168
+ <text x="80" y="316" fill="#94a3b8" font-size="9" text-anchor="middle">Browser/Mobile</text>
169
+
170
+ <!-- Security Component -->
171
+ <rect x="30" y="80" width="100" height="60" rx="6" fill="rgba(136, 19, 55, 0.4)" stroke="#fb7185" stroke-width="1.5"/>
172
+ <text x="80" y="105" fill="white" font-size="11" font-weight="600" text-anchor="middle">Auth Provider</text>
173
+ <text x="80" y="121" fill="#94a3b8" font-size="9" text-anchor="middle">OAuth 2.0</text>
174
+
175
+ <!-- Region/Cloud Boundary -->
176
+ <rect x="160" y="40" width="820" height="620" rx="12" fill="rgba(251, 191, 36, 0.05)" stroke="#fbbf24" stroke-width="1" stroke-dasharray="8,4"/>
177
+ <text x="172" y="58" fill="#fbbf24" font-size="10" font-weight="600">AWS Region: us-west-2</text>
178
+
179
+ <!-- AWS/Cloud Service -->
180
+ <rect x="200" y="280" width="110" height="50" rx="6" fill="rgba(120, 53, 15, 0.3)" stroke="#fbbf24" stroke-width="1.5"/>
181
+ <text x="255" y="300" fill="white" font-size="11" font-weight="600" text-anchor="middle">CloudFront</text>
182
+ <text x="255" y="316" fill="#94a3b8" font-size="9" text-anchor="middle">CDN</text>
183
+
184
+ <!-- Multi-line AWS Component (S3 Buckets example) -->
185
+ <rect x="200" y="380" width="110" height="100" rx="6" fill="rgba(120, 53, 15, 0.3)" stroke="#fbbf24" stroke-width="1.5"/>
186
+ <text x="255" y="400" fill="white" font-size="11" font-weight="600" text-anchor="middle">S3 Buckets</text>
187
+ <text x="255" y="420" fill="#94a3b8" font-size="8" text-anchor="middle">• bucket-one</text>
188
+ <text x="255" y="434" fill="#94a3b8" font-size="8" text-anchor="middle">• bucket-two</text>
189
+ <text x="255" y="448" fill="#94a3b8" font-size="8" text-anchor="middle">• bucket-three</text>
190
+ <text x="255" y="466" fill="#fbbf24" font-size="7" text-anchor="middle">OAI Protected</text>
191
+
192
+ <!-- Security Group (dashed boundary) -->
193
+ <rect x="350" y="265" width="120" height="80" rx="8" fill="transparent" stroke="#fb7185" stroke-width="1" stroke-dasharray="4,4"/>
194
+ <text x="358" y="279" fill="#fb7185" font-size="8">sg-name :port</text>
195
+
196
+ <!-- Component inside security group -->
197
+ <rect x="360" y="280" width="100" height="50" rx="6" fill="rgba(120, 53, 15, 0.3)" stroke="#fbbf24" stroke-width="1.5"/>
198
+ <text x="410" y="300" fill="white" font-size="11" font-weight="600" text-anchor="middle">Load Balancer</text>
199
+ <text x="410" y="316" fill="#94a3b8" font-size="9" text-anchor="middle">HTTPS :443</text>
200
+
201
+ <!-- Backend Component -->
202
+ <rect x="510" y="280" width="110" height="50" rx="6" fill="rgba(6, 78, 59, 0.4)" stroke="#34d399" stroke-width="1.5"/>
203
+ <text x="565" y="300" fill="white" font-size="11" font-weight="600" text-anchor="middle">API Server</text>
204
+ <text x="565" y="316" fill="#94a3b8" font-size="9" text-anchor="middle">FastAPI :8000</text>
205
+
206
+ <!-- Database Component -->
207
+ <rect x="700" y="280" width="120" height="50" rx="6" fill="rgba(76, 29, 149, 0.4)" stroke="#a78bfa" stroke-width="1.5"/>
208
+ <text x="760" y="300" fill="white" font-size="11" font-weight="600" text-anchor="middle">Database</text>
209
+ <text x="760" y="316" fill="#94a3b8" font-size="9" text-anchor="middle">PostgreSQL</text>
210
+
211
+ <!-- Frontend Component -->
212
+ <rect x="200" y="520" width="200" height="110" rx="8" fill="rgba(8, 51, 68, 0.4)" stroke="#22d3ee" stroke-width="1.5"/>
213
+ <text x="300" y="545" fill="white" font-size="12" font-weight="600" text-anchor="middle">Frontend</text>
214
+ <text x="300" y="565" fill="#94a3b8" font-size="9" text-anchor="middle">React + TypeScript</text>
215
+ <text x="300" y="580" fill="#94a3b8" font-size="9" text-anchor="middle">Additional detail</text>
216
+ <text x="300" y="595" fill="#94a3b8" font-size="9" text-anchor="middle">More info</text>
217
+ <text x="300" y="615" fill="#22d3ee" font-size="8" text-anchor="middle">domain.example.com</text>
218
+
219
+ <!-- =================================================================
220
+ ARROW EXAMPLES
221
+ ================================================================= -->
222
+
223
+ <!-- Standard arrow with label -->
224
+ <line x1="130" y1="305" x2="198" y2="305" stroke="#22d3ee" stroke-width="1.5" marker-end="url(#arrowhead)"/>
225
+ <text x="164" y="299" fill="#94a3b8" font-size="9" text-anchor="middle">HTTPS</text>
226
+
227
+ <!-- Simple arrow (no label) -->
228
+ <line x1="310" y1="305" x2="358" y2="305" stroke="#22d3ee" stroke-width="1.5" marker-end="url(#arrowhead)"/>
229
+
230
+ <!-- Vertical arrow -->
231
+ <line x1="255" y1="330" x2="255" y2="378" stroke="#fbbf24" stroke-width="1.5" marker-end="url(#arrowhead)"/>
232
+ <text x="270" y="358" fill="#94a3b8" font-size="9">OAI</text>
233
+
234
+ <!-- Dashed arrow (for auth/security flows) -->
235
+ <line x1="460" y1="305" x2="508" y2="305" stroke="#34d399" stroke-width="1.5" marker-end="url(#arrowhead)"/>
236
+ <line x1="620" y1="305" x2="698" y2="305" stroke="#a78bfa" stroke-width="1.5" marker-end="url(#arrowhead)"/>
237
+ <text x="655" y="299" fill="#94a3b8" font-size="9">TLS</text>
238
+
239
+ <!-- Curved path for auth flow -->
240
+ <path d="M 80 140 L 80 200 Q 80 220 100 220 L 200 220 Q 220 220 220 240 L 220 278" fill="none" stroke="#fb7185" stroke-width="1.5" stroke-dasharray="5,5"/>
241
+ <text x="150" y="210" fill="#fb7185" font-size="8">JWT + PKCE</text>
242
+
243
+ <!-- =================================================================
244
+ LEGEND
245
+ ================================================================= -->
246
+ <text x="720" y="70" fill="white" font-size="10" font-weight="600">Legend</text>
247
+
248
+ <rect x="720" y="82" width="16" height="10" rx="2" fill="rgba(8, 51, 68, 0.4)" stroke="#22d3ee" stroke-width="1"/>
249
+ <text x="742" y="90" fill="#94a3b8" font-size="8">Frontend</text>
250
+
251
+ <rect x="720" y="98" width="16" height="10" rx="2" fill="rgba(6, 78, 59, 0.4)" stroke="#34d399" stroke-width="1"/>
252
+ <text x="742" y="106" fill="#94a3b8" font-size="8">Backend</text>
253
+
254
+ <rect x="720" y="114" width="16" height="10" rx="2" fill="rgba(120, 53, 15, 0.3)" stroke="#fbbf24" stroke-width="1"/>
255
+ <text x="742" y="122" fill="#94a3b8" font-size="8">Cloud Service</text>
256
+
257
+ <rect x="720" y="130" width="16" height="10" rx="2" fill="rgba(76, 29, 149, 0.4)" stroke="#a78bfa" stroke-width="1"/>
258
+ <text x="742" y="138" fill="#94a3b8" font-size="8">Database</text>
259
+
260
+ <rect x="720" y="146" width="16" height="10" rx="2" fill="rgba(136, 19, 55, 0.4)" stroke="#fb7185" stroke-width="1"/>
261
+ <text x="742" y="154" fill="#94a3b8" font-size="8">Security</text>
262
+
263
+ <line x1="720" y1="168" x2="736" y2="168" stroke="#fb7185" stroke-width="1" stroke-dasharray="3,3"/>
264
+ <text x="742" y="171" fill="#94a3b8" font-size="8">Auth Flow</text>
265
+
266
+ <rect x="720" y="178" width="16" height="10" rx="2" fill="transparent" stroke="#fb7185" stroke-width="1" stroke-dasharray="3,3"/>
267
+ <text x="742" y="186" fill="#94a3b8" font-size="8">Security Group</text>
268
+ </svg>
269
+ </div>
270
+
271
+ <!-- Info Cards -->
272
+ <div class="cards">
273
+ <div class="card">
274
+ <div class="card-header">
275
+ <div class="card-dot rose"></div>
276
+ <h3>Card Title 1</h3>
277
+ </div>
278
+ <ul>
279
+ <li>• Item one</li>
280
+ <li>• Item two</li>
281
+ <li>• Item three</li>
282
+ <li>• Item four</li>
283
+ </ul>
284
+ </div>
285
+
286
+ <div class="card">
287
+ <div class="card-header">
288
+ <div class="card-dot amber"></div>
289
+ <h3>Card Title 2</h3>
290
+ </div>
291
+ <ul>
292
+ <li>• Item one</li>
293
+ <li>• Item two</li>
294
+ <li>• Item three</li>
295
+ <li>• Item four</li>
296
+ </ul>
297
+ </div>
298
+
299
+ <div class="card">
300
+ <div class="card-header">
301
+ <div class="card-dot violet"></div>
302
+ <h3>Card Title 3</h3>
303
+ </div>
304
+ <ul>
305
+ <li>• Item one</li>
306
+ <li>• Item two</li>
307
+ <li>• Item three</li>
308
+ <li>• Item four</li>
309
+ </ul>
310
+ </div>
311
+ </div>
312
+
313
+ <!-- Footer -->
314
+ <p class="footer">
315
+ [Project Name] • [Additional metadata]
316
+ </p>
317
+ </div>
318
+ </body>
319
+ </html>
skills/.archive/arxiv/SKILL.md ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: arxiv
3
+ description: "Search arXiv papers by keyword, author, category, or ID."
4
+ version: 1.0.0
5
+ author: Hermes Agent
6
+ license: MIT
7
+ platforms: [linux, macos, windows]
8
+ metadata:
9
+ hermes:
10
+ tags: [Research, Arxiv, Papers, Academic, Science, API]
11
+ related_skills: [ocr-and-documents]
12
+ ---
13
+
14
+ # arXiv Research
15
+
16
+ Search and retrieve academic papers from arXiv via their free REST API. No API key, no dependencies — just curl.
17
+
18
+ ## Quick Reference
19
+
20
+ | Action | Command |
21
+ |--------|---------|
22
+ | Search papers | `curl "https://export.arxiv.org/api/query?search_query=all:QUERY&max_results=5"` |
23
+ | Get specific paper | `curl "https://export.arxiv.org/api/query?id_list=2402.03300"` |
24
+ | Read abstract (web) | `web_extract(urls=["https://arxiv.org/abs/2402.03300"])` |
25
+ | Read full paper (PDF) | `web_extract(urls=["https://arxiv.org/pdf/2402.03300"])` |
26
+
27
+ ## Searching Papers
28
+
29
+ The API returns Atom XML. Parse with `grep`/`sed` or pipe through `python3` for clean output.
30
+
31
+ ### Basic search
32
+
33
+ ```bash
34
+ curl -s "https://export.arxiv.org/api/query?search_query=all:GRPO+reinforcement+learning&max_results=5"
35
+ ```
36
+
37
+ ### Clean output (parse XML to readable format)
38
+
39
+ ```bash
40
+ curl -s "https://export.arxiv.org/api/query?search_query=all:GRPO+reinforcement+learning&max_results=5&sortBy=submittedDate&sortOrder=descending" | python3 -c "
41
+ import sys, xml.etree.ElementTree as ET
42
+ ns = {'a': 'http://www.w3.org/2005/Atom'}
43
+ root = ET.parse(sys.stdin).getroot()
44
+ for i, entry in enumerate(root.findall('a:entry', ns)):
45
+ title = entry.find('a:title', ns).text.strip().replace('\n', ' ')
46
+ arxiv_id = entry.find('a:id', ns).text.strip().split('/abs/')[-1]
47
+ published = entry.find('a:published', ns).text[:10]
48
+ authors = ', '.join(a.find('a:name', ns).text for a in entry.findall('a:author', ns))
49
+ summary = entry.find('a:summary', ns).text.strip()[:200]
50
+ cats = ', '.join(c.get('term') for c in entry.findall('a:category', ns))
51
+ print(f'{i+1}. [{arxiv_id}] {title}')
52
+ print(f' Authors: {authors}')
53
+ print(f' Published: {published} | Categories: {cats}')
54
+ print(f' Abstract: {summary}...')
55
+ print(f' PDF: https://arxiv.org/pdf/{arxiv_id}')
56
+ print()
57
+ "
58
+ ```
59
+
60
+ ## Search Query Syntax
61
+
62
+ | Prefix | Searches | Example |
63
+ |--------|----------|---------|
64
+ | `all:` | All fields | `all:transformer+attention` |
65
+ | `ti:` | Title | `ti:large+language+models` |
66
+ | `au:` | Author | `au:vaswani` |
67
+ | `abs:` | Abstract | `abs:reinforcement+learning` |
68
+ | `cat:` | Category | `cat:cs.AI` |
69
+ | `co:` | Comment | `co:accepted+NeurIPS` |
70
+
71
+ ### Boolean operators
72
+
73
+ ```
74
+ # AND (default when using +)
75
+ search_query=all:transformer+attention
76
+
77
+ # OR
78
+ search_query=all:GPT+OR+all:BERT
79
+
80
+ # AND NOT
81
+ search_query=all:language+model+ANDNOT+all:vision
82
+
83
+ # Exact phrase
84
+ search_query=ti:"chain+of+thought"
85
+
86
+ # Combined
87
+ search_query=au:hinton+AND+cat:cs.LG
88
+ ```
89
+
90
+ ## Sort and Pagination
91
+
92
+ | Parameter | Options |
93
+ |-----------|---------|
94
+ | `sortBy` | `relevance`, `lastUpdatedDate`, `submittedDate` |
95
+ | `sortOrder` | `ascending`, `descending` |
96
+ | `start` | Result offset (0-based) |
97
+ | `max_results` | Number of results (default 10, max 30000) |
98
+
99
+ ```bash
100
+ # Latest 10 papers in cs.AI
101
+ curl -s "https://export.arxiv.org/api/query?search_query=cat:cs.AI&sortBy=submittedDate&sortOrder=descending&max_results=10"
102
+ ```
103
+
104
+ ## Fetching Specific Papers
105
+
106
+ ```bash
107
+ # By arXiv ID
108
+ curl -s "https://export.arxiv.org/api/query?id_list=2402.03300"
109
+
110
+ # Multiple papers
111
+ curl -s "https://export.arxiv.org/api/query?id_list=2402.03300,2401.12345,2403.00001"
112
+ ```
113
+
114
+ ## BibTeX Generation
115
+
116
+ After fetching metadata for a paper, generate a BibTeX entry:
117
+
118
+ {% raw %}
119
+ ```bash
120
+ curl -s "https://export.arxiv.org/api/query?id_list=1706.03762" | python3 -c "
121
+ import sys, xml.etree.ElementTree as ET
122
+ ns = {'a': 'http://www.w3.org/2005/Atom', 'arxiv': 'http://arxiv.org/schemas/atom'}
123
+ root = ET.parse(sys.stdin).getroot()
124
+ entry = root.find('a:entry', ns)
125
+ if entry is None: sys.exit('Paper not found')
126
+ title = entry.find('a:title', ns).text.strip().replace('\n', ' ')
127
+ authors = ' and '.join(a.find('a:name', ns).text for a in entry.findall('a:author', ns))
128
+ year = entry.find('a:published', ns).text[:4]
129
+ raw_id = entry.find('a:id', ns).text.strip().split('/abs/')[-1]
130
+ cat = entry.find('arxiv:primary_category', ns)
131
+ primary = cat.get('term') if cat is not None else 'cs.LG'
132
+ last_name = entry.find('a:author', ns).find('a:name', ns).text.split()[-1]
133
+ print(f'@article{{{last_name}{year}_{raw_id.replace(\".\", \"\")},')
134
+ print(f' title = {{{title}}},')
135
+ print(f' author = {{{authors}}},')
136
+ print(f' year = {{{year}}},')
137
+ print(f' eprint = {{{raw_id}}},')
138
+ print(f' archivePrefix = {{arXiv}},')
139
+ print(f' primaryClass = {{{primary}}},')
140
+ print(f' url = {{https://arxiv.org/abs/{raw_id}}}')
141
+ print('}')
142
+ "
143
+ ```
144
+ {% endraw %}
145
+
146
+ ## Reading Paper Content
147
+
148
+ After finding a paper, read it:
149
+
150
+ ```
151
+ # Abstract page (fast, metadata + abstract)
152
+ web_extract(urls=["https://arxiv.org/abs/2402.03300"])
153
+
154
+ # Full paper (PDF → markdown via Firecrawl)
155
+ web_extract(urls=["https://arxiv.org/pdf/2402.03300"])
156
+ ```
157
+
158
+ For local PDF processing, see the `ocr-and-documents` skill.
159
+
160
+ ## Common Categories
161
+
162
+ | Category | Field |
163
+ |----------|-------|
164
+ | `cs.AI` | Artificial Intelligence |
165
+ | `cs.CL` | Computation and Language (NLP) |
166
+ | `cs.CV` | Computer Vision |
167
+ | `cs.LG` | Machine Learning |
168
+ | `cs.CR` | Cryptography and Security |
169
+ | `stat.ML` | Machine Learning (Statistics) |
170
+ | `math.OC` | Optimization and Control |
171
+ | `physics.comp-ph` | Computational Physics |
172
+
173
+ Full list: https://arxiv.org/category_taxonomy
174
+
175
+ ## Helper Script
176
+
177
+ The `scripts/search_arxiv.py` script handles XML parsing and provides clean output:
178
+
179
+ ```bash
180
+ python scripts/search_arxiv.py "GRPO reinforcement learning"
181
+ python scripts/search_arxiv.py "transformer attention" --max 10 --sort date
182
+ python scripts/search_arxiv.py --author "Yann LeCun" --max 5
183
+ python scripts/search_arxiv.py --category cs.AI --sort date
184
+ python scripts/search_arxiv.py --id 2402.03300
185
+ python scripts/search_arxiv.py --id 2402.03300,2401.12345
186
+ ```
187
+
188
+ No dependencies — uses only Python stdlib.
189
+
190
+ ---
191
+
192
+ ## Semantic Scholar (Citations, Related Papers, Author Profiles)
193
+
194
+ arXiv doesn't provide citation data or recommendations. Use the **Semantic Scholar API** for that — free, no key needed for basic use (1 req/sec), returns JSON.
195
+
196
+ ### Get paper details + citations
197
+
198
+ ```bash
199
+ # By arXiv ID
200
+ curl -s "https://api.semanticscholar.org/graph/v1/paper/arXiv:2402.03300?fields=title,authors,citationCount,referenceCount,influentialCitationCount,year,abstract" | python3 -m json.tool
201
+
202
+ # By Semantic Scholar paper ID or DOI
203
+ curl -s "https://api.semanticscholar.org/graph/v1/paper/DOI:10.1234/example?fields=title,citationCount"
204
+ ```
205
+
206
+ ### Get citations OF a paper (who cited it)
207
+
208
+ ```bash
209
+ curl -s "https://api.semanticscholar.org/graph/v1/paper/arXiv:2402.03300/citations?fields=title,authors,year,citationCount&limit=10" | python3 -m json.tool
210
+ ```
211
+
212
+ ### Get references FROM a paper (what it cites)
213
+
214
+ ```bash
215
+ curl -s "https://api.semanticscholar.org/graph/v1/paper/arXiv:2402.03300/references?fields=title,authors,year,citationCount&limit=10" | python3 -m json.tool
216
+ ```
217
+
218
+ ### Search papers (alternative to arXiv search, returns JSON)
219
+
220
+ ```bash
221
+ curl -s "https://api.semanticscholar.org/graph/v1/paper/search?query=GRPO+reinforcement+learning&limit=5&fields=title,authors,year,citationCount,externalIds" | python3 -m json.tool
222
+ ```
223
+
224
+ ### Get paper recommendations
225
+
226
+ ```bash
227
+ curl -s -X POST "https://api.semanticscholar.org/recommendations/v1/papers/" \
228
+ -H "Content-Type: application/json" \
229
+ -d '{"positivePaperIds": ["arXiv:2402.03300"], "negativePaperIds": []}' | python3 -m json.tool
230
+ ```
231
+
232
+ ### Author profile
233
+
234
+ ```bash
235
+ curl -s "https://api.semanticscholar.org/graph/v1/author/search?query=Yann+LeCun&fields=name,hIndex,citationCount,paperCount" | python3 -m json.tool
236
+ ```
237
+
238
+ ### Useful Semantic Scholar fields
239
+
240
+ `title`, `authors`, `year`, `abstract`, `citationCount`, `referenceCount`, `influentialCitationCount`, `isOpenAccess`, `openAccessPdf`, `fieldsOfStudy`, `publicationVenue`, `externalIds` (contains arXiv ID, DOI, etc.)
241
+
242
+ ---
243
+
244
+ ## Complete Research Workflow
245
+
246
+ 1. **Discover**: `python scripts/search_arxiv.py "your topic" --sort date --max 10`
247
+ 2. **Assess impact**: `curl -s "https://api.semanticscholar.org/graph/v1/paper/arXiv:ID?fields=citationCount,influentialCitationCount"`
248
+ 3. **Read abstract**: `web_extract(urls=["https://arxiv.org/abs/ID"])`
249
+ 4. **Read full paper**: `web_extract(urls=["https://arxiv.org/pdf/ID"])`
250
+ 5. **Find related work**: `curl -s "https://api.semanticscholar.org/graph/v1/paper/arXiv:ID/references?fields=title,citationCount&limit=20"`
251
+ 6. **Get recommendations**: POST to Semantic Scholar recommendations endpoint
252
+ 7. **Track authors**: `curl -s "https://api.semanticscholar.org/graph/v1/author/search?query=NAME"`
253
+
254
+ ## Rate Limits
255
+
256
+ | API | Rate | Auth |
257
+ |-----|------|------|
258
+ | arXiv | ~1 req / 3 seconds | None needed |
259
+ | Semantic Scholar | 1 req / second | None (100/sec with API key) |
260
+
261
+ ## Notes
262
+
263
+ - arXiv returns Atom XML — use the helper script or parsing snippet for clean output
264
+ - Semantic Scholar returns JSON — pipe through `python3 -m json.tool` for readability
265
+ - arXiv IDs: old format (`hep-th/0601001`) vs new (`2402.03300`)
266
+ - PDF: `https://arxiv.org/pdf/{id}` — Abstract: `https://arxiv.org/abs/{id}`
267
+ - HTML (when available): `https://arxiv.org/html/{id}`
268
+ - For local PDF processing, see the `ocr-and-documents` skill
269
+
270
+ ## ID Versioning
271
+
272
+ - `arxiv.org/abs/1706.03762` always resolves to the **latest** version
273
+ - `arxiv.org/abs/1706.03762v1` points to a **specific** immutable version
274
+ - When generating citations, preserve the version suffix you actually read to prevent citation drift (a later version may substantially change content)
275
+ - The API `<id>` field returns the versioned URL (e.g., `http://arxiv.org/abs/1706.03762v7`)
276
+
277
+ ## Withdrawn Papers
278
+
279
+ Papers can be withdrawn after submission. When this happens:
280
+ - The `<summary>` field contains a withdrawal notice (look for "withdrawn" or "retracted")
281
+ - Metadata fields may be incomplete
282
+ - Always check the summary before treating a result as a valid paper
skills/.archive/arxiv/scripts/__pycache__/search_arxiv.cpython-311.pyc ADDED
Binary file (8.24 kB). View file
 
skills/.archive/arxiv/scripts/search_arxiv.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Search arXiv and display results in a clean format.
3
+
4
+ Usage:
5
+ python search_arxiv.py "GRPO reinforcement learning"
6
+ python search_arxiv.py "GRPO reinforcement learning" --max 10
7
+ python search_arxiv.py "GRPO reinforcement learning" --sort date
8
+ python search_arxiv.py --author "Yann LeCun" --max 5
9
+ python search_arxiv.py --category cs.AI --sort date --max 10
10
+ python search_arxiv.py --id 2402.03300
11
+ python search_arxiv.py --id 2402.03300,2401.12345
12
+ """
13
+ import sys
14
+ import urllib.request
15
+ import urllib.parse
16
+ import xml.etree.ElementTree as ET
17
+
18
+ NS = {'a': 'http://www.w3.org/2005/Atom'}
19
+
20
+ def search(query=None, author=None, category=None, ids=None, max_results=5, sort="relevance"):
21
+ params = {}
22
+
23
+ if ids:
24
+ params['id_list'] = ids
25
+ else:
26
+ parts = []
27
+ if query:
28
+ parts.append(f'all:{urllib.parse.quote(query)}')
29
+ if author:
30
+ parts.append(f'au:{urllib.parse.quote(author)}')
31
+ if category:
32
+ parts.append(f'cat:{category}')
33
+ if not parts:
34
+ print("Error: provide a query, --author, --category, or --id")
35
+ sys.exit(1)
36
+ params['search_query'] = '+AND+'.join(parts)
37
+
38
+ params['max_results'] = str(max_results)
39
+
40
+ sort_map = {"relevance": "relevance", "date": "submittedDate", "updated": "lastUpdatedDate"}
41
+ params['sortBy'] = sort_map.get(sort, sort)
42
+ params['sortOrder'] = 'descending'
43
+
44
+ url = "https://export.arxiv.org/api/query?" + "&".join(f"{k}={v}" for k, v in params.items())
45
+
46
+ req = urllib.request.Request(url, headers={'User-Agent': 'HermesAgent/1.0'})
47
+ with urllib.request.urlopen(req, timeout=15) as resp:
48
+ data = resp.read()
49
+
50
+ root = ET.fromstring(data)
51
+ entries = root.findall('a:entry', NS)
52
+
53
+ if not entries:
54
+ print("No results found.")
55
+ return
56
+
57
+ total = root.find('{http://a9.com/-/spec/opensearch/1.1/}totalResults')
58
+ if total is not None:
59
+ print(f"Found {total.text} results (showing {len(entries)})\n")
60
+
61
+ for i, entry in enumerate(entries):
62
+ title = entry.find('a:title', NS).text.strip().replace('\n', ' ')
63
+ raw_id = entry.find('a:id', NS).text.strip()
64
+ full_id = raw_id.split('/abs/')[-1] if '/abs/' in raw_id else raw_id
65
+ arxiv_id = full_id.split('v')[0] # base ID for links
66
+ published = entry.find('a:published', NS).text[:10]
67
+ updated = entry.find('a:updated', NS).text[:10]
68
+ authors = ', '.join(a.find('a:name', NS).text for a in entry.findall('a:author', NS))
69
+ summary = entry.find('a:summary', NS).text.strip().replace('\n', ' ')
70
+ cats = ', '.join(c.get('term') for c in entry.findall('a:category', NS))
71
+
72
+ version = full_id[len(arxiv_id):] if full_id != arxiv_id else ""
73
+ print(f"{i+1}. {title}")
74
+ print(f" ID: {arxiv_id}{version} | Published: {published} | Updated: {updated}")
75
+ print(f" Authors: {authors}")
76
+ print(f" Categories: {cats}")
77
+ print(f" Abstract: {summary[:300]}{'...' if len(summary) > 300 else ''}")
78
+ print(f" Links: https://arxiv.org/abs/{arxiv_id} | https://arxiv.org/pdf/{arxiv_id}")
79
+ print()
80
+
81
+
82
+ if __name__ == "__main__":
83
+ args = sys.argv[1:]
84
+ if not args or args[0] in {"-h", "--help"}:
85
+ print(__doc__)
86
+ sys.exit(0)
87
+
88
+ query = None
89
+ author = None
90
+ category = None
91
+ ids = None
92
+ max_results = 5
93
+ sort = "relevance"
94
+
95
+ i = 0
96
+ positional = []
97
+ while i < len(args):
98
+ if args[i] == "--max" and i + 1 < len(args):
99
+ max_results = int(args[i + 1]); i += 2
100
+ elif args[i] == "--sort" and i + 1 < len(args):
101
+ sort = args[i + 1]; i += 2
102
+ elif args[i] == "--author" and i + 1 < len(args):
103
+ author = args[i + 1]; i += 2
104
+ elif args[i] == "--category" and i + 1 < len(args):
105
+ category = args[i + 1]; i += 2
106
+ elif args[i] == "--id" and i + 1 < len(args):
107
+ ids = args[i + 1]; i += 2
108
+ else:
109
+ positional.append(args[i]); i += 1
110
+
111
+ if positional:
112
+ query = " ".join(positional)
113
+
114
+ search(query=query, author=author, category=category, ids=ids, max_results=max_results, sort=sort)
skills/.archive/ascii-art/SKILL.md ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: ascii-art
3
+ description: "ASCII art: pyfiglet, cowsay, boxes, image-to-ascii."
4
+ version: 4.0.0
5
+ author: 0xbyt4, Hermes Agent
6
+ license: MIT
7
+ dependencies: []
8
+ platforms: [linux, macos, windows]
9
+ metadata:
10
+ hermes:
11
+ tags: [ASCII, Art, Banners, Creative, Unicode, Text-Art, pyfiglet, figlet, cowsay, boxes]
12
+ related_skills: [excalidraw]
13
+
14
+ ---
15
+
16
+ # ASCII Art Skill
17
+
18
+ Multiple tools for different ASCII art needs. All tools are local CLI programs or free REST APIs — no API keys required.
19
+
20
+ ## Tool 1: Text Banners (pyfiglet — local)
21
+
22
+ Render text as large ASCII art banners. 571 built-in fonts.
23
+
24
+ ### Setup
25
+
26
+ ```bash
27
+ pip install pyfiglet --break-system-packages -q
28
+ ```
29
+
30
+ ### Usage
31
+
32
+ ```bash
33
+ python3 -m pyfiglet "YOUR TEXT" -f slant
34
+ python3 -m pyfiglet "TEXT" -f doom -w 80 # Set width
35
+ python3 -m pyfiglet --list_fonts # List all 571 fonts
36
+ ```
37
+
38
+ ### Recommended fonts
39
+
40
+ | Style | Font | Best for |
41
+ |-------|------|----------|
42
+ | Clean & modern | `slant` | Project names, headers |
43
+ | Bold & blocky | `doom` | Titles, logos |
44
+ | Big & readable | `big` | Banners |
45
+ | Classic banner | `banner3` | Wide displays |
46
+ | Compact | `small` | Subtitles |
47
+ | Cyberpunk | `cyberlarge` | Tech themes |
48
+ | 3D effect | `3-d` | Splash screens |
49
+ | Gothic | `gothic` | Dramatic text |
50
+
51
+ ### Tips
52
+
53
+ - Preview 2-3 fonts and let the user pick their favorite
54
+ - Short text (1-8 chars) works best with detailed fonts like `doom` or `block`
55
+ - Long text works better with compact fonts like `small` or `mini`
56
+
57
+ ## Tool 2: Text Banners (asciified API — remote, no install)
58
+
59
+ Free REST API that converts text to ASCII art. 250+ FIGlet fonts. Returns plain text directly — no parsing needed. Use this when pyfiglet is not installed or as a quick alternative.
60
+
61
+ ### Usage (via terminal curl)
62
+
63
+ ```bash
64
+ # Basic text banner (default font)
65
+ curl -s "https://asciified.thelicato.io/api/v2/ascii?text=Hello+World"
66
+
67
+ # With a specific font
68
+ curl -s "https://asciified.thelicato.io/api/v2/ascii?text=Hello&font=Slant"
69
+ curl -s "https://asciified.thelicato.io/api/v2/ascii?text=Hello&font=Doom"
70
+ curl -s "https://asciified.thelicato.io/api/v2/ascii?text=Hello&font=Star+Wars"
71
+ curl -s "https://asciified.thelicato.io/api/v2/ascii?text=Hello&font=3-D"
72
+ curl -s "https://asciified.thelicato.io/api/v2/ascii?text=Hello&font=Banner3"
73
+
74
+ # List all available fonts (returns JSON array)
75
+ curl -s "https://asciified.thelicato.io/api/v2/fonts"
76
+ ```
77
+
78
+ ### Tips
79
+
80
+ - URL-encode spaces as `+` in the text parameter
81
+ - The response is plain text ASCII art — no JSON wrapping, ready to display
82
+ - Font names are case-sensitive; use the fonts endpoint to get exact names
83
+ - Works from any terminal with curl — no Python or pip needed
84
+
85
+ ## Tool 3: Cowsay (Message Art)
86
+
87
+ Classic tool that wraps text in a speech bubble with an ASCII character.
88
+
89
+ ### Setup
90
+
91
+ ```bash
92
+ sudo apt install cowsay -y # Debian/Ubuntu
93
+ # brew install cowsay # macOS
94
+ ```
95
+
96
+ ### Usage
97
+
98
+ ```bash
99
+ cowsay "Hello World"
100
+ cowsay -f tux "Linux rules" # Tux the penguin
101
+ cowsay -f dragon "Rawr!" # Dragon
102
+ cowsay -f stegosaurus "Roar!" # Stegosaurus
103
+ cowthink "Hmm..." # Thought bubble
104
+ cowsay -l # List all characters
105
+ ```
106
+
107
+ ### Available characters (50+)
108
+
109
+ `beavis.zen`, `bong`, `bunny`, `cheese`, `daemon`, `default`, `dragon`,
110
+ `dragon-and-cow`, `elephant`, `eyes`, `flaming-skull`, `ghostbusters`,
111
+ `hellokitty`, `kiss`, `kitty`, `koala`, `luke-koala`, `mech-and-cow`,
112
+ `meow`, `moofasa`, `moose`, `ren`, `sheep`, `skeleton`, `small`,
113
+ `stegosaurus`, `stimpy`, `supermilker`, `surgery`, `three-eyes`,
114
+ `turkey`, `turtle`, `tux`, `udder`, `vader`, `vader-koala`, `www`
115
+
116
+ ### Eye/tongue modifiers
117
+
118
+ ```bash
119
+ cowsay -b "Borg" # =_= eyes
120
+ cowsay -d "Dead" # x_x eyes
121
+ cowsay -g "Greedy" # $_$ eyes
122
+ cowsay -p "Paranoid" # @_@ eyes
123
+ cowsay -s "Stoned" # *_* eyes
124
+ cowsay -w "Wired" # O_O eyes
125
+ cowsay -e "OO" "Msg" # Custom eyes
126
+ cowsay -T "U " "Msg" # Custom tongue
127
+ ```
128
+
129
+ ## Tool 4: Boxes (Decorative Borders)
130
+
131
+ Draw decorative ASCII art borders/frames around any text. 70+ built-in designs.
132
+
133
+ ### Setup
134
+
135
+ ```bash
136
+ sudo apt install boxes -y # Debian/Ubuntu
137
+ # brew install boxes # macOS
138
+ ```
139
+
140
+ ### Usage
141
+
142
+ ```bash
143
+ echo "Hello World" | boxes # Default box
144
+ echo "Hello World" | boxes -d stone # Stone border
145
+ echo "Hello World" | boxes -d parchment # Parchment scroll
146
+ echo "Hello World" | boxes -d cat # Cat border
147
+ echo "Hello World" | boxes -d dog # Dog border
148
+ echo "Hello World" | boxes -d unicornsay # Unicorn
149
+ echo "Hello World" | boxes -d diamonds # Diamond pattern
150
+ echo "Hello World" | boxes -d c-cmt # C-style comment
151
+ echo "Hello World" | boxes -d html-cmt # HTML comment
152
+ echo "Hello World" | boxes -a c # Center text
153
+ boxes -l # List all 70+ designs
154
+ ```
155
+
156
+ ### Combine with pyfiglet or asciified
157
+
158
+ ```bash
159
+ python3 -m pyfiglet "HERMES" -f slant | boxes -d stone
160
+ # Or without pyfiglet installed:
161
+ curl -s "https://asciified.thelicato.io/api/v2/ascii?text=HERMES&font=Slant" | boxes -d stone
162
+ ```
163
+
164
+ ## Tool 5: TOIlet (Colored Text Art)
165
+
166
+ Like pyfiglet but with ANSI color effects and visual filters. Great for terminal eye candy.
167
+
168
+ ### Setup
169
+
170
+ ```bash
171
+ sudo apt install toilet toilet-fonts -y # Debian/Ubuntu
172
+ # brew install toilet # macOS
173
+ ```
174
+
175
+ ### Usage
176
+
177
+ ```bash
178
+ toilet "Hello World" # Basic text art
179
+ toilet -f bigmono12 "Hello" # Specific font
180
+ toilet --gay "Rainbow!" # Rainbow coloring
181
+ toilet --metal "Metal!" # Metallic effect
182
+ toilet -F border "Bordered" # Add border
183
+ toilet -F border --gay "Fancy!" # Combined effects
184
+ toilet -f pagga "Block" # Block-style font (unique to toilet)
185
+ toilet -F list # List available filters
186
+ ```
187
+
188
+ ### Filters
189
+
190
+ `crop`, `gay` (rainbow), `metal`, `flip`, `flop`, `180`, `left`, `right`, `border`
191
+
192
+ **Note**: toilet outputs ANSI escape codes for colors — works in terminals but may not render in all contexts (e.g., plain text files, some chat platforms).
193
+
194
+ ## Tool 6: Image to ASCII Art
195
+
196
+ Convert images (PNG, JPEG, GIF, WEBP) to ASCII art.
197
+
198
+ ### Option A: ascii-image-converter (recommended, modern)
199
+
200
+ ```bash
201
+ # Install
202
+ sudo snap install ascii-image-converter
203
+ # OR: go install github.com/TheZoraiz/ascii-image-converter@latest
204
+ ```
205
+
206
+ ```bash
207
+ ascii-image-converter image.png # Basic
208
+ ascii-image-converter image.png -C # Color output
209
+ ascii-image-converter image.png -d 60,30 # Set dimensions
210
+ ascii-image-converter image.png -b # Braille characters
211
+ ascii-image-converter image.png -n # Negative/inverted
212
+ ascii-image-converter https://url/image.jpg # Direct URL
213
+ ascii-image-converter image.png --save-txt out # Save as text
214
+ ```
215
+
216
+ ### Option B: jp2a (lightweight, JPEG only)
217
+
218
+ ```bash
219
+ sudo apt install jp2a -y
220
+ jp2a --width=80 image.jpg
221
+ jp2a --colors image.jpg # Colorized
222
+ ```
223
+
224
+ ## Tool 7: Search Pre-Made ASCII Art
225
+
226
+ Search curated ASCII art from the web. Use `terminal` with `curl`.
227
+
228
+ ### Source A: ascii.co.uk (recommended for pre-made art)
229
+
230
+ Large collection of classic ASCII art organized by subject. Art is inside HTML `<pre>` tags. Fetch the page with curl, then extract art with a small Python snippet.
231
+
232
+ **URL pattern:** `https://ascii.co.uk/art/{subject}`
233
+
234
+ **Step 1 — Fetch the page:**
235
+
236
+ ```bash
237
+ curl -s 'https://ascii.co.uk/art/cat' -o /tmp/ascii_art.html
238
+ ```
239
+
240
+ **Step 2 — Extract art from pre tags:**
241
+
242
+ ```python
243
+ import re, html
244
+ with open('/tmp/ascii_art.html') as f:
245
+ text = f.read()
246
+ arts = re.findall(r'<pre[^>]*>(.*?)</pre>', text, re.DOTALL)
247
+ for art in arts:
248
+ clean = re.sub(r'<[^>]+>', '', art)
249
+ clean = html.unescape(clean).strip()
250
+ if len(clean) > 30:
251
+ print(clean)
252
+ print('\n---\n')
253
+ ```
254
+
255
+ **Available subjects** (use as URL path):
256
+ - Animals: `cat`, `dog`, `horse`, `bird`, `fish`, `dragon`, `snake`, `rabbit`, `elephant`, `dolphin`, `butterfly`, `owl`, `wolf`, `bear`, `penguin`, `turtle`
257
+ - Objects: `car`, `ship`, `airplane`, `rocket`, `guitar`, `computer`, `coffee`, `beer`, `cake`, `house`, `castle`, `sword`, `crown`, `key`
258
+ - Nature: `tree`, `flower`, `sun`, `moon`, `star`, `mountain`, `ocean`, `rainbow`
259
+ - Characters: `skull`, `robot`, `angel`, `wizard`, `pirate`, `ninja`, `alien`
260
+ - Holidays: `christmas`, `halloween`, `valentine`
261
+
262
+ **Tips:**
263
+ - Preserve artist signatures/initials — important etiquette
264
+ - Multiple art pieces per page — pick the best one for the user
265
+ - Works reliably via curl, no JavaScript needed
266
+
267
+ ### Source B: GitHub Octocat API (fun easter egg)
268
+
269
+ Returns a random GitHub Octocat with a wise quote. No auth needed.
270
+
271
+ ```bash
272
+ curl -s https://api.github.com/octocat
273
+ ```
274
+
275
+ ## Tool 8: Fun ASCII Utilities (via curl)
276
+
277
+ These free services return ASCII art directly — great for fun extras.
278
+
279
+ ### QR Codes as ASCII Art
280
+
281
+ ```bash
282
+ curl -s "qrenco.de/Hello+World"
283
+ curl -s "qrenco.de/https://example.com"
284
+ ```
285
+
286
+ ### Weather as ASCII Art
287
+
288
+ ```bash
289
+ curl -s "wttr.in/London" # Full weather report with ASCII graphics
290
+ curl -s "wttr.in/Moon" # Moon phase in ASCII art
291
+ curl -s "v2.wttr.in/London" # Detailed version
292
+ ```
293
+
294
+ ## Tool 9: LLM-Generated Custom Art (Fallback)
295
+
296
+ When tools above don't have what's needed, generate ASCII art directly using these Unicode characters:
297
+
298
+ ### Character Palette
299
+
300
+ **Box Drawing:** `╔ ╗ ╚ ╝ ║ ═ ╠ ╣ ╦ ╩ ╬ ┌ ┐ └ ┘ │ ─ ├ ┤ ┬ ┴ ┼ ╭ ╮ ╰ ╯`
301
+
302
+ **Block Elements:** `░ ▒ ▓ █ ▄ ▀ ▌ ▐ ▖ ▗ ▘ ▝ ▚ ▞`
303
+
304
+ **Geometric & Symbols:** `◆ ◇ ◈ ● ○ ◉ ■ □ ▲ △ ▼ ▽ ★ ☆ ✦ ✧ ◀ ▶ ◁ ▷ ⬡ ⬢ ⌂`
305
+
306
+ ### Rules
307
+
308
+ - Max width: 60 characters per line (terminal-safe)
309
+ - Max height: 15 lines for banners, 25 for scenes
310
+ - Monospace only: output must render correctly in fixed-width fonts
311
+
312
+ ## Decision Flow
313
+
314
+ 1. **Text as a banner** → pyfiglet if installed, otherwise asciified API via curl
315
+ 2. **Wrap a message in fun character art** → cowsay
316
+ 3. **Add decorative border/frame** → boxes (can combine with pyfiglet/asciified)
317
+ 4. **Art of a specific thing** (cat, rocket, dragon) → ascii.co.uk via curl + parsing
318
+ 5. **Convert an image to ASCII** → ascii-image-converter or jp2a
319
+ 6. **QR code** → qrenco.de via curl
320
+ 7. **Weather/moon art** → wttr.in via curl
321
+ 8. **Something custom/creative** → LLM generation with Unicode palette
322
+ 9. **Any tool not installed** → install it, or fall back to next option
skills/.archive/ascii-video/README.md ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ☤ ASCII Video
2
+
3
+ Renders any content as colored ASCII character video. Audio, video, images, text, or pure math in, MP4/GIF/PNG sequence out. Full RGB color per character cell, 1080p 24fps default. No GPU.
4
+
5
+ Built for [Hermes Agent](https://github.com/NousResearch/hermes-agent). Usable in any coding agent. Canonical source lives here; synced to [`NousResearch/hermes-agent/skills/creative/ascii-video`](https://github.com/NousResearch/hermes-agent/tree/main/skills/creative/ascii-video) via PR.
6
+
7
+ ## What this is
8
+
9
+ A skill that teaches an agent how to build single-file Python renderers for ASCII video from scratch. The agent gets the full pipeline: grid system, font rasterization, effect library, shader chain, audio analysis, parallel encoding. It writes the renderer, runs it, gets video.
10
+
11
+ The output is actual video. Not terminal escape codes. Frames are computed as grids of colored characters, composited onto pixel canvases with pre-rasterized font bitmaps, post-processed through shaders, piped to ffmpeg.
12
+
13
+ ## Modes
14
+
15
+ | Mode | Input | Output |
16
+ |------|-------|--------|
17
+ | Video-to-ASCII | A video file | ASCII recreation of the footage |
18
+ | Audio-reactive | An audio file | Visuals driven by frequency bands, beats, energy |
19
+ | Generative | Nothing | Procedural animation from math |
20
+ | Hybrid | Video + audio | ASCII video with audio-reactive overlays |
21
+ | Lyrics/text | Audio + timed text (SRT) | Karaoke-style text with effects |
22
+ | TTS narration | Text quotes + API key | Narrated video with typewriter text and generated speech |
23
+
24
+ ## Pipeline
25
+
26
+ Every mode follows the same 6-stage path:
27
+
28
+ ```
29
+ INPUT --> ANALYZE --> SCENE_FN --> TONEMAP --> SHADE --> ENCODE
30
+ ```
31
+
32
+ 1. **Input** loads source material (or nothing for generative).
33
+ 2. **Analyze** extracts per-frame features. Audio gets 6-band FFT, RMS, spectral centroid, flatness, flux, beat detection with exponential decay. Video gets luminance, edges, motion.
34
+ 3. **Scene function** returns a pixel canvas directly. Composes multiple character grids at different densities, value/hue fields, pixel blend modes. This is where the visuals happen.
35
+ 4. **Tonemap** does adaptive percentile-based brightness normalization with per-scene gamma. ASCII on black is inherently dark. Linear multipliers don't work. This does.
36
+ 5. **Shade** runs a `ShaderChain` (38 composable shaders) plus a `FeedbackBuffer` for temporal recursion with spatial transforms.
37
+ 6. **Encode** pipes raw RGB frames to ffmpeg for H.264 encoding. Segments concatenated, audio muxed.
38
+
39
+ ## Grid system
40
+
41
+ Characters render on fixed-size grids. Layer multiple densities for depth.
42
+
43
+ | Size | Font | Grid at 1080p | Use |
44
+ |------|------|---------------|-----|
45
+ | xs | 8px | 400x108 | Ultra-dense data fields |
46
+ | sm | 10px | 320x83 | Rain, starfields |
47
+ | md | 16px | 192x56 | Default balanced |
48
+ | lg | 20px | 160x45 | Readable text |
49
+ | xl | 24px | 137x37 | Large titles |
50
+ | xxl | 40px | 80x22 | Giant minimal |
51
+
52
+ Rendering the same scene on `sm` and `lg` then screen-blending them creates natural texture interference. Fine detail shows through gaps in coarse characters. Most scenes use two or three grids.
53
+
54
+ ## Character palettes (24)
55
+
56
+ Each sorted dark-to-bright, each a different visual texture. Validated against the font at init so broken glyphs get dropped silently.
57
+
58
+ | Family | Examples | Feel |
59
+ |--------|----------|------|
60
+ | Density ramps | ` .:-=+#@█` | Classic ASCII art gradient |
61
+ | Block elements | ` ░▒▓█▄▀▐▌` | Chunky, digital |
62
+ | Braille | ` ⠁⠂⠃...⠿` | Fine-grained pointillism |
63
+ | Dots | ` ⋅∘∙●◉◎` | Smooth, organic |
64
+ | Stars | ` ·✧✦✩✨★✶` | Sparkle, celestial |
65
+ | Half-fills | ` ◔◑◕◐◒◓◖◗◙` | Directional fill progression |
66
+ | Crosshatch | ` ▣▤▥▦▧▨▩` | Hatched density ramp |
67
+ | Math | ` ·∘∙•°±×÷≈≠≡∞∫∑Ω` | Scientific, abstract |
68
+ | Box drawing | ` ─│┌┐└┘├┤┬┴┼` | Structural, circuit-like |
69
+ | Katakana | ` ·ヲァィゥェォャュ...` | Matrix rain |
70
+ | Greek | ` αβγδεζηθ...ω` | Classical, academic |
71
+ | Runes | ` ᚠᚢᚦᚱᚷᛁᛇᛒᛖᛚᛞᛟ` | Mystical, ancient |
72
+ | Alchemical | ` ☉☽♀♂♃♄♅♆♇` | Esoteric |
73
+ | Arrows | ` ←↑→↓↔↕↖↗↘↙` | Directional, kinetic |
74
+ | Music | ` ♪♫♬♩♭♮♯○●` | Musical |
75
+ | Project-specific | ` .·~=≈∞⚡☿✦★⊕◊◆▲▼●■` | Themed per project |
76
+
77
+ Custom palettes are built per project to match the content.
78
+
79
+ ## Color strategies
80
+
81
+ | Strategy | How it maps hue | Good for |
82
+ |----------|----------------|----------|
83
+ | Angle-mapped | Position angle from center | Rainbow radial effects |
84
+ | Distance-mapped | Distance from center | Depth, tunnels |
85
+ | Frequency-mapped | Audio spectral centroid | Timbral shifting |
86
+ | Value-mapped | Brightness level | Heat maps, fire |
87
+ | Time-cycled | Slow rotation over time | Ambient, chill |
88
+ | Source-sampled | Original video pixel colors | Video-to-ASCII |
89
+ | Palette-indexed | Discrete lookup table | Retro, flat graphic |
90
+ | Temperature | Warm-to-cool blend | Emotional tone |
91
+ | Complementary | Hue + opposite | Bold, dramatic |
92
+ | Triadic | Three equidistant hues | Psychedelic, vibrant |
93
+ | Analogous | Neighboring hues | Harmonious, subtle |
94
+ | Monochrome | Fixed hue, vary S/V | Noir, focused |
95
+
96
+ Plus 10 discrete RGB palettes (neon, pastel, cyberpunk, vaporwave, earth, ice, blood, forest, mono-green, mono-amber).
97
+
98
+ Full OKLAB/OKLCH color system: sRGB↔linear↔OKLAB conversion pipeline, perceptually uniform gradient interpolation, and color harmony generation (complementary, triadic, analogous, split-complementary, tetradic).
99
+
100
+ ## Value field generators (21)
101
+
102
+ Value fields are the core visual building blocks. Each produces a 2D float array in [0, 1] mapping every grid cell to a brightness value.
103
+
104
+ ### Trigonometric (12)
105
+
106
+ | Field | Description |
107
+ |-------|-------------|
108
+ | Sine field | Layered multi-sine interference, general-purpose background |
109
+ | Smooth noise | Multi-octave sine approximation of Perlin noise |
110
+ | Rings | Concentric rings, bass-driven count and wobble |
111
+ | Spiral | Logarithmic spiral arms, configurable arm count/tightness |
112
+ | Tunnel | Infinite depth perspective (inverse distance) |
113
+ | Vortex | Twisting radial pattern, distance modulates angle |
114
+ | Interference | N overlapping sine waves creating moire |
115
+ | Aurora | Horizontal flowing bands |
116
+ | Ripple | Concentric waves from configurable source points |
117
+ | Plasma | Sum of sines at multiple orientations/speeds |
118
+ | Diamond | Diamond/checkerboard pattern |
119
+ | Noise/static | Random per-cell per-frame flicker |
120
+
121
+ ### Noise-based (4)
122
+
123
+ | Field | Description |
124
+ |-------|-------------|
125
+ | Value noise | Smooth organic noise, no axis-alignment artifacts |
126
+ | fBM | Fractal Brownian Motion — octaved noise for clouds, terrain, smoke |
127
+ | Domain warp | Inigo Quilez technique — fBM-driven coordinate distortion for flowing organic forms |
128
+ | Voronoi | Moving seed points with distance, edge, and cell-ID output modes |
129
+
130
+ ### Simulation-based (4)
131
+
132
+ | Field | Description |
133
+ |-------|-------------|
134
+ | Reaction-diffusion | Gray-Scott with 7 presets: coral, spots, worms, labyrinths, mitosis, pulsating, chaos |
135
+ | Cellular automata | Game of Life + 4 rule variants with analog fade trails |
136
+ | Strange attractors | Clifford, De Jong, Bedhead — iterated point systems binned to density fields |
137
+ | Temporal noise | 3D noise that morphs in-place without directional drift |
138
+
139
+ ### SDF-based
140
+
141
+ 7 signed distance field primitives (circle, box, ring, line, triangle, star, heart) with smooth boolean combinators (union, intersection, subtraction, smooth union/subtraction) and infinite tiling. Render as solid fills or glowing outlines.
142
+
143
+ ## Hue field generators (9)
144
+
145
+ Determine per-cell color independent of brightness: fixed hue, angle-mapped rainbow, distance gradient, time-cycled rotation, audio spectral centroid, horizontal/vertical gradients, plasma variation, perceptually uniform OKLCH rainbow.
146
+
147
+ ## Coordinate transforms (11)
148
+
149
+ UV-space transforms applied before effect evaluation: rotate, scale, skew, tile (with mirror seaming), polar, inverse-polar, twist (rotation increasing with distance), fisheye, wave displacement, Möbius conformal transformation. `make_tgrid()` wraps transformed coordinates into a grid object.
150
+
151
+ ## Particle systems (9)
152
+
153
+ | Type | Behavior |
154
+ |------|----------|
155
+ | Explosion | Beat-triggered radial burst with gravity and life decay |
156
+ | Embers | Rising from bottom with horizontal drift |
157
+ | Dissolving cloud | Spreading outward with accelerating fade |
158
+ | Starfield | 3D projected, Z-depth stars approaching with streak trails |
159
+ | Orbit | Circular/elliptical paths around center |
160
+ | Gravity well | Attracted toward configurable point sources |
161
+ | Boid flocking | Separation/alignment/cohesion with spatial hash for O(n) neighbors |
162
+ | Flow-field | Steered by gradient of any value field |
163
+ | Trail particles | Fading lines between current and previous positions |
164
+
165
+ 14 themed particle character sets (energy, spark, leaf, snow, rain, bubble, data, hex, binary, rune, zodiac, dot, dash).
166
+
167
+ ## Temporal coherence
168
+
169
+ 10 easing functions (linear, quad, cubic, expo, elastic, bounce — in/out/in-out). Keyframe interpolation with eased transitions. Value field morphing (smooth crossfade between fields). Value field sequencing (cycle through fields with crossfade). Temporal noise (3D noise evolving smoothly in-place).
170
+
171
+ ## Shader pipeline
172
+
173
+ 38 composable shaders, applied to the pixel canvas after character rendering. Configurable per section.
174
+
175
+ | Category | Shaders |
176
+ |----------|---------|
177
+ | Geometry | CRT barrel, pixelate, wave distort, displacement map, kaleidoscope, mirror (h/v/quad/diag) |
178
+ | Channel | Chromatic aberration (beat-reactive), channel shift, channel swap, RGB split radial |
179
+ | Color | Invert, posterize, threshold, solarize, hue rotate, saturation, color grade, color wobble, color ramp |
180
+ | Glow/Blur | Bloom, edge glow, soft focus, radial blur |
181
+ | Noise | Film grain (beat-reactive), static noise |
182
+ | Lines/Patterns | Scanlines, halftone |
183
+ | Tone | Vignette, contrast, gamma, levels, brightness |
184
+ | Glitch/Data | Glitch bands (beat-reactive), block glitch, pixel sort, data bend |
185
+
186
+ 12 color tint presets: warm, cool, matrix green, amber, sepia, neon pink, ice, blood, forest, void, sunset, neutral.
187
+
188
+ 7 mood presets for common shader combos:
189
+
190
+ | Mood | Shaders |
191
+ |------|---------|
192
+ | Retro terminal | CRT + scanlines + grain + amber/green tint |
193
+ | Clean modern | Light bloom + subtle vignette |
194
+ | Glitch art | Heavy chromatic + glitch bands + color wobble |
195
+ | Cinematic | Bloom + vignette + grain + color grade |
196
+ | Dreamy | Heavy bloom + soft focus + color wobble |
197
+ | Harsh/industrial | High contrast + grain + scanlines, no bloom |
198
+ | Psychedelic | Color wobble + chromatic + kaleidoscope mirror |
199
+
200
+ ## Blend modes and composition
201
+
202
+ 20 pixel blend modes for layering canvases: normal, add, subtract, multiply, screen, overlay, softlight, hardlight, difference, exclusion, colordodge, colorburn, linearlight, vividlight, pin_light, hard_mix, lighten, darken, grain_extract, grain_merge. Both sRGB and linear-light blending supported.
203
+
204
+ **Feedback buffer.** Temporal recursion — each frame blends with a transformed version of the previous frame. 7 spatial transforms: zoom, shrink, rotate CW/CCW, shift up/down, mirror. Optional per-frame hue shift for rainbow trails. Configurable decay, blend mode, and opacity per scene.
205
+
206
+ **Masking.** 16 mask types for spatial compositing: shape masks (circle, rect, ring, gradients), procedural masks (any value field as a mask, text stencils), animated masks (iris open/close, wipe, dissolve), boolean operations (union, intersection, subtraction, invert).
207
+
208
+ **Transitions.** Crossfade, directional wipe, radial wipe, dissolve, glitch cut.
209
+
210
+ ## Scene design patterns
211
+
212
+ Compositional patterns for making scenes that look intentional rather than random.
213
+
214
+ **Layer hierarchy.** Background (dim atmosphere, dense grid), content (main visual, standard grid), accent (sparse highlights, coarse grid). Three distinct roles, not three competing layers.
215
+
216
+ **Directional parameter arcs.** The defining parameter of each scene ramps, accelerates, or builds over its duration. Progress-based formulas (linear, ease-out, step reveal) replace aimless `sin(t)` oscillation.
217
+
218
+ **Scene concepts.** Scenes built around visual metaphors (emergence, descent, collision, entropy) with motivated layer/palette/feedback choices. Not named after their effects.
219
+
220
+ **Compositional techniques.** Counter-rotating dual systems, wave collision, progressive fragmentation (voronoi cells multiplying over time), entropy (geometry consumed by reaction-diffusion), staggered layer entry (crescendo buildup).
221
+
222
+ ## Hardware adaptation
223
+
224
+ Auto-detects CPU count, RAM, platform, ffmpeg. Adapts worker count, resolution, FPS.
225
+
226
+ | Profile | Resolution | FPS | When |
227
+ |---------|-----------|-----|------|
228
+ | `draft` | 960x540 | 12 | Check timing/layout |
229
+ | `preview` | 1280x720 | 15 | Review effects |
230
+ | `production` | 1920x1080 | 24 | Final output |
231
+ | `max` | 3840x2160 | 30 | Ultra-high |
232
+ | `auto` | Detected | 24 | Adapts to hardware + duration |
233
+
234
+ `auto` estimates render time and downgrades if it would take over an hour. Low-memory systems drop to 720p automatically.
235
+
236
+ ### Render times (1080p 24fps, ~180ms/frame/worker)
237
+
238
+ | Duration | 4 workers | 8 workers | 16 workers |
239
+ |----------|-----------|-----------|------------|
240
+ | 30s | ~3 min | ~2 min | ~1 min |
241
+ | 2 min | ~13 min | ~7 min | ~4 min |
242
+ | 5 min | ~33 min | ~17 min | ~9 min |
243
+ | 10 min | ~65 min | ~33 min | ~17 min |
244
+
245
+ 720p roughly halves these. 4K roughly quadruples them.
246
+
247
+ ## Known pitfalls
248
+
249
+ **Brightness.** ASCII characters are small bright dots on black. Most frame pixels are background. Linear `* N` multipliers clip highlights and wash out. Use `tonemap()` with per-scene gamma instead. Default gamma 0.75, solarize scenes 0.55, posterize 0.50.
250
+
251
+ **Render bottleneck.** The per-cell Python loop compositing font bitmaps runs at ~100-150ms/frame. Unavoidable without Cython/C. Everything else must be vectorized numpy. Python for-loops over rows/cols in effect functions will tank performance.
252
+
253
+ **ffmpeg deadlock.** Never `stderr=subprocess.PIPE` on long-running encodes. Buffer fills at ~64KB, process hangs. Redirect stderr to a file.
254
+
255
+ **Font cell height.** Pillow's `textbbox()` returns wrong height on macOS. Use `font.getmetrics()` for `ascent + descent`.
256
+
257
+ **Font compatibility.** Not all Unicode renders in all fonts. Palettes validated at init, blank glyphs silently removed.
258
+
259
+ ## Requirements
260
+
261
+ ◆ Python 3.10+
262
+ ◆ NumPy, Pillow, SciPy (audio modes)
263
+ ◆ ffmpeg on PATH
264
+ ◆ A monospace font (Menlo, Courier, Monaco, auto-detected)
265
+ ◆ Optional: OpenCV, ElevenLabs API key (TTS mode)
266
+
267
+ ## File structure
268
+
269
+ ```
270
+ ├── SKILL.md # Modes, workflow, creative direction
271
+ ├── README.md # This file
272
+ └── references/
273
+ ├── architecture.md # Grid system, fonts, palettes, color, _render_vf()
274
+ ├── effects.md # Value fields, hue fields, backgrounds, particles
275
+ ├── shaders.md # 38 shaders, ShaderChain, tint presets, transitions
276
+ ├── composition.md # Blend modes, multi-grid, tonemap, FeedbackBuffer
277
+ ├── scenes.md # Scene protocol, SCENES table, render_clip(), examples
278
+ ├── design-patterns.md # Layer hierarchy, directional arcs, scene concepts
279
+ ├── inputs.md # Audio analysis, video sampling, text, TTS
280
+ ├── optimization.md # Hardware detection, vectorized patterns, parallelism
281
+ └── troubleshooting.md # Broadcasting traps, blend pitfalls, diagnostics
282
+ ```
283
+
284
+ ## Projects built with this
285
+
286
+ ✦ 85-second highlight reel. 15 scenes (14×5s + 15s crescendo finale), randomized order, directional parameter arcs, layer hierarchy composition. Showcases the full effect vocabulary: fBM, voronoi fragmentation, reaction-diffusion, cellular automata, dual counter-rotating spirals, wave collision, domain warping, tunnel descent, kaleidoscope symmetry, boid flocking, fire simulation, glitch corruption, and a 7-layer crescendo buildup.
287
+
288
+ ✦ Audio-reactive music visualizer. 3.5 min, 8 sections with distinct effects, beat-triggered particles and glitch, cycling palettes.
289
+
290
+ ✦ TTS narrated testimonial video. 23 quotes, per-quote ElevenLabs voices, background music at 15% wide stereo, per-clip re-rendering for iterative editing.
skills/.archive/ascii-video/SKILL.md ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: ascii-video
3
+ description: "ASCII video: convert video/audio to colored ASCII MP4/GIF."
4
+ platforms: [linux, macos, windows]
5
+ ---
6
+
7
+ # ASCII Video Production Pipeline
8
+
9
+ ## When to use
10
+
11
+ Use when users request: ASCII video, text art video, terminal-style video, character art animation, retro text visualization, audio visualizer in ASCII, converting video to ASCII art, matrix-style effects, or any animated ASCII output.
12
+
13
+ ## What's inside
14
+
15
+ Production pipeline for ASCII art video — any format. Converts video/audio/images/generative input into colored ASCII character video output (MP4, GIF, image sequence). Covers: video-to-ASCII conversion, audio-reactive music visualizers, generative ASCII art animations, hybrid video+audio reactive, text/lyrics overlays, real-time terminal rendering.
16
+
17
+ ## Creative Standard
18
+
19
+ This is visual art. ASCII characters are the medium; cinema is the standard.
20
+
21
+ **Before writing a single line of code**, articulate the creative concept. What is the mood? What visual story does this tell? What makes THIS project different from every other ASCII video? The user's prompt is a starting point — interpret it with creative ambition, not literal transcription.
22
+
23
+ **First-render excellence is non-negotiable.** The output must be visually striking without requiring revision rounds. If something looks generic, flat, or like "AI-generated ASCII art," it is wrong — rethink the creative concept before shipping.
24
+
25
+ **Go beyond the reference vocabulary.** The effect catalogs, shader presets, and palette libraries in the references are a starting vocabulary. For every project, combine, modify, and invent new patterns. The catalog is a palette of paints — you write the painting.
26
+
27
+ **Be proactively creative.** Extend the skill's vocabulary when the project calls for it. If the references don't have what the vision demands, build it. Include at least one visual moment the user didn't ask for but will appreciate — a transition, an effect, a color choice that elevates the whole piece.
28
+
29
+ **Cohesive aesthetic over technical correctness.** All scenes in a video must feel connected by a unifying visual language — shared color temperature, related character palettes, consistent motion vocabulary. A technically correct video where every scene uses a random different effect is an aesthetic failure.
30
+
31
+ **Dense, layered, considered.** Every frame should reward viewing. Never flat black backgrounds. Always multi-grid composition. Always per-scene variation. Always intentional color.
32
+
33
+ ## Modes
34
+
35
+ | Mode | Input | Output | Reference |
36
+ |------|-------|--------|-----------|
37
+ | **Video-to-ASCII** | Video file | ASCII recreation of source footage | `references/inputs.md` § Video Sampling |
38
+ | **Audio-reactive** | Audio file | Generative visuals driven by audio features | `references/inputs.md` § Audio Analysis |
39
+ | **Generative** | None (or seed params) | Procedural ASCII animation | `references/effects.md` |
40
+ | **Hybrid** | Video + audio | ASCII video with audio-reactive overlays | Both input refs |
41
+ | **Lyrics/text** | Audio + text/SRT | Timed text with visual effects | `references/inputs.md` § Text/Lyrics |
42
+ | **TTS narration** | Text quotes + TTS API | Narrated testimonial/quote video with typed text | `references/inputs.md` § TTS Integration |
43
+
44
+ ## Stack
45
+
46
+ Single self-contained Python script per project. No GPU required.
47
+
48
+ | Layer | Tool | Purpose |
49
+ |-------|------|---------|
50
+ | Core | Python 3.10+, NumPy | Math, array ops, vectorized effects |
51
+ | Signal | SciPy | FFT, peak detection (audio modes) |
52
+ | Imaging | Pillow (PIL) | Font rasterization, frame decoding, image I/O |
53
+ | Video I/O | ffmpeg (CLI) | Decode input, encode output, mux audio |
54
+ | Parallel | concurrent.futures | N workers for batch/clip rendering |
55
+ | TTS | ElevenLabs API (optional) | Generate narration clips |
56
+ | Optional | OpenCV | Video frame sampling, edge detection |
57
+
58
+ ## Pipeline Architecture
59
+
60
+ Every mode follows the same 6-stage pipeline:
61
+
62
+ ```
63
+ INPUT → ANALYZE → SCENE_FN → TONEMAP → SHADE → ENCODE
64
+ ```
65
+
66
+ 1. **INPUT** — Load/decode source material (video frames, audio samples, images, or nothing)
67
+ 2. **ANALYZE** — Extract per-frame features (audio bands, video luminance/edges, motion vectors)
68
+ 3. **SCENE_FN** — Scene function renders to pixel canvas (`uint8 H,W,3`). Composes multiple character grids via `_render_vf()` + pixel blend modes. See `references/composition.md`
69
+ 4. **TONEMAP** — Percentile-based adaptive brightness normalization. See `references/composition.md` § Adaptive Tonemap
70
+ 5. **SHADE** — Post-processing via `ShaderChain` + `FeedbackBuffer`. See `references/shaders.md`
71
+ 6. **ENCODE** — Pipe raw RGB frames to ffmpeg for H.264/GIF encoding
72
+
73
+ ## Creative Direction
74
+
75
+ ### Aesthetic Dimensions
76
+
77
+ | Dimension | Options | Reference |
78
+ |-----------|---------|-----------|
79
+ | **Character palette** | Density ramps, block elements, symbols, scripts (katakana, Greek, runes, braille), project-specific | `architecture.md` § Palettes |
80
+ | **Color strategy** | HSV, OKLAB/OKLCH, discrete RGB palettes, auto-generated harmony, monochrome, temperature | `architecture.md` § Color System |
81
+ | **Background texture** | Sine fields, fBM noise, domain warp, voronoi, reaction-diffusion, cellular automata, video | `effects.md` |
82
+ | **Primary effects** | Rings, spirals, tunnel, vortex, waves, interference, aurora, fire, SDFs, strange attractors | `effects.md` |
83
+ | **Particles** | Sparks, snow, rain, bubbles, runes, orbits, flocking boids, flow-field followers, trails | `effects.md` § Particles |
84
+ | **Shader mood** | Retro CRT, clean modern, glitch art, cinematic, dreamy, industrial, psychedelic | `shaders.md` |
85
+ | **Grid density** | xs(8px) through xxl(40px), mixed per layer | `architecture.md` § Grid System |
86
+ | **Coordinate space** | Cartesian, polar, tiled, rotated, fisheye, Möbius, domain-warped | `effects.md` § Transforms |
87
+ | **Feedback** | Zoom tunnel, rainbow trails, ghostly echo, rotating mandala, color evolution | `composition.md` § Feedback |
88
+ | **Masking** | Circle, ring, gradient, text stencil, animated iris/wipe/dissolve | `composition.md` § Masking |
89
+ | **Transitions** | Crossfade, wipe, dissolve, glitch cut, iris, mask-based reveal | `shaders.md` § Transitions |
90
+
91
+ ### Per-Section Variation
92
+
93
+ Never use the same config for the entire video. For each section/scene:
94
+ - **Different background effect** (or compose 2-3)
95
+ - **Different character palette** (match the mood)
96
+ - **Different color strategy** (or at minimum a different hue)
97
+ - **Vary shader intensity** (more bloom during peaks, more grain during quiet)
98
+ - **Different particle types** if particles are active
99
+
100
+ ### Project-Specific Invention
101
+
102
+ For every project, invent at least one of:
103
+ - A custom character palette matching the theme
104
+ - A custom background effect (combine/modify existing building blocks)
105
+ - A custom color palette (discrete RGB set matching the brand/mood)
106
+ - A custom particle character set
107
+ - A novel scene transition or visual moment
108
+
109
+ Don't just pick from the catalog. The catalog is vocabulary — you write the poem.
110
+
111
+ ## Workflow
112
+
113
+ ### Step 1: Creative Vision
114
+
115
+ Before any code, articulate the creative concept:
116
+
117
+ - **Mood/atmosphere**: What should the viewer feel? Energetic, meditative, chaotic, elegant, ominous?
118
+ - **Visual story**: What happens over the duration? Build tension? Transform? Dissolve?
119
+ - **Color world**: Warm/cool? Monochrome? Neon? Earth tones? What's the dominant hue?
120
+ - **Character texture**: Dense data? Sparse stars? Organic dots? Geometric blocks?
121
+ - **What makes THIS different**: What's the one thing that makes this project unique?
122
+ - **Emotional arc**: How do scenes progress? Open with energy, build to climax, resolve?
123
+
124
+ Map the user's prompt to aesthetic choices. A "chill lo-fi visualizer" demands different everything from a "glitch cyberpunk data stream."
125
+
126
+ ### Step 2: Technical Design
127
+
128
+ - **Mode** — which of the 6 modes above
129
+ - **Resolution** — landscape 1920x1080 (default), portrait 1080x1920, square 1080x1080 @ 24fps
130
+ - **Hardware detection** — auto-detect cores/RAM, set quality profile. See `references/optimization.md`
131
+ - **Sections** — map timestamps to scene functions, each with its own effect/palette/color/shader config
132
+ - **Output format** — MP4 (default), GIF (640x360 @ 15fps), PNG sequence
133
+
134
+ ### Step 3: Build the Script
135
+
136
+ Single Python file. Components (with references):
137
+
138
+ 1. **Hardware detection + quality profile** — `references/optimization.md`
139
+ 2. **Input loader** — mode-dependent; `references/inputs.md`
140
+ 3. **Feature analyzer** — audio FFT, video luminance, or synthetic
141
+ 4. **Grid + renderer** — multi-density grids with bitmap cache; `references/architecture.md`
142
+ 5. **Character palettes** — multiple per project; `references/architecture.md` § Palettes
143
+ 6. **Color system** — HSV + discrete RGB + harmony generation; `references/architecture.md` § Color
144
+ 7. **Scene functions** — each returns `canvas (uint8 H,W,3)`; `references/scenes.md`
145
+ 8. **Tonemap** — adaptive brightness normalization; `references/composition.md`
146
+ 9. **Shader pipeline** — `ShaderChain` + `FeedbackBuffer`; `references/shaders.md`
147
+ 10. **Scene table + dispatcher** — time → scene function + config; `references/scenes.md`
148
+ 11. **Parallel encoder** — N-worker clip rendering with ffmpeg pipes
149
+ 12. **Main** — orchestrate full pipeline
150
+
151
+ ### Step 4: Quality Verification
152
+
153
+ - **Test frames first**: render single frames at key timestamps before full render
154
+ - **Brightness check**: `canvas.mean() > 8` for all ASCII content. If dark, lower gamma
155
+ - **Visual coherence**: do all scenes feel like they belong to the same video?
156
+ - **Creative vision check**: does the output match the concept from Step 1? If it looks generic, go back
157
+
158
+ ## Critical Implementation Notes
159
+
160
+ ### Brightness — Use `tonemap()`, Not Linear Multipliers
161
+
162
+ This is the #1 visual issue. ASCII on black is inherently dark. **Never use `canvas * N` multipliers** — they clip highlights. Use adaptive tonemap:
163
+
164
+ ```python
165
+ def tonemap(canvas, gamma=0.75):
166
+ f = canvas.astype(np.float32)
167
+ lo, hi = np.percentile(f[::4, ::4], [1, 99.5])
168
+ if hi - lo < 10: hi = lo + 10
169
+ f = np.clip((f - lo) / (hi - lo), 0, 1) ** gamma
170
+ return (f * 255).astype(np.uint8)
171
+ ```
172
+
173
+ Pipeline: `scene_fn() → tonemap() → FeedbackBuffer → ShaderChain → ffmpeg`
174
+
175
+ Per-scene gamma: default 0.75, solarize 0.55, posterize 0.50, bright scenes 0.85. Use `screen` blend (not `overlay`) for dark layers.
176
+
177
+ ### Font Cell Height
178
+
179
+ macOS Pillow: `textbbox()` returns wrong height. Use `font.getmetrics()`: `cell_height = ascent + descent`. See `references/troubleshooting.md`.
180
+
181
+ ### ffmpeg Pipe Deadlock
182
+
183
+ Never `stderr=subprocess.PIPE` with long-running ffmpeg — buffer fills at 64KB and deadlocks. Redirect to file. See `references/troubleshooting.md`.
184
+
185
+ ### Font Compatibility
186
+
187
+ Not all Unicode chars render in all fonts. Validate palettes at init — render each char, check for blank output. See `references/troubleshooting.md`.
188
+
189
+ ### Per-Clip Architecture
190
+
191
+ For segmented videos (quotes, scenes, chapters), render each as a separate clip file for parallel rendering and selective re-rendering. See `references/scenes.md`.
192
+
193
+ ## Performance Targets
194
+
195
+ | Component | Budget |
196
+ |-----------|--------|
197
+ | Feature extraction | 1-5ms |
198
+ | Effect function | 2-15ms |
199
+ | Character render | 80-150ms (bottleneck) |
200
+ | Shader pipeline | 5-25ms |
201
+ | **Total** | ~100-200ms/frame |
202
+
203
+ ## References
204
+
205
+ | File | Contents |
206
+ |------|----------|
207
+ | `references/architecture.md` | Grid system, resolution presets, font selection, character palettes (20+), color system (HSV + OKLAB + discrete RGB + harmony generation), `_render_vf()` helper, GridLayer class |
208
+ | `references/composition.md` | Pixel blend modes (20 modes), `blend_canvas()`, multi-grid composition, adaptive `tonemap()`, `FeedbackBuffer`, `PixelBlendStack`, masking/stencil system |
209
+ | `references/effects.md` | Effect building blocks: value field generators, hue fields, noise/fBM/domain warp, voronoi, reaction-diffusion, cellular automata, SDFs, strange attractors, particle systems, coordinate transforms, temporal coherence |
210
+ | `references/shaders.md` | `ShaderChain`, `_apply_shader_step()` dispatch, 38 shader catalog, audio-reactive scaling, transitions, tint presets, output format encoding, terminal rendering |
211
+ | `references/scenes.md` | Scene protocol, `Renderer` class, `SCENES` table, `render_clip()`, beat-synced cutting, parallel rendering, design patterns (layer hierarchy, directional arcs, visual metaphors, compositional techniques), complete scene examples at every complexity level, scene design checklist |
212
+ | `references/inputs.md` | Audio analysis (FFT, bands, beats), video sampling, image conversion, text/lyrics, TTS integration (ElevenLabs, voice assignment, audio mixing) |
213
+ | `references/optimization.md` | Hardware detection, quality profiles, vectorized patterns, parallel rendering, memory management, performance budgets |
214
+ | `references/troubleshooting.md` | NumPy broadcasting traps, blend mode pitfalls, multiprocessing/pickling, brightness diagnostics, ffmpeg issues, font problems, common mistakes |
215
+
216
+ ---
217
+
218
+ ## Creative Divergence (use only when user requests experimental/creative/unique output)
219
+
220
+ If the user asks for creative, experimental, surprising, or unconventional output, select the strategy that best fits and reason through its steps BEFORE generating code.
221
+
222
+ - **Forced Connections** — when the user wants cross-domain inspiration ("make it look organic," "industrial aesthetic")
223
+ - **Conceptual Blending** — when the user names two things to combine ("ocean meets music," "space + calligraphy")
224
+ - **Oblique Strategies** — when the user is maximally open ("surprise me," "something I've never seen")
225
+
226
+ ### Forced Connections
227
+ 1. Pick a domain unrelated to the visual goal (weather systems, microbiology, architecture, fluid dynamics, textile weaving)
228
+ 2. List its core visual/structural elements (erosion → gradual reveal; mitosis → splitting duplication; weaving → interlocking patterns)
229
+ 3. Map those elements onto ASCII characters and animation patterns
230
+ 4. Synthesize — what does "erosion" or "crystallization" look like in a character grid?
231
+
232
+ ### Conceptual Blending
233
+ 1. Name two distinct visual/conceptual spaces (e.g., ocean waves + sheet music)
234
+ 2. Map correspondences (crests = high notes, troughs = rests, foam = staccato)
235
+ 3. Blend selectively — keep the most interesting mappings, discard forced ones
236
+ 4. Develop emergent properties that exist only in the blend
237
+
238
+ ### Oblique Strategies
239
+ 1. Draw one: "Honor thy error as a hidden intention" / "Use an old idea" / "What would your closest friend do?" / "Emphasize the flaws" / "Turn it upside down" / "Only a part, not the whole" / "Reverse"
240
+ 2. Interpret the directive against the current ASCII animation challenge
241
+ 3. Apply the lateral insight to the visual design before writing code
skills/.archive/ascii-video/references/architecture.md ADDED
@@ -0,0 +1,802 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Architecture Reference
2
+
3
+ > **See also:** composition.md · effects.md · scenes.md · shaders.md · inputs.md · optimization.md · troubleshooting.md
4
+
5
+ ## Grid System
6
+
7
+ ### Resolution Presets
8
+
9
+ ```python
10
+ RESOLUTION_PRESETS = {
11
+ "landscape": (1920, 1080), # 16:9 — YouTube, default
12
+ "portrait": (1080, 1920), # 9:16 — TikTok, Reels, Stories
13
+ "square": (1080, 1080), # 1:1 — Instagram feed
14
+ "ultrawide": (2560, 1080), # 21:9 — cinematic
15
+ "landscape4k":(3840, 2160), # 16:9 — 4K
16
+ "portrait4k": (2160, 3840), # 9:16 — 4K portrait
17
+ }
18
+
19
+ def get_resolution(preset="landscape", custom=None):
20
+ """Returns (VW, VH) tuple."""
21
+ if custom:
22
+ return custom
23
+ return RESOLUTION_PRESETS.get(preset, RESOLUTION_PRESETS["landscape"])
24
+ ```
25
+
26
+ ### Multi-Density Grids
27
+
28
+ Pre-initialize multiple grid sizes. Switch per section for visual variety. Grid dimensions auto-compute from resolution:
29
+
30
+ **Landscape (1920x1080):**
31
+
32
+ | Key | Font Size | Grid (cols x rows) | Use |
33
+ |-----|-----------|-------------------|-----|
34
+ | xs | 8 | 400x108 | Ultra-dense data fields |
35
+ | sm | 10 | 320x83 | Dense detail, rain, starfields |
36
+ | md | 16 | 192x56 | Default balanced, transitions |
37
+ | lg | 20 | 160x45 | Quote/lyric text (readable at 1080p) |
38
+ | xl | 24 | 137x37 | Short quotes, large titles |
39
+ | xxl | 40 | 80x22 | Giant text, minimal |
40
+
41
+ **Portrait (1080x1920):**
42
+
43
+ | Key | Font Size | Grid (cols x rows) | Use |
44
+ |-----|-----------|-------------------|-----|
45
+ | xs | 8 | 225x192 | Ultra-dense, tall data columns |
46
+ | sm | 10 | 180x148 | Dense detail, vertical rain |
47
+ | md | 16 | 112x100 | Default balanced |
48
+ | lg | 20 | 90x80 | Readable text (~30 chars/line centered) |
49
+ | xl | 24 | 75x66 | Short quotes, stacked |
50
+ | xxl | 40 | 45x39 | Giant text, minimal |
51
+
52
+ **Square (1080x1080):**
53
+
54
+ | Key | Font Size | Grid (cols x rows) | Use |
55
+ |-----|-----------|-------------------|-----|
56
+ | sm | 10 | 180x83 | Dense detail |
57
+ | md | 16 | 112x56 | Default balanced |
58
+ | lg | 20 | 90x45 | Readable text |
59
+
60
+ **Key differences in portrait mode:**
61
+ - Fewer columns (90 at `lg` vs 160) — lines must be shorter or wrap
62
+ - Many more rows (80 at `lg` vs 45) — vertical stacking is natural
63
+ - Aspect ratio correction flips: `asp = cw / ch` still works but the visual emphasis is vertical
64
+ - Radial effects appear as tall ellipses unless corrected
65
+ - Vertical effects (rain, embers, fire columns) are naturally enhanced
66
+ - Horizontal effects (spectrum bars, waveforms) need rotation or compression
67
+
68
+ **Grid sizing for text in portrait**: Use `lg` (20px) for 2-3 word lines. Max comfortable line length is ~25-30 chars. For longer quotes, break aggressively into many short lines stacked vertically — portrait has vertical space to spare. `xl` (24px) works for single words or very short phrases.
69
+
70
+ Grid dimensions: `cols = VW // cell_width`, `rows = VH // cell_height`.
71
+
72
+ ### Font Selection
73
+
74
+ Don't hardcode a single font. Choose fonts to match the project's mood. Monospace fonts are required for grid alignment but vary widely in personality:
75
+
76
+ | Font | Personality | Platform |
77
+ |------|-------------|----------|
78
+ | Menlo | Clean, neutral, Apple-native | macOS |
79
+ | Monaco | Retro terminal, compact | macOS |
80
+ | Courier New | Classic typewriter, wide | Cross-platform |
81
+ | SF Mono | Modern, tight spacing | macOS |
82
+ | Consolas | Windows native, clean | Windows |
83
+ | JetBrains Mono | Developer, ligature-ready | Install |
84
+ | Fira Code | Geometric, modern | Install |
85
+ | IBM Plex Mono | Corporate, authoritative | Install |
86
+ | Source Code Pro | Adobe, balanced | Install |
87
+
88
+ **Font detection at init**: probe available fonts and fall back gracefully:
89
+
90
+ ```python
91
+ import platform
92
+
93
+ def find_font(preferences):
94
+ """Try fonts in order, return first that exists."""
95
+ for name, path in preferences:
96
+ if os.path.exists(path):
97
+ return path
98
+ raise FileNotFoundError(f"No monospace font found. Tried: {[p for _,p in preferences]}")
99
+
100
+ FONT_PREFS_MACOS = [
101
+ ("Menlo", "/System/Library/Fonts/Menlo.ttc"),
102
+ ("Monaco", "/System/Library/Fonts/Monaco.ttf"),
103
+ ("SF Mono", "/System/Library/Fonts/SFNSMono.ttf"),
104
+ ("Courier", "/System/Library/Fonts/Courier.ttc"),
105
+ ]
106
+ FONT_PREFS_LINUX = [
107
+ ("DejaVu Sans Mono", "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf"),
108
+ ("Liberation Mono", "/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf"),
109
+ ("Noto Sans Mono", "/usr/share/fonts/truetype/noto/NotoSansMono-Regular.ttf"),
110
+ ("Ubuntu Mono", "/usr/share/fonts/truetype/ubuntu/UbuntuMono-R.ttf"),
111
+ ]
112
+ FONT_PREFS_WINDOWS = [
113
+ ("Consolas", r"C:\Windows\Fonts\consola.ttf"),
114
+ ("Courier New", r"C:\Windows\Fonts\cour.ttf"),
115
+ ("Lucida Console", r"C:\Windows\Fonts\lucon.ttf"),
116
+ ("Cascadia Code", os.path.expandvars(r"%LOCALAPPDATA%\Microsoft\Windows\Fonts\CascadiaCode.ttf")),
117
+ ("Cascadia Mono", os.path.expandvars(r"%LOCALAPPDATA%\Microsoft\Windows\Fonts\CascadiaMono.ttf")),
118
+ ]
119
+
120
+ def _get_font_prefs():
121
+ s = platform.system()
122
+ if s == "Darwin":
123
+ return FONT_PREFS_MACOS
124
+ elif s == "Windows":
125
+ return FONT_PREFS_WINDOWS
126
+ return FONT_PREFS_LINUX
127
+
128
+ FONT_PREFS = _get_font_prefs()
129
+ ```
130
+
131
+ **Multi-font rendering**: use different fonts for different layers (e.g., monospace for background, a bolder variant for overlay text). Each GridLayer owns its own font:
132
+
133
+ ```python
134
+ grid_bg = GridLayer(find_font(FONT_PREFS), 16) # background
135
+ grid_text = GridLayer(find_font(BOLD_PREFS), 20) # readable text
136
+ ```
137
+
138
+ ### Collecting All Characters
139
+
140
+ Before initializing grids, gather all characters that need bitmap pre-rasterization:
141
+
142
+ ```python
143
+ all_chars = set()
144
+ for pal in [PAL_DEFAULT, PAL_DENSE, PAL_BLOCKS, PAL_RUNE, PAL_KATA,
145
+ PAL_GREEK, PAL_MATH, PAL_DOTS, PAL_BRAILLE, PAL_STARS,
146
+ PAL_HALFFILL, PAL_HATCH, PAL_BINARY, PAL_MUSIC, PAL_BOX,
147
+ PAL_CIRCUIT, PAL_ARROWS, PAL_HERMES]: # ... all palettes used in project
148
+ all_chars.update(pal)
149
+ # Add any overlay text characters
150
+ all_chars.update("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,-:;!?/|")
151
+ all_chars.discard(" ") # space is never rendered
152
+ ```
153
+
154
+ ### GridLayer Initialization
155
+
156
+ Each grid pre-computes coordinate arrays for vectorized effect math. The grid automatically adapts to any resolution (landscape, portrait, square):
157
+
158
+ ```python
159
+ class GridLayer:
160
+ def __init__(self, font_path, font_size, vw=None, vh=None):
161
+ """Initialize grid for any resolution.
162
+ vw, vh: video width/height in pixels. Defaults to global VW, VH."""
163
+ vw = vw or VW; vh = vh or VH
164
+ self.vw = vw; self.vh = vh
165
+
166
+ self.font = ImageFont.truetype(font_path, font_size)
167
+ asc, desc = self.font.getmetrics()
168
+ bbox = self.font.getbbox("M")
169
+ self.cw = bbox[2] - bbox[0] # character cell width
170
+ self.ch = asc + desc # CRITICAL: not textbbox height
171
+
172
+ self.cols = vw // self.cw
173
+ self.rows = vh // self.ch
174
+ self.ox = (vw - self.cols * self.cw) // 2 # centering
175
+ self.oy = (vh - self.rows * self.ch) // 2
176
+
177
+ # Aspect ratio metadata
178
+ self.aspect = vw / vh # >1 = landscape, <1 = portrait, 1 = square
179
+ self.is_portrait = vw < vh
180
+ self.is_landscape = vw > vh
181
+
182
+ # Index arrays
183
+ self.rr = np.arange(self.rows, dtype=np.float32)[:, None]
184
+ self.cc = np.arange(self.cols, dtype=np.float32)[None, :]
185
+
186
+ # Polar coordinates (aspect-corrected)
187
+ cx, cy = self.cols / 2.0, self.rows / 2.0
188
+ asp = self.cw / self.ch
189
+ self.dx = self.cc - cx
190
+ self.dy = (self.rr - cy) * asp
191
+ self.dist = np.sqrt(self.dx**2 + self.dy**2)
192
+ self.angle = np.arctan2(self.dy, self.dx)
193
+
194
+ # Normalized (0-1 range) -- for distance falloff
195
+ self.dx_n = (self.cc - cx) / max(self.cols, 1)
196
+ self.dy_n = (self.rr - cy) / max(self.rows, 1) * asp
197
+ self.dist_n = np.sqrt(self.dx_n**2 + self.dy_n**2)
198
+
199
+ # Pre-rasterize all characters to float32 bitmaps
200
+ self.bm = {}
201
+ for c in all_chars:
202
+ img = Image.new("L", (self.cw, self.ch), 0)
203
+ ImageDraw.Draw(img).text((0, 0), c, fill=255, font=self.font)
204
+ self.bm[c] = np.array(img, dtype=np.float32) / 255.0
205
+ ```
206
+
207
+ ### Character Render Loop
208
+
209
+ The bottleneck. Composites pre-rasterized bitmaps onto pixel canvas:
210
+
211
+ ```python
212
+ def render(self, chars, colors, canvas=None):
213
+ if canvas is None:
214
+ canvas = np.zeros((VH, VW, 3), dtype=np.uint8)
215
+ for row in range(self.rows):
216
+ y = self.oy + row * self.ch
217
+ if y + self.ch > VH: break
218
+ for col in range(self.cols):
219
+ c = chars[row, col]
220
+ if c == " ": continue
221
+ x = self.ox + col * self.cw
222
+ if x + self.cw > VW: break
223
+ a = self.bm[c] # float32 bitmap
224
+ canvas[y:y+self.ch, x:x+self.cw] = np.maximum(
225
+ canvas[y:y+self.ch, x:x+self.cw],
226
+ (a[:, :, None] * colors[row, col]).astype(np.uint8))
227
+ return canvas
228
+ ```
229
+
230
+ Use `np.maximum` for additive blending (brighter chars overwrite dimmer ones, never darken).
231
+
232
+ ### Multi-Layer Rendering
233
+
234
+ Render multiple grids onto the same canvas for depth:
235
+
236
+ ```python
237
+ canvas = np.zeros((VH, VW, 3), dtype=np.uint8)
238
+ canvas = grid_lg.render(bg_chars, bg_colors, canvas) # background layer
239
+ canvas = grid_md.render(main_chars, main_colors, canvas) # main layer
240
+ canvas = grid_sm.render(detail_chars, detail_colors, canvas) # detail overlay
241
+ ```
242
+
243
+ ---
244
+
245
+ ## Character Palettes
246
+
247
+ ### Design Principles
248
+
249
+ Character palettes are the primary visual texture of ASCII video. They control not just brightness mapping but the entire visual feel. Design palettes intentionally:
250
+
251
+ - **Visual weight**: characters sorted by the amount of ink/pixels they fill. Space is always index 0.
252
+ - **Coherence**: characters within a palette should belong to the same visual family.
253
+ - **Density curve**: the brightness-to-character mapping is nonlinear. Dense palettes (many chars) give smoother gradients; sparse palettes (5-8 chars) give posterized/graphic looks.
254
+ - **Rendering compatibility**: every character in the palette must exist in the font. Test at init and remove missing glyphs.
255
+
256
+ ### Palette Library
257
+
258
+ Organized by visual family. Mix and match per project -- don't default to PAL_DEFAULT for everything.
259
+
260
+ #### Density / Brightness Palettes
261
+ ```python
262
+ PAL_DEFAULT = " .`'-:;!><=+*^~?/|(){}[]#&$@%" # classic ASCII art
263
+ PAL_DENSE = " .:;+=xX$#@\u2588" # simple 11-level ramp
264
+ PAL_MINIMAL = " .:-=+#@" # 8-level, graphic
265
+ PAL_BINARY = " \u2588" # 2-level, extreme contrast
266
+ PAL_GRADIENT = " \u2591\u2592\u2593\u2588" # 4-level block gradient
267
+ ```
268
+
269
+ #### Unicode Block Elements
270
+ ```python
271
+ PAL_BLOCKS = " \u2591\u2592\u2593\u2588\u2584\u2580\u2590\u258c" # standard blocks
272
+ PAL_BLOCKS_EXT = " \u2596\u2597\u2598\u2599\u259a\u259b\u259c\u259d\u259e\u259f\u2591\u2592\u2593\u2588" # quadrant blocks (more detail)
273
+ PAL_SHADE = " \u2591\u2592\u2593\u2588\u2587\u2586\u2585\u2584\u2583\u2582\u2581" # vertical fill progression
274
+ ```
275
+
276
+ #### Symbolic / Thematic
277
+ ```python
278
+ PAL_MATH = " \u00b7\u2218\u2219\u2022\u00b0\u00b1\u2213\u00d7\u00f7\u2248\u2260\u2261\u2264\u2265\u221e\u222b\u2211\u220f\u221a\u2207\u2202\u2206\u03a9" # math symbols
279
+ PAL_BOX = " \u2500\u2502\u250c\u2510\u2514\u2518\u251c\u2524\u252c\u2534\u253c\u2550\u2551\u2554\u2557\u255a\u255d\u2560\u2563\u2566\u2569\u256c" # box drawing
280
+ PAL_CIRCUIT = " .\u00b7\u2500\u2502\u250c\u2510\u2514\u2518\u253c\u25cb\u25cf\u25a1\u25a0\u2206\u2207\u2261" # circuit board
281
+ PAL_RUNE = " .\u16a0\u16a2\u16a6\u16b1\u16b7\u16c1\u16c7\u16d2\u16d6\u16da\u16de\u16df" # elder futhark runes
282
+ PAL_ALCHEMIC = " \u2609\u263d\u2640\u2642\u2643\u2644\u2645\u2646\u2647\u2648\u2649\u264a\u264b" # planetary/alchemical symbols
283
+ PAL_ZODIAC = " \u2648\u2649\u264a\u264b\u264c\u264d\u264e\u264f\u2650\u2651\u2652\u2653" # zodiac
284
+ PAL_ARROWS = " \u2190\u2191\u2192\u2193\u2194\u2195\u2196\u2197\u2198\u2199\u21a9\u21aa\u21bb\u27a1" # directional arrows
285
+ PAL_MUSIC = " \u266a\u266b\u266c\u2669\u266d\u266e\u266f\u25cb\u25cf" # musical notation
286
+ ```
287
+
288
+ #### Script / Writing System
289
+ ```python
290
+ PAL_KATA = " \u00b7\uff66\uff67\uff68\uff69\uff6a\uff6b\uff6c\uff6d\uff6e\uff6f\uff70\uff71\uff72\uff73\uff74\uff75\uff76\uff77" # katakana halfwidth (matrix rain)
291
+ PAL_GREEK = " \u03b1\u03b2\u03b3\u03b4\u03b5\u03b6\u03b7\u03b8\u03b9\u03ba\u03bb\u03bc\u03bd\u03be\u03c0\u03c1\u03c3\u03c4\u03c6\u03c8\u03c9" # Greek lowercase
292
+ PAL_CYRILLIC = " \u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u043a\u043b\u043c\u043d\u043e\u043f\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448" # Cyrillic lowercase
293
+ PAL_ARABIC = " \u0627\u0628\u062a\u062b\u062c\u062d\u062e\u062f\u0630\u0631\u0632\u0633\u0634\u0635\u0636\u0637" # Arabic letters (isolated forms)
294
+ ```
295
+
296
+ #### Dot / Point Progressions
297
+ ```python
298
+ PAL_DOTS = " ⋅∘∙●◉◎◆✦★" # dot size progression
299
+ PAL_BRAILLE = " ⠁⠂⠃⠄⠅⠆⠇⠈⠉⠊⠋⠌⠍⠎⠏⠐⠑⠒⠓⠔⠕⠖⠗⠘⠙⠚⠛⠜⠝⠞⠟⠿" # braille patterns
300
+ PAL_STARS = " ·✧✦✩✨★✶✳✸" # star progression
301
+ PAL_HALFFILL = " ◔◑◕◐◒◓◖◗◙" # directional half-fill progression
302
+ PAL_HATCH = " ▣▤▥▦▧▨▩" # crosshatch density ramp
303
+ ```
304
+
305
+ #### Project-Specific (examples -- invent new ones per project)
306
+ ```python
307
+ PAL_HERMES = " .\u00b7~=\u2248\u221e\u26a1\u263f\u2726\u2605\u2295\u25ca\u25c6\u25b2\u25bc\u25cf\u25a0" # mythology/tech blend
308
+ PAL_OCEAN = " ~\u2248\u2248\u2248\u223c\u2307\u2248\u224b\u224c\u2248" # water/wave characters
309
+ PAL_ORGANIC = " .\u00b0\u2218\u2022\u25e6\u25c9\u2742\u273f\u2741\u2743" # growing/botanical
310
+ PAL_MACHINE = " _\u2500\u2502\u250c\u2510\u253c\u2261\u25a0\u2588\u2593\u2592\u2591" # mechanical/industrial
311
+ ```
312
+
313
+ ### Creating Custom Palettes
314
+
315
+ When designing for a project, build palettes from the content's theme:
316
+
317
+ 1. **Choose a visual family** (dots, blocks, symbols, script)
318
+ 2. **Sort by visual weight** -- render each char at target font size, count lit pixels, sort ascending
319
+ 3. **Test at target grid size** -- some chars collapse to blobs at small sizes
320
+ 4. **Validate in font** -- remove chars the font can't render:
321
+
322
+ ```python
323
+ def validate_palette(pal, font):
324
+ """Remove characters the font can't render."""
325
+ valid = []
326
+ for c in pal:
327
+ if c == " ":
328
+ valid.append(c)
329
+ continue
330
+ img = Image.new("L", (20, 20), 0)
331
+ ImageDraw.Draw(img).text((0, 0), c, fill=255, font=font)
332
+ if np.array(img).max() > 0: # char actually rendered something
333
+ valid.append(c)
334
+ return "".join(valid)
335
+ ```
336
+
337
+ ### Mapping Values to Characters
338
+
339
+ ```python
340
+ def val2char(v, mask, pal=PAL_DEFAULT):
341
+ """Map float array (0-1) to character array using palette."""
342
+ n = len(pal)
343
+ idx = np.clip((v * n).astype(int), 0, n - 1)
344
+ out = np.full(v.shape, " ", dtype="U1")
345
+ for i, ch in enumerate(pal):
346
+ out[mask & (idx == i)] = ch
347
+ return out
348
+ ```
349
+
350
+ **Nonlinear mapping** for different visual curves:
351
+
352
+ ```python
353
+ def val2char_gamma(v, mask, pal, gamma=1.0):
354
+ """Gamma-corrected palette mapping. gamma<1 = brighter, gamma>1 = darker."""
355
+ v_adj = np.power(np.clip(v, 0, 1), gamma)
356
+ return val2char(v_adj, mask, pal)
357
+
358
+ def val2char_step(v, mask, pal, thresholds):
359
+ """Custom threshold mapping. thresholds = list of float breakpoints."""
360
+ out = np.full(v.shape, pal[0], dtype="U1")
361
+ for i, thr in enumerate(thresholds):
362
+ out[mask & (v > thr)] = pal[min(i + 1, len(pal) - 1)]
363
+ return out
364
+ ```
365
+
366
+ ---
367
+
368
+ ## Color System
369
+
370
+ ### HSV->RGB (Vectorized)
371
+
372
+ All color computation in HSV for intuitive control, converted at render time:
373
+
374
+ ```python
375
+ def hsv2rgb(h, s, v):
376
+ """Vectorized HSV->RGB. h,s,v are numpy arrays. Returns (R,G,B) uint8 arrays."""
377
+ h = h % 1.0
378
+ c = v * s; x = c * (1 - np.abs((h*6) % 2 - 1)); m = v - c
379
+ # ... 6 sector assignment ...
380
+ return (np.clip((r+m)*255, 0, 255).astype(np.uint8),
381
+ np.clip((g+m)*255, 0, 255).astype(np.uint8),
382
+ np.clip((b+m)*255, 0, 255).astype(np.uint8))
383
+ ```
384
+
385
+ ### Color Mapping Strategies
386
+
387
+ Don't default to a single strategy. Choose based on the visual intent:
388
+
389
+ | Strategy | Hue source | Effect | Good for |
390
+ |----------|------------|--------|----------|
391
+ | Angle-mapped | `g.angle / (2*pi)` | Rainbow around center | Radial effects, kaleidoscopes |
392
+ | Distance-mapped | `g.dist_n * 0.3` | Gradient from center | Tunnels, depth effects |
393
+ | Frequency-mapped | `f["cent"] * 0.2` | Timbral color shifting | Audio-reactive |
394
+ | Value-mapped | `val * 0.15` | Brightness-dependent hue | Fire, heat maps |
395
+ | Time-cycled | `t * rate` | Slow color rotation | Ambient, chill |
396
+ | Source-sampled | Video frame pixel colors | Preserve original color | Video-to-ASCII |
397
+ | Palette-indexed | Discrete color lookup | Flat graphic style | Retro, pixel art |
398
+ | Temperature | Blend between warm/cool | Emotional tone | Mood-driven scenes |
399
+ | Complementary | `hue` and `hue + 0.5` | High contrast | Bold, dramatic |
400
+ | Triadic | `hue`, `hue + 0.33`, `hue + 0.66` | Vibrant, balanced | Psychedelic |
401
+ | Analogous | `hue +/- 0.08` | Harmonious, subtle | Elegant, cohesive |
402
+ | Monochrome | Fixed hue, vary S and V | Restrained, focused | Noir, minimal |
403
+
404
+ ### Color Palettes (Discrete RGB)
405
+
406
+ For non-HSV workflows -- direct RGB color sets for graphic/retro looks:
407
+
408
+ ```python
409
+ # Named color palettes -- use for flat/graphic styles or per-character coloring
410
+ COLORS_NEON = [(255,0,102), (0,255,153), (102,0,255), (255,255,0), (0,204,255)]
411
+ COLORS_PASTEL = [(255,179,186), (255,223,186), (255,255,186), (186,255,201), (186,225,255)]
412
+ COLORS_MONO_GREEN = [(0,40,0), (0,80,0), (0,140,0), (0,200,0), (0,255,0)]
413
+ COLORS_MONO_AMBER = [(40,20,0), (80,50,0), (140,90,0), (200,140,0), (255,191,0)]
414
+ COLORS_CYBERPUNK = [(255,0,60), (0,255,200), (180,0,255), (255,200,0)]
415
+ COLORS_VAPORWAVE = [(255,113,206), (1,205,254), (185,103,255), (5,255,161)]
416
+ COLORS_EARTH = [(86,58,26), (139,90,43), (189,154,91), (222,193,136), (245,230,193)]
417
+ COLORS_ICE = [(200,230,255), (150,200,240), (100,170,230), (60,130,210), (30,80,180)]
418
+ COLORS_BLOOD = [(80,0,0), (140,10,10), (200,20,20), (255,50,30), (255,100,80)]
419
+ COLORS_FOREST = [(10,30,10), (20,60,15), (30,100,20), (50,150,30), (80,200,50)]
420
+
421
+ def rgb_palette_map(val, mask, palette):
422
+ """Map float array (0-1) to RGB colors from a discrete palette."""
423
+ n = len(palette)
424
+ idx = np.clip((val * n).astype(int), 0, n - 1)
425
+ R = np.zeros(val.shape, dtype=np.uint8)
426
+ G = np.zeros(val.shape, dtype=np.uint8)
427
+ B = np.zeros(val.shape, dtype=np.uint8)
428
+ for i, (r, g, b) in enumerate(palette):
429
+ m = mask & (idx == i)
430
+ R[m] = r; G[m] = g; B[m] = b
431
+ return R, G, B
432
+ ```
433
+
434
+ ### OKLAB Color Space (Perceptually Uniform)
435
+
436
+ HSV hue is perceptually non-uniform: green occupies far more visual range than blue. OKLAB / OKLCH provide perceptually even color steps — hue increments of 0.1 look equally different regardless of starting hue. Use OKLAB for:
437
+ - Gradient interpolation (no unwanted intermediate hues)
438
+ - Color harmony generation (perceptually balanced palettes)
439
+ - Smooth color transitions over time
440
+
441
+ ```python
442
+ # --- sRGB <-> Linear sRGB ---
443
+
444
+ def srgb_to_linear(c):
445
+ """Convert sRGB [0,1] to linear light. c: float32 array."""
446
+ return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
447
+
448
+ def linear_to_srgb(c):
449
+ """Convert linear light to sRGB [0,1]."""
450
+ return np.where(c <= 0.0031308, c * 12.92, 1.055 * np.power(np.maximum(c, 0), 1/2.4) - 0.055)
451
+
452
+ # --- Linear sRGB <-> OKLAB ---
453
+
454
+ def linear_rgb_to_oklab(r, g, b):
455
+ """Linear sRGB to OKLAB. r,g,b: float32 arrays [0,1].
456
+ Returns (L, a, b) where L=[0,1], a,b=[-0.4, 0.4] approx."""
457
+ l_ = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b
458
+ m_ = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b
459
+ s_ = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b
460
+ l_c = np.cbrt(l_); m_c = np.cbrt(m_); s_c = np.cbrt(s_)
461
+ L = 0.2104542553 * l_c + 0.7936177850 * m_c - 0.0040720468 * s_c
462
+ a = 1.9779984951 * l_c - 2.4285922050 * m_c + 0.4505937099 * s_c
463
+ b_ = 0.0259040371 * l_c + 0.7827717662 * m_c - 0.8086757660 * s_c
464
+ return L, a, b_
465
+
466
+ def oklab_to_linear_rgb(L, a, b):
467
+ """OKLAB to linear sRGB. Returns (r, g, b) float32 arrays [0,1]."""
468
+ l_ = L + 0.3963377774 * a + 0.2158037573 * b
469
+ m_ = L - 0.1055613458 * a - 0.0638541728 * b
470
+ s_ = L - 0.0894841775 * a - 1.2914855480 * b
471
+ l_c = l_ ** 3; m_c = m_ ** 3; s_c = s_ ** 3
472
+ r = +4.0767416621 * l_c - 3.3077115913 * m_c + 0.2309699292 * s_c
473
+ g = -1.2684380046 * l_c + 2.6097574011 * m_c - 0.3413193965 * s_c
474
+ b_ = -0.0041960863 * l_c - 0.7034186147 * m_c + 1.7076147010 * s_c
475
+ return np.clip(r, 0, 1), np.clip(g, 0, 1), np.clip(b_, 0, 1)
476
+
477
+ # --- Convenience: sRGB uint8 <-> OKLAB ---
478
+
479
+ def rgb_to_oklab(R, G, B):
480
+ """sRGB uint8 arrays to OKLAB."""
481
+ r = srgb_to_linear(R.astype(np.float32) / 255.0)
482
+ g = srgb_to_linear(G.astype(np.float32) / 255.0)
483
+ b = srgb_to_linear(B.astype(np.float32) / 255.0)
484
+ return linear_rgb_to_oklab(r, g, b)
485
+
486
+ def oklab_to_rgb(L, a, b):
487
+ """OKLAB to sRGB uint8 arrays."""
488
+ r, g, b_ = oklab_to_linear_rgb(L, a, b)
489
+ R = np.clip(linear_to_srgb(r) * 255, 0, 255).astype(np.uint8)
490
+ G = np.clip(linear_to_srgb(g) * 255, 0, 255).astype(np.uint8)
491
+ B = np.clip(linear_to_srgb(b_) * 255, 0, 255).astype(np.uint8)
492
+ return R, G, B
493
+
494
+ # --- OKLCH (cylindrical form of OKLAB) ---
495
+
496
+ def oklab_to_oklch(L, a, b):
497
+ """OKLAB to OKLCH. Returns (L, C, H) where H is in [0, 1] (normalized)."""
498
+ C = np.sqrt(a**2 + b**2)
499
+ H = (np.arctan2(b, a) / (2 * np.pi)) % 1.0
500
+ return L, C, H
501
+
502
+ def oklch_to_oklab(L, C, H):
503
+ """OKLCH to OKLAB. H in [0, 1]."""
504
+ angle = H * 2 * np.pi
505
+ a = C * np.cos(angle)
506
+ b = C * np.sin(angle)
507
+ return L, a, b
508
+ ```
509
+
510
+ ### Gradient Interpolation (OKLAB vs HSV)
511
+
512
+ Interpolating colors through OKLAB avoids the hue detours that HSV produces:
513
+
514
+ ```python
515
+ def lerp_oklab(color_a, color_b, t_array):
516
+ """Interpolate between two sRGB colors through OKLAB.
517
+ color_a, color_b: (R, G, B) tuples 0-255
518
+ t_array: float32 array [0,1] — interpolation parameter per pixel.
519
+ Returns (R, G, B) uint8 arrays."""
520
+ La, aa, ba = rgb_to_oklab(
521
+ np.full_like(t_array, color_a[0], dtype=np.uint8),
522
+ np.full_like(t_array, color_a[1], dtype=np.uint8),
523
+ np.full_like(t_array, color_a[2], dtype=np.uint8))
524
+ Lb, ab, bb = rgb_to_oklab(
525
+ np.full_like(t_array, color_b[0], dtype=np.uint8),
526
+ np.full_like(t_array, color_b[1], dtype=np.uint8),
527
+ np.full_like(t_array, color_b[2], dtype=np.uint8))
528
+ L = La + (Lb - La) * t_array
529
+ a = aa + (ab - aa) * t_array
530
+ b = ba + (bb - ba) * t_array
531
+ return oklab_to_rgb(L, a, b)
532
+
533
+ def lerp_oklch(color_a, color_b, t_array, short_path=True):
534
+ """Interpolate through OKLCH (preserves chroma, smooth hue path).
535
+ short_path: take the shorter arc around the hue wheel."""
536
+ La, aa, ba = rgb_to_oklab(
537
+ np.full_like(t_array, color_a[0], dtype=np.uint8),
538
+ np.full_like(t_array, color_a[1], dtype=np.uint8),
539
+ np.full_like(t_array, color_a[2], dtype=np.uint8))
540
+ Lb, ab, bb = rgb_to_oklab(
541
+ np.full_like(t_array, color_b[0], dtype=np.uint8),
542
+ np.full_like(t_array, color_b[1], dtype=np.uint8),
543
+ np.full_like(t_array, color_b[2], dtype=np.uint8))
544
+ L1, C1, H1 = oklab_to_oklch(La, aa, ba)
545
+ L2, C2, H2 = oklab_to_oklch(Lb, ab, bb)
546
+ # Shortest hue path
547
+ if short_path:
548
+ dh = H2 - H1
549
+ dh = np.where(dh > 0.5, dh - 1.0, np.where(dh < -0.5, dh + 1.0, dh))
550
+ H = (H1 + dh * t_array) % 1.0
551
+ else:
552
+ H = H1 + (H2 - H1) * t_array
553
+ L = L1 + (L2 - L1) * t_array
554
+ C = C1 + (C2 - C1) * t_array
555
+ Lout, aout, bout = oklch_to_oklab(L, C, H)
556
+ return oklab_to_rgb(Lout, aout, bout)
557
+ ```
558
+
559
+ ### Color Harmony Generation
560
+
561
+ Auto-generate harmonious palettes from a seed color:
562
+
563
+ ```python
564
+ def harmony_complementary(seed_rgb):
565
+ """Two colors: seed + opposite hue."""
566
+ L, a, b = rgb_to_oklab(np.array([seed_rgb[0]]), np.array([seed_rgb[1]]), np.array([seed_rgb[2]]))
567
+ _, C, H = oklab_to_oklch(L, a, b)
568
+ return [seed_rgb, _oklch_to_srgb_tuple(L[0], C[0], (H[0] + 0.5) % 1.0)]
569
+
570
+ def harmony_triadic(seed_rgb):
571
+ """Three colors: seed + two at 120-degree offsets."""
572
+ L, a, b = rgb_to_oklab(np.array([seed_rgb[0]]), np.array([seed_rgb[1]]), np.array([seed_rgb[2]]))
573
+ _, C, H = oklab_to_oklch(L, a, b)
574
+ return [seed_rgb,
575
+ _oklch_to_srgb_tuple(L[0], C[0], (H[0] + 0.333) % 1.0),
576
+ _oklch_to_srgb_tuple(L[0], C[0], (H[0] + 0.667) % 1.0)]
577
+
578
+ def harmony_analogous(seed_rgb, spread=0.08, n=5):
579
+ """N colors spread evenly around seed hue."""
580
+ L, a, b = rgb_to_oklab(np.array([seed_rgb[0]]), np.array([seed_rgb[1]]), np.array([seed_rgb[2]]))
581
+ _, C, H = oklab_to_oklch(L, a, b)
582
+ offsets = np.linspace(-spread * (n-1)/2, spread * (n-1)/2, n)
583
+ return [_oklch_to_srgb_tuple(L[0], C[0], (H[0] + off) % 1.0) for off in offsets]
584
+
585
+ def harmony_split_complementary(seed_rgb, split=0.08):
586
+ """Three colors: seed + two flanking the complement."""
587
+ L, a, b = rgb_to_oklab(np.array([seed_rgb[0]]), np.array([seed_rgb[1]]), np.array([seed_rgb[2]]))
588
+ _, C, H = oklab_to_oklch(L, a, b)
589
+ comp = (H[0] + 0.5) % 1.0
590
+ return [seed_rgb,
591
+ _oklch_to_srgb_tuple(L[0], C[0], (comp - split) % 1.0),
592
+ _oklch_to_srgb_tuple(L[0], C[0], (comp + split) % 1.0)]
593
+
594
+ def harmony_tetradic(seed_rgb):
595
+ """Four colors: two complementary pairs at 90-degree offset."""
596
+ L, a, b = rgb_to_oklab(np.array([seed_rgb[0]]), np.array([seed_rgb[1]]), np.array([seed_rgb[2]]))
597
+ _, C, H = oklab_to_oklch(L, a, b)
598
+ return [seed_rgb,
599
+ _oklch_to_srgb_tuple(L[0], C[0], (H[0] + 0.25) % 1.0),
600
+ _oklch_to_srgb_tuple(L[0], C[0], (H[0] + 0.5) % 1.0),
601
+ _oklch_to_srgb_tuple(L[0], C[0], (H[0] + 0.75) % 1.0)]
602
+
603
+ def _oklch_to_srgb_tuple(L, C, H):
604
+ """Helper: single OKLCH -> sRGB (R,G,B) int tuple."""
605
+ La = np.array([L]); Ca = np.array([C]); Ha = np.array([H])
606
+ Lo, ao, bo = oklch_to_oklab(La, Ca, Ha)
607
+ R, G, B = oklab_to_rgb(Lo, ao, bo)
608
+ return (int(R[0]), int(G[0]), int(B[0]))
609
+ ```
610
+
611
+ ### OKLAB Hue Fields
612
+
613
+ Drop-in replacements for `hf_*` generators that produce perceptually uniform hue variation:
614
+
615
+ ```python
616
+ def hf_oklch_angle(offset=0.0, chroma=0.12, lightness=0.7):
617
+ """OKLCH hue mapped to angle from center. Perceptually uniform rainbow.
618
+ Returns (R, G, B) uint8 color array instead of a float hue.
619
+ NOTE: Use with _render_vf_rgb() variant, not standard _render_vf()."""
620
+ def fn(g, f, t, S):
621
+ H = (g.angle / (2 * np.pi) + offset + t * 0.05) % 1.0
622
+ L = np.full_like(H, lightness)
623
+ C = np.full_like(H, chroma)
624
+ Lo, ao, bo = oklch_to_oklab(L, C, H)
625
+ R, G, B = oklab_to_rgb(Lo, ao, bo)
626
+ return mkc(R, G, B, g.rows, g.cols)
627
+ return fn
628
+ ```
629
+
630
+ ### Compositing Helpers
631
+
632
+ ```python
633
+ def mkc(R, G, B, rows, cols):
634
+ """Pack 3 uint8 arrays into (rows, cols, 3) color array."""
635
+ o = np.zeros((rows, cols, 3), dtype=np.uint8)
636
+ o[:,:,0] = R; o[:,:,1] = G; o[:,:,2] = B
637
+ return o
638
+
639
+ def layer_over(base_ch, base_co, top_ch, top_co):
640
+ """Composite top layer onto base. Non-space chars overwrite."""
641
+ m = top_ch != " "
642
+ base_ch[m] = top_ch[m]; base_co[m] = top_co[m]
643
+ return base_ch, base_co
644
+
645
+ def layer_blend(base_co, top_co, alpha):
646
+ """Alpha-blend top color layer onto base. alpha is float array (0-1) or scalar."""
647
+ if isinstance(alpha, (int, float)):
648
+ alpha = np.full(base_co.shape[:2], alpha, dtype=np.float32)
649
+ a = alpha[:,:,None]
650
+ return np.clip(base_co * (1 - a) + top_co * a, 0, 255).astype(np.uint8)
651
+
652
+ def stamp(ch, co, text, row, col, color=(255,255,255)):
653
+ """Write text string at position."""
654
+ for i, c in enumerate(text):
655
+ cc = col + i
656
+ if 0 <= row < ch.shape[0] and 0 <= cc < ch.shape[1]:
657
+ ch[row, cc] = c; co[row, cc] = color
658
+ ```
659
+
660
+ ---
661
+
662
+ ## Section System
663
+
664
+ Map time ranges to effect functions + shader configs + grid sizes:
665
+
666
+ ```python
667
+ SECTIONS = [
668
+ (0.0, "void"), (3.94, "starfield"), (21.0, "matrix"),
669
+ (46.0, "drop"), (130.0, "glitch"), (187.0, "outro"),
670
+ ]
671
+
672
+ FX_DISPATCH = {"void": fx_void, "starfield": fx_starfield, ...}
673
+ SECTION_FX = {"void": {"vignette": 0.3, "bloom": 170}, ...}
674
+ SECTION_GRID = {"void": "md", "starfield": "sm", "drop": "lg", ...}
675
+ SECTION_MIRROR = {"drop": "h", "bass_rings": "quad"}
676
+
677
+ def get_section(t):
678
+ sec = SECTIONS[0][1]
679
+ for ts, name in SECTIONS:
680
+ if t >= ts: sec = name
681
+ return sec
682
+ ```
683
+
684
+ ---
685
+
686
+ ## Parallel Encoding
687
+
688
+ Split frames across N workers. Each pipes raw RGB to its own ffmpeg subprocess:
689
+
690
+ ```python
691
+ def render_batch(batch_id, frame_start, frame_end, features, seg_path):
692
+ r = Renderer()
693
+ cmd = ["ffmpeg", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24",
694
+ "-s", f"{VW}x{VH}", "-r", str(FPS), "-i", "pipe:0",
695
+ "-c:v", "libx264", "-preset", "fast", "-crf", "18",
696
+ "-pix_fmt", "yuv420p", seg_path]
697
+
698
+ # CRITICAL: stderr to file, not pipe
699
+ stderr_fh = open(os.path.join(workdir, f"err_{batch_id:02d}.log"), "w")
700
+ pipe = subprocess.Popen(cmd, stdin=subprocess.PIPE,
701
+ stdout=subprocess.DEVNULL, stderr=stderr_fh)
702
+
703
+ for fi in range(frame_start, frame_end):
704
+ t = fi / FPS
705
+ sec = get_section(t)
706
+ f = {k: float(features[k][fi]) for k in features}
707
+ ch, co = FX_DISPATCH[sec](r, f, t)
708
+ canvas = r.render(ch, co)
709
+ canvas = apply_mirror(canvas, sec, f)
710
+ canvas = apply_shaders(canvas, sec, f, t)
711
+ pipe.stdin.write(canvas.tobytes())
712
+
713
+ pipe.stdin.close()
714
+ pipe.wait()
715
+ stderr_fh.close()
716
+ ```
717
+
718
+ Concatenate segments + mux audio:
719
+
720
+ ```python
721
+ # Write concat file
722
+ with open(concat_path, "w") as cf:
723
+ for seg in segments:
724
+ cf.write(f"file '{seg}'\n")
725
+
726
+ subprocess.run(["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", concat_path,
727
+ "-i", audio_path, "-c:v", "copy", "-c:a", "aac", "-b:a", "192k",
728
+ "-shortest", output_path])
729
+ ```
730
+
731
+ ## Effect Function Contract
732
+
733
+ ### v2 Protocol (Current)
734
+
735
+ Every scene function: `(r, f, t, S) -> canvas_uint8` — where `r` = Renderer, `f` = features dict, `t` = time float, `S` = persistent state dict
736
+
737
+ ```python
738
+ def fx_example(r, f, t, S):
739
+ """Scene function returns a full pixel canvas (uint8 H,W,3).
740
+ Scenes have full control over multi-grid rendering and pixel-level composition.
741
+ """
742
+ # Render multiple layers at different grid densities
743
+ canvas_a = _render_vf(r, "md", vf_plasma, hf_angle(0.0), PAL_DENSE, f, t, S)
744
+ canvas_b = _render_vf(r, "sm", vf_vortex, hf_time_cycle(0.1), PAL_RUNE, f, t, S)
745
+
746
+ # Pixel-level blend
747
+ result = blend_canvas(canvas_a, canvas_b, "screen", 0.8)
748
+ return result
749
+ ```
750
+
751
+ See `references/scenes.md` for the full scene protocol, the Renderer class, `_render_vf()` helper, and complete scene examples.
752
+
753
+ See `references/composition.md` for blend modes, tone mapping, feedback buffers, and multi-grid composition.
754
+
755
+ ### v1 Protocol (Legacy)
756
+
757
+ Simple scenes that use a single grid can still return `(chars, colors)` and let the caller handle rendering, but the v2 canvas protocol is preferred for all new code.
758
+
759
+ ```python
760
+ def fx_simple(r, f, t, S):
761
+ g = r.get_grid("md")
762
+ val = np.sin(g.dist * 0.1 - t * 3) * f.get("bass", 0.3) * 2
763
+ val = np.clip(val, 0, 1); mask = val > 0.03
764
+ ch = val2char(val, mask, PAL_DEFAULT)
765
+ R, G, B = hsv2rgb(np.full_like(val, 0.6), np.full_like(val, 0.7), val)
766
+ co = mkc(R, G, B, g.rows, g.cols)
767
+ return g.render(ch, co) # returns canvas directly
768
+ ```
769
+
770
+ ### Persistent State
771
+
772
+ Effects that need state across frames (particles, rain columns) use the `S` dict parameter (which is `r.S` — same object, but passed explicitly for clarity):
773
+
774
+ ```python
775
+ def fx_with_state(r, f, t, S):
776
+ if "particles" not in S:
777
+ S["particles"] = initialize_particles()
778
+ update_particles(S["particles"])
779
+ # ...
780
+ ```
781
+
782
+ State persists across frames within a single scene/clip. Each worker process (and each scene) gets its own independent state.
783
+
784
+ ### Helper Functions
785
+
786
+ ```python
787
+ def hsv2rgb_scalar(h, s, v):
788
+ """Single-value HSV to RGB. Returns (R, G, B) tuple of ints 0-255."""
789
+ h = h % 1.0
790
+ c = v * s; x = c * (1 - abs((h * 6) % 2 - 1)); m = v - c
791
+ if h * 6 < 1: r, g, b = c, x, 0
792
+ elif h * 6 < 2: r, g, b = x, c, 0
793
+ elif h * 6 < 3: r, g, b = 0, c, x
794
+ elif h * 6 < 4: r, g, b = 0, x, c
795
+ elif h * 6 < 5: r, g, b = x, 0, c
796
+ else: r, g, b = c, 0, x
797
+ return (int((r+m)*255), int((g+m)*255), int((b+m)*255))
798
+
799
+ def log(msg):
800
+ """Print timestamped log message."""
801
+ print(msg, flush=True)
802
+ ```
skills/.archive/ascii-video/references/composition.md ADDED
@@ -0,0 +1,892 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Composition & Brightness Reference
2
+
3
+ The composable system is the core of visual complexity. It operates at three levels: pixel-level blend modes, multi-grid composition, and adaptive brightness management. This document covers all three, plus the masking/stencil system for spatial control.
4
+
5
+ > **See also:** architecture.md · effects.md · scenes.md · shaders.md · troubleshooting.md
6
+
7
+ ## Pixel-Level Blend Modes
8
+
9
+ ### The `blend_canvas()` Function
10
+
11
+ All blending operates on full pixel canvases (`uint8 H,W,3`). Internally converts to float32 [0,1] for precision, blends, lerps by opacity, converts back.
12
+
13
+ ```python
14
+ def blend_canvas(base, top, mode="normal", opacity=1.0):
15
+ af = base.astype(np.float32) / 255.0
16
+ bf = top.astype(np.float32) / 255.0
17
+ fn = BLEND_MODES.get(mode, BLEND_MODES["normal"])
18
+ result = fn(af, bf)
19
+ if opacity < 1.0:
20
+ result = af * (1 - opacity) + result * opacity
21
+ return np.clip(result * 255, 0, 255).astype(np.uint8)
22
+ ```
23
+
24
+ ### 20 Blend Modes
25
+
26
+ ```python
27
+ BLEND_MODES = {
28
+ # Basic arithmetic
29
+ "normal": lambda a, b: b,
30
+ "add": lambda a, b: np.clip(a + b, 0, 1),
31
+ "subtract": lambda a, b: np.clip(a - b, 0, 1),
32
+ "multiply": lambda a, b: a * b,
33
+ "screen": lambda a, b: 1 - (1 - a) * (1 - b),
34
+
35
+ # Contrast
36
+ "overlay": lambda a, b: np.where(a < 0.5, 2*a*b, 1 - 2*(1-a)*(1-b)),
37
+ "softlight": lambda a, b: (1 - 2*b)*a*a + 2*b*a,
38
+ "hardlight": lambda a, b: np.where(b < 0.5, 2*a*b, 1 - 2*(1-a)*(1-b)),
39
+
40
+ # Difference
41
+ "difference": lambda a, b: np.abs(a - b),
42
+ "exclusion": lambda a, b: a + b - 2*a*b,
43
+
44
+ # Dodge / burn
45
+ "colordodge": lambda a, b: np.clip(a / (1 - b + 1e-6), 0, 1),
46
+ "colorburn": lambda a, b: np.clip(1 - (1 - a) / (b + 1e-6), 0, 1),
47
+
48
+ # Light
49
+ "linearlight": lambda a, b: np.clip(a + 2*b - 1, 0, 1),
50
+ "vividlight": lambda a, b: np.where(b < 0.5,
51
+ np.clip(1 - (1-a)/(2*b + 1e-6), 0, 1),
52
+ np.clip(a / (2*(1-b) + 1e-6), 0, 1)),
53
+ "pin_light": lambda a, b: np.where(b < 0.5,
54
+ np.minimum(a, 2*b), np.maximum(a, 2*b - 1)),
55
+ "hard_mix": lambda a, b: np.where(a + b >= 1.0, 1.0, 0.0),
56
+
57
+ # Compare
58
+ "lighten": lambda a, b: np.maximum(a, b),
59
+ "darken": lambda a, b: np.minimum(a, b),
60
+
61
+ # Grain
62
+ "grain_extract": lambda a, b: np.clip(a - b + 0.5, 0, 1),
63
+ "grain_merge": lambda a, b: np.clip(a + b - 0.5, 0, 1),
64
+ }
65
+ ```
66
+
67
+ ### Blend Mode Selection Guide
68
+
69
+ **Modes that brighten** (safe for dark inputs):
70
+ - `screen` — always brightens. Two 50% gray layers screen to 75%. The go-to safe blend.
71
+ - `add` — simple addition, clips at white. Good for sparkles, glows, particle overlays.
72
+ - `colordodge` — extreme brightening at overlap zones. Can blow out. Use low opacity (0.3-0.5).
73
+ - `linearlight` — aggressive brightening. Similar to add but with offset.
74
+
75
+ **Modes that darken** (avoid with dark inputs):
76
+ - `multiply` — darkens everything. Only use when both layers are already bright.
77
+ - `overlay` — darkens when base < 0.5, brightens when base > 0.5. Crushes dark inputs: `2 * 0.12 * 0.12 = 0.03`. Use `screen` instead for dark material.
78
+ - `colorburn` — extreme darkening at overlap zones.
79
+
80
+ **Modes that create contrast**:
81
+ - `softlight` — gentle contrast. Good for subtle texture overlay.
82
+ - `hardlight` — strong contrast. Like overlay but keyed on the top layer.
83
+ - `vividlight` — very aggressive contrast. Use sparingly.
84
+
85
+ **Modes that create color effects**:
86
+ - `difference` — XOR-like patterns. Two identical layers difference to black; offset layers create wild colors. Great for psychedelic looks.
87
+ - `exclusion` — softer version of difference. Creates complementary color patterns.
88
+ - `hard_mix` — posterizes to pure black/white/saturated color at intersections.
89
+
90
+ **Modes for texture blending**:
91
+ - `grain_extract` / `grain_merge` — extract a texture from one layer, apply it to another.
92
+
93
+ ### Multi-Layer Chaining
94
+
95
+ ```python
96
+ # Pattern: render layers -> blend sequentially
97
+ canvas_a = _render_vf(r, "md", vf_plasma, hf_angle(0.0), PAL_DENSE, f, t, S)
98
+ canvas_b = _render_vf(r, "sm", vf_vortex, hf_time_cycle(0.1), PAL_RUNE, f, t, S)
99
+ canvas_c = _render_vf(r, "lg", vf_rings, hf_distance(), PAL_BLOCKS, f, t, S)
100
+
101
+ result = blend_canvas(canvas_a, canvas_b, "screen", 0.8)
102
+ result = blend_canvas(result, canvas_c, "difference", 0.6)
103
+ ```
104
+
105
+ Order matters: `screen(A, B)` is commutative, but `difference(screen(A,B), C)` differs from `difference(A, screen(B,C))`.
106
+
107
+ ### Linear-Light Blend Modes
108
+
109
+ Standard `blend_canvas()` operates in sRGB space — the raw byte values. This is fine for most uses, but sRGB is perceptually non-linear: blending in sRGB darkens midtones and shifts hues slightly. For physically accurate blending (matching how light actually combines), convert to linear light first.
110
+
111
+ Uses `srgb_to_linear()` / `linear_to_srgb()` from `architecture.md` § OKLAB Color System.
112
+
113
+ ```python
114
+ def blend_canvas_linear(base, top, mode="normal", opacity=1.0):
115
+ """Blend in linear light space for physically accurate results.
116
+
117
+ Identical API to blend_canvas(), but converts sRGB → linear before
118
+ blending and linear → sRGB after. More expensive (~2x) due to the
119
+ gamma conversions, but produces correct results for additive blending,
120
+ screen, and any mode where brightness matters.
121
+ """
122
+ af = srgb_to_linear(base.astype(np.float32) / 255.0)
123
+ bf = srgb_to_linear(top.astype(np.float32) / 255.0)
124
+ fn = BLEND_MODES.get(mode, BLEND_MODES["normal"])
125
+ result = fn(af, bf)
126
+ if opacity < 1.0:
127
+ result = af * (1 - opacity) + result * opacity
128
+ result = linear_to_srgb(np.clip(result, 0, 1))
129
+ return np.clip(result * 255, 0, 255).astype(np.uint8)
130
+ ```
131
+
132
+ **When to use `blend_canvas_linear()` vs `blend_canvas()`:**
133
+
134
+ | Scenario | Use | Why |
135
+ |----------|-----|-----|
136
+ | Screen-blending two bright layers | `linear` | sRGB screen over-brightens highlights |
137
+ | Add mode for glow/bloom effects | `linear` | Additive light follows linear physics |
138
+ | Blending text overlay at low opacity | `srgb` | Perceptual blending looks more natural for text |
139
+ | Multiply for shadow/darkening | `srgb` | Differences are minimal for darken ops |
140
+ | Color-critical work (matching reference) | `linear` | Avoids sRGB hue shifts in midtones |
141
+ | Performance-critical inner loop | `srgb` | ~2x faster, good enough for most ASCII art |
142
+
143
+ **Batch version** for compositing many layers (converts once, blends multiple, converts back):
144
+
145
+ ```python
146
+ def blend_many_linear(layers, modes, opacities):
147
+ """Blend a stack of layers in linear light space.
148
+
149
+ Args:
150
+ layers: list of uint8 (H,W,3) canvases
151
+ modes: list of blend mode strings (len = len(layers) - 1)
152
+ opacities: list of floats (len = len(layers) - 1)
153
+ Returns:
154
+ uint8 (H,W,3) canvas
155
+ """
156
+ # Convert all to linear at once
157
+ linear = [srgb_to_linear(l.astype(np.float32) / 255.0) for l in layers]
158
+ result = linear[0]
159
+ for i in range(1, len(linear)):
160
+ fn = BLEND_MODES.get(modes[i-1], BLEND_MODES["normal"])
161
+ blended = fn(result, linear[i])
162
+ op = opacities[i-1]
163
+ if op < 1.0:
164
+ blended = result * (1 - op) + blended * op
165
+ result = np.clip(blended, 0, 1)
166
+ result = linear_to_srgb(result)
167
+ return np.clip(result * 255, 0, 255).astype(np.uint8)
168
+ ```
169
+
170
+ ---
171
+
172
+ ## Multi-Grid Composition
173
+
174
+ This is the core visual technique. Rendering the same conceptual scene at different grid densities (character sizes) creates natural texture interference, because characters at different scales overlap at different spatial frequencies.
175
+
176
+ ### Why It Works
177
+
178
+ - `sm` grid (10pt font): 320x83 characters. Fine detail, dense texture.
179
+ - `md` grid (16pt): 192x56 characters. Medium density.
180
+ - `lg` grid (20pt): 160x45 characters. Coarse, chunky characters.
181
+
182
+ When you render a plasma field on `sm` and a vortex on `lg`, then screen-blend them, the fine plasma texture shows through the gaps in the coarse vortex characters. The result has more visual complexity than either layer alone.
183
+
184
+ ### The `_render_vf()` Helper
185
+
186
+ This is the workhorse function. It takes a value field + hue field + palette + grid, renders to a complete pixel canvas:
187
+
188
+ ```python
189
+ def _render_vf(r, grid_key, val_fn, hue_fn, pal, f, t, S, sat=0.8, threshold=0.03):
190
+ """Render a value field + hue field to a pixel canvas via a named grid.
191
+
192
+ Args:
193
+ r: Renderer instance (has .get_grid())
194
+ grid_key: "xs", "sm", "md", "lg", "xl", "xxl"
195
+ val_fn: (g, f, t, S) -> float32 [0,1] array (rows, cols)
196
+ hue_fn: callable (g, f, t, S) -> float32 hue array, OR float scalar
197
+ pal: character palette string
198
+ f: feature dict
199
+ t: time in seconds
200
+ S: persistent state dict
201
+ sat: HSV saturation (0-1)
202
+ threshold: minimum value to render (below = space)
203
+
204
+ Returns:
205
+ uint8 array (VH, VW, 3) — full pixel canvas
206
+ """
207
+ g = r.get_grid(grid_key)
208
+ val = np.clip(val_fn(g, f, t, S), 0, 1)
209
+ mask = val > threshold
210
+ ch = val2char(val, mask, pal)
211
+
212
+ # Hue: either a callable or a fixed float
213
+ if callable(hue_fn):
214
+ h = hue_fn(g, f, t, S) % 1.0
215
+ else:
216
+ h = np.full((g.rows, g.cols), float(hue_fn), dtype=np.float32)
217
+
218
+ # CRITICAL: broadcast to full shape and copy (see Troubleshooting)
219
+ h = np.broadcast_to(h, (g.rows, g.cols)).copy()
220
+
221
+ R, G, B = hsv2rgb(h, np.full_like(val, sat), val)
222
+ co = mkc(R, G, B, g.rows, g.cols)
223
+ return g.render(ch, co)
224
+ ```
225
+
226
+ ### Grid Combination Strategies
227
+
228
+ | Combination | Effect | Good For |
229
+ |-------------|--------|----------|
230
+ | `sm` + `lg` | Maximum contrast between fine detail and chunky blocks | Bold, graphic looks |
231
+ | `sm` + `md` | Subtle texture layering, similar scales | Organic, flowing looks |
232
+ | `md` + `lg` + `xs` | Three-scale interference, maximum complexity | Psychedelic, dense |
233
+ | `sm` + `sm` (different effects) | Same scale, pattern interference only | Moire, interference |
234
+
235
+ ### Complete Multi-Grid Scene Example
236
+
237
+ ```python
238
+ def fx_psychedelic(r, f, t, S):
239
+ """Three-layer multi-grid scene with beat-reactive kaleidoscope."""
240
+ # Layer A: plasma on medium grid with rainbow hue
241
+ canvas_a = _render_vf(r, "md",
242
+ lambda g, f, t, S: vf_plasma(g, f, t, S) * 1.3,
243
+ hf_angle(0.0), PAL_DENSE, f, t, S, sat=0.8)
244
+
245
+ # Layer B: vortex on small grid with cycling hue
246
+ canvas_b = _render_vf(r, "sm",
247
+ lambda g, f, t, S: vf_vortex(g, f, t, S, twist=5.0) * 1.2,
248
+ hf_time_cycle(0.1), PAL_RUNE, f, t, S, sat=0.7)
249
+
250
+ # Layer C: rings on large grid with distance hue
251
+ canvas_c = _render_vf(r, "lg",
252
+ lambda g, f, t, S: vf_rings(g, f, t, S, n_base=8, spacing_base=3) * 1.4,
253
+ hf_distance(0.3, 0.02), PAL_BLOCKS, f, t, S, sat=0.9)
254
+
255
+ # Blend: A screened with B, then difference with C
256
+ result = blend_canvas(canvas_a, canvas_b, "screen", 0.8)
257
+ result = blend_canvas(result, canvas_c, "difference", 0.6)
258
+
259
+ # Beat-triggered kaleidoscope
260
+ if f.get("bdecay", 0) > 0.3:
261
+ result = sh_kaleidoscope(result.copy(), folds=6)
262
+
263
+ return result
264
+ ```
265
+
266
+ ---
267
+
268
+ ## Adaptive Tone Mapping
269
+
270
+ ### The Brightness Problem
271
+
272
+ ASCII characters are small bright dots on a black background. Most pixels in any frame are background (black). This means:
273
+ - Mean frame brightness is inherently low (often 5-30 out of 255)
274
+ - Different effect combinations produce wildly different brightness levels
275
+ - A spiral scene might be 50 mean, while a fire scene is 9 mean
276
+ - Linear multipliers (e.g., `canvas * 2.0`) either leave dark scenes dark or blow out bright scenes
277
+
278
+ ### The `tonemap()` Function
279
+
280
+ Replaces linear brightness multipliers with adaptive per-frame normalization + gamma correction:
281
+
282
+ ```python
283
+ def tonemap(canvas, target_mean=90, gamma=0.75, black_point=2, white_point=253):
284
+ """Adaptive tone-mapping: normalizes + gamma-corrects so no frame is
285
+ fully dark or washed out.
286
+
287
+ 1. Compute 1st and 99.5th percentile on 4x subsample (16x fewer values,
288
+ negligible accuracy loss, major speedup at 1080p+)
289
+ 2. Stretch that range to [0, 1]
290
+ 3. Apply gamma curve (< 1 lifts shadows, > 1 darkens)
291
+ 4. Rescale to [black_point, white_point]
292
+ """
293
+ f = canvas.astype(np.float32)
294
+ sub = f[::4, ::4] # 4x subsample: ~390K values vs ~6.2M at 1080p
295
+ lo = np.percentile(sub, 1)
296
+ hi = np.percentile(sub, 99.5)
297
+ if hi - lo < 10:
298
+ hi = max(hi, lo + 10) # near-uniform frame fallback
299
+ f = np.clip((f - lo) / (hi - lo), 0.0, 1.0)
300
+ np.power(f, gamma, out=f) # in-place: avoids allocation
301
+ np.multiply(f, (white_point - black_point), out=f)
302
+ np.add(f, black_point, out=f)
303
+ return np.clip(f, 0, 255).astype(np.uint8)
304
+ ```
305
+
306
+ ### Why Gamma, Not Linear
307
+
308
+ Linear multiplier `* 2.0`:
309
+ ```
310
+ input 10 -> output 20 (still dark)
311
+ input 100 -> output 200 (ok)
312
+ input 200 -> output 255 (clipped, lost detail)
313
+ ```
314
+
315
+ Gamma 0.75 after normalization:
316
+ ```
317
+ input 0.04 -> output 0.08 (lifted from invisible to visible)
318
+ input 0.39 -> output 0.50 (moderate lift)
319
+ input 0.78 -> output 0.84 (gentle lift, no clipping)
320
+ ```
321
+
322
+ Gamma < 1 compresses the highlights and expands the shadows. This is exactly what we need: lift dark ASCII content into visibility without blowing out the bright parts.
323
+
324
+ ### Pipeline Ordering
325
+
326
+ The pipeline in `render_clip()` is:
327
+
328
+ ```
329
+ scene_fn(r, f, t, S) -> canvas
330
+ |
331
+ tonemap(canvas, gamma=scene_gamma)
332
+ |
333
+ FeedbackBuffer.apply(canvas, ...)
334
+ |
335
+ ShaderChain.apply(canvas, f=f, t=t)
336
+ |
337
+ ffmpeg pipe
338
+ ```
339
+
340
+ Tonemap runs BEFORE feedback and shaders. This means:
341
+ - Feedback operates on normalized data (consistent behavior regardless of scene brightness)
342
+ - Shaders like solarize, posterize, contrast operate on properly-ranged data
343
+ - The brightness shader in the chain is no longer needed (tonemap handles it)
344
+
345
+ ### Per-Scene Gamma Tuning
346
+
347
+ Default gamma is 0.75. Scenes that apply destructive post-processing need more aggressive lift because the destruction happens after tonemap:
348
+
349
+ | Scene Type | Recommended Gamma | Why |
350
+ |------------|-------------------|-----|
351
+ | Standard effects | 0.75 | Default, works for most scenes |
352
+ | Solarize post-process | 0.50-0.60 | Solarize inverts bright pixels, reducing overall brightness |
353
+ | Posterize post-process | 0.50-0.55 | Posterize quantizes, often crushing mid-values to black |
354
+ | Heavy difference blending | 0.60-0.70 | Difference mode creates many near-zero pixels |
355
+ | Already bright scenes | 0.85-1.0 | Don't over-boost scenes that are naturally bright |
356
+
357
+ Configure via the scene table:
358
+
359
+ ```python
360
+ SCENES = [
361
+ {"start": 9.17, "end": 11.25, "name": "fire", "gamma": 0.55,
362
+ "fx": fx_fire, "shaders": [("solarize", {"threshold": 200}), ...]},
363
+ {"start": 25.96, "end": 27.29, "name": "diamond", "gamma": 0.5,
364
+ "fx": fx_diamond, "shaders": [("bloom", {"thr": 90}), ...]},
365
+ ]
366
+ ```
367
+
368
+ ### Brightness Verification
369
+
370
+ After rendering, spot-check frame brightness:
371
+
372
+ ```python
373
+ # In test-frame mode
374
+ canvas = scene["fx"](r, feat, t, r.S)
375
+ canvas = tonemap(canvas, gamma=scene.get("gamma", 0.75))
376
+ chain = ShaderChain()
377
+ for sn, kw in scene.get("shaders", []):
378
+ chain.add(sn, **kw)
379
+ canvas = chain.apply(canvas, f=feat, t=t)
380
+ print(f"Mean brightness: {canvas.astype(float).mean():.1f}, max: {canvas.max()}")
381
+ ```
382
+
383
+ Target ranges after tonemap + shaders:
384
+ - Quiet/ambient scenes: mean 30-60
385
+ - Active scenes: mean 40-100
386
+ - Climax/peak scenes: mean 60-150
387
+ - If mean < 20: gamma is too high or a shader is destroying brightness
388
+ - If mean > 180: gamma is too low or add is stacking too much
389
+
390
+ ---
391
+
392
+ ## FeedbackBuffer Spatial Transforms
393
+
394
+ The feedback buffer stores the previous frame and blends it into the current frame with decay. Spatial transforms applied to the buffer before blending create the illusion of motion in the feedback trail.
395
+
396
+ ### Implementation
397
+
398
+ ```python
399
+ class FeedbackBuffer:
400
+ def __init__(self):
401
+ self.buf = None
402
+
403
+ def apply(self, canvas, decay=0.85, blend="screen", opacity=0.5,
404
+ transform=None, transform_amt=0.02, hue_shift=0.0):
405
+ if self.buf is None:
406
+ self.buf = canvas.astype(np.float32) / 255.0
407
+ return canvas
408
+
409
+ # Decay old buffer
410
+ self.buf *= decay
411
+
412
+ # Spatial transform
413
+ if transform:
414
+ self.buf = self._transform(self.buf, transform, transform_amt)
415
+
416
+ # Hue shift the feedback for rainbow trails
417
+ if hue_shift > 0:
418
+ self.buf = self._hue_shift(self.buf, hue_shift)
419
+
420
+ # Blend feedback into current frame
421
+ result = blend_canvas(canvas,
422
+ np.clip(self.buf * 255, 0, 255).astype(np.uint8),
423
+ blend, opacity)
424
+
425
+ # Update buffer with current frame
426
+ self.buf = result.astype(np.float32) / 255.0
427
+ return result
428
+
429
+ def _transform(self, buf, transform, amt):
430
+ h, w = buf.shape[:2]
431
+ if transform == "zoom":
432
+ # Zoom in: sample from slightly inside (creates expanding tunnel)
433
+ m = int(h * amt); n = int(w * amt)
434
+ if m > 0 and n > 0:
435
+ cropped = buf[m:-m or None, n:-n or None]
436
+ # Resize back to full (nearest-neighbor for speed)
437
+ buf = np.array(Image.fromarray(
438
+ np.clip(cropped * 255, 0, 255).astype(np.uint8)
439
+ ).resize((w, h), Image.NEAREST)).astype(np.float32) / 255.0
440
+ elif transform == "shrink":
441
+ # Zoom out: pad edges, shrink center
442
+ m = int(h * amt); n = int(w * amt)
443
+ small = np.array(Image.fromarray(
444
+ np.clip(buf * 255, 0, 255).astype(np.uint8)
445
+ ).resize((w - 2*n, h - 2*m), Image.NEAREST))
446
+ new = np.zeros((h, w, 3), dtype=np.uint8)
447
+ new[m:m+small.shape[0], n:n+small.shape[1]] = small
448
+ buf = new.astype(np.float32) / 255.0
449
+ elif transform == "rotate_cw":
450
+ # Small clockwise rotation via affine
451
+ angle = amt * 10 # amt=0.005 -> 0.05 degrees per frame
452
+ cy, cx = h / 2, w / 2
453
+ Y = np.arange(h, dtype=np.float32)[:, None]
454
+ X = np.arange(w, dtype=np.float32)[None, :]
455
+ cos_a, sin_a = np.cos(angle), np.sin(angle)
456
+ sx = (X - cx) * cos_a + (Y - cy) * sin_a + cx
457
+ sy = -(X - cx) * sin_a + (Y - cy) * cos_a + cy
458
+ sx = np.clip(sx.astype(int), 0, w - 1)
459
+ sy = np.clip(sy.astype(int), 0, h - 1)
460
+ buf = buf[sy, sx]
461
+ elif transform == "rotate_ccw":
462
+ angle = -amt * 10
463
+ cy, cx = h / 2, w / 2
464
+ Y = np.arange(h, dtype=np.float32)[:, None]
465
+ X = np.arange(w, dtype=np.float32)[None, :]
466
+ cos_a, sin_a = np.cos(angle), np.sin(angle)
467
+ sx = (X - cx) * cos_a + (Y - cy) * sin_a + cx
468
+ sy = -(X - cx) * sin_a + (Y - cy) * cos_a + cy
469
+ sx = np.clip(sx.astype(int), 0, w - 1)
470
+ sy = np.clip(sy.astype(int), 0, h - 1)
471
+ buf = buf[sy, sx]
472
+ elif transform == "shift_up":
473
+ pixels = max(1, int(h * amt))
474
+ buf = np.roll(buf, -pixels, axis=0)
475
+ buf[-pixels:] = 0 # black fill at bottom
476
+ elif transform == "shift_down":
477
+ pixels = max(1, int(h * amt))
478
+ buf = np.roll(buf, pixels, axis=0)
479
+ buf[:pixels] = 0
480
+ elif transform == "mirror_h":
481
+ buf = buf[:, ::-1]
482
+ return buf
483
+
484
+ def _hue_shift(self, buf, amount):
485
+ """Rotate hues of the feedback buffer. Operates on float32 [0,1]."""
486
+ rgb = np.clip(buf * 255, 0, 255).astype(np.uint8)
487
+ hsv = np.zeros_like(buf)
488
+ # Simple approximate RGB->HSV->shift->RGB
489
+ r, g, b = buf[:,:,0], buf[:,:,1], buf[:,:,2]
490
+ mx = np.maximum(np.maximum(r, g), b)
491
+ mn = np.minimum(np.minimum(r, g), b)
492
+ delta = mx - mn + 1e-10
493
+ # Hue
494
+ h = np.where(mx == r, ((g - b) / delta) % 6,
495
+ np.where(mx == g, (b - r) / delta + 2, (r - g) / delta + 4))
496
+ h = (h / 6 + amount) % 1.0
497
+ # Reconstruct with shifted hue (simplified)
498
+ s = delta / (mx + 1e-10)
499
+ v = mx
500
+ c = v * s; x = c * (1 - np.abs((h * 6) % 2 - 1)); m = v - c
501
+ ro = np.zeros_like(h); go = np.zeros_like(h); bo = np.zeros_like(h)
502
+ for lo, hi, rv, gv, bv in [(0,1,c,x,0),(1,2,x,c,0),(2,3,0,c,x),
503
+ (3,4,0,x,c),(4,5,x,0,c),(5,6,c,0,x)]:
504
+ mask = ((h*6) >= lo) & ((h*6) < hi)
505
+ ro[mask] = rv[mask] if not isinstance(rv, (int,float)) else rv
506
+ go[mask] = gv[mask] if not isinstance(gv, (int,float)) else gv
507
+ bo[mask] = bv[mask] if not isinstance(bv, (int,float)) else bv
508
+ return np.stack([ro+m, go+m, bo+m], axis=2)
509
+ ```
510
+
511
+ ### Feedback Presets
512
+
513
+ | Preset | Config | Visual Effect |
514
+ |--------|--------|---------------|
515
+ | Infinite zoom tunnel | `decay=0.8, blend="screen", transform="zoom", transform_amt=0.015` | Expanding ring patterns |
516
+ | Rainbow trails | `decay=0.7, blend="screen", transform="zoom", transform_amt=0.01, hue_shift=0.02` | Psychedelic color trails |
517
+ | Ghostly echo | `decay=0.9, blend="add", opacity=0.15, transform="shift_up", transform_amt=0.01` | Faint upward smearing |
518
+ | Kaleidoscopic recursion | `decay=0.75, blend="screen", transform="rotate_cw", transform_amt=0.005, hue_shift=0.01` | Rotating mandala feedback |
519
+ | Color evolution | `decay=0.8, blend="difference", opacity=0.4, hue_shift=0.03` | Frame-to-frame color XOR |
520
+ | Rising heat haze | `decay=0.5, blend="add", opacity=0.2, transform="shift_up", transform_amt=0.02` | Hot air shimmer |
521
+
522
+ ---
523
+
524
+ ## Masking / Stencil System
525
+
526
+ Masks are float32 arrays `(rows, cols)` or `(VH, VW)` in range [0, 1]. They control where effects are visible: 1.0 = fully visible, 0.0 = fully hidden. Use masks to create figure/ground relationships, focal points, and shaped reveals.
527
+
528
+ ### Shape Masks
529
+
530
+ ```python
531
+ def mask_circle(g, cx_frac=0.5, cy_frac=0.5, radius=0.3, feather=0.05):
532
+ """Circular mask centered at (cx_frac, cy_frac) in normalized coords.
533
+ feather: width of soft edge (0 = hard cutoff)."""
534
+ asp = g.cw / g.ch if hasattr(g, 'cw') else 1.0
535
+ dx = (g.cc / g.cols - cx_frac)
536
+ dy = (g.rr / g.rows - cy_frac) * asp
537
+ d = np.sqrt(dx**2 + dy**2)
538
+ if feather > 0:
539
+ return np.clip(1.0 - (d - radius) / feather, 0, 1)
540
+ return (d <= radius).astype(np.float32)
541
+
542
+ def mask_rect(g, x0=0.2, y0=0.2, x1=0.8, y1=0.8, feather=0.03):
543
+ """Rectangular mask. Coordinates in [0,1] normalized."""
544
+ dx = np.maximum(x0 - g.cc / g.cols, g.cc / g.cols - x1)
545
+ dy = np.maximum(y0 - g.rr / g.rows, g.rr / g.rows - y1)
546
+ d = np.maximum(dx, dy)
547
+ if feather > 0:
548
+ return np.clip(1.0 - d / feather, 0, 1)
549
+ return (d <= 0).astype(np.float32)
550
+
551
+ def mask_ring(g, cx_frac=0.5, cy_frac=0.5, inner_r=0.15, outer_r=0.35,
552
+ feather=0.03):
553
+ """Ring / annulus mask."""
554
+ inner = mask_circle(g, cx_frac, cy_frac, inner_r, feather)
555
+ outer = mask_circle(g, cx_frac, cy_frac, outer_r, feather)
556
+ return outer - inner
557
+
558
+ def mask_gradient_h(g, start=0.0, end=1.0):
559
+ """Left-to-right gradient mask."""
560
+ return np.clip((g.cc / g.cols - start) / (end - start + 1e-10), 0, 1).astype(np.float32)
561
+
562
+ def mask_gradient_v(g, start=0.0, end=1.0):
563
+ """Top-to-bottom gradient mask."""
564
+ return np.clip((g.rr / g.rows - start) / (end - start + 1e-10), 0, 1).astype(np.float32)
565
+
566
+ def mask_gradient_radial(g, cx_frac=0.5, cy_frac=0.5, inner=0.0, outer=0.5):
567
+ """Radial gradient mask — bright at center, dark at edges."""
568
+ d = np.sqrt((g.cc / g.cols - cx_frac)**2 + (g.rr / g.rows - cy_frac)**2)
569
+ return np.clip(1.0 - (d - inner) / (outer - inner + 1e-10), 0, 1)
570
+ ```
571
+
572
+ ### Value Field as Mask
573
+
574
+ Use any `vf_*` function's output as a spatial mask:
575
+
576
+ ```python
577
+ def mask_from_vf(vf_result, threshold=0.5, feather=0.1):
578
+ """Convert a value field to a mask by thresholding.
579
+ feather: smooth edge width around threshold."""
580
+ if feather > 0:
581
+ return np.clip((vf_result - threshold + feather) / (2 * feather), 0, 1)
582
+ return (vf_result > threshold).astype(np.float32)
583
+
584
+ def mask_select(mask, vf_a, vf_b):
585
+ """Spatial conditional: show vf_a where mask is 1, vf_b where mask is 0.
586
+ mask: float32 [0,1] array. Intermediate values blend."""
587
+ return vf_a * mask + vf_b * (1 - mask)
588
+ ```
589
+
590
+ ### Text Stencil
591
+
592
+ Render text to a mask. Effects are visible only through the letterforms:
593
+
594
+ ```python
595
+ def mask_text(grid, text, row_frac=0.5, font=None, font_size=None):
596
+ """Render text string as a float32 mask [0,1] at grid resolution.
597
+ Characters = 1.0, background = 0.0.
598
+
599
+ row_frac: vertical position as fraction of grid height.
600
+ font: PIL ImageFont (defaults to grid's font if None).
601
+ font_size: override font size for the mask text (for larger stencil text).
602
+ """
603
+ from PIL import Image, ImageDraw, ImageFont
604
+
605
+ f = font or grid.font
606
+ if font_size and font != grid.font:
607
+ f = ImageFont.truetype(font.path, font_size)
608
+
609
+ # Render text to image at pixel resolution, then downsample to grid
610
+ img = Image.new("L", (grid.cols * grid.cw, grid.ch), 0)
611
+ draw = ImageDraw.Draw(img)
612
+ bbox = draw.textbbox((0, 0), text, font=f)
613
+ tw = bbox[2] - bbox[0]
614
+ x = (grid.cols * grid.cw - tw) // 2
615
+ draw.text((x, 0), text, fill=255, font=f)
616
+ row_mask = np.array(img, dtype=np.float32) / 255.0
617
+
618
+ # Place in full grid mask
619
+ mask = np.zeros((grid.rows, grid.cols), dtype=np.float32)
620
+ target_row = int(grid.rows * row_frac)
621
+ # Downsample rendered text to grid cells
622
+ for c in range(grid.cols):
623
+ px = c * grid.cw
624
+ if px + grid.cw <= row_mask.shape[1]:
625
+ cell = row_mask[:, px:px + grid.cw]
626
+ if cell.mean() > 0.1:
627
+ mask[target_row, c] = cell.mean()
628
+ return mask
629
+
630
+ def mask_text_block(grid, lines, start_row_frac=0.3, font=None):
631
+ """Multi-line text stencil. Returns full grid mask."""
632
+ mask = np.zeros((grid.rows, grid.cols), dtype=np.float32)
633
+ for i, line in enumerate(lines):
634
+ row_frac = start_row_frac + i / grid.rows
635
+ line_mask = mask_text(grid, line, row_frac, font)
636
+ mask = np.maximum(mask, line_mask)
637
+ return mask
638
+ ```
639
+
640
+ ### Animated Masks
641
+
642
+ Masks that change over time for reveals, wipes, and morphing:
643
+
644
+ ```python
645
+ def mask_iris(g, t, t_start, t_end, cx_frac=0.5, cy_frac=0.5,
646
+ max_radius=0.7, ease_fn=None):
647
+ """Iris open/close: circle that grows from 0 to max_radius.
648
+ ease_fn: easing function (default: ease_in_out_cubic from effects.md)."""
649
+ if ease_fn is None:
650
+ ease_fn = lambda x: x * x * (3 - 2 * x) # smoothstep fallback
651
+ progress = np.clip((t - t_start) / (t_end - t_start), 0, 1)
652
+ radius = ease_fn(progress) * max_radius
653
+ return mask_circle(g, cx_frac, cy_frac, radius, feather=0.03)
654
+
655
+ def mask_wipe_h(g, t, t_start, t_end, direction="right"):
656
+ """Horizontal wipe reveal."""
657
+ progress = np.clip((t - t_start) / (t_end - t_start), 0, 1)
658
+ if direction == "left":
659
+ progress = 1 - progress
660
+ return mask_gradient_h(g, start=progress - 0.05, end=progress + 0.05)
661
+
662
+ def mask_wipe_v(g, t, t_start, t_end, direction="down"):
663
+ """Vertical wipe reveal."""
664
+ progress = np.clip((t - t_start) / (t_end - t_start), 0, 1)
665
+ if direction == "up":
666
+ progress = 1 - progress
667
+ return mask_gradient_v(g, start=progress - 0.05, end=progress + 0.05)
668
+
669
+ def mask_dissolve(g, t, t_start, t_end, seed=42):
670
+ """Random pixel dissolve — noise threshold sweeps from 0 to 1."""
671
+ progress = np.clip((t - t_start) / (t_end - t_start), 0, 1)
672
+ rng = np.random.RandomState(seed)
673
+ noise = rng.random((g.rows, g.cols)).astype(np.float32)
674
+ return (noise < progress).astype(np.float32)
675
+ ```
676
+
677
+ ### Mask Boolean Operations
678
+
679
+ ```python
680
+ def mask_union(a, b):
681
+ """OR — visible where either mask is active."""
682
+ return np.maximum(a, b)
683
+
684
+ def mask_intersect(a, b):
685
+ """AND — visible only where both masks are active."""
686
+ return np.minimum(a, b)
687
+
688
+ def mask_subtract(a, b):
689
+ """A minus B — visible where A is active but B is not."""
690
+ return np.clip(a - b, 0, 1)
691
+
692
+ def mask_invert(m):
693
+ """NOT — flip mask."""
694
+ return 1.0 - m
695
+ ```
696
+
697
+ ### Applying Masks to Canvases
698
+
699
+ ```python
700
+ def apply_mask_canvas(canvas, mask, bg_canvas=None):
701
+ """Apply a grid-resolution mask to a pixel canvas.
702
+ Expands mask from (rows, cols) to (VH, VW) via nearest-neighbor.
703
+
704
+ canvas: uint8 (VH, VW, 3)
705
+ mask: float32 (rows, cols) [0,1]
706
+ bg_canvas: what shows through where mask=0. None = black.
707
+ """
708
+ # Expand mask to pixel resolution
709
+ mask_px = np.repeat(np.repeat(mask, canvas.shape[0] // mask.shape[0] + 1, axis=0),
710
+ canvas.shape[1] // mask.shape[1] + 1, axis=1)
711
+ mask_px = mask_px[:canvas.shape[0], :canvas.shape[1]]
712
+
713
+ if bg_canvas is not None:
714
+ return np.clip(canvas * mask_px[:, :, None] +
715
+ bg_canvas * (1 - mask_px[:, :, None]), 0, 255).astype(np.uint8)
716
+ return np.clip(canvas * mask_px[:, :, None], 0, 255).astype(np.uint8)
717
+
718
+ def apply_mask_vf(vf_a, vf_b, mask):
719
+ """Apply mask at value-field level — blend two value fields spatially.
720
+ All arrays are (rows, cols) float32."""
721
+ return vf_a * mask + vf_b * (1 - mask)
722
+ ```
723
+
724
+ ---
725
+
726
+ ## PixelBlendStack
727
+
728
+ Higher-level wrapper for multi-layer compositing:
729
+
730
+ ```python
731
+ class PixelBlendStack:
732
+ def __init__(self):
733
+ self.layers = []
734
+
735
+ def add(self, canvas, mode="normal", opacity=1.0):
736
+ self.layers.append((canvas, mode, opacity))
737
+ return self
738
+
739
+ def composite(self):
740
+ if not self.layers:
741
+ return np.zeros((VH, VW, 3), dtype=np.uint8)
742
+ result = self.layers[0][0]
743
+ for canvas, mode, opacity in self.layers[1:]:
744
+ result = blend_canvas(result, canvas, mode, opacity)
745
+ return result
746
+ ```
747
+
748
+ ## Text Backdrop (Readability Mask)
749
+
750
+ When placing readable text over busy multi-grid ASCII backgrounds, the text will blend into the background and become illegible. **Always apply a dark backdrop behind text regions.**
751
+
752
+ The technique: compute the bounding box of all text glyphs, create a gaussian-blurred dark mask covering that area with padding, and multiply the background by `(1 - mask * darkness)` before rendering text on top.
753
+
754
+ ```python
755
+ from scipy.ndimage import gaussian_filter
756
+
757
+ def apply_text_backdrop(canvas, glyphs, padding=80, darkness=0.75):
758
+ """Darken the background behind text for readability.
759
+
760
+ Call AFTER rendering background, BEFORE rendering text.
761
+
762
+ Args:
763
+ canvas: (VH, VW, 3) uint8 background
764
+ glyphs: list of {"x": float, "y": float, ...} glyph positions
765
+ padding: pixel padding around text bounding box
766
+ darkness: 0.0 = no darkening, 1.0 = fully black
767
+ Returns:
768
+ darkened canvas (uint8)
769
+ """
770
+ if not glyphs:
771
+ return canvas
772
+ xs = [g['x'] for g in glyphs]
773
+ ys = [g['y'] for g in glyphs]
774
+ x0 = max(0, int(min(xs)) - padding)
775
+ y0 = max(0, int(min(ys)) - padding)
776
+ x1 = min(VW, int(max(xs)) + padding + 50) # extra for char width
777
+ y1 = min(VH, int(max(ys)) + padding + 60) # extra for char height
778
+
779
+ # Soft dark mask with gaussian blur for feathered edges
780
+ mask = np.zeros((VH, VW), dtype=np.float32)
781
+ mask[y0:y1, x0:x1] = 1.0
782
+ mask = gaussian_filter(mask, sigma=padding * 0.6)
783
+
784
+ factor = 1.0 - mask * darkness
785
+ return (canvas.astype(np.float32) * factor[:, :, np.newaxis]).astype(np.uint8)
786
+ ```
787
+
788
+ ### Usage in render pipeline
789
+
790
+ Insert between background rendering and text rendering:
791
+
792
+ ```python
793
+ # 1. Render background (multi-grid ASCII effects)
794
+ bg = render_background(cfg, t)
795
+
796
+ # 2. Darken behind text region
797
+ bg = apply_text_backdrop(bg, frame_glyphs, padding=80, darkness=0.75)
798
+
799
+ # 3. Render text on top (now readable against dark backdrop)
800
+ bg = text_renderer.render(bg, frame_glyphs, color=(255, 255, 255))
801
+ ```
802
+
803
+ Combine with **reverse vignette** (see shaders.md) for scenes where text is always centered — the reverse vignette provides a persistent center-dark zone, while the backdrop handles per-frame glyph positions.
804
+
805
+ ## External Layout Oracle Pattern
806
+
807
+ For text-heavy videos where text needs to dynamically reflow around obstacles (shapes, icons, other text), use an external layout engine to pre-compute glyph positions and feed them into the Python renderer via JSON.
808
+
809
+ ### Architecture
810
+
811
+ ```
812
+ Layout Engine (browser/Node.js) → layouts.json → Python ASCII Renderer
813
+ ↑ ↑
814
+ Computes per-frame Reads glyph positions,
815
+ glyph (x,y) positions renders as ASCII chars
816
+ with obstacle-aware reflow with full effect pipeline
817
+ ```
818
+
819
+ ### JSON interchange format
820
+
821
+ ```json
822
+ {
823
+ "meta": {
824
+ "canvas_width": 1080, "canvas_height": 1080,
825
+ "fps": 24, "total_frames": 1248,
826
+ "fonts": {
827
+ "body": {"charW": 12.04, "charH": 24, "fontSize": 20},
828
+ "hero": {"charW": 24.08, "charH": 48, "fontSize": 40}
829
+ }
830
+ },
831
+ "scenes": [
832
+ {
833
+ "id": "scene_name",
834
+ "start_frame": 0, "end_frame": 96,
835
+ "frames": {
836
+ "0": {
837
+ "glyphs": [
838
+ {"char": "H", "x": 287.1, "y": 400.0, "alpha": 1.0},
839
+ {"char": "e", "x": 311.2, "y": 400.0, "alpha": 1.0}
840
+ ],
841
+ "obstacles": [
842
+ {"type": "circle", "cx": 540, "cy": 540, "r": 80},
843
+ {"type": "rect", "x": 300, "y": 500, "w": 120, "h": 80}
844
+ ]
845
+ }
846
+ }
847
+ }
848
+ ]
849
+ }
850
+ ```
851
+
852
+ ### When to use
853
+
854
+ - Text that dynamically reflows around moving objects
855
+ - Per-glyph animation (reveal, scatter, physics)
856
+ - Variable typography that needs precise measurement
857
+ - Any case where Python's Pillow text layout is insufficient
858
+
859
+ ### When NOT to use
860
+
861
+ - Static centered text (just use PIL `draw.text()` directly)
862
+ - Text that only fades in/out without spatial animation
863
+ - Simple typewriter effects (handle in Python with a character counter)
864
+
865
+ ### Running the oracle
866
+
867
+ Use Playwright to run the layout engine in a headless browser:
868
+
869
+ ```javascript
870
+ // extract.mjs
871
+ import { chromium } from 'playwright';
872
+ const browser = await chromium.launch({ headless: true });
873
+ const page = await browser.newPage();
874
+ await page.goto(`file://${oraclePath}`);
875
+ await page.waitForFunction(() => window.__ORACLE_DONE__ === true, null, { timeout: 60000 });
876
+ const result = await page.evaluate(() => window.__ORACLE_RESULT__);
877
+ writeFileSync('layouts.json', JSON.stringify(result));
878
+ await browser.close();
879
+ ```
880
+
881
+ ### Consuming in Python
882
+
883
+ ```python
884
+ # In the renderer, map pixel positions to the canvas:
885
+ for glyph in frame_data['glyphs']:
886
+ char, px, py = glyph['char'], glyph['x'], glyph['y']
887
+ alpha = glyph.get('alpha', 1.0)
888
+ # Render using PIL draw.text() at exact pixel position
889
+ draw.text((px, py), char, fill=(int(255*alpha),)*3, font=font)
890
+ ```
891
+
892
+ Obstacles from the JSON can also be rendered as glowing ASCII shapes (circles, rectangles) to visualize the reflow zones.
skills/.archive/ascii-video/references/effects.md ADDED
@@ -0,0 +1,1865 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Effect Catalog
2
+
3
+ Effect building blocks that produce visual patterns. In v2, these are used **inside scene functions** that return a pixel canvas directly. The building blocks below operate on grid coordinate arrays and produce `(chars, colors)` or value/hue fields that the scene function renders to canvas via `_render_vf()`.
4
+
5
+ > **See also:** architecture.md · composition.md · scenes.md · shaders.md · troubleshooting.md
6
+
7
+ ## Design Philosophy
8
+
9
+ Effects are the creative core. Don't copy these verbatim for every project -- use them as **building blocks** and **combine, modify, and invent** new ones. Every project should feel distinct.
10
+
11
+ Key principles:
12
+ - **Layer multiple effects** rather than using a single monolithic function
13
+ - **Parameterize everything** -- hue, speed, density, amplitude should all be arguments
14
+ - **React to features** -- audio/video features should modulate at least 2-3 parameters per effect
15
+ - **Vary per section** -- never use the same effect config for the entire video
16
+ - **Invent project-specific effects** -- the catalog below is a starting vocabulary, not a fixed set
17
+
18
+ ---
19
+
20
+ ## Background Fills
21
+
22
+ Every effect should start with a background. Never leave flat black.
23
+
24
+ ### Animated Sine Field (General Purpose)
25
+ ```python
26
+ def bg_sinefield(g, f, t, hue=0.6, bri=0.5, pal=PAL_DEFAULT,
27
+ freq=(0.13, 0.17, 0.07, 0.09), speed=(0.5, -0.4, -0.3, 0.2)):
28
+ """Layered sine field. Adjust freq/speed tuples for different textures."""
29
+ v1 = np.sin(g.cc*freq[0] + t*speed[0]) * np.sin(g.rr*freq[1] - t*speed[1]) * 0.5 + 0.5
30
+ v2 = np.sin(g.cc*freq[2] - t*speed[2] + g.rr*freq[3]) * 0.4 + 0.5
31
+ v3 = np.sin(g.dist_n*5 + t*0.2) * 0.3 + 0.4
32
+ v4 = np.cos(g.angle*3 - t*0.6) * 0.15 + 0.5
33
+ val = np.clip((v1*0.3 + v2*0.25 + v3*0.25 + v4*0.2) * bri * (0.6 + f["rms"]*0.6), 0.06, 1)
34
+ mask = val > 0.03
35
+ ch = val2char(val, mask, pal)
36
+ h = np.full_like(val, hue) + f.get("cent", 0.5)*0.1 + val*0.08
37
+ R, G, B = hsv2rgb(h, np.clip(0.35+f.get("flat",0.4)*0.4, 0, 1) * np.ones_like(val), val)
38
+ return ch, mkc(R, G, B, g.rows, g.cols)
39
+ ```
40
+
41
+ ### Video-Source Background
42
+ ```python
43
+ def bg_video(g, frame_rgb, pal=PAL_DEFAULT, brightness=0.5):
44
+ small = np.array(Image.fromarray(frame_rgb).resize((g.cols, g.rows)))
45
+ lum = np.mean(small, axis=2) / 255.0 * brightness
46
+ mask = lum > 0.02
47
+ ch = val2char(lum, mask, pal)
48
+ co = np.clip(small * np.clip(lum[:,:,None]*1.5+0.3, 0.3, 1), 0, 255).astype(np.uint8)
49
+ return ch, co
50
+ ```
51
+
52
+ ### Noise / Static Field
53
+ ```python
54
+ def bg_noise(g, f, t, pal=PAL_BLOCKS, density=0.3, hue_drift=0.02):
55
+ val = np.random.random((g.rows, g.cols)).astype(np.float32) * density * (0.5 + f["rms"]*0.5)
56
+ val = np.clip(val, 0, 1); mask = val > 0.02
57
+ ch = val2char(val, mask, pal)
58
+ R, G, B = hsv2rgb(np.full_like(val, t*hue_drift % 1), np.full_like(val, 0.3), val)
59
+ return ch, mkc(R, G, B, g.rows, g.cols)
60
+ ```
61
+
62
+ ### Perlin-Like Smooth Noise
63
+ ```python
64
+ def bg_smooth_noise(g, f, t, hue=0.5, bri=0.5, pal=PAL_DOTS, octaves=3):
65
+ """Layered sine approximation of Perlin noise. Cheap, smooth, organic."""
66
+ val = np.zeros((g.rows, g.cols), dtype=np.float32)
67
+ for i in range(octaves):
68
+ freq = 0.05 * (2 ** i)
69
+ amp = 0.5 / (i + 1)
70
+ phase = t * (0.3 + i * 0.2)
71
+ val += np.sin(g.cc * freq + phase) * np.cos(g.rr * freq * 0.7 - phase * 0.5) * amp
72
+ val = np.clip(val * 0.5 + 0.5, 0, 1) * bri
73
+ mask = val > 0.03
74
+ ch = val2char(val, mask, pal)
75
+ h = np.full_like(val, hue) + val * 0.1
76
+ R, G, B = hsv2rgb(h, np.full_like(val, 0.5), val)
77
+ return ch, mkc(R, G, B, g.rows, g.cols)
78
+ ```
79
+
80
+ ### Cellular / Voronoi Approximation
81
+ ```python
82
+ def bg_cellular(g, f, t, n_centers=12, hue=0.5, bri=0.6, pal=PAL_BLOCKS):
83
+ """Voronoi-like cells using distance to nearest of N moving centers."""
84
+ rng = np.random.RandomState(42) # deterministic centers
85
+ cx = (rng.rand(n_centers) * g.cols).astype(np.float32)
86
+ cy = (rng.rand(n_centers) * g.rows).astype(np.float32)
87
+ # Animate centers
88
+ cx_t = cx + np.sin(t * 0.5 + np.arange(n_centers) * 0.7) * 5
89
+ cy_t = cy + np.cos(t * 0.4 + np.arange(n_centers) * 0.9) * 3
90
+ # Min distance to any center
91
+ min_d = np.full((g.rows, g.cols), 999.0, dtype=np.float32)
92
+ for i in range(n_centers):
93
+ d = np.sqrt((g.cc - cx_t[i])**2 + (g.rr - cy_t[i])**2)
94
+ min_d = np.minimum(min_d, d)
95
+ val = np.clip(1.0 - min_d / (g.cols * 0.3), 0, 1) * bri
96
+ # Cell edges (where distance is near-equal between two centers)
97
+ # ... second-nearest trick for edge highlighting
98
+ mask = val > 0.03
99
+ ch = val2char(val, mask, pal)
100
+ R, G, B = hsv2rgb(np.full_like(val, hue) + min_d * 0.005, np.full_like(val, 0.5), val)
101
+ return ch, mkc(R, G, B, g.rows, g.cols)
102
+ ```
103
+
104
+ ---
105
+
106
+ > **Note:** The v1 `eff_rings`, `eff_rays`, `eff_spiral`, `eff_glow`, `eff_tunnel`, `eff_vortex`, `eff_freq_waves`, `eff_interference`, `eff_aurora`, and `eff_ripple` functions are superseded by the `vf_*` value field generators below (used via `_render_vf()`). The `vf_*` versions integrate with the multi-grid composition pipeline and are preferred for all new scenes.
107
+
108
+ ---
109
+
110
+ ## Particle Systems
111
+
112
+ ### General Pattern
113
+ All particle systems use persistent state via the `S` dict parameter:
114
+ ```python
115
+ # S is the persistent state dict (same as r.S, passed explicitly)
116
+ if "px" not in S:
117
+ S["px"]=[]; S["py"]=[]; S["vx"]=[]; S["vy"]=[]; S["life"]=[]; S["char"]=[]
118
+
119
+ # Emit new particles (on beat, continuously, or on trigger)
120
+ # Update: position += velocity, apply forces, decay life
121
+ # Draw: map to grid, set char/color based on life
122
+ # Cull: remove dead, cap total count
123
+ ```
124
+
125
+ ### Particle Character Sets
126
+
127
+ Don't hardcode particle chars. Choose per project/mood:
128
+
129
+ ```python
130
+ # Energy / explosive
131
+ PART_ENERGY = list("*+#@\u26a1\u2726\u2605\u2588\u2593")
132
+ PART_SPARK = list("\u00b7\u2022\u25cf\u2605\u2736*+")
133
+ # Organic / natural
134
+ PART_LEAF = list("\u2740\u2741\u2742\u2743\u273f\u2618\u2022")
135
+ PART_SNOW = list("\u2744\u2745\u2746\u00b7\u2022*\u25cb")
136
+ PART_RAIN = list("|\u2502\u2503\u2551/\\")
137
+ PART_BUBBLE = list("\u25cb\u25ce\u25c9\u25cf\u2218\u2219\u00b0")
138
+ # Data / tech
139
+ PART_DATA = list("01{}[]<>|/\\")
140
+ PART_HEX = list("0123456789ABCDEF")
141
+ PART_BINARY = list("01")
142
+ # Mystical
143
+ PART_RUNE = list("\u16a0\u16a2\u16a6\u16b1\u16b7\u16c1\u16c7\u16d2\u16d6\u16da\u16de\u16df\u2726\u2605")
144
+ PART_ZODIAC = list("\u2648\u2649\u264a\u264b\u264c\u264d\u264e\u264f\u2650\u2651\u2652\u2653")
145
+ # Minimal
146
+ PART_DOT = list("\u00b7\u2022\u25cf")
147
+ PART_DASH = list("-=~\u2500\u2550")
148
+ ```
149
+
150
+ ### Explosion (Beat-Triggered)
151
+ ```python
152
+ def emit_explosion(S, f, center_r, center_c, char_set=PART_ENERGY, count_base=80):
153
+ if f.get("beat", 0) > 0:
154
+ for _ in range(int(count_base + f["rms"]*150)):
155
+ ang = random.uniform(0, 2*math.pi)
156
+ sp = random.uniform(1, 9) * (0.5 + f.get("sub_r", 0.3)*2)
157
+ S["px"].append(float(center_c))
158
+ S["py"].append(float(center_r))
159
+ S["vx"].append(math.cos(ang)*sp*2.5)
160
+ S["vy"].append(math.sin(ang)*sp)
161
+ S["life"].append(1.0)
162
+ S["char"].append(random.choice(char_set))
163
+ # Update: gravity on vy += 0.03, life -= 0.015
164
+ # Color: life * 255 for brightness, hue fade controlled by caller
165
+ ```
166
+
167
+ ### Rising Embers
168
+ ```python
169
+ # Emit: sy = rows-1, vy = -random.uniform(1,5), vx = random.uniform(-1.5,1.5)
170
+ # Update: vx += random jitter * 0.3, life -= 0.01
171
+ # Cap at ~1500 particles
172
+ ```
173
+
174
+ ### Dissolving Cloud
175
+ ```python
176
+ # Init: N=600 particles spread across screen
177
+ # Update: slow upward drift, fade life progressively
178
+ # life -= 0.002 * (1 + elapsed * 0.05) # accelerating fade
179
+ ```
180
+
181
+ ### Starfield (3D Projection)
182
+ ```python
183
+ # N stars with (sx, sy, sz) in normalized coords
184
+ # Move: sz -= speed (stars approach camera)
185
+ # Project: px = cx + sx/sz * cx, py = cy + sy/sz * cy
186
+ # Reset stars that pass camera (sz <= 0.01)
187
+ # Brightness = (1 - sz), draw streaks behind bright stars
188
+ ```
189
+
190
+ ### Orbit (Circular/Elliptical Motion)
191
+ ```python
192
+ def emit_orbit(S, n=20, radius=15, speed=1.0, char_set=PART_DOT):
193
+ """Particles orbiting a center point."""
194
+ for i in range(n):
195
+ angle = i * 2 * math.pi / n
196
+ S["px"].append(0.0); S["py"].append(0.0) # will be computed from angle
197
+ S["vx"].append(angle) # store angle as "vx" for orbit
198
+ S["vy"].append(radius + random.uniform(-2, 2)) # store radius
199
+ S["life"].append(1.0)
200
+ S["char"].append(random.choice(char_set))
201
+ # Update: angle += speed * dt, px = cx + radius * cos(angle), py = cy + radius * sin(angle)
202
+ ```
203
+
204
+ ### Gravity Well
205
+ ```python
206
+ # Particles attracted toward one or more gravity points
207
+ # Update: compute force vector toward each well, apply as acceleration
208
+ # Particles that reach well center respawn at edges
209
+ ```
210
+
211
+ ### Flocking / Boids
212
+
213
+ Emergent swarm behavior from three simple rules: separation, alignment, cohesion.
214
+
215
+ ```python
216
+ def update_boids(S, g, f, n_boids=200, perception=8.0, max_speed=2.0,
217
+ sep_weight=1.5, ali_weight=1.0, coh_weight=1.0,
218
+ char_set=None):
219
+ """Boids flocking simulation. Particles self-organize into organic groups.
220
+
221
+ perception: how far each boid can see (grid cells)
222
+ sep_weight: separation (avoid crowding) strength
223
+ ali_weight: alignment (match neighbor velocity) strength
224
+ coh_weight: cohesion (steer toward group center) strength
225
+ """
226
+ if char_set is None:
227
+ char_set = list("·•●◦∘⬤")
228
+ if "boid_x" not in S:
229
+ rng = np.random.RandomState(42)
230
+ S["boid_x"] = rng.uniform(0, g.cols, n_boids).astype(np.float32)
231
+ S["boid_y"] = rng.uniform(0, g.rows, n_boids).astype(np.float32)
232
+ S["boid_vx"] = (rng.random(n_boids).astype(np.float32) - 0.5) * max_speed
233
+ S["boid_vy"] = (rng.random(n_boids).astype(np.float32) - 0.5) * max_speed
234
+ S["boid_ch"] = [random.choice(char_set) for _ in range(n_boids)]
235
+
236
+ bx = S["boid_x"]; by = S["boid_y"]
237
+ bvx = S["boid_vx"]; bvy = S["boid_vy"]
238
+ n = len(bx)
239
+
240
+ # For each boid, compute steering forces
241
+ ax = np.zeros(n, dtype=np.float32)
242
+ ay = np.zeros(n, dtype=np.float32)
243
+
244
+ # Spatial hash for efficient neighbor lookup
245
+ cell_size = perception
246
+ cells = {}
247
+ for i in range(n):
248
+ cx_i = int(bx[i] / cell_size)
249
+ cy_i = int(by[i] / cell_size)
250
+ key = (cx_i, cy_i)
251
+ if key not in cells:
252
+ cells[key] = []
253
+ cells[key].append(i)
254
+
255
+ for i in range(n):
256
+ cx_i = int(bx[i] / cell_size)
257
+ cy_i = int(by[i] / cell_size)
258
+ sep_x, sep_y = 0.0, 0.0
259
+ ali_x, ali_y = 0.0, 0.0
260
+ coh_x, coh_y = 0.0, 0.0
261
+ count = 0
262
+
263
+ # Check neighboring cells
264
+ for dcx in range(-1, 2):
265
+ for dcy in range(-1, 2):
266
+ for j in cells.get((cx_i + dcx, cy_i + dcy), []):
267
+ if j == i:
268
+ continue
269
+ dx = bx[j] - bx[i]
270
+ dy = by[j] - by[i]
271
+ dist = np.sqrt(dx * dx + dy * dy)
272
+ if dist < perception and dist > 0.01:
273
+ count += 1
274
+ # Separation: steer away from close neighbors
275
+ if dist < perception * 0.4:
276
+ sep_x -= dx / (dist * dist)
277
+ sep_y -= dy / (dist * dist)
278
+ # Alignment: match velocity
279
+ ali_x += bvx[j]
280
+ ali_y += bvy[j]
281
+ # Cohesion: steer toward center of group
282
+ coh_x += bx[j]
283
+ coh_y += by[j]
284
+
285
+ if count > 0:
286
+ # Normalize and weight
287
+ ax[i] += sep_x * sep_weight
288
+ ay[i] += sep_y * sep_weight
289
+ ax[i] += (ali_x / count - bvx[i]) * ali_weight * 0.1
290
+ ay[i] += (ali_y / count - bvy[i]) * ali_weight * 0.1
291
+ ax[i] += (coh_x / count - bx[i]) * coh_weight * 0.01
292
+ ay[i] += (coh_y / count - by[i]) * coh_weight * 0.01
293
+
294
+ # Audio reactivity: bass pushes boids outward from center
295
+ if f.get("bass", 0) > 0.5:
296
+ cx_g, cy_g = g.cols / 2, g.rows / 2
297
+ dx = bx - cx_g; dy = by - cy_g
298
+ dist = np.sqrt(dx**2 + dy**2) + 1
299
+ ax += (dx / dist) * f["bass"] * 2
300
+ ay += (dy / dist) * f["bass"] * 2
301
+
302
+ # Update velocity and position
303
+ bvx += ax; bvy += ay
304
+ # Clamp speed
305
+ speed = np.sqrt(bvx**2 + bvy**2) + 1e-10
306
+ over = speed > max_speed
307
+ bvx[over] *= max_speed / speed[over]
308
+ bvy[over] *= max_speed / speed[over]
309
+ bx += bvx; by += bvy
310
+
311
+ # Wrap at edges
312
+ bx %= g.cols; by %= g.rows
313
+
314
+ S["boid_x"] = bx; S["boid_y"] = by
315
+ S["boid_vx"] = bvx; S["boid_vy"] = bvy
316
+
317
+ # Draw
318
+ ch = np.full((g.rows, g.cols), " ", dtype="U1")
319
+ co = np.zeros((g.rows, g.cols, 3), dtype=np.uint8)
320
+ for i in range(n):
321
+ r, c = int(by[i]) % g.rows, int(bx[i]) % g.cols
322
+ ch[r, c] = S["boid_ch"][i]
323
+ spd = min(1.0, speed[i] / max_speed)
324
+ R, G, B = hsv2rgb_scalar(spd * 0.3, 0.8, 0.5 + spd * 0.5)
325
+ co[r, c] = (R, G, B)
326
+ return ch, co
327
+ ```
328
+
329
+ ### Flow Field Particles
330
+
331
+ Particles that follow the gradient of a value field. Any `vf_*` function becomes a "river" that carries particles:
332
+
333
+ ```python
334
+ def update_flow_particles(S, g, f, flow_field, n=500, speed=1.0,
335
+ life_drain=0.005, emit_rate=10,
336
+ char_set=None):
337
+ """Particles steered by a value field gradient.
338
+
339
+ flow_field: float32 (rows, cols) — the field particles follow.
340
+ Particles flow from low to high values (uphill) or along
341
+ the gradient direction.
342
+ """
343
+ if char_set is None:
344
+ char_set = list("·•∘◦°⋅")
345
+ if "fp_x" not in S:
346
+ S["fp_x"] = []; S["fp_y"] = []; S["fp_vx"] = []; S["fp_vy"] = []
347
+ S["fp_life"] = []; S["fp_ch"] = []
348
+
349
+ # Emit new particles at random positions
350
+ for _ in range(emit_rate):
351
+ if len(S["fp_x"]) < n:
352
+ S["fp_x"].append(random.uniform(0, g.cols - 1))
353
+ S["fp_y"].append(random.uniform(0, g.rows - 1))
354
+ S["fp_vx"].append(0.0); S["fp_vy"].append(0.0)
355
+ S["fp_life"].append(1.0)
356
+ S["fp_ch"].append(random.choice(char_set))
357
+
358
+ # Compute gradient of flow field (central differences)
359
+ pad = np.pad(flow_field, 1, mode="wrap")
360
+ grad_x = (pad[1:-1, 2:] - pad[1:-1, :-2]) * 0.5
361
+ grad_y = (pad[2:, 1:-1] - pad[:-2, 1:-1]) * 0.5
362
+
363
+ # Update particles
364
+ i = 0
365
+ while i < len(S["fp_x"]):
366
+ px, py = S["fp_x"][i], S["fp_y"][i]
367
+ # Sample gradient at particle position
368
+ gc = int(px) % g.cols; gr = int(py) % g.rows
369
+ gx = grad_x[gr, gc]; gy = grad_y[gr, gc]
370
+ # Steer velocity toward gradient direction
371
+ S["fp_vx"][i] = S["fp_vx"][i] * 0.9 + gx * speed * 10
372
+ S["fp_vy"][i] = S["fp_vy"][i] * 0.9 + gy * speed * 10
373
+ S["fp_x"][i] += S["fp_vx"][i]
374
+ S["fp_y"][i] += S["fp_vy"][i]
375
+ S["fp_life"][i] -= life_drain
376
+
377
+ if S["fp_life"][i] <= 0:
378
+ for k in ("fp_x", "fp_y", "fp_vx", "fp_vy", "fp_life", "fp_ch"):
379
+ S[k].pop(i)
380
+ else:
381
+ i += 1
382
+
383
+ # Draw
384
+ ch = np.full((g.rows, g.cols), " ", dtype="U1")
385
+ co = np.zeros((g.rows, g.cols, 3), dtype=np.uint8)
386
+ for i in range(len(S["fp_x"])):
387
+ r = int(S["fp_y"][i]) % g.rows
388
+ c = int(S["fp_x"][i]) % g.cols
389
+ ch[r, c] = S["fp_ch"][i]
390
+ v = S["fp_life"][i]
391
+ co[r, c] = (int(v * 200), int(v * 180), int(v * 255))
392
+ return ch, co
393
+ ```
394
+
395
+ ### Particle Trails
396
+
397
+ Draw fading lines between current and previous positions:
398
+
399
+ ```python
400
+ def draw_particle_trails(S, g, trail_key="trails", max_trail=8, fade=0.7):
401
+ """Add trails to any particle system. Call after updating positions.
402
+ Stores previous positions in S[trail_key] and draws fading lines.
403
+
404
+ Expects S to have 'px', 'py' lists (standard particle keys).
405
+ max_trail: number of previous positions to remember
406
+ fade: brightness multiplier per trail step (0.7 = 70% each step back)
407
+ """
408
+ if trail_key not in S:
409
+ S[trail_key] = []
410
+
411
+ # Store current positions
412
+ current = list(zip(
413
+ [int(y) for y in S.get("py", [])],
414
+ [int(x) for x in S.get("px", [])]
415
+ ))
416
+ S[trail_key].append(current)
417
+ if len(S[trail_key]) > max_trail:
418
+ S[trail_key] = S[trail_key][-max_trail:]
419
+
420
+ # Draw trails onto char/color arrays
421
+ ch = np.full((g.rows, g.cols), " ", dtype="U1")
422
+ co = np.zeros((g.rows, g.cols, 3), dtype=np.uint8)
423
+ trail_chars = list("·∘◦°⋅.,'`")
424
+
425
+ for age, positions in enumerate(reversed(S[trail_key])):
426
+ bri = fade ** age
427
+ if bri < 0.05:
428
+ break
429
+ ci = min(age, len(trail_chars) - 1)
430
+ for r, c in positions:
431
+ if 0 <= r < g.rows and 0 <= c < g.cols and ch[r, c] == " ":
432
+ ch[r, c] = trail_chars[ci]
433
+ v = int(bri * 180)
434
+ co[r, c] = (v, v, int(v * 0.8))
435
+ return ch, co
436
+ ```
437
+
438
+ ---
439
+
440
+ ## Rain / Matrix Effects
441
+
442
+ ### Column Rain (Vectorized)
443
+ ```python
444
+ def eff_matrix_rain(g, f, t, S, hue=0.33, bri=0.6, pal=PAL_KATA,
445
+ speed_base=0.5, speed_beat=3.0):
446
+ """Vectorized matrix rain. S dict persists column positions."""
447
+ if "ry" not in S or len(S["ry"]) != g.cols:
448
+ S["ry"] = np.random.uniform(-g.rows, g.rows, g.cols).astype(np.float32)
449
+ S["rsp"] = np.random.uniform(0.3, 2.0, g.cols).astype(np.float32)
450
+ S["rln"] = np.random.randint(8, 40, g.cols)
451
+ S["rch"] = np.random.randint(0, len(pal), (g.rows, g.cols)) # pre-assign chars
452
+
453
+ speed_mult = speed_base + f.get("bass", 0.3)*speed_beat + f.get("sub_r", 0.3)*3
454
+ if f.get("beat", 0) > 0: speed_mult *= 2.5
455
+ S["ry"] += S["rsp"] * speed_mult
456
+
457
+ # Reset columns that fall past bottom
458
+ rst = (S["ry"] - S["rln"]) > g.rows
459
+ S["ry"][rst] = np.random.uniform(-25, -2, rst.sum())
460
+
461
+ # Vectorized draw using fancy indexing
462
+ ch = np.full((g.rows, g.cols), " ", dtype="U1")
463
+ co = np.zeros((g.rows, g.cols, 3), dtype=np.uint8)
464
+ heads = S["ry"].astype(int)
465
+ for c in range(g.cols):
466
+ head = heads[c]
467
+ trail_len = S["rln"][c]
468
+ for i in range(trail_len):
469
+ row = head - i
470
+ if 0 <= row < g.rows:
471
+ fade = 1.0 - i / trail_len
472
+ ci = S["rch"][row, c] % len(pal)
473
+ ch[row, c] = pal[ci]
474
+ v = fade * bri * 255
475
+ if i == 0: # head is bright white-ish
476
+ co[row, c] = (int(v*0.9), int(min(255, v*1.1)), int(v*0.9))
477
+ else:
478
+ R, G, B = hsv2rgb_single(hue, 0.7, fade * bri)
479
+ co[row, c] = (R, G, B)
480
+ return ch, co, S
481
+ ```
482
+
483
+ ---
484
+
485
+ ## Glitch / Data Effects
486
+
487
+ ### Horizontal Band Displacement
488
+ ```python
489
+ def eff_glitch_displace(ch, co, f, intensity=1.0):
490
+ n_bands = int(8 + f.get("flux", 0.3)*25 + f.get("bdecay", 0)*15) * intensity
491
+ for _ in range(int(n_bands)):
492
+ y = random.randint(0, ch.shape[0]-1)
493
+ h = random.randint(1, int(3 + f.get("sub", 0.3)*8))
494
+ shift = int((random.random()-0.5) * f.get("rms", 0.3)*40 + f.get("bdecay", 0)*20*(random.random()-0.5))
495
+ if shift != 0:
496
+ for row in range(h):
497
+ rr = y + row
498
+ if 0 <= rr < ch.shape[0]:
499
+ ch[rr] = np.roll(ch[rr], shift)
500
+ co[rr] = np.roll(co[rr], shift, axis=0)
501
+ return ch, co
502
+ ```
503
+
504
+ ### Block Corruption
505
+ ```python
506
+ def eff_block_corrupt(ch, co, f, char_pool=None, count_base=20):
507
+ if char_pool is None:
508
+ char_pool = list(PAL_BLOCKS[4:] + PAL_KATA[2:8])
509
+ for _ in range(int(count_base + f.get("flux", 0.3)*60 + f.get("bdecay", 0)*40)):
510
+ bx = random.randint(0, max(1, ch.shape[1]-6))
511
+ by = random.randint(0, max(1, ch.shape[0]-4))
512
+ bw, bh = random.randint(2,6), random.randint(1,4)
513
+ block_char = random.choice(char_pool)
514
+ # Fill rectangle with single char and random color
515
+ for r in range(bh):
516
+ for c in range(bw):
517
+ rr, cc = by+r, bx+c
518
+ if 0 <= rr < ch.shape[0] and 0 <= cc < ch.shape[1]:
519
+ ch[rr, cc] = block_char
520
+ co[rr, cc] = (random.randint(100,255), random.randint(0,100), random.randint(0,80))
521
+ return ch, co
522
+ ```
523
+
524
+ ### Scan Bars (Vertical)
525
+ ```python
526
+ def eff_scanbars(ch, co, f, t, n_base=4, chars="|\u2551|!1l"):
527
+ for bi in range(int(n_base + f.get("himid_r", 0.3)*12)):
528
+ sx = int((t*50*(1+bi*0.3) + bi*37) % ch.shape[1])
529
+ for rr in range(ch.shape[0]):
530
+ if random.random() < 0.7:
531
+ ch[rr, sx] = random.choice(chars)
532
+ return ch, co
533
+ ```
534
+
535
+ ### Error Messages
536
+ ```python
537
+ # Parameterize the error vocabulary per project:
538
+ ERRORS_TECH = ["SEGFAULT","0xDEADBEEF","BUFFER_OVERRUN","PANIC!","NULL_PTR",
539
+ "CORRUPT","SIGSEGV","ERR_OVERFLOW","STACK_SMASH","BAD_ALLOC"]
540
+ ERRORS_COSMIC = ["VOID_BREACH","ENTROPY_MAX","SINGULARITY","DIMENSION_FAULT",
541
+ "REALITY_ERR","TIME_PARADOX","DARK_MATTER_LEAK","QUANTUM_DECOHERE"]
542
+ ERRORS_ORGANIC = ["CELL_DIVISION_ERR","DNA_MISMATCH","MUTATION_OVERFLOW",
543
+ "NEURAL_DEADLOCK","SYNAPSE_TIMEOUT","MEMBRANE_BREACH"]
544
+ ```
545
+
546
+ ### Hex Data Stream
547
+ ```python
548
+ hex_str = "".join(random.choice("0123456789ABCDEF") for _ in range(random.randint(8,20)))
549
+ stamp(ch, co, hex_str, rand_row, rand_col, (0, 160, 80))
550
+ ```
551
+
552
+ ---
553
+
554
+ ## Spectrum / Visualization
555
+
556
+ ### Mirrored Spectrum Bars
557
+ ```python
558
+ def eff_spectrum(g, f, t, n_bars=64, pal=PAL_BLOCKS, mirror=True):
559
+ bar_w = max(1, g.cols // n_bars); mid = g.rows // 2
560
+ band_vals = np.array([f.get("sub",0.3), f.get("bass",0.3), f.get("lomid",0.3),
561
+ f.get("mid",0.3), f.get("himid",0.3), f.get("hi",0.3)])
562
+ ch = np.full((g.rows, g.cols), " ", dtype="U1")
563
+ co = np.zeros((g.rows, g.cols, 3), dtype=np.uint8)
564
+ for b in range(n_bars):
565
+ frac = b / n_bars
566
+ fi = frac * 5; lo_i = int(fi); hi_i = min(lo_i+1, 5)
567
+ bval = min(1, (band_vals[lo_i]*(1-fi%1) + band_vals[hi_i]*(fi%1)) * 1.8)
568
+ height = int(bval * (g.rows//2 - 2))
569
+ for dy in range(height):
570
+ hue = (f.get("cent",0.5)*0.3 + frac*0.3 + dy/max(height,1)*0.15) % 1.0
571
+ ci = pal[min(int(dy/max(height,1)*len(pal)*0.7+len(pal)*0.2), len(pal)-1)]
572
+ for dc in range(bar_w - (1 if bar_w > 2 else 0)):
573
+ cc = b*bar_w + dc
574
+ if 0 <= cc < g.cols:
575
+ rows_to_draw = [mid - dy, mid + dy] if mirror else [g.rows - 1 - dy]
576
+ for row in rows_to_draw:
577
+ if 0 <= row < g.rows:
578
+ ch[row, cc] = ci
579
+ co[row, cc] = hsv_to_rgb_single(hue, 0.85, 0.5+dy/max(height,1)*0.5)
580
+ return ch, co
581
+ ```
582
+
583
+ ### Waveform
584
+ ```python
585
+ def eff_waveform(g, f, t, row_offset=-5, hue=0.1):
586
+ ch = np.full((g.rows, g.cols), " ", dtype="U1")
587
+ co = np.zeros((g.rows, g.cols, 3), dtype=np.uint8)
588
+ for c in range(g.cols):
589
+ wv = (math.sin(c*0.15+t*5)*f.get("bass",0.3)*0.5
590
+ + math.sin(c*0.3+t*8)*f.get("mid",0.3)*0.3
591
+ + math.sin(c*0.6+t*12)*f.get("hi",0.3)*0.15)
592
+ wr = g.rows + row_offset + int(wv * 4)
593
+ if 0 <= wr < g.rows:
594
+ ch[wr, c] = "~"
595
+ v = int(120 + f.get("rms",0.3)*135)
596
+ co[wr, c] = [v, int(v*0.7), int(v*0.4)]
597
+ return ch, co
598
+ ```
599
+
600
+ ---
601
+
602
+ ## Fire / Lava
603
+
604
+ ### Fire Columns
605
+ ```python
606
+ def eff_fire(g, f, t, n_base=20, hue_base=0.02, hue_range=0.12, pal=PAL_BLOCKS):
607
+ n_cols = int(n_base + f.get("bass",0.3)*30 + f.get("sub_r",0.3)*20)
608
+ ch = np.full((g.rows, g.cols), " ", dtype="U1")
609
+ co = np.zeros((g.rows, g.cols, 3), dtype=np.uint8)
610
+ for fi in range(n_cols):
611
+ fx_c = int((fi*g.cols/n_cols + np.sin(t*2+fi*0.7)*3) % g.cols)
612
+ height = int((f.get("bass",0.3)*0.4 + f.get("sub_r",0.3)*0.3 + f.get("rms",0.3)*0.3) * g.rows * 0.7)
613
+ for dy in range(min(height, g.rows)):
614
+ fr = g.rows - 1 - dy
615
+ frac = dy / max(height, 1)
616
+ bri = max(0.1, (1 - frac*0.6) * (0.5 + f.get("rms",0.3)*0.5))
617
+ hue = hue_base + frac * hue_range
618
+ ci = "\u2588" if frac<0.2 else ("\u2593" if frac<0.4 else ("\u2592" if frac<0.6 else "\u2591"))
619
+ ch[fr, fx_c] = ci
620
+ R, G, B = hsv2rgb_single(hue, 0.9, bri)
621
+ co[fr, fx_c] = (R, G, B)
622
+ return ch, co
623
+ ```
624
+
625
+ ### Ice / Cold Fire (same structure, different hue range)
626
+ ```python
627
+ # hue_base=0.55, hue_range=0.15 -- blue to cyan
628
+ # Lower intensity, slower movement
629
+ ```
630
+
631
+ ---
632
+
633
+ ## Text Overlays
634
+
635
+ ### Scrolling Ticker
636
+ ```python
637
+ def eff_ticker(ch, co, t, text, row, speed=15, color=(80, 100, 140)):
638
+ off = int(t * speed) % max(len(text), 1)
639
+ doubled = text + " " + text
640
+ stamp(ch, co, doubled[off:off+ch.shape[1]], row, 0, color)
641
+ ```
642
+
643
+ ### Beat-Triggered Words
644
+ ```python
645
+ def eff_beat_words(ch, co, f, words, row_center=None, color=(255,240,220)):
646
+ if f.get("beat", 0) > 0:
647
+ w = random.choice(words)
648
+ r = (row_center or ch.shape[0]//2) + random.randint(-5,5)
649
+ stamp(ch, co, w, r, (ch.shape[1]-len(w))//2, color)
650
+ ```
651
+
652
+ ### Fading Message Sequence
653
+ ```python
654
+ def eff_fading_messages(ch, co, t, elapsed, messages, period=4.0, color_base=(220,220,220)):
655
+ msg_idx = int(elapsed / period) % len(messages)
656
+ phase = elapsed % period
657
+ fade = max(0, min(1.0, phase) * min(1.0, period - phase))
658
+ if fade > 0.05:
659
+ v = fade
660
+ msg = messages[msg_idx]
661
+ cr, cg, cb = [int(c * v) for c in color_base]
662
+ stamp(ch, co, msg, ch.shape[0]//2, (ch.shape[1]-len(msg))//2, (cr, cg, cb))
663
+ ```
664
+
665
+ ---
666
+
667
+ ## Screen Shake
668
+ Shift entire char/color arrays on beat:
669
+ ```python
670
+ def eff_shake(ch, co, f, x_amp=6, y_amp=3):
671
+ shake_x = int(f.get("sub",0.3)*x_amp*(random.random()-0.5)*2 + f.get("bdecay",0)*4*(random.random()-0.5)*2)
672
+ shake_y = int(f.get("bass",0.3)*y_amp*(random.random()-0.5)*2)
673
+ if abs(shake_x) > 0:
674
+ ch = np.roll(ch, shake_x, axis=1)
675
+ co = np.roll(co, shake_x, axis=1)
676
+ if abs(shake_y) > 0:
677
+ ch = np.roll(ch, shake_y, axis=0)
678
+ co = np.roll(co, shake_y, axis=0)
679
+ return ch, co
680
+ ```
681
+
682
+ ---
683
+
684
+ ## Composable Effect System
685
+
686
+ The real creative power comes from **composition**. There are three levels:
687
+
688
+ ### Level 1: Character-Level Layering
689
+
690
+ Stack multiple effects as `(chars, colors)` layers:
691
+
692
+ ```python
693
+ class LayerStack(EffectNode):
694
+ """Render effects bottom-to-top with character-level compositing."""
695
+ def add(self, effect, alpha=1.0):
696
+ """alpha < 1.0 = probabilistic override (sparse overlay)."""
697
+ self.layers.append((effect, alpha))
698
+
699
+ # Usage:
700
+ stack = LayerStack()
701
+ stack.add(bg_effect) # base — fills screen
702
+ stack.add(main_effect) # overlay on top (space chars = transparent)
703
+ stack.add(particle_effect) # sparse overlay on top of that
704
+ ch, co = stack.render(g, f, t, S)
705
+ ```
706
+
707
+ ### Level 2: Pixel-Level Blending
708
+
709
+ After rendering to canvases, blend with Photoshop-style modes:
710
+
711
+ ```python
712
+ class PixelBlendStack:
713
+ """Stack canvases with blend modes for complex compositing."""
714
+ def add(self, canvas, mode="normal", opacity=1.0)
715
+ def composite(self) -> canvas
716
+
717
+ # Usage:
718
+ pbs = PixelBlendStack()
719
+ pbs.add(canvas_a) # base
720
+ pbs.add(canvas_b, "screen", 0.7) # additive glow
721
+ pbs.add(canvas_c, "difference", 0.5) # psychedelic interference
722
+ result = pbs.composite()
723
+ ```
724
+
725
+ ### Level 3: Temporal Feedback
726
+
727
+ Feed previous frame back into current frame for recursive effects:
728
+
729
+ ```python
730
+ fb = FeedbackBuffer()
731
+ for each frame:
732
+ canvas = render_current()
733
+ canvas = fb.apply(canvas, decay=0.8, blend="screen",
734
+ transform="zoom", transform_amt=0.015, hue_shift=0.02)
735
+ ```
736
+
737
+ ### Effect Nodes — Uniform Interface
738
+
739
+ In the v2 protocol, effect nodes are used **inside** scene functions. The scene function itself returns a canvas. Effect nodes produce intermediate `(chars, colors)` that are rendered to canvas via the grid's `.render()` method or `_render_vf()`.
740
+
741
+ ```python
742
+ class EffectNode:
743
+ def render(self, g, f, t, S) -> (chars, colors)
744
+
745
+ # Concrete implementations:
746
+ class ValueFieldEffect(EffectNode):
747
+ """Wraps a value field function + hue field function + palette."""
748
+ def __init__(self, val_fn, hue_fn, pal=PAL_DEFAULT, sat=0.7)
749
+
750
+ class LambdaEffect(EffectNode):
751
+ """Wrap any (g,f,t,S) -> (ch,co) function."""
752
+ def __init__(self, fn)
753
+
754
+ class ConditionalEffect(EffectNode):
755
+ """Switch effects based on audio features."""
756
+ def __init__(self, condition, if_true, if_false=None)
757
+ ```
758
+
759
+ ### Value Field Generators (Atomic Building Blocks)
760
+
761
+ These produce float32 arrays `(rows, cols)` in range [0,1]. They are the raw visual patterns. All have signature `(g, f, t, S, **params) -> float32 array`.
762
+
763
+ #### Trigonometric Fields (sine/cosine-based)
764
+
765
+ ```python
766
+ def vf_sinefield(g, f, t, S, bri=0.5,
767
+ freq=(0.13, 0.17, 0.07, 0.09), speed=(0.5, -0.4, -0.3, 0.2)):
768
+ """Layered sine field. General purpose background/texture."""
769
+ v1 = np.sin(g.cc*freq[0] + t*speed[0]) * np.sin(g.rr*freq[1] - t*speed[1]) * 0.5 + 0.5
770
+ v2 = np.sin(g.cc*freq[2] - t*speed[2] + g.rr*freq[3]) * 0.4 + 0.5
771
+ v3 = np.sin(g.dist_n*5 + t*0.2) * 0.3 + 0.4
772
+ return np.clip((v1*0.35 + v2*0.35 + v3*0.3) * bri * (0.6 + f.get("rms",0.3)*0.6), 0, 1)
773
+
774
+ def vf_smooth_noise(g, f, t, S, octaves=3, bri=0.5):
775
+ """Multi-octave sine approximation of Perlin noise."""
776
+ val = np.zeros((g.rows, g.cols), dtype=np.float32)
777
+ for i in range(octaves):
778
+ freq = 0.05 * (2 ** i); amp = 0.5 / (i + 1)
779
+ phase = t * (0.3 + i * 0.2)
780
+ val = val + np.sin(g.cc*freq + phase) * np.cos(g.rr*freq*0.7 - phase*0.5) * amp
781
+ return np.clip(val * 0.5 + 0.5, 0, 1) * bri
782
+
783
+ def vf_rings(g, f, t, S, n_base=6, spacing_base=4):
784
+ """Concentric rings, bass-driven count and wobble."""
785
+ n = int(n_base + f.get("sub_r",0.3)*25 + f.get("bass",0.3)*10)
786
+ sp = spacing_base + f.get("bass_r",0.3)*7 + f.get("rms",0.3)*3
787
+ val = np.zeros((g.rows, g.cols), dtype=np.float32)
788
+ for ri in range(n):
789
+ rad = (ri+1)*sp + f.get("bdecay",0)*15
790
+ wobble = f.get("mid_r",0.3)*5*np.sin(g.angle*3+t*4)
791
+ rd = np.abs(g.dist - rad - wobble)
792
+ th = 1 + f.get("sub",0.3)*3
793
+ val = np.maximum(val, np.clip((1 - rd/th) * (0.4 + f.get("bass",0.3)*0.8), 0, 1))
794
+ return val
795
+
796
+ def vf_spiral(g, f, t, S, n_arms=3, tightness=2.5):
797
+ """Logarithmic spiral arms."""
798
+ val = np.zeros((g.rows, g.cols), dtype=np.float32)
799
+ for ai in range(n_arms):
800
+ offset = ai * 2*np.pi / n_arms
801
+ log_r = np.log(g.dist + 1) * tightness
802
+ arm_phase = g.angle + offset - log_r + t * 0.8
803
+ arm_val = np.clip(np.cos(arm_phase * n_arms) * 0.6 + 0.2, 0, 1)
804
+ arm_val *= (0.4 + f.get("rms",0.3)*0.6) * np.clip(1 - g.dist_n*0.5, 0.2, 1)
805
+ val = np.maximum(val, arm_val)
806
+ return val
807
+
808
+ def vf_tunnel(g, f, t, S, speed=3.0, complexity=6):
809
+ """Tunnel depth effect — infinite zoom feeling."""
810
+ tunnel_d = 1.0 / (g.dist_n + 0.1)
811
+ v1 = np.sin(tunnel_d*2 - t*speed) * 0.45 + 0.55
812
+ v2 = np.sin(g.angle*complexity + tunnel_d*1.5 - t*2) * 0.35 + 0.55
813
+ return np.clip(v1*0.5 + v2*0.5, 0, 1)
814
+
815
+ def vf_vortex(g, f, t, S, twist=3.0):
816
+ """Twisting radial pattern — distance modulates angle."""
817
+ twisted = g.angle + g.dist_n * twist * np.sin(t * 0.5)
818
+ val = np.sin(twisted * 4 - t * 2) * 0.5 + 0.5
819
+ return np.clip(val * (0.5 + f.get("bass",0.3)*0.8), 0, 1)
820
+
821
+ def vf_interference(g, f, t, S, n_waves=6):
822
+ """Overlapping sine waves creating moire patterns."""
823
+ drivers = ["mid_r", "himid_r", "bass_r", "lomid_r", "hi_r", "sub_r"]
824
+ vals = np.zeros((g.rows, g.cols), dtype=np.float32)
825
+ for i in range(min(n_waves, len(drivers))):
826
+ angle = i * np.pi / n_waves
827
+ freq = 0.06 + i * 0.03; sp = 0.5 + i * 0.3
828
+ proj = g.cc * np.cos(angle) + g.rr * np.sin(angle)
829
+ vals = vals + np.sin(proj*freq + t*sp) * f.get(drivers[i], 0.3) * 2.5
830
+ return np.clip(vals * 0.12 + 0.45, 0.1, 1)
831
+
832
+ def vf_aurora(g, f, t, S, n_bands=3):
833
+ """Horizontal aurora bands."""
834
+ val = np.zeros((g.rows, g.cols), dtype=np.float32)
835
+ for i in range(n_bands):
836
+ fr = 0.08 + i*0.04; fc = 0.012 + i*0.008
837
+ sr = 0.7 + i*0.3; sc = 0.18 + i*0.12
838
+ val = val + np.sin(g.rr*fr + t*sr) * np.sin(g.cc*fc + t*sc) * (0.6/n_bands)
839
+ return np.clip(val * (f.get("lomid_r",0.3)*3 + 0.2), 0, 0.7)
840
+
841
+ def vf_ripple(g, f, t, S, sources=None, freq=0.3, damping=0.02):
842
+ """Concentric ripples from point sources."""
843
+ if sources is None: sources = [(0.5, 0.5)]
844
+ val = np.zeros((g.rows, g.cols), dtype=np.float32)
845
+ for ry, rx in sources:
846
+ dy = g.rr - g.rows*ry; dx = g.cc - g.cols*rx
847
+ d = np.sqrt(dy**2 + dx**2)
848
+ val = val + np.sin(d*freq - t*4) * np.exp(-d*damping) * 0.5
849
+ return np.clip(val + 0.5, 0, 1)
850
+
851
+ def vf_plasma(g, f, t, S):
852
+ """Classic plasma: sum of sines at different orientations and speeds."""
853
+ v = np.sin(g.cc * 0.03 + t * 0.7) * 0.5
854
+ v = v + np.sin(g.rr * 0.04 - t * 0.5) * 0.4
855
+ v = v + np.sin((g.cc * 0.02 + g.rr * 0.03) + t * 0.3) * 0.3
856
+ v = v + np.sin(g.dist_n * 4 - t * 0.8) * 0.3
857
+ return np.clip(v * 0.5 + 0.5, 0, 1)
858
+
859
+ def vf_diamond(g, f, t, S, freq=0.15):
860
+ """Diamond/checkerboard pattern."""
861
+ val = np.abs(np.sin(g.cc * freq + t * 0.5)) * np.abs(np.sin(g.rr * freq * 1.2 - t * 0.3))
862
+ return np.clip(val * (0.6 + f.get("rms",0.3)*0.8), 0, 1)
863
+
864
+ def vf_noise_static(g, f, t, S, density=0.4):
865
+ """Random noise — different each frame. Non-deterministic."""
866
+ return np.random.random((g.rows, g.cols)).astype(np.float32) * density * (0.5 + f.get("rms",0.3)*0.5)
867
+ ```
868
+
869
+ #### Noise-Based Fields (organic, non-periodic)
870
+
871
+ These produce qualitatively different textures from sine-based fields — organic, non-repeating, without visible axis alignment. They're the foundation of high-end generative art.
872
+
873
+ ```python
874
+ def _hash2d(ix, iy):
875
+ """Integer-coordinate hash for gradient noise. Returns float32 in [0,1]."""
876
+ # Good-quality hash via large prime mixing
877
+ n = ix * 374761393 + iy * 668265263
878
+ n = (n ^ (n >> 13)) * 1274126177
879
+ return ((n ^ (n >> 16)) & 0x7fffffff).astype(np.float32) / 0x7fffffff
880
+
881
+ def _smoothstep(t):
882
+ """Hermite smoothstep: 3t^2 - 2t^3. Smooth interpolation in [0,1]."""
883
+ t = np.clip(t, 0, 1)
884
+ return t * t * (3 - 2 * t)
885
+
886
+ def _smootherstep(t):
887
+ """Perlin's improved smoothstep: 6t^5 - 15t^4 + 10t^3. C2-continuous."""
888
+ t = np.clip(t, 0, 1)
889
+ return t * t * t * (t * (t * 6 - 15) + 10)
890
+
891
+ def _value_noise_2d(x, y):
892
+ """2D value noise at arbitrary float coordinates. Returns float32 in [0,1].
893
+ x, y: float32 arrays of same shape."""
894
+ ix = np.floor(x).astype(np.int64)
895
+ iy = np.floor(y).astype(np.int64)
896
+ fx = _smootherstep(x - ix)
897
+ fy = _smootherstep(y - iy)
898
+ # 4-corner hashes
899
+ n00 = _hash2d(ix, iy)
900
+ n10 = _hash2d(ix + 1, iy)
901
+ n01 = _hash2d(ix, iy + 1)
902
+ n11 = _hash2d(ix + 1, iy + 1)
903
+ # Bilinear interpolation
904
+ nx0 = n00 * (1 - fx) + n10 * fx
905
+ nx1 = n01 * (1 - fx) + n11 * fx
906
+ return nx0 * (1 - fy) + nx1 * fy
907
+
908
+ def vf_noise(g, f, t, S, freq=0.08, speed=0.3, bri=0.7):
909
+ """Value noise. Smooth, organic, no axis alignment artifacts.
910
+ freq: spatial frequency (higher = finer detail).
911
+ speed: temporal scroll rate."""
912
+ x = g.cc * freq + t * speed
913
+ y = g.rr * freq * 0.8 - t * speed * 0.4
914
+ return np.clip(_value_noise_2d(x, y) * bri, 0, 1)
915
+
916
+ def vf_fbm(g, f, t, S, octaves=5, freq=0.06, lacunarity=2.0, gain=0.5,
917
+ speed=0.2, bri=0.8):
918
+ """Fractal Brownian Motion — octaved noise with lacunarity/gain control.
919
+ The standard building block for clouds, terrain, smoke, organic textures.
920
+
921
+ octaves: number of noise layers (more = finer detail, more cost)
922
+ freq: base spatial frequency
923
+ lacunarity: frequency multiplier per octave (2.0 = standard)
924
+ gain: amplitude multiplier per octave (0.5 = standard, <0.5 = smoother)
925
+ speed: temporal evolution rate
926
+ """
927
+ val = np.zeros((g.rows, g.cols), dtype=np.float32)
928
+ amplitude = 1.0
929
+ f_x = freq
930
+ f_y = freq * 0.85 # slight anisotropy avoids grid artifacts
931
+ for i in range(octaves):
932
+ phase = t * speed * (1 + i * 0.3)
933
+ x = g.cc * f_x + phase + i * 17.3 # offset per octave
934
+ y = g.rr * f_y - phase * 0.6 + i * 31.7
935
+ val = val + _value_noise_2d(x, y) * amplitude
936
+ amplitude *= gain
937
+ f_x *= lacunarity
938
+ f_y *= lacunarity
939
+ # Normalize to [0,1]
940
+ max_amp = (1 - gain ** octaves) / (1 - gain) if gain != 1 else octaves
941
+ return np.clip(val / max_amp * bri * (0.6 + f.get("rms", 0.3) * 0.6), 0, 1)
942
+
943
+ def vf_domain_warp(g, f, t, S, base_fn=None, warp_fn=None,
944
+ warp_strength=15.0, freq=0.06, speed=0.2):
945
+ """Domain warping — feed one noise field's output as coordinate offsets
946
+ into another noise field. Produces flowing, melting organic distortion.
947
+ Signature technique of high-end generative art (Inigo Quilez).
948
+
949
+ base_fn: value field to distort (default: fbm)
950
+ warp_fn: value field for displacement (default: noise at different freq)
951
+ warp_strength: how many grid cells to displace (higher = more warped)
952
+ """
953
+ # Warp field: displacement in x and y
954
+ wx = _value_noise_2d(g.cc * freq * 1.3 + t * speed, g.rr * freq + 7.1)
955
+ wy = _value_noise_2d(g.cc * freq + t * speed * 0.7 + 3.2, g.rr * freq * 1.1 - 11.8)
956
+ # Center warp around 0 (noise returns [0,1], shift to [-0.5, 0.5])
957
+ wx = (wx - 0.5) * warp_strength * (0.5 + f.get("rms", 0.3) * 1.0)
958
+ wy = (wy - 0.5) * warp_strength * (0.5 + f.get("bass", 0.3) * 0.8)
959
+ # Sample base field at warped coordinates
960
+ warped_cc = g.cc + wx
961
+ warped_rr = g.rr + wy
962
+ if base_fn is not None:
963
+ # Create a temporary grid-like object with warped coords
964
+ # Simplification: evaluate base_fn with modified coordinates
965
+ val = _value_noise_2d(warped_cc * freq * 0.8 + t * speed * 0.5,
966
+ warped_rr * freq * 0.7 - t * speed * 0.3)
967
+ else:
968
+ # Default: fbm at warped coordinates
969
+ val = np.zeros((g.rows, g.cols), dtype=np.float32)
970
+ amp = 1.0
971
+ fx, fy = freq * 0.8, freq * 0.7
972
+ for i in range(4):
973
+ val = val + _value_noise_2d(warped_cc * fx + t * speed * 0.5 + i * 13.7,
974
+ warped_rr * fy - t * speed * 0.3 + i * 27.3) * amp
975
+ amp *= 0.5; fx *= 2.0; fy *= 2.0
976
+ val = val / 1.875 # normalize 4-octave sum
977
+ return np.clip(val * 0.8, 0, 1)
978
+
979
+ def vf_voronoi(g, f, t, S, n_cells=20, speed=0.3, edge_width=1.5,
980
+ mode="distance", seed=42):
981
+ """Voronoi diagram as value field. Proper implementation with
982
+ nearest/second-nearest distance for cell interiors and edges.
983
+
984
+ mode: "distance" (bright at center, dark at edges),
985
+ "edge" (bright at cell boundaries),
986
+ "cell_id" (flat color per cell — use with discrete palette)
987
+ edge_width: thickness of edge highlight (for "edge" mode)
988
+ """
989
+ rng = np.random.RandomState(seed)
990
+ # Animated cell centers
991
+ cx = rng.rand(n_cells).astype(np.float32) * g.cols
992
+ cy = rng.rand(n_cells).astype(np.float32) * g.rows
993
+ vx = (rng.rand(n_cells).astype(np.float32) - 0.5) * speed * 10
994
+ vy = (rng.rand(n_cells).astype(np.float32) - 0.5) * speed * 10
995
+ cx_t = (cx + vx * np.sin(t * 0.5 + np.arange(n_cells) * 0.8)) % g.cols
996
+ cy_t = (cy + vy * np.cos(t * 0.4 + np.arange(n_cells) * 1.1)) % g.rows
997
+
998
+ # Compute nearest and second-nearest distance
999
+ d1 = np.full((g.rows, g.cols), 1e9, dtype=np.float32)
1000
+ d2 = np.full((g.rows, g.cols), 1e9, dtype=np.float32)
1001
+ id1 = np.zeros((g.rows, g.cols), dtype=np.int32)
1002
+ for i in range(n_cells):
1003
+ d = np.sqrt((g.cc - cx_t[i]) ** 2 + (g.rr - cy_t[i]) ** 2)
1004
+ mask = d < d1
1005
+ d2 = np.where(mask, d1, np.minimum(d2, d))
1006
+ id1 = np.where(mask, i, id1)
1007
+ d1 = np.minimum(d1, d)
1008
+
1009
+ if mode == "edge":
1010
+ # Edges: where d2 - d1 is small
1011
+ edge_val = np.clip(1.0 - (d2 - d1) / edge_width, 0, 1)
1012
+ return edge_val * (0.5 + f.get("rms", 0.3) * 0.8)
1013
+ elif mode == "cell_id":
1014
+ # Flat per-cell value
1015
+ return (id1.astype(np.float32) / n_cells) % 1.0
1016
+ else:
1017
+ # Distance: bright near center, dark at edges
1018
+ max_d = g.cols * 0.15
1019
+ return np.clip(1.0 - d1 / max_d, 0, 1) * (0.5 + f.get("rms", 0.3) * 0.7)
1020
+ ```
1021
+
1022
+ #### Simulation-Based Fields (emergent, evolving)
1023
+
1024
+ These use persistent state `S` to evolve patterns frame-by-frame. They produce complexity that can't be achieved with stateless math.
1025
+
1026
+ ```python
1027
+ def vf_reaction_diffusion(g, f, t, S, feed=0.055, kill=0.062,
1028
+ da=1.0, db=0.5, dt=1.0, steps_per_frame=8,
1029
+ init_mode="spots"):
1030
+ """Gray-Scott reaction-diffusion model. Produces coral, leopard spots,
1031
+ mitosis, worm-like, and labyrinthine patterns depending on feed/kill.
1032
+
1033
+ The two chemicals A and B interact:
1034
+ A + 2B → 3B (autocatalytic)
1035
+ B → P (decay)
1036
+ feed: rate A is replenished, kill: rate B decays
1037
+ Different feed/kill ratios produce radically different patterns.
1038
+
1039
+ Presets (feed, kill):
1040
+ Spots/dots: (0.055, 0.062)
1041
+ Worms/stripes: (0.046, 0.063)
1042
+ Coral/branching: (0.037, 0.060)
1043
+ Mitosis/splitting: (0.028, 0.062)
1044
+ Labyrinth/maze: (0.029, 0.057)
1045
+ Holes/negative: (0.039, 0.058)
1046
+ Chaos/unstable: (0.026, 0.051)
1047
+
1048
+ steps_per_frame: simulation steps per video frame (more = faster evolution)
1049
+ """
1050
+ key = "rd_" + str(id(g)) # unique per grid
1051
+ if key + "_a" not in S:
1052
+ # Initialize chemical fields
1053
+ A = np.ones((g.rows, g.cols), dtype=np.float32)
1054
+ B = np.zeros((g.rows, g.cols), dtype=np.float32)
1055
+ if init_mode == "spots":
1056
+ # Random seed spots
1057
+ rng = np.random.RandomState(42)
1058
+ for _ in range(max(3, g.rows * g.cols // 200)):
1059
+ r, c = rng.randint(2, g.rows - 2), rng.randint(2, g.cols - 2)
1060
+ B[r - 1:r + 2, c - 1:c + 2] = 1.0
1061
+ elif init_mode == "center":
1062
+ cr, cc = g.rows // 2, g.cols // 2
1063
+ B[cr - 3:cr + 3, cc - 3:cc + 3] = 1.0
1064
+ elif init_mode == "ring":
1065
+ mask = (g.dist_n > 0.2) & (g.dist_n < 0.3)
1066
+ B[mask] = 1.0
1067
+ S[key + "_a"] = A
1068
+ S[key + "_b"] = B
1069
+
1070
+ A = S[key + "_a"]
1071
+ B = S[key + "_b"]
1072
+
1073
+ # Audio modulation: feed/kill shift subtly with audio
1074
+ f_mod = feed + f.get("bass", 0.3) * 0.003
1075
+ k_mod = kill + f.get("hi_r", 0.3) * 0.002
1076
+
1077
+ for _ in range(steps_per_frame):
1078
+ # Laplacian via 3x3 convolution kernel
1079
+ # [0.05, 0.2, 0.05]
1080
+ # [0.2, -1.0, 0.2]
1081
+ # [0.05, 0.2, 0.05]
1082
+ pA = np.pad(A, 1, mode="wrap")
1083
+ pB = np.pad(B, 1, mode="wrap")
1084
+ lapA = (pA[:-2, 1:-1] + pA[2:, 1:-1] + pA[1:-1, :-2] + pA[1:-1, 2:]) * 0.2 \
1085
+ + (pA[:-2, :-2] + pA[:-2, 2:] + pA[2:, :-2] + pA[2:, 2:]) * 0.05 \
1086
+ - A * 1.0
1087
+ lapB = (pB[:-2, 1:-1] + pB[2:, 1:-1] + pB[1:-1, :-2] + pB[1:-1, 2:]) * 0.2 \
1088
+ + (pB[:-2, :-2] + pB[:-2, 2:] + pB[2:, :-2] + pB[2:, 2:]) * 0.05 \
1089
+ - B * 1.0
1090
+ ABB = A * B * B
1091
+ A = A + (da * lapA - ABB + f_mod * (1 - A)) * dt
1092
+ B = B + (db * lapB + ABB - (f_mod + k_mod) * B) * dt
1093
+ A = np.clip(A, 0, 1)
1094
+ B = np.clip(B, 0, 1)
1095
+
1096
+ S[key + "_a"] = A
1097
+ S[key + "_b"] = B
1098
+ # Output B chemical as value (the visible pattern)
1099
+ return np.clip(B * 2.0, 0, 1)
1100
+
1101
+ def vf_game_of_life(g, f, t, S, rule="life", birth=None, survive=None,
1102
+ steps_per_frame=1, density=0.3, fade=0.92, seed=42):
1103
+ """Cellular automaton as value field with analog fade trails.
1104
+ Grid cells are born/die by neighbor count rules. Dead cells fade
1105
+ gradually instead of snapping to black, producing ghost trails.
1106
+
1107
+ rule presets:
1108
+ "life": B3/S23 (Conway's Game of Life)
1109
+ "coral": B3/S45678 (slow crystalline growth)
1110
+ "maze": B3/S12345 (fills to labyrinth)
1111
+ "anneal": B4678/S35678 (smooth blobs)
1112
+ "day_night": B3678/S34678 (balanced growth/decay)
1113
+ Or specify birth/survive directly as sets: birth={3}, survive={2,3}
1114
+
1115
+ fade: how fast dead cells dim (0.9 = slow trails, 0.5 = fast)
1116
+ """
1117
+ presets = {
1118
+ "life": ({3}, {2, 3}),
1119
+ "coral": ({3}, {4, 5, 6, 7, 8}),
1120
+ "maze": ({3}, {1, 2, 3, 4, 5}),
1121
+ "anneal": ({4, 6, 7, 8}, {3, 5, 6, 7, 8}),
1122
+ "day_night": ({3, 6, 7, 8}, {3, 4, 6, 7, 8}),
1123
+ }
1124
+ if birth is None or survive is None:
1125
+ birth, survive = presets.get(rule, presets["life"])
1126
+
1127
+ key = "gol_" + str(id(g))
1128
+ if key + "_grid" not in S:
1129
+ rng = np.random.RandomState(seed)
1130
+ S[key + "_grid"] = (rng.random((g.rows, g.cols)) < density).astype(np.float32)
1131
+ S[key + "_display"] = S[key + "_grid"].copy()
1132
+
1133
+ grid = S[key + "_grid"]
1134
+ display = S[key + "_display"]
1135
+
1136
+ # Beat can inject random noise
1137
+ if f.get("beat", 0) > 0.5:
1138
+ inject = np.random.random((g.rows, g.cols)) < 0.02
1139
+ grid = np.clip(grid + inject.astype(np.float32), 0, 1)
1140
+
1141
+ for _ in range(steps_per_frame):
1142
+ # Count neighbors (toroidal wrap)
1143
+ padded = np.pad(grid > 0.5, 1, mode="wrap").astype(np.int8)
1144
+ neighbors = (padded[:-2, :-2] + padded[:-2, 1:-1] + padded[:-2, 2:] +
1145
+ padded[1:-1, :-2] + padded[1:-1, 2:] +
1146
+ padded[2:, :-2] + padded[2:, 1:-1] + padded[2:, 2:])
1147
+ alive = grid > 0.5
1148
+ new_alive = np.zeros_like(grid, dtype=bool)
1149
+ for b in birth:
1150
+ new_alive |= (~alive) & (neighbors == b)
1151
+ for s in survive:
1152
+ new_alive |= alive & (neighbors == s)
1153
+ grid = new_alive.astype(np.float32)
1154
+
1155
+ # Analog display: alive cells = 1.0, dead cells fade
1156
+ display = np.where(grid > 0.5, 1.0, display * fade)
1157
+ S[key + "_grid"] = grid
1158
+ S[key + "_display"] = display
1159
+ return np.clip(display, 0, 1)
1160
+
1161
+ def vf_strange_attractor(g, f, t, S, attractor="clifford",
1162
+ n_points=50000, warmup=500, bri=0.8, seed=42,
1163
+ params=None):
1164
+ """Strange attractor projected to 2D density field.
1165
+ Iterates N points through attractor equations, bins to grid,
1166
+ produces a density map. Elegant, non-repeating curves.
1167
+
1168
+ attractor presets:
1169
+ "clifford": sin(a*y) + c*cos(a*x), sin(b*x) + d*cos(b*y)
1170
+ "de_jong": sin(a*y) - cos(b*x), sin(c*x) - cos(d*y)
1171
+ "bedhead": sin(x*y/b) + cos(a*x - y), x*sin(a*y) + cos(b*x - y)
1172
+
1173
+ params: (a, b, c, d) floats — each attractor has different sweet spots.
1174
+ If None, uses time-varying defaults for animation.
1175
+ """
1176
+ key = "attr_" + attractor
1177
+ if params is None:
1178
+ # Time-varying parameters for slow morphing
1179
+ a = -1.4 + np.sin(t * 0.05) * 0.3
1180
+ b = 1.6 + np.cos(t * 0.07) * 0.2
1181
+ c = 1.0 + np.sin(t * 0.03 + 1) * 0.3
1182
+ d = 0.7 + np.cos(t * 0.04 + 2) * 0.2
1183
+ else:
1184
+ a, b, c, d = params
1185
+
1186
+ # Iterate attractor
1187
+ rng = np.random.RandomState(seed)
1188
+ x = rng.uniform(-0.1, 0.1, n_points).astype(np.float64)
1189
+ y = rng.uniform(-0.1, 0.1, n_points).astype(np.float64)
1190
+
1191
+ # Warmup iterations (reach the attractor)
1192
+ for _ in range(warmup):
1193
+ if attractor == "clifford":
1194
+ xn = np.sin(a * y) + c * np.cos(a * x)
1195
+ yn = np.sin(b * x) + d * np.cos(b * y)
1196
+ elif attractor == "de_jong":
1197
+ xn = np.sin(a * y) - np.cos(b * x)
1198
+ yn = np.sin(c * x) - np.cos(d * y)
1199
+ elif attractor == "bedhead":
1200
+ xn = np.sin(x * y / b) + np.cos(a * x - y)
1201
+ yn = x * np.sin(a * y) + np.cos(b * x - y)
1202
+ else:
1203
+ xn = np.sin(a * y) + c * np.cos(a * x)
1204
+ yn = np.sin(b * x) + d * np.cos(b * y)
1205
+ x, y = xn, yn
1206
+
1207
+ # Bin to grid
1208
+ # Find bounds
1209
+ margin = 0.1
1210
+ x_min, x_max = x.min() - margin, x.max() + margin
1211
+ y_min, y_max = y.min() - margin, y.max() + margin
1212
+
1213
+ # Map to grid coordinates
1214
+ gx = ((x - x_min) / (x_max - x_min) * (g.cols - 1)).astype(np.int32)
1215
+ gy = ((y - y_min) / (y_max - y_min) * (g.rows - 1)).astype(np.int32)
1216
+ valid = (gx >= 0) & (gx < g.cols) & (gy >= 0) & (gy < g.rows)
1217
+ gx, gy = gx[valid], gy[valid]
1218
+
1219
+ # Accumulate density
1220
+ density = np.zeros((g.rows, g.cols), dtype=np.float32)
1221
+ np.add.at(density, (gy, gx), 1.0)
1222
+
1223
+ # Log-scale density for visibility (most bins have few hits)
1224
+ density = np.log1p(density)
1225
+ mx = density.max()
1226
+ if mx > 0:
1227
+ density = density / mx
1228
+ return np.clip(density * bri * (0.5 + f.get("rms", 0.3) * 0.8), 0, 1)
1229
+ ```
1230
+
1231
+ #### SDF-Based Fields (geometric precision)
1232
+
1233
+ Signed Distance Fields produce mathematically precise shapes. Unlike sine fields (organic, blurry), SDFs give hard geometric boundaries with controllable edge softness. Combined with domain warping, they create "melting geometry" effects.
1234
+
1235
+ All SDF primitives return a **signed distance** (negative inside, positive outside). Convert to a value field with `sdf_render()`.
1236
+
1237
+ ```python
1238
+ def sdf_render(dist, edge_width=1.5, invert=False):
1239
+ """Convert signed distance to value field [0,1].
1240
+ edge_width: controls anti-aliasing / softness of the boundary.
1241
+ invert: True = bright inside shape, False = bright outside."""
1242
+ val = 1.0 - np.clip(dist / edge_width, 0, 1) if not invert else np.clip(dist / edge_width, 0, 1)
1243
+ return np.clip(val, 0, 1)
1244
+
1245
+ def sdf_glow(dist, falloff=0.05):
1246
+ """Render SDF as glowing outline — bright at boundary, fading both directions."""
1247
+ return np.clip(np.exp(-np.abs(dist) * falloff), 0, 1)
1248
+
1249
+ # --- Primitives ---
1250
+
1251
+ def sdf_circle(g, cx_frac=0.5, cy_frac=0.5, radius=0.3):
1252
+ """Circle SDF. cx/cy/radius in normalized [0,1] coordinates."""
1253
+ dx = (g.cc / g.cols - cx_frac) * (g.cols / g.rows) # aspect correction
1254
+ dy = g.rr / g.rows - cy_frac
1255
+ return np.sqrt(dx**2 + dy**2) - radius
1256
+
1257
+ def sdf_box(g, cx_frac=0.5, cy_frac=0.5, w=0.3, h=0.2, round_r=0.0):
1258
+ """Rounded rectangle SDF."""
1259
+ dx = np.abs(g.cc / g.cols - cx_frac) * (g.cols / g.rows) - w + round_r
1260
+ dy = np.abs(g.rr / g.rows - cy_frac) - h + round_r
1261
+ outside = np.sqrt(np.maximum(dx, 0)**2 + np.maximum(dy, 0)**2)
1262
+ inside = np.minimum(np.maximum(dx, dy), 0)
1263
+ return outside + inside - round_r
1264
+
1265
+ def sdf_ring(g, cx_frac=0.5, cy_frac=0.5, radius=0.3, thickness=0.03):
1266
+ """Ring (annulus) SDF."""
1267
+ d = sdf_circle(g, cx_frac, cy_frac, radius)
1268
+ return np.abs(d) - thickness
1269
+
1270
+ def sdf_line(g, x0=0.2, y0=0.5, x1=0.8, y1=0.5, thickness=0.01):
1271
+ """Line segment SDF between two points (normalized coords)."""
1272
+ ax = g.cc / g.cols * (g.cols / g.rows) - x0 * (g.cols / g.rows)
1273
+ ay = g.rr / g.rows - y0
1274
+ bx = (x1 - x0) * (g.cols / g.rows)
1275
+ by = y1 - y0
1276
+ h = np.clip((ax * bx + ay * by) / (bx * bx + by * by + 1e-10), 0, 1)
1277
+ dx = ax - bx * h
1278
+ dy = ay - by * h
1279
+ return np.sqrt(dx**2 + dy**2) - thickness
1280
+
1281
+ def sdf_triangle(g, cx=0.5, cy=0.5, size=0.25):
1282
+ """Equilateral triangle SDF centered at (cx, cy)."""
1283
+ px = (g.cc / g.cols - cx) * (g.cols / g.rows) / size
1284
+ py = (g.rr / g.rows - cy) / size
1285
+ # Equilateral triangle math
1286
+ k = np.sqrt(3.0)
1287
+ px = np.abs(px) - 1.0
1288
+ py = py + 1.0 / k
1289
+ cond = px + k * py > 0
1290
+ px2 = np.where(cond, (px - k * py) / 2.0, px)
1291
+ py2 = np.where(cond, (-k * px - py) / 2.0, py)
1292
+ px2 = np.clip(px2, -2.0, 0.0)
1293
+ return -np.sqrt(px2**2 + py2**2) * np.sign(py2) * size
1294
+
1295
+ def sdf_star(g, cx=0.5, cy=0.5, n_points=5, outer_r=0.25, inner_r=0.12):
1296
+ """Star polygon SDF — n-pointed star."""
1297
+ px = (g.cc / g.cols - cx) * (g.cols / g.rows)
1298
+ py = g.rr / g.rows - cy
1299
+ angle = np.arctan2(py, px)
1300
+ dist = np.sqrt(px**2 + py**2)
1301
+ # Modular angle for star symmetry
1302
+ wedge = 2 * np.pi / n_points
1303
+ a = np.abs((angle % wedge) - wedge / 2)
1304
+ # Interpolate radius between inner and outer
1305
+ r_at_angle = inner_r + (outer_r - inner_r) * np.clip(np.cos(a * n_points) * 0.5 + 0.5, 0, 1)
1306
+ return dist - r_at_angle
1307
+
1308
+ def sdf_heart(g, cx=0.5, cy=0.45, size=0.25):
1309
+ """Heart shape SDF."""
1310
+ px = (g.cc / g.cols - cx) * (g.cols / g.rows) / size
1311
+ py = -(g.rr / g.rows - cy) / size + 0.3 # flip y, offset
1312
+ px = np.abs(px)
1313
+ cond = (px + py) > 1.0
1314
+ d1 = np.sqrt((px - 0.25)**2 + (py - 0.75)**2) - np.sqrt(2.0) / 4.0
1315
+ d2 = np.sqrt((px + py - 1.0)**2) / np.sqrt(2.0)
1316
+ return np.where(cond, d1, d2) * size
1317
+
1318
+ # --- Combinators ---
1319
+
1320
+ def sdf_union(d1, d2):
1321
+ """Boolean union — shape is wherever either SDF is inside."""
1322
+ return np.minimum(d1, d2)
1323
+
1324
+ def sdf_intersect(d1, d2):
1325
+ """Boolean intersection — shape is where both SDFs overlap."""
1326
+ return np.maximum(d1, d2)
1327
+
1328
+ def sdf_subtract(d1, d2):
1329
+ """Boolean subtraction — d1 minus d2."""
1330
+ return np.maximum(d1, -d2)
1331
+
1332
+ def sdf_smooth_union(d1, d2, k=0.1):
1333
+ """Smooth minimum (polynomial) — blends shapes with rounded join.
1334
+ k: smoothing radius. Higher = more rounding."""
1335
+ h = np.clip(0.5 + 0.5 * (d2 - d1) / k, 0, 1)
1336
+ return d2 * (1 - h) + d1 * h - k * h * (1 - h)
1337
+
1338
+ def sdf_smooth_subtract(d1, d2, k=0.1):
1339
+ """Smooth subtraction — d1 minus d2 with rounded edge."""
1340
+ return sdf_smooth_union(d1, -d2, k)
1341
+
1342
+ def sdf_repeat(g, sdf_fn, spacing_x=0.25, spacing_y=0.25, **sdf_kwargs):
1343
+ """Tile an SDF primitive infinitely. spacing in normalized coords."""
1344
+ # Modular coordinates
1345
+ mod_cc = (g.cc / g.cols) % spacing_x - spacing_x / 2
1346
+ mod_rr = (g.rr / g.rows) % spacing_y - spacing_y / 2
1347
+ # Create modified grid-like arrays for the SDF
1348
+ # This is a simplified approach — build a temporary namespace
1349
+ class ModGrid:
1350
+ pass
1351
+ mg = ModGrid()
1352
+ mg.cc = mod_cc * g.cols; mg.rr = mod_rr * g.rows
1353
+ mg.cols = g.cols; mg.rows = g.rows
1354
+ return sdf_fn(mg, **sdf_kwargs)
1355
+
1356
+ # --- SDF as Value Field ---
1357
+
1358
+ def vf_sdf(g, f, t, S, sdf_fn=sdf_circle, edge_width=1.5, glow=False,
1359
+ glow_falloff=0.03, animate=True, **sdf_kwargs):
1360
+ """Wrap any SDF primitive as a standard vf_* value field.
1361
+ If animate=True, applies slow rotation and breathing to the shape."""
1362
+ if animate:
1363
+ sdf_kwargs.setdefault("cx_frac", 0.5)
1364
+ sdf_kwargs.setdefault("cy_frac", 0.5)
1365
+ d = sdf_fn(g, **sdf_kwargs)
1366
+ if glow:
1367
+ return sdf_glow(d, glow_falloff) * (0.5 + f.get("rms", 0.3) * 0.8)
1368
+ return sdf_render(d, edge_width) * (0.5 + f.get("rms", 0.3) * 0.8)
1369
+ ```
1370
+
1371
+ ### Hue Field Generators (Color Mapping)
1372
+
1373
+ These produce float32 hue arrays [0,1]. Independently combinable with any value field. Each is a factory returning a closure with signature `(g, f, t, S) -> float32 array`. Can also be a plain float for fixed hue.
1374
+
1375
+ ```python
1376
+ def hf_fixed(hue):
1377
+ """Single hue everywhere."""
1378
+ def fn(g, f, t, S):
1379
+ return np.full((g.rows, g.cols), hue, dtype=np.float32)
1380
+ return fn
1381
+
1382
+ def hf_angle(offset=0.0):
1383
+ """Hue mapped to angle from center — rainbow wheel."""
1384
+ def fn(g, f, t, S):
1385
+ return (g.angle / (2 * np.pi) + offset + t * 0.05) % 1.0
1386
+ return fn
1387
+
1388
+ def hf_distance(base=0.5, scale=0.02):
1389
+ """Hue mapped to distance from center."""
1390
+ def fn(g, f, t, S):
1391
+ return (base + g.dist * scale + t * 0.03) % 1.0
1392
+ return fn
1393
+
1394
+ def hf_time_cycle(speed=0.1):
1395
+ """Hue cycles uniformly over time."""
1396
+ def fn(g, f, t, S):
1397
+ return np.full((g.rows, g.cols), (t * speed) % 1.0, dtype=np.float32)
1398
+ return fn
1399
+
1400
+ def hf_audio_cent():
1401
+ """Hue follows spectral centroid — timbral color shifting."""
1402
+ def fn(g, f, t, S):
1403
+ return np.full((g.rows, g.cols), f.get("cent", 0.5) * 0.3, dtype=np.float32)
1404
+ return fn
1405
+
1406
+ def hf_gradient_h(start=0.0, end=1.0):
1407
+ """Left-to-right hue gradient."""
1408
+ def fn(g, f, t, S):
1409
+ h = np.broadcast_to(
1410
+ start + (g.cc / g.cols) * (end - start),
1411
+ (g.rows, g.cols)
1412
+ ).copy() # .copy() is CRITICAL — see troubleshooting.md
1413
+ return h % 1.0
1414
+ return fn
1415
+
1416
+ def hf_gradient_v(start=0.0, end=1.0):
1417
+ """Top-to-bottom hue gradient."""
1418
+ def fn(g, f, t, S):
1419
+ h = np.broadcast_to(
1420
+ start + (g.rr / g.rows) * (end - start),
1421
+ (g.rows, g.cols)
1422
+ ).copy()
1423
+ return h % 1.0
1424
+ return fn
1425
+
1426
+ def hf_plasma(speed=0.3):
1427
+ """Plasma-style hue field — organic color variation."""
1428
+ def fn(g, f, t, S):
1429
+ return (np.sin(g.cc*0.02 + t*speed)*0.5 + np.sin(g.rr*0.015 + t*speed*0.7)*0.5) % 1.0
1430
+ return fn
1431
+ ```
1432
+
1433
+ ---
1434
+
1435
+ ## Coordinate Transforms
1436
+
1437
+ UV-space transforms applied **before** effect evaluation. Any `vf_*` function can be rotated, zoomed, tiled, or distorted by transforming the grid coordinates it sees.
1438
+
1439
+ ### Transform Helpers
1440
+
1441
+ ```python
1442
+ def uv_rotate(g, angle):
1443
+ """Rotate UV coordinates around grid center.
1444
+ Returns (rotated_cc, rotated_rr) arrays — use in place of g.cc, g.rr."""
1445
+ cx, cy = g.cols / 2.0, g.rows / 2.0
1446
+ cos_a, sin_a = np.cos(angle), np.sin(angle)
1447
+ dx = g.cc - cx
1448
+ dy = g.rr - cy
1449
+ return cx + dx * cos_a - dy * sin_a, cy + dx * sin_a + dy * cos_a
1450
+
1451
+ def uv_scale(g, sx=1.0, sy=1.0, cx_frac=0.5, cy_frac=0.5):
1452
+ """Scale UV coordinates around a center point.
1453
+ sx, sy > 1 = zoom in (fewer repeats), < 1 = zoom out (more repeats)."""
1454
+ cx = g.cols * cx_frac; cy = g.rows * cy_frac
1455
+ return cx + (g.cc - cx) / sx, cy + (g.rr - cy) / sy
1456
+
1457
+ def uv_skew(g, kx=0.0, ky=0.0):
1458
+ """Skew UV coordinates. kx shears horizontally, ky vertically."""
1459
+ return g.cc + g.rr * kx, g.rr + g.cc * ky
1460
+
1461
+ def uv_tile(g, nx=3.0, ny=3.0, mirror=False):
1462
+ """Tile UV coordinates. nx, ny = number of repeats.
1463
+ mirror=True: alternating tiles are flipped (seamless)."""
1464
+ u = (g.cc / g.cols * nx) % 1.0
1465
+ v = (g.rr / g.rows * ny) % 1.0
1466
+ if mirror:
1467
+ flip_u = ((g.cc / g.cols * nx).astype(int) % 2) == 1
1468
+ flip_v = ((g.rr / g.rows * ny).astype(int) % 2) == 1
1469
+ u = np.where(flip_u, 1.0 - u, u)
1470
+ v = np.where(flip_v, 1.0 - v, v)
1471
+ return u * g.cols, v * g.rows
1472
+
1473
+ def uv_polar(g):
1474
+ """Convert Cartesian to polar UV. Returns (angle_as_cc, dist_as_rr).
1475
+ Use to make any linear effect radial."""
1476
+ # Angle wraps [0, cols), distance wraps [0, rows)
1477
+ return g.angle / (2 * np.pi) * g.cols, g.dist_n * g.rows
1478
+
1479
+ def uv_cartesian_from_polar(g):
1480
+ """Convert polar-addressed effects back to Cartesian.
1481
+ Treats g.cc as angle and g.rr as radius."""
1482
+ angle = g.cc / g.cols * 2 * np.pi
1483
+ radius = g.rr / g.rows
1484
+ cx, cy = g.cols / 2.0, g.rows / 2.0
1485
+ return cx + radius * np.cos(angle) * cx, cy + radius * np.sin(angle) * cy
1486
+
1487
+ def uv_twist(g, amount=2.0):
1488
+ """Twist: rotation increases with distance from center. Creates spiral distortion."""
1489
+ twist_angle = g.dist_n * amount
1490
+ return uv_rotate_raw(g.cc, g.rr, g.cols / 2, g.rows / 2, twist_angle)
1491
+
1492
+ def uv_rotate_raw(cc, rr, cx, cy, angle):
1493
+ """Raw rotation on arbitrary coordinate arrays."""
1494
+ cos_a, sin_a = np.cos(angle), np.sin(angle)
1495
+ dx = cc - cx; dy = rr - cy
1496
+ return cx + dx * cos_a - dy * sin_a, cy + dx * sin_a + dy * cos_a
1497
+
1498
+ def uv_fisheye(g, strength=1.5):
1499
+ """Fisheye / barrel distortion on UV coordinates."""
1500
+ cx, cy = g.cols / 2.0, g.rows / 2.0
1501
+ dx = (g.cc - cx) / cx
1502
+ dy = (g.rr - cy) / cy
1503
+ r = np.sqrt(dx**2 + dy**2)
1504
+ r_distort = np.power(r, strength)
1505
+ scale = np.where(r > 0, r_distort / (r + 1e-10), 1.0)
1506
+ return cx + dx * scale * cx, cy + dy * scale * cy
1507
+
1508
+ def uv_wave(g, t, freq=0.1, amp=3.0, axis="x"):
1509
+ """Sinusoidal coordinate displacement. Wobbles the UV space."""
1510
+ if axis == "x":
1511
+ return g.cc + np.sin(g.rr * freq + t * 3) * amp, g.rr
1512
+ else:
1513
+ return g.cc, g.rr + np.sin(g.cc * freq + t * 3) * amp
1514
+
1515
+ def uv_mobius(g, a=1.0, b=0.0, c=0.0, d=1.0):
1516
+ """Möbius transformation (conformal map): f(z) = (az + b) / (cz + d).
1517
+ Operates on complex plane. Produces mathematically precise, visually
1518
+ striking inversions and circular transforms."""
1519
+ cx, cy = g.cols / 2.0, g.rows / 2.0
1520
+ # Map grid to complex plane [-1, 1]
1521
+ zr = (g.cc - cx) / cx
1522
+ zi = (g.rr - cy) / cy
1523
+ # Complex division: (a*z + b) / (c*z + d)
1524
+ num_r = a * zr - 0 * zi + b # imaginary parts of a,b,c,d = 0 for real params
1525
+ num_i = a * zi + 0 * zr + 0
1526
+ den_r = c * zr - 0 * zi + d
1527
+ den_i = c * zi + 0 * zr + 0
1528
+ denom = den_r**2 + den_i**2 + 1e-10
1529
+ wr = (num_r * den_r + num_i * den_i) / denom
1530
+ wi = (num_i * den_r - num_r * den_i) / denom
1531
+ return cx + wr * cx, cy + wi * cy
1532
+ ```
1533
+
1534
+ ### Using Transforms with Value Fields
1535
+
1536
+ Transforms modify what coordinates a value field sees. Wrap the transform around the `vf_*` call:
1537
+
1538
+ ```python
1539
+ # Rotate a plasma field 45 degrees
1540
+ def vf_rotated_plasma(g, f, t, S):
1541
+ rc, rr = uv_rotate(g, np.pi / 4 + t * 0.1)
1542
+ class TG: # transformed grid
1543
+ pass
1544
+ tg = TG(); tg.cc = rc; tg.rr = rr
1545
+ tg.rows = g.rows; tg.cols = g.cols
1546
+ tg.dist_n = g.dist_n; tg.angle = g.angle; tg.dist = g.dist
1547
+ return vf_plasma(tg, f, t, S)
1548
+
1549
+ # Tile a vortex 3x3 with mirror
1550
+ def vf_tiled_vortex(g, f, t, S):
1551
+ tc, tr = uv_tile(g, 3, 3, mirror=True)
1552
+ class TG:
1553
+ pass
1554
+ tg = TG(); tg.cc = tc; tg.rr = tr
1555
+ tg.rows = g.rows; tg.cols = g.cols
1556
+ tg.dist = np.sqrt((tc - g.cols/2)**2 + (tr - g.rows/2)**2)
1557
+ tg.dist_n = tg.dist / (tg.dist.max() + 1e-10)
1558
+ tg.angle = np.arctan2(tr - g.rows/2, tc - g.cols/2)
1559
+ return vf_vortex(tg, f, t, S)
1560
+
1561
+ # Helper: create transformed grid from coordinate arrays
1562
+ def make_tgrid(g, new_cc, new_rr):
1563
+ """Build a grid-like object with transformed coordinates.
1564
+ Preserves rows/cols for sizing, recomputes polar coords."""
1565
+ class TG:
1566
+ pass
1567
+ tg = TG()
1568
+ tg.cc = new_cc; tg.rr = new_rr
1569
+ tg.rows = g.rows; tg.cols = g.cols
1570
+ cx, cy = g.cols / 2.0, g.rows / 2.0
1571
+ dx = new_cc - cx; dy = new_rr - cy
1572
+ tg.dist = np.sqrt(dx**2 + dy**2)
1573
+ tg.dist_n = tg.dist / (max(cx, cy) + 1e-10)
1574
+ tg.angle = np.arctan2(dy, dx)
1575
+ tg.dx = dx; tg.dy = dy
1576
+ tg.dx_n = dx / max(g.cols, 1)
1577
+ tg.dy_n = dy / max(g.rows, 1)
1578
+ return tg
1579
+ ```
1580
+
1581
+ ---
1582
+
1583
+ ## Temporal Coherence
1584
+
1585
+ Tools for smooth, intentional parameter evolution over time. Replaces the default pattern of either static parameters or raw audio reactivity.
1586
+
1587
+ ### Easing Functions
1588
+
1589
+ Standard animation easing curves. All take `t` in [0,1] and return [0,1]:
1590
+
1591
+ ```python
1592
+ def ease_linear(t): return t
1593
+ def ease_in_quad(t): return t * t
1594
+ def ease_out_quad(t): return t * (2 - t)
1595
+ def ease_in_out_quad(t): return np.where(t < 0.5, 2*t*t, -1 + (4-2*t)*t)
1596
+ def ease_in_cubic(t): return t**3
1597
+ def ease_out_cubic(t): return (t - 1)**3 + 1
1598
+ def ease_in_out_cubic(t):
1599
+ return np.where(t < 0.5, 4*t**3, 1 - (-2*t + 2)**3 / 2)
1600
+ def ease_in_expo(t): return np.where(t == 0, 0, 2**(10*(t-1)))
1601
+ def ease_out_expo(t): return np.where(t == 1, 1, 1 - 2**(-10*t))
1602
+ def ease_elastic(t):
1603
+ """Elastic ease-out — overshoots then settles."""
1604
+ return np.where(t == 0, 0, np.where(t == 1, 1,
1605
+ 2**(-10*t) * np.sin((t*10 - 0.75) * (2*np.pi) / 3) + 1))
1606
+ def ease_bounce(t):
1607
+ """Bounce ease-out — bounces at the end."""
1608
+ t = np.asarray(t, dtype=np.float64)
1609
+ result = np.empty_like(t)
1610
+ m1 = t < 1/2.75
1611
+ m2 = (~m1) & (t < 2/2.75)
1612
+ m3 = (~m1) & (~m2) & (t < 2.5/2.75)
1613
+ m4 = ~(m1 | m2 | m3)
1614
+ result[m1] = 7.5625 * t[m1]**2
1615
+ t2 = t[m2] - 1.5/2.75; result[m2] = 7.5625 * t2**2 + 0.75
1616
+ t3 = t[m3] - 2.25/2.75; result[m3] = 7.5625 * t3**2 + 0.9375
1617
+ t4 = t[m4] - 2.625/2.75; result[m4] = 7.5625 * t4**2 + 0.984375
1618
+ return result
1619
+ ```
1620
+
1621
+ ### Keyframe Interpolation
1622
+
1623
+ Define parameter values at specific times. Interpolates between them with easing:
1624
+
1625
+ ```python
1626
+ def keyframe(t, points, ease_fn=ease_in_out_cubic, loop=False):
1627
+ """Interpolate between keyframed values.
1628
+
1629
+ Args:
1630
+ t: current time (float, seconds)
1631
+ points: list of (time, value) tuples, sorted by time
1632
+ ease_fn: easing function for interpolation
1633
+ loop: if True, wraps around after last keyframe
1634
+
1635
+ Returns:
1636
+ interpolated value at time t
1637
+
1638
+ Example:
1639
+ twist = keyframe(t, [(0, 1.0), (5, 6.0), (10, 2.0)], ease_out_cubic)
1640
+ """
1641
+ if not points:
1642
+ return 0.0
1643
+ if loop:
1644
+ period = points[-1][0] - points[0][0]
1645
+ if period > 0:
1646
+ t = points[0][0] + (t - points[0][0]) % period
1647
+
1648
+ # Clamp to range
1649
+ if t <= points[0][0]:
1650
+ return points[0][1]
1651
+ if t >= points[-1][0]:
1652
+ return points[-1][1]
1653
+
1654
+ # Find surrounding keyframes
1655
+ for i in range(len(points) - 1):
1656
+ t0, v0 = points[i]
1657
+ t1, v1 = points[i + 1]
1658
+ if t0 <= t <= t1:
1659
+ progress = (t - t0) / (t1 - t0)
1660
+ eased = ease_fn(progress)
1661
+ return v0 + (v1 - v0) * eased
1662
+
1663
+ return points[-1][1]
1664
+
1665
+ def keyframe_array(t, points, ease_fn=ease_in_out_cubic):
1666
+ """Keyframe interpolation that works with numpy arrays as values.
1667
+ points: list of (time, np.array) tuples."""
1668
+ if t <= points[0][0]: return points[0][1].copy()
1669
+ if t >= points[-1][0]: return points[-1][1].copy()
1670
+ for i in range(len(points) - 1):
1671
+ t0, v0 = points[i]
1672
+ t1, v1 = points[i + 1]
1673
+ if t0 <= t <= t1:
1674
+ progress = ease_fn((t - t0) / (t1 - t0))
1675
+ return v0 * (1 - progress) + v1 * progress
1676
+ return points[-1][1].copy()
1677
+ ```
1678
+
1679
+ ### Value Field Morphing
1680
+
1681
+ Smooth transition between two different value fields:
1682
+
1683
+ ```python
1684
+ def vf_morph(g, f, t, S, vf_a, vf_b, t_start, t_end,
1685
+ ease_fn=ease_in_out_cubic):
1686
+ """Morph between two value fields over a time range.
1687
+
1688
+ Usage:
1689
+ val = vf_morph(g, f, t, S,
1690
+ lambda g,f,t,S: vf_plasma(g,f,t,S),
1691
+ lambda g,f,t,S: vf_vortex(g,f,t,S, twist=5),
1692
+ t_start=10.0, t_end=15.0)
1693
+ """
1694
+ if t <= t_start:
1695
+ return vf_a(g, f, t, S)
1696
+ if t >= t_end:
1697
+ return vf_b(g, f, t, S)
1698
+ progress = ease_fn((t - t_start) / (t_end - t_start))
1699
+ a = vf_a(g, f, t, S)
1700
+ b = vf_b(g, f, t, S)
1701
+ return a * (1 - progress) + b * progress
1702
+
1703
+ def vf_sequence(g, f, t, S, fields, durations, crossfade=1.0,
1704
+ ease_fn=ease_in_out_cubic):
1705
+ """Cycle through a sequence of value fields with crossfades.
1706
+
1707
+ fields: list of vf_* callables
1708
+ durations: list of float seconds per field
1709
+ crossfade: seconds of overlap between adjacent fields
1710
+ """
1711
+ total = sum(durations)
1712
+ t_local = t % total # loop
1713
+ elapsed = 0
1714
+ for i, dur in enumerate(durations):
1715
+ if t_local < elapsed + dur:
1716
+ # Current field
1717
+ base = fields[i](g, f, t, S)
1718
+ # Check if we're in a crossfade zone
1719
+ time_in = t_local - elapsed
1720
+ time_left = dur - time_in
1721
+ if time_in < crossfade and i > 0:
1722
+ # Fading in from previous
1723
+ prev = fields[(i - 1) % len(fields)](g, f, t, S)
1724
+ blend = ease_fn(time_in / crossfade)
1725
+ return prev * (1 - blend) + base * blend
1726
+ if time_left < crossfade and i < len(fields) - 1:
1727
+ # Fading out to next
1728
+ nxt = fields[(i + 1) % len(fields)](g, f, t, S)
1729
+ blend = ease_fn(1 - time_left / crossfade)
1730
+ return base * (1 - blend) + nxt * blend
1731
+ return base
1732
+ elapsed += dur
1733
+ return fields[-1](g, f, t, S)
1734
+ ```
1735
+
1736
+ ### Temporal Noise
1737
+
1738
+ 3D noise sampled at `(x, y, t)` — patterns evolve smoothly in time without per-frame discontinuities:
1739
+
1740
+ ```python
1741
+ def vf_temporal_noise(g, f, t, S, freq=0.06, t_freq=0.3, octaves=4,
1742
+ bri=0.8):
1743
+ """Noise field that evolves smoothly in time. Uses 3D noise via
1744
+ two 2D noise lookups combined with temporal interpolation.
1745
+
1746
+ Unlike vf_fbm which scrolls noise (creating directional motion),
1747
+ this morphs the pattern in-place — cells brighten and dim without
1748
+ the field moving in any direction."""
1749
+ # Two noise samples at floor/ceil of temporal coordinate
1750
+ t_scaled = t * t_freq
1751
+ t_lo = np.floor(t_scaled)
1752
+ t_frac = _smootherstep(np.full((g.rows, g.cols), t_scaled - t_lo, dtype=np.float32))
1753
+
1754
+ val_lo = np.zeros((g.rows, g.cols), dtype=np.float32)
1755
+ val_hi = np.zeros((g.rows, g.cols), dtype=np.float32)
1756
+ amp = 1.0; fx = freq
1757
+ for i in range(octaves):
1758
+ val_lo = val_lo + _value_noise_2d(
1759
+ g.cc * fx + t_lo * 7.3 + i * 13, g.rr * fx + t_lo * 3.1 + i * 29) * amp
1760
+ val_hi = val_hi + _value_noise_2d(
1761
+ g.cc * fx + (t_lo + 1) * 7.3 + i * 13, g.rr * fx + (t_lo + 1) * 3.1 + i * 29) * amp
1762
+ amp *= 0.5; fx *= 2.0
1763
+ max_amp = (1 - 0.5 ** octaves) / 0.5
1764
+ val = (val_lo * (1 - t_frac) + val_hi * t_frac) / max_amp
1765
+ return np.clip(val * bri * (0.6 + f.get("rms", 0.3) * 0.6), 0, 1)
1766
+ ```
1767
+
1768
+ ---
1769
+
1770
+ ### Combining Value Fields
1771
+
1772
+ The combinatorial explosion comes from mixing value fields with math:
1773
+
1774
+ ```python
1775
+ # Multiplication = intersection (only shows where both have brightness)
1776
+ combined = vf_plasma(g,f,t,S) * vf_vortex(g,f,t,S)
1777
+
1778
+ # Addition = union (shows both, clips at 1.0)
1779
+ combined = np.clip(vf_rings(g,f,t,S) + vf_spiral(g,f,t,S), 0, 1)
1780
+
1781
+ # Interference = beat pattern (shows XOR-like patterns)
1782
+ combined = np.abs(vf_plasma(g,f,t,S) - vf_tunnel(g,f,t,S))
1783
+
1784
+ # Modulation = one effect shapes the other
1785
+ combined = vf_rings(g,f,t,S) * (0.3 + 0.7 * vf_plasma(g,f,t,S))
1786
+
1787
+ # Maximum = shows the brightest of two effects
1788
+ combined = np.maximum(vf_spiral(g,f,t,S), vf_aurora(g,f,t,S))
1789
+ ```
1790
+
1791
+ ### Full Scene Example (v2 — Canvas Return)
1792
+
1793
+ A v2 scene function composes effects internally and returns a pixel canvas:
1794
+
1795
+ ```python
1796
+ def scene_complex(r, f, t, S):
1797
+ """v2 scene function: returns canvas (uint8 H,W,3).
1798
+ r = Renderer, f = audio features, t = time, S = persistent state dict."""
1799
+ g = r.grids["md"]
1800
+ rows, cols = g.rows, g.cols
1801
+
1802
+ # 1. Value field composition
1803
+ plasma = vf_plasma(g, f, t, S)
1804
+ vortex = vf_vortex(g, f, t, S, twist=4.0)
1805
+ combined = np.clip(plasma * 0.6 + vortex * 0.5 + plasma * vortex * 0.4, 0, 1)
1806
+
1807
+ # 2. Color from hue field
1808
+ h = (hf_angle(0.3)(g,f,t,S) * 0.5 + hf_time_cycle(0.08)(g,f,t,S) * 0.5) % 1.0
1809
+
1810
+ # 3. Render to canvas via _render_vf helper
1811
+ canvas = _render_vf(g, combined, h, sat=0.75, pal=PAL_DENSE)
1812
+
1813
+ # 4. Optional: blend a second layer
1814
+ overlay = _render_vf(r.grids["sm"], vf_rings(r.grids["sm"],f,t,S),
1815
+ hf_fixed(0.6)(r.grids["sm"],f,t,S), pal=PAL_BLOCK)
1816
+ canvas = blend_canvas(canvas, overlay, "screen", 0.4)
1817
+
1818
+ return canvas
1819
+
1820
+ # In the render_clip() loop (handled by the framework):
1821
+ # canvas = scene_fn(r, f, t, S)
1822
+ # canvas = tonemap(canvas, gamma=scene_gamma)
1823
+ # canvas = feedback.apply(canvas, ...)
1824
+ # canvas = shader_chain.apply(canvas, f=f, t=t)
1825
+ # pipe.stdin.write(canvas.tobytes())
1826
+ ```
1827
+
1828
+ Vary the **value field combo**, **hue field**, **palette**, **blend modes**, **feedback config**, and **shader chain** per section for maximum visual variety. With 12 value fields × 8 hue fields × 14 palettes × 20 blend modes × 7 feedback transforms × 38 shaders, the combinations are effectively infinite.
1829
+
1830
+ ---
1831
+
1832
+ ## Combining Effects — Creative Guide
1833
+
1834
+ The catalog above is vocabulary. Here's how to compose it into something that looks intentional.
1835
+
1836
+ ### Layering for Depth
1837
+ Every scene should have at least two layers at different grid densities:
1838
+ - **Background** (sm or xs): dense, dim texture that prevents flat black. fBM, smooth noise, or domain warp at low brightness (bri=0.15-0.25).
1839
+ - **Content** (md): the main visual — rings, voronoi, spirals, tunnel. Full brightness.
1840
+ - **Accent** (lg or xl): sparse highlights — particles, text stencil, glow pulse. Screen-blended on top.
1841
+
1842
+ ### Interesting Effect Pairs
1843
+ | Pair | Blend | Why it works |
1844
+ |------|-------|-------------|
1845
+ | fBM + voronoi edges | `screen` | Organic fills the cells, edges add structure |
1846
+ | Domain warp + plasma | `difference` | Psychedelic organic interference |
1847
+ | Tunnel + vortex | `screen` | Depth perspective + rotational energy |
1848
+ | Spiral + interference | `exclusion` | Moire patterns from different spatial frequencies |
1849
+ | Reaction-diffusion + fire | `add` | Living organic base + dynamic foreground |
1850
+ | SDF geometry + domain warp | `screen` | Clean shapes floating in organic texture |
1851
+
1852
+ ### Effects as Masks
1853
+ Any value field can be used as a mask for another effect via `mask_from_vf()`:
1854
+ - Voronoi cells masking fire (fire visible only inside cells)
1855
+ - fBM masking a solid color layer (organic color clouds)
1856
+ - SDF shapes masking a reaction-diffusion field
1857
+ - Animated iris/wipe revealing one effect over another
1858
+
1859
+ ### Inventing New Effects
1860
+ For every project, create at least one effect that isn't in the catalog:
1861
+ - **Combine two vf_* functions** with math: `np.clip(vf_fbm(...) * vf_rings(...), 0, 1)`
1862
+ - **Apply coordinate transforms** before evaluation: `vf_plasma(twisted_grid, ...)`
1863
+ - **Use one field to modulate another's parameters**: `vf_spiral(..., tightness=2 + vf_fbm(...) * 5)`
1864
+ - **Stack time offsets**: render the same field at `t` and `t - 0.5`, difference-blend for motion trails
1865
+ - **Mirror a value field** through an SDF boundary for kaleidoscopic geometry
skills/.archive/ascii-video/references/inputs.md ADDED
@@ -0,0 +1,685 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Input Sources
2
+
3
+ > **See also:** architecture.md · effects.md · scenes.md · shaders.md · optimization.md · troubleshooting.md
4
+
5
+ ## Audio Analysis
6
+
7
+ ### Loading
8
+
9
+ ```python
10
+ tmp = tempfile.mktemp(suffix=".wav")
11
+ subprocess.run(["ffmpeg", "-y", "-i", input_path, "-ac", "1", "-ar", "22050",
12
+ "-sample_fmt", "s16", tmp], capture_output=True, check=True)
13
+ with wave.open(tmp) as wf:
14
+ sr = wf.getframerate()
15
+ raw = wf.readframes(wf.getnframes())
16
+ samples = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0
17
+ ```
18
+
19
+ ### Per-Frame FFT
20
+
21
+ ```python
22
+ hop = sr // fps # samples per frame
23
+ win = hop * 2 # analysis window (2x hop for overlap)
24
+ window = np.hanning(win)
25
+ freqs = rfftfreq(win, 1.0 / sr)
26
+
27
+ bands = {
28
+ "sub": (freqs >= 20) & (freqs < 80),
29
+ "bass": (freqs >= 80) & (freqs < 250),
30
+ "lomid": (freqs >= 250) & (freqs < 500),
31
+ "mid": (freqs >= 500) & (freqs < 2000),
32
+ "himid": (freqs >= 2000)& (freqs < 6000),
33
+ "hi": (freqs >= 6000),
34
+ }
35
+ ```
36
+
37
+ For each frame: extract chunk, apply window, FFT, compute band energies.
38
+
39
+ ### Feature Set
40
+
41
+ | Feature | Formula | Controls |
42
+ |---------|---------|----------|
43
+ | `rms` | `sqrt(mean(chunk²))` | Overall loudness/energy |
44
+ | `sub`..`hi` | `sqrt(mean(band_magnitudes²))` | Per-band energy |
45
+ | `centroid` | `sum(freq*mag) / sum(mag)` | Brightness/timbre |
46
+ | `flatness` | `geomean(mag) / mean(mag)` | Noise vs tone |
47
+ | `flux` | `sum(max(0, mag - prev_mag))` | Transient strength |
48
+ | `sub_r`..`hi_r` | `band / sum(all_bands)` | Spectral shape (volume-independent) |
49
+ | `cent_d` | `abs(gradient(centroid))` | Timbral change rate |
50
+ | `beat` | Flux peak detection | Binary beat onset |
51
+ | `bdecay` | Exponential decay from beats | Smooth beat pulse (0→1→0) |
52
+
53
+ **Band ratios are critical** — they decouple spectral shape from volume, so a quiet bass section and a loud bass section both read as "bassy" rather than just "loud" vs "quiet".
54
+
55
+ ### Smoothing
56
+
57
+ EMA prevents visual jitter:
58
+
59
+ ```python
60
+ def ema(arr, alpha):
61
+ out = np.empty_like(arr); out[0] = arr[0]
62
+ for i in range(1, len(arr)):
63
+ out[i] = alpha * arr[i] + (1 - alpha) * out[i-1]
64
+ return out
65
+
66
+ # Slow-moving features (alpha=0.12): centroid, flatness, band ratios, cent_d
67
+ # Fast-moving features (alpha=0.3): rms, flux, raw bands
68
+ ```
69
+
70
+ ### Beat Detection
71
+
72
+ ```python
73
+ flux_smooth = np.convolve(flux, np.ones(5)/5, mode="same")
74
+ peaks, _ = signal.find_peaks(flux_smooth, height=0.15, distance=fps//5, prominence=0.05)
75
+
76
+ beat = np.zeros(n_frames)
77
+ bdecay = np.zeros(n_frames, dtype=np.float32)
78
+ for p in peaks:
79
+ beat[p] = 1.0
80
+ for d in range(fps // 2):
81
+ if p + d < n_frames:
82
+ bdecay[p + d] = max(bdecay[p + d], math.exp(-d * 2.5 / (fps // 2)))
83
+ ```
84
+
85
+ `bdecay` gives smooth 0→1→0 pulse per beat, decaying over ~0.5s. Use for flash/glitch/mirror triggers.
86
+
87
+ ### Normalization
88
+
89
+ After computing all frames, normalize each feature to 0-1:
90
+
91
+ ```python
92
+ for k in features:
93
+ a = features[k]
94
+ lo, hi = a.min(), a.max()
95
+ features[k] = (a - lo) / (hi - lo + 1e-10)
96
+ ```
97
+
98
+ ## Video Sampling
99
+
100
+ ### Frame Extraction
101
+
102
+ ```python
103
+ # Method 1: ffmpeg pipe (memory efficient)
104
+ cmd = ["ffmpeg", "-i", input_video, "-f", "rawvideo", "-pix_fmt", "rgb24",
105
+ "-s", f"{target_w}x{target_h}", "-r", str(fps), "-"]
106
+ pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
107
+ frame_size = target_w * target_h * 3
108
+ for fi in range(n_frames):
109
+ raw = pipe.stdout.read(frame_size)
110
+ if len(raw) < frame_size: break
111
+ frame = np.frombuffer(raw, dtype=np.uint8).reshape(target_h, target_w, 3)
112
+ # process frame...
113
+
114
+ # Method 2: OpenCV (if available)
115
+ cap = cv2.VideoCapture(input_video)
116
+ ```
117
+
118
+ ### Luminance-to-Character Mapping
119
+
120
+ Convert video pixels to ASCII characters based on brightness:
121
+
122
+ ```python
123
+ def frame_to_ascii(frame_rgb, grid, pal=PAL_DEFAULT):
124
+ """Convert video frame to character + color arrays."""
125
+ rows, cols = grid.rows, grid.cols
126
+ # Resize frame to grid dimensions
127
+ small = np.array(Image.fromarray(frame_rgb).resize((cols, rows), Image.LANCZOS))
128
+ # Luminance
129
+ lum = (0.299 * small[:,:,0] + 0.587 * small[:,:,1] + 0.114 * small[:,:,2]) / 255.0
130
+ # Map to chars
131
+ chars = val2char(lum, lum > 0.02, pal)
132
+ # Colors: use source pixel colors, scaled by luminance for visibility
133
+ colors = np.clip(small * np.clip(lum[:,:,None] * 1.5 + 0.3, 0.3, 1), 0, 255).astype(np.uint8)
134
+ return chars, colors
135
+ ```
136
+
137
+ ### Edge-Weighted Character Mapping
138
+
139
+ Use edge detection for more detail in contour regions:
140
+
141
+ ```python
142
+ def frame_to_ascii_edges(frame_rgb, grid, pal=PAL_DEFAULT, edge_pal=PAL_BOX):
143
+ gray = np.mean(frame_rgb, axis=2)
144
+ small_gray = resize(gray, (grid.rows, grid.cols))
145
+ lum = small_gray / 255.0
146
+
147
+ # Sobel edge detection
148
+ gx = np.abs(small_gray[:, 2:] - small_gray[:, :-2])
149
+ gy = np.abs(small_gray[2:, :] - small_gray[:-2, :])
150
+ edge = np.zeros_like(small_gray)
151
+ edge[:, 1:-1] += gx; edge[1:-1, :] += gy
152
+ edge = np.clip(edge / edge.max(), 0, 1)
153
+
154
+ # Edge regions get box drawing chars, flat regions get brightness chars
155
+ is_edge = edge > 0.15
156
+ chars = val2char(lum, lum > 0.02, pal)
157
+ edge_chars = val2char(edge, is_edge, edge_pal)
158
+ chars[is_edge] = edge_chars[is_edge]
159
+
160
+ return chars, colors
161
+ ```
162
+
163
+ ### Motion Detection
164
+
165
+ Detect pixel changes between frames for motion-reactive effects:
166
+
167
+ ```python
168
+ prev_frame = None
169
+ def compute_motion(frame):
170
+ global prev_frame
171
+ if prev_frame is None:
172
+ prev_frame = frame.astype(np.float32)
173
+ return np.zeros(frame.shape[:2])
174
+ diff = np.abs(frame.astype(np.float32) - prev_frame).mean(axis=2)
175
+ prev_frame = frame.astype(np.float32) * 0.7 + prev_frame * 0.3 # smoothed
176
+ return np.clip(diff / 30.0, 0, 1) # normalized motion map
177
+ ```
178
+
179
+ Use motion map to drive particle emission, glitch intensity, or character density.
180
+
181
+ ### Video Feature Extraction
182
+
183
+ Per-frame features analogous to audio features, for driving effects:
184
+
185
+ ```python
186
+ def analyze_video_frame(frame_rgb):
187
+ gray = np.mean(frame_rgb, axis=2)
188
+ return {
189
+ "brightness": gray.mean() / 255.0,
190
+ "contrast": gray.std() / 128.0,
191
+ "edge_density": compute_edge_density(gray),
192
+ "motion": compute_motion(frame_rgb).mean(),
193
+ "dominant_hue": compute_dominant_hue(frame_rgb),
194
+ "color_variance": compute_color_variance(frame_rgb),
195
+ }
196
+ ```
197
+
198
+ ## Image Sequence
199
+
200
+ ### Static Image to ASCII
201
+
202
+ Same as single video frame conversion. For animated sequences:
203
+
204
+ ```python
205
+ import glob
206
+ frames = sorted(glob.glob("frames/*.png"))
207
+ for fi, path in enumerate(frames):
208
+ img = np.array(Image.open(path).resize((VW, VH)))
209
+ chars, colors = frame_to_ascii(img, grid, pal)
210
+ ```
211
+
212
+ ### Image as Texture Source
213
+
214
+ Use an image as a background texture that effects modulate:
215
+
216
+ ```python
217
+ def load_texture(path, grid):
218
+ img = np.array(Image.open(path).resize((grid.cols, grid.rows)))
219
+ lum = np.mean(img, axis=2) / 255.0
220
+ return lum, img # luminance for char mapping, RGB for colors
221
+ ```
222
+
223
+ ## Text / Lyrics
224
+
225
+ ### SRT Parsing
226
+
227
+ ```python
228
+ import re
229
+ def parse_srt(path):
230
+ """Returns [(start_sec, end_sec, text), ...]"""
231
+ entries = []
232
+ with open(path) as f:
233
+ content = f.read()
234
+ blocks = content.strip().split("\n\n")
235
+ for block in blocks:
236
+ lines = block.strip().split("\n")
237
+ if len(lines) >= 3:
238
+ times = lines[1]
239
+ m = re.match(r"(\d+):(\d+):(\d+),(\d+) --> (\d+):(\d+):(\d+),(\d+)", times)
240
+ if m:
241
+ g = [int(x) for x in m.groups()]
242
+ start = g[0]*3600 + g[1]*60 + g[2] + g[3]/1000
243
+ end = g[4]*3600 + g[5]*60 + g[6] + g[7]/1000
244
+ text = " ".join(lines[2:])
245
+ entries.append((start, end, text))
246
+ return entries
247
+ ```
248
+
249
+ ### Lyrics Display Modes
250
+
251
+ - **Typewriter**: characters appear left-to-right over the time window
252
+ - **Fade-in**: whole line fades from dark to bright
253
+ - **Flash**: appear instantly on beat, fade out
254
+ - **Scatter**: characters start at random positions, converge to final position
255
+ - **Wave**: text follows a sine wave path
256
+
257
+ ```python
258
+ def lyrics_typewriter(ch, co, text, row, col, t, t_start, t_end, color):
259
+ """Reveal characters progressively over time window."""
260
+ progress = np.clip((t - t_start) / (t_end - t_start), 0, 1)
261
+ n_visible = int(len(text) * progress)
262
+ stamp(ch, co, text[:n_visible], row, col, color)
263
+ ```
264
+
265
+ ## Generative (No Input)
266
+
267
+ For pure generative ASCII art, the "features" dict is synthesized from time:
268
+
269
+ ```python
270
+ def synthetic_features(t, bpm=120):
271
+ """Generate audio-like features from time alone."""
272
+ beat_period = 60.0 / bpm
273
+ beat_phase = (t % beat_period) / beat_period
274
+ return {
275
+ "rms": 0.5 + 0.3 * math.sin(t * 0.5),
276
+ "bass": 0.5 + 0.4 * math.sin(t * 2 * math.pi / beat_period),
277
+ "sub": 0.3 + 0.3 * math.sin(t * 0.8),
278
+ "mid": 0.4 + 0.3 * math.sin(t * 1.3),
279
+ "hi": 0.3 + 0.2 * math.sin(t * 2.1),
280
+ "cent": 0.5 + 0.2 * math.sin(t * 0.3),
281
+ "flat": 0.4,
282
+ "flux": 0.3 + 0.2 * math.sin(t * 3),
283
+ "beat": 1.0 if beat_phase < 0.05 else 0.0,
284
+ "bdecay": max(0, 1.0 - beat_phase * 4),
285
+ # ratios
286
+ "sub_r": 0.2, "bass_r": 0.25, "lomid_r": 0.15,
287
+ "mid_r": 0.2, "himid_r": 0.12, "hi_r": 0.08,
288
+ "cent_d": 0.1,
289
+ }
290
+ ```
291
+
292
+ ## TTS Integration
293
+
294
+ For narrated videos (testimonials, quotes, storytelling), generate speech audio per segment and mix with background music.
295
+
296
+ ### ElevenLabs Voice Generation
297
+
298
+ ```python
299
+ import requests, time, os
300
+
301
+ def generate_tts(text, voice_id, api_key, output_path, model="eleven_multilingual_v2"):
302
+ """Generate TTS audio via ElevenLabs API. Streams response to disk."""
303
+ # Skip if already generated (idempotent re-runs)
304
+ if os.path.exists(output_path) and os.path.getsize(output_path) > 1000:
305
+ return
306
+
307
+ url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
308
+ headers = {"xi-api-key": api_key, "Content-Type": "application/json"}
309
+ data = {
310
+ "text": text,
311
+ "model_id": model,
312
+ "voice_settings": {
313
+ "stability": 0.65,
314
+ "similarity_boost": 0.80,
315
+ "style": 0.15,
316
+ "use_speaker_boost": True,
317
+ },
318
+ }
319
+ resp = requests.post(url, json=data, headers=headers, stream=True)
320
+ resp.raise_for_status()
321
+ with open(output_path, "wb") as f:
322
+ for chunk in resp.iter_content(chunk_size=4096):
323
+ f.write(chunk)
324
+ time.sleep(0.3) # rate limit: avoid 429s on batch generation
325
+ ```
326
+
327
+ Voice settings notes:
328
+ - `stability` 0.65 gives natural variation without drift. Lower (0.3-0.5) for more expressive reads, higher (0.7-0.9) for monotone/narration.
329
+ - `similarity_boost` 0.80 keeps it close to the voice profile. Lower for more generic sound.
330
+ - `style` 0.15 adds slight stylistic variation. Keep low (0-0.2) for straightforward reads.
331
+ - `use_speaker_boost` True improves clarity at the cost of slightly more processing time.
332
+
333
+ ### Voice Pool
334
+
335
+ ElevenLabs has ~20 built-in voices. Use multiple voices for variety across quotes. Reference pool:
336
+
337
+ ```python
338
+ VOICE_POOL = [
339
+ ("JBFqnCBsd6RMkjVDRZzb", "George"),
340
+ ("nPczCjzI2devNBz1zQrb", "Brian"),
341
+ ("pqHfZKP75CvOlQylNhV4", "Bill"),
342
+ ("CwhRBWXzGAHq8TQ4Fs17", "Roger"),
343
+ ("cjVigY5qzO86Huf0OWal", "Eric"),
344
+ ("onwK4e9ZLuTAKqWW03F9", "Daniel"),
345
+ ("IKne3meq5aSn9XLyUdCD", "Charlie"),
346
+ ("iP95p4xoKVk53GoZ742B", "Chris"),
347
+ ("bIHbv24MWmeRgasZH58o", "Will"),
348
+ ("TX3LPaxmHKxFdv7VOQHJ", "Liam"),
349
+ ("SAz9YHcvj6GT2YYXdXww", "River"),
350
+ ("EXAVITQu4vr4xnSDxMaL", "Sarah"),
351
+ ("Xb7hH8MSUJpSbSDYk0k2", "Alice"),
352
+ ("pFZP5JQG7iQjIQuC4Bku", "Lily"),
353
+ ("XrExE9yKIg1WjnnlVkGX", "Matilda"),
354
+ ("FGY2WhTYpPnrIDTdsKH5", "Laura"),
355
+ ("SOYHLrjzK2X1ezoPC6cr", "Harry"),
356
+ ("hpp4J3VqNfWAUOO0d1Us", "Bella"),
357
+ ("N2lVS1w4EtoT3dr4eOWO", "Callum"),
358
+ ("cgSgspJ2msm6clMCkdW9", "Jessica"),
359
+ ("pNInz6obpgDQGcFmaJgB", "Adam"),
360
+ ]
361
+ ```
362
+
363
+ ### Voice Assignment
364
+
365
+ Shuffle deterministically so re-runs produce the same voice mapping:
366
+
367
+ ```python
368
+ import random as _rng
369
+
370
+ def assign_voices(n_quotes, voice_pool, seed=42):
371
+ """Assign a different voice to each quote, cycling if needed."""
372
+ r = _rng.Random(seed)
373
+ ids = [v[0] for v in voice_pool]
374
+ r.shuffle(ids)
375
+ return [ids[i % len(ids)] for i in range(n_quotes)]
376
+ ```
377
+
378
+ ### Pronunciation Control
379
+
380
+ TTS text must be separate from display text. The display text has line breaks for visual layout; the TTS text is a flat sentence with phonetic fixes.
381
+
382
+ Common fixes:
383
+ - Brand names: spell phonetically ("Nous" -> "Noose", "nginx" -> "engine-x")
384
+ - Abbreviations: expand ("API" -> "A P I", "CLI" -> "C L I")
385
+ - Technical terms: add phonetic hints
386
+ - Punctuation for pacing: periods create pauses, commas create slight pauses
387
+
388
+ ```python
389
+ # Display text: line breaks control visual layout
390
+ QUOTES = [
391
+ ("It can do far more than the Claws,\nand you don't need to buy a Mac Mini.\nNous Research has a winner here.", "Brian Roemmele"),
392
+ ]
393
+
394
+ # TTS text: flat, phonetically corrected for speech
395
+ QUOTES_TTS = [
396
+ "It can do far more than the Claws, and you don't need to buy a Mac Mini. Noose Research has a winner here.",
397
+ ]
398
+ # Keep both arrays in sync -- same indices
399
+ ```
400
+
401
+ ### Audio Pipeline
402
+
403
+ 1. Generate individual TTS clips (MP3 per quote, skipping existing)
404
+ 2. Convert each to WAV (mono, 22050 Hz) for duration measurement and concatenation
405
+ 3. Calculate timing: intro pad + speech + gaps + outro pad = target duration
406
+ 4. Concatenate into single TTS track with silence padding
407
+ 5. Mix with background music
408
+
409
+ ```python
410
+ def build_tts_track(tts_clips, target_duration, intro_pad=5.0, outro_pad=4.0):
411
+ """Concatenate TTS clips with calculated gaps, pad to target duration.
412
+
413
+ Returns:
414
+ timing: list of (start_time, end_time, quote_index) tuples
415
+ """
416
+ sr = 22050
417
+
418
+ # Convert MP3s to WAV for duration and sample-level concatenation
419
+ durations = []
420
+ for clip in tts_clips:
421
+ wav = clip.replace(".mp3", ".wav")
422
+ subprocess.run(
423
+ ["ffmpeg", "-y", "-i", clip, "-ac", "1", "-ar", str(sr),
424
+ "-sample_fmt", "s16", wav],
425
+ capture_output=True, check=True)
426
+ result = subprocess.run(
427
+ ["ffprobe", "-v", "error", "-show_entries", "format=duration",
428
+ "-of", "csv=p=0", wav],
429
+ capture_output=True, text=True)
430
+ durations.append(float(result.stdout.strip()))
431
+
432
+ # Calculate gap to fill target duration
433
+ total_speech = sum(durations)
434
+ n_gaps = len(tts_clips) - 1
435
+ remaining = target_duration - total_speech - intro_pad - outro_pad
436
+ gap = max(1.0, remaining / max(1, n_gaps))
437
+
438
+ # Build timing and concatenate samples
439
+ timing = []
440
+ t = intro_pad
441
+ all_audio = [np.zeros(int(sr * intro_pad), dtype=np.int16)]
442
+
443
+ for i, dur in enumerate(durations):
444
+ wav = tts_clips[i].replace(".mp3", ".wav")
445
+ with wave.open(wav) as wf:
446
+ samples = np.frombuffer(wf.readframes(wf.getnframes()), dtype=np.int16)
447
+ timing.append((t, t + dur, i))
448
+ all_audio.append(samples)
449
+ t += dur
450
+ if i < len(tts_clips) - 1:
451
+ all_audio.append(np.zeros(int(sr * gap), dtype=np.int16))
452
+ t += gap
453
+
454
+ all_audio.append(np.zeros(int(sr * outro_pad), dtype=np.int16))
455
+
456
+ # Pad or trim to exactly target_duration
457
+ full = np.concatenate(all_audio)
458
+ target_samples = int(sr * target_duration)
459
+ if len(full) < target_samples:
460
+ full = np.pad(full, (0, target_samples - len(full)))
461
+ else:
462
+ full = full[:target_samples]
463
+
464
+ # Write concatenated TTS track
465
+ with wave.open("tts_full.wav", "w") as wf:
466
+ wf.setnchannels(1)
467
+ wf.setsampwidth(2)
468
+ wf.setframerate(sr)
469
+ wf.writeframes(full.tobytes())
470
+
471
+ return timing
472
+ ```
473
+
474
+ ### Audio Mixing
475
+
476
+ Mix TTS (center) with background music (wide stereo, low volume). The filter chain:
477
+ 1. TTS mono duplicated to both channels (centered)
478
+ 2. BGM loudness-normalized, volume reduced to 15%, stereo widened with `extrastereo`
479
+ 3. Mixed together with dropout transition for smooth endings
480
+
481
+ ```python
482
+ def mix_audio(tts_path, bgm_path, output_path, bgm_volume=0.15):
483
+ """Mix TTS centered with BGM panned wide stereo."""
484
+ filter_complex = (
485
+ # TTS: mono -> stereo center
486
+ "[0:a]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=mono,"
487
+ "pan=stereo|c0=c0|c1=c0[tts];"
488
+ # BGM: normalize loudness, reduce volume, widen stereo
489
+ f"[1:a]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo,"
490
+ f"loudnorm=I=-16:TP=-1.5:LRA=11,"
491
+ f"volume={bgm_volume},"
492
+ f"extrastereo=m=2.5[bgm];"
493
+ # Mix with smooth dropout at end
494
+ "[tts][bgm]amix=inputs=2:duration=longest:dropout_transition=3,"
495
+ "aformat=sample_fmts=s16:sample_rates=44100:channel_layouts=stereo[out]"
496
+ )
497
+ cmd = [
498
+ "ffmpeg", "-y",
499
+ "-i", tts_path,
500
+ "-i", bgm_path,
501
+ "-filter_complex", filter_complex,
502
+ "-map", "[out]", output_path,
503
+ ]
504
+ subprocess.run(cmd, capture_output=True, check=True)
505
+ ```
506
+
507
+ ### Per-Quote Visual Style
508
+
509
+ Cycle through visual presets per quote for variety. Each preset defines a background effect, color scheme, and text color:
510
+
511
+ ```python
512
+ QUOTE_STYLES = [
513
+ {"hue": 0.08, "accent": 0.7, "bg": "spiral", "text_rgb": (255, 220, 140)}, # warm gold
514
+ {"hue": 0.55, "accent": 0.6, "bg": "rings", "text_rgb": (180, 220, 255)}, # cool blue
515
+ {"hue": 0.75, "accent": 0.7, "bg": "wave", "text_rgb": (220, 180, 255)}, # purple
516
+ {"hue": 0.35, "accent": 0.6, "bg": "matrix", "text_rgb": (140, 255, 180)}, # green
517
+ {"hue": 0.95, "accent": 0.8, "bg": "fire", "text_rgb": (255, 180, 160)}, # red/coral
518
+ {"hue": 0.12, "accent": 0.5, "bg": "interference", "text_rgb": (255, 240, 200)}, # amber
519
+ {"hue": 0.60, "accent": 0.7, "bg": "tunnel", "text_rgb": (160, 210, 255)}, # cyan
520
+ {"hue": 0.45, "accent": 0.6, "bg": "aurora", "text_rgb": (180, 255, 220)}, # teal
521
+ ]
522
+
523
+ style = QUOTE_STYLES[quote_index % len(QUOTE_STYLES)]
524
+ ```
525
+
526
+ This guarantees no two adjacent quotes share the same look, even without randomness.
527
+
528
+ ### Typewriter Text Rendering
529
+
530
+ Display quote text character-by-character synced to speech progress. Recently revealed characters are brighter, creating a "just typed" glow:
531
+
532
+ ```python
533
+ def render_typewriter(ch, co, lines, block_start, cols, progress, total_chars, text_rgb, t):
534
+ """Overlay typewriter text onto character/color grids.
535
+ progress: 0.0 (nothing visible) to 1.0 (all text visible)."""
536
+ chars_visible = int(total_chars * min(1.0, progress * 1.2)) # slight overshoot for snappy feel
537
+ tr, tg, tb = text_rgb
538
+ char_count = 0
539
+ for li, line in enumerate(lines):
540
+ row = block_start + li
541
+ col = (cols - len(line)) // 2
542
+ for ci, c in enumerate(line):
543
+ if char_count < chars_visible:
544
+ age = chars_visible - char_count
545
+ bri_factor = min(1.0, 0.5 + 0.5 / (1 + age * 0.015)) # newer = brighter
546
+ hue_shift = math.sin(char_count * 0.3 + t * 2) * 0.05
547
+ stamp(ch, co, c, row, col + ci,
548
+ (int(min(255, tr * bri_factor * (1.0 + hue_shift))),
549
+ int(min(255, tg * bri_factor)),
550
+ int(min(255, tb * bri_factor * (1.0 - hue_shift)))))
551
+ char_count += 1
552
+
553
+ # Blinking cursor at insertion point
554
+ if progress < 1.0 and int(t * 3) % 2 == 0:
555
+ # Find cursor position (char_count == chars_visible)
556
+ cc = 0
557
+ for li, line in enumerate(lines):
558
+ for ci, c in enumerate(line):
559
+ if cc == chars_visible:
560
+ stamp(ch, co, "\u258c", block_start + li,
561
+ (cols - len(line)) // 2 + ci, (255, 220, 100))
562
+ return
563
+ cc += 1
564
+ ```
565
+
566
+ ### Feature Analysis on Mixed Audio
567
+
568
+ Run the standard audio analysis (FFT, beat detection) on the final mixed track so visual effects react to both TTS and music:
569
+
570
+ ```python
571
+ # Analyze mixed_final.wav (not individual tracks)
572
+ features = analyze_audio("mixed_final.wav", fps=24)
573
+ ```
574
+
575
+ Visuals pulse with both the music beats and the speech energy.
576
+
577
+ ---
578
+
579
+ ## Audio-Video Sync Verification
580
+
581
+ After rendering, verify that visual beat markers align with actual audio beats. Drift accumulates from frame timing errors, ffmpeg concat boundaries, and rounding in `fi / fps`.
582
+
583
+ ### Beat Timestamp Extraction
584
+
585
+ ```python
586
+ def extract_beat_timestamps(features, fps, threshold=0.5):
587
+ """Extract timestamps where beat feature exceeds threshold."""
588
+ beat = features["beat"]
589
+ timestamps = []
590
+ for fi in range(len(beat)):
591
+ if beat[fi] > threshold:
592
+ timestamps.append(fi / fps)
593
+ return timestamps
594
+
595
+ def extract_visual_beat_timestamps(video_path, fps, brightness_jump=30):
596
+ """Detect visual beats by brightness jumps between consecutive frames.
597
+ Returns timestamps where mean brightness increases by more than threshold."""
598
+ import subprocess
599
+ cmd = ["ffmpeg", "-i", video_path, "-f", "rawvideo", "-pix_fmt", "gray", "-"]
600
+ proc = subprocess.run(cmd, capture_output=True)
601
+ frames = np.frombuffer(proc.stdout, dtype=np.uint8)
602
+ # Infer frame dimensions from total byte count
603
+ n_pixels = len(frames)
604
+ # For 1080p: 1920*1080 pixels per frame
605
+ # Auto-detect from video metadata is more robust:
606
+ probe = subprocess.run(
607
+ ["ffprobe", "-v", "error", "-select_streams", "v:0",
608
+ "-show_entries", "stream=width,height",
609
+ "-of", "csv=p=0", video_path],
610
+ capture_output=True, text=True)
611
+ w, h = map(int, probe.stdout.strip().split(","))
612
+ ppf = w * h # pixels per frame
613
+ n_frames = n_pixels // ppf
614
+ frames = frames[:n_frames * ppf].reshape(n_frames, ppf)
615
+ means = frames.mean(axis=1)
616
+
617
+ timestamps = []
618
+ for i in range(1, len(means)):
619
+ if means[i] - means[i-1] > brightness_jump:
620
+ timestamps.append(i / fps)
621
+ return timestamps
622
+ ```
623
+
624
+ ### Sync Report
625
+
626
+ ```python
627
+ def sync_report(audio_beats, visual_beats, tolerance_ms=50):
628
+ """Compare audio beat timestamps to visual beat timestamps.
629
+
630
+ Args:
631
+ audio_beats: list of timestamps (seconds) from audio analysis
632
+ visual_beats: list of timestamps (seconds) from video brightness analysis
633
+ tolerance_ms: max acceptable drift in milliseconds
634
+
635
+ Returns:
636
+ dict with matched/unmatched/drift statistics
637
+ """
638
+ tolerance = tolerance_ms / 1000.0
639
+ matched = []
640
+ unmatched_audio = []
641
+ unmatched_visual = list(visual_beats)
642
+
643
+ for at in audio_beats:
644
+ best_match = None
645
+ best_delta = float("inf")
646
+ for vt in unmatched_visual:
647
+ delta = abs(at - vt)
648
+ if delta < best_delta:
649
+ best_delta = delta
650
+ best_match = vt
651
+ if best_match is not None and best_delta < tolerance:
652
+ matched.append({"audio": at, "visual": best_match, "drift_ms": best_delta * 1000})
653
+ unmatched_visual.remove(best_match)
654
+ else:
655
+ unmatched_audio.append(at)
656
+
657
+ drifts = [m["drift_ms"] for m in matched]
658
+ return {
659
+ "matched": len(matched),
660
+ "unmatched_audio": len(unmatched_audio),
661
+ "unmatched_visual": len(unmatched_visual),
662
+ "total_audio_beats": len(audio_beats),
663
+ "total_visual_beats": len(visual_beats),
664
+ "mean_drift_ms": np.mean(drifts) if drifts else 0,
665
+ "max_drift_ms": np.max(drifts) if drifts else 0,
666
+ "p95_drift_ms": np.percentile(drifts, 95) if len(drifts) > 1 else 0,
667
+ }
668
+
669
+ # Usage:
670
+ audio_beats = extract_beat_timestamps(features, fps=24)
671
+ visual_beats = extract_visual_beat_timestamps("output.mp4", fps=24)
672
+ report = sync_report(audio_beats, visual_beats)
673
+ print(f"Matched: {report['matched']}/{report['total_audio_beats']} beats")
674
+ print(f"Mean drift: {report['mean_drift_ms']:.1f}ms, Max: {report['max_drift_ms']:.1f}ms")
675
+ # Target: mean drift < 20ms, max drift < 42ms (1 frame at 24fps)
676
+ ```
677
+
678
+ ### Common Sync Issues
679
+
680
+ | Symptom | Cause | Fix |
681
+ |---------|-------|-----|
682
+ | Consistent late visual beats | ffmpeg concat adds frames at boundaries | Use `-vsync cfr` flag; pad segments to exact frame count |
683
+ | Drift increases over time | Floating-point accumulation in `t = fi / fps` | Use integer frame counter, compute `t` fresh each frame |
684
+ | Random missed beats | Beat threshold too high / feature smoothing too aggressive | Lower threshold; reduce EMA alpha for beat feature |
685
+ | Beats land on wrong frame | Off-by-one in frame indexing | Verify: frame 0 = t=0, frame 1 = t=1/fps (not t=0) |
skills/.archive/ascii-video/references/optimization.md ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Optimization Reference
2
+
3
+ > **See also:** architecture.md · composition.md · scenes.md · shaders.md · inputs.md · troubleshooting.md
4
+
5
+ ## Hardware Detection
6
+
7
+ Detect the user's hardware at script startup and adapt rendering parameters automatically. Never hardcode worker counts or resolution.
8
+
9
+ ### CPU and Memory Detection
10
+
11
+ ```python
12
+ import multiprocessing
13
+ import platform
14
+ import shutil
15
+ import os
16
+
17
+ def detect_hardware():
18
+ """Detect hardware capabilities and return render config."""
19
+ cpu_count = multiprocessing.cpu_count()
20
+
21
+ # Leave 1-2 cores free for OS + ffmpeg encoding
22
+ if cpu_count >= 16:
23
+ workers = cpu_count - 2
24
+ elif cpu_count >= 8:
25
+ workers = cpu_count - 1
26
+ elif cpu_count >= 4:
27
+ workers = cpu_count - 1
28
+ else:
29
+ workers = max(1, cpu_count)
30
+
31
+ # Memory detection (platform-specific)
32
+ try:
33
+ if platform.system() == "Darwin":
34
+ import subprocess
35
+ mem_bytes = int(subprocess.check_output(["sysctl", "-n", "hw.memsize"]).strip())
36
+ elif platform.system() == "Linux":
37
+ with open("/proc/meminfo") as f:
38
+ for line in f:
39
+ if line.startswith("MemTotal"):
40
+ mem_bytes = int(line.split()[1]) * 1024
41
+ break
42
+ else:
43
+ mem_bytes = 8 * 1024**3 # assume 8GB on unknown
44
+ except Exception:
45
+ mem_bytes = 8 * 1024**3
46
+
47
+ mem_gb = mem_bytes / (1024**3)
48
+
49
+ # Each worker uses ~50-150MB depending on grid sizes
50
+ # Cap workers if memory is tight
51
+ mem_per_worker_mb = 150
52
+ max_workers_by_mem = int(mem_gb * 1024 * 0.6 / mem_per_worker_mb) # use 60% of RAM
53
+ workers = min(workers, max_workers_by_mem)
54
+
55
+ # ffmpeg availability and codec support
56
+ has_ffmpeg = shutil.which("ffmpeg") is not None
57
+
58
+ return {
59
+ "cpu_count": cpu_count,
60
+ "workers": workers,
61
+ "mem_gb": mem_gb,
62
+ "platform": platform.system(),
63
+ "arch": platform.machine(),
64
+ "has_ffmpeg": has_ffmpeg,
65
+ }
66
+ ```
67
+
68
+ ### Adaptive Quality Profiles
69
+
70
+ Scale resolution, FPS, CRF, and grid density based on hardware:
71
+
72
+ ```python
73
+ def quality_profile(hw, target_duration_s, user_preference="auto"):
74
+ """
75
+ Returns render settings adapted to hardware.
76
+ user_preference: "auto", "draft", "preview", "production", "max"
77
+ """
78
+ if user_preference == "draft":
79
+ return {"vw": 960, "vh": 540, "fps": 12, "crf": 28, "workers": min(4, hw["workers"]),
80
+ "grid_scale": 0.5, "shaders": "minimal", "particles_max": 200}
81
+
82
+ if user_preference == "preview":
83
+ return {"vw": 1280, "vh": 720, "fps": 15, "crf": 25, "workers": hw["workers"],
84
+ "grid_scale": 0.75, "shaders": "standard", "particles_max": 500}
85
+
86
+ if user_preference == "max":
87
+ return {"vw": 3840, "vh": 2160, "fps": 30, "crf": 15, "workers": hw["workers"],
88
+ "grid_scale": 2.0, "shaders": "full", "particles_max": 3000}
89
+
90
+ # "production" or "auto"
91
+ # Auto-detect: estimate render time, downgrade if it would take too long
92
+ n_frames = int(target_duration_s * 24)
93
+ est_seconds_per_frame = 0.18 # ~180ms at 1080p
94
+ est_total_s = n_frames * est_seconds_per_frame / max(1, hw["workers"])
95
+
96
+ if hw["mem_gb"] < 4 or hw["cpu_count"] <= 2:
97
+ # Low-end: 720p, 15fps
98
+ return {"vw": 1280, "vh": 720, "fps": 15, "crf": 23, "workers": hw["workers"],
99
+ "grid_scale": 0.75, "shaders": "standard", "particles_max": 500}
100
+
101
+ if est_total_s > 3600: # would take over an hour
102
+ # Downgrade to 720p to speed up
103
+ return {"vw": 1280, "vh": 720, "fps": 24, "crf": 20, "workers": hw["workers"],
104
+ "grid_scale": 0.75, "shaders": "standard", "particles_max": 800}
105
+
106
+ # Standard production: 1080p 24fps
107
+ return {"vw": 1920, "vh": 1080, "fps": 24, "crf": 20, "workers": hw["workers"],
108
+ "grid_scale": 1.0, "shaders": "full", "particles_max": 1200}
109
+
110
+
111
+ def apply_quality_profile(profile):
112
+ """Set globals from quality profile."""
113
+ global VW, VH, FPS, N_WORKERS
114
+ VW = profile["vw"]
115
+ VH = profile["vh"]
116
+ FPS = profile["fps"]
117
+ N_WORKERS = profile["workers"]
118
+ # Grid sizes scale with resolution
119
+ # CRF passed to ffmpeg encoder
120
+ # Shader set determines which post-processing is active
121
+ ```
122
+
123
+ ### CLI Integration
124
+
125
+ ```python
126
+ parser = argparse.ArgumentParser()
127
+ parser.add_argument("--quality", choices=["draft", "preview", "production", "max", "auto"],
128
+ default="auto", help="Render quality preset")
129
+ parser.add_argument("--aspect", choices=["landscape", "portrait", "square"],
130
+ default="landscape", help="Aspect ratio preset")
131
+ parser.add_argument("--workers", type=int, default=0, help="Override worker count (0=auto)")
132
+ parser.add_argument("--resolution", type=str, default="", help="Override resolution e.g. 1280x720")
133
+ args = parser.parse_args()
134
+
135
+ hw = detect_hardware()
136
+ if args.workers > 0:
137
+ hw["workers"] = args.workers
138
+ profile = quality_profile(hw, target_duration, args.quality)
139
+
140
+ # Apply aspect ratio preset (before manual resolution override)
141
+ ASPECT_PRESETS = {
142
+ "landscape": (1920, 1080),
143
+ "portrait": (1080, 1920),
144
+ "square": (1080, 1080),
145
+ }
146
+ if args.aspect != "landscape" and not args.resolution:
147
+ profile["vw"], profile["vh"] = ASPECT_PRESETS[args.aspect]
148
+
149
+ if args.resolution:
150
+ w, h = args.resolution.split("x")
151
+ profile["vw"], profile["vh"] = int(w), int(h)
152
+ apply_quality_profile(profile)
153
+
154
+ log(f"Hardware: {hw['cpu_count']} cores, {hw['mem_gb']:.1f}GB RAM, {hw['platform']}")
155
+ log(f"Render: {profile['vw']}x{profile['vh']} @{profile['fps']}fps, "
156
+ f"CRF {profile['crf']}, {profile['workers']} workers")
157
+ ```
158
+
159
+ ### Portrait Mode Considerations
160
+
161
+ Portrait (1080x1920) has the same pixel count as landscape 1080p, so performance is equivalent. But composition patterns differ:
162
+
163
+ | Concern | Landscape | Portrait |
164
+ |---------|-----------|----------|
165
+ | Grid cols at `lg` | 160 | 90 |
166
+ | Grid rows at `lg` | 45 | 80 |
167
+ | Max text line chars | ~50 centered | ~25-30 centered |
168
+ | Vertical rain | Short travel | Long, dramatic travel |
169
+ | Horizontal spectrum | Full width | Needs rotation or compression |
170
+ | Radial effects | Natural circles | Tall ellipses (aspect correction handles this) |
171
+ | Particle explosions | Wide spread | Tall spread |
172
+ | Text stacking | 3-4 lines comfortable | 8-10 lines comfortable |
173
+ | Quote layout | 2-3 wide lines | 5-6 short lines |
174
+
175
+ **Portrait-optimized patterns:**
176
+ - Vertical rain/matrix effects are naturally enhanced — longer column travel
177
+ - Fire columns rise through more screen space
178
+ - Rising embers/particles have more vertical runway
179
+ - Text can be stacked more aggressively with more lines
180
+ - Radial effects work if aspect correction is applied (GridLayer handles this automatically)
181
+ - Spectrum bars can be rotated 90 degrees (vertical bars from bottom)
182
+
183
+ **Portrait text layout:**
184
+ ```python
185
+ def layout_text_portrait(text, max_chars_per_line=25, grid=None):
186
+ """Break text into short lines for portrait display."""
187
+ words = text.split()
188
+ lines = []; current = ""
189
+ for w in words:
190
+ if len(current) + len(w) + 1 > max_chars_per_line:
191
+ lines.append(current.strip())
192
+ current = w + " "
193
+ else:
194
+ current += w + " "
195
+ if current.strip():
196
+ lines.append(current.strip())
197
+ return lines
198
+ ```
199
+
200
+ ## Performance Budget
201
+
202
+ Target: 100-200ms per frame (5-10 fps single-threaded, 40-80 fps across 8 workers).
203
+
204
+ | Component | Time | Notes |
205
+ |-----------|------|-------|
206
+ | Feature extraction | 1-5ms | Pre-computed for all frames before render |
207
+ | Effect function | 2-15ms | Vectorized numpy, avoid Python loops |
208
+ | Character render | 80-150ms | **Bottleneck** -- per-cell Python loop |
209
+ | Shader pipeline | 5-25ms | Depends on active shaders |
210
+ | ffmpeg encode | ~5ms | Amortized by pipe buffering |
211
+
212
+ ## Bitmap Pre-Rasterization
213
+
214
+ Rasterize every character at init, not per-frame:
215
+
216
+ ```python
217
+ # At init time -- done once
218
+ for c in all_characters:
219
+ img = Image.new("L", (cell_w, cell_h), 0)
220
+ ImageDraw.Draw(img).text((0, 0), c, fill=255, font=font)
221
+ bitmaps[c] = np.array(img, dtype=np.float32) / 255.0 # float32 for fast multiply
222
+
223
+ # At render time -- fast lookup
224
+ bitmap = bitmaps[char]
225
+ canvas[y:y+ch, x:x+cw] = np.maximum(canvas[y:y+ch, x:x+cw],
226
+ (bitmap[:,:,None] * color).astype(np.uint8))
227
+ ```
228
+
229
+ Collect all characters from all palettes + overlay text into the init set. Lazy-init for any missed characters.
230
+
231
+ ## Pre-Rendered Background Textures
232
+
233
+ Alternative to `_render_vf()` for backgrounds where characters don't need to change every frame. Pre-bake a static ASCII texture once at init, then multiply by a per-cell color field each frame. One matrix multiply vs thousands of bitmap blits.
234
+
235
+ Use when: background layer uses a fixed character palette and only color/brightness varies per frame. NOT suitable for layers where character selection depends on a changing value field.
236
+
237
+ ### Init: Bake the Texture
238
+
239
+ ```python
240
+ # In GridLayer.__init__:
241
+ self._bg_row_idx = np.clip(
242
+ (np.arange(VH) - self.oy) // self.ch, 0, self.rows - 1
243
+ )
244
+ self._bg_col_idx = np.clip(
245
+ (np.arange(VW) - self.ox) // self.cw, 0, self.cols - 1
246
+ )
247
+ self._bg_textures = {}
248
+
249
+ def make_bg_texture(self, palette):
250
+ """Pre-render a static ASCII texture (grayscale float32) once."""
251
+ if palette not in self._bg_textures:
252
+ texture = np.zeros((VH, VW), dtype=np.float32)
253
+ rng = random.Random(12345)
254
+ ch_list = [c for c in palette if c != " " and c in self.bm]
255
+ if not ch_list:
256
+ ch_list = list(self.bm.keys())[:5]
257
+ for row in range(self.rows):
258
+ y = self.oy + row * self.ch
259
+ if y + self.ch > VH:
260
+ break
261
+ for col in range(self.cols):
262
+ x = self.ox + col * self.cw
263
+ if x + self.cw > VW:
264
+ break
265
+ bm = self.bm[rng.choice(ch_list)]
266
+ texture[y:y+self.ch, x:x+self.cw] = bm
267
+ self._bg_textures[palette] = texture
268
+ return self._bg_textures[palette]
269
+ ```
270
+
271
+ ### Render: Color Field x Cached Texture
272
+
273
+ ```python
274
+ def render_bg(self, color_field, palette=PAL_CIRCUIT):
275
+ """Fast background: pre-rendered ASCII texture * per-cell color field.
276
+ color_field: (rows, cols, 3) uint8. Returns (VH, VW, 3) uint8."""
277
+ texture = self.make_bg_texture(palette)
278
+ # Expand cell colors to pixel coords via pre-computed index maps
279
+ color_px = color_field[
280
+ self._bg_row_idx[:, None], self._bg_col_idx[None, :]
281
+ ].astype(np.float32)
282
+ return (texture[:, :, None] * color_px).astype(np.uint8)
283
+ ```
284
+
285
+ ### Usage in a Scene
286
+
287
+ ```python
288
+ # Build per-cell color from effect fields (cheap — rows*cols, not VH*VW)
289
+ hue = ((t * 0.05 + val * 0.2) % 1.0).astype(np.float32)
290
+ R, G, B = hsv2rgb(hue, np.full_like(val, 0.5), val)
291
+ color_field = mkc(R, G, B, g.rows, g.cols) # (rows, cols, 3) uint8
292
+
293
+ # Render background — single matrix multiply, no per-cell loop
294
+ canvas_bg = g.render_bg(color_field, PAL_DENSE)
295
+ ```
296
+
297
+ The texture init loop runs once and is cached per palette. Per-frame cost is one fancy-index lookup + one broadcast multiply — orders of magnitude faster than the per-cell bitmap blit loop in `render()` for dense backgrounds.
298
+
299
+ ## Coordinate Array Caching
300
+
301
+ Pre-compute all grid-relative coordinate arrays at init, not per-frame:
302
+
303
+ ```python
304
+ # These are O(rows*cols) and used in every effect
305
+ self.rr = np.arange(rows)[:, None] # row indices
306
+ self.cc = np.arange(cols)[None, :] # col indices
307
+ self.dist = np.sqrt(dx**2 + dy**2) # distance from center
308
+ self.angle = np.arctan2(dy, dx) # angle from center
309
+ self.dist_n = ... # normalized distance
310
+ ```
311
+
312
+ ## Vectorized Effect Patterns
313
+
314
+ ### Avoid Per-Cell Python Loops in Effects
315
+
316
+ The render loop (compositing bitmaps) is unavoidably per-cell. But effect functions must be fully vectorized numpy -- never iterate over rows/cols in Python.
317
+
318
+ Bad (O(rows*cols) Python loop):
319
+ ```python
320
+ for r in range(rows):
321
+ for c in range(cols):
322
+ val[r, c] = math.sin(c * 0.1 + t) * math.cos(r * 0.1 - t)
323
+ ```
324
+
325
+ Good (vectorized):
326
+ ```python
327
+ val = np.sin(g.cc * 0.1 + t) * np.cos(g.rr * 0.1 - t)
328
+ ```
329
+
330
+ ### Vectorized Matrix Rain
331
+
332
+ The naive per-column per-trail-pixel loop is the second biggest bottleneck after the render loop. Use numpy fancy indexing:
333
+
334
+ ```python
335
+ # Instead of nested Python loops over columns and trail pixels:
336
+ # Build row index arrays for all active trail pixels at once
337
+ all_rows = []
338
+ all_cols = []
339
+ all_fades = []
340
+ for c in range(cols):
341
+ head = int(S["ry"][c])
342
+ trail_len = S["rln"][c]
343
+ for i in range(trail_len):
344
+ row = head - i
345
+ if 0 <= row < rows:
346
+ all_rows.append(row)
347
+ all_cols.append(c)
348
+ all_fades.append(1.0 - i / trail_len)
349
+
350
+ # Vectorized assignment
351
+ ar = np.array(all_rows)
352
+ ac = np.array(all_cols)
353
+ af = np.array(all_fades, dtype=np.float32)
354
+ # Assign chars and colors in bulk using fancy indexing
355
+ ch[ar, ac] = ... # vectorized char assignment
356
+ co[ar, ac, 1] = (af * bri * 255).astype(np.uint8) # green channel
357
+ ```
358
+
359
+ ### Vectorized Fire Columns
360
+
361
+ Same pattern -- accumulate index arrays, assign in bulk:
362
+
363
+ ```python
364
+ fire_val = np.zeros((rows, cols), dtype=np.float32)
365
+ for fi in range(n_cols):
366
+ fx_c = int((fi * cols / n_cols + np.sin(t * 2 + fi * 0.7) * 3) % cols)
367
+ height = int(energy * rows * 0.7)
368
+ dy = np.arange(min(height, rows))
369
+ fr = rows - 1 - dy
370
+ frac = dy / max(height, 1)
371
+ # Width spread: base columns wider at bottom
372
+ for dx in range(-1, 2): # 3-wide columns
373
+ c = fx_c + dx
374
+ if 0 <= c < cols:
375
+ fire_val[fr, c] = np.maximum(fire_val[fr, c],
376
+ (1 - frac * 0.6) * (0.5 + rms * 0.5))
377
+ # Now map fire_val to chars and colors in one vectorized pass
378
+ ```
379
+
380
+ ## PIL String Rendering for Text-Heavy Scenes
381
+
382
+ Alternative to per-cell bitmap blitting when rendering many long text strings (scrolling tickers, typewriter sequences, idea floods). Uses PIL's native `ImageDraw.text()` which renders an entire string in one C call, vs one Python-loop bitmap blit per character.
383
+
384
+ Typical win: a scene with 56 ticker rows renders 56 PIL `text()` calls instead of ~10K individual bitmap blits.
385
+
386
+ Use when: scene renders many rows of readable text strings. NOT suitable for sparse or spatially-scattered single characters (use normal `render()` for those).
387
+
388
+ ```python
389
+ from PIL import Image, ImageDraw
390
+
391
+ def render_text_layer(grid, rows_data, font):
392
+ """Render dense text rows via PIL instead of per-cell bitmap blitting.
393
+
394
+ Args:
395
+ grid: GridLayer instance (for oy, ch, ox, font metrics)
396
+ rows_data: list of (row_index, text_string, rgb_tuple) — one per row
397
+ font: PIL ImageFont instance (grid.font)
398
+
399
+ Returns:
400
+ uint8 array (VH, VW, 3) — canvas with rendered text
401
+ """
402
+ img = Image.new("RGB", (VW, VH), (0, 0, 0))
403
+ draw = ImageDraw.Draw(img)
404
+ for row_idx, text, color in rows_data:
405
+ y = grid.oy + row_idx * grid.ch
406
+ if y + grid.ch > VH:
407
+ break
408
+ draw.text((grid.ox, y), text, fill=color, font=font)
409
+ return np.array(img)
410
+ ```
411
+
412
+ ### Usage in a Ticker Scene
413
+
414
+ ```python
415
+ # Build ticker data (text + color per row)
416
+ rows_data = []
417
+ for row in range(n_tickers):
418
+ text = build_ticker_text(row, t) # scrolling substring
419
+ color = hsv2rgb_scalar(hue, 0.85, bri) # (R, G, B) tuple
420
+ rows_data.append((row, text, color))
421
+
422
+ # One PIL pass instead of thousands of bitmap blits
423
+ canvas_tickers = render_text_layer(g_md, rows_data, g_md.font)
424
+
425
+ # Blend with other layers normally
426
+ result = blend_canvas(canvas_bg, canvas_tickers, "screen", 0.9)
427
+ ```
428
+
429
+ This is purely a rendering optimization — same visual output, fewer draw calls. The grid's `render()` method is still needed for sparse character fields where characters are placed individually based on value fields.
430
+
431
+ ## Bloom Optimization
432
+
433
+ **Do NOT use `scipy.ndimage.uniform_filter`** -- measured at 424ms/frame.
434
+
435
+ Use 4x downsample + manual box blur instead -- 84ms/frame (5x faster):
436
+
437
+ ```python
438
+ sm = canvas[::4, ::4].astype(np.float32) # 4x downsample
439
+ br = np.where(sm > threshold, sm, 0)
440
+ for _ in range(3): # 3-pass manual box blur
441
+ p = np.pad(br, ((1,1),(1,1),(0,0)), mode='edge')
442
+ br = (p[:-2,:-2] + p[:-2,1:-1] + p[:-2,2:] +
443
+ p[1:-1,:-2] + p[1:-1,1:-1] + p[1:-1,2:] +
444
+ p[2:,:-2] + p[2:,1:-1] + p[2:,2:]) / 9.0
445
+ bl = np.repeat(np.repeat(br, 4, axis=0), 4, axis=1)[:H, :W]
446
+ ```
447
+
448
+ ## Vignette Caching
449
+
450
+ Distance field is resolution- and strength-dependent, never changes per frame:
451
+
452
+ ```python
453
+ _vig_cache = {}
454
+ def sh_vignette(canvas, strength):
455
+ key = (canvas.shape[0], canvas.shape[1], round(strength, 2))
456
+ if key not in _vig_cache:
457
+ Y = np.linspace(-1, 1, H)[:, None]
458
+ X = np.linspace(-1, 1, W)[None, :]
459
+ _vig_cache[key] = np.clip(1.0 - np.sqrt(X**2+Y**2) * strength, 0.15, 1).astype(np.float32)
460
+ return np.clip(canvas * _vig_cache[key][:,:,None], 0, 255).astype(np.uint8)
461
+ ```
462
+
463
+ Same pattern for CRT barrel distortion (cache remap coordinates).
464
+
465
+ ## Film Grain Optimization
466
+
467
+ Generate noise at half resolution, tile up:
468
+
469
+ ```python
470
+ noise = np.random.randint(-amt, amt+1, (H//2, W//2, 1), dtype=np.int16)
471
+ noise = np.repeat(np.repeat(noise, 2, axis=0), 2, axis=1)[:H, :W]
472
+ ```
473
+
474
+ 2x blocky grain looks like film grain and costs 1/4 the random generation.
475
+
476
+ ## Parallel Rendering
477
+
478
+ ### Worker Architecture
479
+
480
+ ```python
481
+ hw = detect_hardware()
482
+ N_WORKERS = hw["workers"]
483
+
484
+ # Batch splitting (for non-clip architectures)
485
+ batch_size = (n_frames + N_WORKERS - 1) // N_WORKERS
486
+ batches = [(i, i*batch_size, min((i+1)*batch_size, n_frames), features, seg_path) ...]
487
+
488
+ with multiprocessing.Pool(N_WORKERS) as pool:
489
+ segments = pool.starmap(render_batch, batches)
490
+ ```
491
+
492
+ ### Per-Clip Parallelism (Preferred for Segmented Videos)
493
+
494
+ ```python
495
+ from concurrent.futures import ProcessPoolExecutor, as_completed
496
+
497
+ with ProcessPoolExecutor(max_workers=N_WORKERS) as pool:
498
+ futures = {pool.submit(render_clip, seg, features, path): seg["id"]
499
+ for seg, path in clip_args}
500
+ for fut in as_completed(futures):
501
+ clip_id = futures[fut]
502
+ try:
503
+ fut.result()
504
+ log(f" {clip_id} done")
505
+ except Exception as e:
506
+ log(f" {clip_id} FAILED: {e}")
507
+ ```
508
+
509
+ ### Worker Isolation
510
+
511
+ Each worker:
512
+ - Creates its own `Renderer` instance (with full grid + bitmap init)
513
+ - Opens its own ffmpeg subprocess
514
+ - Has independent random seed (`random.seed(batch_id * 10000)`)
515
+ - Writes to its own segment file and stderr log
516
+
517
+ ### ffmpeg Pipe Safety
518
+
519
+ **CRITICAL**: Never `stderr=subprocess.PIPE` with long-running ffmpeg. The stderr buffer fills at ~64KB and deadlocks:
520
+
521
+ ```python
522
+ # WRONG -- will deadlock
523
+ pipe = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
524
+
525
+ # RIGHT -- stderr to file
526
+ stderr_fh = open(err_path, "w")
527
+ pipe = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=stderr_fh)
528
+ # ... write all frames ...
529
+ pipe.stdin.close()
530
+ pipe.wait()
531
+ stderr_fh.close()
532
+ ```
533
+
534
+ ### Concatenation
535
+
536
+ ```python
537
+ with open(concat_file, "w") as cf:
538
+ for seg in segments:
539
+ cf.write(f"file '{seg}'\n")
540
+
541
+ cmd = ["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", concat_file]
542
+ if audio_path:
543
+ cmd += ["-i", audio_path, "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-shortest"]
544
+ else:
545
+ cmd += ["-c:v", "copy"]
546
+ cmd.append(output_path)
547
+ subprocess.run(cmd, capture_output=True, check=True)
548
+ ```
549
+
550
+ ## Particle System Performance
551
+
552
+ Cap particle counts based on quality profile:
553
+
554
+ | System | Low | Standard | High |
555
+ |--------|-----|----------|------|
556
+ | Explosion | 300 | 1000 | 2500 |
557
+ | Embers | 500 | 1500 | 3000 |
558
+ | Starfield | 300 | 800 | 1500 |
559
+ | Dissolve | 200 | 600 | 1200 |
560
+
561
+ Cull by truncating lists:
562
+ ```python
563
+ MAX_PARTICLES = profile.get("particles_max", 1200)
564
+ if len(S["px"]) > MAX_PARTICLES:
565
+ for k in ("px", "py", "vx", "vy", "life", "char"):
566
+ S[k] = S[k][-MAX_PARTICLES:] # keep newest
567
+ ```
568
+
569
+ ## Memory Management
570
+
571
+ - Feature arrays: pre-computed for all frames, shared across workers via fork semantics (COW)
572
+ - Canvas: allocated once per worker, reused (`np.zeros(...)`)
573
+ - Character arrays: allocated per frame (cheap -- rows*cols U1 strings)
574
+ - Bitmap cache: ~500KB per grid size, initialized once per worker
575
+
576
+ Total memory per worker: ~50-150MB. Total: ~400-800MB for 8 workers.
577
+
578
+ For low-memory systems (< 4GB), reduce worker count and use smaller grids.
579
+
580
+ ## Brightness Verification
581
+
582
+ After render, spot-check brightness at sample timestamps:
583
+
584
+ ```python
585
+ for t in [2, 30, 60, 120, 180]:
586
+ cmd = ["ffmpeg", "-ss", str(t), "-i", output_path,
587
+ "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]
588
+ r = subprocess.run(cmd, capture_output=True)
589
+ arr = np.frombuffer(r.stdout, dtype=np.uint8)
590
+ print(f"t={t}s mean={arr.mean():.1f} max={arr.max()}")
591
+ ```
592
+
593
+ Target: mean > 5 for quiet sections, mean > 15 for active sections. If consistently below, increase brightness floor in effects and/or global boost multiplier.
594
+
595
+ ## Render Time Estimates
596
+
597
+ Scale with hardware. Baseline: 1080p, 24fps, ~180ms/frame/worker.
598
+
599
+ | Duration | Frames | 4 workers | 8 workers | 16 workers |
600
+ |----------|--------|-----------|-----------|------------|
601
+ | 30s | 720 | ~3 min | ~2 min | ~1 min |
602
+ | 2 min | 2,880 | ~13 min | ~7 min | ~4 min |
603
+ | 3.5 min | 5,040 | ~23 min | ~12 min | ~6 min |
604
+ | 5 min | 7,200 | ~33 min | ~17 min | ~9 min |
605
+ | 10 min | 14,400 | ~65 min | ~33 min | ~17 min |
606
+
607
+ At 720p: multiply times by ~0.5. At 4K: multiply by ~4.
608
+
609
+ Heavier effects (many particles, dense grids, extra shader passes) add ~20-50%.
610
+
611
+ ---
612
+
613
+ ## Temp File Cleanup
614
+
615
+ Rendering generates intermediate files that accumulate across runs. Clean up after the final concat/mux step.
616
+
617
+ ### Files to Clean
618
+
619
+ | File type | Source | Location |
620
+ |-----------|--------|----------|
621
+ | WAV extracts | `ffmpeg -i input.mp3 ... tmp.wav` | `tempfile.mktemp()` or project dir |
622
+ | Segment clips | `render_clip()` output | `segments/seg_00.mp4` etc. |
623
+ | Concat list | ffmpeg concat demuxer input | `segments/concat.txt` |
624
+ | ffmpeg stderr logs | piped to file for debugging | `*.log` in project dir |
625
+ | Feature cache | pickled numpy arrays | `*.pkl` or `*.npz` |
626
+
627
+ ### Cleanup Function
628
+
629
+ ```python
630
+ import glob
631
+ import tempfile
632
+ import shutil
633
+
634
+ def cleanup_render_artifacts(segments_dir="segments", keep_final=True):
635
+ """Remove intermediate files after successful render.
636
+
637
+ Call this AFTER verifying the final output exists and plays correctly.
638
+
639
+ Args:
640
+ segments_dir: directory containing segment clips and concat list
641
+ keep_final: if True, only delete intermediates (not the final output)
642
+ """
643
+ removed = []
644
+
645
+ # 1. Segment clips
646
+ if os.path.isdir(segments_dir):
647
+ shutil.rmtree(segments_dir)
648
+ removed.append(f"directory: {segments_dir}")
649
+
650
+ # 2. Temporary WAV files
651
+ for wav in glob.glob("*.wav"):
652
+ if wav.startswith("tmp") or wav.startswith("extracted_"):
653
+ os.remove(wav)
654
+ removed.append(wav)
655
+
656
+ # 3. ffmpeg stderr logs
657
+ for log in glob.glob("ffmpeg_*.log"):
658
+ os.remove(log)
659
+ removed.append(log)
660
+
661
+ # 4. Feature cache (optional — useful to keep for re-renders)
662
+ # for cache in glob.glob("features_*.npz"):
663
+ # os.remove(cache)
664
+ # removed.append(cache)
665
+
666
+ print(f"Cleaned {len(removed)} artifacts: {removed}")
667
+ return removed
668
+ ```
669
+
670
+ ### Integration with Render Pipeline
671
+
672
+ Call cleanup at the end of the main render script, after the final output is verified:
673
+
674
+ ```python
675
+ # At end of main()
676
+ if os.path.exists(output_path) and os.path.getsize(output_path) > 1000:
677
+ cleanup_render_artifacts(segments_dir="segments")
678
+ print(f"Done. Output: {output_path}")
679
+ else:
680
+ print("WARNING: final output missing or empty — skipping cleanup")
681
+ ```
682
+
683
+ ### Temp File Best Practices
684
+
685
+ - Use `tempfile.mkdtemp()` for segment directories — avoids polluting the project dir
686
+ - Name WAV extracts with `tempfile.mktemp(suffix=".wav")` so they're in the OS temp dir
687
+ - For debugging, set `KEEP_INTERMEDIATES=1` env var to skip cleanup
688
+ - Feature caches (`.npz`) are cheap to store and expensive to recompute — default to keeping them
skills/.archive/ascii-video/references/scenes.md ADDED
@@ -0,0 +1,1011 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Scene System & Creative Composition
2
+
3
+ > **See also:** architecture.md · composition.md · effects.md · shaders.md
4
+
5
+ ## Scene Design Philosophy
6
+
7
+ Scenes are storytelling units, not effect demos. Every scene needs:
8
+ - A **concept** — what is happening visually? Not "plasma + rings" but "emergence from void" or "crystallization"
9
+ - An **arc** — how does it change over its duration? Build, decay, transform, reveal?
10
+ - A **role** — how does it serve the larger video narrative? Opening tension, peak energy, resolution?
11
+
12
+ The design patterns below provide compositional techniques. The scene examples show them in practice at increasing complexity. The protocol section covers the technical contract.
13
+
14
+ Good scene design starts with the concept, then selects effects and parameters that serve it. The design patterns section shows *how* to compose layers intentionally. The examples section shows complete working scenes at every complexity level. The protocol section covers the technical contract that all scenes must follow.
15
+
16
+ ---
17
+
18
+ ## Scene Design Patterns
19
+
20
+ Higher-order patterns for composing scenes that feel intentional rather than random. These patterns use the existing building blocks (value fields, blend modes, shaders, feedback) but organize them with compositional intent.
21
+
22
+ ## Layer Hierarchy
23
+
24
+ Every scene should have clear visual layers with distinct roles:
25
+
26
+ | Layer | Grid | Brightness | Purpose |
27
+ |-------|------|-----------|---------|
28
+ | **Background** | xs or sm (dense) | 0.1–0.25 | Atmosphere, texture. Never competes with content. |
29
+ | **Content** | md (balanced) | 0.4–0.8 | The main visual idea. Carries the scene's concept. |
30
+ | **Accent** | lg or sm (sparse) | 0.5–1.0 (sparse coverage) | Highlights, punctuation, sparse bright points. |
31
+
32
+ The background sets mood. The content layer is what the scene *is about*. The accent adds visual interest without overwhelming.
33
+
34
+ ```python
35
+ def fx_example(r, f, t, S):
36
+ local = t
37
+ progress = min(local / 5.0, 1.0)
38
+
39
+ g_bg = r.get_grid("sm")
40
+ g_main = r.get_grid("md")
41
+ g_accent = r.get_grid("lg")
42
+
43
+ # --- Background: dim atmosphere ---
44
+ bg_val = vf_smooth_noise(g_bg, f, t * 0.3, S, octaves=2, bri=0.15)
45
+ # ... render bg to canvas
46
+
47
+ # --- Content: the main visual idea ---
48
+ content_val = vf_spiral(g_main, f, t, S, n_arms=n_arms, tightness=tightness)
49
+ # ... render content on top of canvas
50
+
51
+ # --- Accent: sparse highlights ---
52
+ accent_val = vf_noise_static(g_accent, f, t, S, density=0.05)
53
+ # ... render accent on top
54
+
55
+ return canvas
56
+ ```
57
+
58
+ ## Directional Parameter Arcs
59
+
60
+ Parameters should *go somewhere* over the scene's duration — not oscillate aimlessly with `sin(t * N)`.
61
+
62
+ **Bad:** `twist = 3.0 + 2.0 * math.sin(t * 0.6)` — wobbles back and forth, feels aimless.
63
+
64
+ **Good:** `twist = 2.0 + progress * 5.0` — starts gentle, ends intense. The scene *builds*.
65
+
66
+ Use `progress = min(local / duration, 1.0)` (0→1 over the scene) to drive directional change:
67
+
68
+ | Pattern | Formula | Feel |
69
+ |---------|---------|------|
70
+ | Linear ramp | `progress * range` | Steady buildup |
71
+ | Ease-out | `1 - (1 - progress) ** 2` | Fast start, gentle finish |
72
+ | Ease-in | `progress ** 2` | Slow start, accelerating |
73
+ | Step reveal | `np.clip((progress - 0.5) / 0.25, 0, 1)` | Nothing until 50%, then fades in |
74
+ | Build + plateau | `min(1.0, progress * 1.5)` | Reaches full at 67%, holds |
75
+
76
+ Oscillation is fine for *secondary* parameters (saturation shimmer, hue drift). But the *defining* parameter of the scene should have a direction.
77
+
78
+ ### Examples of Directional Arcs
79
+
80
+ | Scene concept | Parameter | Arc |
81
+ |--------------|-----------|-----|
82
+ | Emergence | Ring radius | 0 → max (ease-out) |
83
+ | Shatter | Voronoi cell count | 8 → 38 (linear) |
84
+ | Descent | Tunnel speed | 2.0 → 10.0 (linear) |
85
+ | Mandala | Shape complexity | ring → +polygon → +star → +rosette (step reveals) |
86
+ | Crescendo | Layer count | 1 → 7 (staggered entry) |
87
+ | Entropy | Geometry visibility | 1.0 → 0.0 (consumed) |
88
+
89
+ ## Scene Concepts
90
+
91
+ Each scene should be built around a *visual idea*, not an effect name.
92
+
93
+ **Bad:** "fx_plasma_cascade" — named after the effect. No concept.
94
+ **Good:** "fx_emergence" — a point of light expands into a field. The name tells you *what happens*.
95
+
96
+ Good scene concepts have:
97
+ 1. A **visual metaphor** (emergence, descent, collision, entropy)
98
+ 2. A **directional arc** (things change from A to B, not oscillate)
99
+ 3. **Motivated layer choices** (each layer serves the concept)
100
+ 4. **Motivated feedback** (transform direction matches the metaphor)
101
+
102
+ | Concept | Metaphor | Feedback transform | Why |
103
+ |---------|----------|-------------------|-----|
104
+ | Emergence | Birth, expansion | zoom-out | Past frames expand outward |
105
+ | Descent | Falling, acceleration | zoom-in | Past frames rush toward center |
106
+ | Inferno | Rising fire | shift-up | Past frames rise with the flames |
107
+ | Entropy | Decay, dissolution | none | Clean, no persistence — things disappear |
108
+ | Crescendo | Accumulation | zoom + hue_shift | Everything compounds and shifts |
109
+
110
+ ## Compositional Techniques
111
+
112
+ ### Counter-Rotating Dual Systems
113
+
114
+ Two instances of the same effect rotating in opposite directions create visual interference:
115
+
116
+ ```python
117
+ # Primary spiral (clockwise)
118
+ s1_val = vf_spiral(g_main, f, t * 1.5, S, n_arms=n_arms_1, tightness=tightness_1)
119
+
120
+ # Counter-rotating spiral (counter-clockwise via negative time)
121
+ s2_val = vf_spiral(g_accent, f, -t * 1.2, S, n_arms=n_arms_2, tightness=tightness_2)
122
+
123
+ # Screen blend creates bright interference at crossing points
124
+ canvas = blend_canvas(canvas_with_s1, c2, "screen", 0.7)
125
+ ```
126
+
127
+ Works with spirals, vortexes, rings. The counter-rotation creates constantly shifting interference patterns.
128
+
129
+ ### Wave Collision
130
+
131
+ Two wave fronts converging from opposite sides, meeting at a collision point:
132
+
133
+ ```python
134
+ collision_phase = abs(progress - 0.5) * 2 # 1→0→1 (0 at collision)
135
+
136
+ # Wave A approaches from left
137
+ offset_a = (1 - progress) * g.cols * 0.4
138
+ wave_a = np.sin((g.cc + offset_a) * 0.08 + t * 2) * 0.5 + 0.5
139
+
140
+ # Wave B approaches from right
141
+ offset_b = -(1 - progress) * g.cols * 0.4
142
+ wave_b = np.sin((g.cc + offset_b) * 0.08 - t * 2) * 0.5 + 0.5
143
+
144
+ # Interference peaks at collision
145
+ combined = wave_a * 0.5 + wave_b * 0.5 + np.abs(wave_a - wave_b) * (1 - collision_phase) * 0.5
146
+ ```
147
+
148
+ ### Progressive Fragmentation
149
+
150
+ Voronoi with cell count increasing over time — visual shattering:
151
+
152
+ ```python
153
+ n_pts = int(8 + progress * 30) # 8 cells → 38 cells
154
+ # Pre-generate enough points, slice to n_pts
155
+ px = base_x[:n_pts] + np.sin(t * 0.3 + np.arange(n_pts) * 0.7) * (3 + progress * 3)
156
+ ```
157
+
158
+ The edge glow width can also increase with progress to emphasize the cracks.
159
+
160
+ ### Entropy / Consumption
161
+
162
+ A clean geometric pattern being overtaken by an organic process:
163
+
164
+ ```python
165
+ # Geometry fades out
166
+ geo_val = clean_pattern * max(0.05, 1.0 - progress * 0.9)
167
+
168
+ # Organic process grows in
169
+ rd_val = vf_reaction_diffusion(g, f, t, S) * min(1.0, progress * 1.5)
170
+
171
+ # Render geometry first, organic on top — organic consumes geometry
172
+ ```
173
+
174
+ ### Staggered Layer Entry (Crescendo)
175
+
176
+ Layers enter one at a time, building to overwhelming density:
177
+
178
+ ```python
179
+ def layer_strength(enter_t, ramp=1.5):
180
+ """0.0 until enter_t, ramps to 1.0 over ramp seconds."""
181
+ return max(0.0, min(1.0, (local - enter_t) / ramp))
182
+
183
+ # Layer 1: always present
184
+ s1 = layer_strength(0.0)
185
+ # Layer 2: enters at 2s
186
+ s2 = layer_strength(2.0)
187
+ # Layer 3: enters at 4s
188
+ s3 = layer_strength(4.0)
189
+ # ... etc
190
+
191
+ # Each layer uses a different effect, grid, palette, and blend mode
192
+ # Screen blend between layers so they accumulate light
193
+ ```
194
+
195
+ For a 15-second crescendo, 7 layers entering every 2 seconds works well. Use different blend modes (screen for most, add for energy, colordodge for the final wash).
196
+
197
+ ## Scene Ordering
198
+
199
+ For a multi-scene reel or video:
200
+ - **Vary mood between adjacent scenes** — don't put two calm scenes next to each other
201
+ - **Randomize order** rather than grouping by type — prevents "effect demo" feel
202
+ - **End on the strongest scene** — crescendo or something with a clear payoff
203
+ - **Open with energy** — grab attention in the first 2 seconds
204
+
205
+ ---
206
+
207
+ ## Scene Protocol
208
+
209
+ Scenes are the top-level creative unit. Each scene is a time-bounded segment with its own effect function, shader chain, feedback configuration, and tone-mapping gamma.
210
+
211
+ ### Scene Protocol (v2)
212
+
213
+ ### Function Signature
214
+
215
+ ```python
216
+ def fx_scene_name(r, f, t, S) -> canvas:
217
+ """
218
+ Args:
219
+ r: Renderer instance — access multiple grids via r.get_grid("sm")
220
+ f: dict of audio/video features, all values normalized to [0, 1]
221
+ t: time in seconds — local to scene (0.0 at scene start)
222
+ S: dict for persistent state (particles, rain columns, etc.)
223
+
224
+ Returns:
225
+ canvas: numpy uint8 array, shape (VH, VW, 3) — full pixel frame
226
+ """
227
+ ```
228
+
229
+ **Local time convention:** Scene functions receive `t` starting at 0.0 for the first frame of the scene, regardless of where the scene appears in the timeline. The render loop subtracts the scene's start time before calling the function:
230
+
231
+ ```python
232
+ # In render_clip:
233
+ t_local = fi / FPS - scene_start
234
+ canvas = fx_fn(r, feat, t_local, S)
235
+ ```
236
+
237
+ This makes scenes reorderable without modifying their code. Compute scene progress as:
238
+
239
+ ```python
240
+ progress = min(t / scene_duration, 1.0) # 0→1 over the scene
241
+ ```
242
+
243
+ This replaces the v1 protocol where scenes returned `(chars, colors)` tuples. The v2 protocol gives scenes full control over multi-grid rendering and pixel-level composition internally.
244
+
245
+ ### The Renderer Class
246
+
247
+ ```python
248
+ class Renderer:
249
+ def __init__(self):
250
+ self.grids = {} # lazy-initialized grid cache
251
+ self.g = None # "active" grid (for backward compat)
252
+ self.S = {} # persistent state dict
253
+
254
+ def get_grid(self, key):
255
+ """Get or create a GridLayer by size key."""
256
+ if key not in self.grids:
257
+ sizes = {"xs": 8, "sm": 10, "md": 16, "lg": 20, "xl": 24, "xxl": 40}
258
+ self.grids[key] = GridLayer(FONT_PATH, sizes[key])
259
+ return self.grids[key]
260
+
261
+ def set_grid(self, key):
262
+ """Set active grid (legacy). Prefer get_grid() for multi-grid scenes."""
263
+ self.g = self.get_grid(key)
264
+ return self.g
265
+ ```
266
+
267
+ **Key difference from v1**: scenes call `r.get_grid("sm")`, `r.get_grid("lg")`, etc. to access multiple grids. Each grid is lazy-initialized and cached. The `set_grid()` method still works for single-grid scenes.
268
+
269
+ ### Minimal Scene (Single Grid)
270
+
271
+ ```python
272
+ def fx_simple_rings(r, f, t, S):
273
+ """Single-grid scene: rings with distance-mapped hue."""
274
+ canvas = _render_vf(r, "md",
275
+ lambda g, f, t, S: vf_rings(g, f, t, S, n_base=8, spacing_base=3),
276
+ hf_distance(0.3, 0.02), PAL_STARS, f, t, S, sat=0.85)
277
+ return canvas
278
+ ```
279
+
280
+ ### Standard Scene (Two Grids + Blend)
281
+
282
+ ```python
283
+ def fx_tunnel_ripple(r, f, t, S):
284
+ """Two-grid scene: tunnel depth exclusion-blended with ripple."""
285
+ canvas_a = _render_vf(r, "md",
286
+ lambda g, f, t, S: vf_tunnel(g, f, t, S, speed=5.0, complexity=10) * 1.3,
287
+ hf_distance(0.55, 0.02), PAL_GREEK, f, t, S, sat=0.7)
288
+
289
+ canvas_b = _render_vf(r, "sm",
290
+ lambda g, f, t, S: vf_ripple(g, f, t, S,
291
+ sources=[(0.3,0.3), (0.7,0.7), (0.5,0.2)], freq=0.5, damping=0.012) * 1.4,
292
+ hf_angle(0.1), PAL_STARS, f, t, S, sat=0.8)
293
+
294
+ return blend_canvas(canvas_a, canvas_b, "exclusion", 0.8)
295
+ ```
296
+
297
+ ### Complex Scene (Three Grids + Conditional + Custom Rendering)
298
+
299
+ ```python
300
+ def fx_rings_explosion(r, f, t, S):
301
+ """Three-grid scene with particles and conditional kaleidoscope."""
302
+ # Layer 1: rings
303
+ canvas_a = _render_vf(r, "sm",
304
+ lambda g, f, t, S: vf_rings(g, f, t, S, n_base=10, spacing_base=2) * 1.4,
305
+ lambda g, f, t, S: (g.angle / (2*np.pi) + t * 0.15) % 1.0,
306
+ PAL_STARS, f, t, S, sat=0.9)
307
+
308
+ # Layer 2: vortex on different grid
309
+ canvas_b = _render_vf(r, "md",
310
+ lambda g, f, t, S: vf_vortex(g, f, t, S, twist=6.0) * 1.2,
311
+ hf_time_cycle(0.15), PAL_BLOCKS, f, t, S, sat=0.8)
312
+
313
+ result = blend_canvas(canvas_b, canvas_a, "screen", 0.7)
314
+
315
+ # Layer 3: particles (custom rendering, not _render_vf)
316
+ g = r.get_grid("sm")
317
+ if "px" not in S:
318
+ S["px"], S["py"], S["vx"], S["vy"], S["life"], S["pch"] = (
319
+ [], [], [], [], [], [])
320
+ if f.get("beat", 0) > 0.5:
321
+ chars = list("\u2605\u2736\u2733\u2738\u2726\u2728*+")
322
+ for _ in range(int(80 + f.get("rms", 0.3) * 120)):
323
+ ang = random.uniform(0, 2 * math.pi)
324
+ sp = random.uniform(1, 10) * (0.5 + f.get("sub_r", 0.3) * 2)
325
+ S["px"].append(float(g.cols // 2))
326
+ S["py"].append(float(g.rows // 2))
327
+ S["vx"].append(math.cos(ang) * sp * 2.5)
328
+ S["vy"].append(math.sin(ang) * sp)
329
+ S["life"].append(1.0)
330
+ S["pch"].append(random.choice(chars))
331
+
332
+ # Update + draw particles
333
+ ch_p = np.full((g.rows, g.cols), " ", dtype="U1")
334
+ co_p = np.zeros((g.rows, g.cols, 3), dtype=np.uint8)
335
+ i = 0
336
+ while i < len(S["px"]):
337
+ S["px"][i] += S["vx"][i]; S["py"][i] += S["vy"][i]
338
+ S["vy"][i] += 0.03; S["life"][i] -= 0.02
339
+ if S["life"][i] <= 0:
340
+ for k in ("px","py","vx","vy","life","pch"): S[k].pop(i)
341
+ else:
342
+ pr, pc = int(S["py"][i]), int(S["px"][i])
343
+ if 0 <= pr < g.rows and 0 <= pc < g.cols:
344
+ ch_p[pr, pc] = S["pch"][i]
345
+ co_p[pr, pc] = hsv2rgb_scalar(
346
+ 0.08 + (1-S["life"][i])*0.15, 0.95, S["life"][i])
347
+ i += 1
348
+
349
+ canvas_p = g.render(ch_p, co_p)
350
+ result = blend_canvas(result, canvas_p, "add", 0.8)
351
+
352
+ # Conditional kaleidoscope on strong beats
353
+ if f.get("bdecay", 0) > 0.4:
354
+ result = sh_kaleidoscope(result.copy(), folds=6)
355
+
356
+ return result
357
+ ```
358
+
359
+ ### Scene with Custom Character Rendering (Matrix Rain)
360
+
361
+ When you need per-cell control beyond what `_render_vf()` provides:
362
+
363
+ ```python
364
+ def fx_matrix_layered(r, f, t, S):
365
+ """Matrix rain blended with tunnel — two grids, screen blend."""
366
+ # Layer 1: Matrix rain (custom per-column rendering)
367
+ g = r.get_grid("md")
368
+ rows, cols = g.rows, g.cols
369
+ pal = PAL_KATA
370
+
371
+ if "ry" not in S or len(S["ry"]) != cols:
372
+ S["ry"] = np.random.uniform(-rows, rows, cols).astype(np.float32)
373
+ S["rsp"] = np.random.uniform(0.3, 2.0, cols).astype(np.float32)
374
+ S["rln"] = np.random.randint(8, 35, cols)
375
+ S["rch"] = np.random.randint(1, len(pal), (rows, cols))
376
+
377
+ speed = 0.6 + f.get("bass", 0.3) * 3
378
+ if f.get("beat", 0) > 0.5: speed *= 2.5
379
+ S["ry"] += S["rsp"] * speed
380
+
381
+ ch = np.full((rows, cols), " ", dtype="U1")
382
+ co = np.zeros((rows, cols, 3), dtype=np.uint8)
383
+ heads = S["ry"].astype(int)
384
+ for c in range(cols):
385
+ head = heads[c]
386
+ for i in range(S["rln"][c]):
387
+ row = head - i
388
+ if 0 <= row < rows:
389
+ fade = 1.0 - i / S["rln"][c]
390
+ ch[row, c] = pal[S["rch"][row, c] % len(pal)]
391
+ if i == 0:
392
+ v = int(min(255, fade * 300))
393
+ co[row, c] = (int(v*0.9), v, int(v*0.9))
394
+ else:
395
+ v = int(fade * 240)
396
+ co[row, c] = (int(v*0.1), v, int(v*0.4))
397
+ canvas_a = g.render(ch, co)
398
+
399
+ # Layer 2: Tunnel on sm grid for depth texture
400
+ canvas_b = _render_vf(r, "sm",
401
+ lambda g, f, t, S: vf_tunnel(g, f, t, S, speed=5.0, complexity=10),
402
+ hf_distance(0.3, 0.02), PAL_BLOCKS, f, t, S, sat=0.6)
403
+
404
+ return blend_canvas(canvas_a, canvas_b, "screen", 0.5)
405
+ ```
406
+
407
+ ---
408
+
409
+ ## Scene Table
410
+
411
+ The scene table defines the timeline: which scene plays when, with what configuration.
412
+
413
+ ### Structure
414
+
415
+ ```python
416
+ SCENES = [
417
+ {
418
+ "start": 0.0, # start time in seconds
419
+ "end": 3.96, # end time in seconds
420
+ "name": "starfield", # identifier (used for clip filenames)
421
+ "grid": "sm", # default grid (for render_clip setup)
422
+ "fx": fx_starfield, # scene function reference (must be module-level)
423
+ "gamma": 0.75, # tonemap gamma override (default 0.75)
424
+ "shaders": [ # shader chain (applied after tonemap + feedback)
425
+ ("bloom", {"thr": 120}),
426
+ ("vignette", {"s": 0.2}),
427
+ ("grain", {"amt": 8}),
428
+ ],
429
+ "feedback": None, # feedback buffer config (None = disabled)
430
+ # "feedback": {"decay": 0.8, "blend": "screen", "opacity": 0.3,
431
+ # "transform": "zoom", "transform_amt": 0.02, "hue_shift": 0.02},
432
+ },
433
+ {
434
+ "start": 3.96,
435
+ "end": 6.58,
436
+ "name": "matrix_layered",
437
+ "grid": "md",
438
+ "fx": fx_matrix_layered,
439
+ "shaders": [
440
+ ("crt", {"strength": 0.05}),
441
+ ("scanlines", {"intensity": 0.12}),
442
+ ("color_grade", {"tint": (0.7, 1.2, 0.7)}),
443
+ ("bloom", {"thr": 100}),
444
+ ],
445
+ "feedback": {"decay": 0.5, "blend": "add", "opacity": 0.2},
446
+ },
447
+ # ... more scenes ...
448
+ ]
449
+ ```
450
+
451
+ ### Beat-Synced Scene Cutting
452
+
453
+ Derive cut points from audio analysis:
454
+
455
+ ```python
456
+ # Get beat timestamps
457
+ beats = [fi / FPS for fi in range(N_FRAMES) if features["beat"][fi] > 0.5]
458
+
459
+ # Group beats into phrase boundaries (every 4-8 beats)
460
+ cuts = [0.0]
461
+ for i in range(0, len(beats), 4): # cut every 4 beats
462
+ cuts.append(beats[i])
463
+ cuts.append(DURATION)
464
+
465
+ # Or use the music's structure: silence gaps, energy changes
466
+ energy = features["rms"]
467
+ # Find timestamps where energy drops significantly -> natural break points
468
+ ```
469
+
470
+ ### `render_clip()` — The Render Loop
471
+
472
+ This function renders one scene to a clip file:
473
+
474
+ ```python
475
+ def render_clip(seg, features, clip_path):
476
+ r = Renderer()
477
+ r.set_grid(seg["grid"])
478
+ S = r.S
479
+ random.seed(hash(seg["id"]) + 42) # deterministic per scene
480
+
481
+ # Build shader chain from config
482
+ chain = ShaderChain()
483
+ for shader_name, kwargs in seg.get("shaders", []):
484
+ chain.add(shader_name, **kwargs)
485
+
486
+ # Setup feedback buffer
487
+ fb = None
488
+ fb_cfg = seg.get("feedback", None)
489
+ if fb_cfg:
490
+ fb = FeedbackBuffer()
491
+
492
+ fx_fn = seg["fx"]
493
+
494
+ # Open ffmpeg pipe
495
+ cmd = ["ffmpeg", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24",
496
+ "-s", f"{VW}x{VH}", "-r", str(FPS), "-i", "pipe:0",
497
+ "-c:v", "libx264", "-preset", "fast", "-crf", "20",
498
+ "-pix_fmt", "yuv420p", clip_path]
499
+ stderr_fh = open(clip_path.replace(".mp4", ".log"), "w")
500
+ pipe = subprocess.Popen(cmd, stdin=subprocess.PIPE,
501
+ stdout=subprocess.DEVNULL, stderr=stderr_fh)
502
+
503
+ for fi in range(seg["frame_start"], seg["frame_end"]):
504
+ t = fi / FPS
505
+ feat = {k: float(features[k][fi]) for k in features}
506
+
507
+ # 1. Scene renders canvas
508
+ canvas = fx_fn(r, feat, t, S)
509
+
510
+ # 2. Tonemap normalizes brightness
511
+ canvas = tonemap(canvas, gamma=seg.get("gamma", 0.75))
512
+
513
+ # 3. Feedback adds temporal recursion
514
+ if fb and fb_cfg:
515
+ canvas = fb.apply(canvas, **{k: fb_cfg[k] for k in fb_cfg})
516
+
517
+ # 4. Shader chain adds post-processing
518
+ canvas = chain.apply(canvas, f=feat, t=t)
519
+
520
+ pipe.stdin.write(canvas.tobytes())
521
+
522
+ pipe.stdin.close(); pipe.wait(); stderr_fh.close()
523
+ ```
524
+
525
+ ### Building Segments from Scene Table
526
+
527
+ ```python
528
+ segments = []
529
+ for i, scene in enumerate(SCENES):
530
+ segments.append({
531
+ "id": f"s{i:02d}_{scene['name']}",
532
+ "name": scene["name"],
533
+ "grid": scene["grid"],
534
+ "fx": scene["fx"],
535
+ "shaders": scene.get("shaders", []),
536
+ "feedback": scene.get("feedback", None),
537
+ "gamma": scene.get("gamma", 0.75),
538
+ "frame_start": int(scene["start"] * FPS),
539
+ "frame_end": int(scene["end"] * FPS),
540
+ })
541
+ ```
542
+
543
+ ### Parallel Rendering
544
+
545
+ Scenes are independent units dispatched to a process pool:
546
+
547
+ ```python
548
+ from concurrent.futures import ProcessPoolExecutor, as_completed
549
+
550
+ with ProcessPoolExecutor(max_workers=N_WORKERS) as pool:
551
+ futures = {
552
+ pool.submit(render_clip, seg, features, clip_path): seg["id"]
553
+ for seg, clip_path in zip(segments, clip_paths)
554
+ }
555
+ for fut in as_completed(futures):
556
+ try:
557
+ fut.result()
558
+ except Exception as e:
559
+ log(f"ERROR {futures[fut]}: {e}")
560
+ ```
561
+
562
+ **Pickling constraint**: `ProcessPoolExecutor` serializes arguments via pickle. Module-level functions can be pickled; lambdas and closures cannot. All `fx_*` scene functions MUST be defined at module level, not as closures or class methods.
563
+
564
+ ### Test-Frame Mode
565
+
566
+ Render a single frame at a specific timestamp to verify visuals without a full render:
567
+
568
+ ```python
569
+ if args.test_frame >= 0:
570
+ fi = min(int(args.test_frame * FPS), N_FRAMES - 1)
571
+ t = fi / FPS
572
+ feat = {k: float(features[k][fi]) for k in features}
573
+ scene = next(sc for sc in reversed(SCENES) if t >= sc["start"])
574
+ r = Renderer()
575
+ r.set_grid(scene["grid"])
576
+ canvas = scene["fx"](r, feat, t, r.S)
577
+ canvas = tonemap(canvas, gamma=scene.get("gamma", 0.75))
578
+ chain = ShaderChain()
579
+ for sn, kw in scene.get("shaders", []):
580
+ chain.add(sn, **kw)
581
+ canvas = chain.apply(canvas, f=feat, t=t)
582
+ Image.fromarray(canvas).save(f"test_{args.test_frame:.1f}s.png")
583
+ print(f"Mean brightness: {canvas.astype(float).mean():.1f}")
584
+ ```
585
+
586
+ CLI: `python reel.py --test-frame 10.0`
587
+
588
+ ---
589
+
590
+ ## Scene Design Checklist
591
+
592
+ For each scene:
593
+
594
+ 1. **Choose 2-3 grid sizes** — different scales create interference
595
+ 2. **Choose different value fields** per layer — don't use the same effect on every grid
596
+ 3. **Choose different hue fields** per layer — or at minimum different hue offsets
597
+ 4. **Choose different palettes** per layer — mixing PAL_RUNE with PAL_BLOCKS looks different from PAL_RUNE with PAL_DENSE
598
+ 5. **Choose a blend mode** that matches the energy — screen for bright, difference for psychedelic, exclusion for subtle
599
+ 6. **Add conditional effects** on beat — kaleidoscope, mirror, glitch
600
+ 7. **Configure feedback** for trailing/recursive looks — or None for clean cuts
601
+ 8. **Set gamma** if using destructive shaders (solarize, posterize)
602
+ 9. **Test with --test-frame** at the scene's midpoint before full render
603
+
604
+ ---
605
+
606
+ ## Scene Examples
607
+
608
+ Copy-paste-ready scene functions at increasing complexity. Each is a complete, working v2 scene function that returns a pixel canvas. See the Scene Protocol section above for the scene protocol and `composition.md` for blend modes and tonemap.
609
+
610
+ ---
611
+
612
+ ### Minimal — Single Grid, Single Effect
613
+
614
+ ### Breathing Plasma
615
+
616
+ One grid, one value field, one hue field. The simplest possible scene.
617
+
618
+ ```python
619
+ def fx_breathing_plasma(r, f, t, S):
620
+ """Plasma field with time-cycling hue. Audio modulates brightness."""
621
+ canvas = _render_vf(r, "md",
622
+ lambda g, f, t, S: vf_plasma(g, f, t, S) * 1.3,
623
+ hf_time_cycle(0.08), PAL_DENSE, f, t, S, sat=0.8)
624
+ return canvas
625
+ ```
626
+
627
+ ### Reaction-Diffusion Coral
628
+
629
+ Single grid, simulation-based field. Evolves organically over time.
630
+
631
+ ```python
632
+ def fx_coral(r, f, t, S):
633
+ """Gray-Scott reaction-diffusion — coral branching pattern.
634
+ Slow-evolving, organic. Best for ambient/chill sections."""
635
+ canvas = _render_vf(r, "sm",
636
+ lambda g, f, t, S: vf_reaction_diffusion(g, f, t, S,
637
+ feed=0.037, kill=0.060, steps_per_frame=6, init_mode="center"),
638
+ hf_distance(0.55, 0.015), PAL_DOTS, f, t, S, sat=0.7)
639
+ return canvas
640
+ ```
641
+
642
+ ### SDF Geometry
643
+
644
+ Geometric shapes from SDFs. Clean, precise, graphic.
645
+
646
+ ```python
647
+ def fx_sdf_rings(r, f, t, S):
648
+ """Concentric SDF rings with smooth pulsing."""
649
+ def val_fn(g, f, t, S):
650
+ d1 = sdf_ring(g, radius=0.15 + f.get("bass", 0.3) * 0.05, thickness=0.015)
651
+ d2 = sdf_ring(g, radius=0.25 + f.get("mid", 0.3) * 0.05, thickness=0.012)
652
+ d3 = sdf_ring(g, radius=0.35 + f.get("hi", 0.3) * 0.04, thickness=0.010)
653
+ combined = sdf_smooth_union(sdf_smooth_union(d1, d2, 0.05), d3, 0.05)
654
+ return sdf_glow(combined, falloff=0.08) * (0.5 + f.get("rms", 0.3) * 0.8)
655
+ canvas = _render_vf(r, "md", val_fn, hf_angle(0.0), PAL_STARS, f, t, S, sat=0.85)
656
+ return canvas
657
+ ```
658
+
659
+ ---
660
+
661
+ ### Standard — Two Grids + Blend
662
+
663
+ ### Tunnel Through Noise
664
+
665
+ Two grids at different densities, screen blended. The fine noise texture shows through the coarser tunnel characters.
666
+
667
+ ```python
668
+ def fx_tunnel_noise(r, f, t, S):
669
+ """Tunnel depth on md grid + fBM noise on sm grid, screen blended."""
670
+ canvas_a = _render_vf(r, "md",
671
+ lambda g, f, t, S: vf_tunnel(g, f, t, S, speed=4.0, complexity=8) * 1.2,
672
+ hf_distance(0.5, 0.02), PAL_BLOCKS, f, t, S, sat=0.7)
673
+
674
+ canvas_b = _render_vf(r, "sm",
675
+ lambda g, f, t, S: vf_fbm(g, f, t, S, octaves=4, freq=0.05, speed=0.15) * 1.3,
676
+ hf_time_cycle(0.06), PAL_RUNE, f, t, S, sat=0.6)
677
+
678
+ return blend_canvas(canvas_a, canvas_b, "screen", 0.7)
679
+ ```
680
+
681
+ ### Voronoi Cells + Spiral Overlay
682
+
683
+ Voronoi cell edges with a spiral arm pattern overlaid.
684
+
685
+ ```python
686
+ def fx_voronoi_spiral(r, f, t, S):
687
+ """Voronoi edge detection on md + logarithmic spiral on lg."""
688
+ canvas_a = _render_vf(r, "md",
689
+ lambda g, f, t, S: vf_voronoi(g, f, t, S,
690
+ n_cells=15, mode="edge", edge_width=2.0, speed=0.4),
691
+ hf_angle(0.2), PAL_CIRCUIT, f, t, S, sat=0.75)
692
+
693
+ canvas_b = _render_vf(r, "lg",
694
+ lambda g, f, t, S: vf_spiral(g, f, t, S, n_arms=4, tightness=3.0) * 1.2,
695
+ hf_distance(0.1, 0.03), PAL_BLOCKS, f, t, S, sat=0.9)
696
+
697
+ return blend_canvas(canvas_a, canvas_b, "exclusion", 0.6)
698
+ ```
699
+
700
+ ### Domain-Warped fBM
701
+
702
+ Two layers of the same fBM, one domain-warped, difference-blended for psychedelic organic texture.
703
+
704
+ ```python
705
+ def fx_organic_warp(r, f, t, S):
706
+ """Clean fBM vs domain-warped fBM, difference blended."""
707
+ canvas_a = _render_vf(r, "sm",
708
+ lambda g, f, t, S: vf_fbm(g, f, t, S, octaves=5, freq=0.04, speed=0.1),
709
+ hf_plasma(0.2), PAL_DENSE, f, t, S, sat=0.6)
710
+
711
+ canvas_b = _render_vf(r, "md",
712
+ lambda g, f, t, S: vf_domain_warp(g, f, t, S,
713
+ warp_strength=20.0, freq=0.05, speed=0.15),
714
+ hf_time_cycle(0.05), PAL_BRAILLE, f, t, S, sat=0.7)
715
+
716
+ return blend_canvas(canvas_a, canvas_b, "difference", 0.7)
717
+ ```
718
+
719
+ ---
720
+
721
+ ### Complex — Three Grids + Conditional + Feedback
722
+
723
+ ### Psychedelic Cathedral
724
+
725
+ Three-grid composition with beat-triggered kaleidoscope and feedback zoom tunnel. The most visually complex pattern.
726
+
727
+ ```python
728
+ def fx_cathedral(r, f, t, S):
729
+ """Three-layer cathedral: interference + rings + noise, kaleidoscope on beat,
730
+ feedback zoom tunnel."""
731
+ # Layer 1: interference pattern on sm grid
732
+ canvas_a = _render_vf(r, "sm",
733
+ lambda g, f, t, S: vf_interference(g, f, t, S, n_waves=7) * 1.3,
734
+ hf_angle(0.0), PAL_MATH, f, t, S, sat=0.8)
735
+
736
+ # Layer 2: pulsing rings on md grid
737
+ canvas_b = _render_vf(r, "md",
738
+ lambda g, f, t, S: vf_rings(g, f, t, S, n_base=10, spacing_base=3) * 1.4,
739
+ hf_distance(0.3, 0.02), PAL_STARS, f, t, S, sat=0.9)
740
+
741
+ # Layer 3: temporal noise on lg grid (slow morph)
742
+ canvas_c = _render_vf(r, "lg",
743
+ lambda g, f, t, S: vf_temporal_noise(g, f, t, S,
744
+ freq=0.04, t_freq=0.2, octaves=3),
745
+ hf_time_cycle(0.12), PAL_BLOCKS, f, t, S, sat=0.7)
746
+
747
+ # Blend: A screen B, then difference with C
748
+ result = blend_canvas(canvas_a, canvas_b, "screen", 0.8)
749
+ result = blend_canvas(result, canvas_c, "difference", 0.5)
750
+
751
+ # Beat-triggered kaleidoscope
752
+ if f.get("bdecay", 0) > 0.3:
753
+ folds = 6 if f.get("sub_r", 0.3) > 0.4 else 8
754
+ result = sh_kaleidoscope(result.copy(), folds=folds)
755
+
756
+ return result
757
+
758
+ # Scene table entry with feedback:
759
+ # {"start": 30.0, "end": 50.0, "name": "cathedral", "fx": fx_cathedral,
760
+ # "gamma": 0.65, "shaders": [("bloom", {"thr": 110}), ("chromatic", {"amt": 4}),
761
+ # ("vignette", {"s": 0.2}), ("grain", {"amt": 8})],
762
+ # "feedback": {"decay": 0.75, "blend": "screen", "opacity": 0.35,
763
+ # "transform": "zoom", "transform_amt": 0.012, "hue_shift": 0.015}}
764
+ ```
765
+
766
+ ### Masked Reaction-Diffusion with Attractor Overlay
767
+
768
+ Reaction-diffusion visible only through an animated iris mask, with a strange attractor density field underneath.
769
+
770
+ ```python
771
+ def fx_masked_life(r, f, t, S):
772
+ """Attractor base + reaction-diffusion visible through iris mask + particles."""
773
+ g_sm = r.get_grid("sm")
774
+ g_md = r.get_grid("md")
775
+
776
+ # Layer 1: strange attractor density field (background)
777
+ canvas_bg = _render_vf(r, "sm",
778
+ lambda g, f, t, S: vf_strange_attractor(g, f, t, S,
779
+ attractor="clifford", n_points=30000),
780
+ hf_time_cycle(0.04), PAL_DOTS, f, t, S, sat=0.5)
781
+
782
+ # Layer 2: reaction-diffusion (foreground, will be masked)
783
+ canvas_rd = _render_vf(r, "md",
784
+ lambda g, f, t, S: vf_reaction_diffusion(g, f, t, S,
785
+ feed=0.046, kill=0.063, steps_per_frame=4, init_mode="ring"),
786
+ hf_angle(0.15), PAL_HALFFILL, f, t, S, sat=0.85)
787
+
788
+ # Animated iris mask — opens over first 5 seconds of scene
789
+ scene_start = S.get("_scene_start", t)
790
+ if "_scene_start" not in S:
791
+ S["_scene_start"] = t
792
+ mask = mask_iris(g_md, t, scene_start, scene_start + 5.0,
793
+ max_radius=0.6)
794
+ canvas_rd = apply_mask_canvas(canvas_rd, mask, bg_canvas=canvas_bg)
795
+
796
+ # Layer 3: flow-field particles following the R-D gradient
797
+ rd_field = vf_reaction_diffusion(g_sm, f, t, S,
798
+ feed=0.046, kill=0.063, steps_per_frame=0) # read without stepping
799
+ ch_p, co_p = update_flow_particles(S, g_sm, f, rd_field,
800
+ n=300, speed=0.8, char_set=list("·•◦∘°"))
801
+ canvas_p = g_sm.render(ch_p, co_p)
802
+
803
+ result = blend_canvas(canvas_rd, canvas_p, "add", 0.7)
804
+ return result
805
+ ```
806
+
807
+ ### Morphing Field Sequence with Eased Keyframes
808
+
809
+ Demonstrates temporal coherence: smooth morphing between effects with keyframed parameters.
810
+
811
+ ```python
812
+ def fx_morphing_journey(r, f, t, S):
813
+ """Morphs through 4 value fields over 20 seconds with eased transitions.
814
+ Parameters (twist, arm count) also keyframed."""
815
+ # Keyframed twist parameter
816
+ twist = keyframe(t, [(0, 1.0), (5, 5.0), (10, 2.0), (15, 8.0), (20, 1.0)],
817
+ ease_fn=ease_in_out_cubic, loop=True)
818
+
819
+ # Sequence of value fields with 2s crossfade
820
+ fields = [
821
+ lambda g, f, t, S: vf_plasma(g, f, t, S),
822
+ lambda g, f, t, S: vf_vortex(g, f, t, S, twist=twist),
823
+ lambda g, f, t, S: vf_fbm(g, f, t, S, octaves=5, freq=0.04),
824
+ lambda g, f, t, S: vf_domain_warp(g, f, t, S, warp_strength=15),
825
+ ]
826
+ durations = [5.0, 5.0, 5.0, 5.0]
827
+
828
+ val_fn = lambda g, f, t, S: vf_sequence(g, f, t, S, fields, durations,
829
+ crossfade=2.0)
830
+
831
+ # Render with slowly rotating hue
832
+ canvas = _render_vf(r, "md", val_fn, hf_time_cycle(0.06),
833
+ PAL_DENSE, f, t, S, sat=0.8)
834
+
835
+ # Second layer: tiled version of same sequence at smaller grid
836
+ tiled_fn = lambda g, f, t, S: vf_sequence(
837
+ make_tgrid(g, *uv_tile(g, 3, 3, mirror=True)),
838
+ f, t, S, fields, durations, crossfade=2.0)
839
+ canvas_b = _render_vf(r, "sm", tiled_fn, hf_angle(0.1),
840
+ PAL_RUNE, f, t, S, sat=0.6)
841
+
842
+ return blend_canvas(canvas, canvas_b, "screen", 0.5)
843
+ ```
844
+
845
+ ---
846
+
847
+ ### Specialized — Unique State Patterns
848
+
849
+ ### Game of Life with Ghost Trails
850
+
851
+ Cellular automaton with analog fade trails. Beat injects random cells.
852
+
853
+ ```python
854
+ def fx_life(r, f, t, S):
855
+ """Conway's Game of Life with fading ghost trails.
856
+ Beat events inject random live cells for disruption."""
857
+ canvas = _render_vf(r, "sm",
858
+ lambda g, f, t, S: vf_game_of_life(g, f, t, S,
859
+ rule="life", steps_per_frame=1, fade=0.92, density=0.25),
860
+ hf_fixed(0.33), PAL_BLOCKS, f, t, S, sat=0.8)
861
+
862
+ # Overlay: coral automaton on lg grid for chunky texture
863
+ canvas_b = _render_vf(r, "lg",
864
+ lambda g, f, t, S: vf_game_of_life(g, f, t, S,
865
+ rule="coral", steps_per_frame=1, fade=0.85, density=0.15, seed=99),
866
+ hf_time_cycle(0.1), PAL_HATCH, f, t, S, sat=0.6)
867
+
868
+ return blend_canvas(canvas, canvas_b, "screen", 0.5)
869
+ ```
870
+
871
+ ### Boids Flock Over Voronoi
872
+
873
+ Emergent swarm movement over a cellular background.
874
+
875
+ ```python
876
+ def fx_boid_swarm(r, f, t, S):
877
+ """Flocking boids over animated voronoi cells."""
878
+ # Background: voronoi cells
879
+ canvas_bg = _render_vf(r, "md",
880
+ lambda g, f, t, S: vf_voronoi(g, f, t, S,
881
+ n_cells=20, mode="distance", speed=0.2),
882
+ hf_distance(0.4, 0.02), PAL_CIRCUIT, f, t, S, sat=0.5)
883
+
884
+ # Foreground: boids
885
+ g = r.get_grid("md")
886
+ ch_b, co_b = update_boids(S, g, f, n_boids=150, perception=6.0,
887
+ max_speed=1.5, char_set=list("▸▹►▻→⟶"))
888
+ canvas_boids = g.render(ch_b, co_b)
889
+
890
+ # Trails for the boids
891
+ # (boid positions are stored in S["boid_x"], S["boid_y"])
892
+ S["px"] = list(S.get("boid_x", []))
893
+ S["py"] = list(S.get("boid_y", []))
894
+ ch_t, co_t = draw_particle_trails(S, g, max_trail=6, fade=0.6)
895
+ canvas_trails = g.render(ch_t, co_t)
896
+
897
+ result = blend_canvas(canvas_bg, canvas_trails, "add", 0.3)
898
+ result = blend_canvas(result, canvas_boids, "add", 0.9)
899
+ return result
900
+ ```
901
+
902
+ ### Fire Rising Through SDF Text Stencil
903
+
904
+ Fire effect visible only through text letterforms.
905
+
906
+ ```python
907
+ def fx_fire_text(r, f, t, S):
908
+ """Fire columns visible through text stencil. Text acts as window."""
909
+ g = r.get_grid("lg")
910
+
911
+ # Full-screen fire (will be masked)
912
+ canvas_fire = _render_vf(r, "sm",
913
+ lambda g, f, t, S: np.clip(
914
+ vf_fbm(g, f, t, S, octaves=4, freq=0.08, speed=0.8) *
915
+ (1.0 - g.rr / g.rows) * # fade toward top
916
+ (0.6 + f.get("bass", 0.3) * 0.8), 0, 1),
917
+ hf_fixed(0.05), PAL_BLOCKS, f, t, S, sat=0.9) # fire hue
918
+
919
+ # Background: dark domain warp
920
+ canvas_bg = _render_vf(r, "md",
921
+ lambda g, f, t, S: vf_domain_warp(g, f, t, S,
922
+ warp_strength=8, freq=0.03, speed=0.05) * 0.3,
923
+ hf_fixed(0.6), PAL_DENSE, f, t, S, sat=0.4)
924
+
925
+ # Text stencil mask
926
+ mask = mask_text(g, "FIRE", row_frac=0.45)
927
+ # Expand vertically for multi-row coverage
928
+ for offset in range(-2, 3):
929
+ shifted = mask_text(g, "FIRE", row_frac=0.45 + offset / g.rows)
930
+ mask = mask_union(mask, shifted)
931
+
932
+ canvas_masked = apply_mask_canvas(canvas_fire, mask, bg_canvas=canvas_bg)
933
+ return canvas_masked
934
+ ```
935
+
936
+ ### Portrait Mode: Vertical Rain + Quote
937
+
938
+ Optimized for 9:16. Uses vertical space for long rain trails and stacked text.
939
+
940
+ ```python
941
+ def fx_portrait_rain_quote(r, f, t, S):
942
+ """Portrait-optimized: matrix rain (long vertical trails) with stacked quote.
943
+ Designed for 1080x1920 (9:16)."""
944
+ g = r.get_grid("md") # ~112x100 in portrait
945
+
946
+ # Matrix rain — long trails benefit from portrait's extra rows
947
+ ch, co, S = eff_matrix_rain(g, f, t, S,
948
+ hue=0.33, bri=0.6, pal=PAL_KATA, speed_base=0.4, speed_beat=2.5)
949
+ canvas_rain = g.render(ch, co)
950
+
951
+ # Tunnel depth underneath for texture
952
+ canvas_tunnel = _render_vf(r, "sm",
953
+ lambda g, f, t, S: vf_tunnel(g, f, t, S, speed=3.0, complexity=6) * 0.8,
954
+ hf_fixed(0.33), PAL_BLOCKS, f, t, S, sat=0.5)
955
+
956
+ result = blend_canvas(canvas_tunnel, canvas_rain, "screen", 0.8)
957
+
958
+ # Quote text — portrait layout: short lines, many of them
959
+ g_text = r.get_grid("lg") # ~90x80 in portrait
960
+ quote_lines = layout_text_portrait(
961
+ "The code is the art and the art is the code",
962
+ max_chars_per_line=20)
963
+ # Center vertically
964
+ block_start = (g_text.rows - len(quote_lines)) // 2
965
+ ch_t = np.full((g_text.rows, g_text.cols), " ", dtype="U1")
966
+ co_t = np.zeros((g_text.rows, g_text.cols, 3), dtype=np.uint8)
967
+ total_chars = sum(len(l) for l in quote_lines)
968
+ progress = min(1.0, (t - S.get("_scene_start", t)) / 3.0)
969
+ if "_scene_start" not in S: S["_scene_start"] = t
970
+ render_typewriter(ch_t, co_t, quote_lines, block_start, g_text.cols,
971
+ progress, total_chars, (200, 255, 220), t)
972
+ canvas_text = g_text.render(ch_t, co_t)
973
+
974
+ result = blend_canvas(result, canvas_text, "add", 0.9)
975
+ return result
976
+ ```
977
+
978
+ ---
979
+
980
+ ### Scene Table Template
981
+
982
+ Wire scenes into a complete video:
983
+
984
+ ```python
985
+ SCENES = [
986
+ {"start": 0.0, "end": 5.0, "name": "coral",
987
+ "fx": fx_coral, "grid": "sm", "gamma": 0.70,
988
+ "shaders": [("bloom", {"thr": 110}), ("vignette", {"s": 0.2})],
989
+ "feedback": {"decay": 0.8, "blend": "screen", "opacity": 0.3,
990
+ "transform": "zoom", "transform_amt": 0.01}},
991
+
992
+ {"start": 5.0, "end": 15.0, "name": "tunnel_noise",
993
+ "fx": fx_tunnel_noise, "grid": "md", "gamma": 0.75,
994
+ "shaders": [("chromatic", {"amt": 3}), ("bloom", {"thr": 120}),
995
+ ("scanlines", {"intensity": 0.06}), ("grain", {"amt": 8})],
996
+ "feedback": None},
997
+
998
+ {"start": 15.0, "end": 35.0, "name": "cathedral",
999
+ "fx": fx_cathedral, "grid": "sm", "gamma": 0.65,
1000
+ "shaders": [("bloom", {"thr": 100}), ("chromatic", {"amt": 5}),
1001
+ ("color_wobble", {"amt": 0.2}), ("vignette", {"s": 0.18})],
1002
+ "feedback": {"decay": 0.75, "blend": "screen", "opacity": 0.35,
1003
+ "transform": "zoom", "transform_amt": 0.012, "hue_shift": 0.015}},
1004
+
1005
+ {"start": 35.0, "end": 50.0, "name": "morphing",
1006
+ "fx": fx_morphing_journey, "grid": "md", "gamma": 0.70,
1007
+ "shaders": [("bloom", {"thr": 110}), ("grain", {"amt": 6})],
1008
+ "feedback": {"decay": 0.7, "blend": "screen", "opacity": 0.25,
1009
+ "transform": "rotate_cw", "transform_amt": 0.003}},
1010
+ ]
1011
+ ```
skills/.archive/ascii-video/references/shaders.md ADDED
@@ -0,0 +1,1385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Shader Pipeline & Composable Effects
2
+
3
+ Post-processing effects applied to the pixel canvas (`numpy uint8 array, shape (H,W,3)`) after character rendering and before encoding. Also covers **pixel-level blend modes**, **feedback buffers**, and the **ShaderChain** compositor.
4
+
5
+ > **See also:** composition.md (blend modes, tonemap) · effects.md · scenes.md · architecture.md · optimization.md · troubleshooting.md
6
+ >
7
+ > **Blend modes:** For the 20 pixel blend modes and `blend_canvas()`, see `composition.md`. All blending uses `blend_canvas(base, top, mode, opacity)`.
8
+
9
+ ## Design Philosophy
10
+
11
+ The shader pipeline turns raw ASCII renders into cinematic output. The system is designed for **composability** — every shader, blend mode, and feedback transform is an independent building block. Combining them creates infinite visual variety from a small set of primitives.
12
+
13
+ Choose shaders that reinforce the mood:
14
+ - **Retro terminal**: CRT + scanlines + grain + green/amber tint
15
+ - **Clean modern**: light bloom + subtle vignette only
16
+ - **Glitch art**: heavy chromatic aberration + glitch bands + color wobble + pixel sort
17
+ - **Cinematic**: bloom + vignette + grain + color grade
18
+ - **Dreamy**: heavy bloom + soft focus + color wobble + low contrast
19
+ - **Harsh/industrial**: high contrast + grain + scanlines + no bloom
20
+ - **Psychedelic**: color wobble + chromatic + kaleidoscope mirror + high saturation + feedback with hue shift
21
+ - **Data corruption**: pixel sort + data bend + block glitch + posterize
22
+ - **Recursive/infinite**: feedback buffer with zoom + screen blend + hue shift
23
+
24
+ ---
25
+
26
+ ## Pixel-Level Blend Modes
27
+
28
+ All operate on float32 [0,1] canvases for precision. Use `blend_canvas(base, top, mode, opacity)` which handles uint8 <-> float conversion.
29
+
30
+ ### Available Modes
31
+
32
+ ```python
33
+ BLEND_MODES = {
34
+ "normal": lambda a, b: b,
35
+ "add": lambda a, b: np.clip(a + b, 0, 1),
36
+ "subtract": lambda a, b: np.clip(a - b, 0, 1),
37
+ "multiply": lambda a, b: a * b,
38
+ "screen": lambda a, b: 1 - (1-a)*(1-b),
39
+ "overlay": # 2*a*b if a<0.5, else 1-2*(1-a)*(1-b)
40
+ "softlight": lambda a, b: (1-2*b)*a*a + 2*b*a,
41
+ "hardlight": # like overlay but keyed on b
42
+ "difference": lambda a, b: abs(a - b),
43
+ "exclusion": lambda a, b: a + b - 2*a*b,
44
+ "colordodge": lambda a, b: a / (1-b),
45
+ "colorburn": lambda a, b: 1 - (1-a)/b,
46
+ "linearlight": lambda a, b: a + 2*b - 1,
47
+ "vividlight": # burn if b<0.5, dodge if b>=0.5
48
+ "pin_light": # min(a,2b) if b<0.5, max(a,2b-1) if b>=0.5
49
+ "hard_mix": lambda a, b: 1 if a+b>=1 else 0,
50
+ "lighten": lambda a, b: max(a, b),
51
+ "darken": lambda a, b: min(a, b),
52
+ "grain_extract": lambda a, b: a - b + 0.5,
53
+ "grain_merge": lambda a, b: a + b - 0.5,
54
+ }
55
+ ```
56
+
57
+ ### Usage
58
+
59
+ ```python
60
+ def blend_canvas(base, top, mode="normal", opacity=1.0):
61
+ """Blend two uint8 canvases (H,W,3) using a named blend mode + opacity."""
62
+ af = base.astype(np.float32) / 255.0
63
+ bf = top.astype(np.float32) / 255.0
64
+ result = BLEND_MODES[mode](af, bf)
65
+ if opacity < 1.0:
66
+ result = af * (1-opacity) + result * opacity
67
+ return np.clip(result * 255, 0, 255).astype(np.uint8)
68
+
69
+ # Multi-layer compositing
70
+ result = blend_canvas(base, layer_a, "screen", 0.7)
71
+ result = blend_canvas(result, layer_b, "difference", 0.5)
72
+ result = blend_canvas(result, layer_c, "multiply", 0.3)
73
+ ```
74
+
75
+ ### Creative Combinations
76
+
77
+ - **Feedback + difference** = psychedelic color evolution (each frame XORs with the previous)
78
+ - **Screen + screen** = additive glow stacking
79
+ - **Multiply** on two different effects = only shows where both have brightness (intersection)
80
+ - **Exclusion** between two layers = creates complementary patterns where they differ
81
+ - **Color dodge/burn** = extreme contrast enhancement at overlap zones
82
+ - **Hard mix** = reduces everything to pure black/white/color at intersections
83
+
84
+ ---
85
+
86
+ ## Feedback Buffer
87
+
88
+ Recursive temporal effect: frame N-1 feeds back into frame N with decay and optional spatial transform. Creates trails, echoes, smearing, zoom tunnels, rotation feedback, rainbow trails.
89
+
90
+ ```python
91
+ class FeedbackBuffer:
92
+ def __init__(self):
93
+ self.buf = None # previous frame (float32, 0-1)
94
+
95
+ def apply(self, canvas, decay=0.85, blend="screen", opacity=0.5,
96
+ transform=None, transform_amt=0.02, hue_shift=0.0):
97
+ """Mix current frame with decayed/transformed previous frame.
98
+
99
+ Args:
100
+ canvas: current frame (uint8 H,W,3)
101
+ decay: how fast old frame fades (0=instant, 1=permanent)
102
+ blend: blend mode for mixing feedback
103
+ opacity: strength of feedback mix
104
+ transform: None, "zoom", "shrink", "rotate_cw", "rotate_ccw",
105
+ "shift_up", "shift_down", "mirror_h"
106
+ transform_amt: strength of spatial transform per frame
107
+ hue_shift: rotate hue of feedback buffer each frame (0-1)
108
+ """
109
+ ```
110
+
111
+ ### Feedback Presets
112
+
113
+ ```python
114
+ # Infinite zoom tunnel
115
+ fb_cfg = {"decay": 0.8, "blend": "screen", "opacity": 0.4,
116
+ "transform": "zoom", "transform_amt": 0.015}
117
+
118
+ # Rainbow trails (psychedelic)
119
+ fb_cfg = {"decay": 0.7, "blend": "screen", "opacity": 0.3,
120
+ "transform": "zoom", "transform_amt": 0.01, "hue_shift": 0.02}
121
+
122
+ # Ghostly echo (horror)
123
+ fb_cfg = {"decay": 0.9, "blend": "add", "opacity": 0.15,
124
+ "transform": "shift_up", "transform_amt": 0.01}
125
+
126
+ # Kaleidoscopic recursion
127
+ fb_cfg = {"decay": 0.75, "blend": "screen", "opacity": 0.35,
128
+ "transform": "rotate_cw", "transform_amt": 0.005, "hue_shift": 0.01}
129
+
130
+ # Color evolution (abstract)
131
+ fb_cfg = {"decay": 0.8, "blend": "difference", "opacity": 0.4, "hue_shift": 0.03}
132
+
133
+ # Multiplied depth
134
+ fb_cfg = {"decay": 0.65, "blend": "multiply", "opacity": 0.3, "transform": "mirror_h"}
135
+
136
+ # Rising heat haze
137
+ fb_cfg = {"decay": 0.5, "blend": "add", "opacity": 0.2,
138
+ "transform": "shift_up", "transform_amt": 0.02}
139
+ ```
140
+
141
+ ---
142
+
143
+ ## ShaderChain
144
+
145
+ Composable shader pipeline. Build chains of named shaders with parameters. Order matters — shaders are applied sequentially to the canvas.
146
+
147
+ ```python
148
+ class ShaderChain:
149
+ """Composable shader pipeline.
150
+
151
+ Usage:
152
+ chain = ShaderChain()
153
+ chain.add("bloom", thr=120)
154
+ chain.add("chromatic", amt=5)
155
+ chain.add("kaleidoscope", folds=6)
156
+ chain.add("vignette", s=0.2)
157
+ chain.add("grain", amt=12)
158
+ canvas = chain.apply(canvas, f=features, t=time)
159
+ """
160
+ def __init__(self):
161
+ self.steps = []
162
+
163
+ def add(self, shader_name, **kwargs):
164
+ self.steps.append((shader_name, kwargs))
165
+ return self # chainable
166
+
167
+ def apply(self, canvas, f=None, t=0):
168
+ if f is None: f = {}
169
+ for name, kwargs in self.steps:
170
+ canvas = _apply_shader_step(canvas, name, kwargs, f, t)
171
+ return canvas
172
+ ```
173
+
174
+ ### `_apply_shader_step()` — Full Dispatch Function
175
+
176
+ Routes shader names to implementations. Some shaders have **audio-reactive scaling** — the dispatch function reads `f["bdecay"]` and `f["rms"]` to modulate parameters on the beat.
177
+
178
+ ```python
179
+ def _apply_shader_step(canvas, name, kwargs, f, t):
180
+ """Dispatch a single shader by name with kwargs.
181
+
182
+ Args:
183
+ canvas: uint8 (H,W,3) pixel array
184
+ name: shader key string (e.g. "bloom", "chromatic")
185
+ kwargs: dict of shader parameters
186
+ f: audio features dict (keys: bdecay, rms, sub, etc.)
187
+ t: current time in seconds (float)
188
+ Returns:
189
+ canvas: uint8 (H,W,3) — processed
190
+ """
191
+ bd = f.get("bdecay", 0) # beat decay (0-1, high on beat)
192
+ rms = f.get("rms", 0.3) # audio energy (0-1)
193
+
194
+ # --- Geometry ---
195
+ if name == "crt":
196
+ return sh_crt(canvas, kwargs.get("strength", 0.05))
197
+ elif name == "pixelate":
198
+ return sh_pixelate(canvas, kwargs.get("block", 4))
199
+ elif name == "wave_distort":
200
+ return sh_wave_distort(canvas, t,
201
+ kwargs.get("freq", 0.02), kwargs.get("amp", 8), kwargs.get("axis", "x"))
202
+ elif name == "kaleidoscope":
203
+ return sh_kaleidoscope(canvas.copy(), kwargs.get("folds", 6))
204
+ elif name == "mirror_h":
205
+ return sh_mirror_h(canvas.copy())
206
+ elif name == "mirror_v":
207
+ return sh_mirror_v(canvas.copy())
208
+ elif name == "mirror_quad":
209
+ return sh_mirror_quad(canvas.copy())
210
+ elif name == "mirror_diag":
211
+ return sh_mirror_diag(canvas.copy())
212
+
213
+ # --- Channel ---
214
+ elif name == "chromatic":
215
+ base = kwargs.get("amt", 3)
216
+ return sh_chromatic(canvas, max(1, int(base * (0.4 + bd * 0.8))))
217
+ elif name == "channel_shift":
218
+ return sh_channel_shift(canvas,
219
+ kwargs.get("r", (0,0)), kwargs.get("g", (0,0)), kwargs.get("b", (0,0)))
220
+ elif name == "channel_swap":
221
+ return sh_channel_swap(canvas, kwargs.get("order", (2,1,0)))
222
+ elif name == "rgb_split_radial":
223
+ return sh_rgb_split_radial(canvas, kwargs.get("strength", 5))
224
+
225
+ # --- Color ---
226
+ elif name == "invert":
227
+ return sh_invert(canvas)
228
+ elif name == "posterize":
229
+ return sh_posterize(canvas, kwargs.get("levels", 4))
230
+ elif name == "threshold":
231
+ return sh_threshold(canvas, kwargs.get("thr", 128))
232
+ elif name == "solarize":
233
+ return sh_solarize(canvas, kwargs.get("threshold", 128))
234
+ elif name == "hue_rotate":
235
+ return sh_hue_rotate(canvas, kwargs.get("amount", 0.1))
236
+ elif name == "saturation":
237
+ return sh_saturation(canvas, kwargs.get("factor", 1.5))
238
+ elif name == "color_grade":
239
+ return sh_color_grade(canvas, kwargs.get("tint", (1,1,1)))
240
+ elif name == "color_wobble":
241
+ return sh_color_wobble(canvas, t, kwargs.get("amt", 0.3) * (0.5 + rms * 0.8))
242
+ elif name == "color_ramp":
243
+ return sh_color_ramp(canvas, kwargs.get("ramp", [(0,0,0),(255,255,255)]))
244
+
245
+ # --- Glow / Blur ---
246
+ elif name == "bloom":
247
+ return sh_bloom(canvas, kwargs.get("thr", 130))
248
+ elif name == "edge_glow":
249
+ return sh_edge_glow(canvas, kwargs.get("hue", 0.5))
250
+ elif name == "soft_focus":
251
+ return sh_soft_focus(canvas, kwargs.get("strength", 0.3))
252
+ elif name == "radial_blur":
253
+ return sh_radial_blur(canvas, kwargs.get("strength", 0.03))
254
+
255
+ # --- Noise ---
256
+ elif name == "grain":
257
+ return sh_grain(canvas, int(kwargs.get("amt", 10) * (0.5 + rms * 0.8)))
258
+ elif name == "static":
259
+ return sh_static_noise(canvas, kwargs.get("density", 0.05), kwargs.get("color", True))
260
+
261
+ # --- Lines / Patterns ---
262
+ elif name == "scanlines":
263
+ return sh_scanlines(canvas, kwargs.get("intensity", 0.08), kwargs.get("spacing", 3))
264
+ elif name == "halftone":
265
+ return sh_halftone(canvas, kwargs.get("dot_size", 6))
266
+
267
+ # --- Tone ---
268
+ elif name == "vignette":
269
+ return sh_vignette(canvas, kwargs.get("s", 0.22))
270
+ elif name == "contrast":
271
+ return sh_contrast(canvas, kwargs.get("factor", 1.3))
272
+ elif name == "gamma":
273
+ return sh_gamma(canvas, kwargs.get("gamma", 1.5))
274
+ elif name == "levels":
275
+ return sh_levels(canvas,
276
+ kwargs.get("black", 0), kwargs.get("white", 255), kwargs.get("midtone", 1.0))
277
+ elif name == "brightness":
278
+ return sh_brightness(canvas, kwargs.get("factor", 1.5))
279
+
280
+ # --- Glitch / Data ---
281
+ elif name == "glitch_bands":
282
+ return sh_glitch_bands(canvas, f)
283
+ elif name == "block_glitch":
284
+ return sh_block_glitch(canvas, kwargs.get("n_blocks", 8), kwargs.get("max_size", 40))
285
+ elif name == "pixel_sort":
286
+ return sh_pixel_sort(canvas, kwargs.get("threshold", 100), kwargs.get("direction", "h"))
287
+ elif name == "data_bend":
288
+ return sh_data_bend(canvas, kwargs.get("offset", 1000), kwargs.get("chunk", 500))
289
+
290
+ else:
291
+ return canvas # unknown shader — passthrough
292
+ ```
293
+
294
+ ### Audio-Reactive Shaders
295
+
296
+ Three shaders scale their parameters based on audio features:
297
+
298
+ | Shader | Reactive To | Effect |
299
+ |--------|------------|--------|
300
+ | `chromatic` | `bdecay` | `amt * (0.4 + bdecay * 0.8)` — aberration kicks on beats |
301
+ | `color_wobble` | `rms` | `amt * (0.5 + rms * 0.8)` — wobble intensity follows energy |
302
+ | `grain` | `rms` | `amt * (0.5 + rms * 0.8)` — grain rougher in loud sections |
303
+ | `glitch_bands` | `bdecay`, `sub` | Number of bands and displacement scale with beat energy |
304
+
305
+ To make any shader beat-reactive, scale its parameter in the dispatch: `base_val * (low + bd * range)`.
306
+
307
+ ---
308
+
309
+ ## Full Shader Catalog
310
+
311
+ ### Geometry Shaders
312
+
313
+ | Shader | Key Params | Description |
314
+ |--------|-----------|-------------|
315
+ | `crt` | `strength=0.05` | CRT barrel distortion (cached remap) |
316
+ | `pixelate` | `block=4` | Reduce effective resolution |
317
+ | `wave_distort` | `freq, amp, axis` | Sinusoidal row/column displacement |
318
+ | `kaleidoscope` | `folds=6` | Radial symmetry via polar remapping |
319
+ | `mirror_h` | — | Horizontal mirror |
320
+ | `mirror_v` | — | Vertical mirror |
321
+ | `mirror_quad` | — | 4-fold mirror |
322
+ | `mirror_diag` | — | Diagonal mirror |
323
+
324
+ ### Channel Manipulation
325
+
326
+ | Shader | Key Params | Description |
327
+ |--------|-----------|-------------|
328
+ | `chromatic` | `amt=3` | R/B channel horizontal shift (beat-reactive) |
329
+ | `channel_shift` | `r=(sx,sy), g, b` | Independent per-channel x,y shifting |
330
+ | `channel_swap` | `order=(2,1,0)` | Reorder RGB channels (BGR, GRB, etc.) |
331
+ | `rgb_split_radial` | `strength=5` | Chromatic aberration radiating from center |
332
+
333
+ ### Color Manipulation
334
+
335
+ | Shader | Key Params | Description |
336
+ |--------|-----------|-------------|
337
+ | `invert` | — | Negate all colors |
338
+ | `posterize` | `levels=4` | Reduce color depth to N levels |
339
+ | `threshold` | `thr=128` | Binary black/white |
340
+ | `solarize` | `threshold=128` | Invert pixels above threshold |
341
+ | `hue_rotate` | `amount=0.1` | Rotate all hues by amount (0-1) |
342
+ | `saturation` | `factor=1.5` | Scale saturation (>1=more, <1=less) |
343
+ | `color_grade` | `tint=(r,g,b)` | Per-channel multiplier |
344
+ | `color_wobble` | `amt=0.3` | Time-varying per-channel sine modulation |
345
+ | `color_ramp` | `ramp=[(R,G,B),...]` | Map luminance to custom color gradient |
346
+
347
+ ### Glow / Blur
348
+
349
+ | Shader | Key Params | Description |
350
+ |--------|-----------|-------------|
351
+ | `bloom` | `thr=130` | Bright area glow (4x downsample + box blur) |
352
+ | `edge_glow` | `hue=0.5` | Detect edges, add colored overlay |
353
+ | `soft_focus` | `strength=0.3` | Blend with blurred version |
354
+ | `radial_blur` | `strength=0.03` | Zoom blur from center outward |
355
+
356
+ ### Noise / Grain
357
+
358
+ | Shader | Key Params | Description |
359
+ |--------|-----------|-------------|
360
+ | `grain` | `amt=10` | 2x-downsampled film grain (beat-reactive) |
361
+ | `static` | `density=0.05, color=True` | Random pixel noise (TV static) |
362
+
363
+ ### Lines / Patterns
364
+
365
+ | Shader | Key Params | Description |
366
+ |--------|-----------|-------------|
367
+ | `scanlines` | `intensity=0.08, spacing=3` | Darken every Nth row |
368
+ | `halftone` | `dot_size=6` | Halftone dot pattern overlay |
369
+
370
+ ### Tone
371
+
372
+ | Shader | Key Params | Description |
373
+ |--------|-----------|-------------|
374
+ | `vignette` | `s=0.22` | Edge darkening (cached distance field) |
375
+ | `contrast` | `factor=1.3` | Adjust contrast around midpoint 128 |
376
+ | `gamma` | `gamma=1.5` | Gamma correction (>1=brighter mids) |
377
+ | `levels` | `black, white, midtone` | Levels adjustment (Photoshop-style) |
378
+ | `brightness` | `factor=1.5` | Global brightness multiplier |
379
+
380
+ ### Glitch / Data
381
+
382
+ | Shader | Key Params | Description |
383
+ |--------|-----------|-------------|
384
+ | `glitch_bands` | (uses `f`) | Beat-reactive horizontal row displacement |
385
+ | `block_glitch` | `n_blocks=8, max_size=40` | Random rectangular block displacement |
386
+ | `pixel_sort` | `threshold=100, direction="h"` | Sort pixels by brightness in rows/columns |
387
+ | `data_bend` | `offset, chunk` | Raw byte displacement (datamoshing) |
388
+
389
+ ---
390
+
391
+ ## Shader Implementations
392
+
393
+ Every shader function takes a canvas (`uint8 H,W,3`) and returns a canvas of the same shape. The naming convention is `sh_<name>`. Geometry shaders that build coordinate remap tables should **cache** them since the table only depends on resolution + parameters, not on frame content.
394
+
395
+ ### Helpers
396
+
397
+ Shaders that manipulate hue/saturation need vectorized HSV conversion:
398
+
399
+ ```python
400
+ def rgb2hsv(r, g, b):
401
+ """Vectorized RGB (0-255 uint8) -> HSV (float32 0-1)."""
402
+ rf = r.astype(np.float32) / 255.0
403
+ gf = g.astype(np.float32) / 255.0
404
+ bf = b.astype(np.float32) / 255.0
405
+ cmax = np.maximum(np.maximum(rf, gf), bf)
406
+ cmin = np.minimum(np.minimum(rf, gf), bf)
407
+ delta = cmax - cmin + 1e-10
408
+ h = np.zeros_like(rf)
409
+ m = cmax == rf; h[m] = ((gf[m] - bf[m]) / delta[m]) % 6
410
+ m = cmax == gf; h[m] = (bf[m] - rf[m]) / delta[m] + 2
411
+ m = cmax == bf; h[m] = (rf[m] - gf[m]) / delta[m] + 4
412
+ h = h / 6.0 % 1.0
413
+ s = np.where(cmax > 0, delta / (cmax + 1e-10), 0)
414
+ return h, s, cmax
415
+
416
+ def hsv2rgb(h, s, v):
417
+ """Vectorized HSV->RGB. h,s,v are numpy float32 arrays."""
418
+ h = h % 1.0
419
+ c = v * s; x = c * (1 - np.abs((h * 6) % 2 - 1)); m = v - c
420
+ r = np.zeros_like(h); g = np.zeros_like(h); b = np.zeros_like(h)
421
+ mask = h < 1/6; r[mask]=c[mask]; g[mask]=x[mask]
422
+ mask = (h>=1/6)&(h<2/6); r[mask]=x[mask]; g[mask]=c[mask]
423
+ mask = (h>=2/6)&(h<3/6); g[mask]=c[mask]; b[mask]=x[mask]
424
+ mask = (h>=3/6)&(h<4/6); g[mask]=x[mask]; b[mask]=c[mask]
425
+ mask = (h>=4/6)&(h<5/6); r[mask]=x[mask]; b[mask]=c[mask]
426
+ mask = h >= 5/6; r[mask]=c[mask]; b[mask]=x[mask]
427
+ R = np.clip((r+m)*255, 0, 255).astype(np.uint8)
428
+ G = np.clip((g+m)*255, 0, 255).astype(np.uint8)
429
+ B = np.clip((b+m)*255, 0, 255).astype(np.uint8)
430
+ return R, G, B
431
+
432
+ def mkc(R, G, B, rows, cols):
433
+ """Stack R,G,B uint8 arrays into (rows,cols,3) canvas."""
434
+ o = np.zeros((rows, cols, 3), dtype=np.uint8)
435
+ o[:,:,0] = R; o[:,:,1] = G; o[:,:,2] = B
436
+ return o
437
+ ```
438
+
439
+ ---
440
+
441
+ ### Geometry Shaders
442
+
443
+ #### CRT Barrel Distortion
444
+ Cache the coordinate remap — it never changes per frame:
445
+ ```python
446
+ _crt_cache = {}
447
+ def sh_crt(c, strength=0.05):
448
+ k = (c.shape[0], c.shape[1], round(strength, 3))
449
+ if k not in _crt_cache:
450
+ h, w = c.shape[:2]; cy, cx = h/2, w/2
451
+ Y = np.arange(h, dtype=np.float32)[:, None]
452
+ X = np.arange(w, dtype=np.float32)[None, :]
453
+ ny = (Y - cy) / cy; nx = (X - cx) / cx
454
+ r2 = nx**2 + ny**2
455
+ factor = 1 + strength * r2
456
+ sx = np.clip((nx * factor * cx + cx), 0, w-1).astype(np.int32)
457
+ sy = np.clip((ny * factor * cy + cy), 0, h-1).astype(np.int32)
458
+ _crt_cache[k] = (sy, sx)
459
+ sy, sx = _crt_cache[k]
460
+ return c[sy, sx]
461
+ ```
462
+
463
+ #### Pixelate
464
+ ```python
465
+ def sh_pixelate(c, block=4):
466
+ """Reduce effective resolution."""
467
+ sm = c[::block, ::block]
468
+ return np.repeat(np.repeat(sm, block, axis=0), block, axis=1)[:c.shape[0], :c.shape[1]]
469
+ ```
470
+
471
+ #### Wave Distort
472
+ ```python
473
+ def sh_wave_distort(c, t, freq=0.02, amp=8, axis="x"):
474
+ """Sinusoidal row/column displacement. Uses time t for animation."""
475
+ h, w = c.shape[:2]
476
+ out = c.copy()
477
+ if axis == "x":
478
+ for y in range(h):
479
+ shift = int(amp * math.sin(y * freq + t * 3))
480
+ out[y] = np.roll(c[y], shift, axis=0)
481
+ else:
482
+ for x in range(w):
483
+ shift = int(amp * math.sin(x * freq + t * 3))
484
+ out[:, x] = np.roll(c[:, x], shift, axis=0)
485
+ return out
486
+ ```
487
+
488
+ #### Displacement Map
489
+ ```python
490
+ def sh_displacement_map(c, dx_map, dy_map, strength=10):
491
+ """Displace pixels using float32 displacement maps (same HxW as c).
492
+ dx_map/dy_map: positive = shift right/down."""
493
+ h, w = c.shape[:2]
494
+ Y = np.arange(h)[:, None]; X = np.arange(w)[None, :]
495
+ ny = np.clip((Y + (dy_map * strength).astype(int)), 0, h-1)
496
+ nx = np.clip((X + (dx_map * strength).astype(int)), 0, w-1)
497
+ return c[ny, nx]
498
+ ```
499
+
500
+ #### Kaleidoscope
501
+ ```python
502
+ def sh_kaleidoscope(c, folds=6):
503
+ """Radial symmetry by polar coordinate remapping."""
504
+ h, w = c.shape[:2]; cy, cx = h//2, w//2
505
+ Y = np.arange(h, dtype=np.float32)[:, None] - cy
506
+ X = np.arange(w, dtype=np.float32)[None, :] - cx
507
+ angle = np.arctan2(Y, X)
508
+ dist = np.sqrt(X**2 + Y**2)
509
+ wedge = 2 * np.pi / folds
510
+ folded_angle = np.abs((angle % wedge) - wedge/2)
511
+ ny = np.clip((cy + dist * np.sin(folded_angle)).astype(int), 0, h-1)
512
+ nx = np.clip((cx + dist * np.cos(folded_angle)).astype(int), 0, w-1)
513
+ return c[ny, nx]
514
+ ```
515
+
516
+ #### Mirror Variants
517
+ ```python
518
+ def sh_mirror_h(c):
519
+ """Horizontal mirror — left half reflected to right."""
520
+ w = c.shape[1]; c[:, w//2:] = c[:, :w//2][:, ::-1]; return c
521
+
522
+ def sh_mirror_v(c):
523
+ """Vertical mirror — top half reflected to bottom."""
524
+ h = c.shape[0]; c[h//2:, :] = c[:h//2, :][::-1, :]; return c
525
+
526
+ def sh_mirror_quad(c):
527
+ """4-fold mirror — top-left quadrant reflected to all four."""
528
+ h, w = c.shape[:2]; hh, hw = h//2, w//2
529
+ tl = c[:hh, :hw].copy()
530
+ c[:hh, hw:hw+tl.shape[1]] = tl[:, ::-1]
531
+ c[hh:hh+tl.shape[0], :hw] = tl[::-1, :]
532
+ c[hh:hh+tl.shape[0], hw:hw+tl.shape[1]] = tl[::-1, ::-1]
533
+ return c
534
+
535
+ def sh_mirror_diag(c):
536
+ """Diagonal mirror — top-left triangle reflected."""
537
+ h, w = c.shape[:2]
538
+ for y in range(h):
539
+ x_cut = int(w * y / h)
540
+ if x_cut > 0 and x_cut < w:
541
+ c[y, x_cut:] = c[y, :x_cut+1][::-1][:w-x_cut]
542
+ return c
543
+ ```
544
+
545
+ > **Note:** Mirror shaders mutate in-place. The dispatch function passes `canvas.copy()` to avoid corrupting the original.
546
+
547
+ ---
548
+
549
+ ### Channel Manipulation Shaders
550
+
551
+ #### Chromatic Aberration
552
+ ```python
553
+ def sh_chromatic(c, amt=3):
554
+ """R/B channel horizontal shift. Beat-reactive in dispatch (amt scaled by bdecay)."""
555
+ if amt < 1: return c
556
+ a = int(amt)
557
+ o = c.copy()
558
+ o[:, a:, 0] = c[:, :-a, 0] # red shifts right
559
+ o[:, :-a, 2] = c[:, a:, 2] # blue shifts left
560
+ return o
561
+ ```
562
+
563
+ #### Channel Shift
564
+ ```python
565
+ def sh_channel_shift(c, r_shift=(0,0), g_shift=(0,0), b_shift=(0,0)):
566
+ """Independent per-channel x,y shifting."""
567
+ o = c.copy()
568
+ for ch_i, (sx, sy) in enumerate([r_shift, g_shift, b_shift]):
569
+ if sx != 0: o[:,:,ch_i] = np.roll(c[:,:,ch_i], sx, axis=1)
570
+ if sy != 0: o[:,:,ch_i] = np.roll(o[:,:,ch_i], sy, axis=0)
571
+ return o
572
+ ```
573
+
574
+ #### Channel Swap
575
+ ```python
576
+ def sh_channel_swap(c, order=(2,1,0)):
577
+ """Reorder RGB channels. (2,1,0)=BGR, (1,0,2)=GRB, etc."""
578
+ return c[:, :, list(order)]
579
+ ```
580
+
581
+ #### RGB Split Radial
582
+ ```python
583
+ def sh_rgb_split_radial(c, strength=5):
584
+ """Chromatic aberration radiating from center — stronger at edges."""
585
+ h, w = c.shape[:2]; cy, cx = h//2, w//2
586
+ Y = np.arange(h, dtype=np.float32)[:, None]
587
+ X = np.arange(w, dtype=np.float32)[None, :]
588
+ dist = np.sqrt((Y-cy)**2 + (X-cx)**2)
589
+ max_dist = np.sqrt(cy**2 + cx**2)
590
+ factor = dist / max_dist * strength
591
+ dy = ((Y-cy) / (dist+1) * factor).astype(int)
592
+ dx = ((X-cx) / (dist+1) * factor).astype(int)
593
+ out = c.copy()
594
+ ry = np.clip(Y.astype(int)+dy, 0, h-1); rx = np.clip(X.astype(int)+dx, 0, w-1)
595
+ out[:,:,0] = c[ry, rx, 0] # red shifts outward
596
+ by = np.clip(Y.astype(int)-dy, 0, h-1); bx = np.clip(X.astype(int)-dx, 0, w-1)
597
+ out[:,:,2] = c[by, bx, 2] # blue shifts inward
598
+ return out
599
+ ```
600
+
601
+ ---
602
+
603
+ ### Color Manipulation Shaders
604
+
605
+ #### Invert
606
+ ```python
607
+ def sh_invert(c):
608
+ return 255 - c
609
+ ```
610
+
611
+ #### Posterize
612
+ ```python
613
+ def sh_posterize(c, levels=4):
614
+ """Reduce color depth to N levels per channel."""
615
+ step = 256.0 / levels
616
+ return (np.floor(c.astype(np.float32) / step) * step).astype(np.uint8)
617
+ ```
618
+
619
+ #### Threshold
620
+ ```python
621
+ def sh_threshold(c, thr=128):
622
+ """Binary black/white at threshold."""
623
+ gray = c.astype(np.float32).mean(axis=2)
624
+ out = np.zeros_like(c); out[gray > thr] = 255
625
+ return out
626
+ ```
627
+
628
+ #### Solarize
629
+ ```python
630
+ def sh_solarize(c, threshold=128):
631
+ """Invert pixels above threshold — classic darkroom effect."""
632
+ o = c.copy(); mask = c > threshold; o[mask] = 255 - c[mask]
633
+ return o
634
+ ```
635
+
636
+ #### Hue Rotate
637
+ ```python
638
+ def sh_hue_rotate(c, amount=0.1):
639
+ """Rotate all hues by amount (0-1)."""
640
+ h, s, v = rgb2hsv(c[:,:,0], c[:,:,1], c[:,:,2])
641
+ h = (h + amount) % 1.0
642
+ R, G, B = hsv2rgb(h, s, v)
643
+ return mkc(R, G, B, c.shape[0], c.shape[1])
644
+ ```
645
+
646
+ #### Saturation
647
+ ```python
648
+ def sh_saturation(c, factor=1.5):
649
+ """Adjust saturation. >1=more saturated, <1=desaturated."""
650
+ h, s, v = rgb2hsv(c[:,:,0], c[:,:,1], c[:,:,2])
651
+ s = np.clip(s * factor, 0, 1)
652
+ R, G, B = hsv2rgb(h, s, v)
653
+ return mkc(R, G, B, c.shape[0], c.shape[1])
654
+ ```
655
+
656
+ #### Color Grade
657
+ ```python
658
+ def sh_color_grade(c, tint):
659
+ """Per-channel multiplier. tint=(r_mul, g_mul, b_mul)."""
660
+ o = c.astype(np.float32)
661
+ o[:,:,0] *= tint[0]; o[:,:,1] *= tint[1]; o[:,:,2] *= tint[2]
662
+ return np.clip(o, 0, 255).astype(np.uint8)
663
+ ```
664
+
665
+ #### Color Wobble
666
+ ```python
667
+ def sh_color_wobble(c, t, amt=0.3):
668
+ """Time-varying per-channel sine modulation. Audio-reactive in dispatch (amt scaled by rms)."""
669
+ o = c.astype(np.float32)
670
+ o[:,:,0] *= 1.0 + amt * math.sin(t * 5.0)
671
+ o[:,:,1] *= 1.0 + amt * math.sin(t * 5.0 + 2.09)
672
+ o[:,:,2] *= 1.0 + amt * math.sin(t * 5.0 + 4.19)
673
+ return np.clip(o, 0, 255).astype(np.uint8)
674
+ ```
675
+
676
+ #### Color Ramp
677
+ ```python
678
+ def sh_color_ramp(c, ramp_colors):
679
+ """Map luminance to a custom color gradient.
680
+ ramp_colors = list of (R,G,B) tuples, evenly spaced from dark to bright."""
681
+ gray = c.astype(np.float32).mean(axis=2) / 255.0
682
+ n = len(ramp_colors)
683
+ idx = np.clip(gray * (n-1), 0, n-1.001)
684
+ lo = np.floor(idx).astype(int); hi = np.minimum(lo+1, n-1)
685
+ frac = idx - lo
686
+ ramp = np.array(ramp_colors, dtype=np.float32)
687
+ out = ramp[lo] * (1-frac[:,:,None]) + ramp[hi] * frac[:,:,None]
688
+ return np.clip(out, 0, 255).astype(np.uint8)
689
+ ```
690
+
691
+ ---
692
+
693
+ ### Glow / Blur Shaders
694
+
695
+ #### Bloom
696
+ ```python
697
+ def sh_bloom(c, thr=130):
698
+ """Bright-area glow: 4x downsample, threshold, 3-pass box blur, screen blend."""
699
+ sm = c[::4, ::4].astype(np.float32)
700
+ br = np.where(sm > thr, sm, 0)
701
+ for _ in range(3):
702
+ p = np.pad(br, ((1,1),(1,1),(0,0)), mode="edge")
703
+ br = (p[:-2,:-2]+p[:-2,1:-1]+p[:-2,2:]+p[1:-1,:-2]+p[1:-1,1:-1]+
704
+ p[1:-1,2:]+p[2:,:-2]+p[2:,1:-1]+p[2:,2:]) / 9.0
705
+ bl = np.repeat(np.repeat(br, 4, axis=0), 4, axis=1)[:c.shape[0], :c.shape[1]]
706
+ return np.clip(c.astype(np.float32) + bl * 0.5, 0, 255).astype(np.uint8)
707
+ ```
708
+
709
+ #### Edge Glow
710
+ ```python
711
+ def sh_edge_glow(c, hue=0.5):
712
+ """Detect edges via gradient, add colored overlay."""
713
+ gray = c.astype(np.float32).mean(axis=2)
714
+ gx = np.abs(gray[:, 2:] - gray[:, :-2])
715
+ gy = np.abs(gray[2:, :] - gray[:-2, :])
716
+ ex = np.zeros_like(gray); ey = np.zeros_like(gray)
717
+ ex[:, 1:-1] = gx; ey[1:-1, :] = gy
718
+ edge = np.clip((ex + ey) / 255 * 2, 0, 1)
719
+ R, G, B = hsv2rgb(np.full_like(edge, hue), np.full_like(edge, 0.8), edge * 0.5)
720
+ out = c.astype(np.int16).copy()
721
+ out[:,:,0] = np.clip(out[:,:,0] + R.astype(np.int16), 0, 255)
722
+ out[:,:,1] = np.clip(out[:,:,1] + G.astype(np.int16), 0, 255)
723
+ out[:,:,2] = np.clip(out[:,:,2] + B.astype(np.int16), 0, 255)
724
+ return out.astype(np.uint8)
725
+ ```
726
+
727
+ #### Soft Focus
728
+ ```python
729
+ def sh_soft_focus(c, strength=0.3):
730
+ """Blend original with 2x-downsampled box blur."""
731
+ sm = c[::2, ::2].astype(np.float32)
732
+ p = np.pad(sm, ((1,1),(1,1),(0,0)), mode="edge")
733
+ bl = (p[:-2,:-2]+p[:-2,1:-1]+p[:-2,2:]+p[1:-1,:-2]+p[1:-1,1:-1]+
734
+ p[1:-1,2:]+p[2:,:-2]+p[2:,1:-1]+p[2:,2:]) / 9.0
735
+ bl = np.repeat(np.repeat(bl, 2, axis=0), 2, axis=1)[:c.shape[0], :c.shape[1]]
736
+ return np.clip(c * (1-strength) + bl * strength, 0, 255).astype(np.uint8)
737
+ ```
738
+
739
+ #### Radial Blur
740
+ ```python
741
+ def sh_radial_blur(c, strength=0.03, center=None):
742
+ """Zoom blur from center — motion blur radiating outward."""
743
+ h, w = c.shape[:2]
744
+ cy, cx = center if center else (h//2, w//2)
745
+ Y = np.arange(h, dtype=np.float32)[:, None]
746
+ X = np.arange(w, dtype=np.float32)[None, :]
747
+ out = c.astype(np.float32)
748
+ for s in [strength, strength*2]:
749
+ dy = (Y - cy) * s; dx = (X - cx) * s
750
+ sy = np.clip((Y + dy).astype(int), 0, h-1)
751
+ sx = np.clip((X + dx).astype(int), 0, w-1)
752
+ out += c[sy, sx].astype(np.float32)
753
+ return np.clip(out / 3, 0, 255).astype(np.uint8)
754
+ ```
755
+
756
+ ---
757
+
758
+ ### Noise / Grain Shaders
759
+
760
+ #### Film Grain
761
+ ```python
762
+ def sh_grain(c, amt=10):
763
+ """2x-downsampled film grain. Audio-reactive in dispatch (amt scaled by rms)."""
764
+ noise = np.random.randint(-amt, amt+1, (c.shape[0]//2, c.shape[1]//2, 1), dtype=np.int16)
765
+ noise = np.repeat(np.repeat(noise, 2, axis=0), 2, axis=1)[:c.shape[0], :c.shape[1]]
766
+ return np.clip(c.astype(np.int16) + noise, 0, 255).astype(np.uint8)
767
+ ```
768
+
769
+ #### Static Noise
770
+ ```python
771
+ def sh_static_noise(c, density=0.05, color=True):
772
+ """Random pixel noise overlay (TV static)."""
773
+ mask = np.random.random((c.shape[0]//2, c.shape[1]//2)) < density
774
+ mask = np.repeat(np.repeat(mask, 2, axis=0), 2, axis=1)[:c.shape[0], :c.shape[1]]
775
+ out = c.copy()
776
+ if color:
777
+ noise = np.random.randint(0, 256, (c.shape[0], c.shape[1], 3), dtype=np.uint8)
778
+ else:
779
+ v = np.random.randint(0, 256, (c.shape[0], c.shape[1]), dtype=np.uint8)
780
+ noise = np.stack([v, v, v], axis=2)
781
+ out[mask] = noise[mask]
782
+ return out
783
+ ```
784
+
785
+ ---
786
+
787
+ ### Lines / Pattern Shaders
788
+
789
+ #### Scanlines
790
+ ```python
791
+ def sh_scanlines(c, intensity=0.08, spacing=3):
792
+ """Darken every Nth row."""
793
+ m = np.ones(c.shape[0], dtype=np.float32)
794
+ m[::spacing] = 1.0 - intensity
795
+ return np.clip(c * m[:, None, None], 0, 255).astype(np.uint8)
796
+ ```
797
+
798
+ #### Halftone
799
+ ```python
800
+ def sh_halftone(c, dot_size=6):
801
+ """Halftone dot pattern overlay — circular dots sized by local brightness."""
802
+ h, w = c.shape[:2]
803
+ gray = c.astype(np.float32).mean(axis=2) / 255.0
804
+ out = np.zeros_like(c)
805
+ for y in range(0, h, dot_size):
806
+ for x in range(0, w, dot_size):
807
+ block = gray[y:y+dot_size, x:x+dot_size]
808
+ if block.size == 0: continue
809
+ radius = block.mean() * dot_size * 0.5
810
+ cy_b, cx_b = dot_size//2, dot_size//2
811
+ for dy in range(min(dot_size, h-y)):
812
+ for dx in range(min(dot_size, w-x)):
813
+ if math.sqrt((dy-cy_b)**2 + (dx-cx_b)**2) < radius:
814
+ out[y+dy, x+dx] = c[y+dy, x+dx]
815
+ return out
816
+ ```
817
+
818
+ > **Performance note:** Halftone is slow due to Python loops. Acceptable for small resolutions or single test frames. For production, consider a vectorized version using precomputed distance masks.
819
+
820
+ ---
821
+
822
+ ### Tone Shaders
823
+
824
+ #### Vignette
825
+ ```python
826
+ _vig_cache = {}
827
+ def sh_vignette(c, s=0.22):
828
+ """Edge darkening using cached distance field."""
829
+ k = (c.shape[0], c.shape[1], round(s, 2))
830
+ if k not in _vig_cache:
831
+ h, w = c.shape[:2]
832
+ Y = np.linspace(-1, 1, h)[:, None]; X = np.linspace(-1, 1, w)[None, :]
833
+ _vig_cache[k] = np.clip(1.0 - np.sqrt(X**2 + Y**2) * s, 0.15, 1).astype(np.float32)
834
+ return np.clip(c * _vig_cache[k][:,:,None], 0, 255).astype(np.uint8)
835
+ ```
836
+
837
+ #### Reverse Vignette
838
+
839
+ Inverted vignette: darkens the **center** and leaves edges bright. Useful when text is centered over busy backgrounds — creates a natural dark zone for readability without a hard-edged box.
840
+
841
+ Combine with `apply_text_backdrop()` (see composition.md) for per-frame glyph-aware darkening.
842
+
843
+ ```python
844
+ _rvignette_cache = {}
845
+
846
+ def sh_reverse_vignette(c, strength=0.5):
847
+ """Center darkening, edge brightening. Cached."""
848
+ k = ('rv', c.shape[0], c.shape[1], round(strength, 2))
849
+ if k not in _rvignette_cache:
850
+ h, w = c.shape[:2]
851
+ Y = np.linspace(-1, 1, h)[:, None]
852
+ X = np.linspace(-1, 1, w)[None, :]
853
+ d = np.sqrt(X**2 + Y**2)
854
+ # Invert: bright at edges, dark at center
855
+ mask = np.clip(1.0 - (1.0 - d * 0.7) * strength, 0.2, 1.0)
856
+ _rvignette_cache[k] = mask[:, :, np.newaxis].astype(np.float32)
857
+ return np.clip(c.astype(np.float32) * _rvignette_cache[k], 0, 255).astype(np.uint8)
858
+ ```
859
+
860
+ | Param | Default | Effect |
861
+ |-------|---------|--------|
862
+ | `strength` | 0.5 | 0 = no effect, 1.0 = center nearly black |
863
+
864
+ Add to ShaderChain dispatch:
865
+ ```python
866
+ elif name == "reverse_vignette":
867
+ return sh_reverse_vignette(canvas, kwargs.get("strength", 0.5))
868
+ ```
869
+
870
+ #### Contrast
871
+ ```python
872
+ def sh_contrast(c, factor=1.3):
873
+ """Adjust contrast around midpoint 128."""
874
+ return np.clip((c.astype(np.float32) - 128) * factor + 128, 0, 255).astype(np.uint8)
875
+ ```
876
+
877
+ #### Gamma
878
+ ```python
879
+ def sh_gamma(c, gamma=1.5):
880
+ """Gamma correction. >1=brighter mids, <1=darker mids."""
881
+ return np.clip(((c.astype(np.float32)/255.0) ** (1.0/gamma)) * 255, 0, 255).astype(np.uint8)
882
+ ```
883
+
884
+ #### Levels
885
+ ```python
886
+ def sh_levels(c, black=0, white=255, midtone=1.0):
887
+ """Levels adjustment (Photoshop-style). Remap black/white points, apply midtone gamma."""
888
+ o = (c.astype(np.float32) - black) / max(1, white - black)
889
+ o = np.clip(o, 0, 1) ** (1.0 / midtone)
890
+ return (o * 255).astype(np.uint8)
891
+ ```
892
+
893
+ #### Brightness
894
+ ```python
895
+ def sh_brightness(c, factor=1.5):
896
+ """Global brightness multiplier. Prefer tonemap() for scene-level brightness control."""
897
+ return np.clip(c.astype(np.float32) * factor, 0, 255).astype(np.uint8)
898
+ ```
899
+
900
+ ---
901
+
902
+ ### Glitch / Data Shaders
903
+
904
+ #### Glitch Bands
905
+ ```python
906
+ def sh_glitch_bands(c, f):
907
+ """Beat-reactive horizontal row displacement. f = audio features dict.
908
+ Uses f["bdecay"] for intensity and f["sub"] for band height."""
909
+ n = int(3 + f.get("bdecay", 0) * 10)
910
+ out = c.copy()
911
+ for _ in range(n):
912
+ y = random.randint(0, c.shape[0]-1)
913
+ h = random.randint(1, max(2, int(4 + f.get("sub", 0.3) * 12)))
914
+ shift = int((random.random()-0.5) * f.get("bdecay", 0) * 60)
915
+ if shift != 0 and y+h < c.shape[0]:
916
+ out[y:y+h] = np.roll(out[y:y+h], shift, axis=1)
917
+ return out
918
+ ```
919
+
920
+ #### Block Glitch
921
+ ```python
922
+ def sh_block_glitch(c, n_blocks=8, max_size=40):
923
+ """Random rectangular block displacement — copy blocks to random positions."""
924
+ out = c.copy(); h, w = c.shape[:2]
925
+ for _ in range(n_blocks):
926
+ bw = random.randint(10, max_size); bh = random.randint(5, max_size//2)
927
+ sx = random.randint(0, w-bw-1); sy = random.randint(0, h-bh-1)
928
+ dx = random.randint(0, w-bw-1); dy = random.randint(0, h-bh-1)
929
+ out[dy:dy+bh, dx:dx+bw] = c[sy:sy+bh, sx:sx+bw]
930
+ return out
931
+ ```
932
+
933
+ #### Pixel Sort
934
+ ```python
935
+ def sh_pixel_sort(c, threshold=100, direction="h"):
936
+ """Sort pixels by brightness in contiguous bright regions."""
937
+ gray = c.astype(np.float32).mean(axis=2)
938
+ out = c.copy()
939
+ if direction == "h":
940
+ for y in range(0, c.shape[0], 3): # every 3rd row for speed
941
+ row_bright = gray[y]
942
+ mask = row_bright > threshold
943
+ regions = np.diff(np.concatenate([[0], mask.astype(int), [0]]))
944
+ starts = np.where(regions == 1)[0]
945
+ ends = np.where(regions == -1)[0]
946
+ for s, e in zip(starts, ends):
947
+ if e - s > 2:
948
+ indices = np.argsort(gray[y, s:e])
949
+ out[y, s:e] = c[y, s:e][indices]
950
+ else:
951
+ for x in range(0, c.shape[1], 3):
952
+ col_bright = gray[:, x]
953
+ mask = col_bright > threshold
954
+ regions = np.diff(np.concatenate([[0], mask.astype(int), [0]]))
955
+ starts = np.where(regions == 1)[0]
956
+ ends = np.where(regions == -1)[0]
957
+ for s, e in zip(starts, ends):
958
+ if e - s > 2:
959
+ indices = np.argsort(gray[s:e, x])
960
+ out[s:e, x] = c[s:e, x][indices]
961
+ return out
962
+ ```
963
+
964
+ #### Data Bend
965
+ ```python
966
+ def sh_data_bend(c, offset=1000, chunk=500):
967
+ """Treat raw pixel bytes as data, copy a chunk to another offset — datamosh artifacts."""
968
+ flat = c.flatten().copy()
969
+ n = len(flat)
970
+ src = offset % n; dst = (offset + chunk*3) % n
971
+ length = min(chunk, n-src, n-dst)
972
+ if length > 0:
973
+ flat[dst:dst+length] = flat[src:src+length]
974
+ return flat.reshape(c.shape)
975
+ ```
976
+
977
+ ---
978
+
979
+ ## Tint Presets
980
+
981
+ ```python
982
+ TINT_WARM = (1.15, 1.0, 0.85) # golden warmth
983
+ TINT_COOL = (0.85, 0.95, 1.15) # blue cool
984
+ TINT_MATRIX = (0.7, 1.2, 0.7) # green terminal
985
+ TINT_AMBER = (1.2, 0.9, 0.6) # amber monitor
986
+ TINT_SEPIA = (1.2, 1.05, 0.8) # old film
987
+ TINT_NEON_PINK = (1.3, 0.7, 1.1) # cyberpunk pink
988
+ TINT_ICE = (0.8, 1.0, 1.3) # frozen
989
+ TINT_BLOOD = (1.4, 0.7, 0.7) # horror red
990
+ TINT_FOREST = (0.8, 1.15, 0.75) # natural green
991
+ TINT_VOID = (0.85, 0.85, 1.1) # deep space
992
+ TINT_SUNSET = (1.3, 0.85, 0.7) # orange dusk
993
+ ```
994
+
995
+ ---
996
+
997
+ ## Transitions
998
+
999
+ > **Note:** These operate on character-level `(chars, colors)` arrays (v1 interface). In v2, transitions between scenes are typically handled by hard cuts at beat boundaries (see `scenes.md`), or by rendering both scenes to canvases and using `blend_canvas()` with a time-varying opacity. The character-level transitions below are still useful for within-scene effects.
1000
+
1001
+ ### Crossfade
1002
+ ```python
1003
+ def tr_crossfade(ch_a, co_a, ch_b, co_b, blend):
1004
+ co = (co_a.astype(np.float32) * (1-blend) + co_b.astype(np.float32) * blend).astype(np.uint8)
1005
+ mask = np.random.random(ch_a.shape) < blend
1006
+ ch = ch_a.copy(); ch[mask] = ch_b[mask]
1007
+ return ch, co
1008
+ ```
1009
+
1010
+ ### v2 Canvas-Level Crossfade
1011
+ ```python
1012
+ def tr_canvas_crossfade(canvas_a, canvas_b, blend):
1013
+ """Smooth pixel crossfade between two canvases."""
1014
+ return np.clip(canvas_a * (1-blend) + canvas_b * blend, 0, 255).astype(np.uint8)
1015
+ ```
1016
+
1017
+ ### Wipe (directional)
1018
+ ```python
1019
+ def tr_wipe(ch_a, co_a, ch_b, co_b, blend, direction="left"):
1020
+ """direction: left, right, up, down, radial, diagonal"""
1021
+ rows, cols = ch_a.shape
1022
+ if direction == "radial":
1023
+ cx, cy = cols/2, rows/2
1024
+ rr = np.arange(rows)[:, None]; cc = np.arange(cols)[None, :]
1025
+ d = np.sqrt((cc-cx)**2 + (rr-cy)**2)
1026
+ mask = d < blend * np.sqrt(cx**2 + cy**2)
1027
+ ch = ch_a.copy(); co = co_a.copy()
1028
+ ch[mask] = ch_b[mask]; co[mask] = co_b[mask]
1029
+ return ch, co
1030
+ ```
1031
+
1032
+ ### Glitch Cut
1033
+ ```python
1034
+ def tr_glitch_cut(ch_a, co_a, ch_b, co_b, blend):
1035
+ if blend < 0.5: ch, co = ch_a.copy(), co_a.copy()
1036
+ else: ch, co = ch_b.copy(), co_b.copy()
1037
+ if 0.3 < blend < 0.7:
1038
+ intensity = 1.0 - abs(blend - 0.5) * 4
1039
+ for _ in range(int(intensity * 20)):
1040
+ y = random.randint(0, ch.shape[0]-1)
1041
+ shift = int((random.random()-0.5) * 40 * intensity)
1042
+ if shift: ch[y] = np.roll(ch[y], shift); co[y] = np.roll(co[y], shift, axis=0)
1043
+ return ch, co
1044
+ ```
1045
+
1046
+ ---
1047
+
1048
+ ## Output Formats
1049
+
1050
+ ### MP4 (default)
1051
+ ```python
1052
+ cmd = ["ffmpeg", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24",
1053
+ "-s", f"{W}x{H}", "-r", str(fps), "-i", "pipe:0",
1054
+ "-c:v", "libx264", "-preset", "fast", "-crf", str(crf),
1055
+ "-pix_fmt", "yuv420p", output_path]
1056
+ ```
1057
+
1058
+ ### GIF
1059
+ ```python
1060
+ cmd = ["ffmpeg", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24",
1061
+ "-s", f"{W}x{H}", "-r", str(fps), "-i", "pipe:0",
1062
+ "-vf", f"fps={fps},scale={W}:{H}:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse",
1063
+ "-loop", "0", output_gif]
1064
+ ```
1065
+
1066
+ ### PNG Sequence
1067
+
1068
+ For frame-accurate editing, compositing in external tools (After Effects, Nuke), or lossless archival:
1069
+
1070
+ ```python
1071
+ import os
1072
+
1073
+ def output_png_sequence(frames, output_dir, W, H, fps, prefix="frame"):
1074
+ """Write frames as numbered PNGs. frames = iterable of uint8 (H,W,3) arrays."""
1075
+ os.makedirs(output_dir, exist_ok=True)
1076
+
1077
+ # Method 1: Direct PIL write (no ffmpeg dependency)
1078
+ from PIL import Image
1079
+ for i, frame in enumerate(frames):
1080
+ img = Image.fromarray(frame)
1081
+ img.save(os.path.join(output_dir, f"{prefix}_{i:06d}.png"))
1082
+
1083
+ # Method 2: ffmpeg pipe (faster for large sequences)
1084
+ cmd = ["ffmpeg", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24",
1085
+ "-s", f"{W}x{H}", "-r", str(fps), "-i", "pipe:0",
1086
+ os.path.join(output_dir, f"{prefix}_%06d.png")]
1087
+ ```
1088
+
1089
+ Reassemble PNG sequence to video:
1090
+ ```bash
1091
+ ffmpeg -framerate 24 -i frame_%06d.png -c:v libx264 -crf 18 -pix_fmt yuv420p output.mp4
1092
+ ```
1093
+
1094
+ ### Alpha Channel / Transparent Background (RGBA)
1095
+
1096
+ For compositing ASCII art over other video or images. Uses RGBA canvas (4 channels) instead of RGB (3 channels):
1097
+
1098
+ ```python
1099
+ def create_rgba_canvas(H, W):
1100
+ """Transparent canvas — alpha channel starts at 0 (fully transparent)."""
1101
+ return np.zeros((H, W, 4), dtype=np.uint8)
1102
+
1103
+ def render_char_rgba(canvas, row, col, char_img, color_rgb, alpha=255):
1104
+ """Render a character with alpha. char_img = PIL glyph mask (grayscale).
1105
+ Alpha comes from the glyph mask — background stays transparent."""
1106
+ r, g, b = color_rgb
1107
+ y0, x0 = row * cell_h, col * cell_w
1108
+ mask = np.array(char_img) # grayscale 0-255
1109
+ canvas[y0:y0+cell_h, x0:x0+cell_w, 0] = np.maximum(canvas[y0:y0+cell_h, x0:x0+cell_w, 0], (mask * r / 255).astype(np.uint8))
1110
+ canvas[y0:y0+cell_h, x0:x0+cell_w, 1] = np.maximum(canvas[y0:y0+cell_h, x0:x0+cell_w, 1], (mask * g / 255).astype(np.uint8))
1111
+ canvas[y0:y0+cell_h, x0:x0+cell_w, 2] = np.maximum(canvas[y0:y0+cell_h, x0:x0+cell_w, 2], (mask * b / 255).astype(np.uint8))
1112
+ canvas[y0:y0+cell_h, x0:x0+cell_w, 3] = np.maximum(canvas[y0:y0+cell_h, x0:x0+cell_w, 3], mask)
1113
+
1114
+ def blend_onto_background(rgba_canvas, bg_rgb):
1115
+ """Composite RGBA canvas over a solid or image background."""
1116
+ alpha = rgba_canvas[:, :, 3:4].astype(np.float32) / 255.0
1117
+ fg = rgba_canvas[:, :, :3].astype(np.float32)
1118
+ bg = bg_rgb.astype(np.float32)
1119
+ result = fg * alpha + bg * (1.0 - alpha)
1120
+ return result.astype(np.uint8)
1121
+ ```
1122
+
1123
+ RGBA output via ffmpeg (ProRes 4444 for editing, WebM VP9 for web):
1124
+ ```bash
1125
+ # ProRes 4444 — preserves alpha, widely supported in NLEs
1126
+ ffmpeg -y -f rawvideo -pix_fmt rgba -s {W}x{H} -r {fps} -i pipe:0 \
1127
+ -c:v prores_ks -profile:v 4444 -pix_fmt yuva444p10le output.mov
1128
+
1129
+ # WebM VP9 — alpha support for web/browser compositing
1130
+ ffmpeg -y -f rawvideo -pix_fmt rgba -s {W}x{H} -r {fps} -i pipe:0 \
1131
+ -c:v libvpx-vp9 -pix_fmt yuva420p -crf 30 -b:v 0 output.webm
1132
+
1133
+ # PNG sequence with alpha (lossless)
1134
+ ffmpeg -y -f rawvideo -pix_fmt rgba -s {W}x{H} -r {fps} -i pipe:0 \
1135
+ frame_%06d.png
1136
+ ```
1137
+
1138
+ **Key constraint**: shaders that operate on `(H,W,3)` arrays need adaptation for RGBA. Either apply shaders to the RGB channels only and preserve alpha, or write RGBA-aware versions:
1139
+
1140
+ ```python
1141
+ def apply_shader_rgba(canvas_rgba, shader_fn, **kwargs):
1142
+ """Apply an RGB shader to the color channels of an RGBA canvas."""
1143
+ rgb = canvas_rgba[:, :, :3]
1144
+ alpha = canvas_rgba[:, :, 3:4]
1145
+ rgb_out = shader_fn(rgb, **kwargs)
1146
+ return np.concatenate([rgb_out, alpha], axis=2)
1147
+ ```
1148
+
1149
+ ---
1150
+
1151
+ ## Real-Time Terminal Rendering
1152
+
1153
+ Live ASCII display in the terminal using ANSI escape codes. Useful for previewing scenes during development, live performances, and interactive parameter tuning.
1154
+
1155
+ ### ANSI Color Escape Codes
1156
+
1157
+ ```python
1158
+ def rgb_to_ansi(r, g, b):
1159
+ """24-bit true color ANSI escape (supported by most modern terminals)."""
1160
+ return f"\033[38;2;{r};{g};{b}m"
1161
+
1162
+ ANSI_RESET = "\033[0m"
1163
+ ANSI_CLEAR = "\033[2J\033[H" # clear screen + cursor home
1164
+ ANSI_HIDE_CURSOR = "\033[?25l"
1165
+ ANSI_SHOW_CURSOR = "\033[?25h"
1166
+ ```
1167
+
1168
+ ### Frame-to-ANSI Conversion
1169
+
1170
+ ```python
1171
+ def frame_to_ansi(chars, colors):
1172
+ """Convert char+color arrays to a single ANSI string for terminal output.
1173
+
1174
+ Args:
1175
+ chars: (rows, cols) array of single characters
1176
+ colors: (rows, cols, 3) uint8 RGB array
1177
+ Returns:
1178
+ str: ANSI-encoded frame ready for sys.stdout.write()
1179
+ """
1180
+ rows, cols = chars.shape
1181
+ lines = []
1182
+ for r in range(rows):
1183
+ parts = []
1184
+ prev_color = None
1185
+ for c in range(cols):
1186
+ rgb = tuple(colors[r, c])
1187
+ ch = chars[r, c]
1188
+ if ch == " " or rgb == (0, 0, 0):
1189
+ parts.append(" ")
1190
+ else:
1191
+ if rgb != prev_color:
1192
+ parts.append(rgb_to_ansi(*rgb))
1193
+ prev_color = rgb
1194
+ parts.append(ch)
1195
+ parts.append(ANSI_RESET)
1196
+ lines.append("".join(parts))
1197
+ return "\n".join(lines)
1198
+ ```
1199
+
1200
+ ### Optimized: Delta Updates
1201
+
1202
+ Only redraw characters that changed since the last frame. Eliminates redundant terminal writes for static regions:
1203
+
1204
+ ```python
1205
+ def frame_to_ansi_delta(chars, colors, prev_chars, prev_colors):
1206
+ """Emit ANSI escapes only for cells that changed."""
1207
+ rows, cols = chars.shape
1208
+ parts = []
1209
+ for r in range(rows):
1210
+ for c in range(cols):
1211
+ if (chars[r, c] != prev_chars[r, c] or
1212
+ not np.array_equal(colors[r, c], prev_colors[r, c])):
1213
+ parts.append(f"\033[{r+1};{c+1}H") # move cursor
1214
+ rgb = tuple(colors[r, c])
1215
+ parts.append(rgb_to_ansi(*rgb))
1216
+ parts.append(chars[r, c])
1217
+ return "".join(parts)
1218
+ ```
1219
+
1220
+ ### Live Render Loop
1221
+
1222
+ ```python
1223
+ import sys
1224
+ import time
1225
+
1226
+ def render_live(scene_fn, r, fps=24, duration=None):
1227
+ """Render a scene function live in the terminal.
1228
+
1229
+ Args:
1230
+ scene_fn: v2 scene function (r, f, t, S) -> canvas
1231
+ OR v1-style function that populates a grid
1232
+ r: Renderer instance
1233
+ fps: target frame rate
1234
+ duration: seconds to run (None = run until Ctrl+C)
1235
+ """
1236
+ frame_time = 1.0 / fps
1237
+ S = {}
1238
+ f = {} # synthesize features or connect to live audio
1239
+
1240
+ sys.stdout.write(ANSI_HIDE_CURSOR + ANSI_CLEAR)
1241
+ sys.stdout.flush()
1242
+
1243
+ t0 = time.monotonic()
1244
+ frame_count = 0
1245
+ try:
1246
+ while True:
1247
+ t = time.monotonic() - t0
1248
+ if duration and t > duration:
1249
+ break
1250
+
1251
+ # Synthesize features from time (or connect to live audio via pyaudio)
1252
+ f = synthesize_features(t)
1253
+
1254
+ # Render scene — for terminal, use a small grid
1255
+ g = r.get_grid("sm")
1256
+ # Option A: v2 scene → extract chars/colors from canvas (reverse render)
1257
+ # Option B: call effect functions directly for chars/colors
1258
+ canvas = scene_fn(r, f, t, S)
1259
+
1260
+ # For terminal display, render chars+colors directly
1261
+ # (bypassing the pixel canvas — terminal uses character cells)
1262
+ chars, colors = scene_to_terminal(scene_fn, r, f, t, S, g)
1263
+
1264
+ frame_str = ANSI_CLEAR + frame_to_ansi(chars, colors)
1265
+ sys.stdout.write(frame_str)
1266
+ sys.stdout.flush()
1267
+
1268
+ # Frame timing
1269
+ elapsed = time.monotonic() - t0 - (frame_count * frame_time)
1270
+ sleep_time = frame_time - elapsed
1271
+ if sleep_time > 0:
1272
+ time.sleep(sleep_time)
1273
+ frame_count += 1
1274
+ except KeyboardInterrupt:
1275
+ pass
1276
+ finally:
1277
+ sys.stdout.write(ANSI_SHOW_CURSOR + ANSI_RESET + "\n")
1278
+ sys.stdout.flush()
1279
+
1280
+ def scene_to_terminal(scene_fn, r, f, t, S, g):
1281
+ """Run effect functions and return (chars, colors) for terminal display.
1282
+ For terminal mode, skip the pixel canvas and work with character arrays directly."""
1283
+ # Effects that return (chars, colors) work directly
1284
+ # For vf-based effects, render the value field + hue field to chars/colors:
1285
+ val = vf_plasma(g, f, t, S)
1286
+ hue = hf_time_cycle(0.08)(g, t)
1287
+ mask = val > 0.03
1288
+ chars = val2char(val, mask, PAL_DENSE)
1289
+ R, G, B = hsv2rgb(hue, np.full_like(val, 0.8), val)
1290
+ colors = mkc(R, G, B, g.rows, g.cols)
1291
+ return chars, colors
1292
+ ```
1293
+
1294
+ ### Curses-Based Rendering (More Robust)
1295
+
1296
+ For full-featured terminal UIs with proper resize handling and input:
1297
+
1298
+ ```python
1299
+ import curses
1300
+
1301
+ def render_curses(scene_fn, r, fps=24):
1302
+ """Curses-based live renderer with resize handling and key input."""
1303
+
1304
+ def _main(stdscr):
1305
+ curses.start_color()
1306
+ curses.use_default_colors()
1307
+ curses.curs_set(0) # hide cursor
1308
+ stdscr.nodelay(True) # non-blocking input
1309
+
1310
+ # Initialize color pairs (curses supports 256 colors)
1311
+ # Map RGB to nearest curses color pair
1312
+ color_cache = {}
1313
+ next_pair = [1]
1314
+
1315
+ def get_color_pair(r, g, b):
1316
+ key = (r >> 4, g >> 4, b >> 4) # quantize to reduce pairs
1317
+ if key not in color_cache:
1318
+ if next_pair[0] < curses.COLOR_PAIRS - 1:
1319
+ ci = 16 + (r // 51) * 36 + (g // 51) * 6 + (b // 51) # 6x6x6 cube
1320
+ curses.init_pair(next_pair[0], ci, -1)
1321
+ color_cache[key] = next_pair[0]
1322
+ next_pair[0] += 1
1323
+ else:
1324
+ return 0
1325
+ return curses.color_pair(color_cache[key])
1326
+
1327
+ S = {}
1328
+ f = {}
1329
+ frame_time = 1.0 / fps
1330
+ t0 = time.monotonic()
1331
+
1332
+ while True:
1333
+ t = time.monotonic() - t0
1334
+ f = synthesize_features(t)
1335
+
1336
+ # Adapt grid to terminal size
1337
+ max_y, max_x = stdscr.getmaxyx()
1338
+ g = r.get_grid_for_size(max_x, max_y) # dynamic grid sizing
1339
+
1340
+ chars, colors = scene_to_terminal(scene_fn, r, f, t, S, g)
1341
+ rows, cols = chars.shape
1342
+
1343
+ for row in range(min(rows, max_y - 1)):
1344
+ for col in range(min(cols, max_x - 1)):
1345
+ ch = chars[row, col]
1346
+ rgb = tuple(colors[row, col])
1347
+ try:
1348
+ stdscr.addch(row, col, ch, get_color_pair(*rgb))
1349
+ except curses.error:
1350
+ pass # ignore writes outside terminal bounds
1351
+
1352
+ stdscr.refresh()
1353
+
1354
+ # Handle input
1355
+ key = stdscr.getch()
1356
+ if key == ord('q'):
1357
+ break
1358
+
1359
+ time.sleep(max(0, frame_time - (time.monotonic() - t0 - t)))
1360
+
1361
+ curses.wrapper(_main)
1362
+ ```
1363
+
1364
+ ### Terminal Rendering Constraints
1365
+
1366
+ | Constraint | Value | Notes |
1367
+ |-----------|-------|-------|
1368
+ | Max practical grid | ~200x60 | Depends on terminal size |
1369
+ | Color support | 24-bit (modern), 256 (fallback), 16 (minimal) | Check `$COLORTERM` for truecolor |
1370
+ | Frame rate ceiling | ~30 fps | Terminal I/O is the bottleneck |
1371
+ | Delta updates | 2-5x faster | Only worth it when <30% of cells change per frame |
1372
+ | SSH latency | Kills performance | Local terminals only for real-time |
1373
+
1374
+ **Detect color support:**
1375
+ ```python
1376
+ import os
1377
+ def get_terminal_color_depth():
1378
+ ct = os.environ.get("COLORTERM", "")
1379
+ if ct in ("truecolor", "24bit"):
1380
+ return 24
1381
+ term = os.environ.get("TERM", "")
1382
+ if "256color" in term:
1383
+ return 8 # 256 colors
1384
+ return 4 # 16 colors basic ANSI
1385
+ ```
skills/.archive/ascii-video/references/troubleshooting.md ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Troubleshooting Reference
2
+
3
+ > **See also:** composition.md · architecture.md · shaders.md · scenes.md · optimization.md
4
+
5
+ ## Quick Diagnostic
6
+
7
+ | Symptom | Likely Cause | Fix |
8
+ |---------|-------------|-----|
9
+ | All black output | tonemap gamma too high or no effects rendering | Lower gamma to 0.5, check scene_fn returns non-zero canvas |
10
+ | Washed out / too bright | Linear brightness multiplier instead of tonemap | Replace `canvas * N` with `tonemap(canvas, gamma=0.75)` |
11
+ | ffmpeg hangs mid-render | stderr=subprocess.PIPE deadlock | Redirect stderr to file |
12
+ | "read-only" array error | broadcast_to view without .copy() | Add `.copy()` after broadcast_to |
13
+ | PicklingError | Lambda or closure in SCENES table | Define all fx_* at module level |
14
+ | Random dark holes in output | Font missing Unicode glyphs | Validate palettes at init |
15
+ | Audio-visual desync | Frame timing accumulation | Use integer frame counter, compute t fresh each frame |
16
+ | Single-color flat output | Hue field shape mismatch | Ensure h,s,v arrays all (rows,cols) before hsv2rgb |
17
+ | Text unreadable over busy bg | No contrast between text and background | Use `apply_text_backdrop()` (composition.md) + `reverse_vignette` shader (shaders.md) |
18
+ | Text garbled/mirrored | Kaleidoscope or mirror shader applied to text scene | **Never apply kaleidoscope, mirror_h/v/quad/diag to scenes with readable text** — radial folding destroys legibility. Apply these only to background layers or text-free scenes |
19
+
20
+ Common bugs, gotchas, and platform-specific issues encountered during ASCII video development.
21
+
22
+ ## NumPy Broadcasting
23
+
24
+ ### The `broadcast_to().copy()` Trap
25
+
26
+ Hue field generators often return arrays that are broadcast views — they have shape `(1, cols)` or `(rows, 1)` that numpy broadcasts to `(rows, cols)`. These views are **read-only**. If any downstream code tries to modify them in-place (e.g., `h %= 1.0`), numpy raises:
27
+
28
+ ```
29
+ ValueError: output array is read-only
30
+ ```
31
+
32
+ **Fix**: Always `.copy()` after `broadcast_to()`:
33
+
34
+ ```python
35
+ h = np.broadcast_to(h, (g.rows, g.cols)).copy()
36
+ ```
37
+
38
+ This is especially important in `_render_vf()` where hue arrays flow through `hsv2rgb()`.
39
+
40
+ ### The `+=` vs `+` Trap
41
+
42
+ Broadcasting also fails with in-place operators when operand shapes don't match exactly:
43
+
44
+ ```python
45
+ # FAILS if result is (rows,1) and operand is (rows, cols)
46
+ val += np.sin(g.cc * 0.02 + t * 0.3) * 0.5
47
+
48
+ # WORKS — creates a new array
49
+ val = val + np.sin(g.cc * 0.02 + t * 0.3) * 0.5
50
+ ```
51
+
52
+ The `vf_plasma()` function had this bug. Use `+` instead of `+=` when mixing different-shaped arrays.
53
+
54
+ ### Shape Mismatch in `hsv2rgb()`
55
+
56
+ `hsv2rgb(h, s, v)` requires all three arrays to have identical shapes. If `h` is `(1, cols)` and `s` is `(rows, cols)`, the function crashes or produces wrong output.
57
+
58
+ **Fix**: Ensure all inputs are broadcast and copied to `(rows, cols)` before calling.
59
+
60
+ ---
61
+
62
+ ## Blend Mode Pitfalls
63
+
64
+ ### Overlay Crushes Dark Inputs
65
+
66
+ `overlay(a, b) = 2*a*b` when `a < 0.5`. Two values of 0.12 produce `2 * 0.12 * 0.12 = 0.03`. The result is darker than either input.
67
+
68
+ **Impact**: If both layers are dark (which ASCII art usually is), overlay produces near-black output.
69
+
70
+ **Fix**: Use `screen` for dark source material. Screen always brightens: `1 - (1-a)*(1-b)`.
71
+
72
+ ### Colordodge Division by Zero
73
+
74
+ `colordodge(a, b) = a / (1 - b)`. When `b = 1.0` (pure white pixels), this divides by zero.
75
+
76
+ **Fix**: Add epsilon: `a / (1 - b + 1e-6)`. The implementation in `BLEND_MODES` should include this.
77
+
78
+ ### Colorburn Division by Zero
79
+
80
+ `colorburn(a, b) = 1 - (1-a) / b`. When `b = 0` (pure black pixels), this divides by zero.
81
+
82
+ **Fix**: Add epsilon: `1 - (1-a) / (b + 1e-6)`.
83
+
84
+ ### Multiply Always Darkens
85
+
86
+ `multiply(a, b) = a * b`. Since both operands are [0,1], the result is always <= min(a,b). Never use multiply as a feedback blend mode — the frame goes black within a few frames.
87
+
88
+ **Fix**: Use `screen` for feedback, or `add` with low opacity.
89
+
90
+ ---
91
+
92
+ ## Multiprocessing
93
+
94
+ ### Pickling Constraints
95
+
96
+ `ProcessPoolExecutor` serializes function arguments via pickle. This constrains what you can pass to workers:
97
+
98
+ | Can Pickle | Cannot Pickle |
99
+ |-----------|---------------|
100
+ | Module-level functions (`def fx_foo():`) | Lambdas (`lambda x: x + 1`) |
101
+ | Dicts, lists, numpy arrays | Closures (functions defined inside functions) |
102
+ | Class instances (with `__reduce__`) | Instance methods |
103
+ | Strings, numbers | File handles, sockets |
104
+
105
+ **Impact**: All scene functions referenced in the SCENES table must be defined at module level with `def`. If you use a lambda or closure, you get:
106
+
107
+ ```
108
+ _pickle.PicklingError: Can't pickle <function <lambda> at 0x...>
109
+ ```
110
+
111
+ **Fix**: Define all scene functions at module top level. Lambdas used inside `_render_vf()` as val_fn/hue_fn are fine because they execute within the worker process — they're not pickled across process boundaries.
112
+
113
+ ### macOS spawn vs Linux fork
114
+
115
+ On macOS, `multiprocessing` defaults to `spawn` (full serialization). On Linux, it defaults to `fork` (copy-on-write). This means:
116
+
117
+ - **macOS**: Feature arrays are serialized per worker (~57KB for 30s video, but scales with duration). Each worker re-imports the entire module.
118
+ - **Linux**: Feature arrays are shared via COW. Workers inherit the parent's memory.
119
+
120
+ **Impact**: On macOS, module-level code (like `detect_hardware()`) runs in every worker process. If it has side effects (e.g., subprocess calls), those happen N+1 times.
121
+
122
+ ### Per-Worker State Isolation
123
+
124
+ Each worker creates its own:
125
+ - `Renderer` instance (with fresh grid cache)
126
+ - `FeedbackBuffer` (feedback doesn't cross scene boundaries)
127
+ - Random seed (`random.seed(hash(seg_id) + 42)`)
128
+
129
+ This means:
130
+ - Particle state doesn't carry between scenes (expected)
131
+ - Feedback trails reset at scene cuts (expected)
132
+ - `np.random` state is NOT seeded by `random.seed()` — they use separate RNGs
133
+
134
+ **Fix for deterministic noise**: Use `np.random.RandomState(seed)` explicitly:
135
+
136
+ ```python
137
+ rng = np.random.RandomState(hash(seg_id) + 42)
138
+ noise = rng.random((rows, cols))
139
+ ```
140
+
141
+ ---
142
+
143
+ ## Brightness Issues
144
+
145
+ ### Dark Scenes After Tonemap
146
+
147
+ If a scene is still dark after tonemap, check:
148
+
149
+ 1. **Gamma too high**: Lower gamma (0.5-0.6) for scenes with destructive post-processing
150
+ 2. **Shader destroying brightness**: Solarize, posterize, or contrast adjustments in the shader chain can undo tonemap's work. Move destructive shaders earlier in the chain, or increase gamma to compensate.
151
+ 3. **Feedback with multiply**: Multiply feedback darkens every frame. Switch to screen or add.
152
+ 4. **Overlay blend in scene**: If the scene function uses `blend_canvas(..., "overlay", ...)` with dark layers, switch to screen.
153
+
154
+ ### Diagnostic: Test-Frame Brightness
155
+
156
+ ```bash
157
+ python reel.py --test-frame 10.0
158
+ # Output: Mean brightness: 44.3, max: 255
159
+ ```
160
+
161
+ If mean < 20, the scene needs attention. Common fixes:
162
+ - Lower gamma in the SCENES entry
163
+ - Change internal blend modes from overlay/multiply to screen/add
164
+ - Increase value field multipliers (e.g., `vf_plasma(...) * 1.5`)
165
+ - Check that the shader chain doesn't have an aggressive solarize or threshold
166
+
167
+ ### v1 Brightness Pattern (Deprecated)
168
+
169
+ The old pattern used a linear multiplier:
170
+
171
+ ```python
172
+ # OLD — don't use
173
+ canvas = np.clip(canvas.astype(np.float32) * 2.0, 0, 255).astype(np.uint8)
174
+ ```
175
+
176
+ This fails because:
177
+ - Dark scenes (mean 8): `8 * 2.0 = 16` — still dark
178
+ - Bright scenes (mean 130): `130 * 2.0 = 255` — clipped, lost detail
179
+
180
+ Use `tonemap()` instead. See `composition.md` § Adaptive Tone Mapping.
181
+
182
+ ---
183
+
184
+ ## ffmpeg Issues
185
+
186
+ ### Pipe Deadlock
187
+
188
+ The #1 production bug. If you use `stderr=subprocess.PIPE`:
189
+
190
+ ```python
191
+ # DEADLOCK — stderr buffer fills at 64KB, blocks ffmpeg, blocks your writes
192
+ pipe = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
193
+ ```
194
+
195
+ **Fix**: Always redirect stderr to a file:
196
+
197
+ ```python
198
+ stderr_fh = open(err_path, "w")
199
+ pipe = subprocess.Popen(cmd, stdin=subprocess.PIPE,
200
+ stdout=subprocess.DEVNULL, stderr=stderr_fh)
201
+ ```
202
+
203
+ ### Frame Count Mismatch
204
+
205
+ If the number of frames written to the pipe doesn't match what ffmpeg expects (based on `-r` and duration), the output may have:
206
+ - Missing frames at the end
207
+ - Incorrect duration
208
+ - Audio-video desync
209
+
210
+ **Fix**: Calculate frame count explicitly: `n_frames = int(duration * FPS)`. Don't use `range(int(start*FPS), int(end*FPS))` without verifying the total matches.
211
+
212
+ ### Concat Fails with "unsafe file name"
213
+
214
+ ```
215
+ [concat @ ...] Unsafe file name
216
+ ```
217
+
218
+ **Fix**: Always use `-safe 0`:
219
+ ```python
220
+ ["ffmpeg", "-f", "concat", "-safe", "0", "-i", concat_path, ...]
221
+ ```
222
+
223
+ ---
224
+
225
+ ## Font Issues
226
+
227
+ ### Cell Height (macOS Pillow)
228
+
229
+ `textbbox()` and `getbbox()` return incorrect heights on some macOS Pillow versions. Use `getmetrics()`:
230
+
231
+ ```python
232
+ ascent, descent = font.getmetrics()
233
+ cell_height = ascent + descent # correct
234
+ # NOT: font.getbbox("M")[3] # wrong on some versions
235
+ ```
236
+
237
+ ### Missing Unicode Glyphs
238
+
239
+ Not all fonts render all Unicode characters. If a palette character isn't in the font, the glyph renders as a blank or tofu box, appearing as a dark hole in the output.
240
+
241
+ **Fix**: Validate at init:
242
+
243
+ ```python
244
+ all_chars = set()
245
+ for pal in [PAL_DEFAULT, PAL_DENSE, PAL_RUNE, ...]:
246
+ all_chars.update(pal)
247
+
248
+ valid_chars = set()
249
+ for c in all_chars:
250
+ if c == " ":
251
+ valid_chars.add(c)
252
+ continue
253
+ img = Image.new("L", (20, 20), 0)
254
+ ImageDraw.Draw(img).text((0, 0), c, fill=255, font=font)
255
+ if np.array(img).max() > 0:
256
+ valid_chars.add(c)
257
+ else:
258
+ log(f"WARNING: '{c}' (U+{ord(c):04X}) missing from font")
259
+ ```
260
+
261
+ ### Platform Font Paths
262
+
263
+ | Platform | Common Paths |
264
+ |----------|-------------|
265
+ | macOS | `/System/Library/Fonts/Menlo.ttc`, `/System/Library/Fonts/Monaco.ttf` |
266
+ | Linux | `/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf` |
267
+ | Windows | `C:\Windows\Fonts\consola.ttf` (Consolas) |
268
+
269
+ Always probe multiple paths and fall back gracefully. See `architecture.md` § Font Selection.
270
+
271
+ ---
272
+
273
+ ## Performance
274
+
275
+ ### Slow Shaders
276
+
277
+ Some shaders use Python loops and are very slow at 1080p:
278
+
279
+ | Shader | Issue | Fix |
280
+ |--------|-------|-----|
281
+ | `wave_distort` | Per-row Python loop | Use vectorized fancy indexing |
282
+ | `halftone` | Triple-nested loop | Vectorize with block reduction |
283
+ | `matrix rain` | Per-column per-trail loop | Accumulate index arrays, bulk assign |
284
+
285
+ ### Render Time Scaling
286
+
287
+ If render is taking much longer than expected:
288
+ 1. Check grid count — each extra grid adds ~100-150ms/frame for init
289
+ 2. Check particle count — cap at quality-appropriate limits
290
+ 3. Check shader count — each shader adds 2-25ms
291
+ 4. Check for accidental Python loops in effects (should be numpy only)
292
+
293
+ ---
294
+
295
+ ## Common Mistakes
296
+
297
+ ### Using `r.S` vs the `S` Parameter
298
+
299
+ The v2 scene protocol passes `S` (the state dict) as an explicit parameter. But `S` IS `r.S` — they're the same object. Both work:
300
+
301
+ ```python
302
+ def fx_scene(r, f, t, S):
303
+ S["counter"] = S.get("counter", 0) + 1 # via parameter (preferred)
304
+ r.S["counter"] = r.S.get("counter", 0) + 1 # via renderer (also works)
305
+ ```
306
+
307
+ Use the `S` parameter for clarity. The explicit parameter makes it obvious that the function has persistent state.
308
+
309
+ ### Forgetting to Handle Empty Feature Values
310
+
311
+ Audio features default to 0.0 if the audio is silent. Use `.get()` with sensible defaults:
312
+
313
+ ```python
314
+ energy = f.get("bass", 0.3) # default to 0.3, not 0
315
+ ```
316
+
317
+ If you default to 0, effects go blank during silence.
318
+
319
+ ### Writing New Files Instead of Editing Existing State
320
+
321
+ A common bug in particle systems: creating new arrays every frame instead of updating persistent state.
322
+
323
+ ```python
324
+ # WRONG — particles reset every frame
325
+ S["px"] = []
326
+ for _ in range(100):
327
+ S["px"].append(random.random())
328
+
329
+ # RIGHT — only initialize once, update each frame
330
+ if "px" not in S:
331
+ S["px"] = []
332
+ # ... emit new particles based on beats
333
+ # ... update existing particles
334
+ ```
335
+
336
+ ### Not Clipping Value Fields
337
+
338
+ Value fields should be [0, 1]. If they exceed this range, `val2char()` produces index errors:
339
+
340
+ ```python
341
+ # WRONG — vf_plasma() * 1.5 can exceed 1.0
342
+ val = vf_plasma(g, f, t, S) * 1.5
343
+
344
+ # RIGHT — clip after scaling
345
+ val = np.clip(vf_plasma(g, f, t, S) * 1.5, 0, 1)
346
+ ```
347
+
348
+ The `_render_vf()` helper clips automatically, but if you're building custom scenes, clip explicitly.
349
+
350
+ ## Brightness Best Practices
351
+
352
+ - Dense animated backgrounds — never flat black, always fill the grid
353
+ - Vignette minimum clamped to 0.15 (not 0.12)
354
+ - Bloom threshold 130 (not 170) so more pixels contribute to glow
355
+ - Use `screen` blend mode (not `overlay`) for dark ASCII layers — overlay squares dark values: `2 * 0.12 * 0.12 = 0.03`
356
+ - FeedbackBuffer decay minimum 0.5 — below that, feedback disappears too fast to see
357
+ - Value field floor: `vf * 0.8 + 0.05` ensures no cell is truly zero
358
+ - Per-scene gamma overrides: default 0.75, solarize 0.55, posterize 0.50, bright scenes 0.85
359
+ - Test frames early: render single frames at key timestamps before committing to full render
360
+
361
+ **Quick checklist before full render:**
362
+ 1. Render 3 test frames (start, middle, end)
363
+ 2. Check `canvas.mean() > 8` after tonemap
364
+ 3. Check no scene is visually flat black
365
+ 4. Verify per-section variation (different bg/palette/color per scene)
366
+ 5. Confirm shader chain includes bloom (threshold 130)
367
+ 6. Confirm vignette strength ≤ 0.25
skills/.archive/audiocraft/SKILL.md ADDED
@@ -0,0 +1,568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: audiocraft-audio-generation
3
+ description: "AudioCraft: MusicGen text-to-music, AudioGen text-to-sound."
4
+ version: 1.0.0
5
+ author: Orchestra Research
6
+ license: MIT
7
+ dependencies: [audiocraft, torch>=2.0.0, transformers>=4.30.0]
8
+ platforms: [linux, macos]
9
+ metadata:
10
+ hermes:
11
+ tags: [Multimodal, Audio Generation, Text-to-Music, Text-to-Audio, MusicGen]
12
+
13
+ ---
14
+
15
+ # AudioCraft: Audio Generation
16
+
17
+ Comprehensive guide to using Meta's AudioCraft for text-to-music and text-to-audio generation with MusicGen, AudioGen, and EnCodec.
18
+
19
+ ## When to use AudioCraft
20
+
21
+ **Use AudioCraft when:**
22
+ - Need to generate music from text descriptions
23
+ - Creating sound effects and environmental audio
24
+ - Building music generation applications
25
+ - Need melody-conditioned music generation
26
+ - Want stereo audio output
27
+ - Require controllable music generation with style transfer
28
+
29
+ **Key features:**
30
+ - **MusicGen**: Text-to-music generation with melody conditioning
31
+ - **AudioGen**: Text-to-sound effects generation
32
+ - **EnCodec**: High-fidelity neural audio codec
33
+ - **Multiple model sizes**: Small (300M) to Large (3.3B)
34
+ - **Stereo support**: Full stereo audio generation
35
+ - **Style conditioning**: MusicGen-Style for reference-based generation
36
+
37
+ **Use alternatives instead:**
38
+ - **Stable Audio**: For longer commercial music generation
39
+ - **Bark**: For text-to-speech with music/sound effects
40
+ - **Riffusion**: For spectogram-based music generation
41
+ - **OpenAI Jukebox**: For raw audio generation with lyrics
42
+
43
+ ## Quick start
44
+
45
+ ### Installation
46
+
47
+ ```bash
48
+ # From PyPI
49
+ pip install audiocraft
50
+
51
+ # From GitHub (latest)
52
+ pip install git+https://github.com/facebookresearch/audiocraft.git
53
+
54
+ # Or use HuggingFace Transformers
55
+ pip install transformers torch torchaudio
56
+ ```
57
+
58
+ ### Basic text-to-music (AudioCraft)
59
+
60
+ ```python
61
+ import torchaudio
62
+ from audiocraft.models import MusicGen
63
+
64
+ # Load model
65
+ model = MusicGen.get_pretrained('facebook/musicgen-small')
66
+
67
+ # Set generation parameters
68
+ model.set_generation_params(
69
+ duration=8, # seconds
70
+ top_k=250,
71
+ temperature=1.0
72
+ )
73
+
74
+ # Generate from text
75
+ descriptions = ["happy upbeat electronic dance music with synths"]
76
+ wav = model.generate(descriptions)
77
+
78
+ # Save audio
79
+ torchaudio.save("output.wav", wav[0].cpu(), sample_rate=32000)
80
+ ```
81
+
82
+ ### Using HuggingFace Transformers
83
+
84
+ ```python
85
+ from transformers import AutoProcessor, MusicgenForConditionalGeneration
86
+ import scipy
87
+
88
+ # Load model and processor
89
+ processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
90
+ model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")
91
+ model.to("cuda")
92
+
93
+ # Generate music
94
+ inputs = processor(
95
+ text=["80s pop track with bassy drums and synth"],
96
+ padding=True,
97
+ return_tensors="pt"
98
+ ).to("cuda")
99
+
100
+ audio_values = model.generate(
101
+ **inputs,
102
+ do_sample=True,
103
+ guidance_scale=3,
104
+ max_new_tokens=256
105
+ )
106
+
107
+ # Save
108
+ sampling_rate = model.config.audio_encoder.sampling_rate
109
+ scipy.io.wavfile.write("output.wav", rate=sampling_rate, data=audio_values[0, 0].cpu().numpy())
110
+ ```
111
+
112
+ ### Text-to-sound with AudioGen
113
+
114
+ ```python
115
+ from audiocraft.models import AudioGen
116
+
117
+ # Load AudioGen
118
+ model = AudioGen.get_pretrained('facebook/audiogen-medium')
119
+
120
+ model.set_generation_params(duration=5)
121
+
122
+ # Generate sound effects
123
+ descriptions = ["dog barking in a park with birds chirping"]
124
+ wav = model.generate(descriptions)
125
+
126
+ torchaudio.save("sound.wav", wav[0].cpu(), sample_rate=16000)
127
+ ```
128
+
129
+ ## Core concepts
130
+
131
+ ### Architecture overview
132
+
133
+ ```
134
+ AudioCraft Architecture:
135
+ ┌──────────────────────────────────────────────────────────────┐
136
+ │ Text Encoder (T5) │
137
+ │ │ │
138
+ │ Text Embeddings │
139
+ └────────────────────────┬─────────────────────────────────────┘
140
+ │
141
+ ┌────────────────────────▼─────────────────────────────────────┐
142
+ │ Transformer Decoder (LM) │
143
+ │ Auto-regressively generates audio tokens │
144
+ │ Using efficient token interleaving patterns │
145
+ └────────────────────────┬─────────────────────────────────────┘
146
+ │
147
+ ┌────────────────────────▼─────────────────────────────────────┐
148
+ │ EnCodec Audio Decoder │
149
+ │ Converts tokens back to audio waveform │
150
+ └──────────────────────────────────────────────────────────────┘
151
+ ```
152
+
153
+ ### Model variants
154
+
155
+ | Model | Size | Description | Use Case |
156
+ |-------|------|-------------|----------|
157
+ | `musicgen-small` | 300M | Text-to-music | Quick generation |
158
+ | `musicgen-medium` | 1.5B | Text-to-music | Balanced |
159
+ | `musicgen-large` | 3.3B | Text-to-music | Best quality |
160
+ | `musicgen-melody` | 1.5B | Text + melody | Melody conditioning |
161
+ | `musicgen-melody-large` | 3.3B | Text + melody | Best melody |
162
+ | `musicgen-stereo-*` | Varies | Stereo output | Stereo generation |
163
+ | `musicgen-style` | 1.5B | Style transfer | Reference-based |
164
+ | `audiogen-medium` | 1.5B | Text-to-sound | Sound effects |
165
+
166
+ ### Generation parameters
167
+
168
+ | Parameter | Default | Description |
169
+ |-----------|---------|-------------|
170
+ | `duration` | 8.0 | Length in seconds (1-120) |
171
+ | `top_k` | 250 | Top-k sampling |
172
+ | `top_p` | 0.0 | Nucleus sampling (0 = disabled) |
173
+ | `temperature` | 1.0 | Sampling temperature |
174
+ | `cfg_coef` | 3.0 | Classifier-free guidance |
175
+
176
+ ## MusicGen usage
177
+
178
+ ### Text-to-music generation
179
+
180
+ ```python
181
+ from audiocraft.models import MusicGen
182
+ import torchaudio
183
+
184
+ model = MusicGen.get_pretrained('facebook/musicgen-medium')
185
+
186
+ # Configure generation
187
+ model.set_generation_params(
188
+ duration=30, # Up to 30 seconds
189
+ top_k=250, # Sampling diversity
190
+ top_p=0.0, # 0 = use top_k only
191
+ temperature=1.0, # Creativity (higher = more varied)
192
+ cfg_coef=3.0 # Text adherence (higher = stricter)
193
+ )
194
+
195
+ # Generate multiple samples
196
+ descriptions = [
197
+ "epic orchestral soundtrack with strings and brass",
198
+ "chill lo-fi hip hop beat with jazzy piano",
199
+ "energetic rock song with electric guitar"
200
+ ]
201
+
202
+ # Generate (returns [batch, channels, samples])
203
+ wav = model.generate(descriptions)
204
+
205
+ # Save each
206
+ for i, audio in enumerate(wav):
207
+ torchaudio.save(f"music_{i}.wav", audio.cpu(), sample_rate=32000)
208
+ ```
209
+
210
+ ### Melody-conditioned generation
211
+
212
+ ```python
213
+ from audiocraft.models import MusicGen
214
+ import torchaudio
215
+
216
+ # Load melody model
217
+ model = MusicGen.get_pretrained('facebook/musicgen-melody')
218
+ model.set_generation_params(duration=30)
219
+
220
+ # Load melody audio
221
+ melody, sr = torchaudio.load("melody.wav")
222
+
223
+ # Generate with melody conditioning
224
+ descriptions = ["acoustic guitar folk song"]
225
+ wav = model.generate_with_chroma(descriptions, melody, sr)
226
+
227
+ torchaudio.save("melody_conditioned.wav", wav[0].cpu(), sample_rate=32000)
228
+ ```
229
+
230
+ ### Stereo generation
231
+
232
+ ```python
233
+ from audiocraft.models import MusicGen
234
+
235
+ # Load stereo model
236
+ model = MusicGen.get_pretrained('facebook/musicgen-stereo-medium')
237
+ model.set_generation_params(duration=15)
238
+
239
+ descriptions = ["ambient electronic music with wide stereo panning"]
240
+ wav = model.generate(descriptions)
241
+
242
+ # wav shape: [batch, 2, samples] for stereo
243
+ print(f"Stereo shape: {wav.shape}") # [1, 2, 480000]
244
+ torchaudio.save("stereo.wav", wav[0].cpu(), sample_rate=32000)
245
+ ```
246
+
247
+ ### Audio continuation
248
+
249
+ ```python
250
+ from transformers import AutoProcessor, MusicgenForConditionalGeneration
251
+
252
+ processor = AutoProcessor.from_pretrained("facebook/musicgen-medium")
253
+ model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-medium")
254
+
255
+ # Load audio to continue
256
+ import torchaudio
257
+ audio, sr = torchaudio.load("intro.wav")
258
+
259
+ # Process with text and audio
260
+ inputs = processor(
261
+ audio=audio.squeeze().numpy(),
262
+ sampling_rate=sr,
263
+ text=["continue with a epic chorus"],
264
+ padding=True,
265
+ return_tensors="pt"
266
+ )
267
+
268
+ # Generate continuation
269
+ audio_values = model.generate(**inputs, do_sample=True, guidance_scale=3, max_new_tokens=512)
270
+ ```
271
+
272
+ ## MusicGen-Style usage
273
+
274
+ ### Style-conditioned generation
275
+
276
+ ```python
277
+ from audiocraft.models import MusicGen
278
+
279
+ # Load style model
280
+ model = MusicGen.get_pretrained('facebook/musicgen-style')
281
+
282
+ # Configure generation with style
283
+ model.set_generation_params(
284
+ duration=30,
285
+ cfg_coef=3.0,
286
+ cfg_coef_beta=5.0 # Style influence
287
+ )
288
+
289
+ # Configure style conditioner
290
+ model.set_style_conditioner_params(
291
+ eval_q=3, # RVQ quantizers (1-6)
292
+ excerpt_length=3.0 # Style excerpt length
293
+ )
294
+
295
+ # Load style reference
296
+ style_audio, sr = torchaudio.load("reference_style.wav")
297
+
298
+ # Generate with text + style
299
+ descriptions = ["upbeat dance track"]
300
+ wav = model.generate_with_style(descriptions, style_audio, sr)
301
+ ```
302
+
303
+ ### Style-only generation (no text)
304
+
305
+ ```python
306
+ # Generate matching style without text prompt
307
+ model.set_generation_params(
308
+ duration=30,
309
+ cfg_coef=3.0,
310
+ cfg_coef_beta=None # Disable double CFG for style-only
311
+ )
312
+
313
+ wav = model.generate_with_style([None], style_audio, sr)
314
+ ```
315
+
316
+ ## AudioGen usage
317
+
318
+ ### Sound effect generation
319
+
320
+ ```python
321
+ from audiocraft.models import AudioGen
322
+ import torchaudio
323
+
324
+ model = AudioGen.get_pretrained('facebook/audiogen-medium')
325
+ model.set_generation_params(duration=10)
326
+
327
+ # Generate various sounds
328
+ descriptions = [
329
+ "thunderstorm with heavy rain and lightning",
330
+ "busy city traffic with car horns",
331
+ "ocean waves crashing on rocks",
332
+ "crackling campfire in forest"
333
+ ]
334
+
335
+ wav = model.generate(descriptions)
336
+
337
+ for i, audio in enumerate(wav):
338
+ torchaudio.save(f"sound_{i}.wav", audio.cpu(), sample_rate=16000)
339
+ ```
340
+
341
+ ## EnCodec usage
342
+
343
+ ### Audio compression
344
+
345
+ ```python
346
+ from audiocraft.models import CompressionModel
347
+ import torch
348
+ import torchaudio
349
+
350
+ # Load EnCodec
351
+ model = CompressionModel.get_pretrained('facebook/encodec_32khz')
352
+
353
+ # Load audio
354
+ wav, sr = torchaudio.load("audio.wav")
355
+
356
+ # Ensure correct sample rate
357
+ if sr != 32000:
358
+ resampler = torchaudio.transforms.Resample(sr, 32000)
359
+ wav = resampler(wav)
360
+
361
+ # Encode to tokens
362
+ with torch.no_grad():
363
+ encoded = model.encode(wav.unsqueeze(0))
364
+ codes = encoded[0] # Audio codes
365
+
366
+ # Decode back to audio
367
+ with torch.no_grad():
368
+ decoded = model.decode(codes)
369
+
370
+ torchaudio.save("reconstructed.wav", decoded[0].cpu(), sample_rate=32000)
371
+ ```
372
+
373
+ ## Common workflows
374
+
375
+ ### Workflow 1: Music generation pipeline
376
+
377
+ ```python
378
+ import torch
379
+ import torchaudio
380
+ from audiocraft.models import MusicGen
381
+
382
+ class MusicGenerator:
383
+ def __init__(self, model_name="facebook/musicgen-medium"):
384
+ self.model = MusicGen.get_pretrained(model_name)
385
+ self.sample_rate = 32000
386
+
387
+ def generate(self, prompt, duration=30, temperature=1.0, cfg=3.0):
388
+ self.model.set_generation_params(
389
+ duration=duration,
390
+ top_k=250,
391
+ temperature=temperature,
392
+ cfg_coef=cfg
393
+ )
394
+
395
+ with torch.no_grad():
396
+ wav = self.model.generate([prompt])
397
+
398
+ return wav[0].cpu()
399
+
400
+ def generate_batch(self, prompts, duration=30):
401
+ self.model.set_generation_params(duration=duration)
402
+
403
+ with torch.no_grad():
404
+ wav = self.model.generate(prompts)
405
+
406
+ return wav.cpu()
407
+
408
+ def save(self, audio, path):
409
+ torchaudio.save(path, audio, sample_rate=self.sample_rate)
410
+
411
+ # Usage
412
+ generator = MusicGenerator()
413
+ audio = generator.generate(
414
+ "epic cinematic orchestral music",
415
+ duration=30,
416
+ temperature=1.0
417
+ )
418
+ generator.save(audio, "epic_music.wav")
419
+ ```
420
+
421
+ ### Workflow 2: Sound design batch processing
422
+
423
+ ```python
424
+ import json
425
+ from pathlib import Path
426
+ from audiocraft.models import AudioGen
427
+ import torchaudio
428
+
429
+ def batch_generate_sounds(sound_specs, output_dir):
430
+ """
431
+ Generate multiple sounds from specifications.
432
+
433
+ Args:
434
+ sound_specs: list of {"name": str, "description": str, "duration": float}
435
+ output_dir: output directory path
436
+ """
437
+ model = AudioGen.get_pretrained('facebook/audiogen-medium')
438
+ output_dir = Path(output_dir)
439
+ output_dir.mkdir(exist_ok=True)
440
+
441
+ results = []
442
+
443
+ for spec in sound_specs:
444
+ model.set_generation_params(duration=spec.get("duration", 5))
445
+
446
+ wav = model.generate([spec["description"]])
447
+
448
+ output_path = output_dir / f"{spec['name']}.wav"
449
+ torchaudio.save(str(output_path), wav[0].cpu(), sample_rate=16000)
450
+
451
+ results.append({
452
+ "name": spec["name"],
453
+ "path": str(output_path),
454
+ "description": spec["description"]
455
+ })
456
+
457
+ return results
458
+
459
+ # Usage
460
+ sounds = [
461
+ {"name": "explosion", "description": "massive explosion with debris", "duration": 3},
462
+ {"name": "footsteps", "description": "footsteps on wooden floor", "duration": 5},
463
+ {"name": "door", "description": "wooden door creaking and closing", "duration": 2}
464
+ ]
465
+
466
+ results = batch_generate_sounds(sounds, "sound_effects/")
467
+ ```
468
+
469
+ ### Workflow 3: Gradio demo
470
+
471
+ ```python
472
+ import gradio as gr
473
+ import torch
474
+ import torchaudio
475
+ from audiocraft.models import MusicGen
476
+
477
+ model = MusicGen.get_pretrained('facebook/musicgen-small')
478
+
479
+ def generate_music(prompt, duration, temperature, cfg_coef):
480
+ model.set_generation_params(
481
+ duration=duration,
482
+ temperature=temperature,
483
+ cfg_coef=cfg_coef
484
+ )
485
+
486
+ with torch.no_grad():
487
+ wav = model.generate([prompt])
488
+
489
+ # Save to temp file
490
+ path = "temp_output.wav"
491
+ torchaudio.save(path, wav[0].cpu(), sample_rate=32000)
492
+ return path
493
+
494
+ demo = gr.Interface(
495
+ fn=generate_music,
496
+ inputs=[
497
+ gr.Textbox(label="Music Description", placeholder="upbeat electronic dance music"),
498
+ gr.Slider(1, 30, value=8, label="Duration (seconds)"),
499
+ gr.Slider(0.5, 2.0, value=1.0, label="Temperature"),
500
+ gr.Slider(1.0, 10.0, value=3.0, label="CFG Coefficient")
501
+ ],
502
+ outputs=gr.Audio(label="Generated Music"),
503
+ title="MusicGen Demo"
504
+ )
505
+
506
+ demo.launch()
507
+ ```
508
+
509
+ ## Performance optimization
510
+
511
+ ### Memory optimization
512
+
513
+ ```python
514
+ # Use smaller model
515
+ model = MusicGen.get_pretrained('facebook/musicgen-small')
516
+
517
+ # Clear cache between generations
518
+ torch.cuda.empty_cache()
519
+
520
+ # Generate shorter durations
521
+ model.set_generation_params(duration=10) # Instead of 30
522
+
523
+ # Use half precision
524
+ model = model.half()
525
+ ```
526
+
527
+ ### Batch processing efficiency
528
+
529
+ ```python
530
+ # Process multiple prompts at once (more efficient)
531
+ descriptions = ["prompt1", "prompt2", "prompt3", "prompt4"]
532
+ wav = model.generate(descriptions) # Single batch
533
+
534
+ # Instead of
535
+ for desc in descriptions:
536
+ wav = model.generate([desc]) # Multiple batches (slower)
537
+ ```
538
+
539
+ ### GPU memory requirements
540
+
541
+ | Model | FP32 VRAM | FP16 VRAM |
542
+ |-------|-----------|-----------|
543
+ | musicgen-small | ~4GB | ~2GB |
544
+ | musicgen-medium | ~8GB | ~4GB |
545
+ | musicgen-large | ~16GB | ~8GB |
546
+
547
+ ## Common issues
548
+
549
+ | Issue | Solution |
550
+ |-------|----------|
551
+ | CUDA OOM | Use smaller model, reduce duration |
552
+ | Poor quality | Increase cfg_coef, better prompts |
553
+ | Generation too short | Check max duration setting |
554
+ | Audio artifacts | Try different temperature |
555
+ | Stereo not working | Use stereo model variant |
556
+
557
+ ## References
558
+
559
+ - **[Advanced Usage](references/advanced-usage.md)** - Training, fine-tuning, deployment
560
+ - **[Troubleshooting](references/troubleshooting.md)** - Common issues and solutions
561
+
562
+ ## Resources
563
+
564
+ - **GitHub**: https://github.com/facebookresearch/audiocraft
565
+ - **Paper (MusicGen)**: https://arxiv.org/abs/2306.05284
566
+ - **Paper (AudioGen)**: https://arxiv.org/abs/2209.15352
567
+ - **HuggingFace**: https://huggingface.co/facebook/musicgen-small
568
+ - **Demo**: https://huggingface.co/spaces/facebook/MusicGen
skills/.archive/audiocraft/references/advanced-usage.md ADDED
@@ -0,0 +1,666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AudioCraft Advanced Usage Guide
2
+
3
+ ## Fine-tuning MusicGen
4
+
5
+ ### Custom dataset preparation
6
+
7
+ ```python
8
+ import os
9
+ import json
10
+ from pathlib import Path
11
+ import torchaudio
12
+
13
+ def prepare_dataset(audio_dir, output_dir, metadata_file):
14
+ """
15
+ Prepare dataset for MusicGen fine-tuning.
16
+
17
+ Directory structure:
18
+ output_dir/
19
+ ├── audio/
20
+ │ ├── 0001.wav
21
+ │ ├── 0002.wav
22
+ │ └── ...
23
+ └── metadata.json
24
+ """
25
+ output_dir = Path(output_dir)
26
+ audio_output = output_dir / "audio"
27
+ audio_output.mkdir(parents=True, exist_ok=True)
28
+
29
+ # Load metadata (format: {"path": "...", "description": "..."})
30
+ with open(metadata_file) as f:
31
+ metadata = json.load(f)
32
+
33
+ processed = []
34
+
35
+ for idx, item in enumerate(metadata):
36
+ audio_path = Path(audio_dir) / item["path"]
37
+
38
+ # Load and resample to 32kHz
39
+ wav, sr = torchaudio.load(str(audio_path))
40
+ if sr != 32000:
41
+ resampler = torchaudio.transforms.Resample(sr, 32000)
42
+ wav = resampler(wav)
43
+
44
+ # Convert to mono if stereo
45
+ if wav.shape[0] > 1:
46
+ wav = wav.mean(dim=0, keepdim=True)
47
+
48
+ # Save processed audio
49
+ output_path = audio_output / f"{idx:04d}.wav"
50
+ torchaudio.save(str(output_path), wav, sample_rate=32000)
51
+
52
+ processed.append({
53
+ "path": str(output_path.relative_to(output_dir)),
54
+ "description": item["description"],
55
+ "duration": wav.shape[1] / 32000
56
+ })
57
+
58
+ # Save processed metadata
59
+ with open(output_dir / "metadata.json", "w") as f:
60
+ json.dump(processed, f, indent=2)
61
+
62
+ print(f"Processed {len(processed)} samples")
63
+ return processed
64
+ ```
65
+
66
+ ### Fine-tuning with dora
67
+
68
+ ```bash
69
+ # AudioCraft uses dora for experiment management
70
+ # Install dora
71
+ pip install dora-search
72
+
73
+ # Clone AudioCraft
74
+ git clone https://github.com/facebookresearch/audiocraft.git
75
+ cd audiocraft
76
+
77
+ # Create config for fine-tuning
78
+ cat > config/solver/musicgen/finetune.yaml << 'EOF'
79
+ defaults:
80
+ - musicgen/musicgen_base
81
+ - /model: lm/musicgen_lm
82
+ - /conditioner: cond_base
83
+
84
+ solver: musicgen
85
+ autocast: true
86
+ autocast_dtype: float16
87
+
88
+ optim:
89
+ epochs: 100
90
+ batch_size: 4
91
+ lr: 1e-4
92
+ ema: 0.999
93
+ optimizer: adamw
94
+
95
+ dataset:
96
+ batch_size: 4
97
+ num_workers: 4
98
+ train:
99
+ - dset: your_dataset
100
+ root: /path/to/dataset
101
+ valid:
102
+ - dset: your_dataset
103
+ root: /path/to/dataset
104
+
105
+ checkpoint:
106
+ save_every: 10
107
+ keep_every_states: null
108
+ EOF
109
+
110
+ # Run fine-tuning
111
+ dora run solver=musicgen/finetune
112
+ ```
113
+
114
+ ### LoRA fine-tuning
115
+
116
+ ```python
117
+ from peft import LoraConfig, get_peft_model
118
+ from audiocraft.models import MusicGen
119
+ import torch
120
+
121
+ # Load base model
122
+ model = MusicGen.get_pretrained('facebook/musicgen-small')
123
+
124
+ # Get the language model component
125
+ lm = model.lm
126
+
127
+ # Configure LoRA
128
+ lora_config = LoraConfig(
129
+ r=8,
130
+ lora_alpha=16,
131
+ target_modules=["q_proj", "v_proj", "k_proj", "out_proj"],
132
+ lora_dropout=0.05,
133
+ bias="none"
134
+ )
135
+
136
+ # Apply LoRA
137
+ lm = get_peft_model(lm, lora_config)
138
+ lm.print_trainable_parameters()
139
+ ```
140
+
141
+ ## Multi-GPU Training
142
+
143
+ ### DataParallel
144
+
145
+ ```python
146
+ import torch
147
+ import torch.nn as nn
148
+ from audiocraft.models import MusicGen
149
+
150
+ model = MusicGen.get_pretrained('facebook/musicgen-small')
151
+
152
+ # Wrap LM with DataParallel
153
+ if torch.cuda.device_count() > 1:
154
+ model.lm = nn.DataParallel(model.lm)
155
+
156
+ model.to("cuda")
157
+ ```
158
+
159
+ ### DistributedDataParallel
160
+
161
+ ```python
162
+ import torch.distributed as dist
163
+ from torch.nn.parallel import DistributedDataParallel as DDP
164
+
165
+ def setup(rank, world_size):
166
+ dist.init_process_group("nccl", rank=rank, world_size=world_size)
167
+ torch.cuda.set_device(rank)
168
+
169
+ def train(rank, world_size):
170
+ setup(rank, world_size)
171
+
172
+ model = MusicGen.get_pretrained('facebook/musicgen-small')
173
+ model.lm = model.lm.to(rank)
174
+ model.lm = DDP(model.lm, device_ids=[rank])
175
+
176
+ # Training loop
177
+ # ...
178
+
179
+ dist.destroy_process_group()
180
+ ```
181
+
182
+ ## Custom Conditioning
183
+
184
+ ### Adding new conditioners
185
+
186
+ ```python
187
+ from audiocraft.modules.conditioners import BaseConditioner
188
+ import torch
189
+
190
+ class CustomConditioner(BaseConditioner):
191
+ """Custom conditioner for additional control signals."""
192
+
193
+ def __init__(self, dim, output_dim):
194
+ super().__init__(dim, output_dim)
195
+ self.embed = torch.nn.Linear(dim, output_dim)
196
+
197
+ def forward(self, x):
198
+ return self.embed(x)
199
+
200
+ def tokenize(self, x):
201
+ # Tokenize input for conditioning
202
+ return x
203
+
204
+ # Use with MusicGen
205
+ from audiocraft.models.builders import get_lm_model
206
+
207
+ # Modify model config to include custom conditioner
208
+ # This requires editing the model configuration
209
+ ```
210
+
211
+ ### Melody conditioning internals
212
+
213
+ ```python
214
+ from audiocraft.models import MusicGen
215
+ from audiocraft.modules.codebooks_patterns import DelayedPatternProvider
216
+ import torch
217
+
218
+ model = MusicGen.get_pretrained('facebook/musicgen-melody')
219
+
220
+ # Access chroma extractor
221
+ chroma_extractor = model.lm.condition_provider.conditioners.get('chroma')
222
+
223
+ # Manual chroma extraction
224
+ def extract_chroma(audio, sr):
225
+ """Extract chroma features from audio."""
226
+ import librosa
227
+
228
+ # Compute chroma
229
+ chroma = librosa.feature.chroma_cqt(y=audio.numpy(), sr=sr)
230
+
231
+ return torch.from_numpy(chroma).float()
232
+
233
+ # Use extracted chroma for conditioning
234
+ chroma = extract_chroma(melody_audio, sample_rate)
235
+ ```
236
+
237
+ ## EnCodec Deep Dive
238
+
239
+ ### Custom compression settings
240
+
241
+ ```python
242
+ from audiocraft.models import CompressionModel
243
+ import torch
244
+
245
+ # Load EnCodec
246
+ encodec = CompressionModel.get_pretrained('facebook/encodec_32khz')
247
+
248
+ # Access codec parameters
249
+ print(f"Sample rate: {encodec.sample_rate}")
250
+ print(f"Channels: {encodec.channels}")
251
+ print(f"Cardinality: {encodec.cardinality}") # Codebook size
252
+ print(f"Num codebooks: {encodec.num_codebooks}")
253
+ print(f"Frame rate: {encodec.frame_rate}")
254
+
255
+ # Encode with specific bandwidth
256
+ # Lower bandwidth = more compression, lower quality
257
+ encodec.set_target_bandwidth(6.0) # 6 kbps
258
+
259
+ audio = torch.randn(1, 1, 32000) # 1 second
260
+ encoded = encodec.encode(audio)
261
+ decoded = encodec.decode(encoded[0])
262
+ ```
263
+
264
+ ### Streaming encoding
265
+
266
+ ```python
267
+ import torch
268
+ from audiocraft.models import CompressionModel
269
+
270
+ encodec = CompressionModel.get_pretrained('facebook/encodec_32khz')
271
+
272
+ def encode_streaming(audio_stream, chunk_size=32000):
273
+ """Encode audio in streaming fashion."""
274
+ all_codes = []
275
+
276
+ for chunk in audio_stream:
277
+ # Ensure chunk is right shape
278
+ if chunk.dim() == 1:
279
+ chunk = chunk.unsqueeze(0).unsqueeze(0)
280
+
281
+ with torch.no_grad():
282
+ codes = encodec.encode(chunk)[0]
283
+ all_codes.append(codes)
284
+
285
+ return torch.cat(all_codes, dim=-1)
286
+
287
+ def decode_streaming(codes_stream, output_stream):
288
+ """Decode codes in streaming fashion."""
289
+ for codes in codes_stream:
290
+ with torch.no_grad():
291
+ audio = encodec.decode(codes)
292
+ output_stream.write(audio.cpu().numpy())
293
+ ```
294
+
295
+ ## MultiBand Diffusion
296
+
297
+ ### Using MBD for enhanced quality
298
+
299
+ ```python
300
+ from audiocraft.models import MusicGen, MultiBandDiffusion
301
+
302
+ # Load MusicGen
303
+ model = MusicGen.get_pretrained('facebook/musicgen-medium')
304
+
305
+ # Load MultiBand Diffusion
306
+ mbd = MultiBandDiffusion.get_mbd_musicgen()
307
+
308
+ model.set_generation_params(duration=10)
309
+
310
+ # Generate with standard decoder
311
+ descriptions = ["epic orchestral music"]
312
+ wav_standard = model.generate(descriptions)
313
+
314
+ # Generate tokens and use MBD decoder
315
+ with torch.no_grad():
316
+ # Get tokens
317
+ gen_tokens = model.generate_tokens(descriptions)
318
+
319
+ # Decode with MBD
320
+ wav_mbd = mbd.tokens_to_wav(gen_tokens)
321
+
322
+ # Compare quality
323
+ print(f"Standard shape: {wav_standard.shape}")
324
+ print(f"MBD shape: {wav_mbd.shape}")
325
+ ```
326
+
327
+ ## API Server Deployment
328
+
329
+ ### FastAPI server
330
+
331
+ ```python
332
+ from fastapi import FastAPI, HTTPException
333
+ from pydantic import BaseModel
334
+ import torch
335
+ import torchaudio
336
+ from audiocraft.models import MusicGen
337
+ import io
338
+ import base64
339
+
340
+ app = FastAPI()
341
+
342
+ # Load model at startup
343
+ model = None
344
+
345
+ @app.on_event("startup")
346
+ async def load_model():
347
+ global model
348
+ model = MusicGen.get_pretrained('facebook/musicgen-small')
349
+ model.set_generation_params(duration=10)
350
+
351
+ class GenerateRequest(BaseModel):
352
+ prompt: str
353
+ duration: float = 10.0
354
+ temperature: float = 1.0
355
+ cfg_coef: float = 3.0
356
+
357
+ class GenerateResponse(BaseModel):
358
+ audio_base64: str
359
+ sample_rate: int
360
+ duration: float
361
+
362
+ @app.post("/generate", response_model=GenerateResponse)
363
+ async def generate(request: GenerateRequest):
364
+ if model is None:
365
+ raise HTTPException(status_code=500, detail="Model not loaded")
366
+
367
+ try:
368
+ model.set_generation_params(
369
+ duration=min(request.duration, 30),
370
+ temperature=request.temperature,
371
+ cfg_coef=request.cfg_coef
372
+ )
373
+
374
+ with torch.no_grad():
375
+ wav = model.generate([request.prompt])
376
+
377
+ # Convert to bytes
378
+ buffer = io.BytesIO()
379
+ torchaudio.save(buffer, wav[0].cpu(), sample_rate=32000, format="wav")
380
+ buffer.seek(0)
381
+
382
+ audio_base64 = base64.b64encode(buffer.read()).decode()
383
+
384
+ return GenerateResponse(
385
+ audio_base64=audio_base64,
386
+ sample_rate=32000,
387
+ duration=wav.shape[-1] / 32000
388
+ )
389
+
390
+ except Exception as e:
391
+ raise HTTPException(status_code=500, detail=str(e))
392
+
393
+ @app.get("/health")
394
+ async def health():
395
+ return {"status": "ok", "model_loaded": model is not None}
396
+
397
+ # Run: uvicorn server:app --host 0.0.0.0 --port 8000
398
+ ```
399
+
400
+ ### Batch processing service
401
+
402
+ ```python
403
+ import asyncio
404
+ from concurrent.futures import ThreadPoolExecutor
405
+ import torch
406
+ from audiocraft.models import MusicGen
407
+
408
+ class MusicGenService:
409
+ def __init__(self, model_name='facebook/musicgen-small', max_workers=2):
410
+ self.model = MusicGen.get_pretrained(model_name)
411
+ self.executor = ThreadPoolExecutor(max_workers=max_workers)
412
+ self.lock = asyncio.Lock()
413
+
414
+ async def generate_async(self, prompt, duration=10):
415
+ """Async generation with thread pool."""
416
+ loop = asyncio.get_event_loop()
417
+
418
+ def _generate():
419
+ with torch.no_grad():
420
+ self.model.set_generation_params(duration=duration)
421
+ return self.model.generate([prompt])
422
+
423
+ # Run in thread pool
424
+ wav = await loop.run_in_executor(self.executor, _generate)
425
+ return wav[0].cpu()
426
+
427
+ async def generate_batch_async(self, prompts, duration=10):
428
+ """Process multiple prompts concurrently."""
429
+ tasks = [self.generate_async(p, duration) for p in prompts]
430
+ return await asyncio.gather(*tasks)
431
+
432
+ # Usage
433
+ service = MusicGenService()
434
+
435
+ async def main():
436
+ prompts = ["jazz piano", "rock guitar", "electronic beats"]
437
+ results = await service.generate_batch_async(prompts)
438
+ return results
439
+ ```
440
+
441
+ ## Integration Patterns
442
+
443
+ ### LangChain tool
444
+
445
+ ```python
446
+ from langchain.tools import BaseTool
447
+ import torch
448
+ import torchaudio
449
+ from audiocraft.models import MusicGen
450
+ import tempfile
451
+
452
+ class MusicGeneratorTool(BaseTool):
453
+ name = "music_generator"
454
+ description = "Generate music from a text description. Input should be a detailed description of the music style, mood, and instruments."
455
+
456
+ def __init__(self):
457
+ super().__init__()
458
+ self.model = MusicGen.get_pretrained('facebook/musicgen-small')
459
+ self.model.set_generation_params(duration=15)
460
+
461
+ def _run(self, description: str) -> str:
462
+ with torch.no_grad():
463
+ wav = self.model.generate([description])
464
+
465
+ # Save to temp file
466
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
467
+ torchaudio.save(f.name, wav[0].cpu(), sample_rate=32000)
468
+ return f"Generated music saved to: {f.name}"
469
+
470
+ async def _arun(self, description: str) -> str:
471
+ return self._run(description)
472
+ ```
473
+
474
+ ### Gradio with advanced controls
475
+
476
+ ```python
477
+ import gradio as gr
478
+ import torch
479
+ import torchaudio
480
+ from audiocraft.models import MusicGen
481
+
482
+ models = {}
483
+
484
+ def load_model(model_size):
485
+ if model_size not in models:
486
+ model_name = f"facebook/musicgen-{model_size}"
487
+ models[model_size] = MusicGen.get_pretrained(model_name)
488
+ return models[model_size]
489
+
490
+ def generate(prompt, duration, temperature, cfg_coef, top_k, model_size):
491
+ model = load_model(model_size)
492
+
493
+ model.set_generation_params(
494
+ duration=duration,
495
+ temperature=temperature,
496
+ cfg_coef=cfg_coef,
497
+ top_k=top_k
498
+ )
499
+
500
+ with torch.no_grad():
501
+ wav = model.generate([prompt])
502
+
503
+ # Save
504
+ path = "output.wav"
505
+ torchaudio.save(path, wav[0].cpu(), sample_rate=32000)
506
+ return path
507
+
508
+ demo = gr.Interface(
509
+ fn=generate,
510
+ inputs=[
511
+ gr.Textbox(label="Prompt", lines=3),
512
+ gr.Slider(1, 30, value=10, label="Duration (s)"),
513
+ gr.Slider(0.1, 2.0, value=1.0, label="Temperature"),
514
+ gr.Slider(0.5, 10.0, value=3.0, label="CFG Coefficient"),
515
+ gr.Slider(50, 500, value=250, step=50, label="Top-K"),
516
+ gr.Dropdown(["small", "medium", "large"], value="small", label="Model Size")
517
+ ],
518
+ outputs=gr.Audio(label="Generated Music"),
519
+ title="MusicGen Advanced",
520
+ allow_flagging="never"
521
+ )
522
+
523
+ demo.launch(share=True)
524
+ ```
525
+
526
+ ## Audio Processing Pipeline
527
+
528
+ ### Post-processing chain
529
+
530
+ ```python
531
+ import torch
532
+ import torchaudio
533
+ import torchaudio.transforms as T
534
+ import numpy as np
535
+
536
+ class AudioPostProcessor:
537
+ def __init__(self, sample_rate=32000):
538
+ self.sample_rate = sample_rate
539
+
540
+ def normalize(self, audio, target_db=-14.0):
541
+ """Normalize audio to target loudness."""
542
+ rms = torch.sqrt(torch.mean(audio ** 2))
543
+ target_rms = 10 ** (target_db / 20)
544
+ gain = target_rms / (rms + 1e-8)
545
+ return audio * gain
546
+
547
+ def fade_in_out(self, audio, fade_duration=0.1):
548
+ """Apply fade in/out."""
549
+ fade_samples = int(fade_duration * self.sample_rate)
550
+
551
+ # Create fade curves
552
+ fade_in = torch.linspace(0, 1, fade_samples)
553
+ fade_out = torch.linspace(1, 0, fade_samples)
554
+
555
+ # Apply fades
556
+ audio[..., :fade_samples] *= fade_in
557
+ audio[..., -fade_samples:] *= fade_out
558
+
559
+ return audio
560
+
561
+ def apply_reverb(self, audio, decay=0.5):
562
+ """Apply simple reverb effect."""
563
+ impulse = torch.zeros(int(self.sample_rate * 0.5))
564
+ impulse[0] = 1.0
565
+ impulse[int(self.sample_rate * 0.1)] = decay * 0.5
566
+ impulse[int(self.sample_rate * 0.2)] = decay * 0.25
567
+
568
+ # Convolve
569
+ audio = torch.nn.functional.conv1d(
570
+ audio.unsqueeze(0),
571
+ impulse.unsqueeze(0).unsqueeze(0),
572
+ padding=len(impulse) // 2
573
+ ).squeeze(0)
574
+
575
+ return audio
576
+
577
+ def process(self, audio):
578
+ """Full processing pipeline."""
579
+ audio = self.normalize(audio)
580
+ audio = self.fade_in_out(audio)
581
+ return audio
582
+
583
+ # Usage with MusicGen
584
+ from audiocraft.models import MusicGen
585
+
586
+ model = MusicGen.get_pretrained('facebook/musicgen-small')
587
+ model.set_generation_params(duration=10)
588
+
589
+ wav = model.generate(["chill ambient music"])
590
+ processor = AudioPostProcessor()
591
+ wav_processed = processor.process(wav[0].cpu())
592
+
593
+ torchaudio.save("processed.wav", wav_processed, sample_rate=32000)
594
+ ```
595
+
596
+ ## Evaluation
597
+
598
+ ### Audio quality metrics
599
+
600
+ ```python
601
+ import torch
602
+ from audiocraft.metrics import CLAPTextConsistencyMetric
603
+ from audiocraft.data.audio import audio_read
604
+
605
+ def evaluate_generation(audio_path, text_prompt):
606
+ """Evaluate generated audio quality."""
607
+ # Load audio
608
+ wav, sr = audio_read(audio_path)
609
+
610
+ # CLAP consistency (text-audio alignment)
611
+ clap_metric = CLAPTextConsistencyMetric()
612
+ clap_score = clap_metric.compute(wav, [text_prompt])
613
+
614
+ return {
615
+ "clap_score": clap_score,
616
+ "duration": wav.shape[-1] / sr
617
+ }
618
+
619
+ # Batch evaluation
620
+ def evaluate_batch(generations):
621
+ """Evaluate multiple generations."""
622
+ results = []
623
+ for gen in generations:
624
+ result = evaluate_generation(gen["path"], gen["prompt"])
625
+ result["prompt"] = gen["prompt"]
626
+ results.append(result)
627
+
628
+ # Aggregate
629
+ avg_clap = sum(r["clap_score"] for r in results) / len(results)
630
+ return {
631
+ "individual": results,
632
+ "average_clap": avg_clap
633
+ }
634
+ ```
635
+
636
+ ## Model Comparison
637
+
638
+ ### MusicGen variants benchmark
639
+
640
+ | Model | CLAP Score | Generation Time (10s) | VRAM |
641
+ |-------|------------|----------------------|------|
642
+ | musicgen-small | 0.35 | ~5s | 2GB |
643
+ | musicgen-medium | 0.42 | ~15s | 4GB |
644
+ | musicgen-large | 0.48 | ~30s | 8GB |
645
+ | musicgen-melody | 0.45 | ~15s | 4GB |
646
+ | musicgen-stereo-medium | 0.41 | ~18s | 5GB |
647
+
648
+ ### Prompt engineering tips
649
+
650
+ ```python
651
+ # Good prompts - specific and descriptive
652
+ good_prompts = [
653
+ "upbeat electronic dance music with synthesizer leads and punchy drums at 128 bpm",
654
+ "melancholic piano ballad with strings, slow tempo, emotional and cinematic",
655
+ "funky disco groove with slap bass, brass section, and rhythmic guitar"
656
+ ]
657
+
658
+ # Bad prompts - too vague
659
+ bad_prompts = [
660
+ "nice music",
661
+ "song",
662
+ "good beat"
663
+ ]
664
+
665
+ # Structure: [mood] [genre] with [instruments] at [tempo/style]
666
+ ```
skills/.archive/audiocraft/references/troubleshooting.md ADDED
@@ -0,0 +1,504 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AudioCraft Troubleshooting Guide
2
+
3
+ ## Installation Issues
4
+
5
+ ### Import errors
6
+
7
+ **Error**: `ModuleNotFoundError: No module named 'audiocraft'`
8
+
9
+ **Solutions**:
10
+ ```bash
11
+ # Install from PyPI
12
+ pip install audiocraft
13
+
14
+ # Or from GitHub
15
+ pip install git+https://github.com/facebookresearch/audiocraft.git
16
+
17
+ # Verify installation
18
+ python -c "from audiocraft.models import MusicGen; print('OK')"
19
+ ```
20
+
21
+ ### FFmpeg not found
22
+
23
+ **Error**: `RuntimeError: ffmpeg not found`
24
+
25
+ **Solutions**:
26
+ ```bash
27
+ # Ubuntu/Debian
28
+ sudo apt-get install ffmpeg
29
+
30
+ # macOS
31
+ brew install ffmpeg
32
+
33
+ # Windows (using conda)
34
+ conda install -c conda-forge ffmpeg
35
+
36
+ # Verify
37
+ ffmpeg -version
38
+ ```
39
+
40
+ ### PyTorch CUDA mismatch
41
+
42
+ **Error**: `RuntimeError: CUDA error: no kernel image is available`
43
+
44
+ **Solutions**:
45
+ ```bash
46
+ # Check CUDA version
47
+ nvcc --version
48
+ python -c "import torch; print(torch.version.cuda)"
49
+
50
+ # Install matching PyTorch
51
+ pip install torch torchaudio --index-url https://download.pytorch.org/whl/cu121
52
+
53
+ # For CUDA 11.8
54
+ pip install torch torchaudio --index-url https://download.pytorch.org/whl/cu118
55
+ ```
56
+
57
+ ### xformers issues
58
+
59
+ **Error**: `ImportError: xformers` related errors
60
+
61
+ **Solutions**:
62
+ ```bash
63
+ # Install xformers for memory efficiency
64
+ pip install xformers
65
+
66
+ # Or disable xformers
67
+ export AUDIOCRAFT_USE_XFORMERS=0
68
+
69
+ # In Python
70
+ import os
71
+ os.environ["AUDIOCRAFT_USE_XFORMERS"] = "0"
72
+ from audiocraft.models import MusicGen
73
+ ```
74
+
75
+ ## Model Loading Issues
76
+
77
+ ### Out of memory during load
78
+
79
+ **Error**: `torch.cuda.OutOfMemoryError` during model loading
80
+
81
+ **Solutions**:
82
+ ```python
83
+ # Use smaller model
84
+ model = MusicGen.get_pretrained('facebook/musicgen-small')
85
+
86
+ # Force CPU loading first
87
+ import torch
88
+ device = "cpu"
89
+ model = MusicGen.get_pretrained('facebook/musicgen-small', device=device)
90
+ model = model.to("cuda")
91
+
92
+ # Use HuggingFace with device_map
93
+ from transformers import MusicgenForConditionalGeneration
94
+ model = MusicgenForConditionalGeneration.from_pretrained(
95
+ "facebook/musicgen-small",
96
+ device_map="auto"
97
+ )
98
+ ```
99
+
100
+ ### Download failures
101
+
102
+ **Error**: Connection errors or incomplete downloads
103
+
104
+ **Solutions**:
105
+ ```python
106
+ # Set cache directory
107
+ import os
108
+ os.environ["AUDIOCRAFT_CACHE_DIR"] = "/path/to/cache"
109
+
110
+ # Or for HuggingFace
111
+ os.environ["HF_HOME"] = "/path/to/hf_cache"
112
+
113
+ # Resume download
114
+ from huggingface_hub import snapshot_download
115
+ snapshot_download("facebook/musicgen-small", resume_download=True)
116
+
117
+ # Use local files
118
+ model = MusicGen.get_pretrained('/local/path/to/model')
119
+ ```
120
+
121
+ ### Wrong model type
122
+
123
+ **Error**: Loading wrong model for task
124
+
125
+ **Solutions**:
126
+ ```python
127
+ # For text-to-music: use MusicGen
128
+ from audiocraft.models import MusicGen
129
+ model = MusicGen.get_pretrained('facebook/musicgen-medium')
130
+
131
+ # For text-to-sound: use AudioGen
132
+ from audiocraft.models import AudioGen
133
+ model = AudioGen.get_pretrained('facebook/audiogen-medium')
134
+
135
+ # For melody conditioning: use melody variant
136
+ model = MusicGen.get_pretrained('facebook/musicgen-melody')
137
+
138
+ # For stereo: use stereo variant
139
+ model = MusicGen.get_pretrained('facebook/musicgen-stereo-medium')
140
+ ```
141
+
142
+ ## Generation Issues
143
+
144
+ ### Empty or silent output
145
+
146
+ **Problem**: Generated audio is silent or very quiet
147
+
148
+ **Solutions**:
149
+ ```python
150
+ import torch
151
+
152
+ # Check output
153
+ wav = model.generate(["upbeat music"])
154
+ print(f"Shape: {wav.shape}")
155
+ print(f"Max amplitude: {wav.abs().max().item()}")
156
+ print(f"Mean amplitude: {wav.abs().mean().item()}")
157
+
158
+ # If too quiet, normalize
159
+ def normalize_audio(audio, target_db=-14.0):
160
+ rms = torch.sqrt(torch.mean(audio ** 2))
161
+ target_rms = 10 ** (target_db / 20)
162
+ gain = target_rms / (rms + 1e-8)
163
+ return audio * gain
164
+
165
+ wav_normalized = normalize_audio(wav)
166
+ ```
167
+
168
+ ### Poor quality output
169
+
170
+ **Problem**: Generated music sounds bad or noisy
171
+
172
+ **Solutions**:
173
+ ```python
174
+ # Use larger model
175
+ model = MusicGen.get_pretrained('facebook/musicgen-large')
176
+
177
+ # Adjust generation parameters
178
+ model.set_generation_params(
179
+ duration=15,
180
+ top_k=250, # Increase for more diversity
181
+ temperature=0.8, # Lower for more focused output
182
+ cfg_coef=4.0 # Increase for better text adherence
183
+ )
184
+
185
+ # Use better prompts
186
+ # Bad: "music"
187
+ # Good: "upbeat electronic dance music with synthesizers and punchy drums"
188
+
189
+ # Try MultiBand Diffusion
190
+ from audiocraft.models import MultiBandDiffusion
191
+ mbd = MultiBandDiffusion.get_mbd_musicgen()
192
+ tokens = model.generate_tokens(["prompt"])
193
+ wav = mbd.tokens_to_wav(tokens)
194
+ ```
195
+
196
+ ### Generation too short
197
+
198
+ **Problem**: Audio shorter than expected
199
+
200
+ **Solutions**:
201
+ ```python
202
+ # Check duration setting
203
+ model.set_generation_params(duration=30) # Set before generate
204
+
205
+ # Verify in generation
206
+ print(f"Duration setting: {model.generation_params}")
207
+
208
+ # Check output shape
209
+ wav = model.generate(["prompt"])
210
+ actual_duration = wav.shape[-1] / 32000
211
+ print(f"Actual duration: {actual_duration}s")
212
+
213
+ # Note: max duration is typically 30s
214
+ ```
215
+
216
+ ### Melody conditioning fails
217
+
218
+ **Error**: Issues with melody-conditioned generation
219
+
220
+ **Solutions**:
221
+ ```python
222
+ import torchaudio
223
+ from audiocraft.models import MusicGen
224
+
225
+ # Load melody model (not base model)
226
+ model = MusicGen.get_pretrained('facebook/musicgen-melody')
227
+
228
+ # Load and prepare melody
229
+ melody, sr = torchaudio.load("melody.wav")
230
+
231
+ # Resample to model sample rate if needed
232
+ if sr != 32000:
233
+ resampler = torchaudio.transforms.Resample(sr, 32000)
234
+ melody = resampler(melody)
235
+
236
+ # Ensure correct shape [batch, channels, samples]
237
+ if melody.dim() == 1:
238
+ melody = melody.unsqueeze(0).unsqueeze(0)
239
+ elif melody.dim() == 2:
240
+ melody = melody.unsqueeze(0)
241
+
242
+ # Convert stereo to mono
243
+ if melody.shape[1] > 1:
244
+ melody = melody.mean(dim=1, keepdim=True)
245
+
246
+ # Generate with melody
247
+ model.set_generation_params(duration=min(melody.shape[-1] / 32000, 30))
248
+ wav = model.generate_with_chroma(["piano cover"], melody, 32000)
249
+ ```
250
+
251
+ ## Memory Issues
252
+
253
+ ### CUDA out of memory
254
+
255
+ **Error**: `torch.cuda.OutOfMemoryError: CUDA out of memory`
256
+
257
+ **Solutions**:
258
+ ```python
259
+ import torch
260
+
261
+ # Clear cache before generation
262
+ torch.cuda.empty_cache()
263
+
264
+ # Use smaller model
265
+ model = MusicGen.get_pretrained('facebook/musicgen-small')
266
+
267
+ # Reduce duration
268
+ model.set_generation_params(duration=10) # Instead of 30
269
+
270
+ # Generate one at a time
271
+ for prompt in prompts:
272
+ wav = model.generate([prompt])
273
+ save_audio(wav)
274
+ torch.cuda.empty_cache()
275
+
276
+ # Use CPU for very large generations
277
+ model = MusicGen.get_pretrained('facebook/musicgen-small', device="cpu")
278
+ ```
279
+
280
+ ### Memory leak during batch processing
281
+
282
+ **Problem**: Memory grows over time
283
+
284
+ **Solutions**:
285
+ ```python
286
+ import gc
287
+ import torch
288
+
289
+ def generate_with_cleanup(model, prompts):
290
+ results = []
291
+
292
+ for prompt in prompts:
293
+ with torch.no_grad():
294
+ wav = model.generate([prompt])
295
+ results.append(wav.cpu())
296
+
297
+ # Cleanup
298
+ del wav
299
+ gc.collect()
300
+ torch.cuda.empty_cache()
301
+
302
+ return results
303
+
304
+ # Use context manager
305
+ with torch.inference_mode():
306
+ wav = model.generate(["prompt"])
307
+ ```
308
+
309
+ ## Audio Format Issues
310
+
311
+ ### Wrong sample rate
312
+
313
+ **Problem**: Audio plays at wrong speed
314
+
315
+ **Solutions**:
316
+ ```python
317
+ import torchaudio
318
+
319
+ # MusicGen outputs at 32kHz
320
+ sample_rate = 32000
321
+
322
+ # AudioGen outputs at 16kHz
323
+ sample_rate = 16000
324
+
325
+ # Always use correct rate when saving
326
+ torchaudio.save("output.wav", wav[0].cpu(), sample_rate=sample_rate)
327
+
328
+ # Resample if needed
329
+ resampler = torchaudio.transforms.Resample(32000, 44100)
330
+ wav_resampled = resampler(wav)
331
+ ```
332
+
333
+ ### Stereo/mono mismatch
334
+
335
+ **Problem**: Wrong number of channels
336
+
337
+ **Solutions**:
338
+ ```python
339
+ # Check model type
340
+ print(f"Audio channels: {wav.shape}")
341
+ # Mono: [batch, 1, samples]
342
+ # Stereo: [batch, 2, samples]
343
+
344
+ # Convert mono to stereo
345
+ if wav.shape[1] == 1:
346
+ wav_stereo = wav.repeat(1, 2, 1)
347
+
348
+ # Convert stereo to mono
349
+ if wav.shape[1] == 2:
350
+ wav_mono = wav.mean(dim=1, keepdim=True)
351
+
352
+ # Use stereo model for stereo output
353
+ model = MusicGen.get_pretrained('facebook/musicgen-stereo-medium')
354
+ ```
355
+
356
+ ### Clipping and distortion
357
+
358
+ **Problem**: Audio has clipping or distortion
359
+
360
+ **Solutions**:
361
+ ```python
362
+ import torch
363
+
364
+ # Check for clipping
365
+ max_val = wav.abs().max().item()
366
+ print(f"Max amplitude: {max_val}")
367
+
368
+ # Normalize to prevent clipping
369
+ if max_val > 1.0:
370
+ wav = wav / max_val
371
+
372
+ # Apply soft clipping
373
+ def soft_clip(x, threshold=0.9):
374
+ return torch.tanh(x / threshold) * threshold
375
+
376
+ wav_clipped = soft_clip(wav)
377
+
378
+ # Lower temperature during generation
379
+ model.set_generation_params(temperature=0.7) # More controlled
380
+ ```
381
+
382
+ ## HuggingFace Transformers Issues
383
+
384
+ ### Processor errors
385
+
386
+ **Error**: Issues with MusicgenProcessor
387
+
388
+ **Solutions**:
389
+ ```python
390
+ from transformers import AutoProcessor, MusicgenForConditionalGeneration
391
+
392
+ # Load matching processor and model
393
+ processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
394
+ model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")
395
+
396
+ # Ensure inputs are on same device
397
+ inputs = processor(
398
+ text=["prompt"],
399
+ padding=True,
400
+ return_tensors="pt"
401
+ ).to("cuda")
402
+
403
+ # Check processor configuration
404
+ print(processor.tokenizer)
405
+ print(processor.feature_extractor)
406
+ ```
407
+
408
+ ### Generation parameter errors
409
+
410
+ **Error**: Invalid generation parameters
411
+
412
+ **Solutions**:
413
+ ```python
414
+ # HuggingFace uses different parameter names
415
+ audio_values = model.generate(
416
+ **inputs,
417
+ do_sample=True, # Enable sampling
418
+ guidance_scale=3.0, # CFG (not cfg_coef)
419
+ max_new_tokens=256, # Token limit (not duration)
420
+ temperature=1.0
421
+ )
422
+
423
+ # Calculate tokens from duration
424
+ # ~50 tokens per second
425
+ duration_seconds = 10
426
+ max_tokens = duration_seconds * 50
427
+ audio_values = model.generate(**inputs, max_new_tokens=max_tokens)
428
+ ```
429
+
430
+ ## Performance Issues
431
+
432
+ ### Slow generation
433
+
434
+ **Problem**: Generation takes too long
435
+
436
+ **Solutions**:
437
+ ```python
438
+ # Use smaller model
439
+ model = MusicGen.get_pretrained('facebook/musicgen-small')
440
+
441
+ # Reduce duration
442
+ model.set_generation_params(duration=10)
443
+
444
+ # Use GPU
445
+ model.to("cuda")
446
+
447
+ # Enable flash attention if available
448
+ # (requires compatible hardware)
449
+
450
+ # Batch multiple prompts
451
+ prompts = ["prompt1", "prompt2", "prompt3"]
452
+ wav = model.generate(prompts) # Single batch is faster than loop
453
+
454
+ # Use compile (PyTorch 2.0+)
455
+ model.lm = torch.compile(model.lm)
456
+ ```
457
+
458
+ ### CPU fallback
459
+
460
+ **Problem**: Generation running on CPU instead of GPU
461
+
462
+ **Solutions**:
463
+ ```python
464
+ import torch
465
+
466
+ # Check CUDA availability
467
+ print(f"CUDA available: {torch.cuda.is_available()}")
468
+ print(f"CUDA device: {torch.cuda.get_device_name(0)}")
469
+
470
+ # Explicitly move to GPU
471
+ model = MusicGen.get_pretrained('facebook/musicgen-small')
472
+ model.to("cuda")
473
+
474
+ # Verify model device
475
+ print(f"Model device: {next(model.lm.parameters()).device}")
476
+ ```
477
+
478
+ ## Common Error Messages
479
+
480
+ | Error | Cause | Solution |
481
+ |-------|-------|----------|
482
+ | `CUDA out of memory` | Model too large | Use smaller model, reduce duration |
483
+ | `ffmpeg not found` | FFmpeg not installed | Install FFmpeg |
484
+ | `No module named 'audiocraft'` | Not installed | `pip install audiocraft` |
485
+ | `RuntimeError: Expected 3D tensor` | Wrong input shape | Check tensor dimensions |
486
+ | `KeyError: 'melody'` | Wrong model for melody | Use musicgen-melody |
487
+ | `Sample rate mismatch` | Wrong audio format | Resample to model rate |
488
+
489
+ ## Getting Help
490
+
491
+ 1. **GitHub Issues**: https://github.com/facebookresearch/audiocraft/issues
492
+ 2. **HuggingFace Forums**: https://discuss.huggingface.co
493
+ 3. **Paper**: https://arxiv.org/abs/2306.05284
494
+
495
+ ### Reporting Issues
496
+
497
+ Include:
498
+ - Python version
499
+ - PyTorch version
500
+ - CUDA version
501
+ - AudioCraft version: `pip show audiocraft`
502
+ - Full error traceback
503
+ - Minimal reproducible code
504
+ - Hardware (GPU model, VRAM)
skills/.archive/baoyu-article-illustrator/PORT_NOTES.md ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Port Notes — baoyu-article-illustrator
2
+
3
+ Ported from [JimLiu/baoyu-skills](https://github.com/JimLiu/baoyu-skills) v1.57.0.
4
+
5
+ ## Changes from upstream
6
+
7
+ `SKILL.md`, `references/workflow.md`, `references/usage.md`, `references/style-presets.md`, `references/styles.md`, `references/prompt-construction.md`, and `prompts/system.md` were adapted. The 23 style files and 4 palette files are verbatim copies. The `references/config/` directory was removed entirely.
8
+
9
+ ### Adaptations
10
+
11
+ | Change | Upstream | Hermes |
12
+ |--------|----------|--------|
13
+ | Metadata namespace | `openclaw` | `hermes` |
14
+ | Trigger | `/baoyu-article-illustrator` slash command + CLI flags | Natural language skill matching |
15
+ | User config | EXTEND.md (project/user/XDG paths) + first-time-setup | Removed — not part of Hermes infra |
16
+ | User prompts | `AskUserQuestion` (batched, multi-question) | `clarify` tool (one question at a time) |
17
+ | Image generation | `baoyu-imagine` (Bun/TypeScript, multi-provider, accepts `--ref`, writes to local path) | `image_generate` (returns URL only; agent downloads via `terminal`/`curl`) |
18
+ | Backend selection | User picks provider via CLI flags | Not agent-selectable — `image_generate` uses the user-configured FAL model. Removed hardcoded "nano banana pro" line from `prompts/system.md`. |
19
+ | Reference images | Passed to backend via `--ref`, copied via shell | `vision_analyze` extracts a textual description (binary never touched by `write_file`/`read_file`); description is embedded in prompts. Optional `terminal cp` for a local record. |
20
+ | Platform support | Linux/macOS/Windows/WSL/PowerShell | Linux/macOS only |
21
+ | File operations | Bash commands | Hermes file tools: `write_file`/`read_file` for text, `terminal` for binaries and URL downloads, `vision_analyze` for reading images |
22
+ | Watermark | Driven by EXTEND.md `watermark.enabled` | Optional — user asks for it per-article |
23
+ | Output directory | EXTEND.md `default_output_dir` (imgs-subdir / same-dir / illustrations-subdir / independent) | Defaults based on input type; user overrides in request |
24
+
25
+ ### What was preserved
26
+
27
+ - Type × Style × Palette three-dimension framework
28
+ - All style definitions (23 files, verbatim)
29
+ - All palette definitions (4 files, verbatim)
30
+ - Core reference files (workflow, prompt-construction, styles, style-presets) — adapted for Hermes tooling
31
+ - Core principles and workflow structure (analyze → confirm → outline → prompts → generate)
32
+ - Prompt-file-as-reproducibility-record discipline
33
+ - Author, version, homepage attribution
34
+
35
+ ## Syncing with upstream
36
+
37
+ To pull upstream updates:
38
+
39
+ ```bash
40
+ # Compare versions
41
+ curl -sL https://raw.githubusercontent.com/JimLiu/baoyu-skills/main/skills/baoyu-article-illustrator/SKILL.md | head -5
42
+ # Look for version: line
43
+
44
+ # Diff style/palette files (safe to overwrite — unchanged from upstream)
45
+ diff <(curl -sL https://raw.githubusercontent.com/JimLiu/baoyu-skills/main/skills/baoyu-article-illustrator/references/styles/blueprint.md) references/styles/blueprint.md
46
+ ```
47
+
48
+ `references/styles/*` and `references/palettes/*` can be overwritten directly. `SKILL.md`, `references/workflow.md`, `references/usage.md`, `references/style-presets.md`, `references/styles.md`, `references/prompt-construction.md`, and `prompts/system.md` must be manually merged since they contain Hermes-specific adaptations (tool wiring, backend neutrality, removed EXTEND.md references).
skills/.archive/baoyu-article-illustrator/SKILL.md ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: baoyu-article-illustrator
3
+ description: "Article illustrations: type × style × palette consistency."
4
+ version: 1.57.0
5
+ author: 宝玉 (JimLiu)
6
+ license: MIT
7
+ platforms: [linux, macos, windows]
8
+ metadata:
9
+ hermes:
10
+ tags: [article-illustration, creative, image-generation]
11
+ category: creative
12
+ homepage: https://github.com/JimLiu/baoyu-skills#baoyu-article-illustrator
13
+ ---
14
+
15
+ # Article Illustrator
16
+
17
+ Adapted from [baoyu-article-illustrator](https://github.com/JimLiu/baoyu-skills) for Hermes Agent's tool ecosystem.
18
+
19
+ Analyze articles, identify illustration positions, generate images with **Type × Style × Palette** consistency.
20
+
21
+ ## When to Use
22
+
23
+ Trigger this skill when the user asks to illustrate an article, add images to an article, generate illustrations for content, or uses phrases like "为文章配图", "illustrate article", or "add images". The user provides an article (file path or pasted content) and optionally specifies type, style, palette, or density.
24
+
25
+ ## Three Dimensions
26
+
27
+ | Dimension | Controls | Examples |
28
+ |-----------|----------|----------|
29
+ | **Type** | Information structure | infographic, scene, flowchart, comparison, framework, timeline |
30
+ | **Style** | Rendering approach | notion, warm, minimal, blueprint, watercolor, elegant |
31
+ | **Palette** | Color scheme (optional) | macaron, warm, neon — overrides style's default colors |
32
+
33
+ Combine freely: `type=infographic, style=vector-illustration, palette=macaron`.
34
+
35
+ Or use presets: `edu-visual` → type + style + palette in one shot. See [style-presets.md](references/style-presets.md).
36
+
37
+ ## Types
38
+
39
+ | Type | Best For |
40
+ |------|----------|
41
+ | `infographic` | Data, metrics, technical |
42
+ | `scene` | Narratives, emotional |
43
+ | `flowchart` | Processes, workflows |
44
+ | `comparison` | Side-by-side, options |
45
+ | `framework` | Models, architecture |
46
+ | `timeline` | History, evolution |
47
+
48
+ ## Styles
49
+
50
+ See [references/styles.md](references/styles.md) for Core Styles, the full gallery, and Type × Style compatibility.
51
+
52
+ ## Output Structure
53
+
54
+ ```
55
+ {output-dir}/
56
+ ├── source-{slug}.{ext} # Only for pasted content
57
+ ├── outline.md
58
+ ├── prompts/
59
+ │ └── NN-{type}-{slug}.md
60
+ └── NN-{type}-{slug}.png
61
+ ```
62
+
63
+ **Default output directory**:
64
+
65
+ | Input | Output Directory | Markdown Insert Path |
66
+ |-------|------------------|----------------------|
67
+ | Article file path | `{article-dir}/imgs/` | `imgs/NN-{type}-{slug}.png` |
68
+ | Pasted content | `illustrations/{topic-slug}/` (cwd) | `illustrations/{topic-slug}/NN-{type}-{slug}.png` |
69
+
70
+ If the user asks for a different layout (e.g., images alongside the article, or a `illustrations/` subdirectory), honor that.
71
+
72
+ **Slug**: 2-4 words, kebab-case. **Conflict**: append `-YYYYMMDD-HHMMSS`.
73
+
74
+ ## Core Principles
75
+
76
+ - **Visualize concepts, not metaphors** — if the article uses a metaphor (e.g., "电锯切西瓜"), illustrate the underlying concept, not the literal image.
77
+ - **Labels use article data** — actual numbers, terms, and quotes from the article, not generic placeholders.
78
+ - **Prompt files are reproducibility records** — every illustration must have a saved prompt file under `prompts/` before any image is generated.
79
+ - **Strip secrets** — scan source content for API keys, tokens, or credentials before writing anything to disk.
80
+
81
+ ## Workflow
82
+
83
+ ```
84
+ - [ ] Step 1: Detect reference images (if provided)
85
+ - [ ] Step 2: Analyze content
86
+ - [ ] Step 3: Confirm settings (clarify tool, one question at a time)
87
+ - [ ] Step 4: Generate outline
88
+ - [ ] Step 5: Generate prompts
89
+ - [ ] Step 6: Generate images (image_generate)
90
+ - [ ] Step 7: Finalize
91
+ ```
92
+
93
+ ### Step 1: Detect Reference Images
94
+
95
+ If the user supplies reference images (paths pasted inline, attachments, or a URL):
96
+
97
+ 1. For each reference, call `vision_analyze` with the path/URL and a question asking for style, palette, composition, and subject. Record the returned description in `{output-dir}/references/NN-ref-{slug}.md` via `write_file`.
98
+ 2. **Do not** try to copy the binary via `write_file` / `read_file` — those are text-only. If you want a local copy for the record, use `terminal` (`cp "$src" "{output-dir}/references/NN-ref-{slug}.{ext}"`). The skill itself never needs to read the binary; it works off the vision description.
99
+ 3. Since `image_generate` doesn't take image inputs, the vision description is what gets embedded in prompts during Step 5.
100
+
101
+ Full procedures: [references/workflow.md](references/workflow.md#step-1-detect-reference-images).
102
+
103
+ ### Step 2: Analyze
104
+
105
+ | Analysis | Output |
106
+ |----------|--------|
107
+ | Content type | Technical / Tutorial / Methodology / Narrative |
108
+ | Purpose | information / visualization / imagination |
109
+ | Core arguments | 2-5 main points |
110
+ | Positions | Where illustrations add value |
111
+
112
+ Read source (file path → `read_file`, or pasted text) and write the analysis to `{output-dir}/analysis.md` using `write_file`.
113
+
114
+ Full procedures: [references/workflow.md](references/workflow.md#step-2-analyze).
115
+
116
+ ### Step 3: Confirm Settings
117
+
118
+ Use the `clarify` tool. Since `clarify` handles one question at a time, ask the most important question first. Skip any question whose answer is already present in the user's request.
119
+
120
+ | Order | Question | Options |
121
+ |-------|----------|---------|
122
+ | Q1 | **Preset or Type** | [Recommended preset], [alt preset], or manual: infographic, scene, flowchart, comparison, framework, timeline, mixed |
123
+ | Q2 | **Density** | minimal (1-2), balanced (3-5), per-section (Recommended), rich (6+) |
124
+ | Q3 | **Style** *(skip if preset chosen in Q1)* | [Recommended], minimal-flat, sci-fi, hand-drawn, editorial, scene, poster |
125
+ | Q4 | **Palette** *(optional)* | Default (style colors), macaron, warm, neon |
126
+ | Q5 | **Language** *(only if article language is ambiguous)* | article language / user language |
127
+
128
+ Don't ask more than 2-3 `clarify` questions in a row. If the user already specified these in their request, skip entirely.
129
+
130
+ Full procedures: [references/workflow.md](references/workflow.md#step-3-confirm-settings).
131
+
132
+ ### Step 4: Generate Outline → `outline.md`
133
+
134
+ Save `{output-dir}/outline.md` using `write_file` with frontmatter (type, density, style, palette, image_count) and one entry per illustration:
135
+
136
+ ```yaml
137
+ ## Illustration 1
138
+ **Position**: [section/paragraph]
139
+ **Purpose**: [why]
140
+ **Visual Content**: [what to show]
141
+ **Filename**: 01-infographic-concept-name.png
142
+ ```
143
+
144
+ Full template: [references/workflow.md](references/workflow.md#step-4-generate-outline).
145
+
146
+ ### Step 5: Generate Prompts
147
+
148
+ **BLOCKING**: Every illustration must have a saved prompt file before any image is generated — the prompt file is the reproducibility record.
149
+
150
+ For each illustration:
151
+
152
+ 1. Create a prompt file per [references/prompt-construction.md](references/prompt-construction.md).
153
+ 2. Save to `{output-dir}/prompts/NN-{type}-{slug}.md` using `write_file` with YAML frontmatter.
154
+ 3. Prompts MUST use type-specific templates with structured sections (ZONES / LABELS / COLORS / STYLE / ASPECT).
155
+ 4. LABELS MUST include article-specific data: actual numbers, terms, metrics, quotes.
156
+ 5. Process references (`direct`/`style`/`palette`) per prompt frontmatter — for `direct` usage, embed a textual description of the reference in the prompt (since `image_generate` doesn't take reference-image inputs).
157
+
158
+ ### Step 6: Generate Images
159
+
160
+ For each prompt file:
161
+
162
+ 1. Call `image_generate(prompt=..., aspect_ratio=...)`. `image_generate` returns a JSON result containing an image URL; it does NOT write to disk and does NOT accept an output path.
163
+ 2. Map the prompt's `ASPECT` to `image_generate`'s enum: `16:9` → `landscape`, `9:16` → `portrait`, `1:1` → `square`. Custom ratios → nearest named aspect.
164
+ 3. Download the returned URL to `{output-dir}/NN-{type}-{slug}.png` via `terminal` (e.g. `curl -sSL -o "{output-dir}/NN-{type}-{slug}.png" "{url}"`).
165
+ 4. On generation failure, auto-retry once.
166
+
167
+ Note: the underlying image-generation backend is user-configured (default: FAL FLUX 2 Klein 9B) and is NOT agent-selectable via `image_generate`. Do not write model names into prompts expecting them to route.
168
+
169
+ ### Step 7: Finalize
170
+
171
+ Insert `![description]({relative-path}/NN-{type}-{slug}.png)` after the corresponding paragraph. Alt text: concise description in the article's language.
172
+
173
+ Report:
174
+
175
+ ```
176
+ Article Illustration Complete!
177
+ Article: [path] | Type: [type] | Density: [level] | Style: [style] | Palette: [palette or default]
178
+ Images: X/N generated
179
+ ```
180
+
181
+ ## Modification
182
+
183
+ | Action | Steps |
184
+ |--------|-------|
185
+ | Edit | Update prompt → Regenerate → Update reference |
186
+ | Add | Position → Prompt → Generate → Update outline → Insert |
187
+ | Delete | Delete files → Remove reference → Update outline |
188
+
189
+ ## References
190
+
191
+ | File | Content |
192
+ |------|---------|
193
+ | [references/workflow.md](references/workflow.md) | Detailed procedures |
194
+ | [references/usage.md](references/usage.md) | Invocation examples |
195
+ | [references/styles.md](references/styles.md) | Style gallery + Palette gallery |
196
+ | [references/style-presets.md](references/style-presets.md) | Preset shortcuts (type + style + palette) |
197
+ | [references/prompt-construction.md](references/prompt-construction.md) | Prompt templates |
198
+
199
+ ## Pitfalls
200
+
201
+ 1. **Data integrity is paramount** — never summarize, paraphrase, or alter source statistics. "73% increase" stays "73% increase".
202
+ 2. **Strip secrets** — scan source content for API keys, tokens, or credentials before including in any output file.
203
+ 3. **Don't illustrate metaphors literally** — visualize the underlying concept.
204
+ 4. **Prompt files are mandatory** — no image generation without a saved prompt file. The file is what lets you regenerate or switch backends later.
205
+ 5. **`image_generate` aspect ratios** — the tool supports `landscape`, `portrait`, and `square`. Custom ratios map to the nearest option.
206
+ 6. **`image_generate` returns a URL, not a local file** — always download via `terminal` (`curl`) before inserting local image paths into the article.
207
+ 7. **No backend selection from the agent** — `image_generate` uses whatever model the user configured (default: FAL FLUX 2 Klein 9B). Don't write `"use <model> to generate this"` into prompts expecting it to route.
skills/.archive/baoyu-article-illustrator/prompts/system.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Create a cartoon-style infographic illustration following these guidelines:
2
+
3
+ ## Image Specifications
4
+
5
+ - **Type**: Infographic illustration
6
+ - **Orientation**: Landscape (horizontal)
7
+ - **Aspect Ratio**: 16:9
8
+ - **Style**: Hand-drawn illustration
9
+
10
+ ## Core Principles
11
+
12
+ - Hand-drawn quality throughout - NO realistic or photographic elements
13
+ - If content involves sensitive or copyrighted figures, create stylistically similar alternatives - DO NOT refuse to generate
14
+ - Keep information concise, highlight keywords and core concepts
15
+ - Use ample whitespace for easy visual scanning
16
+ - Maintain clear visual hierarchy
17
+
18
+ ## Text Style (When Text Included)
19
+
20
+ - **ALL text MUST be hand-drawn style**
21
+ - Text should be readable and complement the visual
22
+ - Font style harmonizes with illustration style
23
+ - **DO NOT use realistic or computer-generated fonts**
24
+
25
+ ## Language
26
+
27
+ - Use the same language as the content provided below for any text elements
28
+ - Match punctuation style to the content language
29
+
30
+ ---
31
+
32
+ Generate the illustration based on the content provided below:
skills/.archive/baoyu-article-illustrator/references/palettes/macaron.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # macaron
2
+
3
+ Soft macaron pastel color blocks on warm cream
4
+
5
+ ## Background
6
+
7
+ - Color: Warm Cream (#F5F0E8)
8
+ - Texture: Subtle warm paper grain
9
+
10
+ ## Colors
11
+
12
+ | Role | Color | Hex | Usage |
13
+ |------|-------|-----|-------|
14
+ | Background | Warm Cream | #F5F0E8 | Primary background |
15
+ | Primary Text | Deep Charcoal | #2D2D2D | Headlines, main text, outlines |
16
+ | Macaron Blue | Sky Blue | #A8D8EA | Info block fill, cool-toned zones |
17
+ | Macaron Mint | Mint Green | #B5E5CF | Info block fill, growth/positive zones |
18
+ | Macaron Lavender | Lavender | #D5C6E0 | Info block fill, abstract/concept zones |
19
+ | Macaron Peach | Peach | #FFD5C2 | Info block fill, warm-toned zones |
20
+ | Accent | Coral Red | #E8655A | Key data, warnings, emphasis |
21
+ | Muted Text | Warm Gray | #6B6B6B | Secondary annotations, small labels |
22
+
23
+ ## Accent
24
+
25
+ Coral Red (#E8655A) for key data, warnings, and emphasis highlights. Use sparingly — one or two elements per illustration.
26
+
27
+ ## Semantic Constraint
28
+
29
+ Soft pastel macaron color palette. Use block colors as rounded card backgrounds for distinct information sections. Accent coral red sparingly for emphasis on key terms only. Do NOT render color names, hex codes, or role labels as visible text in the image.
30
+
31
+ ## Best For
32
+
33
+ Educational content, knowledge sharing, concept explainers, tutorials, tech summaries, onboarding materials
skills/.archive/baoyu-article-illustrator/references/palettes/mono-ink.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mono-ink
2
+
3
+ Black ink on pure white with sparse semantic accent colors
4
+
5
+ ## Background
6
+
7
+ - Color: Pure White (#FFFFFF)
8
+ - Texture: Clean, no grain, no tint
9
+
10
+ ## Colors
11
+
12
+ | Role | Color | Hex | Usage |
13
+ |------|-------|-----|-------|
14
+ | Background | Pure White | #FFFFFF | Canvas |
15
+ | Primary | Near Black | #1A1A1A | All lines, text, figures, arrows |
16
+ | Accent (risk/emphasis) | Coral Red | #E8655A | Risk, problem, gap, key emphasis |
17
+ | Accent (positive) | Muted Teal | #5FA8A8 | Positive, solution, "after" state |
18
+ | Accent (neutral tag) | Dusty Lavender | #9B8AB5 | Neutral tags, category labels |
19
+ | Soft Fill | Pale Gray | #F0F0F0 | Subtle zone backgrounds (optional) |
20
+
21
+ ## Accent
22
+
23
+ Use black ink for all structural elements — lines, text, figures. Accent colors appear only for semantic highlighting: coral red for risks/gaps/problems, muted teal for positive/solution/after-states, dusty lavender for neutral category tags. Total colored pixels must remain under 10% of canvas. Pale gray may back a subtle zone but must never dominate.
24
+
25
+ ## Semantic Constraint
26
+
27
+ Black ink on white canvas. Accent colors for semantic highlighting only — total colored pixels under 10% of canvas. Do NOT render color names, hex codes, or role labels as visible text in the image.
28
+
29
+ ## Compatible With
30
+
31
+ - `ink-notes` (primary, default pairing)
32
+ - `minimal` (strict monochrome variation, drops the style's built-in accent)
33
+ - `sketch` (pencil + ink hybrid look)
34
+
35
+ ## Not Recommended With
36
+
37
+ - `sketch-notes` — its "no pure white backgrounds" rule conflicts
38
+ - `warm`, `elegant`, `watercolor`, `fantasy-animation` — color-heavy by design, mono-ink strips their identity
39
+
40
+ ## Best For
41
+
42
+ Professional visual notes, Before/After essays, tech manifestos, framework analogies, whiteboard-presentation explainers
skills/.archive/baoyu-article-illustrator/references/palettes/neon.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # neon
2
+
3
+ Vibrant neon colors on dark backgrounds
4
+
5
+ ## Background
6
+
7
+ - Color: Deep Purple (#2D1B4E)
8
+ - Texture: Subtle grid pattern or solid dark
9
+
10
+ ## Colors
11
+
12
+ | Role | Color | Hex | Usage |
13
+ |------|-------|-----|-------|
14
+ | Background | Deep Purple | #2D1B4E | Primary background |
15
+ | Alt Background | Dark Teal | #0F4C5C | Alternative sections |
16
+ | Primary | Hot Pink | #FF1493 | Main accent |
17
+ | Secondary | Electric Cyan | #00FFFF | Supporting elements |
18
+ | Tertiary | Neon Yellow | #FFFF00 | Highlights |
19
+ | Accent 1 | Lime Green | #32CD32 | Energy, success |
20
+ | Accent 2 | Orange | #FF6B35 | Warmth |
21
+ | Text | White | #FFFFFF | Text elements |
22
+
23
+ ## Accent
24
+
25
+ Hot Pink (#FF1493) for primary emphasis. High contrast neon-on-dark creates immediate visual impact.
26
+
27
+ ## Semantic Constraint
28
+
29
+ Vibrant neon-on-dark palette. High contrast, immediate visual impact. Do NOT render color names, hex codes, or role labels as visible text in the image.
30
+
31
+ ## Best For
32
+
33
+ Gaming, retro tech, 80s/90s nostalgic content, bold editorial, trend and pop culture
skills/.archive/baoyu-article-illustrator/references/palettes/warm.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # warm
2
+
3
+ Warm earth tones on soft peach, no cool colors
4
+
5
+ ## Background
6
+
7
+ - Color: Soft Peach (#FFECD2)
8
+ - Texture: Warm paper texture
9
+
10
+ ## Colors
11
+
12
+ | Role | Color | Hex | Usage |
13
+ |------|-------|-----|-------|
14
+ | Background | Soft Peach | #FFECD2 | Primary background |
15
+ | Outlines | Deep Charcoal | #2D2D2D | All element outlines |
16
+ | Primary | Warm Orange | #ED8936 | Main accent color |
17
+ | Secondary | Terracotta | #C05621 | Warm depth |
18
+ | Tertiary | Golden Yellow | #F6AD55 | Highlights, energy |
19
+ | Accent | Deep Brown | #744210 | Grounding, anchoring |
20
+ | Text | Warm Charcoal | #4A4A4A | Text elements |
21
+
22
+ ## Accent
23
+
24
+ Warm Orange (#ED8936) for primary emphasis. Warm-only palette — no cool colors (no green, blue, purple). Modern-retro feel.
25
+
26
+ ## Semantic Constraint
27
+
28
+ Warm earth tone palette. Warm-only — no cool colors (no green, blue, purple). Do NOT render color names, hex codes, or role labels as visible text in the image.
29
+
30
+ ## Best For
31
+
32
+ Product showcases, team introductions, feature grids, brand content, personal growth, lifestyle
skills/.archive/baoyu-article-illustrator/references/prompt-construction.md ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Prompt Construction
2
+
3
+ ## Prompt File Format
4
+
5
+ Each prompt file uses YAML frontmatter + content:
6
+
7
+ ```yaml
8
+ ---
9
+ illustration_id: 01
10
+ type: infographic
11
+ style: blueprint
12
+ references: # ⚠️ ONLY if files EXIST in references/ directory
13
+ - ref_id: 01
14
+ filename: 01-ref-diagram.png
15
+ usage: direct # direct | style | palette
16
+ ---
17
+
18
+ [Type-specific template content below...]
19
+ ```
20
+
21
+ **⚠️ CRITICAL - When to include `references` field**:
22
+
23
+ | Situation | Action |
24
+ |-----------|--------|
25
+ | Reference file saved to `references/` | Include in frontmatter ✓ |
26
+ | Style extracted verbally (no file) | DO NOT include in frontmatter, append to prompt body instead |
27
+ | File path in frontmatter but file doesn't exist | ERROR - remove references field |
28
+
29
+ **Reference Usage Types** (only when file exists):
30
+
31
+ | Usage | Description | Generation Action |
32
+ |-------|-------------|-------------------|
33
+ | `direct` | Primary visual reference | Describe the reference (composition, subject, style, palette) in prompt text — `image_generate` does not accept reference-image inputs |
34
+ | `style` | Style characteristics only | Describe style in prompt text |
35
+ | `palette` | Color palette extraction | Include colors in prompt |
36
+
37
+ **If no reference file but style/palette extracted verbally**, append directly to prompt body:
38
+ ```
39
+ COLORS (from reference):
40
+ - Primary: #E8756D coral
41
+ - Secondary: #7ECFC0 mint
42
+ ...
43
+
44
+ STYLE (from reference):
45
+ - Clean lines, minimal shadows
46
+ - Gradient backgrounds
47
+ ...
48
+ ```
49
+
50
+ ---
51
+
52
+ ## Default Composition Requirements
53
+
54
+ **Apply to ALL prompts by default**:
55
+
56
+ | Requirement | Description |
57
+ |-------------|-------------|
58
+ | **Clean composition** | Simple layouts, no visual clutter |
59
+ | **White space** | Generous margins, breathing room around elements |
60
+ | **No complex backgrounds** | Solid colors or subtle gradients only, avoid busy textures |
61
+ | **Centered or content-appropriate** | Main visual elements centered or positioned by content needs |
62
+ | **Matching graphics** | Use graphic elements that align with content theme |
63
+ | **Highlight core info** | White space draws attention to key information |
64
+
65
+ **Add to ALL prompts**:
66
+ > Clean composition with generous white space. Simple or no background. Main elements centered or positioned by content needs.
67
+
68
+ ---
69
+
70
+ ## Color Specification Rules
71
+
72
+ Colors in prompts use hex codes for **rendering guidance only** — they tell the model which colors to use, NOT what text to display.
73
+
74
+ **⚠️ CRITICAL**: Image generation models sometimes render color names and hex values as visible text labels in the image (e.g., painting "Macaron Blue #A8D8EA" as a label). This must be prevented.
75
+
76
+ **Add to ALL prompts that contain a COLORS section**:
77
+ > Color values (#hex) and color names are rendering guidance only — do NOT display color names, hex codes, or palette labels as visible text in the image.
78
+
79
+ ---
80
+
81
+ ## Character Rendering
82
+
83
+ When depicting people:
84
+
85
+ | Guideline | Description |
86
+ |-----------|-------------|
87
+ | **Style** | Simplified cartoon silhouettes or symbolic expressions |
88
+ | **Avoid** | Realistic human portrayals, detailed faces |
89
+ | **Diversity** | Varied body types when showing multiple people |
90
+ | **Emotion** | Express through posture and simple gestures |
91
+
92
+ **Add to ALL prompts with human figures**:
93
+ > Human figures: simplified stylized silhouettes or symbolic representations, not photorealistic.
94
+
95
+ ---
96
+
97
+ ## Text in Illustrations
98
+
99
+ | Element | Guideline |
100
+ |---------|-----------|
101
+ | **Size** | Large, prominent, immediately readable |
102
+ | **Style** | Handwritten fonts preferred for warmth |
103
+ | **Content** | Concise keywords and core concepts only |
104
+ | **Language** | Match article language |
105
+
106
+ **Add to prompts with text**:
107
+ > Text should be large and prominent with handwritten-style fonts. Keep minimal, focus on keywords.
108
+
109
+ ---
110
+
111
+ ## Principles
112
+
113
+ Good prompts must include:
114
+
115
+ 1. **Layout Structure First**: Describe composition, zones, flow direction
116
+ 2. **Specific Data/Labels**: Use actual numbers, terms from article
117
+ 3. **Visual Relationships**: How elements connect
118
+ 4. **Semantic Colors**: Meaning-based color choices (red=warning, green=efficient)
119
+ 5. **Style Characteristics**: Line treatment, texture, mood
120
+ 6. **Aspect Ratio**: End with ratio and complexity level
121
+
122
+ ## Type-Specific Templates
123
+
124
+ ### Infographic
125
+
126
+ ```
127
+ [Title] - Data Visualization
128
+
129
+ Layout: [grid/radial/hierarchical]
130
+
131
+ ZONES:
132
+ - Zone 1: [data point with specific values]
133
+ - Zone 2: [comparison with metrics]
134
+ - Zone 3: [summary/conclusion]
135
+
136
+ LABELS: [specific numbers, percentages, terms from article]
137
+ COLORS: [semantic color mapping]
138
+ STYLE: [style characteristics]
139
+ ASPECT: 16:9
140
+ ```
141
+
142
+ **Infographic + vector-illustration**:
143
+ ```
144
+ Flat vector illustration infographic. Clean black outlines on all elements.
145
+ COLORS: Cream background (#F5F0E6), Coral Red (#E07A5F), Mint Green (#81B29A), Mustard Yellow (#F2CC8F)
146
+ ELEMENTS: Geometric simplified icons, no gradients, playful decorative elements (dots, stars)
147
+ ```
148
+
149
+ **Infographic + vector-illustration + warm palette**:
150
+ ```
151
+ Flat vector illustration infographic. Clean black outlines on all elements.
152
+ PALETTE OVERRIDE (warm): Warm-only color palette, no cool colors.
153
+ COLORS: Soft Peach background (#FFECD2), Warm Orange (#ED8936),
154
+ Terracotta (#C05621), Golden Yellow (#F6AD55), Deep Brown (#744210)
155
+ ELEMENTS: Geometric simplified icons, no gradients, rounded corners,
156
+ modular card layout, consistent icon style
157
+ ```
158
+
159
+ ### Scene
160
+
161
+ ```
162
+ [Title] - Atmospheric Scene
163
+
164
+ FOCAL POINT: [main subject]
165
+ ATMOSPHERE: [lighting, mood, environment]
166
+ MOOD: [emotion to convey]
167
+ COLOR TEMPERATURE: [warm/cool/neutral]
168
+ STYLE: [style characteristics]
169
+ ASPECT: 16:9
170
+ ```
171
+
172
+ ### Flowchart
173
+
174
+ ```
175
+ [Title] - Process Flow
176
+
177
+ Layout: [left-right/top-down/circular]
178
+
179
+ STEPS:
180
+ 1. [Step name] - [brief description]
181
+ 2. [Step name] - [brief description]
182
+ ...
183
+
184
+ CONNECTIONS: [arrow types, decision points]
185
+ STYLE: [style characteristics]
186
+ ASPECT: 16:9
187
+ ```
188
+
189
+ **Flowchart + vector-illustration**:
190
+ ```
191
+ Flat vector flowchart with bold arrows and geometric step containers.
192
+ COLORS: Cream background (#F5F0E6), steps in Coral/Mint/Mustard, black outlines
193
+ ELEMENTS: Rounded rectangles, thick arrows, simple icons per step
194
+ ```
195
+
196
+ **Flowchart + sketch-notes + macaron palette**:
197
+ ```
198
+ Hand-drawn educational flowchart on warm cream paper. Slight wobble on all lines.
199
+ PALETTE: macaron — soft pastel color blocks
200
+ COLORS: Warm Cream background (#F5F0E8), zone fills in Macaron Blue (#A8D8EA),
201
+ Lavender (#D5C6E0), Mint (#B5E5CF), Coral Red (#E8655A) for emphasis
202
+ ELEMENTS: Rounded cards with dashed/solid borders, wavy hand-drawn arrows with labels,
203
+ simple stick-figure characters, doodle decorations (stars, underlines)
204
+ STYLE: Color fills don't completely fill outlines, hand-drawn lettering, generous white space
205
+ ```
206
+
207
+ **Flowchart + ink-notes + mono-ink palette**:
208
+ ```
209
+ Professional hand-drawn visual-note flowchart on pure white. Black ink line work
210
+ with slight wobble, à la Mike Rohde sketchnoting.
211
+ PALETTE: mono-ink — black ink dominant, sparse semantic accents
212
+ COLORS: Pure White background (#FFFFFF), Near Black (#1A1A1A) for all lines,
213
+ text, and figures; Coral Red (#E8655A) only for risk/emphasis,
214
+ Muted Teal (#5FA8A8) only for positive/solution states
215
+ ELEMENTS: Left-to-right stage boxes with rounded-rect frames, wavy hand-drawn
216
+ arrows between stages, simple stick-figure characters with role
217
+ labels above (e.g., "ML Engineer", "Team Lead"), dashed-border box
218
+ for future/empty stage, small doodle icons per stage
219
+ STYLE: Hand-lettered titles (bold, oversized), handwritten stage labels and
220
+ annotations, generous white space, bottom tagline summarizing takeaway
221
+ ```
222
+
223
+ ### Comparison
224
+
225
+ ```
226
+ [Title] - Comparison View
227
+
228
+ LEFT SIDE - [Option A]:
229
+ - [Point 1]
230
+ - [Point 2]
231
+
232
+ RIGHT SIDE - [Option B]:
233
+ - [Point 1]
234
+ - [Point 2]
235
+
236
+ DIVIDER: [visual separator]
237
+ STYLE: [style characteristics]
238
+ ASPECT: 16:9
239
+ ```
240
+
241
+ **Comparison + vector-illustration**:
242
+ ```
243
+ Flat vector comparison with split layout. Clear visual separation.
244
+ COLORS: Left side Coral (#E07A5F), Right side Mint (#81B29A), cream background
245
+ ELEMENTS: Bold icons, black outlines, centered divider line
246
+ ```
247
+
248
+ **Comparison + vector-illustration + warm palette**:
249
+ ```
250
+ Flat vector comparison with split layout. Clear visual separation.
251
+ PALETTE OVERRIDE (warm): Warm-only color palette, no cool colors.
252
+ COLORS: Left side Warm Orange (#ED8936), Right side Terracotta (#C05621),
253
+ Soft Peach background (#FFECD2), Deep Brown (#744210) accents
254
+ ELEMENTS: Bold icons, black outlines, centered divider line
255
+ ```
256
+
257
+ **Comparison + ink-notes + mono-ink palette** (Before/After, Traditional vs New):
258
+ ```
259
+ Professional hand-drawn sketchnote comparison on pure white. Black ink line work
260
+ with slight wobble, à la Mike Rohde sketchnoting.
261
+ PALETTE: mono-ink — black ink dominant, sparse semantic accents
262
+ COLORS: Pure White background (#FFFFFF), Near Black (#1A1A1A) for all outlines,
263
+ text, figures, arrows; Coral Red (#E8655A) reserved for risks/gaps
264
+ (left/Before side); Muted Teal (#5FA8A8) reserved for positives
265
+ (right/After side). Color accents under 10% of canvas.
266
+ LAYOUT: Left | Right split with vertical hand-drawn divider. Hand-lettered
267
+ "Before" label (top-left) and "After" label (top-right).
268
+ LEFT SIDE: Stick figure(s) with role label above, speech bubble showing the
269
+ pain point, bulleted pain-point list in handwritten text.
270
+ RIGHT SIDE: Stick figure(s) showing the new state, bulleted improvement list,
271
+ small positive-action icons.
272
+ BRIDGE: Curved hand-drawn "mindset shift" arrow bridging left → right with
273
+ small inline label describing the shift.
274
+ BOTTOM: Single-line hand-lettered tagline summarizing the takeaway.
275
+ STYLE: Hand-lettered headings (bold, oversized), handwritten body annotations,
276
+ generous white space, no computer fonts, no gradients, no shadows.
277
+ ```
278
+
279
+ ### Framework
280
+
281
+ ```
282
+ [Title] - Conceptual Framework
283
+
284
+ STRUCTURE: [hierarchical/network/matrix]
285
+
286
+ NODES:
287
+ - [Concept 1] - [role]
288
+ - [Concept 2] - [role]
289
+
290
+ RELATIONSHIPS: [how nodes connect]
291
+ STYLE: [style characteristics]
292
+ ASPECT: 16:9
293
+ ```
294
+
295
+ **Framework + vector-illustration**:
296
+ ```
297
+ Flat vector framework diagram with geometric nodes and bold connectors.
298
+ COLORS: Cream background (#F5F0E6), nodes in Coral/Mint/Mustard/Blue, black outlines
299
+ ELEMENTS: Rounded rectangles or circles for nodes, thick connecting lines
300
+ ```
301
+
302
+ **Framework + vector-illustration + warm palette**:
303
+ ```
304
+ Flat vector framework diagram with geometric nodes and bold connectors.
305
+ PALETTE OVERRIDE (warm): Warm-only color palette, no cool colors.
306
+ COLORS: Soft Peach background (#FFECD2), nodes in Warm Orange (#ED8936),
307
+ Terracotta (#C05621), Golden Yellow (#F6AD55), black outlines
308
+ ELEMENTS: Rounded rectangles or circles for nodes, thick connecting lines
309
+ ```
310
+
311
+ **Framework + ink-notes + mono-ink palette** (command center, OS analogy):
312
+ ```
313
+ Professional hand-drawn sketchnote framework on pure white. Black ink line work
314
+ with slight wobble, à la Mike Rohde sketchnoting.
315
+ PALETTE: mono-ink — black ink dominant, sparse semantic accents
316
+ COLORS: Pure White background (#FFFFFF), Near Black (#1A1A1A) for all lines,
317
+ text, figures; Dusty Lavender (#9B8AB5) for neutral category tags only;
318
+ Coral Red (#E8655A) for emphasis sparingly. Color accents under 10%.
319
+ STRUCTURE: Central rounded-rectangle frame as "the system" with hand-lettered
320
+ title inside. Inner layer of labeled sub-components (node labels
321
+ above each). Outer layer of feeder arrows from stick-figure
322
+ operators/users with role labels.
323
+ ELEMENTS: Stick figures at the edges with role tags ("Team Lead", "Operator"),
324
+ wavy hand-drawn connector arrows with small inline labels, small
325
+ doodle icons per component, dashed-border placeholder(s) for
326
+ future/empty capabilities.
327
+ BOTTOM: Single-line hand-lettered tagline.
328
+ STYLE: Hand-lettered headings, handwritten annotations, generous white space,
329
+ no computer fonts, no gradients.
330
+ ```
331
+
332
+ ### Timeline
333
+
334
+ ```
335
+ [Title] - Chronological View
336
+
337
+ DIRECTION: [horizontal/vertical]
338
+
339
+ EVENTS:
340
+ - [Date/Period 1]: [milestone]
341
+ - [Date/Period 2]: [milestone]
342
+
343
+ MARKERS: [visual indicators]
344
+ STYLE: [style characteristics]
345
+ ASPECT: 16:9
346
+ ```
347
+
348
+ ### Screen-Print Style Override
349
+
350
+ When `style: screen-print`, replace standard style instructions with:
351
+
352
+ ```
353
+ Screen print / silkscreen poster art. Flat color blocks, NO gradients.
354
+ COLORS: 2-5 colors maximum. [Choose from style palette or duotone pair]
355
+ TEXTURE: Halftone dot patterns, slight color layer misregistration, paper grain
356
+ COMPOSITION: Bold silhouettes, geometric framing, negative space as storytelling element
357
+ FIGURES: Silhouettes only, no detailed faces, stencil-cut edges
358
+ TYPOGRAPHY: Bold condensed sans-serif integrated into composition (not overlaid)
359
+ ```
360
+
361
+ **Scene + screen-print**:
362
+ ```
363
+ Conceptual poster scene. Single symbolic focal point, NOT literal illustration.
364
+ COLORS: Duotone pair (e.g., Burnt Orange #E8751A + Deep Teal #0A6E6E) on Off-Black #121212
365
+ COMPOSITION: Centered silhouette or geometric frame, 60%+ negative space
366
+ TEXTURE: Halftone dots, paper grain, slight print misregistration
367
+ ```
368
+
369
+ **Comparison + screen-print**:
370
+ ```
371
+ Split poster composition. Each side dominated by one color from duotone pair.
372
+ LEFT: [Color A] side with silhouette/icon for [Option A]
373
+ RIGHT: [Color B] side with silhouette/icon for [Option B]
374
+ DIVIDER: Geometric shape or negative space boundary
375
+ TEXTURE: Halftone transitions between sides
376
+ ```
377
+
378
+ ---
379
+
380
+ ## Palette Override
381
+
382
+ When a palette is specified (via `--palette` or preset), it overrides the style's default colors:
383
+
384
+ 1. Read style file → get rendering rules (Visual Elements, Style Rules, line treatment)
385
+ 2. Read palette file (`palettes/<palette>.md`) → get Colors + Background
386
+ 3. Palette Colors **replace** style's default Color Palette in prompt
387
+ 4. Palette Background **replaces** style's Background color (keep style's texture description)
388
+ 5. Build prompt: style rendering instructions + palette colors
389
+
390
+ **Prompt frontmatter** includes palette when specified:
391
+ ```yaml
392
+ ---
393
+ illustration_id: 01
394
+ type: infographic
395
+ style: vector-illustration
396
+ palette: macaron
397
+ ---
398
+ ```
399
+
400
+ **Example**: `vector-illustration` + `macaron` palette:
401
+ ```
402
+ Flat vector illustration infographic. Clean black outlines on all elements.
403
+ PALETTE: macaron — soft pastel color blocks
404
+ COLORS: Warm Cream background (#F5F0E8), Macaron Blue (#A8D8EA), Mint (#B5E5CF),
405
+ Lavender (#D5C6E0), Peach (#FFD5C2), Coral Red (#E8655A) for emphasis
406
+ ELEMENTS: Geometric simplified icons, no gradients, playful decorative elements
407
+ ```
408
+
409
+ When no palette is specified, use the style's built-in Color Palette as before.
410
+
411
+ ---
412
+
413
+ ## What to Avoid
414
+
415
+ - Vague descriptions ("a nice image")
416
+ - Literal metaphor illustrations
417
+ - Missing concrete labels/annotations
418
+ - Generic decorative elements
419
+
420
+ ## Watermark Integration (optional)
421
+
422
+ If the user asks for a watermark, append:
423
+
424
+ ```
425
+ Include a subtle watermark "[content]" positioned at [position].
426
+ ```
skills/.archive/baoyu-article-illustrator/references/style-presets.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Style Presets
2
+
3
+ A preset expands to a type + style + optional palette combination. Users can override any dimension in their request.
4
+
5
+ ## By Category
6
+
7
+ ### Technical & Engineering
8
+
9
+ | Preset | Type | Style | Palette | Best For |
10
+ |----------|------|-------|---------|----------|
11
+ | `tech-explainer` | `infographic` | `blueprint` | — | API docs, system metrics, technical deep-dives |
12
+ | `system-design` | `framework` | `blueprint` | — | Architecture diagrams, system design |
13
+ | `architecture` | `framework` | `vector-illustration` | — | Component relationships, module structure |
14
+ | `science-paper` | `infographic` | `scientific` | — | Research findings, lab results, academic |
15
+
16
+ ### Knowledge & Education
17
+
18
+ | Preset | Type | Style | Palette | Best For |
19
+ |----------|------|-------|---------|----------|
20
+ | `knowledge-base` | `infographic` | `vector-illustration` | — | Concept explainers, tutorials, how-to |
21
+ | `saas-guide` | `infographic` | `notion` | — | Product guides, SaaS docs, tool walkthroughs |
22
+ | `tutorial` | `flowchart` | `vector-illustration` | — | Step-by-step tutorials, setup guides |
23
+ | `process-flow` | `flowchart` | `notion` | — | Workflow documentation, onboarding flows |
24
+ | `warm-knowledge` | `infographic` | `vector-illustration` | `warm` | Product showcases, team intros, feature cards, brand content |
25
+ | `edu-visual` | `infographic` | `vector-illustration` | `macaron` | Knowledge summaries, concept explainers, educational articles |
26
+ | `hand-drawn-edu` | `flowchart` | `sketch-notes` | `macaron` | Hand-drawn educational diagrams, process explainers, onboarding visuals |
27
+ | `ink-notes-compare` | `comparison` | `ink-notes` | `mono-ink` | Before/After essays, Traditional vs New, OS-style comparisons, mindset-shift narratives |
28
+ | `ink-notes-flow` | `flowchart` | `ink-notes` | `mono-ink` | Professional process explainers, workforce pipelines, hand-drawn technical walkthroughs |
29
+ | `ink-notes-framework` | `framework` | `ink-notes` | `mono-ink` | System analogies, command-center diagrams, architecture-as-metaphor, tech manifestos |
30
+
31
+ ### Data & Analysis
32
+
33
+ | Preset | Type | Style | Palette | Best For |
34
+ |----------|------|-------|---------|----------|
35
+ | `data-report` | `infographic` | `editorial` | — | Data journalism, metrics reports, dashboards |
36
+ | `versus` | `comparison` | `vector-illustration` | — | Tech comparisons, framework shootouts |
37
+ | `business-compare` | `comparison` | `elegant` | — | Product evaluations, strategy options |
38
+
39
+ ### Narrative & Creative
40
+
41
+ | Preset | Type | Style | Palette | Best For |
42
+ |----------|------|-------|---------|----------|
43
+ | `storytelling` | `scene` | `warm` | — | Personal essays, reflections, growth stories |
44
+ | `lifestyle` | `scene` | `watercolor` | — | Travel, wellness, lifestyle, creative |
45
+ | `history` | `timeline` | `elegant` | — | Historical overviews, milestones |
46
+ | `evolution` | `timeline` | `warm` | — | Progress narratives, growth journeys |
47
+
48
+ ### Editorial & Opinion
49
+
50
+ | Preset | Type | Style | Palette | Best For |
51
+ |----------|------|-------|---------|----------|
52
+ | `opinion-piece` | `scene` | `screen-print` | — | Op-eds, commentary, critical essays |
53
+ | `editorial-poster` | `comparison` | `screen-print` | — | Debate, contrasting viewpoints |
54
+ | `cinematic` | `scene` | `screen-print` | — | Dramatic narratives, cultural essays |
55
+
56
+ ## Content Type → Preset Recommendations
57
+
58
+ Use this table during Step 3 to recommend presets based on Step 2 content analysis:
59
+
60
+ | Content Type (Step 2) | Primary Preset | Alternatives |
61
+ |------------------------|----------------|--------------|
62
+ | Technical | `tech-explainer` | `system-design`, `architecture` |
63
+ | Tutorial | `tutorial` | `process-flow`, `knowledge-base`, `edu-visual` |
64
+ | Methodology / Framework | `system-design` | `architecture`, `process-flow` |
65
+ | Data / Metrics | `data-report` | `versus`, `tech-explainer` |
66
+ | Comparison / Review | `versus` | `business-compare`, `editorial-poster`, `ink-notes-compare` |
67
+ | Manifesto / Mindset shift / Professional visual note | `ink-notes-compare` | `ink-notes-framework`, `ink-notes-flow` |
68
+ | Narrative / Personal | `storytelling` | `lifestyle`, `evolution` |
69
+ | Opinion / Editorial | `opinion-piece` | `cinematic`, `editorial-poster` |
70
+ | Historical / Timeline | `history` | `evolution` |
71
+ | Academic / Research | `science-paper` | `tech-explainer`, `data-report` |
72
+ | SaaS / Product | `saas-guide` | `knowledge-base`, `process-flow`, `warm-knowledge` |
73
+ | Education / Knowledge | `edu-visual` | `knowledge-base`, `tutorial`, `hand-drawn-edu` |
74
+
75
+ ## Override Examples
76
+
77
+ - "use the tech-explainer preset but swap the style for notion" = infographic type with notion style
78
+ - "storytelling preset with timeline type" = timeline type with warm style
79
+
80
+ Explicit type/style/palette mentions in the user's request always override preset values.
skills/.archive/baoyu-article-illustrator/references/styles.md ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Style Reference
2
+
3
+ ## Core Styles
4
+
5
+ Simplified style tier for quick selection:
6
+
7
+ | Core Style | Maps To | Best For |
8
+ |------------|---------|----------|
9
+ | `vector` | vector-illustration | Knowledge articles, tutorials, tech content |
10
+ | `minimal-flat` | notion | General, knowledge sharing, SaaS |
11
+ | `sci-fi` | blueprint | AI, frontier tech, system design |
12
+ | `hand-drawn` | sketch/warm | Relaxed, reflective, casual content |
13
+ | `editorial` | editorial | Processes, data, journalism |
14
+ | `scene` | warm/watercolor | Narratives, emotional, lifestyle |
15
+ | `poster` | screen-print | Opinion, editorial, cultural, cinematic |
16
+
17
+ Use Core Styles for most cases. See full Style Gallery below for granular control.
18
+
19
+ ---
20
+
21
+ ## Style Gallery
22
+
23
+ | Style | Description | Best For |
24
+ |-------|-------------|----------|
25
+ | `vector-illustration` | Clean flat vector art with bold shapes | Knowledge articles, tutorials, tech content |
26
+ | `notion` | Minimalist hand-drawn line art | Knowledge sharing, SaaS, productivity |
27
+ | `elegant` | Refined, sophisticated | Business, thought leadership |
28
+ | `warm` | Friendly, approachable | Personal growth, lifestyle, education |
29
+ | `minimal` | Ultra-clean, zen-like | Philosophy, minimalism, core concepts |
30
+ | `blueprint` | Technical schematics | Architecture, system design, engineering |
31
+ | `watercolor` | Soft artistic with natural warmth | Lifestyle, travel, creative |
32
+ | `editorial` | Magazine-style infographic | Tech explainers, journalism |
33
+ | `scientific` | Academic precise diagrams | Biology, chemistry, technical research |
34
+ | `chalkboard` | Classroom chalk drawing style | Education, teaching, explanations |
35
+ | `fantasy-animation` | Ghibli/Disney-inspired hand-drawn | Storybook, magical, emotional |
36
+ | `flat` | Modern bold geometric shapes | Modern digital, contemporary |
37
+ | `flat-doodle` | Cute flat with bold outlines | Cute, friendly, approachable |
38
+ | `intuition-machine` | Technical briefing with aged paper | Technical briefings, academic |
39
+ | `nature` | Organic earthy illustration | Environmental, wellness |
40
+ | `pixel-art` | Retro 8-bit gaming aesthetic | Gaming, retro tech |
41
+ | `playful` | Whimsical pastel doodles | Fun, casual, educational |
42
+ | `retro` | 80s/90s neon geometric | 80s/90s nostalgic, bold |
43
+ | `sketch` | Raw pencil notebook style | Brainstorming, creative exploration |
44
+ | `screen-print` | Bold poster art, halftone textures, limited colors | Opinion, editorial, cultural, cinematic |
45
+ | `sketch-notes` | Soft hand-drawn warm notes | Educational, warm notes |
46
+ | `ink-notes` | Black ink on pure white, sparse semantic accents, hand-lettered (à la Mike Rohde's sketchnoting) | Before/After essays, tech manifestos, framework analogies |
47
+ | `vintage` | Aged parchment historical | Historical, heritage |
48
+
49
+ Full specifications: `references/styles/<style>.md`
50
+
51
+ ## Type × Style Compatibility Matrix
52
+
53
+ | | vector-illustration | notion | warm | minimal | blueprint | watercolor | elegant | editorial | scientific | screen-print |
54
+ |---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
55
+ | infographic | ✓✓ | ✓✓ | ✓ | ✓✓ | ✓✓ | ✓ | ✓✓ | ✓✓ | ✓✓ | ✓ |
56
+ | scene | ✓ | ✓ | ✓✓ | ✓ | ✗ | ✓✓ | ✓ | ✓ | ✗ | ✓✓ |
57
+ | flowchart | ✓✓ | ✓✓ | ✓ | ✓ | ✓✓ | ✗ | ✓ | ✓✓ | ✓ | ✗ |
58
+ | comparison | ✓✓ | ✓✓ | ✓ | ✓✓ | ✓ | ✓ | ✓✓ | ✓✓ | ✓ | ✓ |
59
+ | framework | ✓✓ | ✓✓ | ✓ | ✓✓ | ✓✓ | ✗ | ✓✓ | ✓ | ✓✓ | ✓ |
60
+ | timeline | ✓ | ✓✓ | ✓ | ✓ | ✓ | ✓✓ | ✓✓ | ✓✓ | ✓ | ✓ |
61
+
62
+ ✓✓ = highly recommended | ✓ = compatible | ✗ = not recommended
63
+
64
+ ## Auto Selection by Type
65
+
66
+ | Type | Primary Style | Secondary Styles |
67
+ |------|---------------|------------------|
68
+ | infographic | vector-illustration | notion, blueprint, editorial |
69
+ | scene | warm | watercolor, elegant |
70
+ | flowchart | vector-illustration | notion, blueprint |
71
+ | comparison | vector-illustration | notion, elegant |
72
+ | framework | blueprint | vector-illustration, notion |
73
+ | timeline | elegant | warm, editorial |
74
+
75
+ ## Auto Selection by Content Signals
76
+
77
+ | Content Signals | Recommended Type | Recommended Style |
78
+ |-----------------|------------------|-------------------|
79
+ | API, metrics, data, comparison, numbers | infographic | blueprint, vector-illustration |
80
+ | Knowledge, concept, tutorial, learning, guide | infographic | vector-illustration, notion |
81
+ | Tech, AI, programming, development, code | infographic | vector-illustration, blueprint |
82
+ | How-to, steps, workflow, process, tutorial | flowchart | vector-illustration, notion |
83
+ | Framework, model, architecture, principles | framework | blueprint, vector-illustration |
84
+ | vs, pros/cons, before/after, alternatives | comparison | vector-illustration, notion |
85
+ | Manifesto, mindset shift, workforce, OS, whiteboard, professional visual note | comparison / framework | ink-notes |
86
+ | Story, emotion, journey, experience, personal | scene | warm, watercolor |
87
+ | History, timeline, progress, evolution | timeline | elegant, warm |
88
+ | Productivity, SaaS, tool, app, software | infographic | notion, vector-illustration |
89
+ | Business, professional, strategy, corporate | framework | elegant |
90
+ | Opinion, editorial, culture, philosophy, cinematic, dramatic, poster | scene | screen-print |
91
+ | Biology, chemistry, medical, scientific | infographic | scientific |
92
+ | Explainer, journalism, magazine, investigation | infographic | editorial |
93
+
94
+ ## Style Characteristics by Type
95
+
96
+ ### infographic + vector-illustration
97
+ - Clean flat vector shapes, bold geometric forms
98
+ - Vibrant but harmonious color palette
99
+ - Clear visual hierarchy with icons and labels
100
+ - Modern, professional, highly readable
101
+ - Perfect for knowledge articles and tutorials
102
+
103
+ ### flowchart + vector-illustration
104
+ - Bold arrows and connectors
105
+ - Distinct step containers with icons
106
+ - Clean progression flow
107
+ - High contrast for readability
108
+
109
+ ### comparison + vector-illustration
110
+ - Split layout with clear visual separation
111
+ - Bold iconography for each side
112
+ - Color-coded distinctions
113
+ - Easy at-a-glance comparison
114
+
115
+ ### framework + vector-illustration
116
+ - Geometric node representations
117
+ - Clear hierarchical structure
118
+ - Bold connecting lines
119
+ - Modern system diagram aesthetic
120
+
121
+ ### infographic + blueprint
122
+ - Technical precision, schematic lines
123
+ - Grid-based layout, clear zones
124
+ - Monospace labels, data-focused
125
+ - Blue/white color scheme
126
+
127
+ ### infographic + notion
128
+ - Hand-drawn feel, approachable
129
+ - Soft icons, rounded elements
130
+ - Neutral palette, clean backgrounds
131
+ - Perfect for SaaS/productivity
132
+
133
+ ### scene + warm
134
+ - Golden hour lighting, cozy atmosphere
135
+ - Soft gradients, natural textures
136
+ - Inviting, personal feeling
137
+ - Great for storytelling
138
+
139
+ ### scene + watercolor
140
+ - Artistic, painterly effect
141
+ - Soft edges, color bleeding
142
+ - Dreamy, creative mood
143
+ - Best for lifestyle/travel
144
+
145
+ ### flowchart + notion
146
+ - Clear step indicators
147
+ - Simple arrow connections
148
+ - Minimal decoration
149
+ - Focus on process clarity
150
+
151
+ ### flowchart + blueprint
152
+ - Technical precision
153
+ - Detailed connection points
154
+ - Engineering aesthetic
155
+ - For complex systems
156
+
157
+ ### comparison + elegant
158
+ - Refined dividers
159
+ - Balanced typography
160
+ - Professional appearance
161
+ - Business comparisons
162
+
163
+ ### framework + blueprint
164
+ - Precise node connections
165
+ - Hierarchical clarity
166
+ - System architecture feel
167
+ - Technical frameworks
168
+
169
+ ### timeline + elegant
170
+ - Sophisticated markers
171
+ - Refined typography
172
+ - Historical gravitas
173
+ - Professional presentations
174
+
175
+ ### timeline + warm
176
+ - Friendly progression
177
+ - Organic flow
178
+ - Personal journey feel
179
+ - Growth narratives
180
+
181
+ ### scene + screen-print
182
+ - Bold silhouettes, symbolic compositions
183
+ - 2-5 flat colors with halftone textures
184
+ - Figure-ground inversion (negative space tells secondary story)
185
+ - Vintage poster aesthetic, conceptual not literal
186
+ - Great for opinion pieces and cultural commentary
187
+
188
+ ### comparison + screen-print
189
+ - Split duotone composition (one color per side)
190
+ - Bold geometric dividers
191
+ - Symbolic icons over detailed rendering
192
+ - High contrast, immediate visual impact
193
+
194
+ ### framework + screen-print
195
+ - Geometric node representations with stencil-cut edges
196
+ - Limited color coding (one color per concept level)
197
+ - Clean silhouette-based iconography
198
+ - Poster-style hierarchy with bold typography
199
+
200
+ ---
201
+
202
+ ## Palette Gallery
203
+
204
+ Palettes override a style's default colors. Combine any style with any palette (e.g. `style=vector-illustration, palette=macaron`).
205
+
206
+ | Palette | Description | Best For |
207
+ |---------|-------------|----------|
208
+ | `macaron` | Soft pastel blocks (blue, mint, lavender, peach) on warm cream | Educational, knowledge, tutorials |
209
+ | `warm` | Warm earth tones (orange, terracotta, gold) on soft peach, no cool colors | Brand, product, lifestyle |
210
+ | `neon` | Vibrant neon (pink, cyan, yellow) on dark purple | Gaming, retro, pop culture |
211
+ | `mono-ink` | Black ink on pure white with sparse semantic accents (coral red, muted teal, dusty lavender) | Professional visual notes, Before/After, manifestos |
212
+
213
+ Full specifications: `references/palettes/<palette>.md`
214
+
215
+ When no palette is specified, the style's built-in Color Palette is used.
216
+
217
+ ## Palette Override Rules
218
+
219
+ 1. Read style file → rendering rules (Visual Elements, Style Rules)
220
+ 2. Read palette file → Colors + Background
221
+ 3. Palette colors **replace** style's default Color Palette
222
+ 4. Palette Background **replaces** style's default Background color
223
+ 5. Style's texture description is preserved
224
+
skills/.archive/baoyu-article-illustrator/references/styles/blueprint.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # blueprint
2
+
3
+ Precise technical blueprint style with engineering precision
4
+
5
+ ## Design Aesthetic
6
+
7
+ Clean, structured visual metaphors using blueprints, diagrams, and schematics. Precise, analytical and aesthetically refined. Information presented in grid-based layouts with engineering precision. Technical drawing quality with professional polish.
8
+
9
+ ## Background
10
+
11
+ - Color: Blueprint Off-White (#FAF8F5)
12
+ - Texture: Subtle grid overlay, engineering paper feel
13
+
14
+ ## Color Palette
15
+
16
+ | Role | Color | Hex | Usage |
17
+ |------|-------|-----|-------|
18
+ | Background | Blueprint Paper | #FAF8F5 | Primary background |
19
+ | Grid | Light Gray | #E5E5E5 | Background grid lines |
20
+ | Primary Text | Deep Slate | #334155 | Headlines, body |
21
+ | Primary Accent | Engineering Blue | #2563EB | Key elements |
22
+ | Secondary Accent | Navy Blue | #1E3A5F | Supporting elements |
23
+ | Tertiary | Light Blue | #BFDBFE | Fills, backgrounds |
24
+ | Warning | Amber | #F59E0B | Warnings, emphasis |
25
+
26
+ ## Visual Elements
27
+
28
+ - Precise lines with consistent stroke weights
29
+ - Technical schematics and clean vector graphics
30
+ - Thin line work in technical drawing style
31
+ - Connection lines: straight or 90-degree angles only
32
+ - Data visualization with minimal charts
33
+ - Dimension lines and measurement indicators
34
+ - Cross-section style diagrams
35
+ - Isometric or orthographic projections
36
+
37
+ ## Style Rules
38
+
39
+ ### Do
40
+
41
+ - Maintain consistent line weights
42
+ - Use grid alignment for all elements
43
+ - Keep color palette restrained
44
+ - Create clear visual hierarchy through scale
45
+ - Use geometric precision for all shapes
46
+
47
+ ### Don't
48
+
49
+ - Use hand-drawn or organic shapes
50
+ - Add decorative flourishes
51
+ - Use curved connection lines
52
+ - Include photographic elements
53
+ - Add unnecessary embellishments
54
+
55
+ ## Best For
56
+
57
+ Technical architecture, system design, data analysis, engineering documentation, process flows, infrastructure articles
skills/.archive/baoyu-article-illustrator/references/styles/chalkboard.md ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # chalkboard
2
+
3
+ Black chalkboard background with colorful chalk drawing style
4
+
5
+ ## Design Aesthetic
6
+
7
+ Classic classroom chalkboard aesthetic with hand-drawn chalk illustrations. Nostalgic educational feel with imperfect, sketchy lines that capture the warmth of traditional teaching. Colorful chalk creates visual hierarchy while maintaining the authentic chalkboard experience.
8
+
9
+ ## Background
10
+
11
+ - Color: Chalkboard Black (#1A1A1A) or Dark Green-Black (#1C2B1C)
12
+ - Texture: Realistic chalkboard texture with subtle scratches, dust particles, and faint eraser marks
13
+
14
+ ## Typography
15
+
16
+ Hand-drawn chalk lettering style with visible chalk texture. Imperfect baseline adds authenticity. White or bright colored chalk for emphasis.
17
+
18
+ ## Color Palette
19
+
20
+ | Role | Color | Hex | Usage |
21
+ |------|-------|-----|-------|
22
+ | Background | Chalkboard Black | #1A1A1A | Primary background |
23
+ | Alt Background | Green-Black | #1C2B1C | Traditional green board |
24
+ | Primary Text | Chalk White | #F5F5F5 | Main text, outlines |
25
+ | Accent 1 | Chalk Yellow | #FFE566 | Highlights, emphasis |
26
+ | Accent 2 | Chalk Pink | #FF9999 | Secondary highlights |
27
+ | Accent 3 | Chalk Blue | #66B3FF | Diagrams, links |
28
+ | Accent 4 | Chalk Green | #90EE90 | Success, nature |
29
+ | Accent 5 | Chalk Orange | #FFB366 | Warnings, energy |
30
+
31
+ ## Visual Elements
32
+
33
+ - Hand-drawn chalk illustrations with sketchy, imperfect lines
34
+ - Chalk dust effects around text and key elements
35
+ - Doodles: stars, arrows, underlines, circles, checkmarks
36
+ - Mathematical formulas and simple diagrams
37
+ - Eraser smudges and chalk residue textures
38
+ - Wooden frame border optional
39
+ - Stick figures and simple icons
40
+ - Connection lines with hand-drawn feel
41
+
42
+ ## Style Rules
43
+
44
+ ### Do
45
+
46
+ - Maintain authentic chalk texture on all elements
47
+ - Use imperfect, hand-drawn quality throughout
48
+ - Add subtle chalk dust and smudge effects
49
+ - Create visual hierarchy with color variety
50
+ - Include playful doodles and annotations
51
+
52
+ ### Don't
53
+
54
+ - Use perfect geometric shapes
55
+ - Create clean digital-looking lines
56
+ - Add photorealistic elements
57
+ - Use gradients or glossy effects
58
+ - Make it look computerized
59
+
60
+ ## Best For
61
+
62
+ Educational articles, tutorials, teaching content, workshops, informal learning, knowledge sharing, how-to guides, classroom-style explanations
skills/.archive/baoyu-article-illustrator/references/styles/editorial.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # editorial
2
+
3
+ Magazine-style editorial infographic for professional content
4
+
5
+ ## Design Aesthetic
6
+
7
+ High-quality magazine explainer aesthetic. Clear visual storytelling with structured layouts and professional typography. Think Wired, The Verge, or quality science publications. Complex information made digestible.
8
+
9
+ ## Background
10
+
11
+ - Color: Pure White (#FFFFFF) or Light Gray (#F8F9FA)
12
+ - Texture: None or subtle paper grain
13
+
14
+ ## Color Palette
15
+
16
+ | Role | Color | Hex | Usage |
17
+ |------|-------|-----|-------|
18
+ | Background | Pure White | #FFFFFF | Primary background |
19
+ | Alt Background | Light Gray | #F8F9FA | Section backgrounds |
20
+ | Primary Text | Near Black | #1A1A1A | Headlines, body |
21
+ | Secondary Text | Dark Gray | #4A5568 | Captions |
22
+ | Accent 1 | Editorial Blue | #2563EB | Primary accent |
23
+ | Accent 2 | Coral | #F97316 | Secondary accent |
24
+ | Accent 3 | Emerald | #10B981 | Positive elements |
25
+ | Accent 4 | Amber | #F59E0B | Attention points |
26
+ | Dividers | Medium Gray | #D1D5DB | Section dividers |
27
+
28
+ ## Visual Elements
29
+
30
+ - Clean flat illustrations
31
+ - Structured multi-section layouts
32
+ - Callout boxes for insights
33
+ - Icon-based visualizations
34
+ - Visual metaphors for concepts
35
+ - Flow diagrams with hierarchy
36
+ - Pull quotes and highlights
37
+ - Clear section dividers
38
+
39
+ ## Style Rules
40
+
41
+ ### Do
42
+
43
+ - Create clear narrative flow
44
+ - Use structured layouts
45
+ - Include callout boxes
46
+ - Design visual metaphors
47
+ - Maintain magazine polish
48
+
49
+ ### Don't
50
+
51
+ - Use photographic imagery
52
+ - Create cluttered layouts
53
+ - Mix too many styles
54
+ - Add purposeless decoration
55
+ - Compromise clarity for style
56
+
57
+ ## Best For
58
+
59
+ Technology explainers, science communication, research articles, policy analysis, investigative pieces, thought leadership, long-form journalism
skills/.archive/baoyu-article-illustrator/references/styles/elegant.md ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # elegant
2
+
3
+ Refined, sophisticated illustration style for professional content
4
+
5
+ ## Design Aesthetic
6
+
7
+ Elegant and refined visual approach with sophisticated color palette. Professional polish with subtle artistic touches. Emphasizes clarity and thoughtful composition. Conveys authority and trustworthiness without being cold or clinical.
8
+
9
+ ## Background
10
+
11
+ - Color: Warm Cream (#F5F0E6) or Soft Beige (#FAF6F0)
12
+ - Texture: Subtle paper texture, very light grain
13
+
14
+ ## Color Palette
15
+
16
+ | Role | Color | Hex | Usage |
17
+ |------|-------|-----|-------|
18
+ | Background | Warm Cream | #F5F0E6 | Primary background |
19
+ | Primary | Soft Coral | #E8A598 | Main accent color |
20
+ | Secondary | Muted Teal | #5B8A8A | Supporting elements |
21
+ | Tertiary | Dusty Rose | #D4A5A5 | Subtle highlights |
22
+ | Accent | Gold | #C9A962 | Premium touches |
23
+ | Alt Accent | Copper | #B87333 | Warm metallic notes |
24
+ | Text | Charcoal | #3D3D3D | Text and outlines |
25
+
26
+ ## Visual Elements
27
+
28
+ - Delicate line work with refined strokes
29
+ - Subtle icons with balanced weight
30
+ - Graceful curves and flowing compositions
31
+ - Soft gradients with smooth transitions
32
+ - Balanced whitespace and breathing room
33
+ - Thin borders and elegant dividers
34
+ - Subtle drop shadows for depth
35
+
36
+ ## Style Rules
37
+
38
+ ### Do
39
+
40
+ - Use refined color combinations
41
+ - Create balanced, harmonious compositions
42
+ - Keep elements light and airy
43
+ - Use subtle gradients sparingly
44
+ - Maintain generous margins
45
+
46
+ ### Don't
47
+
48
+ - Use harsh contrasts
49
+ - Overcrowd the composition
50
+ - Add playful or casual elements
51
+ - Use neon or overly bright colors
52
+ - Create busy or cluttered layouts
53
+
54
+ ## Best For
55
+
56
+ Professional articles, thought leadership pieces, business topics, executive communications, corporate blogs, strategy discussions, industry analysis
skills/.archive/baoyu-article-illustrator/references/styles/fantasy-animation.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fantasy-animation
2
+
3
+ Whimsical hand-drawn animation style inspired by Ghibli/Disney
4
+
5
+ ## Design Aesthetic
6
+
7
+ Charming hand-drawn animation aesthetic reminiscent of classic Disney, Studio Ghibli, or European storybook illustration. Soft, painterly textures with warm, inviting colors. Friendly characters, magical elements, and storybook feel. Enchanting, nostalgic, and emotionally engaging.
8
+
9
+ ## Background
10
+
11
+ - Color: Soft Sky Blue (#E8F4FC) or Warm Cream (#FFF8E7)
12
+ - Texture: Subtle watercolor wash, soft brush strokes
13
+
14
+ ## Color Palette
15
+
16
+ | Role | Color | Hex | Usage |
17
+ |------|-------|-----|-------|
18
+ | Background | Soft Sky Blue | #E8F4FC | Primary background |
19
+ | Alt Background | Warm Cream | #FFF8E7 | Secondary areas |
20
+ | Primary Text | Deep Forest | #2D5A3D | Headlines |
21
+ | Body Text | Warm Brown | #5D4E37 | Content |
22
+ | Accent 1 | Golden Yellow | #F4D03F | Magic, highlights |
23
+ | Accent 2 | Rose Pink | #E8A0BF | Warmth, charm |
24
+ | Accent 3 | Sage Green | #87A96B | Nature elements |
25
+ | Accent 4 | Sky Blue | #7EC8E3 | Air, water, dreams |
26
+ | Accent 5 | Coral | #F08080 | Emphasis, life |
27
+
28
+ ## Visual Elements
29
+
30
+ - Central illustrated character (friendly, expressive)
31
+ - Small companion creatures (animals, magical beings)
32
+ - Storybook-style environment backgrounds
33
+ - Magical floating objects (books, orbs, sparkles)
34
+ - Decorative elements: stars, flowers, leaves
35
+ - Soft shadows and gentle highlights
36
+ - Layered depth with foreground/background
37
+
38
+ ## Style Rules
39
+
40
+ ### Do
41
+
42
+ - Create warm, inviting compositions
43
+ - Use soft edges and painterly textures
44
+ - Include charming character illustrations
45
+ - Add magical decorative touches
46
+ - Maintain storybook narrative feel
47
+
48
+ ### Don't
49
+
50
+ - Use harsh geometric shapes
51
+ - Create dark or intimidating imagery
52
+ - Add photorealistic elements
53
+ - Use cold color palettes
54
+ - Make it look digital/computerized
55
+
56
+ ## Best For
57
+
58
+ Educational content, children's articles, storytelling, creative topics, fantasy/gaming, inspirational pieces, family-friendly content
skills/.archive/baoyu-article-illustrator/references/styles/flat-doodle.md ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flat-doodle
2
+
3
+ Cute flat doodle illustration style with bold outlines
4
+
5
+ ## Design Aesthetic
6
+
7
+ Cheerful and approachable visual style combining flat design with doodle charm. Features bold black outlines around simple shapes. Bright pastel colors with no gradients or shading. Cute rounded proportions that feel friendly. Clean white backgrounds create focus and clarity.
8
+
9
+ ## Background
10
+
11
+ - Color: Clean White (#FFFFFF)
12
+ - Texture: None - pure white isolated background
13
+
14
+ ## Color Palette
15
+
16
+ | Role | Color | Hex | Usage |
17
+ |------|-------|-----|-------|
18
+ | Background | White | #FFFFFF | Primary background |
19
+ | Primary | Pastel Pink | #FFB6C1 | Main elements |
20
+ | Secondary | Mint | #98D8C8 | Supporting elements |
21
+ | Tertiary | Lavender | #C8A2C8 | Accent elements |
22
+ | Accent 1 | Butter Yellow | #FFFACD | Highlight pop |
23
+ | Accent 2 | Sky Blue | #87CEEB | Cool accent |
24
+ | Accent 3 | Soft Coral | #F88379 | Warm accent |
25
+ | Outline | Bold Black | #000000 | All outlines |
26
+ | Text | Black | #1A1A1A | Text elements |
27
+
28
+ ## Visual Elements
29
+
30
+ - Bold black outlines around all shapes
31
+ - Simple flat color fills
32
+ - Cute rounded proportions
33
+ - Minimal geometric shapes
34
+ - Productivity icons (laptops, calendars, checkmarks)
35
+ - Isolated elements on white
36
+ - No shading or gradients
37
+ - Hand-drawn quality with clean edges
38
+
39
+ ## Style Rules
40
+
41
+ ### Do
42
+
43
+ - Use bold black outlines consistently
44
+ - Keep shapes simple and rounded
45
+ - Use bright pastel palette
46
+ - Isolate elements on white background
47
+ - Maintain cute proportions
48
+ - Keep minimal shading
49
+
50
+ ### Don't
51
+
52
+ - Add shadows or depth effects
53
+ - Use gradients or textures
54
+ - Create complex detailed illustrations
55
+ - Overlap too many elements
56
+ - Use dark or moody backgrounds
57
+ - Add realistic proportions
58
+
59
+ ## Best For
60
+
61
+ Productivity articles, SaaS and app content, workflow tutorials, beginner guides, casual business content, tool introductions, lifestyle productivity
skills/.archive/baoyu-article-illustrator/references/styles/flat.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flat
2
+
3
+ Modern flat vector illustration style for contemporary content
4
+
5
+ ## Design Aesthetic
6
+
7
+ Contemporary flat design aesthetic with bold shapes and limited depth. Clean geometric forms with no gradients or shadows. Modern, accessible, and highly readable. Optimized for digital consumption with scalable vector quality.
8
+
9
+ ## Background
10
+
11
+ - Color: White (#FFFFFF) or Soft Gray (#F5F5F5)
12
+ - Texture: None - clean solid backgrounds
13
+
14
+ ## Color Palette
15
+
16
+ | Role | Color | Hex | Usage |
17
+ |------|-------|-----|-------|
18
+ | Background | White | #FFFFFF | Primary background |
19
+ | Alt Background | Soft Gray | #F5F5F5 | Accent areas |
20
+ | Primary | Vibrant Blue | #3B82F6 | Main elements |
21
+ | Secondary | Coral | #F97316 | Supporting elements |
22
+ | Tertiary | Emerald | #10B981 | Accent elements |
23
+ | Accent 1 | Purple | #8B5CF6 | Additional accent |
24
+ | Accent 2 | Amber | #F59E0B | Highlight |
25
+ | Text | Dark Slate | #1E293B | Text elements |
26
+ | Light | Light Gray | #E5E7EB | Subtle elements |
27
+
28
+ ## Visual Elements
29
+
30
+ - Bold geometric shapes
31
+ - Flat color fills with no gradients
32
+ - Simple character illustrations
33
+ - Clean icon designs
34
+ - Minimal line work
35
+ - Overlapping shape compositions
36
+ - Abstract concept visualizations
37
+ - Consistent stroke weights
38
+
39
+ ## Style Rules
40
+
41
+ ### Do
42
+
43
+ - Use flat solid colors
44
+ - Create clean geometric shapes
45
+ - Keep elements simple
46
+ - Maintain consistent styling
47
+ - Use bold color combinations
48
+
49
+ ### Don't
50
+
51
+ - Add shadows or depth
52
+ - Use gradients or textures
53
+ - Create realistic illustrations
54
+ - Add unnecessary details
55
+ - Use photographic elements
56
+
57
+ ## Best For
58
+
59
+ Modern articles, app and product content, startup stories, digital topics, contemporary business, tech company blogs, social media content
skills/.archive/baoyu-article-illustrator/references/styles/ink-notes.md ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ink-notes
2
+
3
+ Professional black-ink visual notes on pure white, in the tradition of Mike Rohde's sketchnoting
4
+
5
+ ## Compared to sketch-notes
6
+
7
+ `ink-notes` and `sketch-notes` are distinct styles. Pick the right one:
8
+
9
+ | | `sketch-notes` | `ink-notes` |
10
+ |---|---|---|
11
+ | Background | Warm Off-White #FAF8F0 with paper grain | Pure White #FFFFFF, clean, no texture |
12
+ | Palette | Soft warm accents (orange, mustard, sage, light blue) | Black ink dominant + sparse semantic accents |
13
+ | Feel | Soft, warm, educational, approachable | Professional, structured, whiteboard-presentation |
14
+ | Best For | Friendly tutorials, onboarding, casual explainers | Before/After essays, tech manifestos, framework analogies |
15
+
16
+ When in doubt: warm & friendly → `sketch-notes`. Disciplined & professional → `ink-notes`.
17
+
18
+ ## Design Aesthetic
19
+
20
+ Disciplined hand-drawn visual note. Confident black ink line work with slight wobble, hand-lettered typography, and sparse color accents used only for semantic emphasis. Feels like a skilled visual notetaker's whiteboard presentation — clean, structured, intentionally hand-drawn rather than decorative.
21
+
22
+ ## Background
23
+
24
+ - Color: Pure White (#FFFFFF)
25
+ - Texture: Clean, no grain, no tint
26
+
27
+ ## Color Palette
28
+
29
+ | Role | Color | Hex | Usage |
30
+ |------|-------|-----|-------|
31
+ | Background | Pure White | #FFFFFF | Canvas |
32
+ | Primary Ink | Near Black | #1A1A1A | All lines, text, figures, arrows |
33
+ | Accent Warm | Coral Red | #E8655A | Risk, problem, gap, emphasis |
34
+ | Accent Cool | Muted Teal | #5FA8A8 | Positive, solution, "after" state |
35
+ | Accent Neutral | Dusty Lavender | #9B8AB5 | Neutral tags, category labels |
36
+ | Soft Fill | Pale Gray | #F0F0F0 | Subtle zone backgrounds (optional) |
37
+
38
+ Color accents must remain under 10% of canvas area and only carry semantic meaning. Black ink does the structural work.
39
+
40
+ ## Visual Elements
41
+
42
+ - Black ink line work with intentional slight wobble on all strokes
43
+ - Hand-lettered titles (bold, oversized) and handwritten body annotations
44
+ - Simple stick-figure characters with expressive poses (pointing, thinking, walking)
45
+ - Role labels above characters (e.g., "Tech Lead", "Compliance Officer")
46
+ - Thought bubbles and speech bubbles with hand-drawn outlines
47
+ - Rounded-rectangle frames for content groupings
48
+ - Dashed-border rectangles for placeholder, "coming next", or empty states
49
+ - Curvy hand-drawn arrows with small inline labels
50
+ - Vertical or horizontal dividers between comparison zones ("Before" | "After")
51
+ - "Mindset shift" curved arrow bridging two zones
52
+ - Bottom tagline: single-line hand-lettered conclusion that points the takeaway
53
+ - Stars, asterisks, underlines for emphasis — used sparingly
54
+
55
+ ## Style Rules
56
+
57
+ ### Do
58
+
59
+ - Keep background pure white with no texture or tint
60
+ - Let black ink dominate outlines, text, and figures
61
+ - Use accent colors only for semantic highlighting
62
+ - Keep all type hand-lettered — no computer-generated fonts
63
+ - Maintain confident line quality (wobble, not mess)
64
+ - Include a bottom tagline summarizing the main takeaway
65
+ - Structure content into clear zones with visible dividers
66
+ - Use dashed boxes for future, empty, or placeholder states
67
+
68
+ ### Don't
69
+
70
+ - Use warm off-white or paper-textured backgrounds (that is sketch-notes' territory)
71
+ - Fill large zones with color blocks
72
+ - Use more than 3 accent colors per image
73
+ - Use perfect geometric shapes — preserve hand-drawn wobble
74
+ - Clutter with decorative doodles; every element must carry meaning
75
+ - Use gradients, shadows, or computer-generated fonts
76
+
77
+ ## Type Compatibility
78
+
79
+ | Type | Rating | Notes |
80
+ |------|--------|-------|
81
+ | comparison | ✓✓ | Best fit — Before/After, Traditional vs New, side-by-side contrasts |
82
+ | framework | ✓✓ | OS-style command centers, layered architectures, organizational models |
83
+ | flowchart | ✓✓ | Process explainers with labeled stages, workforce pipelines |
84
+ | infographic | ✓ | Multi-zone technical summaries, manifesto-style posters |
85
+ | timeline | ✓ | Hand-drawn horizontal arrow with era markers and milestones |
86
+ | scene | ✗ | Not recommended — lacks scenic space |
87
+
88
+ ## Best For
89
+
90
+ Product and engineering essays, tech manifestos, framework introductions, Before/After narratives, OS-level comparisons, workforce and organizational analogies, visual summaries of talks, thought-leadership articles
skills/.archive/baoyu-article-illustrator/references/styles/intuition-machine.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # intuition-machine
2
+
3
+ Technical briefing infographic style with aged paper and bilingual labels
4
+
5
+ ## Design Aesthetic
6
+
7
+ Academic/technical briefing style with clean 2D or isometric technical illustrations. Information-dense but organized with clear visual hierarchy. Vintage blueprint aesthetic with modern clarity. Multiple explanatory elements with bilingual callouts.
8
+
9
+ ## Background
10
+
11
+ - Color: Aged Cream (#F5F0E6)
12
+ - Texture: Subtle paper texture with light creases, vintage technical print feel
13
+
14
+ ## Color Palette
15
+
16
+ | Role | Color | Hex | Usage |
17
+ |------|-------|-----|-------|
18
+ | Background | Aged Cream | #F5F0E6 | Primary background |
19
+ | Paper Texture | Warm White | #F5F0E1 | Blueprint effect |
20
+ | Primary Text | Dark Maroon | #5D3A3A | Headlines, titles |
21
+ | Body Text | Near Black | #1A1A1A | Content text |
22
+ | Accent 1 | Teal | #2F7373 | Primary illustrations |
23
+ | Accent 2 | Warm Brown | #8B7355 | Secondary elements |
24
+ | Accent 3 | Maroon | #722F37 | Emphasis |
25
+ | Outline | Deep Charcoal | #2D2D2D | Element outlines |
26
+
27
+ ## Visual Elements
28
+
29
+ - Isometric 3D or flat 2D technical diagrams
30
+ - Explanatory text boxes with labeled content
31
+ - Bilingual callout labels (English + Chinese)
32
+ - Faded thematic background patterns
33
+ - Clean black outlines on elements
34
+ - Split or triptych layouts
35
+ - Key insight boxes
36
+
37
+ ## Style Rules
38
+
39
+ ### Do
40
+
41
+ - Include multiple text boxes with content
42
+ - Use bilingual labels for key elements
43
+ - Add faded thematic background patterns
44
+ - Maintain aged paper texture
45
+ - Create clear visual hierarchy
46
+
47
+ ### Don't
48
+
49
+ - Create photorealistic 3D renders
50
+ - Leave illustrations without explanatory text
51
+ - Add stamps or watermarks in corners
52
+ - Use gradients or glossy effects
53
+ - Make it look too modern/digital
54
+
55
+ ## Best For
56
+
57
+ Technical explanations, concept breakdowns, academic content, research summaries, bilingual audiences, knowledge documentation
skills/.archive/baoyu-article-illustrator/references/styles/minimal.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # minimal
2
+
3
+ Ultra-clean, zen-like illustration style for focused content
4
+
5
+ ## Design Aesthetic
6
+
7
+ Maximum simplicity with purposeful restraint. Every element serves a function. Zen-like calm and focus through extensive negative space. Single focal point approach that guides attention naturally. Quiet elegance through reduction.
8
+
9
+ ## Background
10
+
11
+ - Color: Pure White (#FFFFFF) or Off-White (#FAFAFA)
12
+ - Texture: None - clean solid backgrounds
13
+
14
+ ## Color Palette
15
+
16
+ | Role | Color | Hex | Usage |
17
+ |------|-------|-----|-------|
18
+ | Background | White | #FFFFFF | Primary background |
19
+ | Alt Background | Off-White | #FAFAFA | Subtle variation |
20
+ | Primary | Pure Black | #000000 | Main elements |
21
+ | Accent | Content-Derived | varies | Single accent color |
22
+ | Text | Black | #000000 | Text elements |
23
+ | Alt Text | Medium Gray | #6B6B6B | Secondary text |
24
+
25
+ Note: Accent color is derived from content context. Use sparingly.
26
+
27
+ ## Visual Elements
28
+
29
+ - Single focal element per illustration
30
+ - Maximum negative space
31
+ - Thin, precise lines
32
+ - Simple geometric forms
33
+ - Subtle shadows if any
34
+ - Typography as primary element
35
+ - Strategic use of single accent
36
+ - Clean, uncluttered compositions
37
+
38
+ ## Style Rules
39
+
40
+ ### Do
41
+
42
+ - Embrace empty space
43
+ - Use single focal points
44
+ - Keep lines thin and precise
45
+ - Let content breathe
46
+ - Question every element
47
+
48
+ ### Don't
49
+
50
+ - Add decorative elements
51
+ - Use multiple accent colors
52
+ - Fill available space
53
+ - Add textures or patterns
54
+ - Create visual complexity
55
+
56
+ ## Best For
57
+
58
+ Philosophy articles, minimalism content, focused explanations, meditation and mindfulness, essential concepts, clarity-focused writing
skills/.archive/baoyu-article-illustrator/references/styles/nature.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # nature
2
+
3
+ Organic, earthy illustration style for environmental and wellness content
4
+
5
+ ## Design Aesthetic
6
+
7
+ Natural and organic visual approach inspired by the outdoors. Earth tones and natural textures that evoke calm and connection to nature. Flowing lines and organic shapes. Creates a sense of tranquility and environmental awareness.
8
+
9
+ ## Background
10
+
11
+ - Color: Sand Beige (#F5E6D3) or Sky Blue wash (#E0F2FE)
12
+ - Texture: Natural paper texture with organic feel
13
+
14
+ ## Color Palette
15
+
16
+ | Role | Color | Hex | Usage |
17
+ |------|-------|-----|-------|
18
+ | Background | Sand Beige | #F5E6D3 | Primary background |
19
+ | Alt Background | Sky Blue | #E0F2FE | Alternative canvas |
20
+ | Primary | Forest Green | #276749 | Main natural color |
21
+ | Secondary | Sage | #9AE6B4 | Supporting green |
22
+ | Tertiary | Earth Brown | #744210 | Grounding element |
23
+ | Accent 1 | Sunset Orange | #ED8936 | Warm accent |
24
+ | Accent 2 | Water Blue | #63B3ED | Cool accent |
25
+ | Text | Deep Brown | #5D4E3C | Text elements |
26
+
27
+ ## Visual Elements
28
+
29
+ - Leaf and plant motifs
30
+ - Tree and branch silhouettes
31
+ - Mountain and landscape shapes
32
+ - Organic flowing lines
33
+ - Natural textures (wood grain, stone)
34
+ - Water and wave patterns
35
+ - Animal silhouettes
36
+ - Sun and moon symbols
37
+
38
+ ## Style Rules
39
+
40
+ ### Do
41
+
42
+ - Use earth-inspired colors
43
+ - Create organic, flowing shapes
44
+ - Include nature elements
45
+ - Evoke outdoor atmosphere
46
+ - Maintain calm and balance
47
+
48
+ ### Don't
49
+
50
+ - Use synthetic or neon colors
51
+ - Create rigid geometric shapes
52
+ - Add tech or digital elements
53
+ - Use stark contrasts
54
+ - Overcomplicate compositions
55
+
56
+ ## Best For
57
+
58
+ Sustainability articles, wellness content, outdoor topics, slow living, environmental issues, health and fitness, gardening, travel nature pieces
skills/.archive/baoyu-article-illustrator/references/styles/notion.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # notion
2
+
3
+ Minimalist hand-drawn line art style for knowledge content (Default)
4
+
5
+ ## Design Aesthetic
6
+
7
+ Clean, minimalist hand-drawn line art with intellectual feel. Simple doodle-style illustrations with intentional wobble. Maximum whitespace with single concept focus. Notion-like aesthetic that feels thoughtful and organized.
8
+
9
+ ## Background
10
+
11
+ - Color: Pure White (#FFFFFF) or Off-White (#FAFAFA)
12
+ - Texture: None - clean solid backgrounds
13
+
14
+ ## Color Palette
15
+
16
+ | Role | Color | Hex | Usage |
17
+ |------|-------|-----|-------|
18
+ | Background | White | #FFFFFF | Primary background |
19
+ | Alt Background | Off-White | #FAFAFA | Subtle variation |
20
+ | Primary | Black | #1A1A1A | Main outlines |
21
+ | Secondary | Dark Gray | #4A4A4A | Supporting lines |
22
+ | Accent 1 | Pastel Blue | #A8D4F0 | Soft highlight |
23
+ | Accent 2 | Pastel Yellow | #F9E79F | Warm highlight |
24
+ | Accent 3 | Pastel Pink | #FADBD8 | Gentle accent |
25
+ | Text | Near Black | #1A1A1A | Text elements |
26
+
27
+ ## Visual Elements
28
+
29
+ - Simple line doodles
30
+ - Hand-drawn wobble effect
31
+ - Basic geometric shapes
32
+ - Stick figures for people
33
+ - Conceptual icons
34
+ - Clean hand-drawn lettering
35
+ - Minimal decorative elements
36
+ - Single-weight line work
37
+
38
+ ## Style Rules
39
+
40
+ ### Do
41
+
42
+ - Use maximum whitespace
43
+ - Keep illustrations simple
44
+ - Add slight hand-drawn wobble
45
+ - Focus on single concepts
46
+ - Use pastel accents sparingly
47
+
48
+ ### Don't
49
+
50
+ - Create complex illustrations
51
+ - Use many colors at once
52
+ - Add detailed textures
53
+ - Make precise geometric shapes
54
+ - Overcrowd the composition
55
+
56
+ ## Best For
57
+
58
+ Knowledge sharing, concept explanations, SaaS content, productivity articles, educational posts, how-to guides, professional blogs