Estilo Cartoon (Remotion), personagens reaproveitáveis e hashtags do TikTok
Estilo Cartoon (novo, sem Godot) - Pacote cartoon/ (Remotion 4.0.535): cada trecho é um spec JSON desenhado em React/SVG e renderizado em MP4; render em lote (empacota uma vez) e imagem parada (--still). - Cenas montadas por peças, sem cenário pronto: paletas (noite, sépia, dia, entardecer, cinza), lugar com chão, interno/externo, névoa e 24 peças posicionadas por profundidade, foco de luz e vinheta; etiquetas, onomatopeias, ondas de som, X vermelho, painel do topo e legenda palavra por palavra. - Montagem documental: "Cartoon" como estilo do vídeo e tipo de visual do trecho; plano por regras pelo texto (lugar, objetos, expressão, pose), tempos das palavras pela transcrição do áudio, "Gerar de novo" por trecho, paleta da série e elenco da história. Personagens - Aba Personagens: criar pela descrição, ajustar peça por peça com prévia ao vivo, refinar com o agente (tarefa nova "Personagem"); fichas em assets/characters/ e elenco em stories/<id>/cast.json. O mesmo personagem sai igual em qualquer cena, mudando expressão, pose e objeto na mão. TikTok - Hashtags passam a ser digitadas e confirmadas na lista de sugestões do TikTok Studio (coladas, viravam texto). Diagnóstico de alcance em doc/publicacao/TIKTOK_DIAGNOSTICO.md. Docs: estudo das referências, doc/cartoon/ (personagens e cenas) e skill cenaforge 1.46.0. Testes: painel 77/77, cartoon 5/5, Publicador 87/87. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -7,6 +7,42 @@ Versão semântica da **skill** (não do projeto):
|
|||||||
|
|
||||||
Mantido pelo subagente `cenaforge-skill-updater`. Entradas mais novas no topo.
|
Mantido pelo subagente `cenaforge-skill-updater`. Entradas mais novas no topo.
|
||||||
|
|
||||||
|
## 1.46.0 — 17/11/2026
|
||||||
|
|
||||||
|
Cartoon por peças: lugares montados pelo texto e biblioteca de personagens reaproveitados entre histórias.
|
||||||
|
- `references/cartoon.md` (novo): a seção Cartoon saiu de `panel.md` (que ficou só com ponteiro) e foi reescrita: princípio
|
||||||
|
do dono (nada de cenário pronto; personagem criado uma vez), contrato com `scene.kind "place"`, `palette`, `place`
|
||||||
|
(24 peças), `light`, ator com `character`/`expression`/`pose`/`item`; `--still` do `render.ts`; personagens
|
||||||
|
(`character.ts`, `CharacterFigure.tsx`, `assets/characters/`, `cast.json`, rotas, página `/characters`, agente `character`);
|
||||||
|
plano por `LOCATIONS`/`placeFor`, `PlanContext`, paleta da série e `replanCartoon`; tipos sem espelho (`cenaforge-cartoon/spec`);
|
||||||
|
medições e "ainda não existe" (vistas especiais, agente que escreve o spec).
|
||||||
|
- `references/gotchas.md`: 157 reescrito (lugares por peças); novos 160 (`defaultProps` vazando o exemplo), 161 (palavras-chave
|
||||||
|
do plano), 162 (`backslash-b` vira 0x08); 153 ganhou o caso do id sem acento.
|
||||||
|
- `references/tools.md`: link e contagem de testes (painel 9, cartoon 5).
|
||||||
|
- `SKILL.md`: versão, `description`, linhas "Estilo Cartoon" e "Personagem do Cartoon", resumo de armadilhas.
|
||||||
|
- Evidência: conferido no código (`cartoon/package.json` exports, `character.ts`, `places.tsx`, `spec.ts`, `Root.tsx`,
|
||||||
|
`characters.ts`, `agents.ts`, `montage.ts`, `montage-cartoon.ts`); `cd cartoon && npx tsx --test tests/*.test.ts` → 5 pass
|
||||||
|
(reexecutado). Informados, não reexecutados: painel 77/77, `tsc` dos dois pacotes, tempos de render (2,6–2,8 s por trecho
|
||||||
|
de 4 s), `/characters` e `/api/characters` 200. Não verificado: renders dos três lugares (sem `pnpm render`); `assets/characters/`
|
||||||
|
está vazio no repositório (personagens de teste apagados).
|
||||||
|
|
||||||
|
## 1.45.0 — 17/11/2026
|
||||||
|
|
||||||
|
Estilo Cartoon (Remotion) na montagem documental e hashtags do TikTok.
|
||||||
|
- `references/panel.md`: opção `cartoon` em "Estilo do vídeo" e `VISUAL_KINDS`; seção "Estilo Cartoon" (contrato
|
||||||
|
`cartoon/src/spec.ts` v1, peças, `render.ts` e suas 3 formas, plano `planCartoon`, `wordTimings`, `cartoonKey`,
|
||||||
|
integração em `montage.ts` e na UI, testes).
|
||||||
|
- `references/tools.md`: Remotion 4.0.535 e React 19.3.0 em "Em uso" com tempos medidos (exemplo 6 s em 11,8 s; 3 trechos
|
||||||
|
em 25,2 s); Chrome Headless Shell (~120 MB, `CARTOON_CHROME`); aviso de licença da Remotion.
|
||||||
|
- `references/gotchas.md`: itens 156 (síntese sem tempos por palavra), 157 (cartoon genérico), 158 (hashtag do TikTok
|
||||||
|
colada vira texto), 159 (`SlardarWAF`; receita Playwright para baixar vídeo de referência).
|
||||||
|
- `references/publishing.md`: regra da legenda do TikTok com hashtags (`caption_parts`/`type_caption`).
|
||||||
|
- `SKILL.md`: versão, `description`, linha "Estilo Cartoon" em "Onde mexer", linha da montagem e resumo de armadilhas.
|
||||||
|
- Evidência: conferido no código (`cartoon/package.json`, `spec.ts`, `render.ts`, `montage.ts`, `montage-cartoon.ts`,
|
||||||
|
`tiktok_studio.py`); Remotion 4.0.535 em `cartoon/node_modules`. Informados, não reexecutados: tempos de render,
|
||||||
|
suíte do painel, 5 testes de `cartoon/`, 3 de `test_tiktok_caption.py`. Não verificado: hashtags do TikTok com vídeo
|
||||||
|
real; licença da Remotion; versão do Chrome Headless Shell.
|
||||||
|
|
||||||
## 1.44.0 — 17/11/2026
|
## 1.44.0 — 17/11/2026
|
||||||
|
|
||||||
Ordenação da fila de cortes, "Horário específico" ao publicar corte e capa que sumia do dashboard.
|
Ordenação da fila de cortes, "Horário específico" ao publicar corte e capa que sumia do dashboard.
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,99 @@
|
|||||||
|
# Estilo Cartoon (`cartoon/`, Remotion, sem Godot)
|
||||||
|
|
||||||
|
Pacote do workspace (`pnpm-workspace.yaml`: `panel` + `cartoon`; nome `cenaforge-cartoon`). Cada trecho da montagem
|
||||||
|
documental vira um MP4 de desenho 2D com a duração do áudio. Versões e medição: [tools.md](tools.md).
|
||||||
|
|
||||||
|
**Princípio (dono, 17/11/2026): a ferramenta "sabe como faz".** Nada de cenário ou template pronto reaproveitado: cada
|
||||||
|
cena é montada **por peças** a partir do texto (parque de dia, cemitério, bunker…). **Personagens** são o contrário:
|
||||||
|
criados uma vez, na biblioteca, e reaproveitados em várias histórias. Não crie "cena pronta" nova; crie peça ou regra.
|
||||||
|
|
||||||
|
Guias do projeto (fonte de detalhe, não duplicar aqui): `doc/cartoon/cenas.md` (camadas, receitas por situação,
|
||||||
|
composição), `doc/cartoon/personagens.md` (ficha, agente), estudo de referência `doc/estudo-estilo-cartoon-explicativo.md`.
|
||||||
|
|
||||||
|
## Contrato da cena (`cartoon/src/spec.ts`, `schemaVersion` 1; `validateSpec` recusa o resto)
|
||||||
|
|
||||||
|
- `width`/`height`/`fps`/`durationS`/`seed`; `camera {push, panX}`; `hud {badge, label, clock, clockMinutesPerSecond}`;
|
||||||
|
`props` (ícone `house|generator|fuel|battery|phone|door|eye|bulb|solar|warning|money|clock`, `label`, `tone`
|
||||||
|
`info|danger|ok`, `shake`, `rings`, `crossed`); `texts` (`onomatopoeia|tag|counter|big`); `words [{text, startS, endS,
|
||||||
|
tone key|danger}]`; `card`. Posições em fração do quadro (0–1).
|
||||||
|
- `scene.kind`: `street|house|plain|blueprint|card` (cenas antigas) ou **`place`** (por peças). `palette`
|
||||||
|
(`night|sepia|day|dusk|gray`, `PALETTES` em `places.tsx`), `place`, `light` (`none|spot|vignette`).
|
||||||
|
- `place {ground grass|street|dirt|floor|sand|water|none, indoor, fog, horizon, elements[{kind, x, z, scale, flip, color}]}`;
|
||||||
|
`z` 0 = frente, 1 = fundo. 24 peças em `ELEMENTS`: tree, deadtree, pine, bush, rock, mountain, cloud, bench, lamp,
|
||||||
|
gravestone, cross, fence, house, building, car, sign, door, window, table, bed, shelf, crate, tent, fire.
|
||||||
|
Peça nova = entrada em `ELEMENTS` + desenho em `cartoon/src/places.tsx`.
|
||||||
|
- `actors`: `person` com `character {name, caption, look}`, `expression`, `pose`, `item` (objeto na mão), `flip`
|
||||||
|
(campos antigos `label`/`hair`/`glasses`/`pointing` ainda valem); `crowd` (entra antes do personagem, atrás, pés em y 0,6).
|
||||||
|
|
||||||
|
## Peças (`cartoon/src/`)
|
||||||
|
|
||||||
|
`places.tsx` (paletas, chão, peças, `LightLayer`), `scenes.tsx` (fundos antigos, espaço 1080×1920), `actors.tsx` (multidão,
|
||||||
|
pessoa antiga), `CharacterFigure.tsx` (personagem), `icons.tsx`, `overlays.tsx` (etiqueta amarela, onomatopeia com tremor,
|
||||||
|
anéis de som, X vermelho, HUD com relógio, legenda palavra por palavra em blocos de até 3), `Shot.tsx` (empurrão de
|
||||||
|
câmera), `Root.tsx` (composições `Shot` = trecho **vazio**, `Sample` = exemplo do Studio, `Character` = cartão),
|
||||||
|
`colors.ts` (cores sem Remotion; `theme.ts` só carrega fontes). Fontes Anton e Bebas Neue de `assets/fonts/`.
|
||||||
|
|
||||||
|
## Render
|
||||||
|
|
||||||
|
`tsx cartoon/render.ts --jobs <json>` (`[{spec, out}]`) | `--spec x --out y` | `--sample --out y` | **imagem parada de
|
||||||
|
personagem:** `tsx cartoon/render.ts --still --props x.json --out y.png [--frame N]`. Empacota uma vez e renderiza todos;
|
||||||
|
**última linha do stdout = JSON `{ok, results|error}`**. O 1º render baixa o Chrome Headless Shell (~120 MB);
|
||||||
|
`CARTOON_CHROME` aponta outro Chrome. Studio: `pnpm --filter cenaforge-cartoon studio`. Testes (dentro de `cartoon/`):
|
||||||
|
`npx tsx --test tests/*.test.ts`; tipos: `pnpm --filter cenaforge-cartoon typecheck`.
|
||||||
|
|
||||||
|
## Personagens (biblioteca)
|
||||||
|
|
||||||
|
- **Contrato** `cartoon/src/character.ts` (`Character`, `schemaVersion` 1): `id`, `name`, `caption`, `description`,
|
||||||
|
`kind` `cartoon|3d`, `look {build slim|average|heavy, height 0,6–1,2, skin, hair{style short|side|bun|long|curly|spiky|
|
||||||
|
bald|cap, color}, beard none|stubble|mustache|full|goatee, glasses none|round|square|sun, brows thin|thick,
|
||||||
|
top{shirt|jacket|hoodie|dress|uniform, color, accent}, bottom pants|shorts|skirt, shoes}`. `EXPRESSIONS`: neutral, happy,
|
||||||
|
sad, worried, angry, surprised, scared. `POSES`: stand, point, wave, hold, arms_up, shrug, think. `validateLook`.
|
||||||
|
- **Desenho** `CharacterFigure.tsx`: SVG puro (sem Remotion), `viewBox` 200×440, pés em (100,440); `t` anima respirar,
|
||||||
|
piscar e acenar. O painel importa o mesmo componente (prévia ao vivo): dependência `"cenaforge-cartoon": "workspace:*"` em
|
||||||
|
`panel/package.json`, `transpilePackages` em `panel/next.config.ts`, `exports` do pacote `./character`, `./figure`, `./spec`.
|
||||||
|
- **Arquivos:** `assets/characters/<id>/character.json`; elenco da história `stories/<id>/cast.json` (`{"cast":[ids]}`).
|
||||||
|
- **Painel** `panel/src/lib/characters.ts`: `listCharacters`/`getCharacter`/`saveCharacter`/`deleteCharacter` (não apaga
|
||||||
|
quem está em elenco), `describeToLook` (descrição pt-BR → `look` + `caption` por regras: idade, gênero, criança,
|
||||||
|
profissão → uniforme/cor, cabelo, barba, óculos, corpo, cor de roupa), `getCast`/`setCast`. Rotas: `GET/POST
|
||||||
|
/api/characters`, `GET/PUT/DELETE /api/characters/[id]`, `POST /api/characters/[id]/agent`, `GET/PUT
|
||||||
|
/api/stories/[storyId]/cast`. Página `/characters` (aba "Personagens"; `components/character-studio.tsx`: criar pela
|
||||||
|
descrição, prévia com expressão/pose, formulário peça por peça, "Refinar com o agente", apagar).
|
||||||
|
- **Agente:** `AgentKind` `"character"` (`types.ts`; `agents.ts`: orçamento US$ 0,5, Sonnet, Claude preferido; `prompts.ts`
|
||||||
|
manda ler SÓ `doc/cartoon/personagens.md` e gravar a ficha).
|
||||||
|
- Para testar a API com acento use Python/UTF-8 (gotchas 153); o `id` sai do nome sem acento.
|
||||||
|
|
||||||
|
## Plano no painel (`panel/src/lib/montage-cartoon.ts`, sem banco)
|
||||||
|
|
||||||
|
- Tipos vêm de `"cenaforge-cartoon/spec"` (não há mais espelho). `planCartoon(shot, ctx, variant)` com
|
||||||
|
`PlanContext {hud, cast, palette}` por regras do texto:
|
||||||
|
- **Lugar:** `LOCATIONS` por palavra (cemitério, bunker/porão, hospital/escritório, casa/quarto, parque, floresta,
|
||||||
|
acampamento, praia, sítio, rua/cidade) → `placeFor` (peças espalhadas pela semente, longe do centro; cada lugar traz
|
||||||
|
paleta/luz própria). Sem lugar reconhecido cai nas cenas antigas.
|
||||||
|
- **Personagem:** `expressionOf`/`poseOf` pelo texto; quem é citado pelo nome entra com a aparência da biblioteca; com 1
|
||||||
|
personagem só, ele aparece nos trechos pares ou quando o texto diz "ele/ela"; objeto pequeno vai para a mão (`item`).
|
||||||
|
- Ícones por palavra-chave; "pessoas/vizinhos" vira multidão; "nunca/não" + perigo risca o objeto; sons viram
|
||||||
|
onomatopeia (motor só com gerador/motor/moto/carro perto; barulho genérico = "Crec"); texto na tela numérico vira `big`,
|
||||||
|
senão etiqueta; `variant` troca arranjo e seed.
|
||||||
|
- `wordTimings` (transcreve o áudio com `detail: "words"`; sem o serviço, reparte o texto pela duração; gotchas 156).
|
||||||
|
`cartoonKey(scene, duração, audio.key)` decide se está atual. `renderCartoonShots`: specs em
|
||||||
|
`stories/<id>/cartoon/`, MP4 em `output/cartoon/<story>-<file_key>/`.
|
||||||
|
- **`lib/montage.ts`:** `VisualKind` `"cartoon"`; `ShotVisual.cartoon`/`cartoonVariant`/`cartoonKey`;
|
||||||
|
`SavedMontage.cartoonPalette` (`CARTOON_PALETTES`); `cartoonCtx(ep)` monta o contexto com o elenco da história. O
|
||||||
|
automático planeja tudo em cartoon no estilo `"cartoon"`; a etapa 3b renderiza **todos** os trechos desatualizados numa
|
||||||
|
execução; em `buildSegment` o trecho cartoon **não** recebe texto na tela nem legenda do FFmpeg (já vêm na cena). Mudar a
|
||||||
|
paleta, ou `PATCH {replanCartoon: true}`, apaga o plano dos trechos Cartoon automáticos (replanejados na próxima
|
||||||
|
geração); "Gerar de novo" troca `cartoonVariant`; `hudFor` = 2 primeiras palavras do título + "Ep. N".
|
||||||
|
- **UI** (`montage-editor.tsx`, recebe `storyId`): opção de estilo, bloco `CartoonSetup` (paleta da série + elenco por chips,
|
||||||
|
só no estilo Cartoon), botão "Cartoon" no trecho, `CartoonPreview`.
|
||||||
|
- **Testes:** `panel/src/lib/montage-cartoon.test.ts` (9).
|
||||||
|
|
||||||
|
## Medido (17/11/2026)
|
||||||
|
|
||||||
|
Mesmo personagem em parque (`day`), cemitério (`dusk` + fog + `vignette`) e bunker (`sepia` + `spot` + indoor): 3 trechos de
|
||||||
|
4 s em ~2,6–2,8 s cada. Plano com elenco "Marta" → parque de dia (acenando) e cemitério (com medo, "Crec") renderizados.
|
||||||
|
Testes: painel 77/77, cartoon 5/5; `tsc` ok nos dois (informados pelo dono; cartoon 5/5 reexecutado na skill).
|
||||||
|
|
||||||
|
## Ainda não existe (próximo passo)
|
||||||
|
|
||||||
|
Vistas especiais da referência: corte do subsolo, mapa visto de cima, painel/gráfico, celular, tela dividida. Agente que
|
||||||
|
escreve o spec de cada trecho (em vez das regras de `planCartoon`). Personagem `kind: "3d"` existe só na ficha. Não prometa.
|
||||||
@@ -708,6 +708,8 @@ observada num envio real ainda. Contexto em [publishing.md](publishing.md).
|
|||||||
Instagram não têm leitura sem janela logada (página pública devolve só verificação ou nada). Ver [publishing.md](publishing.md).
|
Instagram não têm leitura sem janela logada (página pública devolve só verificação ou nada). Ver [publishing.md](publishing.md).
|
||||||
153. **Corpo JSON com acento por `curl -d` no Git Bash chega com UTF-8 inválido** (`jsontext: invalid UTF-8`). Correção:
|
153. **Corpo JSON com acento por `curl -d` no Git Bash chega com UTF-8 inválido** (`jsontext: invalid UTF-8`). Correção:
|
||||||
gravar o corpo num arquivo (scratchpad) e enviar com `--data-binary @arquivo`, com `Origin` e `Content-Type` (item 125).
|
gravar o corpo num arquivo (scratchpad) e enviar com `--data-binary @arquivo`, com `Origin` e `Content-Type` (item 125).
|
||||||
|
Mesmo com `curl` o nome "Verificação" virou id `teste-verifica-o` na API de personagens (17/11/2026): teste acentos por
|
||||||
|
Python/UTF-8.
|
||||||
154. **Publicar o repositório (Gitea) expondo segredo ou e-mail pessoal.** O projeto é PÚBLICO em
|
154. **Publicar o repositório (Gitea) expondo segredo ou e-mail pessoal.** O projeto é PÚBLICO em
|
||||||
`https://git.origininteractivestudios.com/Mateuus/CenaForge` (Gitea 1.27.3; 1º commit `84f30bb`, 484 arquivos,
|
`https://git.origininteractivestudios.com/Mateuus/CenaForge` (Gitea 1.27.3; 1º commit `84f30bb`, 484 arquivos,
|
||||||
~7,4 MB, 17/11/2026). Fora do git: `data/`, `.env`, venvs (inclui `publisher/.venv/`) e `output/`. Commits neste
|
~7,4 MB, 17/11/2026). Fora do git: `data/`, `.env`, venvs (inclui `publisher/.venv/`) e `output/`. Commits neste
|
||||||
@@ -722,6 +724,38 @@ observada num envio real ainda. Contexto em [publishing.md](publishing.md).
|
|||||||
1080×1920 (`maxresdefault` é 1280×720 horizontal); foi o que se fez no corte 91. Junto: em `metrics.ts` a regex do
|
1080×1920 (`maxresdefault` é 1280×720 horizontal); foi o que se fez no corte 91. Junto: em `metrics.ts` a regex do
|
||||||
episódio era `/^ep(d+)/i` (faltava a barra) e o link ia só para a história; agora `/^ep(\d+)/i`. Onde:
|
episódio era `/^ep(d+)/i` (faltava a barra) e o link ia só para a história; agora `/^ep(\d+)/i`. Onde:
|
||||||
`panel/src/lib/publishing.ts`, `panel/src/lib/metrics.ts`.
|
`panel/src/lib/publishing.ts`, `panel/src/lib/metrics.ts`.
|
||||||
|
156. **Cartoon: a síntese de voz não devolve tempos por palavra.** `POST /v1/synthesize` só entrega o áudio; tempos vêm da
|
||||||
|
transcrição (`/v1/transcribe`, `X-Detail: words`). `wordTimings` transcreve o áudio do trecho; sem o serviço de voz,
|
||||||
|
reparte o texto pela duração (aproximado). A montagem antiga (FFmpeg) reparte a legenda por tamanho (`captionChunks`
|
||||||
|
em `montage-ffmpeg.ts`). Onde: `panel/src/lib/montage-cartoon.ts`.
|
||||||
|
157. **Cartoon: o plano sai genérico (rua de casas, noite) quando o texto não cita um lugar conhecido.** Observado
|
||||||
|
(17/11/2026, antes dos lugares por peças): história de ilha/cobras saiu em rua de casas. Hoje `LOCATIONS` cobre 10
|
||||||
|
lugares (parque, cemitério, bunker, casa…); fora deles cai nas cenas antigas (`scenes.tsx`, da história de energia).
|
||||||
|
Lugar novo = linha em `LOCATIONS` (+ peça em `places.tsx` se faltar), nunca cena pronta. Sem lugar, prefira `mixed`/`3d`.
|
||||||
|
Onde: `panel/src/lib/montage-cartoon.ts`.
|
||||||
|
158. **TikTok: `#hashtag` publicada vira texto, não hashtag.** Diagnóstico (`doc/publicacao/TIKTOK_DIAGNOSTICO.md`): a página
|
||||||
|
pública do vídeo mostrava `challenges: []` e `textExtra: []`, porque `insert_text` cola `#tag` como texto puro.
|
||||||
|
Correção: `caption_parts` separa texto e tags; `type_caption` cola o texto, digita cada `#tag` e confirma clicando na
|
||||||
|
sugestão exata (`hashtag_options`); sem sugestão a tag fica como texto; progresso "N de M hashtags confirmadas". Teste:
|
||||||
|
`publisher/tests/test_tiktok_caption.py` (3, não reexecutado na skill). **Não validado com vídeo real**; só vale
|
||||||
|
depois de reiniciar o `pnpm dev` (item 143). Onde: `publisher/app/platforms/session/tiktok_studio.py`.
|
||||||
|
159. **Ler várias páginas públicas do TikTok seguidas devolve o desafio anti-robô `SlardarWAF`** (1.462 bytes) para
|
||||||
|
`curl`/`yt-dlp`. Um Chrome real passa. Receita para baixar um vídeo de referência (informada, não reexecutada): Playwright
|
||||||
|
com `channel="chrome"` e perfil temporário, ler `__UNIVERSAL_DATA_FOR_REHYDRATION__`
|
||||||
|
(`itemStruct.video.bitrateInfo[].PlayAddr.UrlList`) e baixar por `ctx.request` com `Referer: https://www.tiktok.com/`.
|
||||||
|
Só para referência/estudo; nunca em stealth no fluxo de publicação (regra em publishing.md).
|
||||||
|
160. **Cartoon: HUD, gerador e onomatopeia do exemplo aparecem em todo trecho.** Causa: a Remotion completa props ausentes
|
||||||
|
com os `defaultProps` da composição; com o exemplo como padrão, tudo que o spec não trazia vinha do exemplo.
|
||||||
|
Correção: `Shot` tem padrão VAZIO; o exemplo fica na composição `Sample` (só Studio). Campo opcional novo no spec
|
||||||
|
precisa de valor vazio em `BLANK`. Onde: `cartoon/src/Root.tsx`.
|
||||||
|
161. **Cartoon: o plano errava o assunto do trecho.** "um barulho" solto virava "Vrrrum" (agora motor só com
|
||||||
|
gerador/motor/moto/carro perto; barulho genérico = "Crec"); "domingo de sol" virava noite (regra de dia ganhou
|
||||||
|
sol/manhã/domingo/claro); multidão era desenhada na frente do personagem (agora entra antes, pés em y 0,6);
|
||||||
|
onomatopeia cobria a etiqueta do personagem (vai para x 0,76 / y 0,24 quando há personagem). Ao mexer em palavra-chave,
|
||||||
|
rode `montage-cartoon.test.ts`. Onde: `panel/src/lib/montage-cartoon.ts`.
|
||||||
|
162. **Regex com `\b` escrita por heredoc/Python sem string raw vira um caractere de controle (backspace, 0x08)** (aconteceu 2x ao
|
||||||
|
editar `montage-cartoon.ts`): a regex deixa de casar, sem erro. Use `r"..."` ou o Edit (item 44) e confira com
|
||||||
|
`grep -nP "\x08" <arquivo>` que não sobrou nenhum.
|
||||||
|
|
||||||
Relacionadas, já registradas acima:
|
Relacionadas, já registradas acima:
|
||||||
- Patch por script em arquivos CRLF do painel (`lib/metrics.ts`, `components/metrics-view.tsx`, `dashboard-controls.tsx`,
|
- Patch por script em arquivos CRLF do painel (`lib/metrics.ts`, `components/metrics-view.tsx`, `dashboard-controls.tsx`,
|
||||||
|
|||||||
@@ -99,12 +99,13 @@ Card "Montagem do vídeo" (`components/montage-editor.tsx`) na página do vídeo
|
|||||||
"0,0055" → "zero vírgula zero zero cinquenta e cinco", milhar "1.500", km, m², ha, cm, kg, %, "por m²"). Texto na
|
"0,0055" → "zero vírgula zero zero cinquenta e cinco", milhar "1.500", km, m², ha, cm, kg, %, "por m²"). Texto na
|
||||||
tela que é pergunta e que a narração não repete entra antes da fala ("Uma cobra por metro quadrado? Não. ...");
|
tela que é pergunta e que a narração não repete entra antes da fala ("Uma cobra por metro quadrado? Não. ...");
|
||||||
- **visual** (`VISUAL_KINDS` em `lib/montage.ts`; rótulo da UI entre parênteses): `image` (Foto), `godot2d`
|
- **visual** (`VISUAL_KINDS` em `lib/montage.ts`; rótulo da UI entre parênteses): `image` (Foto), `godot2d`
|
||||||
(Animação 2D), `godot3d` (Cena 3D da biblioteca), `video` (Clipe: envio ou render Godot já feito), `card`
|
(Animação 2D), `godot3d` (Cena 3D da biblioteca), `cartoon` (Cartoon, Remotion), `video` (Clipe: envio ou render Godot já feito), `card`
|
||||||
(Cartela, sem arquivo). Pode misturar. `ShotVisual`: `scene` + `sceneKey` (Godot), `search {queries, pick}` (foto
|
(Cartela, sem arquivo). Pode misturar. `ShotVisual`: `scene` + `sceneKey` (Godot), `search {queries, pick}` (foto
|
||||||
da internet), `auto` (escolhido pelo automático; trocar à mão grava `auto: false`), `inset` (cartão de foto por
|
da internet), `auto` (escolhido pelo automático; trocar à mão grava `auto: false`), `inset` (cartão de foto por
|
||||||
cima do visual; na UI, `InsetCard`: "Outra foto", "Tirar", "Pôr foto da internet").
|
cima do visual; na UI, `InsetCard`: "Outra foto", "Tirar", "Pôr foto da internet").
|
||||||
- **Estilo do vídeo** (`style` no `.montage.json`, `PATCH {style}`; seletor "Estilo do vídeo" no topo): `"mixed"`
|
- **Estilo do vídeo** (`style` no `.montage.json`, `PATCH {style}`; seletor "Estilo do vídeo" no topo): `"mixed"`
|
||||||
(padrão: foto, 2D e 3D) ou `"3d"` ("Tudo em 3D": todo trecho vira cena 3D da biblioteca, fotos só em cartão).
|
(padrão: foto, 2D e 3D), `"3d"` ("Tudo em 3D": todo trecho vira cena 3D da biblioteca, fotos só em cartão) ou
|
||||||
|
`"cartoon"` ("Cartoon: desenho 2D chapado": todo trecho vira cena Remotion; ver "Estilo Cartoon").
|
||||||
Regras de roteiro para isso: "Vídeo todo em 3D" em `doc/roteiro/documental.md` (coluna Imagem = tomada 3D,
|
Regras de roteiro para isso: "Vídeo todo em 3D" em `doc/roteiro/documental.md` (coluna Imagem = tomada 3D,
|
||||||
`[foto: termos]`, cenas 3D que faltam em "Necessidades de produção").
|
`[foto: termos]`, cenas 3D que faltam em "Necessidades de produção").
|
||||||
- **Cartões de informação em sequência:** texto na tela `A; depois: B; depois: C` mostra as partes uma após a outra,
|
- **Cartões de informação em sequência:** texto na tela `A; depois: B; depois: C` mostra as partes uma após a outra,
|
||||||
@@ -194,6 +195,11 @@ Card "Montagem do vídeo" (`components/montage-editor.tsx`) na página do vídeo
|
|||||||
dentro de outra e `.glb` por `GLTFDocument` em tempo de execução: `doc/godot/cenas.md`.
|
dentro de outra e `.glb` por `GLTFDocument` em tempo de execução: `doc/godot/cenas.md`.
|
||||||
- Cena nova pelo painel: tarefa "Cena no Godot" do agente (seção "Agentes e modelos").
|
- Cena nova pelo painel: tarefa "Cena no Godot" do agente (seção "Agentes e modelos").
|
||||||
|
|
||||||
|
### Estilo Cartoon (`cartoon/`, Remotion, sem Godot)
|
||||||
|
|
||||||
|
Cada trecho vira um MP4 de desenho 2D montado por peças a partir do texto; personagens vêm da biblioteca
|
||||||
|
(`assets/characters/`). Contrato, peças, render, plano, personagens e integração em `montage.ts`: [cartoon.md](cartoon.md).
|
||||||
|
|
||||||
### Gerar o MP4 (`startMontageRender(id, { auto, replan })`)
|
### Gerar o MP4 (`startMontageRender(id, { auto, replan })`)
|
||||||
|
|
||||||
- `auto: false` ("Só montar"): exige áudio atualizado e visual em todos os trechos (menos cartela); as cenas Godot
|
- `auto: false` ("Só montar"): exige áudio atualizado e visual em todos os trechos (menos cartela); as cenas Godot
|
||||||
|
|||||||
@@ -166,6 +166,11 @@ confirmou (regra "YouTube Studio"); a confirmação nova não foi testada.**
|
|||||||
roda antes da legenda e antes de "Publicar". `TIP_BUTTONS` só aceita `^(Entendi|Entendido|Ok, entendi|Got it)$`:
|
roda antes da legenda e antes de "Publicar". `TIP_BUTTONS` só aceita `^(Entendi|Entendido|Ok, entendi|Got it)$`:
|
||||||
**nunca aceitar ou recusar opções por esse caminho**, só fechar avisos. Gotchas 142.
|
**nunca aceitar ou recusar opções por esse caminho**, só fechar avisos. Gotchas 142.
|
||||||
|
|
||||||
|
- **Legenda do TikTok com hashtags de verdade** (`tiktok_studio.py`: `caption_parts`, `type_caption`, `hashtag_options`):
|
||||||
|
texto colado; cada `#tag` digitada e confirmada clicando na sugestão exata; sem sugestão fica texto; progresso "N de M
|
||||||
|
hashtags confirmadas". Corrigido em 17/11/2026 após diagnóstico (`doc/publicacao/TIKTOK_DIAGNOSTICO.md`); **falta
|
||||||
|
validar com vídeo real** (conferir `challenges`/`textExtra` na página pública). Gotchas 158–159.
|
||||||
|
|
||||||
- **YouTube Studio (modo sessão): confirmar a publicação** (`youtube_studio.py`; gotchas 151). O `#done-button` é um
|
- **YouTube Studio (modo sessão): confirmar a publicação** (`youtube_studio.py`; gotchas 151). O `#done-button` é um
|
||||||
componente `ytcp-button`, não um `<button>` nativo: o Playwright clica mesmo desativado e o clique se perde.
|
componente `ytcp-button`, não um `<button>` nativo: o Playwright clica mesmo desativado e o clique se perde.
|
||||||
`is_enabled`/`wait_enabled` leem `disabled`/`aria-disabled` do elemento e do `<button>` de dentro e esperam até 10 min;
|
`is_enabled`/`wait_enabled` leem `disabled`/`aria-disabled` do elemento e do `<button>` de dentro e esperam até 10 min;
|
||||||
|
|||||||
@@ -25,6 +25,19 @@ prévia e registre aqui (via `cenaforge-skill-updater`).
|
|||||||
| API do Wikimedia Commons (`commons.wikimedia.org/w/api.php`) | sem versão (HTTP público, sem chave; User-Agent genérico) | fotos reais por trecho na montagem documental (`panel/src/lib/image-search.ts`), com autor, licença e página de origem nos créditos | chamada direta do painel | 17/11/2026 (`ep01.montage.json`: 5 fotos do Commons com licença CC registrada; MP4 de 88,3 s; licença não conferida na página de cada foto) |
|
| API do Wikimedia Commons (`commons.wikimedia.org/w/api.php`) | sem versão (HTTP público, sem chave; User-Agent genérico) | fotos reais por trecho na montagem documental (`panel/src/lib/image-search.ts`), com autor, licença e página de origem nos créditos | chamada direta do painel | 17/11/2026 (`ep01.montage.json`: 5 fotos do Commons com licença CC registrada; MP4 de 88,3 s; licença não conferida na página de cada foto) |
|
||||||
| Claude Code CLI | 2.1.314 | agente chamado pelo painel (`-p`, `stream-json`, `--resume`, `--model claude-*-5-5`/`claude-fable-5-2`) | `CLAUDE_BIN` → `PATH` (`claude.exe`) | 17/11/2026 |
|
| Claude Code CLI | 2.1.314 | agente chamado pelo painel (`-p`, `stream-json`, `--resume`, `--model claude-*-5-5`/`claude-fable-5-2`) | `CLAUDE_BIN` → `PATH` (`claude.exe`) | 17/11/2026 |
|
||||||
|
|
||||||
|
Estilo Cartoon (`cartoon/`, 17/11/2026; contrato e uso em [cartoon.md](cartoon.md)):
|
||||||
|
|
||||||
|
| Ferramenta | Versão | Papel | Evidência (17/11/2026) |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Remotion (`remotion`, `@remotion/bundler`, `@remotion/renderer`, `@remotion/cli`) | 4.0.535 (fixada; conferida em `cartoon/node_modules`) | cenas 2D vetoriais em React → MP4 por trecho | exemplo de 6 s (180 quadros) em 11,8 s; 3 trechos reais (~21 s de vídeo) em 25,2 s (1º 11,2 s, depois ~4 s cada). Medido pelo dono, não reexecutado aqui |
|
||||||
|
| React / react-dom | 19.3.0 | componentes das cenas | idem |
|
||||||
|
| Chrome Headless Shell | baixado pela Remotion no 1º render (~120 MB; versão não registrada); `CARTOON_CHROME` aponta outro Chrome | renderiza os quadros | idem |
|
||||||
|
| Fontes Anton e Bebas Neue | `assets/fonts/` (`publicDir` = `assets`) | texto das etiquetas e legenda | ver licenças em "Clipador" |
|
||||||
|
|
||||||
|
Licença da Remotion: grátis para pessoa física e empresa pequena; empresa maior paga. **Conferir os termos antes de uso
|
||||||
|
comercial** (não verificado aqui). Testes: `npx tsx --test tests/*.test.ts` em `cartoon/` (5 testes de `spec.test.ts`);
|
||||||
|
painel: `montage-cartoon.test.ts` (9). Cartoon 5/5 reexecutado em 17/11/2026; painel 77/77 informado pelo dono.
|
||||||
|
|
||||||
Hardware do teste de referência: i9-13900K, 64 GB, RTX 2060 SUPER. Tempos: prévia 540×960
|
Hardware do teste de referência: i9-13900K, 64 GB, RTX 2060 SUPER. Tempos: prévia 540×960
|
||||||
42–44 s; final 1080×1920 ~160 s. A etapa de render da Godot ocupa 94–96% do total, dominada
|
42–44 s; final 1080×1920 ~160 s. A etapa de render da Godot ocupa 94–96% do total, dominada
|
||||||
pela codificação PNG (105 ms/quadro na prévia, 404 ms no final; ~90–91% do total); GPU
|
pela codificação PNG (105 ms/quadro na prévia, 404 ms no final; ~90–91% do total); GPU
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"name": "cenaforge-cartoon",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.1.0",
|
||||||
|
"type": "module",
|
||||||
|
"description": "Estilo Cartoon da montagem documental: cenas 2D vetoriais em React (Remotion) renderizadas em MP4 por trecho.",
|
||||||
|
"scripts": {
|
||||||
|
"studio": "remotion studio src/index.ts",
|
||||||
|
"render": "tsx render.ts",
|
||||||
|
"test": "tsx --test tests/*.test.ts",
|
||||||
|
"typecheck": "tsc -p tsconfig.json --noEmit"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@remotion/bundler": "4.0.535",
|
||||||
|
"@remotion/cli": "4.0.535",
|
||||||
|
"@remotion/renderer": "4.0.535",
|
||||||
|
"react": "19.3.0",
|
||||||
|
"react-dom": "19.3.0",
|
||||||
|
"remotion": "4.0.535"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/react": "19.3.0",
|
||||||
|
"tsx": "4.23.15",
|
||||||
|
"typescript": "7.0.2"
|
||||||
|
},
|
||||||
|
"exports": {
|
||||||
|
"./character": "./src/character.ts",
|
||||||
|
"./figure": "./src/CharacterFigure.tsx",
|
||||||
|
"./spec": "./src/spec.ts"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
// Remotion Studio (`pnpm --filter cenaforge-cartoon studio`): as fontes vêm de assets/ do repositório.
|
||||||
|
import { Config } from "@remotion/cli/config";
|
||||||
|
|
||||||
|
Config.setPublicDir("../assets");
|
||||||
|
Config.setVideoImageFormat("jpeg");
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
// Render do estilo Cartoon por linha de comando. Empacota uma vez e renderiza todos os trechos pedidos.
|
||||||
|
//
|
||||||
|
// tsx render.ts --jobs <arquivo.json> [{ "spec": "<spec.json>", "out": "<trecho.mp4>" }, ...]
|
||||||
|
// tsx render.ts --spec <spec.json> --out <trecho.mp4>
|
||||||
|
// tsx render.ts --sample --out <exemplo.mp4>
|
||||||
|
//
|
||||||
|
// Caminhos relativos valem a partir da raiz do repositório. Última linha do stdout = relatório JSON
|
||||||
|
// ({ ok, results: [{ out, frames, ms }], error? }); código de saída 0 só se todos saírem.
|
||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { bundle } from "@remotion/bundler";
|
||||||
|
import { renderMedia, renderStill, selectComposition } from "@remotion/renderer";
|
||||||
|
import { validateLook } from "./src/character";
|
||||||
|
import { frameCount, validateSpec, type ShotSpec } from "./src/spec";
|
||||||
|
import { SAMPLE } from "./src/sample";
|
||||||
|
|
||||||
|
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
const REPO = path.resolve(HERE, "..");
|
||||||
|
const resolve = (p: string) => (path.isAbsolute(p) ? p : path.resolve(REPO, p));
|
||||||
|
|
||||||
|
type Job = { spec: ShotSpec; out: string };
|
||||||
|
|
||||||
|
function arg(name: string): string | undefined {
|
||||||
|
const i = process.argv.indexOf(`--${name}`);
|
||||||
|
return i >= 0 ? process.argv[i + 1] : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readJobs(): Job[] {
|
||||||
|
const jobsFile = arg("jobs");
|
||||||
|
if (jobsFile) {
|
||||||
|
const list = JSON.parse(fs.readFileSync(resolve(jobsFile), "utf8")) as { spec: string; out: string }[];
|
||||||
|
if (!Array.isArray(list) || list.length === 0) throw new Error("--jobs precisa ser uma lista com pelo menos um trecho");
|
||||||
|
return list.map((j) => ({ spec: JSON.parse(fs.readFileSync(resolve(j.spec), "utf8")), out: resolve(j.out) }));
|
||||||
|
}
|
||||||
|
const out = arg("out");
|
||||||
|
if (!out) throw new Error("falta --out (ou use --jobs)");
|
||||||
|
if (process.argv.includes("--sample")) return [{ spec: SAMPLE, out: resolve(out) }];
|
||||||
|
const spec = arg("spec");
|
||||||
|
if (!spec) throw new Error("falta --spec (ou use --jobs / --sample)");
|
||||||
|
return [{ spec: JSON.parse(fs.readFileSync(resolve(spec), "utf8")), out: resolve(out) }];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `--still --props <json> --out <png> [--frame N]`: imagem parada do cartão de personagem (prévia da biblioteca). */
|
||||||
|
async function still() {
|
||||||
|
const propsFile = arg("props");
|
||||||
|
const out = arg("out");
|
||||||
|
if (!propsFile || !out) throw new Error("--still precisa de --props e --out");
|
||||||
|
const inputProps = JSON.parse(fs.readFileSync(resolve(propsFile), "utf8")) as Record<string, unknown>;
|
||||||
|
const looks = (inputProps.figures as { look: unknown }[] | undefined) ?? [];
|
||||||
|
if (!looks.length) throw new Error("--still: figures vazio");
|
||||||
|
for (const [i, f] of looks.entries()) {
|
||||||
|
const errors = validateLook(f.look);
|
||||||
|
if (errors.length) throw new Error(`figures[${i}].look: ${errors.join("; ")}`);
|
||||||
|
}
|
||||||
|
const serveUrl = await bundle({ entryPoint: path.join(HERE, "src", "index.ts"), publicDir: path.join(REPO, "assets") });
|
||||||
|
const composition = await selectComposition({ serveUrl, id: "Character", inputProps });
|
||||||
|
fs.mkdirSync(path.dirname(resolve(out)), { recursive: true });
|
||||||
|
await renderStill({ composition, serveUrl, inputProps, output: resolve(out), frame: Number(arg("frame") ?? 0), imageFormat: "png",
|
||||||
|
browserExecutable: process.env.CARTOON_CHROME || null });
|
||||||
|
console.log(JSON.stringify({ ok: true, results: [{ out: path.relative(REPO, resolve(out)).replace(/\\/g, "/"), frames: 1, ms: 0 }] }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
if (process.argv.includes("--still")) return still();
|
||||||
|
const jobs = readJobs();
|
||||||
|
for (const [i, job] of jobs.entries()) {
|
||||||
|
const errors = validateSpec(job.spec);
|
||||||
|
if (errors.length) throw new Error(`trecho ${i + 1} (${path.basename(job.out)}): ${errors.join("; ")}`);
|
||||||
|
}
|
||||||
|
const started = Date.now();
|
||||||
|
const serveUrl = await bundle({ entryPoint: path.join(HERE, "src", "index.ts"), publicDir: path.join(REPO, "assets") });
|
||||||
|
console.log(`empacotado em ${((Date.now() - started) / 1000).toFixed(1)} s`);
|
||||||
|
const results: { out: string; frames: number; ms: number }[] = [];
|
||||||
|
for (const job of jobs) {
|
||||||
|
const t0 = Date.now();
|
||||||
|
const inputProps = job.spec as unknown as Record<string, unknown>;
|
||||||
|
const composition = await selectComposition({ serveUrl, id: "Shot", inputProps });
|
||||||
|
fs.mkdirSync(path.dirname(job.out), { recursive: true });
|
||||||
|
await renderMedia({
|
||||||
|
composition, serveUrl, inputProps, codec: "h264", outputLocation: job.out, crf: 18, pixelFormat: "yuv420p",
|
||||||
|
imageFormat: "jpeg", jpegQuality: 92, muted: true, overwrite: true,
|
||||||
|
browserExecutable: process.env.CARTOON_CHROME || null,
|
||||||
|
});
|
||||||
|
results.push({ out: path.relative(REPO, job.out).replace(/\\/g, "/"), frames: frameCount(job.spec), ms: Date.now() - t0 });
|
||||||
|
console.log(`ok ${path.basename(job.out)} (${frameCount(job.spec)} quadros, ${((Date.now() - t0) / 1000).toFixed(1)} s)`);
|
||||||
|
}
|
||||||
|
console.log(JSON.stringify({ ok: true, results }));
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((error: unknown) => {
|
||||||
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
|
console.log(JSON.stringify({ ok: false, error: message }));
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
// Cartão de personagem (prévia da biblioteca e conferência): um ou mais personagens lado a lado, cada um com
|
||||||
|
// expressão e pose, sobre fundo neutro, com o nome na etiqueta.
|
||||||
|
import React from "react";
|
||||||
|
import { AbsoluteFill, useCurrentFrame, useVideoConfig } from "remotion";
|
||||||
|
import { CharacterFigure } from "./CharacterFigure";
|
||||||
|
import { TagLabel } from "./overlays";
|
||||||
|
import { loadFonts } from "./theme";
|
||||||
|
import type { CharacterLook, Expression, Pose } from "./character";
|
||||||
|
import type { IconId } from "./spec";
|
||||||
|
|
||||||
|
loadFonts();
|
||||||
|
|
||||||
|
export type CardProps = {
|
||||||
|
width: number; height: number;
|
||||||
|
background?: string;
|
||||||
|
figures: { look: CharacterLook; expression?: Expression; pose?: Pose; item?: IconId; label?: string }[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export function CharacterCard({ figures, background = "#2a2e45" }: CardProps) {
|
||||||
|
const frame = useCurrentFrame();
|
||||||
|
const { fps } = useVideoConfig();
|
||||||
|
const n = Math.max(1, figures.length);
|
||||||
|
return (
|
||||||
|
<AbsoluteFill style={{ background, containerType: "size" }}>
|
||||||
|
<div style={{ position: "absolute", inset: "8% 2% 4%", display: "grid", gridTemplateColumns: `repeat(${n}, 1fr)`, alignItems: "end" }}>
|
||||||
|
{figures.map((f, i) => (
|
||||||
|
<div key={i} style={{ position: "relative", height: "100%", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "flex-end" }}>
|
||||||
|
{f.label && <div style={{ marginBottom: "4%" }}><TagLabel text={f.label} size={n > 3 ? 2.2 : 3.4} /></div>}
|
||||||
|
<div style={{ width: "90%", aspectRatio: "200 / 440", maxHeight: "86%" }}>
|
||||||
|
<CharacterFigure look={f.look} expression={f.expression} pose={f.pose} item={f.item} t={frame / fps} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</AbsoluteFill>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
// Desenho do personagem a partir das peças (character.ts). SVG puro, sem Remotion: o painel usa o mesmo
|
||||||
|
// componente na prévia ao vivo da aba Personagens. viewBox 200×440 com os pés em (100, 440).
|
||||||
|
// `t` (segundos) só move detalhes vivos: respiração, piscar, braço acenando.
|
||||||
|
import React from "react";
|
||||||
|
import { Icon } from "./icons";
|
||||||
|
import type { IconId } from "./spec";
|
||||||
|
import { DEFAULT_LOOK, type CharacterLook, type Expression, type Pose } from "./character";
|
||||||
|
|
||||||
|
const INK = "#15161f";
|
||||||
|
|
||||||
|
/** Ângulo dos braços por pose (graus; 0 = para baixo). Direito negativo = para fora; esquerdo positivo = para fora. */
|
||||||
|
const ARMS: Record<Pose, [number, number]> = {
|
||||||
|
stand: [-8, 8], point: [-95, 8], wave: [-150, 8], hold: [-38, 8], arms_up: [-160, 160], shrug: [-55, 55], think: [150, 8],
|
||||||
|
};
|
||||||
|
|
||||||
|
function shade(hex: string, k: number): string {
|
||||||
|
const n = parseInt(hex.slice(1), 16);
|
||||||
|
const c = (v: number) => Math.max(0, Math.min(255, Math.round(v * k))).toString(16).padStart(2, "0");
|
||||||
|
return `#${c((n >> 16) & 255)}${c((n >> 8) & 255)}${c(n & 255)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Mouth({ expression }: { expression: Expression }) {
|
||||||
|
const common = { stroke: INK, strokeWidth: 4.5, fill: "none", strokeLinecap: "round" as const };
|
||||||
|
switch (expression) {
|
||||||
|
case "happy": return <path d="M84 131 Q100 150 116 131 Q100 140 84 131 Z" fill={INK} />;
|
||||||
|
case "sad": return <path d="M87 141 Q100 129 113 141" {...common} />;
|
||||||
|
case "worried": return <path d="M86 139 Q93 133 100 139 Q107 145 114 139" {...common} />;
|
||||||
|
case "angry": return <path d="M87 139 L113 136" {...common} strokeWidth={6} />;
|
||||||
|
case "surprised": return <ellipse cx={100} cy={139} rx={8} ry={10} fill={INK} />;
|
||||||
|
case "scared": return <ellipse cx={100} cy={140} rx={10} ry={7} fill={INK} />;
|
||||||
|
default: return <path d="M88 136 Q100 140 112 136" {...common} />;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Brows({ expression, thick, color }: { expression: Expression; thick: boolean; color: string }) {
|
||||||
|
// Inclinação da sobrancelha esquerda (a direita espelha): + sobe por dentro (triste/preocupado), − desce (bravo).
|
||||||
|
const tilt = { neutral: 0, happy: -6, sad: 16, worried: 14, angry: -18, surprised: 0, scared: 18 }[expression];
|
||||||
|
const lift = expression === "surprised" || expression === "scared" ? -7 : expression === "happy" ? -3 : 0;
|
||||||
|
const w = thick ? 7 : 4.5;
|
||||||
|
return (
|
||||||
|
<g stroke={color} strokeWidth={w} strokeLinecap="round">
|
||||||
|
<line x1={71} y1={89 + lift} x2={92} y2={89 + lift} transform={`rotate(${tilt} 92 ${89 + lift})`} />
|
||||||
|
<line x1={108} y1={89 + lift} x2={129} y2={89 + lift} transform={`rotate(${-tilt} 108 ${89 + lift})`} />
|
||||||
|
</g>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Eyes({ expression, t }: { expression: Expression; t: number }) {
|
||||||
|
const big = expression === "surprised" || expression === "scared";
|
||||||
|
const r = big ? 12.5 : 10.5;
|
||||||
|
const pupil = expression === "scared" ? 3.4 : big ? 5.5 : 5;
|
||||||
|
const blink = (t % 3.7) < 0.12 && !big ? 0.12 : 1;
|
||||||
|
const squint = expression === "angry" ? 0.7 : expression === "happy" ? 0.8 : 1;
|
||||||
|
return (
|
||||||
|
<g>
|
||||||
|
{[82, 118].map((x) => (
|
||||||
|
<g key={x} transform={`translate(${x} 108) scale(1 ${blink * squint})`}>
|
||||||
|
<circle r={r} fill="#ffffff" />
|
||||||
|
<circle r={pupil} cx={expression === "worried" ? -1.5 : 0} cy={expression === "sad" ? 2 : 0} fill={INK} />
|
||||||
|
</g>
|
||||||
|
))}
|
||||||
|
</g>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Glasses({ kind }: { kind: CharacterLook["glasses"] }) {
|
||||||
|
if (kind === "none") return null;
|
||||||
|
const lens = kind === "sun" ? INK : "none";
|
||||||
|
return (
|
||||||
|
<g stroke={INK} strokeWidth={4} fill={lens}>
|
||||||
|
{kind === "square"
|
||||||
|
? <><rect x={67} y={95} width={30} height={25} rx={5} /><rect x={103} y={95} width={30} height={25} rx={5} /></>
|
||||||
|
: <><circle cx={82} cy={108} r={15} /><circle cx={118} cy={108} r={15} /></>}
|
||||||
|
<line x1={97} y1={107} x2={103} y2={107} />
|
||||||
|
<line x1={55} y1={104} x2={67} y2={106} /><line x1={133} y1={106} x2={145} y2={104} />
|
||||||
|
</g>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Beard({ style, color }: { style: CharacterLook["beard"]["style"]; color: string }) {
|
||||||
|
switch (style) {
|
||||||
|
case "full": return <path d="M56 108 Q58 168 100 172 Q142 168 144 108 Q138 128 124 126 Q100 122 76 126 Q62 128 56 108 Z" fill={color} />;
|
||||||
|
case "stubble": return <path d="M60 116 Q64 162 100 166 Q136 162 140 116 Q130 132 100 128 Q70 132 60 116 Z" fill={color} opacity={0.35} />;
|
||||||
|
case "goatee": return <path d="M88 146 Q100 166 112 146 Q100 152 88 146 Z" fill={color} />;
|
||||||
|
case "mustache": return <path d="M82 128 Q100 120 118 128 Q110 134 100 130 Q90 134 82 128 Z" fill={color} />;
|
||||||
|
default: return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function HairBack({ look }: { look: CharacterLook }) {
|
||||||
|
if (look.hair.style !== "long") return null;
|
||||||
|
return <path d="M50 100 Q48 40 100 38 Q152 40 150 100 L156 190 Q100 205 44 190 Z" fill={look.hair.color} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function HairFront({ look }: { look: CharacterLook }) {
|
||||||
|
const c = look.hair.color;
|
||||||
|
switch (look.hair.style) {
|
||||||
|
case "bald": return <><path d="M53 112 Q50 86 62 80 L62 112 Z" fill={c} /><path d="M147 112 Q150 86 138 80 L138 112 Z" fill={c} /></>;
|
||||||
|
case "short": return <path d="M53 104 Q52 50 100 50 Q148 50 147 104 Q140 76 100 74 Q60 76 53 104 Z" fill={c} />;
|
||||||
|
case "side": return <path d="M53 106 Q50 48 104 50 Q150 54 147 104 Q134 70 92 80 Q66 86 53 106 Z" fill={c} />;
|
||||||
|
case "bun": return <><circle cx={100} cy={46} r={20} fill={c} /><path d="M53 104 Q52 52 100 52 Q148 52 147 104 Q138 74 100 72 Q62 74 53 104 Z" fill={c} /></>;
|
||||||
|
case "long": return <path d="M53 108 Q50 50 100 50 Q150 50 147 108 Q136 72 100 70 Q64 72 53 108 Z" fill={c} />;
|
||||||
|
case "curly": return <g fill={c}>{[[60, 84], [72, 64], [90, 54], [110, 54], [128, 64], [140, 84], [100, 62], [80, 74], [120, 74]].map(([x, y], i) => <circle key={i} cx={x} cy={y} r={15} />)}</g>;
|
||||||
|
case "spiky": return <path d="M54 102 L58 66 L72 76 L80 48 L94 70 L104 44 L114 70 L128 50 L132 76 L146 66 L146 102 Q130 80 100 80 Q70 80 54 102 Z" fill={c} />;
|
||||||
|
case "cap": return <><path d="M54 96 Q54 50 100 50 Q146 50 146 96 Z" fill={c} /><path d="M120 92 Q160 92 172 100 L120 102 Z" fill={shade(c, 0.8)} /></>;
|
||||||
|
default: return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Torso({ look, w }: { look: CharacterLook; w: number }) {
|
||||||
|
const { top } = look;
|
||||||
|
const x0 = 100 - 36 * w;
|
||||||
|
const x1 = 100 + 36 * w;
|
||||||
|
const bottomY = top.style === "dress" ? 345 : 290;
|
||||||
|
const flare = top.style === "dress" ? 14 : 0;
|
||||||
|
const body = `M${x0} 172 Q${x0} 158 ${x0 + 14} 156 L${x1 - 14} 156 Q${x1} 158 ${x1} 172 L${x1 + flare} ${bottomY} L${x0 - flare} ${bottomY} Z`;
|
||||||
|
const accent = top.accent ?? shade(top.color, 1.3);
|
||||||
|
return (
|
||||||
|
<g>
|
||||||
|
{top.style === "hoodie" && <path d={`M${x0 + 6} 160 Q100 132 ${x1 - 6} 160 Z`} fill={shade(top.color, 0.8)} />}
|
||||||
|
<path d={body} fill={top.color} />
|
||||||
|
{top.style === "uniform" && <rect x={x0} y={248} width={x1 - x0} height={11} fill={accent} />}
|
||||||
|
{top.style === "shirt" && top.accent && <rect x={x0} y={252} width={x1 - x0} height={9} fill={accent} />}
|
||||||
|
{top.style === "jacket" && <><path d={`M100 158 L100 ${bottomY}`} stroke={shade(top.color, 0.6)} strokeWidth={4} /><path d="M86 158 L100 186 L114 158 Z" fill={accent} /></>}
|
||||||
|
{top.style === "hoodie" && <rect x={84} y={240} width={32} height={22} rx={6} fill={shade(top.color, 0.85)} />}
|
||||||
|
{top.style === "dress" && [0, 1, 2, 3].map((i) => <circle key={i} cx={84 + (i % 2) * 32} cy={196 + Math.floor(i / 2) * 70} r={3.5} fill="#ffffff" opacity={0.5} />)}
|
||||||
|
</g>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Legs({ look, w }: { look: CharacterLook; w: number }) {
|
||||||
|
const { bottom } = look;
|
||||||
|
const gap = 10 * w;
|
||||||
|
const legW = 20 * w;
|
||||||
|
const left = 100 - gap - legW;
|
||||||
|
const right = 100 + gap;
|
||||||
|
const skinTop = look.top.style === "dress" ? 345 : bottom.style === "shorts" ? 330 : bottom.style === "skirt" ? 345 : 440;
|
||||||
|
return (
|
||||||
|
<g>
|
||||||
|
<rect x={left} y={286} width={legW} height={140} rx={6} fill={look.skin} />
|
||||||
|
<rect x={right} y={286} width={legW} height={140} rx={6} fill={look.skin} />
|
||||||
|
{look.top.style !== "dress" && bottom.style === "pants" && <><rect x={left} y={284} width={legW} height={142} rx={4} fill={bottom.color} /><rect x={right} y={284} width={legW} height={142} rx={4} fill={bottom.color} /></>}
|
||||||
|
{look.top.style !== "dress" && bottom.style === "shorts" && <path d={`M${left - 2} 284 L${right + legW + 2} 284 L${right + legW + 2} ${skinTop} L${left - 2} ${skinTop} Z`} fill={bottom.color} />}
|
||||||
|
{look.top.style !== "dress" && bottom.style === "skirt" && <path d={`M${left + 2} 284 L${right + legW - 2} 284 L${right + legW + 12} ${skinTop} L${left - 12} ${skinTop} Z`} fill={bottom.color} />}
|
||||||
|
<rect x={left - 4} y={422} width={legW + 10} height={16} rx={7} fill={look.shoes} />
|
||||||
|
<rect x={right - 6} y={422} width={legW + 10} height={16} rx={7} fill={look.shoes} />
|
||||||
|
</g>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CharacterFigure({ look = DEFAULT_LOOK, expression = "neutral", pose = "stand", item, t = 0 }: {
|
||||||
|
look?: CharacterLook; expression?: Expression; pose?: Pose; item?: IconId; t?: number;
|
||||||
|
}) {
|
||||||
|
const w = look.build === "slim" ? 0.86 : look.build === "heavy" ? 1.22 : 1;
|
||||||
|
const breathe = Math.sin(t * 2.2) * 1.6;
|
||||||
|
const [r0, l0] = ARMS[pose];
|
||||||
|
const swing = pose === "wave" ? Math.sin(t * 9) * 14 : Math.sin(t * 1.4) * 2.5;
|
||||||
|
const rAngle = r0 + swing;
|
||||||
|
const lAngle = l0 - (pose === "wave" ? 0 : swing);
|
||||||
|
const shoulderY = 168;
|
||||||
|
const sx = 34 * w;
|
||||||
|
const sleeve = look.top.style === "dress" ? look.skin : look.top.color;
|
||||||
|
const arm = (side: 1 | -1, angle: number, holds?: IconId) => (
|
||||||
|
<g transform={`rotate(${angle} ${100 + side * sx} ${shoulderY})`}>
|
||||||
|
<rect x={100 + side * sx - 9} y={shoulderY - 6} width={18} height={104} rx={9} fill={sleeve} />
|
||||||
|
<circle cx={100 + side * sx} cy={shoulderY + 102} r={11} fill={look.skin} />
|
||||||
|
{holds && (
|
||||||
|
<g transform={`translate(${100 + side * sx - 26} ${shoulderY + 96}) rotate(${-angle} 26 26)`}>
|
||||||
|
<svg x={0} y={0} width={52} height={52} viewBox="0 0 100 100" overflow="visible"><Icon id={holds} /></svg>
|
||||||
|
</g>
|
||||||
|
)}
|
||||||
|
</g>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<svg viewBox="0 0 200 440" width="100%" height="100%" overflow="visible">
|
||||||
|
<g transform={`translate(100 440) scale(${look.height}) translate(-100 -440) translate(0 ${breathe * 0.3})`}>
|
||||||
|
<HairBack look={look} />
|
||||||
|
<Legs look={look} w={w} />
|
||||||
|
{arm(-1, lAngle)}
|
||||||
|
<Torso look={look} w={w} />
|
||||||
|
{pose !== "think" && arm(1, rAngle, pose === "hold" || pose === "point" ? item : undefined)}
|
||||||
|
<rect x={90} y={146} width={20} height={16} fill={shade(look.skin, 0.9)} />
|
||||||
|
<g transform={`translate(0 ${breathe * 0.4})`}>
|
||||||
|
<ellipse cx={53} cy={112} rx={8} ry={11} fill={shade(look.skin, 0.92)} />
|
||||||
|
<ellipse cx={147} cy={112} rx={8} ry={11} fill={shade(look.skin, 0.92)} />
|
||||||
|
<ellipse cx={100} cy={106} rx={47} ry={50} fill={look.skin} />
|
||||||
|
<Beard style={look.beard.style} color={look.beard.color} />
|
||||||
|
<Eyes expression={expression} t={t} />
|
||||||
|
<Brows expression={expression} thick={look.brows === "thick"} color={look.hair.style === "bald" || look.hair.style === "cap" ? look.beard.color : look.hair.color} />
|
||||||
|
<Glasses kind={look.glasses} />
|
||||||
|
<Mouth expression={expression} />
|
||||||
|
<HairFront look={look} />
|
||||||
|
</g>
|
||||||
|
{/* Pensando: a mão vai ao queixo, por cima da barba. */}
|
||||||
|
{pose === "think" && arm(1, rAngle)}
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Composition } from "remotion";
|
||||||
|
import { Shot } from "./Shot";
|
||||||
|
import { frameCount, type ShotSpec } from "./spec";
|
||||||
|
import { SAMPLE } from "./sample";
|
||||||
|
import { CharacterCard, type CardProps } from "./CharacterCard";
|
||||||
|
|
||||||
|
// ATENÇÃO: a Remotion completa o que falta nas props com os `defaultProps` da composição. Por isso o padrão do
|
||||||
|
// "Shot" é um trecho VAZIO: se fosse o exemplo, o HUD, o gerador e a onomatopeia dele vazariam em todo trecho
|
||||||
|
// que não tivesse esses campos. O exemplo fica numa composição própria ("Sample"), só para o Studio.
|
||||||
|
const BLANK: ShotSpec = { schemaVersion: 1, width: 1080, height: 1920, fps: 30, durationS: 1, seed: 1, scene: { kind: "plain" } };
|
||||||
|
const BLANK_CARD: CardProps = { width: 1080, height: 1080, figures: [] };
|
||||||
|
|
||||||
|
const shotMetadata = ({ props }: { props: Record<string, unknown> }) => {
|
||||||
|
const spec = props as unknown as ShotSpec;
|
||||||
|
return { width: spec.width, height: spec.height, fps: spec.fps, durationInFrames: frameCount(spec) };
|
||||||
|
};
|
||||||
|
const asFc = (c: unknown) => c as React.FC<Record<string, unknown>>;
|
||||||
|
const asProps = (p: unknown) => p as Record<string, unknown>;
|
||||||
|
|
||||||
|
/** "Shot": um trecho (tamanho, fps e duração vêm do spec). "Character": cartão de personagem. "Sample": exemplo do Studio. */
|
||||||
|
export function Root() {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Composition id="Shot" component={asFc(Shot)} defaultProps={asProps(BLANK)} width={1080} height={1920} fps={30}
|
||||||
|
durationInFrames={30} calculateMetadata={shotMetadata} />
|
||||||
|
<Composition id="Sample" component={asFc(Shot)} defaultProps={asProps(SAMPLE)} width={SAMPLE.width} height={SAMPLE.height}
|
||||||
|
fps={SAMPLE.fps} durationInFrames={frameCount(SAMPLE)} calculateMetadata={shotMetadata} />
|
||||||
|
<Composition id="Character" component={asFc(CharacterCard)} defaultProps={asProps(BLANK_CARD)} width={1080} height={1080} fps={30}
|
||||||
|
durationInFrames={90} calculateMetadata={({ props }) => ({ width: (props as unknown as CardProps).width, height: (props as unknown as CardProps).height })} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
// Um trecho do estilo Cartoon: cena de fundo + personagens + objetos + textos + HUD + legenda, com a câmera
|
||||||
|
// fazendo um empurrão lento (nunca fica parado, como na referência).
|
||||||
|
import React from "react";
|
||||||
|
import { AbsoluteFill, useCurrentFrame, useVideoConfig } from "remotion";
|
||||||
|
import { CrowdFigure, PersonFigure } from "./actors";
|
||||||
|
import { Icon } from "./icons";
|
||||||
|
import { Captions, CrossOut, Hud, Rings, TagLabel, TextLayer, pop, shake } from "./overlays";
|
||||||
|
import { SceneBackground } from "./scenes";
|
||||||
|
import { CharacterFigure } from "./CharacterFigure";
|
||||||
|
import { LightLayer } from "./places";
|
||||||
|
import type { ShotSpec } from "./spec";
|
||||||
|
import { loadFonts } from "./theme";
|
||||||
|
|
||||||
|
loadFonts();
|
||||||
|
|
||||||
|
export function Shot(spec: ShotSpec) {
|
||||||
|
const frame = useCurrentFrame();
|
||||||
|
const { fps, durationInFrames, width, height } = useVideoConfig();
|
||||||
|
const progress = durationInFrames > 1 ? frame / (durationInFrames - 1) : 0;
|
||||||
|
const push = spec.camera?.push ?? (spec.scene.kind === "card" ? 1 : 1.07);
|
||||||
|
const zoom = 1 + (push - 1) * progress;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AbsoluteFill style={{ background: "#07080f", containerType: "size", overflow: "hidden" }}>
|
||||||
|
<AbsoluteFill style={{ transform: `scale(${zoom})`, transformOrigin: "50% 45%" }}>
|
||||||
|
<SceneBackground spec={spec} frame={frame} progress={progress} />
|
||||||
|
{(spec.actors ?? []).map((a, i) => {
|
||||||
|
const k = pop(frame, fps, a.enterS ?? 0);
|
||||||
|
if (a.kind === "crowd") {
|
||||||
|
return (
|
||||||
|
<div key={i} style={{ position: "absolute", left: "-2%", width: "104%", top: `${(a.y - 0.16) * 100}%`, height: "16%",
|
||||||
|
opacity: k, transform: `translateY(${(1 - k) * 8}%)` }}>
|
||||||
|
<CrowdFigure c={a} frame={frame} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (a.character) {
|
||||||
|
// Personagem da biblioteca: mesmo visual em toda cena; muda expressão, pose e objeto na mão.
|
||||||
|
const ch = height * 0.36 * (a.scale ?? 1);
|
||||||
|
const cw = (ch * 200) / 440;
|
||||||
|
const label = a.label ?? a.character.name;
|
||||||
|
return (
|
||||||
|
<div key={i} style={{ position: "absolute", left: a.x * width - cw / 2, top: a.y * height - ch, width: cw, height: ch,
|
||||||
|
opacity: Math.min(1, k * 1.5), transform: `translateY(${(1 - k) * 10}%) scaleX(${a.flip ? -1 : 1})` }}>
|
||||||
|
<CharacterFigure look={a.character.look} expression={a.expression} pose={a.pose} item={a.item} t={frame / fps} />
|
||||||
|
{label && (
|
||||||
|
<div style={{ position: "absolute", left: "50%", top: "-15%", transform: `translateX(-50%) scaleX(${a.flip ? -1 : 1})`, textAlign: "center" }}>
|
||||||
|
<TagLabel text={label} />
|
||||||
|
{a.character.caption && <div style={{ marginTop: "0.6cqw" }}><TagLabel text={a.character.caption} tone="ok" size={2.4} /></div>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const h = height * 0.27 * (a.scale ?? 1);
|
||||||
|
return (
|
||||||
|
<div key={i} style={{ position: "absolute", left: a.x * width - (h * 200) / 420 / 2, top: a.y * height - h, width: (h * 200) / 420,
|
||||||
|
height: h, opacity: Math.min(1, k * 1.5), transform: `translateY(${(1 - k) * 12}%)` }}>
|
||||||
|
<PersonFigure p={a} frame={frame} fps={fps} />
|
||||||
|
{a.label && <div style={{ position: "absolute", left: "50%", top: "-14%", transform: "translateX(-50%)" }}><TagLabel text={a.label} /></div>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{(spec.props ?? []).map((p, i) => {
|
||||||
|
const k = pop(frame, fps, p.enterS ?? 0);
|
||||||
|
if (k <= 0.001) return null;
|
||||||
|
const size = height * (p.size ?? 0.16);
|
||||||
|
const s = p.shake ? shake(frame, 2.5) : { x: 0, y: 0 };
|
||||||
|
const cross = p.crossed ? pop(frame, fps, (p.enterS ?? 0) + 0.5, 90) : 0;
|
||||||
|
return (
|
||||||
|
<div key={i} style={{ position: "absolute", left: p.x * width - size / 2 + s.x, top: p.y * height - size / 2 + s.y, width: size, height: size,
|
||||||
|
transform: `scale(${0.5 + 0.5 * k})`, opacity: Math.min(1, k * 1.5) }}>
|
||||||
|
{p.rings && <div style={{ position: "absolute", inset: "-60%" }}><Rings frame={frame} fps={fps} /></div>}
|
||||||
|
<Icon id={p.icon} />
|
||||||
|
{p.crossed && <div style={{ position: "absolute", inset: "-8%" }}><CrossOut k={cross} /></div>}
|
||||||
|
{p.label && <div style={{ position: "absolute", left: "50%", top: "-22%", transform: "translateX(-50%)" }}><TagLabel text={p.label} tone={p.tone} /></div>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
<LightLayer light={spec.light} palette={spec.palette} />
|
||||||
|
{(spec.texts ?? []).map((t, i) => <TextLayer key={i} t={t} frame={frame} fps={fps} />)}
|
||||||
|
</AbsoluteFill>
|
||||||
|
{spec.hud && <Hud hud={spec.hud} frame={frame} fps={fps} />}
|
||||||
|
{spec.words?.length ? <Captions words={spec.words} frame={frame} fps={fps} /> : null}
|
||||||
|
</AbsoluteFill>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
// Personagens "de recorte": peças rígidas (cabeça, cabelo, tronco, braços, pernas) que se mexem por inteiro —
|
||||||
|
// sem boca sincronizada, como na referência. Multidão = silhuetas.
|
||||||
|
import React from "react";
|
||||||
|
import { COLORS } from "./colors";
|
||||||
|
import { rng } from "./random";
|
||||||
|
import type { Crowd, Person } from "./spec";
|
||||||
|
|
||||||
|
/** Pessoa em pé num viewBox 200×420; (0,0) do grupo = pés no centro. */
|
||||||
|
export function PersonFigure({ p, frame, fps }: { p: Person; frame: number; fps: number }) {
|
||||||
|
const skin = p.skin ?? "#c98a5e";
|
||||||
|
const outfit = p.outfit ?? "#9b7be0";
|
||||||
|
const hair = p.hairColor ?? "#e8e8ee";
|
||||||
|
const sway = Math.sin(frame / (fps * 0.9)) * 1.5;
|
||||||
|
const arm = p.pointing ? -70 + Math.sin(frame / (fps * 0.5)) * 4 : 6 + Math.sin(frame / fps) * 2;
|
||||||
|
return (
|
||||||
|
<svg viewBox="0 0 200 420" width="100%" height="100%" overflow="visible">
|
||||||
|
<g transform={`rotate(${sway} 100 420)`}>
|
||||||
|
<rect x={74} y={300} width={18} height={115} rx={6} fill={COLORS.ink} />
|
||||||
|
<rect x={108} y={300} width={18} height={115} rx={6} fill={COLORS.ink} />
|
||||||
|
<path d="M60 150 Q100 130 140 150 L156 320 Q100 334 44 320 Z" fill={outfit} />
|
||||||
|
{[0, 1, 2, 3, 4, 5].map((i) => <circle key={i} cx={70 + (i % 3) * 30} cy={190 + Math.floor(i / 3) * 70} r={4} fill="#ffffff" opacity={0.55} />)}
|
||||||
|
<g transform={`rotate(${arm} 142 160)`}>
|
||||||
|
<rect x={136} y={156} width={16} height={110} rx={8} fill={outfit} />
|
||||||
|
<circle cx={144} cy={270} r={10} fill={skin} />
|
||||||
|
</g>
|
||||||
|
<g transform={`rotate(${-6 - Math.sin(frame / fps) * 2} 58 160)`}>
|
||||||
|
<rect x={48} y={156} width={16} height={110} rx={8} fill={outfit} />
|
||||||
|
<circle cx={56} cy={270} r={10} fill={skin} />
|
||||||
|
</g>
|
||||||
|
<rect x={90} y={118} width={20} height={26} fill={skin} />
|
||||||
|
<circle cx={100} cy={92} r={40} fill={skin} />
|
||||||
|
{p.hair === "bun" && <><circle cx={100} cy={46} r={20} fill={hair} /><path d="M60 88 Q100 40 140 88 Q140 64 100 56 Q60 64 60 88" fill={hair} /></>}
|
||||||
|
{(p.hair ?? "short") === "short" && <path d="M58 90 Q60 46 100 48 Q142 46 142 90 Q132 64 100 64 Q70 64 58 90" fill={hair} />}
|
||||||
|
{p.glasses && (
|
||||||
|
<g fill="none" stroke={COLORS.ink} strokeWidth={4}>
|
||||||
|
<circle cx={84} cy={92} r={11} /><circle cx={116} cy={92} r={11} /><line x1={95} y1={92} x2={105} y2={92} />
|
||||||
|
</g>
|
||||||
|
)}
|
||||||
|
<circle cx={84} cy={93} r={4} fill={COLORS.ink} />
|
||||||
|
<circle cx={116} cy={93} r={4} fill={COLORS.ink} />
|
||||||
|
<path d="M88 112 Q100 118 112 112" stroke={COLORS.ink} strokeWidth={4} fill="none" strokeLinecap="round" />
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fila de silhuetas pretas (multidão no portão). */
|
||||||
|
export function CrowdFigure({ c, frame }: { c: Crowd; frame: number }) {
|
||||||
|
const rand = rng(c.count * 31 + 3);
|
||||||
|
const people = Array.from({ length: c.count }, (_, i) => ({ x: (i + 0.5) / c.count, h: 0.8 + rand() * 0.35, p: rand() * 6 }));
|
||||||
|
return (
|
||||||
|
<svg viewBox="0 0 1000 300" width="100%" height="100%" preserveAspectRatio="none" overflow="visible">
|
||||||
|
{people.map((m, i) => {
|
||||||
|
const bob = Math.sin(frame / 14 + m.p) * 3;
|
||||||
|
const x = m.x * 1000;
|
||||||
|
const h = 260 * m.h;
|
||||||
|
return (
|
||||||
|
<g key={i} transform={`translate(${x} ${300 + bob})`} fill="#06070f">
|
||||||
|
<rect x={-26} y={-h * 0.62} width={52} height={h * 0.62} rx={18} />
|
||||||
|
<circle cx={0} cy={-h * 0.75} r={h * 0.13} />
|
||||||
|
</g>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
// Personagem do estilo Cartoon montado por PEÇAS (não é desenho pronto): o mesmo personagem sai igual em
|
||||||
|
// qualquer cena e história, mudando só expressão, pose e o que tem na mão. Guardado na biblioteca de
|
||||||
|
// personagens (assets/characters/<id>/character.json) e copiado no spec de cada trecho.
|
||||||
|
|
||||||
|
export const BUILDS = ["slim", "average", "heavy"] as const;
|
||||||
|
export const HAIR_STYLES = ["short", "side", "bun", "long", "curly", "spiky", "bald", "cap"] as const;
|
||||||
|
export const BEARD_STYLES = ["none", "stubble", "mustache", "full", "goatee"] as const;
|
||||||
|
export const GLASSES = ["none", "round", "square", "sun"] as const;
|
||||||
|
export const BROWS = ["thin", "thick"] as const;
|
||||||
|
export const TOP_STYLES = ["shirt", "jacket", "hoodie", "dress", "uniform"] as const;
|
||||||
|
export const BOTTOM_STYLES = ["pants", "shorts", "skirt"] as const;
|
||||||
|
export const EXPRESSIONS = ["neutral", "happy", "sad", "worried", "angry", "surprised", "scared"] as const;
|
||||||
|
export const POSES = ["stand", "point", "wave", "hold", "arms_up", "shrug", "think"] as const;
|
||||||
|
|
||||||
|
export type Expression = (typeof EXPRESSIONS)[number];
|
||||||
|
export type Pose = (typeof POSES)[number];
|
||||||
|
|
||||||
|
export type CharacterLook = {
|
||||||
|
build: (typeof BUILDS)[number];
|
||||||
|
/** Altura relativa (0,85 a 1,15). Criança ≈ 0,8 é aceito também. */
|
||||||
|
height: number;
|
||||||
|
skin: string;
|
||||||
|
hair: { style: (typeof HAIR_STYLES)[number]; color: string };
|
||||||
|
beard: { style: (typeof BEARD_STYLES)[number]; color: string };
|
||||||
|
glasses: (typeof GLASSES)[number];
|
||||||
|
brows: (typeof BROWS)[number];
|
||||||
|
top: { style: (typeof TOP_STYLES)[number]; color: string; accent?: string };
|
||||||
|
bottom: { style: (typeof BOTTOM_STYLES)[number]; color: string };
|
||||||
|
shoes: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Ficha do personagem na biblioteca. `kind: "3d"` aponta para a pessoa articulada da Godot (godot/kits). */
|
||||||
|
export type Character = {
|
||||||
|
schemaVersion: 1;
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
/** Texto curto que aparece na etiqueta (ex.: "Engenheiro de minas · 58 anos"). */
|
||||||
|
caption?: string;
|
||||||
|
description?: string;
|
||||||
|
kind: "cartoon" | "3d";
|
||||||
|
look: CharacterLook;
|
||||||
|
/** Só kind "3d": parâmetros da pessoa articulada da Godot. */
|
||||||
|
godot?: Record<string, unknown>;
|
||||||
|
createdAt?: string;
|
||||||
|
updatedAt?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const DEFAULT_LOOK: CharacterLook = {
|
||||||
|
build: "average", height: 1, skin: "#c98a5e",
|
||||||
|
hair: { style: "short", color: "#3a2a1e" }, beard: { style: "none", color: "#3a2a1e" },
|
||||||
|
glasses: "none", brows: "thin",
|
||||||
|
top: { style: "shirt", color: "#4f7a4a", accent: "#e8b13a" }, bottom: { style: "pants", color: "#2b3350" }, shoes: "#1b1b22",
|
||||||
|
};
|
||||||
|
|
||||||
|
const HEX = /^#[0-9a-f]{6}$/i;
|
||||||
|
const one = <T extends readonly string[]>(list: T, v: unknown): v is T[number] => typeof v === "string" && list.includes(v);
|
||||||
|
|
||||||
|
/** Confere a aparência e devolve os problemas (vazio = ok). */
|
||||||
|
export function validateLook(look: unknown): string[] {
|
||||||
|
const l = look as Partial<CharacterLook> | null;
|
||||||
|
if (!l || typeof l !== "object") return ["look precisa ser um objeto"];
|
||||||
|
const errors: string[] = [];
|
||||||
|
if (!one(BUILDS, l.build)) errors.push(`build: ${BUILDS.join("|")}`);
|
||||||
|
if (typeof l.height !== "number" || !(l.height >= 0.6 && l.height <= 1.2)) errors.push("height entre 0,6 e 1,2");
|
||||||
|
for (const [k, v] of [["skin", l.skin], ["hair.color", l.hair?.color], ["beard.color", l.beard?.color], ["top.color", l.top?.color],
|
||||||
|
["bottom.color", l.bottom?.color], ["shoes", l.shoes]] as const) {
|
||||||
|
if (typeof v !== "string" || !HEX.test(v)) errors.push(`${k}: cor #rrggbb`);
|
||||||
|
}
|
||||||
|
if (l.top?.accent !== undefined && !HEX.test(l.top.accent)) errors.push("top.accent: cor #rrggbb");
|
||||||
|
if (!one(HAIR_STYLES, l.hair?.style)) errors.push(`hair.style: ${HAIR_STYLES.join("|")}`);
|
||||||
|
if (!one(BEARD_STYLES, l.beard?.style)) errors.push(`beard.style: ${BEARD_STYLES.join("|")}`);
|
||||||
|
if (!one(GLASSES, l.glasses)) errors.push(`glasses: ${GLASSES.join("|")}`);
|
||||||
|
if (!one(BROWS, l.brows)) errors.push(`brows: ${BROWS.join("|")}`);
|
||||||
|
if (!one(TOP_STYLES, l.top?.style)) errors.push(`top.style: ${TOP_STYLES.join("|")}`);
|
||||||
|
if (!one(BOTTOM_STYLES, l.bottom?.style)) errors.push(`bottom.style: ${BOTTOM_STYLES.join("|")}`);
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const isExpression = (v: unknown): v is Expression => one(EXPRESSIONS, v);
|
||||||
|
export const isPose = (v: unknown): v is Pose => one(POSES, v);
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
// Cores e nomes de fonte do estilo Cartoon (vetor chapado). Sem Remotion: o painel também usa.
|
||||||
|
import type { TimeOfDay, Tone } from "./spec";
|
||||||
|
|
||||||
|
export const SKY: Record<TimeOfDay, [string, string]> = {
|
||||||
|
night: ["#0b0e22", "#1c2147"],
|
||||||
|
dawn: ["#2a2c5c", "#8a6a9c"],
|
||||||
|
day: ["#5aa9e6", "#bfe3f5"],
|
||||||
|
};
|
||||||
|
export const COLORS = {
|
||||||
|
ground: "#14172e",
|
||||||
|
road: "#1a1d38",
|
||||||
|
roadLine: "#3a3f6b",
|
||||||
|
house: ["#3b3f74", "#34386a", "#2f3362", "#41467e"],
|
||||||
|
houseFar: "#2a2d57",
|
||||||
|
roof: "#272a52",
|
||||||
|
window: "#1b1d3a",
|
||||||
|
light: "#ffc94a",
|
||||||
|
glow: "rgba(255, 190, 70, 0.35)",
|
||||||
|
text: "#ffffff",
|
||||||
|
key: "#ffcf3f",
|
||||||
|
danger: "#ff4d4d",
|
||||||
|
ok: "#3ddc84",
|
||||||
|
ink: "#0c0d1a",
|
||||||
|
blueprint: "#10245a",
|
||||||
|
grid: "rgba(120, 160, 255, 0.12)",
|
||||||
|
};
|
||||||
|
export const TONE_BG: Record<Tone, string> = { info: "#ffcf3f", danger: "#ff4d4d", ok: "#3ddc84" };
|
||||||
|
export const TONE_FG: Record<Tone, string> = { info: "#141414", danger: "#ffffff", ok: "#0c2a18" };
|
||||||
|
|
||||||
|
export const FONT_CAPTION = "CartoonAnton";
|
||||||
|
export const FONT_LABEL = "CartoonBebas";
|
||||||
|
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
// Ícones chapados (viewBox 100×100). Formas simples, sem contorno, na paleta do estilo.
|
||||||
|
import React from "react";
|
||||||
|
import { COLORS } from "./colors";
|
||||||
|
import type { IconId } from "./spec";
|
||||||
|
|
||||||
|
const INK = COLORS.ink;
|
||||||
|
|
||||||
|
const DRAW: Record<IconId, React.ReactNode> = {
|
||||||
|
house: (<>
|
||||||
|
<polygon points="8,46 50,12 92,46" fill={COLORS.roof} />
|
||||||
|
<rect x={16} y={44} width={68} height={48} fill={COLORS.house[3]} />
|
||||||
|
<rect x={24} y={54} width={14} height={14} rx={2} fill={COLORS.light} />
|
||||||
|
<rect x={62} y={54} width={14} height={14} rx={2} fill={COLORS.light} />
|
||||||
|
<rect x={44} y={66} width={12} height={26} fill={COLORS.window} />
|
||||||
|
</>),
|
||||||
|
generator: (<>
|
||||||
|
<rect x={8} y={30} width={84} height={56} rx={8} fill="#2a2d3c" />
|
||||||
|
<rect x={14} y={22} width={58} height={16} rx={6} fill="#e8463d" />
|
||||||
|
<rect x={16} y={44} width={34} height={34} rx={4} fill="#4a4e63" />
|
||||||
|
{[0, 1, 2, 3, 4].map((i) => <rect key={i} x={19} y={48 + i * 6} width={28} height={3} fill="#2a2d3c" />)}
|
||||||
|
<circle cx={64} cy={52} r={4} fill="#11121a" /><circle cx={76} cy={52} r={4} fill="#11121a" />
|
||||||
|
<circle cx={70} cy={68} r={3} fill={COLORS.ok} />
|
||||||
|
<rect x={10} y={86} width={14} height={6} fill="#11121a" /><rect x={76} y={86} width={14} height={6} fill="#11121a" />
|
||||||
|
</>),
|
||||||
|
fuel: (<>
|
||||||
|
<rect x={20} y={22} width={60} height={72} rx={8} fill="#c8352f" />
|
||||||
|
<rect x={26} y={50} width={48} height={38} rx={4} fill="#e6b347" />
|
||||||
|
<path d="M30 22 L30 12 L60 12 L60 22" stroke="#c8352f" strokeWidth={6} fill="none" />
|
||||||
|
<rect x={66} y={8} width={12} height={14} fill="#c8352f" />
|
||||||
|
<path d="M30 56 L70 84 M70 56 L30 84" stroke="#c8352f" strokeWidth={3} />
|
||||||
|
</>),
|
||||||
|
battery: (<>
|
||||||
|
<rect x={28} y={14} width={44} height={80} rx={8} fill="#1d2b2a" stroke={COLORS.ok} strokeWidth={4} />
|
||||||
|
<rect x={40} y={6} width={20} height={10} rx={3} fill={COLORS.ok} />
|
||||||
|
<polygon points="54,30 38,58 50,58 46,80 62,50 50,50" fill={COLORS.ok} />
|
||||||
|
</>),
|
||||||
|
phone: (<>
|
||||||
|
<rect x={30} y={8} width={40} height={84} rx={8} fill="#15161f" />
|
||||||
|
<rect x={35} y={16} width={30} height={64} rx={3} fill="#2c3150" />
|
||||||
|
<rect x={42} y={40} width={16} height={8} rx={2} fill={COLORS.danger} />
|
||||||
|
</>),
|
||||||
|
door: (<>
|
||||||
|
<rect x={24} y={6} width={52} height={90} rx={3} fill="#4a2f22" />
|
||||||
|
<rect x={30} y={14} width={40} height={34} rx={2} fill="#3c251b" />
|
||||||
|
<rect x={30} y={54} width={40} height={34} rx={2} fill="#3c251b" />
|
||||||
|
<circle cx={66} cy={56} r={3.5} fill="#e6c27a" />
|
||||||
|
</>),
|
||||||
|
eye: (<>
|
||||||
|
<path d="M6 50 Q50 10 94 50 Q50 90 6 50 Z" fill="#f4f6ff" />
|
||||||
|
<circle cx={50} cy={50} r={20} fill="#2c3466" /><circle cx={50} cy={50} r={9} fill={INK} /><circle cx={56} cy={44} r={4} fill="#fff" />
|
||||||
|
</>),
|
||||||
|
bulb: (<>
|
||||||
|
<circle cx={50} cy={40} r={28} fill={COLORS.light} />
|
||||||
|
<rect x={38} y={64} width={24} height={16} rx={3} fill="#9aa0b8" /><rect x={42} y={80} width={16} height={8} rx={3} fill="#6c7190" />
|
||||||
|
</>),
|
||||||
|
solar: (<>
|
||||||
|
<polygon points="10,70 30,30 92,30 72,70" fill="#2b4fb8" />
|
||||||
|
<path d="M30 50 L82 50 M27 40 L87 40 M24 60 L77 60 M45 30 L35 70 M61 30 L51 70 M77 30 L67 70" stroke="#8fb0ff" strokeWidth={2} />
|
||||||
|
<rect x={46} y={70} width={6} height={22} fill="#6c7190" />
|
||||||
|
</>),
|
||||||
|
warning: (<>
|
||||||
|
<polygon points="50,8 94,88 6,88" fill={COLORS.key} />
|
||||||
|
<rect x={46} y={34} width={8} height={30} rx={3} fill={INK} /><circle cx={50} cy={74} r={5} fill={INK} />
|
||||||
|
</>),
|
||||||
|
money: (<>
|
||||||
|
<rect x={8} y={26} width={84} height={48} rx={6} fill="#3a9e5f" />
|
||||||
|
<circle cx={50} cy={50} r={14} fill="#2b7a49" /><text x={50} y={57} textAnchor="middle" fontSize={20} fontWeight={700} fill="#d9f5e3">$</text>
|
||||||
|
</>),
|
||||||
|
clock: (<>
|
||||||
|
<circle cx={50} cy={50} r={40} fill="#f4f6ff" /><circle cx={50} cy={50} r={34} fill="#232850" />
|
||||||
|
<rect x={48} y={24} width={4} height={28} rx={2} fill="#fff" /><rect x={48} y={48} width={22} height={4} rx={2} fill={COLORS.key} />
|
||||||
|
</>),
|
||||||
|
};
|
||||||
|
|
||||||
|
export function Icon({ id }: { id: IconId }) {
|
||||||
|
return <svg viewBox="0 0 100 100" width="100%" height="100%" overflow="visible">{DRAW[id]}</svg>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import { registerRoot } from "remotion";
|
||||||
|
import { Root } from "./Root";
|
||||||
|
|
||||||
|
registerRoot(Root);
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
// Camadas por cima da cena: etiqueta, onomatopeia, contador, ondas de som, X vermelho, painel do topo (HUD) e a
|
||||||
|
// legenda palavra por palavra (cada palavra entra pequena e cresce; palavra-chave em amarelo, perigo em vermelho).
|
||||||
|
import React from "react";
|
||||||
|
import { spring } from "remotion";
|
||||||
|
import { COLORS, FONT_CAPTION, FONT_LABEL, TONE_BG, TONE_FG } from "./theme";
|
||||||
|
import type { ShotSpec, TextItem, Tone, Word } from "./spec";
|
||||||
|
|
||||||
|
/** 0 → 1 com mola, a partir de `startS` (antes disso, 0). */
|
||||||
|
export function pop(frame: number, fps: number, startS = 0, stiffness = 220): number {
|
||||||
|
const f = frame - Math.round(startS * fps);
|
||||||
|
return f < 0 ? 0 : spring({ frame: f, fps, config: { damping: 13, stiffness, mass: 0.6 } });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tremor determinístico de ±amp px (vibração do gerador, onomatopeia). */
|
||||||
|
export function shake(frame: number, amp = 3): { x: number; y: number } {
|
||||||
|
return { x: Math.sin(frame * 12.9898) * amp, y: Math.cos(frame * 78.233) * amp * 0.7 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const at = (x: number, y: number): React.CSSProperties => ({ position: "absolute", left: `${x * 100}%`, top: `${y * 100}%` });
|
||||||
|
|
||||||
|
export function TagLabel({ text, tone = "info", size = 3.6 }: { text: string; tone?: Tone; size?: number }) {
|
||||||
|
return (
|
||||||
|
<span style={{ fontFamily: FONT_LABEL, fontSize: `${size}cqw`, letterSpacing: "0.04em", lineHeight: 1, whiteSpace: "nowrap",
|
||||||
|
padding: "0.25em 0.5em 0.15em", borderRadius: "0.25em", background: TONE_BG[tone], color: TONE_FG[tone],
|
||||||
|
boxShadow: "0 0.15em 0 rgba(0,0,0,0.35)" }}>
|
||||||
|
{text.toUpperCase()}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TextLayer({ t, frame, fps }: { t: TextItem; frame: number; fps: number }) {
|
||||||
|
const k = pop(frame, fps, t.atS ?? 0);
|
||||||
|
if (k <= 0.001) return null;
|
||||||
|
const base = { ...at(t.x, t.y), transform: `translate(-50%, -50%) rotate(${t.rotate ?? 0}deg) scale(${0.4 + 0.6 * k})`, opacity: Math.min(1, k * 1.4) };
|
||||||
|
if (t.kind === "tag") return <div style={base}><TagLabel text={t.text} tone={t.tone} /></div>;
|
||||||
|
if (t.kind === "counter") {
|
||||||
|
return (
|
||||||
|
<div style={{ ...base, textAlign: "center", border: "0.35cqw solid #fff", borderRadius: "1.4cqw", padding: "0.8cqw 2.6cqw",
|
||||||
|
background: "rgba(10,12,28,0.85)" }}>
|
||||||
|
<div style={{ fontFamily: FONT_LABEL, fontSize: "2.6cqw", color: "#c9cbe0", letterSpacing: "0.08em" }}>{t.text.toUpperCase()}</div>
|
||||||
|
<div style={{ fontFamily: FONT_CAPTION, fontSize: "8cqw", color: "#fff", lineHeight: 1 }}>{t.value ?? ""}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const s = t.kind === "onomatopoeia" ? shake(frame, 4) : { x: 0, y: 0 };
|
||||||
|
const color = t.tone === "danger" ? COLORS.danger : t.kind === "big" ? "#ffffff" : COLORS.key;
|
||||||
|
return (
|
||||||
|
<div style={{ ...base, transform: `${base.transform} translate(${s.x}px, ${s.y}px)`, fontFamily: FONT_CAPTION, color,
|
||||||
|
fontSize: t.kind === "big" ? "12cqw" : "9cqw", whiteSpace: "nowrap", WebkitTextStroke: "0.35cqw #121326",
|
||||||
|
paintOrder: "stroke fill", textShadow: "0 0.6cqw 0 rgba(0,0,0,0.35)" }}>
|
||||||
|
{t.text.toUpperCase()}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Anéis que crescem e somem em volta de (x, y) — barulho, luz chamando atenção. */
|
||||||
|
export function Rings({ frame, fps, color = COLORS.key }: { frame: number; fps: number; color?: string }) {
|
||||||
|
const period = fps * 1.3;
|
||||||
|
return (
|
||||||
|
<svg viewBox="-100 -100 200 200" width="100%" height="100%" overflow="visible" style={{ position: "absolute", inset: 0 }}>
|
||||||
|
{[0, 1, 2].map((i) => {
|
||||||
|
const p = ((frame + (i * period) / 3) % period) / period;
|
||||||
|
return <circle key={i} r={30 + p * 70} fill="none" stroke={color} strokeWidth={2.5} opacity={(1 - p) * 0.8} />;
|
||||||
|
})}
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** X vermelho que se desenha por cima de algo ("não faça"). */
|
||||||
|
export function CrossOut({ k }: { k: number }) {
|
||||||
|
const len = 140 * Math.min(1, k);
|
||||||
|
return (
|
||||||
|
<svg viewBox="0 0 100 100" width="100%" height="100%" overflow="visible" style={{ position: "absolute", inset: 0 }}>
|
||||||
|
<line x1={0} y1={0} x2={len / 1.41} y2={len / 1.41} stroke={COLORS.danger} strokeWidth={9} strokeLinecap="round" />
|
||||||
|
{k > 0.5 && <line x1={100} y1={0} x2={100 - ((k - 0.5) * 2 * 140) / 1.41} y2={((k - 0.5) * 2 * 140) / 1.41} stroke={COLORS.danger} strokeWidth={9} strokeLinecap="round" />}
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Hud({ hud, frame, fps }: { hud: NonNullable<ShotSpec["hud"]>; frame: number; fps: number }) {
|
||||||
|
let clock = hud.clock;
|
||||||
|
if (clock && /^\d{1,2}:\d{2}$/.test(clock) && hud.clockMinutesPerSecond) {
|
||||||
|
const [h, m] = clock.split(":").map(Number);
|
||||||
|
const total = (h * 60 + m + Math.floor((frame / fps) * hud.clockMinutesPerSecond)) % (24 * 60);
|
||||||
|
clock = `${String(Math.floor(total / 60)).padStart(2, "0")}:${String(total % 60).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div style={{ position: "absolute", top: "5.5%", left: 0, right: 0, display: "flex", justifyContent: "center", alignItems: "center",
|
||||||
|
gap: "1.4cqw", fontFamily: FONT_LABEL }}>
|
||||||
|
<span style={{ background: COLORS.danger, color: "#fff", fontSize: "3.4cqw", padding: "0.2em 0.5em 0.1em", borderRadius: "0.25em" }}>⚡ {hud.badge.toUpperCase()}</span>
|
||||||
|
<span style={{ color: "#fff", fontSize: "4.2cqw" }}>{hud.label.toUpperCase()}</span>
|
||||||
|
{clock && <span style={{ background: "#0d0f1f", color: COLORS.key, fontSize: "3.4cqw", padding: "0.2em 0.45em 0.1em", borderRadius: "0.25em",
|
||||||
|
border: "0.25cqw solid #3a3f6b" }}>{clock}</span>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Agrupa as palavras em blocos de até 3 (quebra também depois de pontuação), como a legenda da referência. */
|
||||||
|
export function captionChunks(words: Word[]): Word[][] {
|
||||||
|
const chunks: Word[][] = [];
|
||||||
|
let current: Word[] = [];
|
||||||
|
for (const w of words) {
|
||||||
|
current.push(w);
|
||||||
|
if (current.length >= 3 || /[.,!?;:…]$/.test(w.text)) { chunks.push(current); current = []; }
|
||||||
|
}
|
||||||
|
if (current.length) chunks.push(current);
|
||||||
|
return chunks;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Captions({ words, frame, fps, y = 0.665 }: { words: Word[]; frame: number; fps: number; y?: number }) {
|
||||||
|
const t = frame / fps;
|
||||||
|
const chunks = captionChunks(words);
|
||||||
|
const chunk = chunks.find((c, i) => t >= c[0].startS && (i === chunks.length - 1 || t < chunks[i + 1][0].startS));
|
||||||
|
if (!chunk) return null;
|
||||||
|
const last = chunk[chunk.length - 1];
|
||||||
|
if (t > last.endS + 0.6) return null;
|
||||||
|
return (
|
||||||
|
<div style={{ position: "absolute", left: "6%", right: "6%", top: `${y * 100}%`, transform: "translateY(-50%)", display: "flex",
|
||||||
|
flexWrap: "wrap", justifyContent: "center", alignItems: "baseline", columnGap: "2.2cqw", fontFamily: FONT_CAPTION, lineHeight: 1.05 }}>
|
||||||
|
{chunk.filter((w) => t >= w.startS).map((w, i) => {
|
||||||
|
const k = pop(frame, fps, w.startS, 320);
|
||||||
|
const color = w.tone === "danger" ? COLORS.danger : w.tone === "key" ? COLORS.key : "#ffffff";
|
||||||
|
return (
|
||||||
|
<span key={i} style={{ fontSize: "8.4cqw", color, transform: `scale(${0.55 + 0.45 * k})`, display: "inline-block",
|
||||||
|
textShadow: "0 0.5cqw 0 rgba(0,0,0,0.55), 0 0 1.4cqw rgba(0,0,0,0.5)" }}>
|
||||||
|
{w.text.toUpperCase().replace(/[.,;:]$/, "")}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
// Lugares montados por PEÇAS (não há cenário pronto): paleta + céu/hora + chão + peças posicionadas por
|
||||||
|
// profundidade (z: 0 = frente, 1 = fundo). Parque de dia, cemitério na névoa, quarto à noite, bunker com foco
|
||||||
|
// de luz… tudo sai da mesma gramática. Espaço de desenho 1080×1920; chão começa em `horizon` (fração da altura).
|
||||||
|
import React from "react";
|
||||||
|
import { rng } from "./random";
|
||||||
|
import type { ShotSpec } from "./spec";
|
||||||
|
|
||||||
|
export const PALETTES = ["night", "sepia", "day", "dusk", "gray"] as const;
|
||||||
|
export type PaletteId = (typeof PALETTES)[number];
|
||||||
|
export const GROUNDS = ["grass", "street", "dirt", "floor", "sand", "water", "none"] as const;
|
||||||
|
export const ELEMENTS = ["tree", "deadtree", "pine", "bush", "rock", "mountain", "cloud", "bench", "lamp", "gravestone", "cross", "fence",
|
||||||
|
"house", "building", "car", "sign", "door", "window", "table", "bed", "shelf", "crate", "tent", "fire"] as const;
|
||||||
|
export type ElementKind = (typeof ELEMENTS)[number];
|
||||||
|
|
||||||
|
export type Place = {
|
||||||
|
ground: (typeof GROUNDS)[number];
|
||||||
|
/** Interno: parede no lugar do céu (quarto, bunker, loja). */
|
||||||
|
indoor?: boolean;
|
||||||
|
/** Linha do horizonte (fração da altura; padrão 0,56). */
|
||||||
|
horizon?: number;
|
||||||
|
fog?: boolean;
|
||||||
|
elements: { kind: ElementKind; x: number; z?: number; scale?: number; flip?: boolean; color?: string }[];
|
||||||
|
};
|
||||||
|
|
||||||
|
type Pal = { sky: [string, string]; wall: string; ground: Record<string, string>; far: string; near: string; ink: string; leaf: string; trunk: string; stone: string; light: string };
|
||||||
|
const P: Record<PaletteId, Pal> = {
|
||||||
|
night: { sky: ["#0b0e22", "#1c2147"], wall: "#2a2f4a", far: "#2a2d57", near: "#3b3f74", ink: "#0c0d1a", leaf: "#24445a", trunk: "#2b2338", stone: "#5a5f86", light: "#ffc94a",
|
||||||
|
ground: { grass: "#1d2e3a", street: "#1a1d38", dirt: "#2a2433", floor: "#22243a", sand: "#4a4560", water: "#152a4a" } },
|
||||||
|
sepia: { sky: ["#c9ad83", "#e8d6ae"], wall: "#7d6a55", far: "#a88f6e", near: "#6e5843", ink: "#2a2018", leaf: "#7b7a45", trunk: "#5a4330", stone: "#9b9387", light: "#ffd98a",
|
||||||
|
ground: { grass: "#8b8a52", street: "#6a5a4a", dirt: "#7a5a3c", floor: "#5e4c3c", sand: "#d2b886", water: "#6f8a8a" } },
|
||||||
|
day: { sky: ["#5aa9e6", "#cfeaf8"], wall: "#e9dcc5", far: "#9cc3d9", near: "#d98a5c", ink: "#22252e", leaf: "#4caf50", trunk: "#7a5232", stone: "#a9adb5", light: "#fff3b0",
|
||||||
|
ground: { grass: "#78c25a", street: "#8a8f99", dirt: "#b88a5a", floor: "#c9a77c", sand: "#f0d79a", water: "#3f9ad8" } },
|
||||||
|
dusk: { sky: ["#2a2c5c", "#e8946a"], wall: "#4a3a52", far: "#4c3f6e", near: "#6a4a62", ink: "#140f1c", leaf: "#2f4a3f", trunk: "#3a2a2a", stone: "#7a7090", light: "#ffcf7a",
|
||||||
|
ground: { grass: "#3a4a3a", street: "#3a3348", dirt: "#4a3530", floor: "#3c3040", sand: "#a87d6a", water: "#4a5a8a" } },
|
||||||
|
gray: { sky: ["#6f7680", "#b4b9bf"], wall: "#565b63", far: "#8a9098", near: "#5c6168", ink: "#1b1d21", leaf: "#5a6b55", trunk: "#4a4038", stone: "#9aa0a8", light: "#f2e6c8",
|
||||||
|
ground: { grass: "#5f6e55", street: "#4a4f57", dirt: "#5e5246", floor: "#45484f", sand: "#a8a08a", water: "#5a6f80" } },
|
||||||
|
};
|
||||||
|
export const palette = (id: PaletteId | undefined): Pal => P[id ?? "night"] ?? P.night;
|
||||||
|
|
||||||
|
const W = 1080;
|
||||||
|
const H = 1920;
|
||||||
|
|
||||||
|
function mix(a: string, b: string, k: number): string {
|
||||||
|
const pa = parseInt(a.slice(1), 16);
|
||||||
|
const pb = parseInt(b.slice(1), 16);
|
||||||
|
const ch = (s: number) => Math.round(((pa >> s) & 255) * (1 - k) + ((pb >> s) & 255) * k);
|
||||||
|
return `#${[16, 8, 0].map((s) => ch(s).toString(16).padStart(2, "0")).join("")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Uma peça desenhada com a base em (0,0), altura de referência ~300 px. */
|
||||||
|
function Element({ kind, pal, color, seed }: { kind: ElementKind; pal: Pal; color?: string; seed: number }) {
|
||||||
|
const r = rng(seed);
|
||||||
|
switch (kind) {
|
||||||
|
case "tree": return <g><rect x={-14} y={-150} width={28} height={150} fill={pal.trunk} /><circle cx={0} cy={-210} r={95} fill={color ?? pal.leaf} /><circle cx={-60} cy={-170} r={60} fill={color ?? pal.leaf} /><circle cx={62} cy={-175} r={62} fill={color ?? pal.leaf} /></g>;
|
||||||
|
case "pine": return <g><rect x={-12} y={-60} width={24} height={60} fill={pal.trunk} /><polygon points="0,-330 -90,-60 90,-60" fill={color ?? pal.leaf} /></g>;
|
||||||
|
case "deadtree": return <g stroke={color ?? pal.trunk} strokeLinecap="round" fill="none"><path d="M0 0 L0 -220" strokeWidth={26} /><path d="M0 -120 L-70 -200 M-40 -160 L-80 -150 M0 -170 L60 -250 M30 -210 L80 -215 M0 -220 L-20 -280" strokeWidth={12} /></g>;
|
||||||
|
case "bush": return <g fill={color ?? pal.leaf}><circle cx={-40} cy={-35} r={42} /><circle cx={10} cy={-50} r={52} /><circle cx={55} cy={-30} r={38} /></g>;
|
||||||
|
case "rock": return <path d="M-70 0 Q-80 -50 -30 -70 Q20 -90 60 -50 Q85 -20 70 0 Z" fill={color ?? pal.stone} />;
|
||||||
|
case "mountain": return <g><polygon points="-520,0 0,-520 520,0" fill={color ?? pal.far} /><polygon points="-110,-410 0,-520 110,-410 50,-430 0,-400 -50,-430" fill="#ffffff" opacity={0.6} /></g>;
|
||||||
|
case "cloud": return <g fill={color ?? "#ffffff"} opacity={0.85}><ellipse cx={0} cy={-40} rx={110} ry={40} /><circle cx={-40} cy={-70} r={45} /><circle cx={30} cy={-80} r={55} /></g>;
|
||||||
|
case "bench": return <g fill={color ?? "#8a5a3a"}><rect x={-110} y={-70} width={220} height={16} rx={4} /><rect x={-110} y={-120} width={220} height={14} rx={4} /><rect x={-95} y={-70} width={12} height={70} fill={pal.ink} /><rect x={83} y={-70} width={12} height={70} fill={pal.ink} /></g>;
|
||||||
|
case "lamp": return <g><rect x={-7} y={-420} width={14} height={420} fill={pal.ink} /><rect x={-36} y={-440} width={72} height={26} rx={8} fill={pal.ink} /><ellipse cx={0} cy={-408} rx={26} ry={8} fill={pal.light} /><path d="M-24 -408 L-140 0 L140 0 L24 -408 Z" fill={pal.light} opacity={0.08} /></g>;
|
||||||
|
case "gravestone": return <g><path d="M-55 0 L-55 -130 Q-55 -185 0 -185 Q55 -185 55 -130 L55 0 Z" fill={color ?? pal.stone} /><rect x={-28} y={-120} width={56} height={6} rx={3} fill={pal.ink} opacity={0.35} /><rect x={-22} y={-100} width={44} height={6} rx={3} fill={pal.ink} opacity={0.35} /></g>;
|
||||||
|
case "cross": return <g fill={color ?? pal.stone}><rect x={-12} y={-200} width={24} height={200} /><rect x={-60} y={-160} width={120} height={22} /></g>;
|
||||||
|
case "fence": return <g fill={color ?? pal.ink}>{Array.from({ length: 9 }, (_, i) => <rect key={i} x={-200 + i * 50} y={-130} width={14} height={130} />)}<rect x={-210} y={-110} width={430} height={10} /><rect x={-210} y={-50} width={430} height={10} /></g>;
|
||||||
|
case "house": return <g><polygon points="-150,-180 0,-290 150,-180" fill={pal.ink} opacity={0.6} /><rect x={-140} y={-180} width={280} height={180} fill={color ?? pal.near} /><rect x={-110} y={-140} width={50} height={50} rx={4} fill={pal.light} opacity={r() > 0.5 ? 1 : 0.15} /><rect x={60} y={-140} width={50} height={50} rx={4} fill={pal.light} opacity={r() > 0.5 ? 1 : 0.15} /><rect x={-25} y={-100} width={50} height={100} fill={pal.ink} opacity={0.7} /></g>;
|
||||||
|
case "building": {
|
||||||
|
const floors = 4 + Math.floor(r() * 4);
|
||||||
|
return <g><rect x={-120} y={-floors * 80} width={240} height={floors * 80} fill={color ?? pal.far} />{Array.from({ length: floors * 3 }, (_, i) => <rect key={i} x={-95 + (i % 3) * 70} y={-floors * 80 + 20 + Math.floor(i / 3) * 80} width={44} height={40} fill={pal.light} opacity={r() > 0.7 ? 0.9 : 0.12} />)}</g>;
|
||||||
|
}
|
||||||
|
case "car": return <g><path d="M-150 -40 L-150 -90 Q-140 -110 -100 -112 L-60 -160 L70 -160 L110 -112 L150 -100 L150 -40 Z" fill={color ?? "#c8443a"} /><rect x={-50} y={-150} width={50} height={36} fill="#cfe3f3" opacity={0.85} /><rect x={8} y={-150} width={52} height={36} fill="#cfe3f3" opacity={0.85} /><circle cx={-90} cy={-35} r={32} fill={pal.ink} /><circle cx={95} cy={-35} r={32} fill={pal.ink} /></g>;
|
||||||
|
case "sign": return <g><rect x={-6} y={-220} width={12} height={220} fill={pal.ink} /><rect x={-90} y={-260} width={180} height={70} rx={8} fill={color ?? "#2f6d3a"} stroke="#ffffff" strokeWidth={5} /></g>;
|
||||||
|
case "door": return <g><rect x={-80} y={-330} width={160} height={330} rx={4} fill={color ?? "#4a2f22"} /><rect x={-60} y={-305} width={120} height={130} rx={3} fill="#000000" opacity={0.15} /><rect x={-60} y={-155} width={120} height={130} rx={3} fill="#000000" opacity={0.15} /><circle cx={52} cy={-165} r={9} fill="#e6c27a" /></g>;
|
||||||
|
case "window": return <g><rect x={-120} y={-260} width={240} height={200} rx={6} fill={pal.ink} /><rect x={-108} y={-248} width={216} height={176} fill={color ?? mix(pal.sky[0], pal.sky[1], 0.5)} /><rect x={-4} y={-248} width={8} height={176} fill={pal.ink} /><rect x={-108} y={-164} width={216} height={8} fill={pal.ink} /></g>;
|
||||||
|
case "table": return <g fill={color ?? "#7a5232"}><rect x={-140} y={-130} width={280} height={20} rx={4} /><rect x={-120} y={-110} width={18} height={110} /><rect x={102} y={-110} width={18} height={110} /></g>;
|
||||||
|
case "bed": return <g><rect x={-170} y={-90} width={340} height={60} rx={10} fill={color ?? "#5a6aa8"} /><rect x={-170} y={-150} width={24} height={150} fill={pal.trunk} /><rect x={-140} y={-120} width={90} height={34} rx={12} fill="#eeeeee" /><rect x={146} y={-110} width={24} height={110} fill={pal.trunk} /></g>;
|
||||||
|
case "shelf": return <g><rect x={-120} y={-360} width={240} height={360} fill={color ?? pal.trunk} />{[0, 1, 2, 3].map((i) => <g key={i}><rect x={-108} y={-340 + i * 88} width={216} height={70} fill="#000000" opacity={0.25} />{[0, 1, 2, 3, 4].map((j) => <rect key={j} x={-100 + j * 42} y={-330 + i * 88 + (r() * 14)} width={30} height={56 - (r() * 14)} rx={3} fill={["#e8463d", "#f2c230", "#4fb0e8", "#5cc48a", "#e8e8ee"][(i + j) % 5]} />)}</g>)}</g>;
|
||||||
|
case "crate": return <g><rect x={-70} y={-140} width={140} height={140} fill={color ?? "#a0743f"} /><path d="M-70 -140 L70 0 M70 -140 L-70 0" stroke="#6e4e28" strokeWidth={10} /><rect x={-70} y={-140} width={140} height={140} fill="none" stroke="#6e4e28" strokeWidth={10} /></g>;
|
||||||
|
case "tent": return <g><polygon points="-170,0 0,-220 170,0" fill={color ?? "#d9773a"} /><polygon points="-40,0 0,-120 40,0" fill={pal.ink} opacity={0.6} /></g>;
|
||||||
|
case "fire": return <g><rect x={-60} y={-18} width={120} height={18} rx={6} fill={pal.trunk} /><path d="M-40 -18 Q-50 -80 -10 -120 Q-5 -80 20 -70 Q30 -110 10 -150 Q70 -100 45 -18 Z" fill="#ff8a2a" /><path d="M-15 -18 Q-20 -60 5 -80 Q10 -50 25 -45 Q30 -30 20 -18 Z" fill="#ffd34a" /></g>;
|
||||||
|
default: return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PlaceBackground({ spec, frame }: { spec: ShotSpec; frame: number }) {
|
||||||
|
const place = spec.place!;
|
||||||
|
const pal = palette(spec.palette);
|
||||||
|
const horizon = (place.horizon ?? 0.56) * H;
|
||||||
|
const ground = place.ground === "none" ? null : pal.ground[place.ground];
|
||||||
|
const elements = [...place.elements].map((e, i) => ({ ...e, i, z: e.z ?? 0.3 })).sort((a, b) => b.z - a.z);
|
||||||
|
const rand = rng(spec.seed + 13);
|
||||||
|
const stars = !place.indoor && (spec.palette ?? "night") === "night"
|
||||||
|
? Array.from({ length: 60 }, () => ({ x: rand() * W, y: rand() * horizon * 0.8, r: 1 + rand() * 2, p: rand() * 6 })) : [];
|
||||||
|
return (
|
||||||
|
<svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" preserveAspectRatio="xMidYMid slice">
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="placeSky" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor={pal.sky[0]} /><stop offset="1" stopColor={pal.sky[1]} /></linearGradient>
|
||||||
|
<linearGradient id="placeFog" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#ffffff" stopOpacity={0} /><stop offset="1" stopColor="#d8dce6" stopOpacity={0.35} /></linearGradient>
|
||||||
|
</defs>
|
||||||
|
<rect width={W} height={H} fill={place.indoor ? pal.wall : "url(#placeSky)"} />
|
||||||
|
{stars.map((s, i) => <circle key={i} cx={s.x} cy={s.y} r={s.r} fill="#fff" opacity={0.3 + 0.3 * Math.sin(frame / 12 + s.p)} />)}
|
||||||
|
{!place.indoor && (spec.palette ?? "night") === "night" && <circle cx={W * 0.78} cy={H * 0.12} r={40} fill="#f4ecc8" />}
|
||||||
|
{!place.indoor && (spec.palette === "day" || spec.palette === "sepia") && <circle cx={W * 0.8} cy={H * 0.1} r={60} fill={pal.light} opacity={0.9} />}
|
||||||
|
{place.indoor && <rect x={0} y={horizon - 18} width={W} height={18} fill={pal.ink} opacity={0.25} />}
|
||||||
|
{ground && <rect x={0} y={horizon} width={W} height={H - horizon} fill={ground} />}
|
||||||
|
{place.ground === "street" && Array.from({ length: 8 }, (_, i) => <rect key={i} x={i * 150 - 40} y={horizon + (H - horizon) * 0.32} width={90} height={9} rx={4} fill="#ffffff" opacity={0.25} />)}
|
||||||
|
{elements.map((e) => {
|
||||||
|
// Profundidade: mais ao fundo = mais perto do horizonte, menor e mais apagado (névoa/atmosfera).
|
||||||
|
const baseY = e.kind === "cloud" ? horizon * (0.15 + 0.5 * e.z) : horizon + (1 - e.z) * (H * 0.72 - horizon);
|
||||||
|
const scale = (e.scale ?? 1) * (1 - e.z * 0.62) * 1.15;
|
||||||
|
const fade = e.kind === "cloud" ? 0 : e.z * (place.fog ? 0.7 : 0.35);
|
||||||
|
return (
|
||||||
|
<g key={e.i} transform={`translate(${e.x * W} ${baseY}) scale(${e.flip ? -scale : scale} ${scale})`} opacity={1 - fade * 0.3}>
|
||||||
|
<Element kind={e.kind} pal={pal} color={e.color ?? (fade > 0.05 && e.kind !== "fire" ? undefined : undefined)} seed={spec.seed + e.i * 17} />
|
||||||
|
</g>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{place.fog && <rect x={0} y={horizon - H * 0.15} width={W} height={H * 0.5} fill="url(#placeFog)" />}
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Foco de luz vindo do teto (bunker, interrogatório) ou vinheta de anoitecer, por cima de tudo. */
|
||||||
|
export function LightLayer({ light, palette: id }: { light: ShotSpec["light"]; palette?: PaletteId }) {
|
||||||
|
if (!light || light === "none") return null;
|
||||||
|
const pal = palette(id);
|
||||||
|
if (light === "vignette") {
|
||||||
|
return <div style={{ position: "absolute", inset: 0, background: "radial-gradient(ellipse at 50% 45%, rgba(0,0,0,0) 45%, rgba(0,0,0,0.55) 100%)" }} />;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" preserveAspectRatio="xMidYMid slice" style={{ position: "absolute", inset: 0 }}>
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="spot" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor={pal.light} stopOpacity={0.32} /><stop offset="1" stopColor={pal.light} stopOpacity={0.05} /></linearGradient>
|
||||||
|
<radialGradient id="spotDark" cx="0.5" cy="0.55" r="0.65"><stop offset="0.35" stopColor="#000" stopOpacity={0} /><stop offset="1" stopColor="#000" stopOpacity={0.6} /></radialGradient>
|
||||||
|
</defs>
|
||||||
|
<rect width={W} height={H} fill="url(#spotDark)" />
|
||||||
|
<polygon points={`${W * 0.44},${H * 0.03} ${W * 0.56},${H * 0.03} ${W * 0.86},${H * 0.75} ${W * 0.14},${H * 0.75}`} fill="url(#spot)" />
|
||||||
|
<rect x={W * 0.42} y={H * 0.025} width={W * 0.16} height={14} rx={6} fill="#d9d9d9" />
|
||||||
|
<ellipse cx={W / 2} cy={H * 0.75} rx={W * 0.36} ry={34} fill={pal.light} opacity={0.12} />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
/** Sorteio determinístico (mulberry32): a mesma semente desenha sempre o mesmo cenário. */
|
||||||
|
export function rng(seed: number): () => number {
|
||||||
|
let a = (Math.floor(seed) >>> 0) || 1;
|
||||||
|
return () => {
|
||||||
|
a = (a + 0x6d2b79f5) >>> 0;
|
||||||
|
let t = a;
|
||||||
|
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||||
|
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||||
|
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
// Trecho de exemplo (Studio e teste de render). Conteúdo próprio, só para mostrar as peças.
|
||||||
|
import type { ShotSpec } from "./spec";
|
||||||
|
|
||||||
|
const say = (text: string, from: number, step = 0.42) =>
|
||||||
|
text.split(" ").map((w, i) => ({ text: w.replace(/[*_]/g, ""), startS: from + i * step, endS: from + (i + 1) * step,
|
||||||
|
tone: w.startsWith("*") ? ("key" as const) : w.startsWith("_") ? ("danger" as const) : undefined }));
|
||||||
|
|
||||||
|
export const SAMPLE: ShotSpec = {
|
||||||
|
schemaVersion: 1,
|
||||||
|
width: 1080, height: 1920, fps: 30, durationS: 6,
|
||||||
|
seed: 11,
|
||||||
|
scene: { kind: "street", time: "night", litHouse: true },
|
||||||
|
camera: { push: 1.08, panX: 0.05 },
|
||||||
|
hud: { badge: "Tempestade", label: "Noite 1", clock: "22:00", clockMinutesPerSecond: 1 },
|
||||||
|
actors: [{ kind: "person", x: 0.28, y: 0.6, outfit: "#f2c230", hair: "short", hairColor: "#3a2a1e", label: "Seu João", enterS: 0.4, pointing: true }],
|
||||||
|
props: [{ icon: "generator", x: 0.72, y: 0.52, size: 0.12, label: "Gerador", shake: true, rings: true, enterS: 1.2 }],
|
||||||
|
texts: [{ kind: "onomatopoeia", text: "Vrrrum", x: 0.68, y: 0.4, atS: 1.6, rotate: -6 }],
|
||||||
|
words: say("A única casa *acesa da rua chama _atenção", 0.3),
|
||||||
|
};
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
// Fundos do estilo Cartoon, desenhados num espaço fixo de 1080×1920 (o SVG escala para o tamanho do vídeo).
|
||||||
|
import React from "react";
|
||||||
|
import { COLORS, FONT_CAPTION, FONT_LABEL, SKY } from "./theme";
|
||||||
|
import { rng } from "./random";
|
||||||
|
import { PlaceBackground } from "./places";
|
||||||
|
import type { ShotSpec, TimeOfDay } from "./spec";
|
||||||
|
|
||||||
|
export const W = 1080;
|
||||||
|
export const H = 1920;
|
||||||
|
|
||||||
|
type SceneProps = { spec: ShotSpec; frame: number; progress: number };
|
||||||
|
|
||||||
|
function Sky({ time, seed, frame }: { time: TimeOfDay; seed: number; frame: number }) {
|
||||||
|
const [top, bottom] = SKY[time];
|
||||||
|
const rand = rng(seed + 7);
|
||||||
|
const stars = time === "day" ? [] : Array.from({ length: 70 }, () => ({ x: rand() * W, y: rand() * H * 0.45, r: 1 + rand() * 2.2, p: rand() * 6 }));
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
|
||||||
|
<stop offset="0" stopColor={top} />
|
||||||
|
<stop offset="1" stopColor={bottom} />
|
||||||
|
</linearGradient>
|
||||||
|
<radialGradient id="glow">
|
||||||
|
<stop offset="0" stopColor="rgba(255,200,80,0.55)" />
|
||||||
|
<stop offset="1" stopColor="rgba(255,200,80,0)" />
|
||||||
|
</radialGradient>
|
||||||
|
</defs>
|
||||||
|
<rect width={W} height={H} fill="url(#sky)" />
|
||||||
|
{stars.map((s, i) => (
|
||||||
|
<circle key={i} cx={s.x} cy={s.y} r={s.r} fill="#fff" opacity={0.35 + 0.35 * Math.sin(frame / 12 + s.p)} />
|
||||||
|
))}
|
||||||
|
{time === "night" && <circle cx={W * 0.2} cy={H * 0.11} r={38} fill="#f4ecc8" />}
|
||||||
|
{time === "dawn" && <circle cx={W * 0.8} cy={H * 0.2} r={46} fill="#ffd36b" />}
|
||||||
|
{time === "day" && <circle cx={W * 0.82} cy={H * 0.1} r={56} fill="#ffe27a" />}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Casa chapada: corpo, telhado, janelas (acesas ou não) e porta. */
|
||||||
|
export function HouseShape({ x, base, w, h, color, lit, detail = true }: {
|
||||||
|
x: number; base: number; w: number; h: number; color: string; lit?: boolean; detail?: boolean;
|
||||||
|
}) {
|
||||||
|
const roofH = h * 0.42;
|
||||||
|
const win = w * 0.18;
|
||||||
|
const winY = base - h * 0.62;
|
||||||
|
const windowFill = lit ? COLORS.light : COLORS.window;
|
||||||
|
return (
|
||||||
|
<g>
|
||||||
|
{lit && <ellipse cx={x + w / 2} cy={base - h * 0.5} rx={w * 1.4} ry={h * 1.3} fill="url(#glow)" />}
|
||||||
|
<polygon points={`${x - w * 0.06},${base - h} ${x + w / 2},${base - h - roofH} ${x + w * 1.06},${base - h}`} fill={COLORS.roof} />
|
||||||
|
<rect x={x} y={base - h} width={w} height={h} fill={color} />
|
||||||
|
{detail && (
|
||||||
|
<>
|
||||||
|
<rect x={x + w * 0.14} y={winY} width={win} height={win * 1.1} rx={3} fill={windowFill} />
|
||||||
|
<rect x={x + w * 0.68} y={winY} width={win} height={win * 1.1} rx={3} fill={windowFill} />
|
||||||
|
<rect x={x + w * 0.42} y={base - h * 0.48} width={w * 0.16} height={h * 0.48} fill={COLORS.window} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</g>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Street({ spec, frame, progress }: SceneProps) {
|
||||||
|
const time = spec.scene.time ?? "night";
|
||||||
|
const pan = (spec.camera?.panX ?? 0) * W * progress;
|
||||||
|
const rand = rng(spec.seed);
|
||||||
|
const rows = [
|
||||||
|
{ base: H * 0.43, w: 92, h: 70, gap: 6, color: COLORS.houseFar, depth: 0.25, detail: false },
|
||||||
|
{ base: H * 0.5, w: 150, h: 110, gap: 14, color: COLORS.house[2], depth: 0.5, detail: true },
|
||||||
|
{ base: H * 0.6, w: 250, h: 180, gap: 30, color: COLORS.house[0], depth: 1, detail: true },
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" preserveAspectRatio="xMidYMid slice">
|
||||||
|
<Sky time={time} seed={spec.seed} frame={frame} />
|
||||||
|
{rows.map((row, r) => {
|
||||||
|
const count = Math.ceil((W * 1.6) / (row.w + row.gap)) + 2;
|
||||||
|
const start = -W * 0.3 - pan * row.depth;
|
||||||
|
const litIndex = spec.scene.litHouse && r === 2 ? Math.floor(count / 2) - 1 : -1;
|
||||||
|
return (
|
||||||
|
<g key={r}>
|
||||||
|
<rect x={0} y={row.base} width={W} height={H * 0.6 - row.base + 2} fill={r === 2 ? COLORS.ground : "transparent"} />
|
||||||
|
{Array.from({ length: count }, (_, i) => {
|
||||||
|
const jitter = (rand() - 0.5) * row.h * 0.18;
|
||||||
|
return (
|
||||||
|
<HouseShape key={i} x={start + i * (row.w + row.gap)} base={row.base} w={row.w} h={row.h + jitter}
|
||||||
|
color={row.color} lit={i === litIndex} detail={row.detail} />
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</g>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
<rect x={0} y={H * 0.6} width={W} height={H * 0.4} fill={COLORS.road} />
|
||||||
|
{Array.from({ length: 9 }, (_, i) => (
|
||||||
|
<rect key={i} x={((i * 160 - pan * 1.2) % (W + 160)) - 80} y={H * 0.735} width={90} height={8} rx={4} fill={COLORS.roadLine} />
|
||||||
|
))}
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function HouseFront({ spec, frame }: SceneProps) {
|
||||||
|
const time = spec.scene.time ?? "night";
|
||||||
|
const lit = !!spec.scene.litHouse;
|
||||||
|
return (
|
||||||
|
<svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" preserveAspectRatio="xMidYMid slice">
|
||||||
|
<Sky time={time} seed={spec.seed} frame={frame} />
|
||||||
|
<polygon points={`-40,${H * 0.3} ${W / 2},${H * 0.17} ${W + 40},${H * 0.3}`} fill={COLORS.roof} />
|
||||||
|
<rect x={0} y={H * 0.3} width={W} height={H * 0.32} fill={COLORS.house[3]} />
|
||||||
|
<rect x={W * 0.08} y={H * 0.36} width={W * 0.2} height={H * 0.08} rx={6} fill={lit ? COLORS.light : COLORS.window} />
|
||||||
|
<rect x={W * 0.72} y={H * 0.36} width={W * 0.2} height={H * 0.08} rx={6} fill={lit ? COLORS.light : COLORS.window} />
|
||||||
|
<rect x={0} y={H * 0.53} width={W} height={H * 0.09} fill={COLORS.house[1]} />
|
||||||
|
{Array.from({ length: 13 }, (_, i) => (
|
||||||
|
<rect key={i} x={W * 0.34 + i * 26} y={H * 0.53} width={7} height={H * 0.09} fill={COLORS.ink} />
|
||||||
|
))}
|
||||||
|
<rect x={W * 0.33} y={H * 0.53} width={W * 0.34} height={10} fill={COLORS.ink} />
|
||||||
|
<rect x={0} y={H * 0.62} width={W} height={H * 0.38} fill={COLORS.road} />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Plain({ spec, frame }: SceneProps) {
|
||||||
|
const time = spec.scene.time ?? "night";
|
||||||
|
return (
|
||||||
|
<svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" preserveAspectRatio="xMidYMid slice">
|
||||||
|
<Sky time={time} seed={spec.seed} frame={frame} />
|
||||||
|
<rect x={0} y={H * 0.6} width={W} height={H * 0.4} fill={COLORS.road} />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Blueprint() {
|
||||||
|
return (
|
||||||
|
<svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" preserveAspectRatio="xMidYMid slice">
|
||||||
|
<rect width={W} height={H} fill={COLORS.blueprint} />
|
||||||
|
{Array.from({ length: 28 }, (_, i) => <rect key={`v${i}`} x={i * 40} y={0} width={1.5} height={H} fill={COLORS.grid} />)}
|
||||||
|
{Array.from({ length: 49 }, (_, i) => <rect key={`h${i}`} x={0} y={i * 40} width={W} height={1.5} fill={COLORS.grid} />)}
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Card({ spec }: SceneProps) {
|
||||||
|
const card = spec.card!;
|
||||||
|
return (
|
||||||
|
<div style={{ position: "absolute", inset: 0, background: "#07080f", display: "flex", flexDirection: "column",
|
||||||
|
alignItems: "center", justifyContent: "center", gap: "1.2%", textAlign: "center", padding: "0 8%" }}>
|
||||||
|
<div style={{ fontFamily: FONT_CAPTION, fontSize: "11cqw", color: COLORS.text, lineHeight: 1 }}>{card.title}</div>
|
||||||
|
{card.subtitle && <div style={{ fontFamily: FONT_LABEL, fontSize: "6cqw", color: COLORS.key }}>{card.subtitle}</div>}
|
||||||
|
{card.footer && <div style={{ fontFamily: FONT_LABEL, fontSize: "3.2cqw", color: "#b7b9cc", marginTop: "6%" }}>{card.footer}</div>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SceneBackground(props: SceneProps) {
|
||||||
|
switch (props.spec.scene.kind) {
|
||||||
|
case "place": return <PlaceBackground spec={props.spec} frame={props.frame} />;
|
||||||
|
case "street": return <Street {...props} />;
|
||||||
|
case "house": return <HouseFront {...props} />;
|
||||||
|
case "blueprint": return <Blueprint />;
|
||||||
|
case "card": return <Card {...props} />;
|
||||||
|
default: return <Plain {...props} />;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
// Contrato de um trecho do estilo Cartoon (versão 1). O painel escreve este JSON por trecho da montagem e o
|
||||||
|
// render (render.ts) transforma cada um num MP4 com a duração do áudio do trecho. Posições (x, y) são frações
|
||||||
|
// do quadro (0 = esquerda/topo, 1 = direita/base). Tempos em segundos, a partir do início do trecho.
|
||||||
|
|
||||||
|
import { EXPRESSIONS, POSES, validateLook, type CharacterLook, type Expression, type Pose } from "./character";
|
||||||
|
import { ELEMENTS, GROUNDS, PALETTES, type PaletteId, type Place } from "./places";
|
||||||
|
|
||||||
|
/** "place" = lugar montado por peças (ver places.tsx); os demais são fundos prontos da 1ª versão. */
|
||||||
|
export const SCENES = ["place", "street", "house", "plain", "blueprint", "card"] as const;
|
||||||
|
export const LIGHTS = ["none", "spot", "vignette"] as const;
|
||||||
|
export type SceneKind = (typeof SCENES)[number];
|
||||||
|
export const TIMES = ["night", "dawn", "day"] as const;
|
||||||
|
export type TimeOfDay = (typeof TIMES)[number];
|
||||||
|
export const ICONS = ["house", "generator", "fuel", "battery", "phone", "door", "eye", "bulb", "solar", "warning", "money", "clock"] as const;
|
||||||
|
export type IconId = (typeof ICONS)[number];
|
||||||
|
export const TONES = ["info", "danger", "ok"] as const;
|
||||||
|
export type Tone = (typeof TONES)[number];
|
||||||
|
|
||||||
|
export type Person = {
|
||||||
|
kind: "person";
|
||||||
|
x: number; y: number; scale?: number;
|
||||||
|
/** Personagem da biblioteca (aparência por peças). Sem ele, usa o boneco simples abaixo (outfit/hair…). */
|
||||||
|
character?: { name: string; caption?: string; look: CharacterLook };
|
||||||
|
expression?: Expression;
|
||||||
|
pose?: Pose;
|
||||||
|
/** Objeto na mão (pose "hold" ou "point"). */
|
||||||
|
item?: IconId;
|
||||||
|
/** Olha para a esquerda (espelha o desenho). */
|
||||||
|
flip?: boolean;
|
||||||
|
/** Cor da roupa (hex). */
|
||||||
|
outfit?: string;
|
||||||
|
hair?: "short" | "bun" | "none";
|
||||||
|
hairColor?: string;
|
||||||
|
skin?: string;
|
||||||
|
glasses?: boolean;
|
||||||
|
/** Braço direito levantado (apontando/segurando). */
|
||||||
|
pointing?: boolean;
|
||||||
|
label?: string;
|
||||||
|
enterS?: number;
|
||||||
|
};
|
||||||
|
export type Crowd = { kind: "crowd"; count: number; y: number; enterS?: number };
|
||||||
|
export type Actor = Person | Crowd;
|
||||||
|
|
||||||
|
export type Prop = {
|
||||||
|
icon: IconId;
|
||||||
|
x: number; y: number;
|
||||||
|
/** Altura em fração do quadro (padrão 0,16). */
|
||||||
|
size?: number;
|
||||||
|
label?: string;
|
||||||
|
tone?: Tone;
|
||||||
|
enterS?: number;
|
||||||
|
shake?: boolean;
|
||||||
|
rings?: boolean;
|
||||||
|
crossed?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TextItem = {
|
||||||
|
kind: "onomatopoeia" | "tag" | "counter" | "big";
|
||||||
|
text: string;
|
||||||
|
/** Só no "counter": o número grande embaixo do rótulo. */
|
||||||
|
value?: string;
|
||||||
|
x: number; y: number;
|
||||||
|
atS?: number;
|
||||||
|
tone?: Tone;
|
||||||
|
/** Graus (onomatopeia costuma ir levemente girada). */
|
||||||
|
rotate?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type Word = { text: string; startS: number; endS: number; tone?: "key" | "danger" };
|
||||||
|
|
||||||
|
export type ShotSpec = {
|
||||||
|
schemaVersion: 1;
|
||||||
|
width: number; height: number; fps: number;
|
||||||
|
durationS: number;
|
||||||
|
seed: number;
|
||||||
|
scene: { kind: SceneKind; time?: TimeOfDay; litHouse?: boolean };
|
||||||
|
/** Paleta do estilo (a mesma na história inteira dá a "cara" da série). */
|
||||||
|
palette?: PaletteId;
|
||||||
|
/** Lugar montado por peças (scene.kind "place"). */
|
||||||
|
place?: Place;
|
||||||
|
/** Luz por cima: foco do teto ("spot") ou vinheta. */
|
||||||
|
light?: (typeof LIGHTS)[number];
|
||||||
|
/** push = zoom no fim do trecho (1 = parado); panX = deslocamento horizontal da câmera (fração). */
|
||||||
|
camera?: { push?: number; panX?: number };
|
||||||
|
hud?: { badge: string; label: string; clock?: string; clockMinutesPerSecond?: number };
|
||||||
|
actors?: Actor[];
|
||||||
|
props?: Prop[];
|
||||||
|
texts?: TextItem[];
|
||||||
|
/** Legenda palavra por palavra (tempos da narração). Vazio = sem legenda. */
|
||||||
|
words?: Word[];
|
||||||
|
card?: { title: string; subtitle?: string; footer?: string };
|
||||||
|
};
|
||||||
|
|
||||||
|
const finite = (v: unknown) => typeof v === "number" && Number.isFinite(v);
|
||||||
|
const frac = (v: unknown) => finite(v) && (v as number) >= -0.5 && (v as number) <= 1.5;
|
||||||
|
|
||||||
|
/** Confere o spec e devolve a lista de problemas (vazia = válido). Não aceita nada além de dados. */
|
||||||
|
export function validateSpec(spec: unknown): string[] {
|
||||||
|
const errors: string[] = [];
|
||||||
|
const s = spec as Partial<ShotSpec> | null;
|
||||||
|
if (!s || typeof s !== "object") return ["o spec precisa ser um objeto"];
|
||||||
|
if (s.schemaVersion !== 1) errors.push("schemaVersion precisa ser 1");
|
||||||
|
if (!finite(s.width) || !finite(s.height) || s.width! < 64 || s.height! < 64 || s.width! % 2 || s.height! % 2) {
|
||||||
|
errors.push("width/height precisam ser números pares ≥ 64");
|
||||||
|
}
|
||||||
|
if (!finite(s.fps) || s.fps! < 1 || s.fps! > 60) errors.push("fps entre 1 e 60");
|
||||||
|
if (!finite(s.durationS) || s.durationS! <= 0 || s.durationS! > 120) errors.push("durationS entre 0 e 120 s");
|
||||||
|
if (!finite(s.seed)) errors.push("seed precisa ser número");
|
||||||
|
if (!s.scene || !SCENES.includes(s.scene.kind)) errors.push(`scene.kind precisa ser um de: ${SCENES.join(", ")}`);
|
||||||
|
if (s.scene?.time !== undefined && !TIMES.includes(s.scene.time)) errors.push(`scene.time precisa ser um de: ${TIMES.join(", ")}`);
|
||||||
|
if (s.scene?.kind === "card" && !s.card?.title) errors.push("scene card precisa de card.title");
|
||||||
|
if (s.palette !== undefined && !PALETTES.includes(s.palette)) errors.push(`palette precisa ser um de: ${PALETTES.join(", ")}`);
|
||||||
|
if (s.light !== undefined && !LIGHTS.includes(s.light)) errors.push(`light precisa ser um de: ${LIGHTS.join(", ")}`);
|
||||||
|
if (s.scene?.kind === "place") {
|
||||||
|
const place = s.place;
|
||||||
|
if (!place || !GROUNDS.includes(place.ground) || !Array.isArray(place.elements)) errors.push(`place precisa de ground (${GROUNDS.join(", ")}) e elements`);
|
||||||
|
else {
|
||||||
|
if (place.elements.length > 40) errors.push("place: no máximo 40 peças");
|
||||||
|
for (const [i, e] of place.elements.entries()) {
|
||||||
|
if (!ELEMENTS.includes(e.kind)) errors.push(`place.elements[${i}]: peça "${e.kind}" não existe (${ELEMENTS.join(", ")})`);
|
||||||
|
if (!frac(e.x) || (e.z !== undefined && !(e.z >= 0 && e.z <= 1))) errors.push(`place.elements[${i}]: x fora do quadro ou z fora de 0–1`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const [i, a] of (s.actors ?? []).entries()) {
|
||||||
|
if (a.kind === "person" && (!frac(a.x) || !frac(a.y))) errors.push(`actors[${i}]: x/y fora do quadro`);
|
||||||
|
else if (a.kind === "person" && a.character && (typeof a.character.name !== "string" || validateLook(a.character.look).length)) {
|
||||||
|
errors.push(`actors[${i}].character: ${validateLook(a.character.look).join("; ") || "name obrigatório"}`);
|
||||||
|
} else if (a.kind === "person" && a.expression !== undefined && !EXPRESSIONS.includes(a.expression)) errors.push(`actors[${i}]: expressão (${EXPRESSIONS.join(", ")})`);
|
||||||
|
else if (a.kind === "person" && a.pose !== undefined && !POSES.includes(a.pose)) errors.push(`actors[${i}]: pose (${POSES.join(", ")})`);
|
||||||
|
else if (a.kind === "person" && a.item !== undefined && !ICONS.includes(a.item)) errors.push(`actors[${i}]: item "${a.item}" não existe`);
|
||||||
|
else if (a.kind === "crowd" && (!finite(a.count) || a.count < 1 || a.count > 40 || !frac(a.y))) errors.push(`actors[${i}]: crowd inválida`);
|
||||||
|
else if (a.kind !== "person" && a.kind !== "crowd") errors.push(`actors[${i}]: kind inválido`);
|
||||||
|
}
|
||||||
|
for (const [i, p] of (s.props ?? []).entries()) {
|
||||||
|
if (!ICONS.includes(p.icon)) errors.push(`props[${i}]: ícone "${p.icon}" não existe (${ICONS.join(", ")})`);
|
||||||
|
if (!frac(p.x) || !frac(p.y)) errors.push(`props[${i}]: x/y fora do quadro`);
|
||||||
|
if (p.tone !== undefined && !TONES.includes(p.tone)) errors.push(`props[${i}]: tone inválido`);
|
||||||
|
}
|
||||||
|
for (const [i, t] of (s.texts ?? []).entries()) {
|
||||||
|
if (!["onomatopoeia", "tag", "counter", "big"].includes(t.kind)) errors.push(`texts[${i}]: kind inválido`);
|
||||||
|
if (typeof t.text !== "string" || !t.text.trim()) errors.push(`texts[${i}]: texto vazio`);
|
||||||
|
if (!frac(t.x) || !frac(t.y)) errors.push(`texts[${i}]: x/y fora do quadro`);
|
||||||
|
}
|
||||||
|
for (const [i, w] of (s.words ?? []).entries()) {
|
||||||
|
if (typeof w.text !== "string" || !finite(w.startS) || !finite(w.endS) || w.endS < w.startS) errors.push(`words[${i}]: inválida`);
|
||||||
|
}
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Número de quadros do trecho (arredonda para cima: o vídeo nunca fica mais curto que o áudio). */
|
||||||
|
export const frameCount = (spec: Pick<ShotSpec, "durationS" | "fps">) => Math.max(1, Math.ceil(spec.durationS * spec.fps));
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
// Fontes do estilo Cartoon (carregadas pela Remotion antes do 1º quadro). As cores ficam em colors.ts.
|
||||||
|
import { continueRender, delayRender, staticFile } from "remotion";
|
||||||
|
import { FONT_CAPTION, FONT_LABEL } from "./colors";
|
||||||
|
|
||||||
|
export * from "./colors";
|
||||||
|
|
||||||
|
let loaded = false;
|
||||||
|
/** Carrega as fontes de assets/fonts antes do primeiro quadro (o render espera). */
|
||||||
|
export function loadFonts(): void {
|
||||||
|
if (loaded || typeof document === "undefined") return;
|
||||||
|
loaded = true;
|
||||||
|
const handle = delayRender("fontes do Cartoon");
|
||||||
|
const faces = [
|
||||||
|
new FontFace(FONT_CAPTION, `url(${staticFile("fonts/Anton-Regular.ttf")})`),
|
||||||
|
new FontFace(FONT_LABEL, `url(${staticFile("fonts/BebasNeue-Regular.ttf")})`),
|
||||||
|
];
|
||||||
|
Promise.all(faces.map((f) => f.load().then((ok) => document.fonts.add(ok))))
|
||||||
|
.then(() => continueRender(handle))
|
||||||
|
.catch((error) => { console.error("fontes do Cartoon:", error); continueRender(handle); });
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { describe, it } from "node:test";
|
||||||
|
import { captionChunks } from "../src/overlays";
|
||||||
|
import { SAMPLE } from "../src/sample";
|
||||||
|
import { frameCount, validateSpec } from "../src/spec";
|
||||||
|
|
||||||
|
describe("spec do Cartoon", () => {
|
||||||
|
it("o exemplo é válido", () => assert.deepEqual(validateSpec(SAMPLE), []));
|
||||||
|
|
||||||
|
it("recusa versão, cena, ícone e tamanhos inválidos", () => {
|
||||||
|
const bad = { ...SAMPLE, schemaVersion: 2, width: 1081, scene: { kind: "lua" }, props: [{ icon: "foguete", x: 0.5, y: 0.5 }] };
|
||||||
|
const errors = validateSpec(bad).join(" | ");
|
||||||
|
assert.match(errors, /schemaVersion/);
|
||||||
|
assert.match(errors, /width\/height/);
|
||||||
|
assert.match(errors, /scene.kind/);
|
||||||
|
assert.match(errors, /foguete/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("card precisa de título; palavra com fim antes do início é recusada", () => {
|
||||||
|
assert.match(validateSpec({ ...SAMPLE, scene: { kind: "card" } }).join(), /card.title/);
|
||||||
|
assert.match(validateSpec({ ...SAMPLE, words: [{ text: "oi", startS: 2, endS: 1 }] }).join(), /words\[0\]/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("quadros arredondam para cima (o vídeo nunca fica mais curto que o áudio)", () => {
|
||||||
|
assert.equal(frameCount({ durationS: 2.01, fps: 30 }), 61);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("legenda em blocos de até 3 palavras, quebrando depois de pontuação", () => {
|
||||||
|
const w = (text: string) => ({ text, startS: 0, endS: 0 });
|
||||||
|
const chunks = captionChunks(["Num", "apagão,", "a", "casa", "acesa", "chama", "atenção."].map(w)).map((c) => c.map((x) => x.text).join(" "));
|
||||||
|
assert.deepEqual(chunks, ["Num apagão,", "a casa acesa", "chama atenção."]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "Bundler",
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"strict": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"lib": ["ES2022", "DOM"]
|
||||||
|
},
|
||||||
|
"include": ["src", "render.ts", "tests", "remotion.config.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Cenas do estilo Cartoon — como se monta (não há cenário pronto)
|
||||||
|
|
||||||
|
Cada trecho é um spec JSON (`cartoon/src/spec.ts`, schemaVersion 1) que a Remotion desenha em MP4. O cenário
|
||||||
|
é **montado por peças** a cada vez: a mesma gramática faz um parque de dia, um cemitério na névoa ou um bunker
|
||||||
|
com foco de luz. Nunca copie um vídeo de referência; reaproveite a *linguagem* (legenda palavra por palavra,
|
||||||
|
etiquetas, onomatopeias, painel do topo) com conteúdo próprio.
|
||||||
|
|
||||||
|
## Camadas (de trás para frente)
|
||||||
|
|
||||||
|
1. **Paleta** (`palette`): `night`, `sepia`, `day`, `dusk`, `gray`. Uma paleta por história dá a cara da série.
|
||||||
|
2. **Lugar** (`scene.kind: "place"` + `place`):
|
||||||
|
- `ground`: `grass`, `street`, `dirt`, `floor`, `sand`, `water`, `none`
|
||||||
|
- `indoor: true` troca o céu por parede (quarto, bunker, loja); `fog: true` põe névoa; `horizon` (0–1).
|
||||||
|
- `elements`: peças com `x` (0–1), `z` (0 frente … 1 fundo: menor e mais apagado), `scale`, `flip`, `color`.
|
||||||
|
Peças: `tree`, `deadtree`, `pine`, `bush`, `rock`, `mountain`, `cloud`, `bench`, `lamp`, `gravestone`,
|
||||||
|
`cross`, `fence`, `house`, `building`, `car`, `sign`, `door`, `window`, `table`, `bed`, `shelf`, `crate`,
|
||||||
|
`tent`, `fire`.
|
||||||
|
3. **Atores**: personagens da biblioteca (`doc/cartoon/personagens.md`) ou multidão (`crowd`, silhuetas).
|
||||||
|
4. **Objetos** (`props`): ícones com etiqueta, tremor (`shake`), ondas de som (`rings`) e X vermelho (`crossed`).
|
||||||
|
5. **Luz** (`light`): `spot` (cone do teto, bunker/interrogatório) ou `vignette` (tensão).
|
||||||
|
6. **Textos** (`texts`): `tag` (etiqueta), `big` (número grande), `counter` (rótulo + número), `onomatopoeia`.
|
||||||
|
7. **Painel do topo** (`hud`) e **legenda** (`words`, tempos da narração).
|
||||||
|
|
||||||
|
## Receitas de lugar (ponto de partida, não modelo fixo)
|
||||||
|
|
||||||
|
| Situação | Paleta | Chão | Peças típicas | Extra |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| Parque de dia | day | grass | tree ×2, bench, lamp, bush, cloud, building ao fundo | — |
|
||||||
|
| Cemitério | dusk / night | dirt | gravestone ×3–4, cross, deadtree, fence ao fundo | fog, vignette |
|
||||||
|
| Bunker / porão | sepia | floor, indoor | shelf, crate ×2, door | light spot |
|
||||||
|
| Casa / quarto | night / day | floor, indoor | window, bed ou table, shelf, door | — |
|
||||||
|
| Rua / bairro | night | street | building, house, lamp, car, sign | litHouse |
|
||||||
|
| Floresta / trilha | day / dusk | grass | pine ×3, tree, rock, mountain ao fundo | — |
|
||||||
|
| Sítio | day / sepia | grass | house, fence, tree, mountain, cloud | — |
|
||||||
|
| Acampamento | dusk | grass | tent, fire, pine ×2, rock | — |
|
||||||
|
|
||||||
|
Composição: personagem principal entre x 0,35 e 0,5 e y ≈ 0,74 (pés); peças grandes nas laterais
|
||||||
|
(x < 0,25 ou > 0,75) e/ou ao fundo (z ≥ 0,6) para não cobrir o rosto nem a legenda (y ≈ 0,66).
|
||||||
|
Varie a cada trecho (posições, `flip`, câmera `push`/`panX`) para o vídeo não parecer repetido.
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
# Personagens do estilo Cartoon
|
||||||
|
|
||||||
|
Um personagem é criado uma vez e reaproveitado em qualquer história. Ele é **montado por peças** (não é um
|
||||||
|
desenho pronto): a ficha diz qual peça e qual cor, e o desenho (`cartoon/src/CharacterFigure.tsx`) faz o resto.
|
||||||
|
Nas cenas só mudam **expressão**, **pose** e **objeto na mão** — a aparência é sempre a mesma.
|
||||||
|
|
||||||
|
## Onde fica
|
||||||
|
|
||||||
|
`assets/characters/<id>/character.json` (id em minúsculas com hífens). A aba **Personagens** do painel lista,
|
||||||
|
cria (pela descrição), ajusta e apaga. O elenco de cada história fica em `stories/<história>/cast.json`
|
||||||
|
(`{ "cast": ["otavio", "dona-cida"] }`) e a montagem Cartoon usa esses personagens.
|
||||||
|
|
||||||
|
## Ficha (schemaVersion 1)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"schemaVersion": 1,
|
||||||
|
"id": "otavio",
|
||||||
|
"name": "Otávio",
|
||||||
|
"caption": "Engenheiro de minas · 58 anos",
|
||||||
|
"description": "texto livre que originou o personagem",
|
||||||
|
"kind": "cartoon",
|
||||||
|
"look": {
|
||||||
|
"build": "average",
|
||||||
|
"height": 1,
|
||||||
|
"skin": "#e0b48f",
|
||||||
|
"hair": { "style": "bald", "color": "#b9b9bf" },
|
||||||
|
"beard": { "style": "full", "color": "#a9a9b0" },
|
||||||
|
"glasses": "round",
|
||||||
|
"brows": "thick",
|
||||||
|
"top": { "style": "uniform", "color": "#56704a", "accent": "#e8b13a" },
|
||||||
|
"bottom": { "style": "pants", "color": "#2c3346" },
|
||||||
|
"shoes": "#1d1d24"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Campo | Valores |
|
||||||
|
|---|---|
|
||||||
|
| `build` | `slim`, `average`, `heavy` |
|
||||||
|
| `height` | 0,6 a 1,2 (adulto ≈ 1; criança ≈ 0,78) |
|
||||||
|
| `hair.style` | `short`, `side`, `bun`, `long`, `curly`, `spiky`, `bald` (só as laterais), `cap` (boné; a cor do cabelo vira a do boné) |
|
||||||
|
| `beard.style` | `none`, `stubble`, `mustache`, `full`, `goatee` |
|
||||||
|
| `glasses` | `none`, `round`, `square`, `sun` |
|
||||||
|
| `brows` | `thin`, `thick` |
|
||||||
|
| `top.style` | `shirt`, `jacket`, `hoodie`, `dress`, `uniform` (`accent` = faixa/gola) |
|
||||||
|
| `bottom.style` | `pants`, `shorts`, `skirt` |
|
||||||
|
| cores | sempre `#rrggbb` |
|
||||||
|
|
||||||
|
`kind: "3d"` reserva o personagem para a Godot (pessoa articulada de `godot/kits/`, parâmetros em `godot`);
|
||||||
|
o Cartoon ignora esses.
|
||||||
|
|
||||||
|
## Em cena
|
||||||
|
|
||||||
|
No spec do trecho (`cartoon/src/spec.ts`), um ator `person` com `character` (nome, legenda, look) e:
|
||||||
|
|
||||||
|
- `expression`: `neutral`, `happy`, `sad`, `worried`, `angry`, `surprised`, `scared`
|
||||||
|
- `pose`: `stand`, `point`, `wave`, `hold`, `arms_up`, `shrug`, `think`
|
||||||
|
- `item` (com `hold`/`point`): ícone na mão — `phone`, `fuel`, `battery`, `money`, `bulb`, `clock`, …
|
||||||
|
- `flip`: olha para a esquerda.
|
||||||
|
|
||||||
|
## Como criar um bom personagem
|
||||||
|
|
||||||
|
- Uma silhueta reconhecível de longe: **uma** marca forte (careca + barba grisalha, coque branco, boné vermelho).
|
||||||
|
- Roupa de cor chapada que contraste com a paleta da série (sépia pede verde/azul; noite pede amarelo/roxo).
|
||||||
|
- `caption` curta, com função e idade ("Engenheiro de minas · 58 anos"): aparece na 1ª cena.
|
||||||
|
- Não copie personagens de outras obras (nome, roupa e marca registrada).
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
# Estudo — estilo "cartoon explicativo" (referência TikTok, 17/11/2026)
|
||||||
|
|
||||||
|
Referência: série "Apagão · 30 dias", Ep. 2 ("Num apagão, a casa com luz é a mais segura… ou a mais visada?").
|
||||||
|
537 mil views, 30 mil curtidas, 6,4 mil salvos em ~3 semanas, numa conta com 14 vídeos e 5,8 mil seguidores.
|
||||||
|
TikTok classificou como "Comics & Cartoon"; rótulo de IA desligado; 4 hashtags reconhecidas.
|
||||||
|
O vídeo foi baixado só para estudo (pasta temporária, fora do repositório) e não deve ser reaproveitado.
|
||||||
|
|
||||||
|
## Ficha técnica
|
||||||
|
|
||||||
|
- 1080×1920, 30 fps, 83,7 s (79 s de história + 4 s de cartela final), HEVC + AAC.
|
||||||
|
- Só 4 cortes secos em 84 s (7,4 / 50,4 / 70,7 / 73,5 s): o resto é troca de cena por movimento contínuo de
|
||||||
|
câmera, empurrão (zoom) e elementos entrando e saindo.
|
||||||
|
- Narração do começo ao fim: ~180 palavras em 79 s (~2,3 palavras/s), uma frase curta a cada 2–4 s, sem
|
||||||
|
respiro. Trilha/ambiente contínuo ~6 dB abaixo da voz (pausas a −18/−21 dB, fala a −14 dB) e efeitos
|
||||||
|
pontuais (gerador, "toc toc toc", rosnado).
|
||||||
|
|
||||||
|
## Linguagem visual
|
||||||
|
|
||||||
|
- **Tudo vetor chapado**: retângulos com cantos arredondados, círculos e caminhos simples; sem textura, sem
|
||||||
|
contorno, sombras só como faixa mais escura. Paleta noturna fixa: azul-marinho (#1b1f3b‑ish), roxo-acinzentado
|
||||||
|
das casas, amarelo-âmbar da luz, vermelho de alerta, verde de "ok".
|
||||||
|
- **Cenário procedural**: fileiras de casas idênticas repetidas em 3–4 profundidades (parallax), estrelas,
|
||||||
|
lua. Cara de gerado por código, não desenhado à mão.
|
||||||
|
- **Personagens "boneco de recorte"**: Dona Cida, o menino de amarelo e o cachorro são peças rígidas; o
|
||||||
|
movimento é do corpo inteiro (entrar, balançar leve, braço que gira no ombro). Sem boca sincronizada. Multidão
|
||||||
|
= silhuetas pretas.
|
||||||
|
- **Ícones explicativos**: calendário "30 dias sem luz", diagrama placa → inversor → casa com linha tracejada
|
||||||
|
animada, cronômetro "2,0 s → 0,3 s → OFF", galão enchendo/esvaziando, "≈ 1 L / hora", régua "6 m", X
|
||||||
|
vermelho grande para "não faça".
|
||||||
|
- **Etiquetas amarelas** (fundo amarelo, texto preto em caixa alta) nomeando cada coisa: DONA CIDA, GERADOR,
|
||||||
|
PLACA SOLAR COMUM, JANELA COBERTA. Vermelho para perigo (ALVO, SEM LUZ, MATA EM MINUTOS), verde para o
|
||||||
|
certo (LADO DE FORA, COM BATERIA).
|
||||||
|
- **HUD fixo no topo**: selo "⚡ APAGÃO" + "DIA 2" + relógio que avança 1 min de história por ~1 s de vídeo
|
||||||
|
(06:00 → 06:39; muda para NOITE 2 · 21:00 e 03:00). Dá a sensação de série e de tempo passando.
|
||||||
|
- **Onomatopeias** escritas na cena: VRRRRRUM (entra com fade + escala, levemente girada), TOC TOC TOC, GRRR.
|
||||||
|
- **Ondas de som**: anéis concêntricos que crescem e somem (gerador, casa acesa chamando atenção).
|
||||||
|
|
||||||
|
## Legenda (o que mais "vende" o estilo)
|
||||||
|
|
||||||
|
- Palavra por palavra, sincronizada com a voz, centralizada no terço inferior, fonte condensada pesada
|
||||||
|
(tipo Bebas Neue / Anton / Oswald Bold), branca com sombra.
|
||||||
|
- Cada palavra nova **entra pequena e cresce** em ~5 quadros (mola); a anterior fica. Mostra 1–3 palavras.
|
||||||
|
- Palavra-chave colorida: amarelo para o conceito (LUZ, GERADOR, GASOLINA, 2 SEGUNDOS), vermelho para perigo
|
||||||
|
(VISADA, NUNCA, MINUTOS, SUA PORTA).
|
||||||
|
|
||||||
|
## Movimento (quadro a quadro)
|
||||||
|
|
||||||
|
- Gerador: tremor de 1–3 px por quadro (vibração), anéis crescendo, fumaça; a onomatopeia aparece em ~4 quadros.
|
||||||
|
- Cenas paradas sempre têm algo vivo: câmera em empurrão lento, relógio do HUD, estrelas, pisca da janela.
|
||||||
|
- Transições: corte seco raro; o normal é a câmera viajar ou o próximo elemento entrar por cima.
|
||||||
|
|
||||||
|
## Roteiro (fórmula)
|
||||||
|
|
||||||
|
1. Gancho contraintuitivo em 5 s: "a casa que tem luz não é a mais segura, é a mais visada".
|
||||||
|
2. Contexto de série: "Dia 2 de 30".
|
||||||
|
3. Personagem com fala curta e regional ("Aquilo ali é gerador, menino").
|
||||||
|
4. Bloco "aprenda": 3–4 fatos concretos com número (2 s, 1 L/h, 20 L, 6 m).
|
||||||
|
5. Regra de ouro resumida.
|
||||||
|
6. Virada narrativa (9 da noite, 10 pessoas no portão; 3 da manhã, batem na porta).
|
||||||
|
7. Gancho para o próximo: cartela "PARTE 3 · QUEM BATEU? · siga pra sobreviver ao dia 3".
|
||||||
|
|
||||||
|
## Como fazer no CenaForge (sem Godot)
|
||||||
|
|
||||||
|
Tudo aqui é forma 2D + texto + transformações no tempo: é exatamente o que **Remotion** (React → MP4) faz
|
||||||
|
bem. Cada cena vira um componente React com SVG; `useCurrentFrame()` + `spring()`/`interpolate()` dão os
|
||||||
|
movimentos. A legenda palavra por palavra precisa do tempo de cada palavra: a síntese (`/v1/synthesize`) só
|
||||||
|
devolve o áudio e a duração, então os tempos saem transcrevendo o áudio gerado (`transcribe` com
|
||||||
|
`detail: "words"`, `panel/src/lib/voice.ts`). Hoje a montagem documental reparte a legenda por tamanho do texto
|
||||||
|
(`captionChunks`, `montage-ffmpeg.ts`), não pela fala. A Godot continua para o 3D.
|
||||||
|
|
||||||
|
| Opção | Bom para | Atenção |
|
||||||
|
|---|---|---|
|
||||||
|
| **Remotion** (React/TS) | Encaixa no painel (Next/React/TS); componentes reutilizáveis (HUD, etiqueta, legenda, casa, personagem); render por linha de comando em MP4 | Licença: grátis para pessoa física e empresas pequenas; empresa maior paga — conferir os termos atuais antes de usar comercialmente |
|
||||||
|
| Motion Canvas (TS, MIT) | Animação por código, ótimo para diagramas | Menos pronto para render em lote/servidor e para legenda |
|
||||||
|
| After Effects / Vyond / Animaker | Feito à mão ou por template | Manual, pago, não automatiza |
|
||||||
|
|
||||||
|
Personagens: SVG simples em peças (cabeça, tronco, braço, perna) desenhados uma vez e reaproveitados como
|
||||||
|
"atores" com poses — mesmo princípio da pessoa articulada da Godot (`godot/kits/`).
|
||||||
|
|
||||||
|
## Próximo passo sugerido
|
||||||
|
|
||||||
|
Prova de conceito de 10–15 s em Remotion reproduzindo a *linguagem* (não o conteúdo): HUD com relógio, rua
|
||||||
|
procedural com parallax, uma etiqueta, uma onomatopeia com tremor e a legenda palavra por palavra a partir de
|
||||||
|
uma narração gerada no serviço de voz. Medir tempo de render e comparar com a Godot.
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
# TikTok sem alcance — diagnóstico (17/11/2026)
|
||||||
|
|
||||||
|
Canal VortPlay, rede TikTok em **sessão logada** (TikTok Studio na web, robô do Publicador). Mesmos arquivos de
|
||||||
|
vídeo que vão para Instagram e YouTube. Reverificar as regras das fontes a cada 3 meses.
|
||||||
|
|
||||||
|
## 1. Números (leitura das 20:27 BRT)
|
||||||
|
|
||||||
|
| Corte | TikTok | Instagram | YouTube |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 68 | 2 (leitura anterior; nesta não foi encontrado) | 5.182 | 839 |
|
||||||
|
| 108 | 0 | 2.778 | 1 |
|
||||||
|
| 105 | 2 | 1.781 | 2 |
|
||||||
|
| 91 | 0 | 1.383 | 7 |
|
||||||
|
| 104 | 0 | 1.100 | 1 |
|
||||||
|
| 121 | 0 | 323 | 0 |
|
||||||
|
| 75 | 2 | 188 | — |
|
||||||
|
| 134 | 0 | 10 | 0 |
|
||||||
|
| 25 | 2 | — | 604 |
|
||||||
|
|
||||||
|
9 vídeos, 0–2 views cada (as 2 views + 1 curtida parecem ser da própria conta). O TikTok não testou os vídeos
|
||||||
|
nem com o grupo inicial do For You. YouTube a partir do 91 também está baixo, mas os vídeos têm 1–3 h (o
|
||||||
|
YouTube conta atrasado); reavaliar amanhã.
|
||||||
|
|
||||||
|
## 2. O que a página pública do vídeo 108 mostra (JSON `webapp.video-detail`)
|
||||||
|
|
||||||
|
| Campo | Valor | Leitura |
|
||||||
|
|---|---|---|
|
||||||
|
| `challenges` / `textExtra` | `[]` | **Nenhuma hashtag reconhecida.** O texto `#Skipnho #ROBRUN…` está lá, mas como texto comum. |
|
||||||
|
| `author.createTime` | 17/11 12:48 BRT | Conta criada hoje; 1º vídeo às 13:41; 9 vídeos em ~6 h; 1 seguidor. |
|
||||||
|
| `penaltyContext.reviewed` | `"0"` | Ainda não revisado. `display_penalty_type` 0, `isProhibited` false, `takeDown` 0: sem punição visível. |
|
||||||
|
| `video.bitrateInfo` | só `lowest_540_0` | O TikTok só gerou a versão mais baixa (enviamos 1080×1920, 11 Mbps). Comum em vídeo ainda sem distribuição — observação, não regra. |
|
||||||
|
| `privateItem`, `secret`, `forFriend` | false | Público. |
|
||||||
|
| `IsAigc` | false | Rótulo de IA desligado (o painel nunca liga para corte). |
|
||||||
|
| `music.original` | true | Som original. |
|
||||||
|
| `diversificationLabels` | Video Games, Games, Entertainment | Categoria entendida. |
|
||||||
|
| `duetDisplay`, `stitchDisplay`, `itemCommentStatus` | 0 | Dueto, stitch e comentários liberados. |
|
||||||
|
|
||||||
|
Ler mais páginas seguidas fez o TikTok devolver página vazia (1,4 KB): limitar essas leituras.
|
||||||
|
|
||||||
|
### Por que as hashtags não pegaram
|
||||||
|
|
||||||
|
`publisher/app/platforms/session/tiktok_studio.py` cola a legenda inteira (`fill_text` → `keyboard.insert_text`)
|
||||||
|
e aperta Esc para fechar a lista de sugestões. No editor do TikTok Studio, a hashtag só vira hashtag (entidade
|
||||||
|
com link) quando é **digitada** e confirmada na lista de sugestões. Colada, fica texto. Vale para todos os
|
||||||
|
vídeos já publicados no TikTok.
|
||||||
|
|
||||||
|
## 3. Pesquisa (resumo; [OFICIAL] = TikTok, [MERCADO] = blogs/ferramentas)
|
||||||
|
|
||||||
|
1. **Conteúdo reaproveitado** [OFICIAL]: fica fora do For You o que tem "material não original ou reaproveitado
|
||||||
|
sem nada novo" — https://www.tiktok.com/community-guidelines/en/integrity-authenticity (versão de 25/08/2026).
|
||||||
|
Repetir pode tirar a **conta inteira** das recomendações por um tempo. Não há definição oficial de
|
||||||
|
"transformação suficiente"; o mercado cita narração/comentário próprio, texto original, recomposição e
|
||||||
|
edição própria.
|
||||||
|
2. **Como ver se foi barrado** [OFICIAL]: a análise de cada post mostra "ineligible for recommendation"
|
||||||
|
(https://www.tiktok.com/community-guidelines/en/fyf-standards); no TikTok Studio do computador há o
|
||||||
|
"Content Check Lite" antes de publicar
|
||||||
|
(https://www.engadget.com/social-media/tiktok-content-check-tells-creators-if-their-videos-will-be-blocked-from-for-you-pages-110015168.html).
|
||||||
|
No app: TikTok Studio → Account check / status da conta [MERCADO]. Recurso pela notificação na Caixa de
|
||||||
|
entrada; não apagar vídeo marcado.
|
||||||
|
3. **Frequência** [MERCADO]: o estudo da Buffer (11,4 mi de posts) não vê punição por volume
|
||||||
|
(https://buffer.com/resources/how-often-should-you-post-on-tiktok/), mas relatos dizem que rajadas numa conta
|
||||||
|
nova deixam os últimos com 0 views. Sem fonte oficial sobre "aquecimento".
|
||||||
|
4. **Web automatizada × app** [MERCADO, anedota]: relato de automação do TikTok Studio com Playwright com 0 views
|
||||||
|
pela web e 87 pelo celular (https://www.blackhatworld.com/posts/20719825/). Sem teste controlado.
|
||||||
|
5. **Hashtags** [MERCADO]: 3–5 específicas; texto da legenda e texto na tela também entram na busca; hashtag
|
||||||
|
no comentário não tem efeito comprovado (https://metricool.com/tiktok-hashtags/,
|
||||||
|
https://vidiq.com/fr/blog/post/tiktok-hashtags).
|
||||||
|
6. **Música** [MERCADO]: música com direitos tocando na live pode mutar o áudio ou derrubar o vídeo.
|
||||||
|
7. **Duração** [MERCADO]: para cortes de live recomendam 15–45 s; o programa de recompensas exige > 1 min.
|
||||||
|
8. **Cortes de Twitch**: sem regra oficial específica; vale a de originalidade e a de propriedade intelectual.
|
||||||
|
|
||||||
|
## 4. O que fazer, em ordem
|
||||||
|
|
||||||
|
**No app do TikTok (dono, 5 min) — antes de mudar qualquer coisa**
|
||||||
|
1. Caixa de entrada: algum aviso de vídeo ou conta?
|
||||||
|
2. TikTok Studio → status da conta / Account check.
|
||||||
|
3. Análise de 2–3 vídeos: aparece "não elegível para recomendação"? Origem do tráfego.
|
||||||
|
Isso separa "vídeo barrado" de "conta barrada" de "só conta nova".
|
||||||
|
|
||||||
|
**No Publicador / painel (código)**
|
||||||
|
4. Hashtags de verdade no TikTok Studio — **feito em 17/11 (falta validar com vídeo real)**:
|
||||||
|
`type_caption` em `tiktok_studio.py` cola o texto comum e digita cada `#tag`, clicando na sugestão exata da
|
||||||
|
lista (`hashtag_options`); sem sugestão, a tag fica como texto e o envio segue. O progresso do job diz
|
||||||
|
"N de M hashtags confirmadas". Vale depois de reiniciar o Publicador. Validar: no 1º vídeo enviado com o
|
||||||
|
código novo, conferir `challenges` na página pública (deve listar as tags).
|
||||||
|
5. Legenda do TikTok: palavras-chave em texto corrido ("GTA RP", nome do servidor, nome do streamer), 3–5
|
||||||
|
hashtags, crédito como "@streamer na Twitch" sem URL (no TikTok o link nem é clicável).
|
||||||
|
6. Ritmo por rede: no TikTok, 1–2 vídeos por dia com horas de intervalo nas primeiras 1–2 semanas (hoje o
|
||||||
|
limite por dia vale só para "próximo horário bom"; "Agora" e "Horário específico" passam por cima).
|
||||||
|
|
||||||
|
**Teste controlado**
|
||||||
|
7. Postar 1 corte à mão pelo app do celular e comparar com o enviado pelo robô no mesmo dia.
|
||||||
|
|
||||||
|
**Conteúdo**
|
||||||
|
8. Algo novo em cada corte para o TikTok (contexto escrito/narrado, gancho próprio) e conferir música de fundo.
|
||||||
@@ -2,6 +2,8 @@ import type { NextConfig } from "next";
|
|||||||
|
|
||||||
// Painel local: dados sempre dinâmicos (SQLite + arquivos), então sem Cache Components.
|
// Painel local: dados sempre dinâmicos (SQLite + arquivos), então sem Cache Components.
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
|
// Personagens do estilo Cartoon: o painel usa o mesmo desenho do pacote cartoon/ (TSX) na prévia ao vivo.
|
||||||
|
transpilePackages: ["cenaforge-cartoon"],
|
||||||
turbopack: {
|
turbopack: {
|
||||||
rules: {
|
rules: {
|
||||||
"*.css": {
|
"*.css": {
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@xyflow/react": "13.0.1",
|
"@xyflow/react": "13.0.1",
|
||||||
|
"cenaforge-cartoon": "workspace:*",
|
||||||
"next": "16.4.6",
|
"next": "16.4.6",
|
||||||
"react": "19.3.0",
|
"react": "19.3.0",
|
||||||
"react-dom": "19.3.0"
|
"react-dom": "19.3.0"
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { defaultModelFor, defaultProviderFor, startRun } from "@/lib/agents";
|
||||||
|
import { characterFileRel, getCharacter } from "@/lib/characters";
|
||||||
|
import { errorResponse, readJson } from "@/lib/http";
|
||||||
|
import { UserError } from "@/lib/stories";
|
||||||
|
|
||||||
|
type Ctx = { params: Promise<{ id: string }> };
|
||||||
|
|
||||||
|
/** POST — pede ao agente (tarefa "Personagem") para refinar a aparência pela descrição. → {runId}. */
|
||||||
|
export async function POST(request: Request, ctx: Ctx) {
|
||||||
|
try {
|
||||||
|
const { id } = await ctx.params;
|
||||||
|
const character = getCharacter(id);
|
||||||
|
if (!character) throw new UserError("Personagem não encontrado.");
|
||||||
|
const body = await readJson<{ note?: string }>(request).catch(() => ({} as { note?: string }));
|
||||||
|
const provider = defaultProviderFor("character");
|
||||||
|
const run = startRun({
|
||||||
|
provider, model: defaultModelFor("character", provider), kind: "character",
|
||||||
|
request: `Personagem ${id} (arquivo ${characterFileRel(id)}): ${character.name}. ${character.description ?? ""} ${String(body.note ?? "").slice(0, 600)}`.trim(),
|
||||||
|
});
|
||||||
|
return Response.json({ runId: run.id });
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { deleteCharacter, getCharacter, saveCharacter } from "@/lib/characters";
|
||||||
|
import { errorResponse, readJson } from "@/lib/http";
|
||||||
|
import { UserError } from "@/lib/stories";
|
||||||
|
|
||||||
|
type Ctx = { params: Promise<{ id: string }> };
|
||||||
|
|
||||||
|
export async function GET(_request: Request, ctx: Ctx) {
|
||||||
|
try {
|
||||||
|
const character = getCharacter((await ctx.params).id);
|
||||||
|
if (!character) throw new UserError("Personagem não encontrado.");
|
||||||
|
return Response.json(character);
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PUT — salva nome, legenda, descrição, tipo e aparência (o id não muda). */
|
||||||
|
export async function PUT(request: Request, ctx: Ctx) {
|
||||||
|
try {
|
||||||
|
const { id } = await ctx.params;
|
||||||
|
const body = await readJson<Record<string, unknown>>(request);
|
||||||
|
return Response.json(saveCharacter({ ...body, id }));
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(_request: Request, ctx: Ctx) {
|
||||||
|
try {
|
||||||
|
deleteCharacter((await ctx.params).id);
|
||||||
|
return Response.json({ ok: true });
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { describeToLook, listCharacters, saveCharacter } from "@/lib/characters";
|
||||||
|
import { errorResponse, readJson } from "@/lib/http";
|
||||||
|
|
||||||
|
/** GET /api/characters — a biblioteca de personagens. */
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
return Response.json(listCharacters());
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/characters — cria um personagem: {name, description?, kind?}. A aparência sai da descrição (regras);
|
||||||
|
* depois dá para ajustar no formulário ou pedir ao agente.
|
||||||
|
*/
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
try {
|
||||||
|
const body = await readJson<{ name?: string; description?: string; kind?: string }>(request);
|
||||||
|
const description = String(body.description ?? "");
|
||||||
|
const draft = describeToLook(`${body.name ?? ""} ${description}`);
|
||||||
|
return Response.json(saveCharacter({ name: body.name, description, kind: body.kind, look: draft.look, caption: draft.caption }, true));
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { getCast, setCast } from "@/lib/characters";
|
||||||
|
import { errorResponse, readJson } from "@/lib/http";
|
||||||
|
import { UserError, getStory } from "@/lib/stories";
|
||||||
|
|
||||||
|
type Ctx = { params: Promise<{ storyId: string }> };
|
||||||
|
|
||||||
|
async function storyOf(ctx: Ctx): Promise<string> {
|
||||||
|
const { storyId } = await ctx.params;
|
||||||
|
if (!getStory(storyId)) throw new UserError("História não encontrada.");
|
||||||
|
return storyId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET — elenco da história (personagens da biblioteca). */
|
||||||
|
export async function GET(_request: Request, ctx: Ctx) {
|
||||||
|
try {
|
||||||
|
return Response.json(getCast(await storyOf(ctx)));
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PUT {cast: ["id", ...]} — troca o elenco (até 12). */
|
||||||
|
export async function PUT(request: Request, ctx: Ctx) {
|
||||||
|
try {
|
||||||
|
const storyId = await storyOf(ctx);
|
||||||
|
const body = await readJson<{ cast?: unknown }>(request);
|
||||||
|
return Response.json(setCast(storyId, body.cast));
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { CharacterStudio } from "@/components/character-studio";
|
||||||
|
import { UsersIcon } from "@/components/icons";
|
||||||
|
import { Meta, PageHeader } from "@/components/ui";
|
||||||
|
import { listCharacters } from "@/lib/characters";
|
||||||
|
|
||||||
|
export const metadata = { title: "Personagens" };
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default function CharactersPage() {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader eyebrow="Biblioteca" title="Personagens"
|
||||||
|
description="Crie um personagem uma vez e use em qualquer história: no estilo Cartoon ele sai igual em todas as cenas, mudando só expressão, pose e o que tem na mão."
|
||||||
|
meta={<Meta icon={<UsersIcon size={15} />}>Montado por peças · elenco escolhido em cada história</Meta>} />
|
||||||
|
<CharacterStudio initial={listCharacters()} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -164,8 +164,8 @@ export default async function EpisodePage({ params }: { params: Promise<{ storyI
|
|||||||
|
|
||||||
{documentary && script && (
|
{documentary && script && (
|
||||||
<Card className="order-first" eyebrow={<><ClapperIcon size={12} />Montagem</>} title="Montagem do vídeo"
|
<Card className="order-first" eyebrow={<><ClapperIcon size={12} />Montagem</>} title="Montagem do vídeo"
|
||||||
description="Um áudio por trecho (a voz fica natural) e um visual por trecho: foto, animação 2D, cena 3D do Godot, clipe ou cartela. Dá para misturar.">
|
description="Um áudio por trecho (a voz fica natural) e um visual por trecho: foto, animação 2D, cena 3D do Godot, Cartoon, clipe ou cartela. Dá para misturar.">
|
||||||
<MontageEditor episodeId={ep.id} />
|
<MontageEditor episodeId={ep.id} storyId={story.id} />
|
||||||
</Card>
|
</Card>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import Link from "next/link";
|
|||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useEffect, useRef, useState, type ComponentType } from "react";
|
import { useEffect, useRef, useState, type ComponentType } from "react";
|
||||||
import type { AgentEvent, AgentKind, AgentRun, Provider, StoryKind } from "@/lib/types";
|
import type { AgentEvent, AgentKind, AgentRun, Provider, StoryKind } from "@/lib/types";
|
||||||
import { BookIcon, CubeIcon, ChatIcon, ClapperIcon, PenIcon, SendIcon, SparkIcon, StopIcon, TerminalIcon } from "./icons";
|
import { BookIcon, CubeIcon, ChatIcon, ClapperIcon, PenIcon, SendIcon, SparkIcon, StopIcon, TerminalIcon, UsersIcon } from "./icons";
|
||||||
import { unitTerms } from "./story-formats";
|
import { unitTerms } from "./story-formats";
|
||||||
import { Badge, Button, EmptyState, Feedback, Field, Kbd, Select, StatusBadge, Textarea, cx } from "./ui";
|
import { Badge, Button, EmptyState, Feedback, Field, Kbd, Select, StatusBadge, Textarea, cx } from "./ui";
|
||||||
|
|
||||||
@@ -23,6 +23,7 @@ const KINDS: { id: AgentKind; label: string; description: string; icon: Componen
|
|||||||
{ id: "script", label: "Roteiro", description: "Escreve o episódio escolhido", icon: PenIcon },
|
{ id: "script", label: "Roteiro", description: "Escreve o episódio escolhido", icon: PenIcon },
|
||||||
{ id: "scene", label: "Cena", description: "Monta o JSON da cena a partir do roteiro", icon: ClapperIcon },
|
{ id: "scene", label: "Cena", description: "Monta o JSON da cena a partir do roteiro", icon: ClapperIcon },
|
||||||
{ id: "godot", label: "Cena no Godot", description: "Constrói uma cena 3D nova e guarda na biblioteca", icon: CubeIcon },
|
{ id: "godot", label: "Cena no Godot", description: "Constrói uma cena 3D nova e guarda na biblioteca", icon: CubeIcon },
|
||||||
|
{ id: "character", label: "Personagem", description: "Monta um personagem Cartoon para a biblioteca", icon: UsersIcon },
|
||||||
{ id: "free", label: "Pedido livre", description: "Ajustes no projeto, testes, iluminação", icon: ChatIcon },
|
{ id: "free", label: "Pedido livre", description: "Ajustes no projeto, testes, iluminação", icon: ChatIcon },
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -35,6 +36,7 @@ const PLACEHOLDER: Record<AgentKind, string> = {
|
|||||||
scene: "Ex.: Monte a cena a partir do roteiro; fim de tarde, moto azul.",
|
scene: "Ex.: Monte a cena a partir do roteiro; fim de tarde, moto azul.",
|
||||||
free: "Ex.: Melhore a iluminação do cenário e rode os testes.",
|
free: "Ex.: Melhore a iluminação do cenário e rode os testes.",
|
||||||
branches: "Ex.: Prepare as vertentes do episódio com consequências bem diferentes entre si.",
|
branches: "Ex.: Prepare as vertentes do episódio com consequências bem diferentes entre si.",
|
||||||
|
character: "Ex.: Personagem otavio: Otávio, 58 anos, engenheiro de minas, careca com barba grisalha e óculos redondos, uniforme verde.",
|
||||||
godot: "Ex.: Faça um campo de futebol de estádio, gramado listrado, traves e torcida; câmera de transmissão e atrás do gol. Depois, o Pelé batendo o pênalti do milésimo gol, de 1969, no Maracanã.",
|
godot: "Ex.: Faça um campo de futebol de estádio, gramado listrado, traves e torcida; câmera de transmissão e atrás do gol. Depois, o Pelé batendo o pênalti do milésimo gol, de 1969, no Maracanã.",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,232 @@
|
|||||||
|
"use client";
|
||||||
|
// Aba Personagens: cria pela descrição (regras na hora; o agente pode refinar), ajusta peça por peça com a
|
||||||
|
// prévia ao vivo (o MESMO desenho do render, vindo do pacote cartoon) e apaga. O elenco de cada história
|
||||||
|
// escolhe daqui (montagem Cartoon).
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import {
|
||||||
|
BEARD_STYLES, BOTTOM_STYLES, BROWS, BUILDS, EXPRESSIONS, GLASSES, HAIR_STYLES, POSES, TOP_STYLES,
|
||||||
|
type Character, type CharacterLook, type Expression, type Pose,
|
||||||
|
} from "cenaforge-cartoon/character";
|
||||||
|
import { CharacterFigure } from "cenaforge-cartoon/figure";
|
||||||
|
import { apiCall } from "./api-client";
|
||||||
|
import { askConfirm } from "./confirm-dialog";
|
||||||
|
import { PlusIcon, SparkIcon, TrashIcon, UsersIcon } from "./icons";
|
||||||
|
import { Badge, Button, Card, ChoiceGroup, EmptyState, Feedback, Field, Input, Select, Spinner, Textarea, cx } from "./ui";
|
||||||
|
|
||||||
|
const LABEL: Record<string, string> = {
|
||||||
|
slim: "magro", average: "médio", heavy: "forte",
|
||||||
|
short: "curto", side: "repartido", bun: "coque", long: "longo", curly: "cacheado", spiky: "espetado", bald: "careca", cap: "boné",
|
||||||
|
none: "nenhum", stubble: "por fazer", mustache: "bigode", full: "cheia", goatee: "cavanhaque",
|
||||||
|
round: "redondo", square: "quadrado", sun: "escuro", thin: "finas", thick: "grossas",
|
||||||
|
shirt: "camisa", jacket: "jaqueta", hoodie: "moletom", dress: "vestido", uniform: "uniforme",
|
||||||
|
pants: "calça", shorts: "bermuda", skirt: "saia",
|
||||||
|
neutral: "neutro", happy: "feliz", sad: "triste", worried: "preocupado", angry: "bravo", surprised: "surpreso", scared: "com medo",
|
||||||
|
stand: "em pé", point: "apontando", wave: "acenando", hold: "segurando", arms_up: "braços pra cima", shrug: "ombros", think: "pensando",
|
||||||
|
};
|
||||||
|
const label = (v: string) => LABEL[v] ?? v;
|
||||||
|
|
||||||
|
function Opt<T extends string>({ name, list, value, onChange }: { name: string; list: readonly T[]; value: T; onChange: (v: T) => void }) {
|
||||||
|
return (
|
||||||
|
<Field label={name}>
|
||||||
|
<Select value={value} onChange={(e) => onChange(e.target.value as T)}>
|
||||||
|
{list.map((v) => <option key={v} value={v}>{label(v)}</option>)}
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Color({ name, value, onChange }: { name: string; value: string; onChange: (v: string) => void }) {
|
||||||
|
return (
|
||||||
|
<Field label={name}>
|
||||||
|
<input type="color" value={value} onChange={(e) => onChange(e.target.value)} aria-label={name}
|
||||||
|
className="h-9 w-full cursor-pointer rounded-control border border-line-strong bg-raised p-1" />
|
||||||
|
</Field>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Mini({ c }: { c: Character }) {
|
||||||
|
return (
|
||||||
|
<div className="h-20 w-10 shrink-0"><CharacterFigure look={c.look} /></div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CharacterStudio({ initial }: { initial: Character[] }) {
|
||||||
|
const [list, setList] = useState(initial);
|
||||||
|
const [selectedId, setSelectedId] = useState<string | null>(initial[0]?.id ?? null);
|
||||||
|
const [draft, setDraft] = useState<Character | null>(initial[0] ?? null);
|
||||||
|
const [expression, setExpression] = useState<Expression>("neutral");
|
||||||
|
const [pose, setPose] = useState<Pose>("stand");
|
||||||
|
const [t, setT] = useState(0);
|
||||||
|
const [busy, setBusy] = useState<string | null>(null);
|
||||||
|
const [message, setMessage] = useState<{ ok: boolean; text: React.ReactNode } | null>(null);
|
||||||
|
const [newName, setNewName] = useState("");
|
||||||
|
const [newDescription, setNewDescription] = useState("");
|
||||||
|
const [newKind, setNewKind] = useState<"cartoon" | "3d">("cartoon");
|
||||||
|
|
||||||
|
// Prévia viva (respirar, piscar, acenar): o mesmo `t` que o render usa.
|
||||||
|
useEffect(() => {
|
||||||
|
let raf = 0;
|
||||||
|
const start = performance.now();
|
||||||
|
const tick = () => { setT((performance.now() - start) / 1000); raf = requestAnimationFrame(tick); };
|
||||||
|
raf = requestAnimationFrame(tick);
|
||||||
|
return () => cancelAnimationFrame(raf);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const select = (c: Character) => { setSelectedId(c.id); setDraft(c); setMessage(null); };
|
||||||
|
const setLook = (patch: (l: CharacterLook) => CharacterLook) => setDraft((d) => (d ? { ...d, look: patch(d.look) } : d));
|
||||||
|
const dirty = !!draft && JSON.stringify(draft) !== JSON.stringify(list.find((c) => c.id === draft.id));
|
||||||
|
|
||||||
|
async function reload(focus?: string) {
|
||||||
|
const r = await apiCall<Character[]>("/api/characters");
|
||||||
|
if (!r.ok) return;
|
||||||
|
setList(r.data);
|
||||||
|
const next = r.data.find((c) => c.id === (focus ?? selectedId)) ?? r.data[0] ?? null;
|
||||||
|
setSelectedId(next?.id ?? null);
|
||||||
|
setDraft(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function create() {
|
||||||
|
setBusy("create");
|
||||||
|
const r = await apiCall<Character>("/api/characters", "POST", { name: newName, description: newDescription, kind: newKind });
|
||||||
|
setBusy(null);
|
||||||
|
if (!r.ok) { setMessage({ ok: false, text: r.error }); return; }
|
||||||
|
setNewName(""); setNewDescription("");
|
||||||
|
await reload(r.data.id);
|
||||||
|
setMessage({ ok: true, text: `“${r.data.name}” criado pela descrição. Ajuste as peças ou peça ao agente para refinar.` });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
if (!draft) return;
|
||||||
|
setBusy("save");
|
||||||
|
const r = await apiCall<Character>(`/api/characters/${draft.id}`, "PUT", draft);
|
||||||
|
setBusy(null);
|
||||||
|
if (!r.ok) { setMessage({ ok: false, text: r.error }); return; }
|
||||||
|
await reload(draft.id);
|
||||||
|
setMessage({ ok: true, text: "Salvo. As próximas montagens Cartoon usam esta aparência." });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function askAgent() {
|
||||||
|
if (!draft) return;
|
||||||
|
setBusy("agent");
|
||||||
|
const r = await apiCall<{ runId: number }>(`/api/characters/${draft.id}/agent`, "POST", {});
|
||||||
|
setBusy(null);
|
||||||
|
setMessage(r.ok
|
||||||
|
? { ok: true, text: <>O agente está montando o personagem. Acompanhe em <a className="underline" href="/agent">Agente</a> e recarregue esta página quando terminar.</> }
|
||||||
|
: { ok: false, text: r.error });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove() {
|
||||||
|
if (!draft) return;
|
||||||
|
const ok = await askConfirm({ tone: "danger", title: `Apagar “${draft.name}”?`, message: <p>Some da biblioteca. Vídeos já renderizados não mudam.</p>, confirmLabel: "Apagar" });
|
||||||
|
if (!ok) return;
|
||||||
|
setBusy("delete");
|
||||||
|
const r = await apiCall<{ ok: true }>(`/api/characters/${draft.id}`, "DELETE");
|
||||||
|
setBusy(null);
|
||||||
|
if (!r.ok) { setMessage({ ok: false, text: r.error }); return; }
|
||||||
|
await reload("");
|
||||||
|
setMessage({ ok: true, text: "Personagem apagado." });
|
||||||
|
}
|
||||||
|
|
||||||
|
const look = draft?.look;
|
||||||
|
return (
|
||||||
|
<div className="grid gap-6 lg:grid-cols-[20rem_minmax(0,1fr)]">
|
||||||
|
<div className="grid content-start gap-5">
|
||||||
|
<Card title="Novo personagem" eyebrow="Pela descrição">
|
||||||
|
<div className="grid gap-3">
|
||||||
|
<Field label="Nome"><Input value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="Ex.: Otávio" /></Field>
|
||||||
|
<Field label="Descrição" hint="Idade, profissão, cabelo, barba, óculos, corpo, roupa e cores.">
|
||||||
|
<Textarea rows={4} value={newDescription} onChange={(e) => setNewDescription(e.target.value)}
|
||||||
|
placeholder="58 anos, engenheiro de minas, careca com barba grisalha, óculos redondos, uniforme verde" />
|
||||||
|
</Field>
|
||||||
|
<ChoiceGroup name="novo-tipo" legend="Tipo" value={newKind} onChange={setNewKind} options={[
|
||||||
|
{ value: "cartoon", label: "Cartoon", hint: "desenho 2D" },
|
||||||
|
{ value: "3d", label: "3D", hint: "Godot (em breve)" },
|
||||||
|
]} />
|
||||||
|
<Button onClick={() => void create()} disabled={busy !== null || newName.trim().length < 2}>
|
||||||
|
{busy === "create" ? <><Spinner />Criando…</> : <><PlusIcon size={15} />Criar personagem</>}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
<Card title={`Biblioteca (${list.length})`} padded={false}>
|
||||||
|
{list.length === 0 ? (
|
||||||
|
<EmptyState compact icon={<UsersIcon size={18} />} title="Nenhum personagem ainda">Crie o primeiro pela descrição.</EmptyState>
|
||||||
|
) : (
|
||||||
|
<ul className="grid divide-y divide-line">
|
||||||
|
{list.map((c) => (
|
||||||
|
<li key={c.id}>
|
||||||
|
<button type="button" onClick={() => select(c)} aria-pressed={c.id === selectedId}
|
||||||
|
className={cx("flex w-full items-center gap-3 px-4 py-2 text-left transition-colors hover:bg-raised/60", c.id === selectedId && "bg-accent-soft")}>
|
||||||
|
<Mini c={c} />
|
||||||
|
<span className="grid min-w-0">
|
||||||
|
<span className="truncate text-sm font-medium text-fg">{c.name}</span>
|
||||||
|
<span className="truncate text-xs text-fg-subtle">{c.caption ?? (c.kind === "3d" ? "3D" : "Cartoon")}</span>
|
||||||
|
</span>
|
||||||
|
{c.kind === "3d" && <Badge tone="info" dot={false} className="ml-auto">3D</Badge>}
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{draft && look ? (
|
||||||
|
<div className="grid content-start gap-5">
|
||||||
|
<div className="grid gap-5 xl:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
|
||||||
|
<div className="grid content-start gap-3">
|
||||||
|
<div className="grid place-items-center rounded-lg border border-line-strong bg-[#2a2e45] p-4">
|
||||||
|
<div className="h-80 w-36"><CharacterFigure look={look} expression={expression} pose={pose} item={pose === "hold" || pose === "point" ? "phone" : undefined} t={t} /></div>
|
||||||
|
</div>
|
||||||
|
<Opt name="Expressão (prévia)" list={EXPRESSIONS} value={expression} onChange={setExpression} />
|
||||||
|
<Opt name="Pose (prévia)" list={POSES} value={pose} onChange={setPose} />
|
||||||
|
</div>
|
||||||
|
<div className="grid content-start gap-4">
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2">
|
||||||
|
<Field label="Nome"><Input value={draft.name} onChange={(e) => setDraft({ ...draft, name: e.target.value })} /></Field>
|
||||||
|
<Field label="Legenda" hint="Aparece na 1ª cena (função · idade)."><Input value={draft.caption ?? ""} onChange={(e) => setDraft({ ...draft, caption: e.target.value })} /></Field>
|
||||||
|
</div>
|
||||||
|
<Field label="Descrição"><Textarea rows={2} value={draft.description ?? ""} onChange={(e) => setDraft({ ...draft, description: e.target.value })} /></Field>
|
||||||
|
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||||
|
<Opt name="Corpo" list={BUILDS} value={look.build} onChange={(v) => setLook((l) => ({ ...l, build: v }))} />
|
||||||
|
<Field label={`Altura (${look.height.toFixed(2)})`}>
|
||||||
|
<input type="range" min={0.7} max={1.15} step={0.01} value={look.height} className="h-9 w-full accent-accent"
|
||||||
|
onChange={(e) => setLook((l) => ({ ...l, height: Number(e.target.value) }))} />
|
||||||
|
</Field>
|
||||||
|
<Color name="Pele" value={look.skin} onChange={(v) => setLook((l) => ({ ...l, skin: v }))} />
|
||||||
|
<Color name="Sapato" value={look.shoes} onChange={(v) => setLook((l) => ({ ...l, shoes: v }))} />
|
||||||
|
<Opt name="Cabelo" list={HAIR_STYLES} value={look.hair.style} onChange={(v) => setLook((l) => ({ ...l, hair: { ...l.hair, style: v } }))} />
|
||||||
|
<Color name="Cor do cabelo" value={look.hair.color} onChange={(v) => setLook((l) => ({ ...l, hair: { ...l.hair, color: v } }))} />
|
||||||
|
<Opt name="Barba" list={BEARD_STYLES} value={look.beard.style} onChange={(v) => setLook((l) => ({ ...l, beard: { ...l.beard, style: v } }))} />
|
||||||
|
<Color name="Cor da barba" value={look.beard.color} onChange={(v) => setLook((l) => ({ ...l, beard: { ...l.beard, color: v } }))} />
|
||||||
|
<Opt name="Óculos" list={GLASSES} value={look.glasses} onChange={(v) => setLook((l) => ({ ...l, glasses: v }))} />
|
||||||
|
<Opt name="Sobrancelhas" list={BROWS} value={look.brows} onChange={(v) => setLook((l) => ({ ...l, brows: v }))} />
|
||||||
|
<Opt name="Parte de cima" list={TOP_STYLES} value={look.top.style} onChange={(v) => setLook((l) => ({ ...l, top: { ...l.top, style: v } }))} />
|
||||||
|
<Color name="Cor de cima" value={look.top.color} onChange={(v) => setLook((l) => ({ ...l, top: { ...l.top, color: v } }))} />
|
||||||
|
<Color name="Detalhe (faixa/gola)" value={look.top.accent ?? "#e8b13a"} onChange={(v) => setLook((l) => ({ ...l, top: { ...l.top, accent: v } }))} />
|
||||||
|
<Opt name="Parte de baixo" list={BOTTOM_STYLES} value={look.bottom.style} onChange={(v) => setLook((l) => ({ ...l, bottom: { ...l.bottom, style: v } }))} />
|
||||||
|
<Color name="Cor de baixo" value={look.bottom.color} onChange={(v) => setLook((l) => ({ ...l, bottom: { ...l.bottom, color: v } }))} />
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<Button onClick={() => void save()} disabled={busy !== null || !dirty}>{busy === "save" ? <><Spinner />Salvando…</> : "Salvar"}</Button>
|
||||||
|
<Button variant="secondary" onClick={() => void askAgent()} disabled={busy !== null || dirty}
|
||||||
|
title={dirty ? "Salve antes de pedir ao agente" : "O agente refina as peças a partir da descrição"}>
|
||||||
|
{busy === "agent" ? <><Spinner />Enviando…</> : <><SparkIcon size={15} />Refinar com o agente</>}
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" className="ml-auto text-fg-muted hover:text-danger" onClick={() => void remove()} disabled={busy !== null}>
|
||||||
|
<TrashIcon size={15} />Apagar
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{draft.kind === "3d" && <p className="text-xs text-fg-subtle">Personagem 3D: o cadastro já fica na biblioteca; o uso na Godot vem numa próxima etapa. A prévia mostra a versão Cartoon.</p>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div aria-live="polite" className="grid content-start gap-3">
|
||||||
|
{message && <Feedback ok={message.ok}>{message.text}</Feedback>}
|
||||||
|
<EmptyState icon={<UsersIcon size={18} />} title="Escolha ou crie um personagem">A prévia e as peças aparecem aqui.</EmptyState>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -7,20 +7,23 @@ import type { RenderJob } from "@/lib/types";
|
|||||||
import { AlertIcon, CheckIcon, ClapperIcon, EyeIcon, MicIcon, PlayIcon, RefreshIcon, SparkIcon, StopIcon, UploadIcon, WaveIcon } from "./icons";
|
import { AlertIcon, CheckIcon, ClapperIcon, EyeIcon, MicIcon, PlayIcon, RefreshIcon, SparkIcon, StopIcon, UploadIcon, WaveIcon } from "./icons";
|
||||||
import { Badge, Button, ChoiceGroup, Feedback, Input, RangeField, Select, Spinner, StatusBadge, Switch, Textarea, cx, fileUrl, formatDate } from "./ui";
|
import { Badge, Button, ChoiceGroup, Feedback, Input, RangeField, Select, Spinner, StatusBadge, Switch, Textarea, cx, fileUrl, formatDate } from "./ui";
|
||||||
|
|
||||||
type VisualKind = "image" | "video" | "godot3d" | "card" | "godot2d";
|
type VisualKind = "image" | "video" | "godot3d" | "card" | "godot2d" | "cartoon";
|
||||||
|
/** Espelho de CartoonScene (panel/src/lib/montage-cartoon.ts): só o que a tela mostra. */
|
||||||
|
type CartoonPlan = { scene: { kind: string; time?: string }; props?: { label?: string }[]; actors?: { kind: string; label?: string }[]; texts?: { kind: string; text: string }[] };
|
||||||
type Template = "title" | "counter" | "map";
|
type Template = "title" | "counter" | "map";
|
||||||
type Scene = { kind?: "doc2d" | "doc3d"; template: Template | "island"; params: Record<string, unknown> };
|
type Scene = { kind?: "doc2d" | "doc3d"; template: Template | "island"; params: Record<string, unknown> };
|
||||||
type ShotVisual = {
|
type ShotVisual = {
|
||||||
kind: VisualKind; file: string | null; credit: string; license: string; sourceUrl: string;
|
kind: VisualKind; file: string | null; credit: string; license: string; sourceUrl: string;
|
||||||
scene?: Scene; sceneKey?: string; search?: { queries: string[]; pick: number }; auto?: boolean;
|
scene?: Scene; sceneKey?: string; search?: { queries: string[]; pick: number }; auto?: boolean;
|
||||||
inset?: { file: string; credit: string; license: string; sourceUrl: string } | null;
|
inset?: { file: string; credit: string; license: string; sourceUrl: string } | null;
|
||||||
|
cartoon?: CartoonPlan; cartoonKey?: string;
|
||||||
};
|
};
|
||||||
type MontageShot = {
|
type MontageShot = {
|
||||||
index: number; time: string; narration: string; onScreen: string; visualHint: string;
|
index: number; time: string; narration: string; onScreen: string; visualHint: string;
|
||||||
spoken: string; spokenEdited: boolean; visual: ShotVisual;
|
spoken: string; spokenEdited: boolean; visual: ShotVisual;
|
||||||
audio: { file: string; durationMs: number } | null; audioStale: boolean;
|
audio: { file: string; durationMs: number } | null; audioStale: boolean;
|
||||||
};
|
};
|
||||||
type Montage = { episodeId: number; voiceId: string; speed: number; captions: boolean; style: "mixed" | "3d"; shots: MontageShot[] };
|
type Montage = { episodeId: number; voiceId: string; speed: number; captions: boolean; style: "mixed" | "3d" | "cartoon"; cartoonPalette: string; shots: MontageShot[] };
|
||||||
type Option = { file: string; name: string };
|
type Option = { file: string; name: string };
|
||||||
type State = {
|
type State = {
|
||||||
storyId: string;
|
storyId: string;
|
||||||
@@ -46,7 +49,7 @@ async function call<T>(url: string, init?: RequestInit): Promise<T> {
|
|||||||
return body as T;
|
return body as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function MontageEditor({ episodeId }: { episodeId: number }) {
|
export function MontageEditor({ episodeId, storyId }: { episodeId: number; storyId: string }) {
|
||||||
const base = `/api/episodes/${episodeId}/montage`;
|
const base = `/api/episodes/${episodeId}/montage`;
|
||||||
const [state, setState] = useState<State | null>(null);
|
const [state, setState] = useState<State | null>(null);
|
||||||
const [voices, setVoices] = useState<Voice[] | null>(null);
|
const [voices, setVoices] = useState<Voice[] | null>(null);
|
||||||
@@ -152,7 +155,7 @@ export function MontageEditor({ episodeId }: { episodeId: number }) {
|
|||||||
const { montage } = state;
|
const { montage } = state;
|
||||||
const missingAudioList = montage.shots.filter((s) => !s.audio || s.audioStale).map((s) => s.index + 1);
|
const missingAudioList = montage.shots.filter((s) => !s.audio || s.audioStale).map((s) => s.index + 1);
|
||||||
// Cena 2D do Godot conta como visual escolhido: ela é renderizada na hora de montar.
|
// Cena 2D do Godot conta como visual escolhido: ela é renderizada na hora de montar.
|
||||||
const missingVisualList = montage.shots.filter((s) => s.visual.kind !== "card" && s.visual.kind !== "godot2d" && !s.visual.file).map((s) => s.index + 1);
|
const missingVisualList = montage.shots.filter((s) => s.visual.kind !== "card" && s.visual.kind !== "godot2d" && s.visual.kind !== "cartoon" && !s.visual.file).map((s) => s.index + 1);
|
||||||
const missingAudio = missingAudioList.length;
|
const missingAudio = missingAudioList.length;
|
||||||
const missingVisual = missingVisualList.length;
|
const missingVisual = missingVisualList.length;
|
||||||
|
|
||||||
@@ -187,7 +190,12 @@ export function MontageEditor({ episodeId }: { episodeId: number }) {
|
|||||||
options={[
|
options={[
|
||||||
{ value: "mixed", label: "Misto: fotos, 2D e 3D" },
|
{ value: "mixed", label: "Misto: fotos, 2D e 3D" },
|
||||||
{ value: "3d", label: "Tudo em 3D (fotos em cartão)" },
|
{ value: "3d", label: "Tudo em 3D (fotos em cartão)" },
|
||||||
|
{ value: "cartoon", label: "Cartoon: desenho 2D chapado" },
|
||||||
]} />
|
]} />
|
||||||
|
{montage.style === "cartoon" && (
|
||||||
|
<CartoonSetup storyId={storyId} palette={montage.cartoonPalette} disabled={working}
|
||||||
|
onPalette={(v) => void patch({ cartoonPalette: v })} onCastChanged={() => void patch({ replanCartoon: true })} />
|
||||||
|
)}
|
||||||
{!voiceOnline && <p className="flex items-center gap-2 text-xs text-warning"><AlertIcon size={14} />O serviço de voz está fora do ar: sem ele não dá para gerar os áudios.</p>}
|
{!voiceOnline && <p className="flex items-center gap-2 text-xs text-warning"><AlertIcon size={14} />O serviço de voz está fora do ar: sem ele não dá para gerar os áudios.</p>}
|
||||||
|
|
||||||
{/* Um clique: plano das cenas + narração + cenas 2D no Godot + montagem. */}
|
{/* Um clique: plano das cenas + narração + cenas 2D no Godot + montagem. */}
|
||||||
@@ -305,7 +313,7 @@ function ShotRow({ shot, state, base, busy, disabled, canGenerate, onGenerate, o
|
|||||||
useEffect(() => { setSpoken(shot.spoken); saved.current = shot.spoken; }, [shot.spoken]);
|
useEffect(() => { setSpoken(shot.spoken); saved.current = shot.spoken; }, [shot.spoken]);
|
||||||
const n = shot.index + 1;
|
const n = shot.index + 1;
|
||||||
const audioOk = !!shot.audio && !shot.audioStale;
|
const audioOk = !!shot.audio && !shot.audioStale;
|
||||||
const visualOk = shot.visual.kind === "card" || shot.visual.kind === "godot2d" || !!shot.visual.file;
|
const visualOk = shot.visual.kind === "card" || shot.visual.kind === "godot2d" || shot.visual.kind === "cartoon" || !!shot.visual.file;
|
||||||
|
|
||||||
function saveSpoken() {
|
function saveSpoken() {
|
||||||
if (spoken.trim() === saved.current.trim()) return;
|
if (spoken.trim() === saved.current.trim()) return;
|
||||||
@@ -323,7 +331,7 @@ function ShotRow({ shot, state, base, busy, disabled, canGenerate, onGenerate, o
|
|||||||
<Badge tone={audioOk ? "success" : shot.audioStale ? "warning" : "neutral"}>
|
<Badge tone={audioOk ? "success" : shot.audioStale ? "warning" : "neutral"}>
|
||||||
{audioOk ? `áudio ${fmtSeconds(shot.audio!.durationMs)}` : shot.audioStale ? "áudio desatualizado" : "sem áudio"}
|
{audioOk ? `áudio ${fmtSeconds(shot.audio!.durationMs)}` : shot.audioStale ? "áudio desatualizado" : "sem áudio"}
|
||||||
</Badge>
|
</Badge>
|
||||||
<Badge tone={visualOk ? "success" : "neutral"}>{shot.visual.kind === "godot2d" ? "cena 2D" : visualOk ? "visual ok" : "sem visual"}</Badge>
|
<Badge tone={visualOk ? "success" : "neutral"}>{shot.visual.kind === "godot2d" ? "cena 2D" : shot.visual.kind === "cartoon" ? "cartoon" : visualOk ? "visual ok" : "sem visual"}</Badge>
|
||||||
</span>
|
</span>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@@ -419,15 +427,17 @@ function VisualEditor({ shot, state, base, disabled, onPatch, onUploaded, onErro
|
|||||||
<div className="grid content-start gap-3">
|
<div className="grid content-start gap-3">
|
||||||
<div className="flex items-center justify-between gap-2">
|
<div className="flex items-center justify-between gap-2">
|
||||||
<span className="flex items-center gap-1.5 text-eyebrow font-semibold text-fg-subtle uppercase"><EyeIcon size={13} />Visual</span>
|
<span className="flex items-center gap-1.5 text-eyebrow font-semibold text-fg-subtle uppercase"><EyeIcon size={13} />Visual</span>
|
||||||
{(kind === "godot2d" || kind === "godot3d" || kind === "image") && (
|
{(kind === "godot2d" || kind === "godot3d" || kind === "image" || kind === "cartoon") && (
|
||||||
<Button size="sm" variant="ghost" disabled={disabled || regenerating} onClick={() => void regenerate()}
|
<Button size="sm" variant="ghost" disabled={disabled || regenerating} onClick={() => void regenerate()}
|
||||||
title={kind === "image" ? "Busca outra imagem na internet (sem repetir as dos outros trechos)" : "Outra variação de layout, câmera e cores, renderizada no Godot"}>
|
title={kind === "image" ? "Busca outra imagem na internet (sem repetir as dos outros trechos)"
|
||||||
|
: kind === "cartoon" ? "Outro arranjo da cena (fundo, câmera, roupa), renderizado na hora se o áudio estiver pronto"
|
||||||
|
: "Outra variação de layout, câmera e cores, renderizada no Godot"}>
|
||||||
{regenerating ? <><Spinner />{kind === "image" ? "Buscando…" : "Renderizando…"}</> : <><RefreshIcon size={14} />{kind === "image" && !shot.visual.file ? "Buscar na internet" : "Gerar de novo"}</>}
|
{regenerating ? <><Spinner />{kind === "image" ? "Buscando…" : "Renderizando…"}</> : <><RefreshIcon size={14} />{kind === "image" && !shot.visual.file ? "Buscar na internet" : "Gerar de novo"}</>}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{/* Estilo do trecho: pode misturar no mesmo vídeo */}
|
{/* Estilo do trecho: pode misturar no mesmo vídeo */}
|
||||||
<div role="radiogroup" aria-label={`Estilo do visual do trecho ${shot.index + 1}`} className="grid grid-cols-3 gap-1.5 sm:grid-cols-5">
|
<div role="radiogroup" aria-label={`Estilo do visual do trecho ${shot.index + 1}`} className="grid grid-cols-3 gap-1.5 sm:grid-cols-6">
|
||||||
{state.kinds.map((k) => (
|
{state.kinds.map((k) => (
|
||||||
<button key={k.id} type="button" role="radio" aria-checked={kind === k.id} disabled={!k.available || disabled} title={k.hint}
|
<button key={k.id} type="button" role="radio" aria-checked={kind === k.id} disabled={!k.available || disabled} title={k.hint}
|
||||||
onClick={() => void onPatch({ shot: { index: shot.index, visual: { kind: k.id, file: null } } })}
|
onClick={() => void onPatch({ shot: { index: shot.index, visual: { kind: k.id, file: null } } })}
|
||||||
@@ -441,6 +451,8 @@ function VisualEditor({ shot, state, base, disabled, onPatch, onUploaded, onErro
|
|||||||
|
|
||||||
{kind === "godot2d" || kind === "godot3d" ? (
|
{kind === "godot2d" || kind === "godot3d" ? (
|
||||||
<SceneEditor shot={shot} state={state} base={base} disabled={disabled} onPatch={onPatch} onUploaded={onUploaded} onError={onError} />
|
<SceneEditor shot={shot} state={state} base={base} disabled={disabled} onPatch={onPatch} onUploaded={onUploaded} onError={onError} />
|
||||||
|
) : kind === "cartoon" ? (
|
||||||
|
<CartoonPreview shot={shot} />
|
||||||
) : kind === "card" ? (
|
) : kind === "card" ? (
|
||||||
<div className="grid h-28 place-items-center rounded-control border border-line bg-[#0d0d10] px-4 text-center font-display text-lg font-bold text-white">
|
<div className="grid h-28 place-items-center rounded-control border border-line bg-[#0d0d10] px-4 text-center font-display text-lg font-bold text-white">
|
||||||
{shot.onScreen || <span className="text-sm font-normal text-fg-subtle">Sem texto na tela neste trecho</span>}
|
{shot.onScreen || <span className="text-sm font-normal text-fg-subtle">Sem texto na tela neste trecho</span>}
|
||||||
@@ -663,3 +675,90 @@ function InsetCard({ shot, base, disabled, onUploaded, onError }: {
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Trecho Cartoon: o vídeo renderizado (se já houver) e o que o plano pôs na cena. */
|
||||||
|
function CartoonPreview({ shot }: { shot: MontageShot }) {
|
||||||
|
const plan = shot.visual.cartoon;
|
||||||
|
const SCENE: Record<string, string> = { street: "rua", house: "frente da casa", plain: "fundo liso", blueprint: "diagrama", card: "cartela" };
|
||||||
|
const TIME: Record<string, string> = { night: "noite", dawn: "amanhecer", day: "dia" };
|
||||||
|
const items = plan ? [
|
||||||
|
...(plan.actors ?? []).map((a) => (a.kind === "crowd" ? "multidão" : a.label ?? "personagem")),
|
||||||
|
...(plan.props ?? []).map((p) => p.label ?? "objeto"),
|
||||||
|
...(plan.texts ?? []).map((t) => `“${t.text}”`),
|
||||||
|
] : [];
|
||||||
|
return (
|
||||||
|
<div className="grid gap-3 sm:grid-cols-[6.5rem_minmax(0,1fr)]">
|
||||||
|
<div className="relative aspect-[9/16] w-full overflow-hidden rounded-lg border border-line-strong bg-[#0b0e22]">
|
||||||
|
{shot.visual.file
|
||||||
|
? <video key={shot.visual.file} muted playsInline loop controls preload="metadata" className="size-full object-cover" src={fileUrl(shot.visual.file)} />
|
||||||
|
: <span className="grid size-full place-items-center px-2 text-center text-[0.6875rem] text-fg-subtle">renderiza na montagem</span>}
|
||||||
|
</div>
|
||||||
|
<div className="grid content-start gap-1.5 text-xs leading-relaxed text-fg-muted">
|
||||||
|
{plan ? (
|
||||||
|
<>
|
||||||
|
<p><span className="font-medium text-fg">Cena:</span> {SCENE[plan.scene.kind] ?? plan.scene.kind}{plan.scene.time ? ` · ${TIME[plan.scene.time] ?? plan.scene.time}` : ""}</p>
|
||||||
|
<p><span className="font-medium text-fg">Na cena:</span> {items.length ? items.join(", ") : "só o cenário"}</p>
|
||||||
|
</>
|
||||||
|
) : <p>O plano sai do texto do trecho quando a montagem rodar.</p>}
|
||||||
|
<p className="text-fg-subtle">Legenda palavra por palavra e texto na tela já vêm dentro da cena. “Gerar de novo” troca o arranjo.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Estilo Cartoon: a paleta da série e o elenco da história (personagens da biblioteca, aba Personagens). */
|
||||||
|
const PALETTE_LABEL: Record<string, string> = { "": "Pela hora de cada trecho", night: "Noite azul", sepia: "Sépia terroso", day: "Dia claro", dusk: "Entardecer", gray: "Cinza nublado" };
|
||||||
|
|
||||||
|
function CartoonSetup({ storyId, palette, disabled, onPalette, onCastChanged }: {
|
||||||
|
storyId: string; palette: string; disabled: boolean; onPalette: (v: string) => void; onCastChanged: () => void;
|
||||||
|
}) {
|
||||||
|
type Person = { id: string; name: string; caption?: string; kind: string };
|
||||||
|
const [all, setAll] = useState<Person[] | null>(null);
|
||||||
|
const [cast, setCast] = useState<string[]>([]);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
void Promise.all([fetch("/api/characters").then((r) => r.json()), fetch(`/api/stories/${storyId}/cast`).then((r) => r.json())])
|
||||||
|
.then(([chars, current]) => { setAll(Array.isArray(chars) ? chars : []); setCast(Array.isArray(current) ? current.map((c: Person) => c.id) : []); })
|
||||||
|
.catch(() => setError("Não deu para ler a biblioteca de personagens."));
|
||||||
|
}, [storyId]);
|
||||||
|
async function toggle(id: string) {
|
||||||
|
const next = cast.includes(id) ? cast.filter((c) => c !== id) : [...cast, id];
|
||||||
|
setSaving(true);
|
||||||
|
setError(null);
|
||||||
|
const r = await fetch(`/api/stories/${storyId}/cast`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ cast: next }) });
|
||||||
|
setSaving(false);
|
||||||
|
if (!r.ok) { setError(((await r.json()) as { error?: string }).error ?? "Não deu para salvar o elenco."); return; }
|
||||||
|
setCast(((await r.json()) as Person[]).map((c) => c.id));
|
||||||
|
onCastChanged();
|
||||||
|
}
|
||||||
|
const cartoon = (all ?? []).filter((c) => c.kind === "cartoon");
|
||||||
|
return (
|
||||||
|
<div className="grid gap-3 rounded-control border border-line bg-sunken/40 px-3.5 py-3">
|
||||||
|
<label className="grid gap-1.5 text-[0.8125rem] font-medium text-fg-muted">
|
||||||
|
Paleta da série
|
||||||
|
<Select value={palette} disabled={disabled} onChange={(e) => onPalette(e.target.value)} className="h-9">
|
||||||
|
{Object.entries(PALETTE_LABEL).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
|
||||||
|
</Select>
|
||||||
|
</label>
|
||||||
|
<div className="grid gap-1.5">
|
||||||
|
<span className="text-[0.8125rem] font-medium text-fg-muted">Elenco desta história</span>
|
||||||
|
{all === null ? <span className="text-xs text-fg-subtle">Carregando…</span>
|
||||||
|
: cartoon.length === 0 ? <span className="text-xs text-fg-subtle">Nenhum personagem Cartoon na biblioteca. Crie em <a className="underline" href="/characters">Personagens</a>.</span>
|
||||||
|
: (
|
||||||
|
<div className="flex flex-wrap gap-1.5">
|
||||||
|
{cartoon.map((c) => (
|
||||||
|
<button key={c.id} type="button" aria-pressed={cast.includes(c.id)} disabled={disabled || saving} onClick={() => void toggle(c.id)} title={c.caption}
|
||||||
|
className={cx("h-8 rounded-full border px-3 text-xs font-medium transition-colors disabled:opacity-45",
|
||||||
|
cast.includes(c.id) ? "border-accent/60 bg-accent-soft text-accent" : "border-line-strong bg-raised text-fg-muted hover:text-fg")}>
|
||||||
|
{c.name}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<span className="text-xs leading-relaxed text-fg-subtle">Quem é citado pelo nome no trecho aparece com a aparência da biblioteca; com um personagem só, ele é o fio condutor. Mudar o elenco ou a paleta refaz o plano dos trechos automáticos.</span>
|
||||||
|
{error && <span className="text-xs text-danger">{error}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ const NAV: NavItem[] = [
|
|||||||
{ href: "/dashboard", label: "Dashboard", hint: "O que funciona e o que não", icon: ChartIcon },
|
{ href: "/dashboard", label: "Dashboard", hint: "O que funciona e o que não", icon: ChartIcon },
|
||||||
{ href: "/", label: "Histórias", hint: "Episódios e votação", icon: FilmIcon },
|
{ href: "/", label: "Histórias", hint: "Episódios e votação", icon: FilmIcon },
|
||||||
{ href: "/clipper", label: "Clipador", hint: "Cortes de live", icon: ScissorsIcon },
|
{ href: "/clipper", label: "Clipador", hint: "Cortes de live", icon: ScissorsIcon },
|
||||||
|
{ href: "/characters", label: "Personagens", hint: "Elenco reaproveitável", icon: UsersIcon },
|
||||||
{ href: "/assets", label: "Assets", hint: "Biblioteca e envios", icon: CubeIcon },
|
{ href: "/assets", label: "Assets", hint: "Biblioteca e envios", icon: CubeIcon },
|
||||||
{ href: "/voices", label: "Vozes", hint: "Narração e legenda", icon: MicIcon },
|
{ href: "/voices", label: "Vozes", hint: "Narração e legenda", icon: MicIcon },
|
||||||
{ href: "/agent", label: "Agente", hint: "Claude e Codex", icon: TerminalIcon },
|
{ href: "/agent", label: "Agente", hint: "Claude e Codex", icon: TerminalIcon },
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ const CLAUDE_LEAN_FLAGS = ["--setting-sources", "project,local", "--strict-mcp-c
|
|||||||
* custou US$ 3,09 no Opus e o padrão agora é o Sonnet. Ao atingir, a CLI encerra a execução e o
|
* custou US$ 3,09 no Opus e o padrão agora é o Sonnet. Ao atingir, a CLI encerra a execução e o
|
||||||
* usuário pode continuar a conversa pelo painel.
|
* usuário pode continuar a conversa pelo painel.
|
||||||
*/
|
*/
|
||||||
export const CLAUDE_BUDGET_USD: Record<AgentKind, number> = { story: 1.5, script: 1.5, branches: 2.5, scene: 1, godot: 3, free: 3 };
|
export const CLAUDE_BUDGET_USD: Record<AgentKind, number> = { story: 1.5, script: 1.5, branches: 2.5, scene: 1, godot: 3, free: 3, character: 0.5 };
|
||||||
|
|
||||||
export type ModelOption = { id: string; label: string };
|
export type ModelOption = { id: string; label: string };
|
||||||
|
|
||||||
@@ -98,13 +98,13 @@ export function models(): Record<Provider, ModelOption[]> {
|
|||||||
/** Modelo sugerido por tipo de tarefa (economia de tokens). */
|
/** Modelo sugerido por tipo de tarefa (economia de tokens). */
|
||||||
// Vertentes: roteiro + cena de 2–4 episódios numa execução só → Sonnet (qualidade de roteiro sem o custo do Opus).
|
// Vertentes: roteiro + cena de 2–4 episódios numa execução só → Sonnet (qualidade de roteiro sem o custo do Opus).
|
||||||
// Cena no Godot: Sonnet (a cena dos náufragos no Opus custou US$ 3,09 e esgotou o limite de 5 h em 11 min).
|
// Cena no Godot: Sonnet (a cena dos náufragos no Opus custou US$ 3,09 e esgotou o limite de 5 h em 11 min).
|
||||||
export const DEFAULT_MODEL: Record<AgentKind, string> = { free: "", story: "", script: "", scene: "claude-sonnet-5-5", branches: "claude-sonnet-5-5", godot: "claude-sonnet-5-5" };
|
export const DEFAULT_MODEL: Record<AgentKind, string> = { free: "", story: "", script: "", scene: "claude-sonnet-5-5", branches: "claude-sonnet-5-5", godot: "claude-sonnet-5-5", character: "claude-sonnet-5-5" };
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Agente preferido por tarefa (decisão do usuário: enredo e roteiro com GPT, via Codex).
|
* Agente preferido por tarefa (decisão do usuário: enredo e roteiro com GPT, via Codex).
|
||||||
* Se o preferido não estiver disponível, cai para o outro.
|
* Se o preferido não estiver disponível, cai para o outro.
|
||||||
*/
|
*/
|
||||||
export const PREFERRED_PROVIDER: Record<AgentKind, Provider> = { free: "claude", story: "codex", script: "codex", scene: "claude", branches: "codex", godot: "claude" };
|
export const PREFERRED_PROVIDER: Record<AgentKind, Provider> = { free: "claude", story: "codex", script: "codex", scene: "claude", branches: "codex", godot: "claude", character: "claude" };
|
||||||
|
|
||||||
export function defaultProviderFor(kind: AgentKind): Provider {
|
export function defaultProviderFor(kind: AgentKind): Provider {
|
||||||
const list = providers();
|
const list = providers();
|
||||||
@@ -123,7 +123,7 @@ export function defaultModelFor(kind: AgentKind, provider: Provider): string {
|
|||||||
* "frontier" do config.toml (GPT-6-Astra, o mais caro). "" = o padrão do config.toml. Só vale se o
|
* "frontier" do config.toml (GPT-6-Astra, o mais caro). "" = o padrão do config.toml. Só vale se o
|
||||||
* modelo existir na lista da CLI; senão cai no padrão.
|
* modelo existir na lista da CLI; senão cai no padrão.
|
||||||
*/
|
*/
|
||||||
const CODEX_DEFAULT_MODEL: Record<AgentKind, string> = { free: "", story: "gpt-6.1-sol", script: "gpt-6.1-sol", branches: "gpt-6.1-sol", scene: "", godot: "" };
|
const CODEX_DEFAULT_MODEL: Record<AgentKind, string> = { free: "", story: "gpt-6.1-sol", script: "gpt-6.1-sol", branches: "gpt-6.1-sol", scene: "", godot: "", character: "" };
|
||||||
|
|
||||||
/** `command` + `prefixArgs` é o que de fato executamos (ex.: node + codex.js no Windows). */
|
/** `command` + `prefixArgs` é o que de fato executamos (ex.: node + codex.js no Windows). */
|
||||||
type ProviderInfo = {
|
type ProviderInfo = {
|
||||||
@@ -381,7 +381,7 @@ export function readEvents(id: number): AgentEvent[] {
|
|||||||
* de fatos; fica "medium". A cena no Godot (#8) gastou 14,5 mil: "medium". A cena JSON só roda
|
* de fatos; fica "medium". A cena no Godot (#8) gastou 14,5 mil: "medium". A cena JSON só roda
|
||||||
* um script: "low". "" = o do config.toml.
|
* um script: "low". "" = o do config.toml.
|
||||||
*/
|
*/
|
||||||
const CODEX_EFFORT: Record<AgentKind, string> = { story: "medium", script: "medium", branches: "medium", godot: "medium", scene: "low", free: "" };
|
const CODEX_EFFORT: Record<AgentKind, string> = { story: "medium", script: "medium", branches: "medium", godot: "medium", scene: "low", free: "", character: "low" };
|
||||||
|
|
||||||
/** Plugins do Codex que não servem ao repositório: o de computer-use põe a ferramenta `cua_repl` (~6,5 mil caracteres) em todo turno. */
|
/** Plugins do Codex que não servem ao repositório: o de computer-use põe a ferramenta `cua_repl` (~6,5 mil caracteres) em todo turno. */
|
||||||
const CODEX_UNUSED_PLUGINS = ["computer-use@openai-bundled", "unified-computer-use@openai-bundled"];
|
const CODEX_UNUSED_PLUGINS = ["computer-use@openai-bundled", "unified-computer-use@openai-bundled"];
|
||||||
|
|||||||
@@ -0,0 +1,174 @@
|
|||||||
|
// Biblioteca de personagens: assets/characters/<id>/character.json. Um personagem é criado uma vez (da
|
||||||
|
// descrição, ajustado no formulário ou pelo agente) e reaproveitado em qualquer história: o elenco da história
|
||||||
|
// fica em stories/<id>/cast.json e a montagem Cartoon usa a mesma aparência em todas as cenas.
|
||||||
|
// O contrato da aparência é o do pacote cartoon (cartoon/src/character.ts), importado direto daqui.
|
||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import {
|
||||||
|
DEFAULT_LOOK, EXPRESSIONS, POSES, validateLook, type Character, type CharacterLook, type Expression, type Pose,
|
||||||
|
} from "cenaforge-cartoon/character";
|
||||||
|
import { REPO_ROOT, SLUG_RE, rel, storyDir } from "./paths";
|
||||||
|
import { UserError } from "./stories";
|
||||||
|
|
||||||
|
export type { Character, CharacterLook, Expression, Pose };
|
||||||
|
export { EXPRESSIONS, POSES };
|
||||||
|
|
||||||
|
export const CHARACTERS_DIR = path.join(REPO_ROOT, "assets", "characters");
|
||||||
|
const fileOf = (id: string) => path.join(CHARACTERS_DIR, id, "character.json");
|
||||||
|
|
||||||
|
function mustId(id: string): string {
|
||||||
|
if (!SLUG_RE.test(id)) throw new UserError("Identificador de personagem inválido.");
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function slugify(name: string): string {
|
||||||
|
return name.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "personagem";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listCharacters(): Character[] {
|
||||||
|
if (!fs.existsSync(CHARACTERS_DIR)) return [];
|
||||||
|
return fs.readdirSync(CHARACTERS_DIR, { withFileTypes: true })
|
||||||
|
.filter((d) => d.isDirectory() && SLUG_RE.test(d.name))
|
||||||
|
.map((d) => readCharacter(d.name))
|
||||||
|
.filter((c): c is Character => !!c)
|
||||||
|
.sort((a, b) => a.name.localeCompare(b.name, "pt-BR"));
|
||||||
|
}
|
||||||
|
|
||||||
|
function readCharacter(id: string): Character | null {
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(fs.readFileSync(fileOf(id), "utf8")) as Character;
|
||||||
|
if (data.schemaVersion !== 1 || data.id !== id || validateLook(data.look).length) return null;
|
||||||
|
return data;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCharacter(id: string): Character | null {
|
||||||
|
return readCharacter(mustId(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
function clean(raw: unknown, max: number): string {
|
||||||
|
return String(raw ?? "").replace(/\s+/g, " ").trim().slice(0, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cria (id novo) ou salva (id existente). A aparência é conferida pelo contrato do cartoon. */
|
||||||
|
export function saveCharacter(input: { id?: unknown; name?: unknown; caption?: unknown; description?: unknown; kind?: unknown; look?: unknown; godot?: unknown }, create = false): Character {
|
||||||
|
const name = clean(input.name, 40);
|
||||||
|
if (name.length < 2) throw new UserError("Dê um nome ao personagem.");
|
||||||
|
const kind = input.kind === "3d" ? "3d" : "cartoon";
|
||||||
|
const look = (input.look ?? DEFAULT_LOOK) as CharacterLook;
|
||||||
|
const errors = validateLook(look);
|
||||||
|
if (errors.length) throw new UserError(`Aparência inválida: ${errors.join("; ")}`);
|
||||||
|
let id = input.id ? mustId(String(input.id)) : slugify(name);
|
||||||
|
const existing = fs.existsSync(fileOf(id)) ? readCharacter(id) : null;
|
||||||
|
if (create && existing) {
|
||||||
|
let n = 2;
|
||||||
|
while (fs.existsSync(fileOf(`${id}-${n}`))) n++;
|
||||||
|
id = `${id}-${n}`;
|
||||||
|
}
|
||||||
|
if (!create && !existing) throw new UserError("Personagem não encontrado.");
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const character: Character = {
|
||||||
|
schemaVersion: 1, id, name, kind, look,
|
||||||
|
caption: clean(input.caption, 50) || undefined,
|
||||||
|
description: clean(input.description, 600) || undefined,
|
||||||
|
...(kind === "3d" && input.godot && typeof input.godot === "object" ? { godot: input.godot as Record<string, unknown> } : {}),
|
||||||
|
createdAt: create || !existing ? now : existing.createdAt, updatedAt: now,
|
||||||
|
};
|
||||||
|
fs.mkdirSync(path.dirname(fileOf(id)), { recursive: true });
|
||||||
|
fs.writeFileSync(fileOf(id), JSON.stringify(character, null, 2) + "\n", "utf8");
|
||||||
|
return character;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteCharacter(id: string): void {
|
||||||
|
const dir = path.join(CHARACTERS_DIR, mustId(id));
|
||||||
|
if (!fs.existsSync(dir)) throw new UserError("Personagem não encontrado.");
|
||||||
|
const used = listCastUsage(id);
|
||||||
|
if (used.length) throw new UserError(`Este personagem está no elenco de: ${used.join(", ")}. Tire-o do elenco antes de apagar.`);
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- descrição → aparência (regras; o agente pode refinar depois) ----------
|
||||||
|
const COLORS: [RegExp, string][] = [
|
||||||
|
[/verde/, "#56704a"], [/azul/, "#2f6db3"], [/vermelh/, "#c8443a"], [/amarel/, "#e8b13a"], [/roxo|lilas/, "#8e6ad8"], [/rosa/, "#e27ba8"],
|
||||||
|
[/preto|preta/, "#26262e"], [/branc/, "#e9ecef"], [/cinza/, "#7c828c"], [/laranja/, "#e07b39"], [/marrom/, "#7a5232"], [/bege/, "#cdb48a"],
|
||||||
|
];
|
||||||
|
const HAIR_COLORS: [RegExp, string][] = [
|
||||||
|
[/grisalh|cabelo branco|cabelos brancos/, "#c9c9cf"], [/loir/, "#e8c35a"], [/ruiv/, "#b4532a"], [/castanh/, "#6b4226"], [/cabelo preto|cabelos pretos/, "#1e1612"],
|
||||||
|
];
|
||||||
|
const PROFESSIONS: [RegExp, { top: CharacterLook["top"]; caption: string }][] = [
|
||||||
|
[/engenheir/, { top: { style: "uniform", color: "#56704a", accent: "#e8b13a" }, caption: "Engenheiro" }],
|
||||||
|
[/policial|delegad/, { top: { style: "uniform", color: "#2b3a67", accent: "#e8b13a" }, caption: "Policial" }],
|
||||||
|
[/medic|enfermeir/, { top: { style: "jacket", color: "#e9ecef", accent: "#4fb0e8" }, caption: "Saúde" }],
|
||||||
|
[/bombeir/, { top: { style: "uniform", color: "#c8352f", accent: "#f2c230" }, caption: "Bombeiro" }],
|
||||||
|
[/militar|soldad/, { top: { style: "uniform", color: "#5b6b3a", accent: "#3a4a2a" }, caption: "Militar" }],
|
||||||
|
[/professor/, { top: { style: "jacket", color: "#7a5232", accent: "#e9ecef" }, caption: "Professor" }],
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Aparência e legenda a partir de uma descrição curta ("Otávio, 58, engenheiro, barba grisalha, óculos"). */
|
||||||
|
export function describeToLook(description: string): { look: CharacterLook; caption?: string } {
|
||||||
|
const t = description.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
|
||||||
|
const age = Number(/\b(\d{1,2})\s*(anos)?\b/.exec(t)?.[1] ?? NaN);
|
||||||
|
const female = /\b(ela|mulher|moca|senhora|dona|menina|garota|vo|avo|tia|mae|filha|esposa)\b/.test(t);
|
||||||
|
const child = /\b(crianca|menino|menina|garoto|garota)\b/.test(t) || (age > 0 && age <= 12);
|
||||||
|
const old = age >= 55 || /\b(idos|velh|senhor|senhora|vo|avo)\w*/.test(t);
|
||||||
|
const hairColor = HAIR_COLORS.find(([re]) => re.test(t))?.[1] ?? (old ? "#c9c9cf" : "#3a2a1e");
|
||||||
|
const style: CharacterLook["hair"]["style"] = /careca|calvo/.test(t) ? "bald" : /coque/.test(t) ? "bun" : /bone\b/.test(t) ? "cap"
|
||||||
|
: /cachead|crespo|black power/.test(t) ? "curly" : /espetad/.test(t) ? "spiky" : /cabelo (longo|comprido)|cabelos longos/.test(t) ? "long"
|
||||||
|
: /repartid|de lado/.test(t) ? "side" : female ? (old ? "bun" : "long") : "short";
|
||||||
|
const beard: CharacterLook["beard"]["style"] = female ? "none" : /barba por fazer/.test(t) ? "stubble" : /cavanhaque/.test(t) ? "goatee"
|
||||||
|
: /bigode/.test(t) && !/barba/.test(t) ? "mustache" : /barb/.test(t) ? "full" : "none";
|
||||||
|
const skin = /\b(negr[oa]|pret[oa]|pele escura)\b/.test(t) ? "#8d5a3b" : /\b(moren[oa]|pard[oa])\b/.test(t) ? "#c98a5e"
|
||||||
|
: /\b(branc[oa]|pele clara|loir[oa]|ruiv[oa])\b/.test(t) ? "#f1c7a3" : "#e0b48f";
|
||||||
|
const profession = PROFESSIONS.find(([re]) => re.test(t))?.[1];
|
||||||
|
const clothColor = COLORS.find(([re]) => new RegExp(`(roupa|camisa|camiseta|vestido|jaqueta|casaco|moletom|blusa)\\s+\\w*\\s*${re.source}`).test(t))?.[1];
|
||||||
|
const topStyle: CharacterLook["top"]["style"] = /vestido/.test(t) ? "dress" : /jaqueta|casaco/.test(t) ? "jacket" : /moletom/.test(t) ? "hoodie"
|
||||||
|
: /uniforme|macacao/.test(t) ? "uniform" : profession?.top.style ?? (female && old ? "dress" : "shirt");
|
||||||
|
const top = { ...(profession?.top ?? { style: topStyle, color: "#4f7a4a" }), style: topStyle, ...(clothColor ? { color: clothColor } : {}) };
|
||||||
|
const look: CharacterLook = {
|
||||||
|
build: /\b(gord[oa]|fort[e]|robust[oa]|grand[e]|gordinh[oa])\b/.test(t) ? "heavy" : /\b(magr[oa]|magrel[oa]|franzin[oa])\b/.test(t) || child ? "slim" : "average",
|
||||||
|
height: child ? 0.78 : /\b(alt[oa])\b/.test(t) ? 1.08 : /\b(baix[oa]|baixinh[oa])\b/.test(t) ? 0.92 : female ? 0.96 : 1,
|
||||||
|
skin,
|
||||||
|
hair: { style, color: style === "cap" ? (COLORS.find(([re]) => new RegExp(`bone\\s+${re.source}`).test(t))?.[1] ?? "#2f6db3") : hairColor },
|
||||||
|
beard: { style: beard, color: hairColor === "#c9c9cf" ? "#a9a9b0" : hairColor },
|
||||||
|
glasses: /oculos escuros/.test(t) ? "sun" : /oculos quadrad/.test(t) ? "square" : /oculos/.test(t) ? "round" : "none",
|
||||||
|
brows: old || /sobrancelha grossa|bravo|serio/.test(t) ? "thick" : "thin",
|
||||||
|
top: top as CharacterLook["top"],
|
||||||
|
bottom: { style: /\b(short|bermuda)\b/.test(t) || child ? "shorts" : /\bsaia\b/.test(t) ? "skirt" : "pants", color: female && /saia/.test(t) ? top.color : "#2c3346" },
|
||||||
|
shoes: child ? "#f2f2f2" : "#1d1d24",
|
||||||
|
};
|
||||||
|
const caption = [profession?.caption, age > 0 ? `${age} anos` : ""].filter(Boolean).join(" · ") || undefined;
|
||||||
|
return { look, caption };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- elenco da história ----------
|
||||||
|
const castFile = (storyId: string) => path.join(storyDir(storyId), "cast.json");
|
||||||
|
|
||||||
|
/** Elenco da história: ids dos personagens da biblioteca (os que sumiram da biblioteca são ignorados). */
|
||||||
|
export function getCast(storyId: string): Character[] {
|
||||||
|
try {
|
||||||
|
const ids = JSON.parse(fs.readFileSync(castFile(storyId), "utf8")) as { cast?: string[] };
|
||||||
|
return (ids.cast ?? []).map((id) => (SLUG_RE.test(id) ? readCharacter(id) : null)).filter((c): c is Character => !!c);
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCast(storyId: string, ids: unknown): Character[] {
|
||||||
|
if (!Array.isArray(ids) || ids.length > 12) throw new UserError("Elenco inválido (até 12 personagens).");
|
||||||
|
const valid = [...new Set(ids.map(String))].filter((id) => SLUG_RE.test(id) && readCharacter(id));
|
||||||
|
fs.mkdirSync(storyDir(storyId), { recursive: true });
|
||||||
|
fs.writeFileSync(castFile(storyId), JSON.stringify({ cast: valid }, null, 2) + "\n", "utf8");
|
||||||
|
return getCast(storyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function listCastUsage(id: string): string[] {
|
||||||
|
const root = path.join(REPO_ROOT, "stories");
|
||||||
|
if (!fs.existsSync(root)) return [];
|
||||||
|
return fs.readdirSync(root).filter((s) => {
|
||||||
|
try { return (JSON.parse(fs.readFileSync(castFile(s), "utf8")) as { cast?: string[] }).cast?.includes(id); } catch { return false; }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export const characterFileRel = (id: string) => rel(fileOf(mustId(id)));
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { describe, it } from "node:test";
|
||||||
|
import { describeToLook } from "./characters";
|
||||||
|
import { cartoonKey, cartoonSpec, planCartoon, wordTimings } from "./montage-cartoon";
|
||||||
|
|
||||||
|
const shot = (narration: string, onScreen = "", index = 0) => ({ index, narration, onScreen, visualHint: "" });
|
||||||
|
|
||||||
|
describe("estilo Cartoon: plano por regras", () => {
|
||||||
|
it("gerador com barulho: objeto tremendo com ondas, onomatopeia e rua acesa à noite", () => {
|
||||||
|
const plan = planCartoon(shot("Já o gerador faz barulho de moto ligada. Com a rua em silêncio, dá pra ouvir de longe à noite."));
|
||||||
|
assert.equal(plan.props?.[0].icon, "generator");
|
||||||
|
assert.equal(plan.props?.[0].shake, true);
|
||||||
|
assert.equal(plan.props?.[0].rings, true);
|
||||||
|
assert.deepEqual(plan.texts?.find((t) => t.kind === "onomatopoeia")?.text, "Vrrrum");
|
||||||
|
assert.equal(plan.scene.time, "night");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("personagem com nome vira pessoa com etiqueta; 'nunca' risca o objeto", () => {
|
||||||
|
const plan = planCartoon(shot("A Dona Cida avisa: nunca ligue o gerador dentro de casa."));
|
||||||
|
const person = plan.actors?.find((a) => a.kind === "person");
|
||||||
|
assert.equal(person && "label" in person ? person.label : "", "Dona Cida");
|
||||||
|
assert.equal(plan.props?.[0].crossed, true);
|
||||||
|
assert.equal(plan.props?.[0].tone, "danger");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("texto na tela numérico vira número grande; o resto vira etiqueta; multidão vira silhuetas", () => {
|
||||||
|
assert.equal(planCartoon(shot("Um galão de gasolina dura pouco.", "20 L")).texts?.[0].kind, "big");
|
||||||
|
const crowd = planCartoon(shot("Já tem dez pessoas no portão da casa acesa.", "Pessoas no portão"));
|
||||||
|
assert.equal(crowd.texts?.[0].kind, "tag");
|
||||||
|
assert.ok(crowd.actors?.some((a) => a.kind === "crowd"));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("assunto técnico vai para o diagrama; a variação troca o arranjo e a semente", () => {
|
||||||
|
const a = planCartoon(shot("Quando a rede cai, o inversor desliga sozinho."), {}, 0);
|
||||||
|
const b = planCartoon(shot("Quando a rede cai, o inversor desliga sozinho."), {}, 1);
|
||||||
|
assert.equal(a.scene.kind, "blueprint");
|
||||||
|
assert.notEqual(a.scene.kind, b.scene.kind);
|
||||||
|
assert.notEqual(a.seed, b.seed);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lugar pelo texto: cemitério vira lugar montado por peças, com névoa e lápides", () => {
|
||||||
|
const plan = planCartoon(shot("À noite, no cemitério, ninguém respondeu."));
|
||||||
|
assert.equal(plan.scene.kind, "place");
|
||||||
|
assert.equal(plan.place?.fog, true);
|
||||||
|
assert.ok(plan.place?.elements.some((e) => e.kind === "gravestone"));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("elenco: o personagem da biblioteca entra com a aparência dele, expressão e pose pelo texto", () => {
|
||||||
|
const look = describeToLook("Otávio, 58 anos, engenheiro, careca, barba grisalha, óculos").look;
|
||||||
|
const ctx = { cast: [{ id: "otavio", name: "Otávio", caption: "Engenheiro · 58 anos", look }], palette: "sepia" as const };
|
||||||
|
const plan = planCartoon(shot("Otávio ficou com medo quando o ar acabou no bunker."), ctx);
|
||||||
|
const actor = plan.actors?.find((a) => a.kind === "person");
|
||||||
|
assert.ok(actor && actor.kind === "person" && actor.character);
|
||||||
|
assert.equal(actor.character!.look.hair.style, "bald");
|
||||||
|
assert.equal(actor.expression, "scared");
|
||||||
|
assert.equal(plan.palette, "sepia");
|
||||||
|
assert.equal(plan.light, "spot");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("descrição → aparência: idade, profissão, cabelo, barba, óculos e roupa", () => {
|
||||||
|
const { look, caption } = describeToLook("Dona Cida, 70 anos, gordinha, coque, óculos, vestido roxo");
|
||||||
|
assert.deepEqual([look.hair.style, look.glasses, look.top.style, look.top.color, look.build, look.beard.style], ["bun", "round", "dress", "#8e6ad8", "heavy", "none"]);
|
||||||
|
assert.equal(caption, "70 anos");
|
||||||
|
assert.equal(describeToLook("menino de 9 anos, cabelo cacheado").look.height, 0.78);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a chave muda com a cena, a duração e o áudio", () => {
|
||||||
|
const plan = planCartoon(shot("A rua está escura."));
|
||||||
|
const k = cartoonKey(plan, 3.2, "abc");
|
||||||
|
assert.notEqual(k, cartoonKey(plan, 3.3, "abc"));
|
||||||
|
assert.notEqual(k, cartoonKey(plan, 3.2, "abd"));
|
||||||
|
assert.equal(k, cartoonKey(plan, 3.2, "abc"));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sem o serviço de voz, reparte as palavras pela duração (em ordem, dentro do trecho, com cor)", async () => {
|
||||||
|
const plan = planCartoon(shot("O gerador nunca fica dentro de casa."));
|
||||||
|
const words = await wordTimings({ repoRoot: "/nao/existe", audio: "x.ogg", spoken: "O gerador nunca fica dentro de casa.", durationS: 3, scene: plan });
|
||||||
|
assert.equal(words.length, 7);
|
||||||
|
assert.ok(words.every((w, i) => w.endS > w.startS && (i === 0 || w.startS >= words[i - 1].endS - 1e-9)));
|
||||||
|
assert.ok(words[words.length - 1].endS <= 3);
|
||||||
|
assert.equal(words.find((w) => w.text === "gerador")?.tone, "key");
|
||||||
|
assert.equal(words.find((w) => w.text === "nunca")?.tone, "danger");
|
||||||
|
const spec = cartoonSpec(plan, 3.0004, words);
|
||||||
|
assert.deepEqual([spec.schemaVersion, spec.width, spec.height, spec.fps, spec.durationS], [1, 1080, 1920, 30, 3]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,292 @@
|
|||||||
|
// Estilo "Cartoon" da montagem documental: cada trecho vira uma cena 2D vetorial renderizada pela Remotion
|
||||||
|
// (pacote cartoon/ na raiz). Aqui ficam o plano por regras (texto do trecho → cena, objetos, etiquetas,
|
||||||
|
// onomatopeia), os tempos de cada palavra (transcrição do áudio do trecho, para a legenda palavra por palavra)
|
||||||
|
// e a chamada do render (todos os trechos numa execução só: empacota uma vez).
|
||||||
|
//
|
||||||
|
// Os tipos vêm do contrato do pacote cartoon (cartoon/src/spec.ts); o render valida de novo.
|
||||||
|
import { spawn } from "node:child_process";
|
||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import type { CharacterLook, Expression, Pose } from "cenaforge-cartoon/character";
|
||||||
|
import type { IconId, ShotSpec, Word } from "cenaforge-cartoon/spec";
|
||||||
|
import type { JobHook } from "./montage-ffmpeg";
|
||||||
|
import { transcribe } from "./voice";
|
||||||
|
|
||||||
|
export type CartoonIcon = IconId;
|
||||||
|
type Tone = "info" | "danger" | "ok";
|
||||||
|
/** O que o plano decide por trecho: o spec sem tamanho, duração e palavras. */
|
||||||
|
export type CartoonScene = Omit<ShotSpec, "schemaVersion" | "width" | "height" | "fps" | "durationS" | "words">;
|
||||||
|
export type CartoonWord = Word;
|
||||||
|
export type CartoonSpec = ShotSpec & { words: Word[] };
|
||||||
|
type Place = NonNullable<ShotSpec["place"]>;
|
||||||
|
type PaletteId = NonNullable<ShotSpec["palette"]>;
|
||||||
|
/** Personagem do elenco da história (biblioteca), como entra no plano. */
|
||||||
|
export type CastMember = { id: string; name: string; caption?: string; look: CharacterLook };
|
||||||
|
export type PlanContext = { hud?: CartoonScene["hud"]; cast?: CastMember[]; palette?: PaletteId };
|
||||||
|
|
||||||
|
type ShotText = { index: number; narration: string; onScreen: string; visualHint: string };
|
||||||
|
|
||||||
|
const norm = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
|
||||||
|
|
||||||
|
/** Palavra do texto → objeto na cena (e etiqueta). A ordem é a prioridade. */
|
||||||
|
const ICON_RULES: [RegExp, CartoonIcon, string][] = [
|
||||||
|
[/\bgerador/, "generator", "Gerador"],
|
||||||
|
[/gasolina|combustivel|diesel|galao/, "fuel", "Combustível"],
|
||||||
|
[/bateria/, "battery", "Bateria"],
|
||||||
|
[/celular|telefone|carregar o/, "phone", "Celular"],
|
||||||
|
[/placa solar|painel solar|energia solar/, "solar", "Placa solar"],
|
||||||
|
[/\bporta\b|portao/, "door", "Porta"],
|
||||||
|
[/dinheiro|reais|r\$|\bpagar|preco|custa/, "money", "Dinheiro"],
|
||||||
|
[/lanterna|lampada|\bluz\b|acesa|aceso/, "bulb", "Luz"],
|
||||||
|
[/\bhoras?\b|minutos?\b|relogio/, "clock", "Tempo"],
|
||||||
|
[/perigo|cuidado|risco|veneno|\bmata\b|morte|morre/, "warning", "Perigo"],
|
||||||
|
[/\bver\b|olho|vigia|observ|enxerg|ninguem precisa ver/, "eye", "Olho"],
|
||||||
|
];
|
||||||
|
const DANGER = /\b(nunca|perigo|mata|morte|morre|morrer|risco|cuidado|proibido|veneno|alvo|visad\w*|ataque|roub\w*)\b/;
|
||||||
|
const SOUNDS: [RegExp, string][] = [
|
||||||
|
// Motor só quando o texto fala de motor/gerador/veículo; "um barulho" solto vira um estalo genérico.
|
||||||
|
[/(gerador|motor|moto|carro|caminhao|onibus)\w*.{0,40}(barulho|ronco|ligad)|ronco do motor|moto ligada/, "Vrrrum"],
|
||||||
|
[/\bbate\b|batida|bateu|bater na/, "Toc toc toc"],
|
||||||
|
[/cachorro|\blate\b|latido/, "Au au"],
|
||||||
|
[/explos|estouro|\btiros?\b/, "Bum!"],
|
||||||
|
[/barulho|estalo|rangeu|range\b|passos/, "Crec"],
|
||||||
|
];
|
||||||
|
const OUTFITS = ["#9b7be0", "#f2c230", "#4fb0e8", "#e86a5c", "#5cc48a"];
|
||||||
|
|
||||||
|
type El = Place["elements"][number];
|
||||||
|
/** Lugares reconhecidos pelo texto → chão, interno?, névoa, paleta sugerida e peças (posições variam pela semente). */
|
||||||
|
const LOCATIONS: { re: RegExp; ground: Place["ground"]; indoor?: boolean; fog?: boolean; palette?: PaletteId; light?: ShotSpec["light"]; pieces: El["kind"][] }[] = [
|
||||||
|
{ re: /cemiterio|tumulo|enterr|velorio/, ground: "dirt", fog: true, palette: "dusk", light: "vignette", pieces: ["gravestone", "gravestone", "cross", "deadtree", "fence", "gravestone"] },
|
||||||
|
{ re: /bunker|porao|abrigo|subsolo|esconderijo/, ground: "floor", indoor: true, palette: "sepia", light: "spot", pieces: ["shelf", "crate", "crate", "door"] },
|
||||||
|
{ re: /hospital|consultorio|escritorio|delegacia|escola|sala de aula/, ground: "floor", indoor: true, pieces: ["window", "table", "door", "shelf"] },
|
||||||
|
{ re: /\b(casa|sala|quarto|cozinha|apartamento)\b/, ground: "floor", indoor: true, pieces: ["window", "table", "shelf", "door", "bed"] },
|
||||||
|
{ re: /parque|praca|jardim/, ground: "grass", pieces: ["tree", "tree", "bench", "lamp", "bush", "cloud", "building", "pine"] },
|
||||||
|
{ re: /floresta|mata\b|trilha|bosque|selva/, ground: "grass", pieces: ["pine", "pine", "tree", "rock", "bush", "pine", "mountain"] },
|
||||||
|
{ re: /acampamento|fogueira|barraca/, ground: "grass", pieces: ["tent", "fire", "pine", "pine", "rock"] },
|
||||||
|
{ re: /praia|litoral|areia|\bmar\b/, ground: "sand", pieces: ["rock", "cloud", "cloud", "rock"] },
|
||||||
|
{ re: /sitio|fazenda|roca|campo\b|interior/, ground: "grass", pieces: ["house", "fence", "tree", "mountain", "bush", "cloud"] },
|
||||||
|
{ re: /\b(rua|cidade|bairro|avenida|estrada|transito|vizinh)\w*/, ground: "street", pieces: ["building", "building", "lamp", "house", "car", "sign"] },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Monta o lugar: peças espalhadas pela semente, longe do centro (onde fica o personagem). */
|
||||||
|
function placeFor(text: string, seed: number, variant: number): { place: Place; palette?: PaletteId; light?: ShotSpec["light"] } | null {
|
||||||
|
const loc = LOCATIONS.find((l) => l.re.test(text));
|
||||||
|
if (!loc) return null;
|
||||||
|
let a = (seed * 9301 + 49297 + variant * 233) % 233280;
|
||||||
|
const rand = () => (a = (a * 9301 + 49297) % 233280) / 233280;
|
||||||
|
const slots = [0.12, 0.88, 0.25, 0.75, 0.06, 0.94, 0.4, 0.62];
|
||||||
|
const elements: El[] = loc.pieces.map((kind, i) => ({
|
||||||
|
kind, x: slots[(i + variant) % slots.length] + (rand() - 0.5) * 0.06,
|
||||||
|
z: kind === "mountain" || kind === "building" ? 0.95 : kind === "cloud" ? 0.3 + rand() * 0.4 : 0.25 + rand() * 0.6,
|
||||||
|
flip: rand() > 0.5,
|
||||||
|
}));
|
||||||
|
return { place: { ground: loc.ground, indoor: loc.indoor, fog: loc.fog, elements }, palette: loc.palette, light: loc.light };
|
||||||
|
}
|
||||||
|
|
||||||
|
function expressionOf(text: string): Expression {
|
||||||
|
if (/\b(medo|apavorad|assust|pavor|terror|socorro)\w*/.test(text)) return "scared";
|
||||||
|
if (/\b(raiva|bravo|brava|irritad|furios|grit)\w*/.test(text)) return "angry";
|
||||||
|
if (/de repente|surpres|choc|nao acredit|inacredit/.test(text)) return "surprised";
|
||||||
|
if (/\b(trist|chor|perdeu|saudade|sozinh)\w*/.test(text)) return "sad";
|
||||||
|
if (DANGER.test(text) || /\b(preocup|problema|nervos|ansios)\w*/.test(text)) return "worried";
|
||||||
|
if (/\b(feliz|alegr|comemor|sorri|riu|rindo|venceu|conseguiu)\w*/.test(text)) return "happy";
|
||||||
|
return "neutral";
|
||||||
|
}
|
||||||
|
|
||||||
|
function poseOf(text: string, hasProp: boolean): Pose {
|
||||||
|
if (/acen|tchau|chamou/.test(text)) return "wave";
|
||||||
|
if (/comemor|venceu|gritou de alegria/.test(text)) return "arms_up";
|
||||||
|
if (/pens|lembr|imagin|calcul|planej/.test(text)) return "think";
|
||||||
|
if (/nao sabe|sem saber|nao entend/.test(text)) return "shrug";
|
||||||
|
return hasProp ? "point" : "stand";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Plano do trecho por regras do texto (narração + texto na tela + coluna Imagem). `variant` troca o arranjo. */
|
||||||
|
export function planCartoon(shot: ShotText, ctx: PlanContext = {}, variant = 0): CartoonScene {
|
||||||
|
const original = `${shot.narration} ${shot.onScreen} ${shot.visualHint}`;
|
||||||
|
const text = norm(original);
|
||||||
|
const time = /noite|madrugada|escuro|meia-noite/.test(text) ? "night"
|
||||||
|
: /amanhecer|sol nasce|amanhece|de madrugada/.test(text) ? "dawn"
|
||||||
|
: /\btarde\b|meio-dia|de dia\b|\bsol\b|ensolarad|\bmanha\b|domingo|claro\b/.test(text) ? "day" : "night";
|
||||||
|
|
||||||
|
const named = /\b(Dona|Seu|Tio|Tia|Doutor|Doutora)\s+([A-ZÁ-Ú][a-zá-ú]+)/.exec(original);
|
||||||
|
const crowd = /\b(pessoas|gente|multidao|vizinhos|fila|moradores|todo mundo)\b/.test(text);
|
||||||
|
const sound = SOUNDS.find(([re]) => re.test(text));
|
||||||
|
const icons = ICON_RULES.filter(([re]) => re.test(text)).slice(0, named ? 1 : 2);
|
||||||
|
const danger = DANGER.test(text);
|
||||||
|
const negated = danger && /\b(nunca|nao)\b/.test(text);
|
||||||
|
|
||||||
|
const props: NonNullable<CartoonScene["props"]> = icons.map(([, icon, label], i) => {
|
||||||
|
const x = named ? 0.7 : icons.length === 1 ? 0.5 : i === 0 ? 0.3 : 0.72;
|
||||||
|
return {
|
||||||
|
icon, x, y: 0.46, size: icons.length === 1 && !named ? 0.17 : 0.13, label, enterS: 0.3 + i * 0.5,
|
||||||
|
tone: danger && i === 0 ? "danger" : "info",
|
||||||
|
shake: !!sound && i === 0 && (icon === "generator" || icon === "door"),
|
||||||
|
rings: (!!sound && i === 0) || /chama atencao|da pra ouvir|de longe/.test(text),
|
||||||
|
crossed: negated && i === 0,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const actors: NonNullable<CartoonScene["actors"]> = [];
|
||||||
|
// Elenco da história: quem é citado pelo nome; sem citação e com um protagonista só, ele aparece nos trechos
|
||||||
|
// pares ou quando o texto fala "ele/ela" (fio condutor, como o Otávio da referência).
|
||||||
|
const cast = ctx.cast ?? [];
|
||||||
|
const firstName = (n: string) => norm(n.split(/\s+/)[0]);
|
||||||
|
let castIn = cast.filter((c) => new RegExp(`\\b${firstName(c.name)}\\b`).test(text));
|
||||||
|
if (!castIn.length && cast.length === 1 && !crowd && (shot.index % 2 === 0 || /\b(ele|ela)\b/.test(text))) castIn = [cast[0]];
|
||||||
|
castIn.slice(0, 2).forEach((c, i) => {
|
||||||
|
actors.push({
|
||||||
|
kind: "person", x: castIn.length > 1 ? (i === 0 ? 0.3 : 0.7) : props.length ? 0.34 : 0.5, y: 0.74, enterS: 0.15 + i * 0.3,
|
||||||
|
character: { name: c.name, caption: i === 0 && shot.index === 0 ? c.caption : undefined, look: c.look },
|
||||||
|
expression: expressionOf(text), pose: i === 0 ? poseOf(text, props.length > 0) : "stand",
|
||||||
|
item: i === 0 && props.length === 1 && ["phone", "fuel", "battery", "money", "bulb"].includes(props[0].icon) ? props[0].icon : undefined,
|
||||||
|
flip: i === 1,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
// Objeto que o personagem segura sai do chão; os outros vão para o lado oposto ao personagem.
|
||||||
|
if (castIn.length) {
|
||||||
|
const held = actors[0] && "item" in actors[0] ? actors[0].item : undefined;
|
||||||
|
for (let i = props.length - 1; i >= 0; i--) if (props[i].icon === held) props.splice(i, 1);
|
||||||
|
props.forEach((p) => { p.x = 0.74; p.y = 0.5; });
|
||||||
|
}
|
||||||
|
if (named && !castIn.length) {
|
||||||
|
const older = /^(Dona|Tia)$/.test(named[1]);
|
||||||
|
actors.push({ kind: "person", x: props.length ? 0.32 : 0.5, y: 0.6, label: `${named[1]} ${named[2]}`, enterS: 0.2,
|
||||||
|
outfit: OUTFITS[(shot.index + variant) % OUTFITS.length], hair: older ? "bun" : "short",
|
||||||
|
hairColor: older ? "#e8e8ee" : "#3a2a1e", glasses: older, pointing: props.length > 0 });
|
||||||
|
}
|
||||||
|
// Multidão atrás do personagem: entra primeiro (desenhada antes) e com os pés acima dos dele.
|
||||||
|
if (crowd) actors.unshift({ kind: "crowd", count: 9 + (shot.index % 4), y: actors.some((a) => a.kind === "person") ? 0.6 : 0.66, enterS: 0.4 });
|
||||||
|
|
||||||
|
const technical = /funciona|liga\b|desliga|inversor|rede eletrica|circuito|sistema|corrente/.test(text);
|
||||||
|
const kinds: CartoonScene["scene"]["kind"][] = technical ? ["blueprint", "plain"]
|
||||||
|
: named || crowd ? (/portao|porta|frente|calcada/.test(text) ? ["house", "street"] : ["street", "house"])
|
||||||
|
: props.length ? ["plain", "street"] : ["street", "plain"];
|
||||||
|
let kind: CartoonScene["scene"]["kind"] = kinds[variant % kinds.length];
|
||||||
|
// Lugar montado por peças quando o texto diz onde é (ou quando a história tem elenco/paleta: tudo vira lugar).
|
||||||
|
const built = technical ? null : placeFor(text, shot.index * 7 + 1, variant)
|
||||||
|
?? (cast.length || ctx.palette ? placeFor("rua", shot.index * 7 + 1, variant) : null);
|
||||||
|
if (built) kind = "place";
|
||||||
|
|
||||||
|
const texts: NonNullable<CartoonScene["texts"]> = [];
|
||||||
|
const onScreen = shot.onScreen.trim();
|
||||||
|
if (onScreen) {
|
||||||
|
const numeric = /^\W*[\d.,]+\s*\S{0,8}\W*$/.test(onScreen);
|
||||||
|
texts.push(numeric
|
||||||
|
? { kind: "big", text: onScreen, x: 0.5, y: 0.27, atS: 0.2, tone: danger ? "danger" : "info" }
|
||||||
|
: { kind: "tag", text: onScreen.slice(0, 40), x: 0.5, y: 0.17, atS: 0.1, tone: danger ? "danger" : "info" });
|
||||||
|
}
|
||||||
|
// Onomatopeia longe da etiqueta do personagem (que fica acima da cabeça, perto do centro).
|
||||||
|
if (sound) texts.push({ kind: "onomatopoeia", text: sound[1], x: props[0]?.x ?? (actors.some((a) => a.kind === "person") ? 0.76 : 0.62), y: props.length ? 0.33 : 0.24, atS: 0.7, rotate: -6 });
|
||||||
|
|
||||||
|
const timePalette: PaletteId = time === "day" ? "day" : time === "dawn" ? "dusk" : "night";
|
||||||
|
return {
|
||||||
|
seed: shot.index * 7 + variant * 101 + 1,
|
||||||
|
scene: { kind, time, litHouse: kind === "street" && /acesa|aceso|luz|iluminad|gerador/.test(text) },
|
||||||
|
...(built ? { place: built.place, palette: ctx.palette ?? built.palette ?? timePalette, ...(built.light ? { light: built.light } : {}) } : ctx.palette ? { palette: ctx.palette } : {}),
|
||||||
|
camera: { push: 1.05 + ((shot.index + variant) % 3) * 0.02, panX: kind === "street" ? (shot.index % 2 ? 0.05 : -0.05) : 0 },
|
||||||
|
...(ctx.hud ? { hud: ctx.hud } : {}),
|
||||||
|
actors, props, texts,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Chave da versão renderizada: muda se a cena, a duração ou o áudio (texto falado, voz, velocidade) mudarem. */
|
||||||
|
export function cartoonKey(scene: CartoonScene, durationS: number, audioKey: string): string {
|
||||||
|
let h = 0;
|
||||||
|
for (const ch of JSON.stringify([scene, Math.round(durationS * 1000), audioKey])) h = (Math.imul(h, 31) + ch.codePointAt(0)!) | 0;
|
||||||
|
return (h >>> 0).toString(36);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cor da palavra na legenda: perigo em vermelho; número e as palavras dos objetos da cena em amarelo. */
|
||||||
|
function toneOf(word: string, keywords: Set<string>): CartoonWord["tone"] {
|
||||||
|
const w = norm(word).replace(/[^\p{L}\p{N}$]/gu, "");
|
||||||
|
if (!w) return undefined;
|
||||||
|
if (DANGER.test(w)) return "danger";
|
||||||
|
if (/\d/.test(w) || keywords.has(w)) return "key";
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function keywordsOf(scene: CartoonScene): Set<string> {
|
||||||
|
const words = [...(scene.props ?? []).map((p) => p.label ?? ""), ...(scene.texts ?? []).map((t) => t.text)].join(" ");
|
||||||
|
return new Set(norm(words).split(/[^\p{L}\p{N}]+/u).filter((w) => w.length > 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tempos de cada palavra da fala do trecho: transcreve o áudio gerado (o serviço de voz devolve palavras com
|
||||||
|
* início/fim). Sem o serviço, reparte o texto falado pela duração (a legenda ainda acompanha, menos exata).
|
||||||
|
*/
|
||||||
|
export async function wordTimings(input: { repoRoot: string; audio: string; spoken: string; durationS: number; scene: CartoonScene; log?: (line: string) => void }): Promise<CartoonWord[]> {
|
||||||
|
const keywords = keywordsOf(input.scene);
|
||||||
|
try {
|
||||||
|
const bytes = fs.readFileSync(path.join(input.repoRoot, input.audio));
|
||||||
|
const result = await transcribe(new File([new Uint8Array(bytes)], path.basename(input.audio), { type: "audio/ogg" }), "pt-BR", "words");
|
||||||
|
const words = (result.segments ?? []).flatMap((s) => s.words ?? []).filter((w) => w.text.trim());
|
||||||
|
if (words.length) {
|
||||||
|
return words.map((w) => ({ text: w.text.trim(), startS: Math.max(0, w.start), endS: Math.max(w.start, w.end), tone: toneOf(w.text, keywords) }));
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
input.log?.(`tempos das palavras (${path.basename(input.audio)}): ${(error as Error).message}; repartindo pelo texto`);
|
||||||
|
}
|
||||||
|
const spoken = input.spoken.split(/\s+/).filter(Boolean);
|
||||||
|
const span = Math.max(0.5, input.durationS - 0.4);
|
||||||
|
const total = spoken.reduce((n, w) => n + w.length + 2, 0);
|
||||||
|
let t = 0.05;
|
||||||
|
return spoken.map((w) => {
|
||||||
|
const d = (span * (w.length + 2)) / total;
|
||||||
|
const word = { text: w, startS: t, endS: t + d, tone: toneOf(w, keywords) };
|
||||||
|
t += d;
|
||||||
|
return word;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Monta o spec completo de um trecho (o que o render recebe). */
|
||||||
|
export function cartoonSpec(scene: CartoonScene, durationS: number, words: CartoonWord[]): CartoonSpec {
|
||||||
|
return { schemaVersion: 1, width: 1080, height: 1920, fps: 30, durationS: Math.round(durationS * 1000) / 1000, ...scene, words };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renderiza vários trechos numa execução do `cartoon/render.ts` (empacota a cena uma vez só). Grava cada spec
|
||||||
|
* em `specDir`, devolve os MP4 (caminhos relativos à raiz) na mesma ordem.
|
||||||
|
*/
|
||||||
|
export async function renderCartoonShots(input: {
|
||||||
|
repoRoot: string; specDir: string; outDir: string; shots: { name: string; spec: CartoonSpec }[]; hook?: JobHook; log?: (line: string) => void;
|
||||||
|
}): Promise<string[]> {
|
||||||
|
const tsxCli = path.join(input.repoRoot, "node_modules", "tsx", "dist", "cli.mjs");
|
||||||
|
if (!fs.existsSync(tsxCli)) throw new Error("tsx não encontrado; rode pnpm install na raiz do projeto.");
|
||||||
|
if (!fs.existsSync(path.join(input.repoRoot, "cartoon", "node_modules", "remotion"))) {
|
||||||
|
throw new Error("O estilo Cartoon não está instalado: rode pnpm install na raiz do projeto.");
|
||||||
|
}
|
||||||
|
fs.mkdirSync(input.specDir, { recursive: true });
|
||||||
|
fs.mkdirSync(input.outDir, { recursive: true });
|
||||||
|
const relTo = (p: string) => path.relative(input.repoRoot, p).split(path.sep).join("/");
|
||||||
|
const jobs = input.shots.map((s) => {
|
||||||
|
const specFile = path.join(input.specDir, `${s.name}.json`);
|
||||||
|
fs.writeFileSync(specFile, JSON.stringify(s.spec, null, 2) + "\n", "utf8");
|
||||||
|
return { spec: relTo(specFile), out: relTo(path.join(input.outDir, `${s.name}.mp4`)) };
|
||||||
|
});
|
||||||
|
const jobsFile = path.join(input.specDir, "_jobs.json");
|
||||||
|
fs.writeFileSync(jobsFile, JSON.stringify(jobs, null, 2) + "\n", "utf8");
|
||||||
|
const output = await new Promise<string>((resolve, reject) => {
|
||||||
|
const child = spawn(process.execPath, [tsxCli, "cartoon/render.ts", "--jobs", relTo(jobsFile)], {
|
||||||
|
cwd: input.repoRoot, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
input.hook?.onChild(child);
|
||||||
|
let out = "";
|
||||||
|
child.stdout.on("data", (d) => { out += d; for (const line of String(d).split("\n")) if (line.startsWith("ok ")) input.log?.(`cartoon: ${line.trim()}`); });
|
||||||
|
child.stderr.on("data", (d) => (out += d));
|
||||||
|
child.on("error", reject);
|
||||||
|
child.on("close", (code) => {
|
||||||
|
input.hook?.onChild(null);
|
||||||
|
if (input.hook?.cancelled()) return reject(new Error("cancelado pelo painel"));
|
||||||
|
const report = out.split("\n").map((l) => l.trim()).filter((l) => l.startsWith("{")).pop();
|
||||||
|
let parsed: { ok?: boolean; error?: string } = {};
|
||||||
|
try { parsed = report ? JSON.parse(report) : {}; } catch { /* sem relatório */ }
|
||||||
|
if (code !== 0 || !parsed.ok) return reject(new Error(`render Cartoon: ${parsed.error ?? out.split("\n").filter(Boolean).slice(-4).join(" | ")}`));
|
||||||
|
resolve(out);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
void output;
|
||||||
|
return jobs.map((j) => {
|
||||||
|
if (!fs.existsSync(path.resolve(input.repoRoot, j.out))) throw new Error(`render Cartoon: ${j.out} não foi gerado`);
|
||||||
|
return j.out;
|
||||||
|
});
|
||||||
|
}
|
||||||
+124
-16
@@ -2,7 +2,8 @@
|
|||||||
// - um ÁUDIO próprio, gerado parágrafo a parágrafo pelo serviço de voz (frase longa numa
|
// - um ÁUDIO próprio, gerado parágrafo a parágrafo pelo serviço de voz (frase longa numa
|
||||||
// tacada só deixa a voz estranha) a partir do "texto falado" (números por extenso);
|
// tacada só deixa a voz estranha) a partir do "texto falado" (números por extenso);
|
||||||
// - um VISUAL: imagem (com movimento lento), clipe de vídeo, cena 3D renderizada pelo Godot,
|
// - um VISUAL: imagem (com movimento lento), clipe de vídeo, cena 3D renderizada pelo Godot,
|
||||||
// ou cartela de texto. O trecho dura o tempo do próprio áudio.
|
// cena Cartoon (2D vetorial pela Remotion, pacote cartoon/) ou cartela de texto. O trecho dura o
|
||||||
|
// tempo do próprio áudio.
|
||||||
// Depois o FFmpeg monta um segmento por trecho (visual + texto na tela + legenda + áudio) e
|
// Depois o FFmpeg monta um segmento por trecho (visual + texto na tela + legenda + áudio) e
|
||||||
// concatena tudo num MP4 vertical 1080x1920. O estado fica em stories/<id>/<file_key>.montage.json.
|
// concatena tudo num MP4 vertical 1080x1920. O estado fica em stories/<id>/<file_key>.montage.json.
|
||||||
import type { ChildProcess } from "node:child_process";
|
import type { ChildProcess } from "node:child_process";
|
||||||
@@ -14,6 +15,8 @@ import { DATA_DIR, OUTPUT_DIR, REPO_ROOT, STORIES_DIR, readTextIfExists, rel, re
|
|||||||
import { LAST_PAD_S, PAD_S, buildCredits, buildSegment, concatSegments, ffmpegBin, fontFile, probeDuration, type JobHook } from "./montage-ffmpeg";
|
import { LAST_PAD_S, PAD_S, buildCredits, buildSegment, concatSegments, ffmpegBin, fontFile, probeDuration, type JobHook } from "./montage-ffmpeg";
|
||||||
import { downloadImage, searchFirst } from "./image-search";
|
import { downloadImage, searchFirst } from "./image-search";
|
||||||
import { DOC2D_TEMPLATES, planScene, planShot, planShot3d, renderGodotScene, sceneKey, scriptEntities, type Doc2DScene } from "./montage-godot";
|
import { DOC2D_TEMPLATES, planScene, planShot, planShot3d, renderGodotScene, sceneKey, scriptEntities, type Doc2DScene } from "./montage-godot";
|
||||||
|
import { getCast } from "./characters";
|
||||||
|
import { cartoonKey, cartoonSpec, planCartoon, renderCartoonShots, wordTimings, type CartoonScene, type PlanContext } from "./montage-cartoon";
|
||||||
import { listLibrary, paramsFor } from "./scene-library";
|
import { listLibrary, paramsFor } from "./scene-library";
|
||||||
import { killTree } from "./proc";
|
import { killTree } from "./proc";
|
||||||
import { parseScript } from "./script-doc";
|
import { parseScript } from "./script-doc";
|
||||||
@@ -22,7 +25,9 @@ import { UserError, getEpisodeById, getStory, touchStory } from "./stories";
|
|||||||
import type { AssetKind, EpisodeView, RenderJob } from "./types";
|
import type { AssetKind, EpisodeView, RenderJob } from "./types";
|
||||||
import { getStatus, synthesize } from "./voice";
|
import { getStatus, synthesize } from "./voice";
|
||||||
|
|
||||||
export type VisualKind = "image" | "video" | "godot3d" | "card" | "godot2d";
|
export type VisualKind = "image" | "video" | "godot3d" | "card" | "godot2d" | "cartoon";
|
||||||
|
/** "mixed": foto, 2D e 3D, o que combinar; "3d": tudo em cena 3D; "cartoon": tudo em desenho 2D chapado (Remotion). */
|
||||||
|
export type MontageStyle = "mixed" | "3d" | "cartoon";
|
||||||
|
|
||||||
/** Estilos de visual por trecho (dá para misturar no mesmo vídeo). */
|
/** Estilos de visual por trecho (dá para misturar no mesmo vídeo). */
|
||||||
export const VISUAL_KINDS: { id: VisualKind; label: string; available: boolean; hint: string }[] = [
|
export const VISUAL_KINDS: { id: VisualKind; label: string; available: boolean; hint: string }[] = [
|
||||||
@@ -30,6 +35,7 @@ export const VISUAL_KINDS: { id: VisualKind; label: string; available: boolean;
|
|||||||
{ id: "godot2d", label: "Animação 2D", available: true, hint: "Mapa, infográfico ou título animados no Godot, com o tempo exato da fala." },
|
{ id: "godot2d", label: "Animação 2D", available: true, hint: "Mapa, infográfico ou título animados no Godot, com o tempo exato da fala." },
|
||||||
{ id: "godot3d", label: "Cena 3D", available: true, hint: "Cena 3D da biblioteca do Godot (ilha, estádio...), com a câmera e as opções da cena." },
|
{ id: "godot3d", label: "Cena 3D", available: true, hint: "Cena 3D da biblioteca do Godot (ilha, estádio...), com a câmera e as opções da cena." },
|
||||||
{ id: "video", label: "Clipe", available: true, hint: "Um clipe enviado por você ou um vídeo já renderizado no painel." },
|
{ id: "video", label: "Clipe", available: true, hint: "Um clipe enviado por você ou um vídeo já renderizado no painel." },
|
||||||
|
{ id: "cartoon", label: "Cartoon", available: true, hint: "Desenho 2D chapado (rua, personagens, etiquetas, onomatopeias) com legenda palavra por palavra." },
|
||||||
{ id: "card", label: "Cartela", available: true, hint: "Fundo escuro com o texto na tela em destaque." },
|
{ id: "card", label: "Cartela", available: true, hint: "Fundo escuro com o texto na tela em destaque." },
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -39,6 +45,9 @@ export type ShotVisual = {
|
|||||||
scene?: Doc2DScene; sceneKey?: string;
|
scene?: Doc2DScene; sceneKey?: string;
|
||||||
/** Imagem da internet: buscas usadas e qual resultado está em uso ("gerar de novo" pega o próximo). */
|
/** Imagem da internet: buscas usadas e qual resultado está em uso ("gerar de novo" pega o próximo). */
|
||||||
search?: { queries: string[]; pick: number };
|
search?: { queries: string[]; pick: number };
|
||||||
|
/** cartoon: a cena planejada (cartoon/src/spec.ts, sem duração e palavras), a variação do "Gerar de novo" e a
|
||||||
|
* chave da versão renderizada em "file". */
|
||||||
|
cartoon?: CartoonScene; cartoonVariant?: number; cartoonKey?: string;
|
||||||
/** Cartão de foto por cima da cena (modo 3D): a foto real da cobra sobre a ilha, por exemplo. */
|
/** Cartão de foto por cima da cena (modo 3D): a foto real da cobra sobre a ilha, por exemplo. */
|
||||||
inset?: { file: string; credit: string; license: string; sourceUrl: string; search?: { queries: string[]; pick: number } } | null;
|
inset?: { file: string; credit: string; license: string; sourceUrl: string; search?: { queries: string[]; pick: number } } | null;
|
||||||
/** Escolhido pelo modo automático (o "Refazer tudo do zero" replaneja só estes). */
|
/** Escolhido pelo modo automático (o "Refazer tudo do zero" replaneja só estes). */
|
||||||
@@ -65,15 +74,20 @@ export type Montage = {
|
|||||||
voiceId: string;
|
voiceId: string;
|
||||||
speed: number;
|
speed: number;
|
||||||
captions: boolean;
|
captions: boolean;
|
||||||
style: "mixed" | "3d";
|
style: MontageStyle;
|
||||||
|
cartoonPalette: string;
|
||||||
shots: MontageShot[];
|
shots: MontageShot[];
|
||||||
/** Fontes do roteiro (domínios), para a cartela final. */
|
/** Fontes do roteiro (domínios), para a cartela final. */
|
||||||
sourceHosts: string[];
|
sourceHosts: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
type SavedShot = { spoken?: string; visual?: ShotVisual; audio?: ShotAudio };
|
type SavedShot = { spoken?: string; visual?: ShotVisual; audio?: ShotAudio };
|
||||||
/** style: "mixed" (foto, 2D e 3D, o que combinar) ou "3d" (tudo em cena 3D; fotos em cartão por cima). */
|
/** style: "mixed" (foto, 2D e 3D, o que combinar), "3d" (tudo em cena 3D; fotos em cartão por cima) ou "cartoon". */
|
||||||
type SavedMontage = { version: 1; voiceId: string; speed: number; captions: boolean; style?: "mixed" | "3d"; shots: Record<string, SavedShot> };
|
type SavedMontage = {
|
||||||
|
version: 1; voiceId: string; speed: number; captions: boolean; style?: MontageStyle; shots: Record<string, SavedShot>;
|
||||||
|
/** Paleta do estilo Cartoon escolhida para o vídeo (vazio = pela hora de cada trecho). */
|
||||||
|
cartoonPalette?: (typeof CARTOON_PALETTES)[number];
|
||||||
|
};
|
||||||
|
|
||||||
const EMPTY_VISUAL: ShotVisual = { kind: "image", file: null, credit: "", license: "", sourceUrl: "" };
|
const EMPTY_VISUAL: ShotVisual = { kind: "image", file: null, credit: "", license: "", sourceUrl: "" };
|
||||||
/** Pastas de onde um visual pode vir (nada fora do projeto). */
|
/** Pastas de onde um visual pode vir (nada fora do projeto). */
|
||||||
@@ -135,12 +149,12 @@ export function loadMontage(episodeId: number): Montage {
|
|||||||
const sources = doc.sections.find((s) => s.role === "sources");
|
const sources = doc.sections.find((s) => s.role === "sources");
|
||||||
const sourceHosts = [...new Set((sources ? JSON.stringify(sources.blocks) : "").match(/https?:\/\/[^/\s"]+/g) ?? [])]
|
const sourceHosts = [...new Set((sources ? JSON.stringify(sources.blocks) : "").match(/https?:\/\/[^/\s"]+/g) ?? [])]
|
||||||
.map((u) => u.replace(/^https?:\/\/(www\.)?/, ""));
|
.map((u) => u.replace(/^https?:\/\/(www\.)?/, ""));
|
||||||
return { episodeId, voiceId: saved.voiceId, speed: saved.speed, captions: saved.captions, style: saved.style ?? "mixed", shots, sourceHosts };
|
return { episodeId, voiceId: saved.voiceId, speed: saved.speed, captions: saved.captions, style: saved.style ?? "mixed", cartoonPalette: saved.cartoonPalette ?? "", shots, sourceHosts };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Ajustes da montagem: voz, velocidade, legenda e, por trecho, texto falado e visual. */
|
/** Ajustes da montagem: voz, velocidade, legenda e, por trecho, texto falado e visual. */
|
||||||
export function updateMontage(episodeId: number, patch: {
|
export function updateMontage(episodeId: number, patch: {
|
||||||
voiceId?: unknown; speed?: unknown; captions?: unknown; style?: unknown;
|
voiceId?: unknown; speed?: unknown; captions?: unknown; style?: unknown; cartoonPalette?: unknown; replanCartoon?: unknown;
|
||||||
shot?: { index?: unknown; spoken?: unknown; resetSpoken?: unknown; visual?: Partial<Record<keyof ShotVisual, unknown>> };
|
shot?: { index?: unknown; spoken?: unknown; resetSpoken?: unknown; visual?: Partial<Record<keyof ShotVisual, unknown>> };
|
||||||
}): Montage {
|
}): Montage {
|
||||||
const ep = episodeOrThrow(episodeId);
|
const ep = episodeOrThrow(episodeId);
|
||||||
@@ -157,7 +171,16 @@ export function updateMontage(episodeId: number, patch: {
|
|||||||
saved.speed = Math.round(speed * 100) / 100;
|
saved.speed = Math.round(speed * 100) / 100;
|
||||||
}
|
}
|
||||||
if (patch.captions !== undefined) saved.captions = Boolean(patch.captions);
|
if (patch.captions !== undefined) saved.captions = Boolean(patch.captions);
|
||||||
if (patch.style !== undefined) saved.style = patch.style === "3d" ? "3d" : "mixed";
|
if (patch.cartoonPalette !== undefined) {
|
||||||
|
const palette = String(patch.cartoonPalette);
|
||||||
|
if (palette && !(CARTOON_PALETTES as readonly string[]).includes(palette)) throw new UserError("Paleta inválida.");
|
||||||
|
saved.cartoonPalette = (palette || undefined) as SavedMontage["cartoonPalette"];
|
||||||
|
}
|
||||||
|
// Paleta ou elenco novos: o plano automático dos trechos Cartoon é refeito (cor e personagens fazem parte da cena).
|
||||||
|
if (patch.cartoonPalette !== undefined || patch.replanCartoon) {
|
||||||
|
for (const own of Object.values(saved.shots)) if (own.visual?.kind === "cartoon" && own.visual.auto !== false) delete own.visual.cartoon;
|
||||||
|
}
|
||||||
|
if (patch.style !== undefined) saved.style = patch.style === "3d" || patch.style === "cartoon" ? patch.style : "mixed";
|
||||||
if (patch.shot) {
|
if (patch.shot) {
|
||||||
const index = Number(patch.shot.index);
|
const index = Number(patch.shot.index);
|
||||||
const shot = current.shots.find((s) => s.index === index);
|
const shot = current.shots.find((s) => s.index === index);
|
||||||
@@ -199,6 +222,9 @@ export function updateMontage(episodeId: number, patch: {
|
|||||||
else if (first) next.scene = { kind: "doc3d", template: first.id, params: { ...paramsFor(first, shot.visualHint), variant: 0 } };
|
else if (first) next.scene = { kind: "doc3d", template: first.id, params: { ...paramsFor(first, shot.visualHint), variant: 0 } };
|
||||||
else throw new UserError("A biblioteca de cenas 3D está vazia: peça uma cena ao agente (tarefa \"Cena no Godot\").");
|
else throw new UserError("A biblioteca de cenas 3D está vazia: peça uma cena ao agente (tarefa \"Cena no Godot\").");
|
||||||
}
|
}
|
||||||
|
// Cartoon: plano do trecho pelo texto (ou o que já estava).
|
||||||
|
if (next.kind === "cartoon" && !next.cartoon) next.cartoon = planCartoon(shot, cartoonCtx(ep), next.cartoonVariant ?? 0);
|
||||||
|
if (next.kind !== "cartoon") { delete next.cartoon; delete next.cartoonKey; delete next.cartoonVariant; }
|
||||||
if (next.kind !== "godot2d" && next.kind !== "godot3d") { delete next.scene; delete next.sceneKey; }
|
if (next.kind !== "godot2d" && next.kind !== "godot3d") { delete next.scene; delete next.sceneKey; }
|
||||||
if (next.kind !== "image") delete next.search;
|
if (next.kind !== "image") delete next.search;
|
||||||
next.auto = false;
|
next.auto = false;
|
||||||
@@ -225,6 +251,58 @@ function shotDuration(montage: Montage, shot: MontageShot): number {
|
|||||||
return shot.audio!.durationMs / 1000 + (last ? LAST_PAD_S : PAD_S);
|
return shot.audio!.durationMs / 1000 + (last ? LAST_PAD_S : PAD_S);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Painel do topo das cenas Cartoon: nome da história e o número do vídeo. */
|
||||||
|
function hudFor(ep: EpisodeView): CartoonScene["hud"] {
|
||||||
|
const story = getStory(ep.story_id);
|
||||||
|
const badge = (story?.title ?? ep.story_id).replace(/[^\p{L}\p{N} ]/gu, "").trim().split(/\s+/).slice(0, 2).join(" ").slice(0, 18);
|
||||||
|
return { badge: badge || "História", label: `Ep. ${ep.number}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Paletas do estilo Cartoon (a mesma em todos os trechos dá a "cara" da série). Vazio = pela hora do trecho. */
|
||||||
|
export const CARTOON_PALETTES = ["night", "sepia", "day", "dusk", "gray"] as const;
|
||||||
|
|
||||||
|
/** Contexto do plano Cartoon: painel do topo, elenco da história (biblioteca de personagens) e paleta. */
|
||||||
|
function cartoonCtx(ep: EpisodeView): PlanContext {
|
||||||
|
const palette = readSaved(ep).cartoonPalette;
|
||||||
|
return {
|
||||||
|
hud: hudFor(ep),
|
||||||
|
cast: getCast(ep.story_id).filter((c) => c.kind === "cartoon").map((c) => ({ id: c.id, name: c.name, caption: c.caption, look: c.look })),
|
||||||
|
...(palette ? { palette } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A cena Cartoon já renderizada vale para este trecho (mesma cena, duração e áudio)? */
|
||||||
|
function cartoonIsCurrent(montage: Montage, shot: MontageShot): boolean {
|
||||||
|
const v = shot.visual;
|
||||||
|
return v.kind === "cartoon" && !!v.cartoon && !!v.file && !!shot.audio && !shot.audioStale &&
|
||||||
|
v.cartoonKey === cartoonKey(v.cartoon, shotDuration(montage, shot), shot.audio.key) && fs.existsSync(path.join(REPO_ROOT, v.file));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Renderiza as cenas Cartoon dos trechos pedidos numa execução só (precisa do áudio: tempos e duração da fala). */
|
||||||
|
async function renderCartoonInternal(ep: EpisodeView, montage: Montage, shots: MontageShot[], hook?: JobHook, log?: (line: string) => void): Promise<void> {
|
||||||
|
if (!shots.length) return;
|
||||||
|
const jobs = [];
|
||||||
|
for (const shot of shots) {
|
||||||
|
if (!shot.audio || shot.audioStale) throw new UserError(`Gere o áudio do trecho ${shot.index + 1} antes: a cena dura o tempo da fala.`);
|
||||||
|
const scene = shot.visual.cartoon ?? planCartoon(shot, cartoonCtx(ep), shot.visual.cartoonVariant ?? 0);
|
||||||
|
const duration = shotDuration(montage, shot);
|
||||||
|
const words = montage.captions
|
||||||
|
? await wordTimings({ repoRoot: REPO_ROOT, audio: shot.audio.file, spoken: shot.spoken, durationS: duration, scene, log })
|
||||||
|
: [];
|
||||||
|
jobs.push({ shot, scene, duration, spec: cartoonSpec(scene, duration, words) });
|
||||||
|
}
|
||||||
|
const files = await renderCartoonShots({
|
||||||
|
repoRoot: REPO_ROOT, specDir: path.join(storyDir(ep.story_id), "cartoon"), outDir: path.join(OUTPUT_DIR, "cartoon", `${ep.story_id}-${ep.file_key}`),
|
||||||
|
shots: jobs.map((j) => ({ name: `${ep.file_key}-t${String(j.shot.index + 1).padStart(2, "0")}`, spec: j.spec })), hook, log,
|
||||||
|
});
|
||||||
|
const saved = readSaved(ep);
|
||||||
|
jobs.forEach((j, i) => {
|
||||||
|
const own = (saved.shots[String(j.shot.index)] ??= {});
|
||||||
|
own.visual = { ...EMPTY_VISUAL, ...own.visual, kind: "cartoon", cartoon: j.scene, file: files[i], cartoonKey: cartoonKey(j.scene, j.duration, j.shot.audio!.key) };
|
||||||
|
});
|
||||||
|
writeSaved(ep, saved);
|
||||||
|
}
|
||||||
|
|
||||||
/** A cena 2D já renderizada vale para este trecho (mesmo modelo, parâmetros e duração)? */
|
/** A cena 2D já renderizada vale para este trecho (mesmo modelo, parâmetros e duração)? */
|
||||||
function sceneIsCurrent(montage: Montage, shot: MontageShot): boolean {
|
function sceneIsCurrent(montage: Montage, shot: MontageShot): boolean {
|
||||||
const v = shot.visual;
|
const v = shot.visual;
|
||||||
@@ -253,8 +331,9 @@ export async function renderShotScene(episodeId: number, index: number): Promise
|
|||||||
const montage = loadMontage(episodeId);
|
const montage = loadMontage(episodeId);
|
||||||
const shot = montage.shots.find((s) => s.index === index);
|
const shot = montage.shots.find((s) => s.index === index);
|
||||||
if (!shot) throw new UserError("Trecho não encontrado.");
|
if (!shot) throw new UserError("Trecho não encontrado.");
|
||||||
if (shot.visual.kind !== "godot2d" && shot.visual.kind !== "godot3d") throw new UserError("Este trecho não usa cena do Godot.");
|
if (shot.visual.kind === "cartoon") await renderCartoonInternal(ep, montage, [shot]);
|
||||||
await renderShotSceneInternal(ep, montage, shot);
|
else if (shot.visual.kind !== "godot2d" && shot.visual.kind !== "godot3d") throw new UserError("Este trecho não usa cena do Godot nem Cartoon.");
|
||||||
|
else await renderShotSceneInternal(ep, montage, shot);
|
||||||
return loadMontage(episodeId);
|
return loadMontage(episodeId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -371,6 +450,18 @@ export async function regenerateShot(episodeId: number, index: number, target: "
|
|||||||
if (!ok) throw new UserError("Não achei outra foto diferente das que já estão no vídeo.");
|
if (!ok) throw new UserError("Não achei outra foto diferente das que já estão no vídeo.");
|
||||||
return loadMontage(episodeId);
|
return loadMontage(episodeId);
|
||||||
}
|
}
|
||||||
|
if (v.kind === "cartoon") {
|
||||||
|
// Outra variação do arranjo (cena, câmera, roupa) e renderiza já, se o áudio estiver pronto.
|
||||||
|
const variant = (v.cartoonVariant ?? 0) + 1;
|
||||||
|
const saved = readSaved(ep);
|
||||||
|
const own = (saved.shots[String(index)] ??= {});
|
||||||
|
own.visual = { ...EMPTY_VISUAL, ...own.visual, kind: "cartoon", cartoonVariant: variant, cartoon: planCartoon(shot, cartoonCtx(ep), variant) };
|
||||||
|
writeSaved(ep, saved);
|
||||||
|
const fresh = loadMontage(episodeId);
|
||||||
|
const freshShot = fresh.shots.find((s) => s.index === index)!;
|
||||||
|
if (freshShot.audio && !freshShot.audioStale) await renderCartoonInternal(ep, fresh, [freshShot]);
|
||||||
|
return loadMontage(episodeId);
|
||||||
|
}
|
||||||
if ((v.kind === "godot2d" || v.kind === "godot3d") && v.scene) {
|
if ((v.kind === "godot2d" || v.kind === "godot3d") && v.scene) {
|
||||||
const variant = Number(v.scene.params.variant ?? 0) + 1;
|
const variant = Number(v.scene.params.variant ?? 0) + 1;
|
||||||
const saved = readSaved(ep);
|
const saved = readSaved(ep);
|
||||||
@@ -427,10 +518,11 @@ export function montageJob(episodeId: number): { renderId: number; progress: str
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Trecho sem visual escolhido pelo admin (imagem/clipe vazio): o modo automático usa cena 2D. */
|
/** Trecho sem visual escolhido pelo admin (imagem/clipe vazio): o modo automático usa cena 2D. */
|
||||||
const needsVisual = (s: MontageShot) => s.visual.kind !== "card" && s.visual.kind !== "godot2d" && s.visual.kind !== "godot3d" && !s.visual.file;
|
const needsVisual = (s: MontageShot) => s.visual.kind !== "card" && s.visual.kind !== "godot2d" && s.visual.kind !== "godot3d" && s.visual.kind !== "cartoon" && !s.visual.file;
|
||||||
/** No "Refazer tudo do zero": o que o automático escolheu (ou cena do Godot sem marca, de versões antigas) é replanejado. */
|
/** No "Refazer tudo do zero": o que o automático escolheu (ou cena do Godot sem marca, de versões antigas) é replanejado. */
|
||||||
const replannable = (s: MontageShot) => needsVisual(s) || s.visual.auto === true || (s.visual.auto === undefined && (s.visual.kind === "godot2d" || s.visual.kind === "godot3d"));
|
const replannable = (s: MontageShot) => needsVisual(s) || s.visual.auto === true || (s.visual.auto === undefined && (s.visual.kind === "godot2d" || s.visual.kind === "godot3d" || s.visual.kind === "cartoon"));
|
||||||
const isGodot = (s: MontageShot) => s.visual.kind === "godot2d" || s.visual.kind === "godot3d";
|
const isGodot = (s: MontageShot) => s.visual.kind === "godot2d" || s.visual.kind === "godot3d";
|
||||||
|
const isCartoon = (s: MontageShot) => s.visual.kind === "cartoon";
|
||||||
|
|
||||||
/** Voz pt-BR padrão do serviço (para o modo automático, quando nenhuma foi escolhida). */
|
/** Voz pt-BR padrão do serviço (para o modo automático, quando nenhuma foi escolhida). */
|
||||||
async function defaultVoice(): Promise<string> {
|
async function defaultVoice(): Promise<string> {
|
||||||
@@ -491,6 +583,13 @@ export function startMontageRender(episodeId: number, options: { auto?: boolean;
|
|||||||
const style = readSaved(ep).style ?? "mixed";
|
const style = readSaved(ep).style ?? "mixed";
|
||||||
for (const shot of toPlan) {
|
for (const shot of toPlan) {
|
||||||
checkCancel();
|
checkCancel();
|
||||||
|
if (style === "cartoon") {
|
||||||
|
// Tudo em Cartoon: o plano sai do texto do trecho; o render vem depois do áudio (precisa da duração).
|
||||||
|
const savedC = readSaved(ep);
|
||||||
|
(savedC.shots[String(shot.index)] ??= {}).visual = { ...EMPTY_VISUAL, kind: "cartoon", cartoon: planCartoon(shot, cartoonCtx(ep)), auto: true };
|
||||||
|
writeSaved(ep, savedC);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (style === "3d") {
|
if (style === "3d") {
|
||||||
// Tudo em 3D: cena 3D da biblioteca + cartão de foto real quando o trecho pede.
|
// Tudo em 3D: cena 3D da biblioteca + cartão de foto real quando o trecho pede.
|
||||||
const plan3d = planShot3d(shot, ctx, shot.index);
|
const plan3d = planShot3d(shot, ctx, shot.index);
|
||||||
@@ -534,9 +633,17 @@ export function startMontageRender(episodeId: number, options: { auto?: boolean;
|
|||||||
step(`Cena ${shot.visual.kind === "godot3d" ? "3D" : "2D"} no Godot ${i + 1} de ${needScene.length} (trecho ${shot.index + 1})`);
|
step(`Cena ${shot.visual.kind === "godot3d" ? "3D" : "2D"} no Godot ${i + 1} de ${needScene.length} (trecho ${shot.index + 1})`);
|
||||||
await renderShotSceneInternal(ep, current, shot, hook);
|
await renderShotSceneInternal(ep, current, shot, hook);
|
||||||
}
|
}
|
||||||
|
// 3b) Cenas Cartoon desatualizadas: todas numa execução da Remotion (empacota uma vez).
|
||||||
|
const afterGodot = loadMontage(episodeId);
|
||||||
|
const needCartoon = afterGodot.shots.filter((s) => isCartoon(s) && s.audio && !s.audioStale && !cartoonIsCurrent(afterGodot, s));
|
||||||
|
if (needCartoon.length) {
|
||||||
|
checkCancel();
|
||||||
|
step(`Cenas Cartoon: ${needCartoon.length} trecho${needCartoon.length === 1 ? "" : "s"}`);
|
||||||
|
await renderCartoonInternal(ep, afterGodot, needCartoon, hook, log);
|
||||||
|
}
|
||||||
const montage = loadMontage(episodeId);
|
const montage = loadMontage(episodeId);
|
||||||
const pending = montage.shots.filter((s) => !s.audio || s.audioStale || (s.visual.kind !== "card" && !s.visual.file) ||
|
const pending = montage.shots.filter((s) => !s.audio || s.audioStale || (s.visual.kind !== "card" && !s.visual.file) ||
|
||||||
(isGodot(s) && !sceneIsCurrent(montage, s)));
|
(isGodot(s) && !sceneIsCurrent(montage, s)) || (isCartoon(s) && !cartoonIsCurrent(montage, s)));
|
||||||
if (pending.length) throw new UserError(`Trechos ainda sem áudio ou visual atualizado: ${pending.map((s) => s.index + 1).join(", ")}.`);
|
if (pending.length) throw new UserError(`Trechos ainda sem áudio ou visual atualizado: ${pending.map((s) => s.index + 1).join(", ")}.`);
|
||||||
// 4) Um segmento por trecho + créditos, depois junta tudo.
|
// 4) Um segmento por trecho + créditos, depois junta tudo.
|
||||||
const segments: string[] = [];
|
const segments: string[] = [];
|
||||||
@@ -546,9 +653,10 @@ export function startMontageRender(episodeId: number, options: { auto?: boolean;
|
|||||||
segments.push(await buildSegment({
|
segments.push(await buildSegment({
|
||||||
visual: shot.visual,
|
visual: shot.visual,
|
||||||
inset: shot.visual.inset ? { file: shot.visual.inset.file, credit: shot.visual.inset.credit } : null,
|
inset: shot.visual.inset ? { file: shot.visual.inset.file, credit: shot.visual.inset.credit } : null,
|
||||||
// A cena 2D já mostra o texto dela; não sobrepõe de novo.
|
// A cena 2D e a Cartoon já mostram o texto delas; a Cartoon traz a legenda palavra por palavra.
|
||||||
onScreen: shot.visual.kind === "godot2d" ? "" : shot.onScreen,
|
onScreen: shot.visual.kind === "godot2d" || isCartoon(shot) ? "" : shot.onScreen,
|
||||||
narration: shot.narration, audio: shot.audio!.file, duration: shotDuration(montage, shot), index: shot.index, captions: montage.captions,
|
narration: shot.narration, audio: shot.audio!.file, duration: shotDuration(montage, shot), index: shot.index,
|
||||||
|
captions: montage.captions && !isCartoon(shot),
|
||||||
}, dir, font, REPO_ROOT, hook));
|
}, dir, font, REPO_ROOT, hook));
|
||||||
}
|
}
|
||||||
const credits = [...new Set(montage.shots.map((s) => s.visual.credit && `${s.visual.credit}${s.visual.license ? ` (${s.visual.license})` : ""}`).filter(Boolean))];
|
const credits = [...new Set(montage.shots.map((s) => s.visual.credit && `${s.visual.credit}${s.visual.license ? ` (${s.visual.license})` : ""}`).filter(Boolean))];
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ export function buildPrompt(input: { kind: AgentKind; provider: Provider; reques
|
|||||||
branches: "Leia SÓ: `doc/roteiro/comum.md`, `doc/roteiro/ficcao.md` e a pasta da história; para a cena, use o script `new_scene.py` indicado abaixo. Não carregue a skill inteira.",
|
branches: "Leia SÓ: `doc/roteiro/comum.md`, `doc/roteiro/ficcao.md` e a pasta da história; para a cena, use o script `new_scene.py` indicado abaixo. Não carregue a skill inteira.",
|
||||||
godot: "Leia SÓ: `doc/godot/cenas.md` e `doc/godot/api.md` (assinaturas das peças e cenas; NÃO leia os .gd inteiros de outras cenas). Não carregue a skill `cenaforge`.",
|
godot: "Leia SÓ: `doc/godot/cenas.md` e `doc/godot/api.md` (assinaturas das peças e cenas; NÃO leia os .gd inteiros de outras cenas). Não carregue a skill `cenaforge`.",
|
||||||
scene: "Siga a skill `cenaforge` (.claude/skills/cenaforge/SKILL.md): leia só as seções que a tarefa pedir.",
|
scene: "Siga a skill `cenaforge` (.claude/skills/cenaforge/SKILL.md): leia só as seções que a tarefa pedir.",
|
||||||
|
character: "Leia SÓ: `doc/cartoon/personagens.md`. Não carregue a skill `cenaforge`.",
|
||||||
free: "Siga o CLAUDE.md; consulte a skill `cenaforge` (.claude/skills/cenaforge/SKILL.md) só no que a tarefa pedir.",
|
free: "Siga o CLAUDE.md; consulte a skill `cenaforge` (.claude/skills/cenaforge/SKILL.md) só no que a tarefa pedir.",
|
||||||
};
|
};
|
||||||
const lines: (string | null)[] = [
|
const lines: (string | null)[] = [
|
||||||
@@ -116,6 +117,13 @@ export function buildPrompt(input: { kind: AgentKind; provider: Provider; reques
|
|||||||
story && documentary ? RESEARCH_ECONOMY : null,
|
story && documentary ? RESEARCH_ECONOMY : null,
|
||||||
story ? scriptCheck(story.id) : null,
|
story ? scriptCheck(story.id) : null,
|
||||||
"Não crie cena JSON nem renderize nesta tarefa.");
|
"Não crie cena JSON nem renderize nesta tarefa.");
|
||||||
|
} else if (kind === "character") {
|
||||||
|
lines.push("", "## Tarefa: personagem do estilo Cartoon (biblioteca de personagens)",
|
||||||
|
"O pedido traz o id e a descrição de um personagem. Monte a aparência por peças conforme `doc/cartoon/personagens.md` e grave a ficha.",
|
||||||
|
"1. Leia `assets/characters/<id>/character.json` se existir (o painel cria um rascunho pelas regras); mantenha id, name e createdAt.",
|
||||||
|
"2. Ajuste `look` (só os valores da tabela do guia; cores #rrggbb), `caption` curta (função · idade) e `description`.",
|
||||||
|
"3. Escreva o arquivo com JSON válido. Não crie imagens, não renderize e não altere `cartoon/` nem `panel/`.",
|
||||||
|
"Ao terminar: diga em 3 linhas o que escolheu e por quê (a marca que deixa o personagem reconhecível).");
|
||||||
} else if (kind === "godot") {
|
} else if (kind === "godot") {
|
||||||
lines.push("", "## Tarefa: construir uma cena no Godot (biblioteca de cenas)",
|
lines.push("", "## Tarefa: construir uma cena no Godot (biblioteca de cenas)",
|
||||||
"O pedido descreve uma cena (lugar, objeto, personagem, animação). Construa-a no Godot e guarde na biblioteca, para este e para os próximos vídeos.",
|
"O pedido descreve uma cena (lugar, objeto, personagem, animação). Construa-a no Godot e guarde na biblioteca, para este e para os próximos vídeos.",
|
||||||
|
|||||||
@@ -125,8 +125,8 @@ export type Decision = {
|
|||||||
|
|
||||||
export type Provider = "claude" | "codex";
|
export type Provider = "claude" | "codex";
|
||||||
// godot: o agente constrói uma cena nova na biblioteca do Godot (godot/library/, doc/godot/cenas.md).
|
// godot: o agente constrói uma cena nova na biblioteca do Godot (godot/library/, doc/godot/cenas.md).
|
||||||
export type AgentKind = "free" | "story" | "script" | "scene" | "branches" | "godot";
|
export type AgentKind = "free" | "story" | "script" | "scene" | "branches" | "godot" | "character";
|
||||||
export const AGENT_KINDS: AgentKind[] = ["free", "story", "script", "scene", "branches", "godot"];
|
export const AGENT_KINDS: AgentKind[] = ["free", "story", "script", "scene", "branches", "godot", "character"];
|
||||||
export type AgentStatus = "running" | "success" | "error" | "cancelled" | "interrupted";
|
export type AgentStatus = "running" | "success" | "error" | "cancelled" | "interrupted";
|
||||||
|
|
||||||
export type AgentRun = {
|
export type AgentRun = {
|
||||||
|
|||||||
Generated
+2544
-6
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,6 @@
|
|||||||
packages:
|
packages:
|
||||||
- panel
|
- panel
|
||||||
|
- cartoon
|
||||||
|
|
||||||
# Não executamos scripts de instalação de terceiros. Os pacotes abaixo funcionam sem eles:
|
# Não executamos scripts de instalação de terceiros. Os pacotes abaixo funcionam sem eles:
|
||||||
# esbuild (tsx) e sharp/unrs-resolver (Next.js) usam binários dos pacotes opcionais da plataforma.
|
# esbuild (tsx) e sharp/unrs-resolver (Next.js) usam binários dos pacotes opcionais da plataforma.
|
||||||
|
|||||||
@@ -7,12 +7,13 @@ frequência: quando aparecer, o envio para em `needs_login` — o usuário resol
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import random
|
||||||
import re
|
import re
|
||||||
import time
|
import time
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from ..base import JobSpec, Progress, PublishError, PublishResult, Sleep
|
from ..base import JobSpec, Progress, PublishError, PublishResult, Sleep
|
||||||
from .common import (Uploader, caption_key, click_through, detect_block, dismiss_tips, fill_text, find, needs_login,
|
from .common import (Uploader, caption_key, click_through, detect_block, dismiss_tips, find, needs_login,
|
||||||
require, step_pause)
|
require, step_pause)
|
||||||
|
|
||||||
UPLOAD_URL = "https://www.tiktok.com/tiktokstudio/upload?from=upload"
|
UPLOAD_URL = "https://www.tiktok.com/tiktokstudio/upload?from=upload"
|
||||||
@@ -41,6 +42,64 @@ SELECTORS: dict[str, list[tuple]] = {
|
|||||||
|
|
||||||
VIDEO_ID = re.compile(r"tiktok\.com/@([\w.-]+)/video/(\d+)")
|
VIDEO_ID = re.compile(r"tiktok\.com/@([\w.-]+)/video/(\d+)")
|
||||||
|
|
||||||
|
# Hashtag da legenda: "#" + letras/números/_ (com acento). Pontuação logo depois fica fora da tag.
|
||||||
|
HASHTAG = re.compile(r"#(\w+)")
|
||||||
|
|
||||||
|
|
||||||
|
def caption_parts(caption: str) -> list[tuple[str, str]]:
|
||||||
|
"""Legenda em pedaços na ordem: ("text", trecho) e ("tag", nome sem "#")."""
|
||||||
|
parts: list[tuple[str, str]] = []
|
||||||
|
pos = 0
|
||||||
|
for match in HASHTAG.finditer(caption):
|
||||||
|
if match.start() > pos:
|
||||||
|
parts.append(("text", caption[pos:match.start()]))
|
||||||
|
parts.append(("tag", match.group(1)))
|
||||||
|
pos = match.end()
|
||||||
|
if pos < len(caption):
|
||||||
|
parts.append(("text", caption[pos:]))
|
||||||
|
return parts
|
||||||
|
|
||||||
|
|
||||||
|
def hashtag_options(tag: str) -> list[tuple]:
|
||||||
|
"""Sugestão da lista do editor que é exatamente esta tag (não uma que só começa igual)."""
|
||||||
|
exact = rf"^#?{re.escape(tag)}(?!\w)"
|
||||||
|
return [("role", "option", exact), ("text", rf"^#{re.escape(tag)}$")]
|
||||||
|
|
||||||
|
|
||||||
|
def type_caption(page: Any, editor: Any, caption: str, sleep: Sleep = time.sleep) -> tuple[int, int]:
|
||||||
|
"""Escreve a legenda no editor do TikTok Studio e devolve (hashtags confirmadas, hashtags na legenda).
|
||||||
|
|
||||||
|
17/11/2026: colada de uma vez, a legenda chega com `#tag` como TEXTO — a página pública do vídeo mostra
|
||||||
|
`challenges: []`. O editor só cria a hashtag (com link, busca e tópico) quando ela é digitada e escolhida na
|
||||||
|
lista de sugestões. Então: texto comum colado; cada `#tag` digitada e confirmada na sugestão exata. Sem
|
||||||
|
sugestão exata a tag fica como texto (como antes) e o envio segue."""
|
||||||
|
click_through(editor, sleep)
|
||||||
|
step_pause(sleep, 0.3, 0.8)
|
||||||
|
page.keyboard.press("Control+A")
|
||||||
|
page.keyboard.press("Delete")
|
||||||
|
step_pause(sleep, 0.2, 0.5)
|
||||||
|
confirmed = total = 0
|
||||||
|
skip_space = False # o editor põe um espaço depois da hashtag escolhida: não duplicar
|
||||||
|
for kind, value in caption_parts(caption):
|
||||||
|
if kind == "text":
|
||||||
|
if skip_space and value[:1] == " ":
|
||||||
|
value = value[1:]
|
||||||
|
skip_space = False
|
||||||
|
if value:
|
||||||
|
page.keyboard.insert_text(value)
|
||||||
|
continue
|
||||||
|
total += 1
|
||||||
|
page.keyboard.type(f"#{value}", delay=random.uniform(60, 120))
|
||||||
|
option = find(page, hashtag_options(value), timeout_s=4, sleep=sleep)
|
||||||
|
if option is None:
|
||||||
|
continue
|
||||||
|
click_through(option, sleep)
|
||||||
|
confirmed += 1
|
||||||
|
step_pause(sleep, 0.3, 0.7)
|
||||||
|
text = (editor.inner_text() or "").replace(" ", " ")
|
||||||
|
skip_space = text.endswith(" ")
|
||||||
|
return confirmed, total
|
||||||
|
|
||||||
|
|
||||||
def check(page: Any, sleep: Sleep = time.sleep) -> str | None:
|
def check(page: Any, sleep: Sleep = time.sleep) -> str | None:
|
||||||
page.goto(UPLOAD_URL, wait_until="domcontentloaded")
|
page.goto(UPLOAD_URL, wait_until="domcontentloaded")
|
||||||
@@ -73,9 +132,11 @@ def upload(page: Any, spec: JobSpec, progress: Progress, sleep: Sleep = time.sle
|
|||||||
# Com o vídeo carregado, o Studio às vezes abre um aviso de novidade por cima de tudo ("Veja a prévia…").
|
# Com o vídeo carregado, o Studio às vezes abre um aviso de novidade por cima de tudo ("Veja a prévia…").
|
||||||
step_pause(sleep, 1.0, 2.0)
|
step_pause(sleep, 1.0, 2.0)
|
||||||
dismiss_tips(page, sleep)
|
dismiss_tips(page, sleep)
|
||||||
fill_text(caption, spec.caption[:2200], sleep)
|
confirmed, total = type_caption(page, caption, spec.caption[:2200], sleep)
|
||||||
# Fecha a lista de sugestões de hashtag/menção que aparece ao digitar "#" ou "@".
|
# Fecha a lista de sugestões de hashtag/menção que sobrar aberta.
|
||||||
page.keyboard.press("Escape")
|
page.keyboard.press("Escape")
|
||||||
|
if total:
|
||||||
|
progress(f"Legenda escrita: {confirmed} de {total} hashtags confirmadas na lista do TikTok.", 0.3)
|
||||||
step_pause(sleep)
|
step_pause(sleep)
|
||||||
|
|
||||||
want_private = spec.privacy in ("private", "unlisted")
|
want_private = spec.privacy in ("private", "unlisted")
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
"""Legenda do TikTok Studio: hashtags digitadas e confirmadas na lista de sugestões (colada, vira só texto)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
from app.platforms.session.tiktok_studio import caption_parts, type_caption
|
||||||
|
|
||||||
|
|
||||||
|
def test_caption_parts_split_text_and_tags():
|
||||||
|
parts = caption_parts("Ele pega tudo.\n\n#Skipnho #ROBRUN #arrecadação, #clã\n\n🎥 Créditos: https://twitch.tv/skipnho")
|
||||||
|
assert parts == [
|
||||||
|
("text", "Ele pega tudo.\n\n"), ("tag", "Skipnho"), ("text", " "), ("tag", "ROBRUN"), ("text", " "),
|
||||||
|
("tag", "arrecadação"), ("text", ", "), ("tag", "clã"), ("text", "\n\n🎥 Créditos: https://twitch.tv/skipnho"),
|
||||||
|
]
|
||||||
|
assert caption_parts("sem tags") == [("text", "sem tags")]
|
||||||
|
|
||||||
|
|
||||||
|
class FakeMatches:
|
||||||
|
def __init__(self, page, tag):
|
||||||
|
self.page, self.tag = page, tag
|
||||||
|
|
||||||
|
def count(self):
|
||||||
|
return 1 if self.tag else 0
|
||||||
|
|
||||||
|
def nth(self, _i):
|
||||||
|
return self
|
||||||
|
|
||||||
|
@property
|
||||||
|
def first(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def is_visible(self):
|
||||||
|
return True
|
||||||
|
|
||||||
|
def click(self, timeout=None):
|
||||||
|
self.page.choose(self.tag)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeKeyboard:
|
||||||
|
def __init__(self, page):
|
||||||
|
self.page = page
|
||||||
|
|
||||||
|
def press(self, key):
|
||||||
|
if key == "Delete":
|
||||||
|
self.page.text = ""
|
||||||
|
|
||||||
|
def insert_text(self, text):
|
||||||
|
self.page.text += text
|
||||||
|
|
||||||
|
def type(self, text, delay=None):
|
||||||
|
self.page.text += text
|
||||||
|
self.page.typing = text[1:]
|
||||||
|
|
||||||
|
|
||||||
|
class FakeEditor:
|
||||||
|
def __init__(self, page):
|
||||||
|
self.page = page
|
||||||
|
|
||||||
|
def click(self, timeout=None):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def inner_text(self):
|
||||||
|
return self.page.text
|
||||||
|
|
||||||
|
|
||||||
|
class FakePage:
|
||||||
|
"""Editor do TikTok: escolher a sugestão troca o "#tag" digitado por "#tag" + espaço (como o Draft do Studio)."""
|
||||||
|
|
||||||
|
def __init__(self, known):
|
||||||
|
self.known, self.text, self.typing, self.chosen = known, "", None, []
|
||||||
|
self.keyboard = FakeKeyboard(self)
|
||||||
|
|
||||||
|
def _match(self, pattern):
|
||||||
|
tag = self.typing if self.typing in self.known and pattern.search(f"#{self.typing}") else None
|
||||||
|
return FakeMatches(self, tag)
|
||||||
|
|
||||||
|
def get_by_role(self, _role, name):
|
||||||
|
return self._match(name)
|
||||||
|
|
||||||
|
def get_by_text(self, pattern):
|
||||||
|
return self._match(pattern)
|
||||||
|
|
||||||
|
def choose(self, tag):
|
||||||
|
self.text = self.text[: -len(tag) - 1] + f"#{tag} "
|
||||||
|
self.chosen.append(tag)
|
||||||
|
self.typing = None
|
||||||
|
|
||||||
|
|
||||||
|
def test_type_caption_confirms_known_tags_without_double_spaces():
|
||||||
|
page = FakePage(known={"Skipnho", "ROBRUN"})
|
||||||
|
page.text = "texto antigo"
|
||||||
|
confirmed, total = type_caption(page, FakeEditor(page), "Ele pega tudo. #Skipnho #ROBRUN #inexistente fim",
|
||||||
|
sleep=lambda _s: None)
|
||||||
|
assert (confirmed, total) == (2, 3)
|
||||||
|
assert page.chosen == ["Skipnho", "ROBRUN"]
|
||||||
|
# A tag sem sugestão fica como texto; nenhum espaço duplicado depois das escolhidas.
|
||||||
|
assert page.text.replace(" ", " ") == "Ele pega tudo. #Skipnho #ROBRUN #inexistente fim"
|
||||||
|
|
||||||
|
|
||||||
|
def test_hashtag_option_is_exact():
|
||||||
|
page = FakePage(known={"saque"})
|
||||||
|
page.typing = "saque"
|
||||||
|
from app.platforms.session.tiktok_studio import hashtag_options
|
||||||
|
role_pattern = re.compile(hashtag_options("saque")[0][2], re.I)
|
||||||
|
assert role_pattern.search("#saque 1,2 mi de visualizações")
|
||||||
|
assert not role_pattern.search("#saquearia")
|
||||||
Reference in New Issue
Block a user