@@ -31,6 +31,11 @@ const norm = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCa
/** Palavra do texto → objeto na cena (e etiqueta). A ordem é a prioridade. */
const ICON_RULES : [ RegExp , CartoonIcon , string ] [ ] = [
[ /ramo de oliveira|folha de oliveira|\boliveira/ , "olive" , "Oliveira" ] ,
[ /\bmartel/ , "hammer" , "Martelo" ] ,
[ /tabua de argila|tablete de argila|placa de argila/ , "tablet" , "Tábua de argila" ] ,
[ /biblia aberta|pergaminho|\blivro\b|escrituras/ , "book" , "Escritura" ] ,
[ /regua|\bcovados?\b|fita metrica|\bmedida\b/ , "ruler" , "Medida" ] ,
[ /\bgerador/ , "generator" , "Gerador" ] ,
[ /gasolina|combustivel|diesel|galao/ , "fuel" , "Combustível" ] ,
[ /bateria/ , "battery" , "Bateria" ] ,
@@ -41,7 +46,7 @@ const ICON_RULES: [RegExp, CartoonIcon, string][] = [
[ /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" ] ,
[ /\bver\b|\b olhos?\b |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 ] [ ] = [
@@ -55,33 +60,92 @@ const SOUNDS: [RegExp, string][] = [
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" ] [ ] } [ ] = [
/** Peça do lugar: só o tipo (posição pela semente, longe do centro) ou já posicionada (arca, arco-íris… ). */
type Piece = El [ "kind" ] | El ;
type Location = {
re : RegExp ; ground : Place [ "ground" ] ; indoor? : boolean ; fog? : boolean ; horizon? : number ;
palette? : PaletteId ;
/** A paleta do lugar vence a paleta da série (tempestade é cinza, arco-íris no entardecer). */
override? : boolean ;
light? : ShotSpec [ "light" ] ;
weather? : Place [ "weather" ] ;
flood? : Place [ "flood" ] ;
pieces : Piece [ ] ;
/** Ajuste pelo texto (ex.: "tempestade" troca chuva por tempestade; "noite" escurece). */
adjust ? : ( text : string ) = > Partial < Pick < Location , "weather" | "palette" | "flood" > > & { extra? : Piece [ ] } ;
} ;
const ARK_X = 0.6 ;
/** Lugares reconhecidos pelo texto (a ordem é a prioridade) → chão, clima, água, paleta e peças. */
const LOCATIONS : Location [ ] = [
{ re : /\bmuseu|exposicao|vitrine/ , ground : "floor" , indoor : true , palette : "sepia" , override : true , light : "spot" , pieces : [ "shelf" , "window" , "shelf" , "frame" , "frame" , { kind : "pendant" , x : 0.5 , z : 0.45 } ] } ,
// Dilúvio: chove forte e a água sobe; a arca boia e balança; casa e árvore ficam embaixo d'água.
{ re : /diluvio|aguas? subi|enchente|inunda/ , ground : "water" , palette : "gray" , override : true , weather : "storm" , flood : { from : 0.8 , to : 0.5 } ,
pieces : [ { kind : "ark" , x : 0.5 , z : 0.4 , float : true } , { kind : "house" , x : 0.14 , z : 0.3 } , { kind : "tree" , x : 0.86 , z : 0.3 } , { kind : "mountain" , x : 0.62 , z : 0.96 } ] ,
adjust : ( t ) = > ( /\bnoite\b/ . test ( t ) ? { palette : "night" } : { } ) } ,
{ re : /\bchuva|\bchov|tempestade|temporal|trovoad/ , ground : "grass" , palette : "gray" , override : true , weather : "rain" ,
pieces : [ { kind : "ark" , x : ARK_X , z : 0.55 , scale : 1.1 } , "cloud" , "palm" , "cloud" , "bush" ] ,
adjust : ( t ) = > ( { . . . ( /tempestade|temporal|trovoad|\braio/ . test ( t ) ? { weather : "storm" as const } : { } ) , . . . ( /\bnoite\b/ . test ( t ) ? { palette : "night" as const } : { } ) } ) } ,
// Mar sem fim: a água fica parada na linha do horizonte e o barco boia nela.
{ re : /mar sem fim|alto mar|\bflutua|boiando|navega|a deriva|no mar\b/ , ground : "water" , horizon : 0.5 , flood : { from : 0.55 , to : 0.55 } ,
pieces : [ { kind : "ark" , x : 0.5 , z : 0.4 , float : true , scale : 1.05 } , { kind : "waves" , x : 0.2 , z : 0.08 } , { kind : "waves" , x : 0.85 , z : 0.12 , flip : true } , "cloud" , "cloud" ] } ,
// Barco pousado no monte: a água ainda em volta, baixando.
{ re : /pousad\w* no monte|pousou|montes? de ararat|encalh/ , ground : "dirt" , flood : { from : 0.66 , to : 0.72 } ,
pieces : [ { kind : "mountain" , x : 0.5 , z : 0.82 , scale : 1.35 } , { kind : "mountain" , x : 0.1 , z : 0.96 } , { kind : "mountain" , x : 0.92 , z : 0.95 } ,
{ kind : "ark" , x : 0.46 , z : 0.82 , scale : 0.8 , lift : 0.1 } , "cloud" ] } ,
{ re : /montanha na turquia|monte ararat|\bexpedic|cordilheira/ , ground : "dirt" ,
pieces : [ { kind : "mountain" , x : 0.5 , z : 0.9 , scale : 1.4 } , { kind : "mountain" , x : 0.12 , z : 0.96 } , "rock" , "rock" , "cloud" ] ,
adjust : ( t ) = > ( /forma de barco|formacao (de )?roch|afloramento/ . test ( t ) ? { extra : [ { kind : "outcrop" , x : 0.5 , z : 0.35 , scale : 1.2 } ] } : { } ) } ,
{ re : /arco-?\s?iris/ , ground : "grass" , palette : "dusk" , override : true ,
pieces : [ { kind : "rainbow" , x : 0.5 , z : 0.97 , scale : 2.3 } , { kind : "mountain" , x : 0.2 , z : 0.95 } , { kind : "mountain" , x : 0.85 , z : 0.94 } ,
{ kind : "ark" , x : 0.78 , z : 0.8 , scale : 0.6 } , "palm" , "bush" ] } ,
// Canteiro de obra de um barco: casco em construção (costelas), andaime e tábuas empilhadas.
{ re : /em construcao|canteiro|construindo|andaime|estaleiro/ , ground : "dirt" ,
pieces : [ { kind : "ark_frame" , x : 0.55 , z : 0.62 , scale : 1.2 } , { kind : "scaffold" , x : 0.16 , z : 0.5 } , { kind : "planks" , x : 0.84 , z : 0.22 } ,
{ kind : "palm" , x : 0.94 , z : 0.75 } , { kind : "mountain" , x : 0.3 , z : 0.97 } , "cloud" ] } ,
{ re : /arca pronta|arca em terra|barco em terra|entrando na arca|entram na arca|entraram na arca|\barca\b|\bbarco grande/ , ground : "grass" ,
pieces : [ { kind : "ark" , x : ARK_X , z : 0.55 , scale : 1.2 } , { kind : "palm" , x : 0.07 , z : 0.6 } , { kind : "palm" , x : 0.95 , z : 0.78 } , { kind : "mountain" , x : 0.3 , z : 0.97 } , "cloud" ] } ,
// Lugar antigo: casas de barro, palmeiras e tendas (sem poste, carro nem prédio).
{ re : /vilarejo|aldeia|povoado|cidade antiga|casas simples|tempos antigos/ , ground : "dirt" ,
pieces : [ { kind : "house" , x : 0.12 , z : 0.45 , color : "#d8b88a" } , { kind : "house" , x : 0.86 , z : 0.6 , color : "#c9a576" , flip : true } , "palm" , "tent" , "palm" , "mountain" , { kind : "wall" , x : 0.5 , z : 0.8 , color : "#d8b88a" } ] } ,
{ re : /campo aberto|planicie|pasto|campina/ , ground : "grass" , pieces : [ "palm" , "bush" , "mountain" , "cloud" , "tree" , "rock" ] } ,
{ 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 : /bunker|porao|abrigo|subsolo|esconderijo/ , ground : "floor" , indoor : true , palette : "sepia" , light : "spot" , pieces : [ "shelf" , "crate" , "crate" , "door" , "cabinet" , { kind : "pendant" , x : 0.5 , z : 0.45 } ] } ,
{ re : /hospital|consultorio|escritorio|delegacia|escola|sala de aula/ , ground : "floor" , indoor : true , pieces : [ "window" , "table" , "door" , "shelf" , "cabinet" , "frame" ] } ,
{ re : /\b(casa|sala|quarto|cozinha|apartamento)\b/ , ground : "floor" , indoor : true , pieces : [ "window" , "table" , "shelf" , "door" , "bed" , "frame" , { kind : "pendant" , x : 0.5 , z : 0.45 } ] } ,
{ 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" ] } ,
{ re : /sitio|fazenda|roca|campo\b|interior/ , ground : "grass" , pieces : [ "house" , "fence" , "tree" , "mountain" , "bush" , "cloud" , "clothesline" ] } ,
{ re : /\b(rua|cidade|bairro|avenida|estrada|transito|vizinh)\w*/ , ground : "street" , pieces : [ "building" , "building" , "lamp" , "house" , "car" , "sign" , "shopfront" ] } ,
] ;
/** 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 {
type Built = { place : Place ; palette? : PaletteId ; override? : boolean ; light? : ShotSpec [ "light" ] } ;
/** Monta o lugar: peças soltas espalhadas pela semente, longe do centro (onde fica o personagem); peças já
* posicionadas ficam onde a regra mandou. */
function placeFor ( text : string , seed : number , variant : number ) : Built | null {
const loc = LOCATIONS . find ( ( l ) = > l . re . test ( text ) ) ;
if ( ! loc ) return null ;
const tuned = loc . adjust ? . ( text ) ? ? { } ;
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 } ;
let n = 0 ;
const elements : El [ ] = [ . . . loc . pieces , . . . ( tuned . extra ? ? [ ] ) ] . map ( ( p ) = > {
if ( typeof p ! == "string" ) return { . . . p , x : p.x + ( variant % 2 ? 0.03 : 0 ) } ;
const kind = p ;
return {
kind , x : slots [ ( n ++ + 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 ,
} ;
} ) ;
const weather = tuned . weather ? ? loc . weather ;
const flood = tuned . flood ? ? loc . flood ;
return {
place : { ground : loc.ground , indoor : loc.indoor , fog : loc.fog , . . . ( loc . horizon ? { horizon : loc.horizon } : { } ) , . . . ( weather ? { weather } : { } ) , . . . ( flood ? { flood } : { } ) , elements } ,
palette : tuned.palette ? ? loc . palette , override : loc.override || ! ! tuned . palette , light : loc.light ,
} ;
}
function expressionOf ( text : string ) : Expression {
@@ -91,6 +155,8 @@ function expressionOf(text: string): Expression {
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" ;
if ( /\b(determinad|decidid|firme)\w*/ . test ( text ) ) return "determined" ;
if ( /\b(seren|calm|aliviad|em paz)\w*/ . test ( text ) ) return "smile" ;
return "neutral" ;
}
@@ -102,27 +168,35 @@ function cueOf(text: string, re: RegExp): string | null {
}
/** Verbos e emoções do texto → linha do tempo do personagem (cada ação começa na palavra que a provocou). */
const MOVES : { re : RegExp ; act : ( cue : string , x : number ) = > Action [ ] } [ ] = [
{ re : /\b(andou|caminhou|foi ate|se aproximou|chegou perto)\b/ , act : ( cue , x ) = > [ { do : "walk" , cue , to : x < 0.5 ? x + 0.2 : x - 0.2 } ] } ,
// `face: true` = gesto com a mão no rosto (pensar, tapar a boca, mão na testa). REGRA: só entra quando a direção
// de cena (coluna Imagem) pede com todas as letras — palavra solta da narração ("imaginar", "lembrar", "riu")
// não põe a mão no rosto. Riso é expressão + corpo quicando, nunca mão na boca.
const MOVES : { re : RegExp ; act : ( cue : string , x : number ) = > Action [ ] ; face? : boolean } [ ] = [
{ re : /\b(andou|caminhou|caminharam|foi ate|se aproximou|chegou perto)\b/ , act : ( cue , x ) = > [ { do : "walk" , cue , to : x < 0.5 ? x + 0.2 : x - 0.2 } ] } ,
{ re : /\b(entra|entram|entrou|entraram) na (arca|casa|barca|caverna)\b/ , act : ( cue , x ) = > [ { do : "walk" , cue , to : Math.min ( 0.92 , x + 0.14 ) , dur : 2.4 } ] } ,
{ re : /\b(correu|fugiu|disparou|saiu correndo)\b/ , act : ( cue , x ) = > [ { do : "run" , cue , to : x < 0.5 ? x + 0.3 : x - 0.3 } ] } ,
{ re : /\b(pulou|saltou)\b/ , act : ( cue ) = > [ { do : "jump" , cue } ] } ,
{ re : /\b(caiu|desmaiou|tropecou|despencou)\b/ , act : ( cue ) = > [ { do : "fall" , cue } ] } ,
{ re : /\b(sentou|se sentou)\b/ , act : ( cue ) = > [ { do : "sit" , cue } ] } ,
{ re : /\b(sentou|se sentou|sentaram )\b/ , act : ( cue ) = > [ { do : "sit" , cue } ] } ,
{ re : /\b(levantou|se levantou|ficou de pe)\b/ , act : ( cue ) = > [ { do : "stand_up" , cue } ] } ,
{ re : /\b(ajoelhou|ajoelharam|orou|oraram|rezou|rezando|orando)\b/ , act : ( cue ) = > [ { do : "pose" , cue , pose : "kneel" } , { do : "look" , cue , dir : "up" } ] } ,
{ re : /\b(martelando|martelou|martelava|pregando)\b/ , act : ( cue ) = > [ { do : "hammer" , cue , dur : 2.6 } ] } ,
{ re : /\b(balancou a cabeca|negou|disse que nao)\b/ , act : ( cue ) = > [ { do : "shake_head" , cue } ] } ,
{ re : /\b(concordou|assentiu|acenou com a cabeca)\b/ , act : ( cue ) = > [ { do : "nod" , cue } ] } ,
{ re : /\b(tremia|tremeu|tremendo|arrepiou|arrepio)\b/ , act : ( cue ) = > [ { do : "tremble" , cue , dur : 1.4 } ] } ,
{ re : /\b(riu|gargalhou|caiu na risada|rindo)\b/ , act : ( cue ) = > [ { do : "express" , cue , expression : "laugh" } , { do : "bounce" , cue , times : 3 } ] } ,
{ re : /\b(chorou|chorando|lagrimas)\b/ , act : ( cue ) = > [ { do : "express" , cue , expression : "cry" } ] } ,
{ re : /\b(olhou para os lados|olhou em volta|procurou)\b/ , act : ( cue ) = > [ { do : "look" , cue , dir : "left" } , { do : "shake_head" , cue , times : 1 , dur : 1.2 } ] } ,
{ re : /\b(olhou para cima|olhou pro ceu)\b/ , act : ( cue ) = > [ { do : "look" , cue , dir : "up" } ] } ,
{ re : /\b(olhou para os lados|olhou em volta|olharam em volta|procurou)\b/ , act : ( cue ) = > [ { do : "look" , cue , dir : "left" } , { do : "shake_head" , cue , times : 1 , dur : 1.2 } ] } ,
{ re : /\b(olhou para cima|olhou pro ceu|olhou para o ceu|olharam para o ceu)\b/ , act : ( cue ) = > [ { do : "look" , cue , dir : "up" } ] } ,
{ re : /\b(virou|deu as costas)\b/ , act : ( cue ) = > [ { do : "turn" , cue } ] } ,
{ re : /\b(pensou|lembrou|imaginou|calculou|planejou )\b/ , act : ( cue ) = > [ { do : "pose" , cue , pose : "think" } ] } ,
{ re : /\b(acenou|tchau|chamou )\b/ , act : ( cue ) = > [ { do : "wav e" , cue } ] } ,
{ re : /\b(pensou|pensaram|pensativo|pensativa|mao no queixo )\b/ , act : ( cue ) = > [ { do : "pose" , cue , pose : "think" } ] , face : true } ,
{ re : /\b(tapou a boca|mao na boca|cobriu a boca|tapando a boca )\b/ , act : ( cue ) = > [ { do : "pos e" , cue , pose : "cover_mouth" } ] , face : true } ,
{ re : /\b(acenou|acenaram|tchau|chamou)\b/ , act : ( cue ) = > [ { do : "wave" , cue } ] } ,
{ re : /\b(apontou|mostrou)\b/ , act : ( cue ) = > [ { do : "pose" , cue , pose : "point" } ] } ,
{ re : /\b(segurou|segurava|ergueu)\b/ , act : ( cue ) = > [ { do : "pose" , cue , pose : "hold" } ] } ,
{ re : /\b(cruzou os bracos)\b/ , act : ( cue ) = > [ { do : "pose" , cue , pose : "cross_arms" } ] } ,
{ re : /\b(desesper |mao na cabeca|nao acreditou)\w* / , act : ( cue ) = > [ { do : "pose" , cue , pose : "facepalm" } ] } ,
{ re : /\b(comemorou |vibrou|venceu|conseguiu)\b/ , act : ( cue ) = > [ { do : "pose" , cue , pose : "celebrate" } , { do : "bounce" , cue , times : 2 } ] } ,
{ re : /\b(mao na testa |mao na cabeca|desesperou|desesperado|desesperada)\b / , act : ( cue ) = > [ { do : "pose" , cue , pose : "facepalm" } ] , face : true } ,
{ re : /\b(comemor\w* |vibrou|vibraram| venceu|conseguiu)\b/ , act : ( cue ) = > [ { do : "pose" , cue , pose : "celebrate" } , { do : "bounce" , cue , times : 2 } ] } ,
{ re : /\b(de repente|susto|assustou)\b/ , act : ( cue ) = > [ { do : "emote" , cue , text : "!" } ] } ,
{ re : /\b(por que|sera que|duvida|estranh)\w*/ , act : ( cue ) = > [ { do : "emote" , cue , text : "?" } ] } ,
] ;
@@ -134,7 +208,9 @@ const EMOTIONS: { re: RegExp; expression: Expression }[] = [
{ re : /\b(trist|perdeu|saudade|sozinh)\w*/ , expression : "sad" } ,
{ re : /\b(preocup|problema|nervos|ansios)\w*/ , expression : "worried" } ,
{ re : /\b(desconfi|suspeit)\w*/ , expression : "suspicious" } ,
{ re : /\b(feliz|alegr|sorri)\w*/ , expression : "happy" } ,
{ re : /\b(feliz|felizes| alegr|sorri)\w*/ , expression : "happy" } ,
{ re : /\b(determinad|decidid)\w*/ , expression : "determined" } ,
{ re : /\b(aliviad|seren|calm)\w*/ , expression : "smile" } ,
] ;
/** Fala entre aspas ou depois de travessão: [1ª palavra, última palavra, texto] (normalizados). */
@@ -146,17 +222,27 @@ function quoteOf(original: string): { first: string; last: string; text: string
return ws . length ? { first : ws [ 0 ] , last : ws [ ws . length - 1 ] , text : said } : null ;
}
/** Linha do tempo do personagem principal do trecho: emoção na palavra, verbos viram movimento, fala na boca. */
export function timelineFor ( original : string , x : number ) : Action [ ] {
/**
* Linha do tempo do personagem principal do trecho: emoção na palavra, verbos viram movimento, fala na boca.
* `hint` = coluna Imagem (direção de cena): o que ela pede e a narração não diz entra em ORDEM ao longo do
* trecho (posição no texto → fração do trecho), já que essas palavras não são faladas.
*/
export function timelineFor ( original : string , x : number , hint = "" ) : Action [ ] {
const text = norm ( original ) ;
const h = norm ( hint ) ;
const at = ( re : RegExp ) = > { const i = h . search ( re ) ; return Math . round ( ( 0.06 + 0.7 * ( i / Math . max ( 1 , h . length ) ) ) * 100 ) / 100 ; } ;
const out : Action [ ] = [ ] ;
for ( const e of EMOTIONS ) {
const cue = cueOf ( text , e . re ) ;
if ( cue ) { out . push ( { do : "express" , cue , expression : e.expression } ) ; break ; }
const emotion = EMOTIONS . find ( ( e ) = > cueOf ( text , e . re ) ) ;
if ( emotion ) out . push ( { do : "express" , cue : cueOf ( text , emotion . re ) ! , expression : emotion.expression } ) ;
else {
const first = EMOTIONS . map ( ( e ) = > ( { e , i : h.search ( e . re ) } ) ) . filter ( ( p ) = > p . i >= 0 ) . sort ( ( p , q ) = > p . i - q . i ) [ 0 ] ;
if ( first ) out . push ( { do : "express" , atP : Math.max ( 0.04 , at ( first . e . re ) - 0.04 ) , expression : first.e.expression } ) ;
}
for ( const m of MOVES ) {
const cue = cueOf ( text , m . re ) ;
// Gesto no rosto: nunca pela narração, só pela direção de cena (hint).
const cue = m . face ? null : cueOf ( text , m . re ) ;
if ( cue ) out . push ( . . . m . act ( cue , x ) ) ;
else if ( h && m . re . test ( h ) ) out . push ( . . . m . act ( "" , x ) . map ( ( a ) = > ( { . . . a , cue : undefined , atP : at ( m . re ) } ) ) ) ;
}
const quote = quoteOf ( original ) ;
if ( quote ) out . push ( { do : "talk" , cue : quote.first , cueEnd : quote.last , text : quote.text } ) ;
@@ -166,25 +252,146 @@ export function timelineFor(original: string, x: number): Action[] {
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" ;
// Mão no queixo só com pedido explícito (ver a regra dos gestos no rosto em MOVES).
if ( /\b(pensou|pensaram|pensativo|pensativa|mao no queixo)\b/ . test ( text ) ) return "think" ;
if ( /nao sabe|sem saber|nao entend/ . test ( text ) ) return "shrug" ;
return hasProp ? "point" : "stand" ;
}
type AnimalActor = Extract < NonNullable < ShotSpec [ "actors" ] > [ number ] , { kind : "animal" } > ;
type Species = AnimalActor [ "species" ] ;
/** Bichos citados (palavra → espécie); "animais/bichos" sem espécie vira um grupo variado. Grandes primeiro (vão atrás). */
const SPECIES_WORDS : [ RegExp , Species ] [ ] = [
[ /\belefantes?\b/ , "elephant" ] , [ /\bgirafas?\b/ , "giraffe" ] , [ /\bcamelos?\b/ , "camel" ] , [ /\bcavalos?\b|\begu[ao]s?\b/ , "horse" ] ,
[ /\bleao\b|\bleoes\b|\bleoa/ , "lion" ] , [ /\bovelhas?\b|\bcarneir\w*|\bcordeir\w*/ , "sheep" ] ,
[ /\bpombas?\b/ , "dove" ] , [ /\bcorvos?\b/ , "raven" ] ,
] ;
const FLYERS : Species [ ] = [ "dove" , "raven" ] ;
/** Animais do trecho: aves voando pelo céu (pomba com ramo, se o texto falar de oliveira); bichos de chão em
* casal, parados ou em fila andando até o barco ("fila", "entrando"). */
function animalsFor ( text : string , arkX : number | null ) : AnimalActor [ ] {
let species = SPECIES_WORDS . filter ( ( [ re ] ) = > re . test ( text ) ) . map ( ( [ , s ] ) = > s ) ;
if ( ! species . some ( ( s ) = > ! FLYERS . includes ( s ) ) && /\b(animais|bichos|casal de cada|bicharada)\b/ . test ( text ) ) {
species = [ . . . new Set < Species > ( [ "elephant" , "giraffe" , "lion" , "sheep" , . . . species ] ) ] ;
}
const out : AnimalActor [ ] = [ ] ;
const birds = species . filter ( ( s ) = > FLYERS . includes ( s ) ) . slice ( 0 , 2 ) ;
birds . forEach ( ( s , i ) = > {
const toRight = i === 0 ;
out . push ( { kind : "animal" , species : s , x : toRight ? 0.06 : 0.94 , y : 0.3 + i * 0.08 , scale : 2.4 , fly : true ,
walk : { to : toRight ? 0.82 : 0.32 } , . . . ( s === "dove" && /oliveira|\bramo\b|\bfolha/ . test ( text ) ? { carry : "olive" as const } : { } ) } ) ;
} ) ;
const ground = species . filter ( ( s ) = > ! FLYERS . includes ( s ) ) . slice ( 0 , 4 ) ;
const pair = /\b(casal|casais|pares|par|dois de cada|macho e femea)\b/ . test ( text ) || /\b(animais|fila)\b/ . test ( text ) ;
const line = /\b(fila|entrando|entram|entraram|marchando|em direcao)\b/ . test ( text ) ;
ground . forEach ( ( s , i ) = > {
if ( line ) {
const target = ( arkX ? ? 0.6 ) - 0.06 - i * 0.1 ;
out . push ( { kind : "animal" , species : s , x : target - 0.42 , y : Math.min ( 0.97 , 0.76 + i * 0.06 ) , pair , walk : { to : target , startS : i * 0.25 } } ) ;
} else {
const slots = [ [ 0.26 , 0.82 ] , [ 0.74 , 0.86 ] , [ 0.5 , 0.95 ] , [ 0.18 , 0.97 ] ] ;
out . push ( { kind : "animal" , species : s , x : slots [ i ] [ 0 ] , y : slots [ i ] [ 1 ] , pair , flip : slots [ i ] [ 0 ] > 0.5 } ) ;
}
} ) ;
return out ;
}
/** Peças que podem ser o ASSUNTO falado (palavra → peça). A arca aceita a versão em construção como ela mesma. */
const FOCUS_ELEMENTS : [ RegExp , El [ "kind" ] ] [ ] = [
[ /\b(arca|barco|barca|navio|embarcacao|bote)\b/ , "ark" ] ,
[ /\b(carro|caminhao|onibus|automovel|caminhonete|carroca)\b/ , "car" ] ,
[ /\barco-?\s?iris\b/ , "rainbow" ] ,
[ /\b(arvore|arvores)\b/ , "tree" ] ,
[ /\b(fogueira)\b/ , "fire" ] ,
[ /\b(barraca|tenda)\b/ , "tent" ] ,
] ;
const FOCUS_ANIMALS = /\b(animais|bichos|aves|pombas?|corvos?|elefantes?|girafas?|leao|leoes|ovelhas?|cavalos?|camelos?)\b/ ;
type Focus = { kind : "element" ; element : El [ "kind" ] } | { kind : "animal" } ;
/** O assunto do trecho: o 1º objeto ou bicho citado na NARRAÇÃO (é do que o vídeo está falando naquele momento);
* sem nenhum, uma peça citada na coluna Imagem. */
function focusOf ( narration : string , direction : string ) : Focus | null {
const hits : { at : number ; f : Focus } [ ] = [ ] ;
for ( const [ re , element ] of FOCUS_ELEMENTS ) { const at = narration . search ( re ) ; if ( at >= 0 ) hits . push ( { at , f : { kind : "element" , element } } ) ; }
const a = narration . search ( FOCUS_ANIMALS ) ;
if ( a >= 0 ) hits . push ( { at : a , f : { kind : "animal" } } ) ;
if ( hits . length ) return hits . sort ( ( p , q ) = > p . at - q . at ) [ 0 ] . f ;
for ( const [ re , element ] of FOCUS_ELEMENTS ) if ( re . test ( direction ) ) return { kind : "element" , element } ;
return null ;
}
const INSIDE = /\b(dentro d[aoe]|a bordo|embarc\w*|entr(a|am|ou|aram) n[ao] (arca|barco|barca|navio|carro|onibus)|n[ao] (arca|barco|carro) (com|por|durante))\b/ ;
/**
* Põe o assunto no centro, grande, e devolve onde ficam os `n` personagens: ao lado (cantos) ou DENTRO da peça
* (no convés da arca / atrás da lataria do carro, com a parte da frente desenhada por cima — `occupied`).
* Medidas iguais às do layout do cartoon (horizonte 0,56; frente 0,72; escala = scale × (1 − z·0,62) × 1,15).
*/
function stageFocus ( place : Place , focus : Focus , text : string , n : number ) : { xs : number [ ] ; ys : number [ ] ; scale : number } | null {
const side = ( count : number ) = > ( { xs : Array.from ( { length : count } , ( _ , i ) = > ( i % 2 === 0 ? 0.15 : 0.85 ) + ( i > 1 ? ( i % 2 === 0 ? 0.1 : - 0.1 ) : 0 ) ) , ys : Array.from ( { length : count } , ( _ , i ) = > 0.8 + ( i > 1 ? 0.03 : 0 ) ) , scale : count > 2 ? 0.6 : 0.72 } ) ;
if ( focus . kind === "animal" ) return n ? side ( n ) : null ;
const family : El [ "kind" ] [ ] = focus . element === "ark" ? [ "ark" , "ark_frame" ] : [ focus . element ] ;
let el = place . elements . find ( ( e ) = > family . includes ( e . kind ) ) ;
if ( ! el ) {
if ( place . indoor ) return null ;
el = { kind : focus.element === "ark" && /constru/ . test ( text ) && ! /pronta/ . test ( text ) ? "ark_frame" : focus . element , x : 0.5 , z : 0.4 } ;
place . elements . push ( el ) ;
}
if ( el . kind === "rainbow" ) return n ? side ( n ) : null ;
el . x = 0.5 ;
const occupiable = el . kind === "ark" || el . kind === "car" ;
const inside = occupiable && n > 0 && ( INSIDE . test ( text ) || ( el . kind === "ark" && place . ground === "water" ) ) ;
if ( ! inside ) {
if ( ! el . lift ) el . z = Math . min ( el . z ? ? 0.4 , 0.42 ) ;
el . scale = Math . max ( el . scale ? ? 1 , el . kind === "ark" || el . kind === "ark_frame" ? 1.2 : 1.3 ) ;
return n ? side ( n ) : null ;
}
// Dentro: a peça vem para a frente e os personagens ficam no convés, da cintura para cima.
el . occupied = true ;
el . z = el . lift ? el.z : 0.12 ;
el . scale = el . kind === "car" ? 0.95 : 1.05 ;
const H = 1920 ;
const horizon = ( place . horizon ? ? 0.56 ) * H ;
const s = el . scale * ( 1 - ( el . z ? ? 0.3 ) * 0.62 ) * 1.15 ;
let baseY = horizon + ( 1 - ( el . z ? ? 0.3 ) ) * ( H * 0.72 - horizon ) - ( el . lift ? ? 0 ) * H ;
if ( el . float && place . flood ) {
// Com gente dentro, a água fica parada no nível final (o convés não pode fugir de quem está nele).
place . flood = { from : place . flood . to , to : place.flood.to } ;
baseY = place . flood . to * H + H * 0.035 ;
}
const deck = baseY - ( el . kind === "car" ? 112 * 2.5 : 150 ) * s ;
const scale = n >= 4 ? 0.5 : n === 3 ? 0.56 : 0.66 ;
// Pés escondidos atrás do casco: o quadril fica na linha do convés.
const feet = ( deck + 0.3 * 0.52 * scale * H ) / H ;
const half = ( ( el . kind === "car" ? 300 : 330 ) * s ) / 1080 ;
const xs = Array . from ( { length : n } , ( _ , i ) = > ( n === 1 ? 0.5 - half * 0.25 : 0.5 - half * 0.7 + ( 1.4 * half * i ) / ( n - 1 ) ) ) ;
return { xs , ys : xs.map ( ( ) = > feet ) , scale } ;
}
/** Objetos que o personagem pode ter na mão (os outros ficam soltos na cena). */
const HANDHELD : CartoonIcon [ ] = [ "phone" , "fuel" , "battery" , "money" , "bulb" , "olive" , "hammer" , "ruler" ] ;
const GROUP_VERB = /\b(olharam|comemoraram|sentaram|pensaram|entram|entraram|caminharam|acenaram|oraram|ajoelharam|felizes|serenos)\b/ ;
/** 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" ;
// A coluna Imagem é a direção de cena: quando existe, lugar, quem aparece, objetos e ações saem dela (e do
// texto na tela); a narração continua dando os tempos (cue) e a fala. Sem ela, vale o texto todo.
const hint = shot . visualHint . trim ( ) ;
const subject = hint ? norm ( ` ${ shot . visualHint } ${ shot . onScreen } ` ) : text ;
const spoken = ` ${ shot . narration } ${ shot . onScreen } ` ;
const explicitTime = /\bnoite|madrugada|escuro|meia-noite/ . test ( subject ) ? "night" : /amanhecer|sol nasce|amanhece|entardecer|por do sol/ . test ( subject ) ? "dawn" : null ;
const dayRe = hint ? /\btarde\b|meio-dia|\bdia\b|\bsol\b|ensolarad|\bmanha\b|domingo|claro\b/ : /\btarde\b|meio-dia|de dia\b|\bsol\b|ensolarad|\bmanha\b|domingo|claro\b/ ;
const time = explicitTime ? ? ( dayRe . test ( subject ) ? "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 ) ;
let crowd = /\b(pessoas|gente|multidao|vizinhos|moradores|todo mundo)\b|\bfila\b(?! de (animais|bichos)) / . test ( subject ) ;
const sound = SOUNDS . find ( ( [ re ] ) = > re . test ( subject ) ) ;
const icons = ICON_RULES . filter ( ( [ re ] ) = > re . test ( subject ) ) . slice ( 0 , named ? 1 : 2 ) ;
const danger = DANGER . test ( subject ) ;
const negated = danger && /\b(nunca|nao)\b/ . test ( subject ) ;
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 ;
@@ -192,38 +399,96 @@ export function planCartoon(shot: ShotText, ctx: PlanContext = {}, variant = 0):
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 ) ,
rings : ( ! ! sound && i === 0 ) || /chama atencao|da pra ouvir|de longe/ . test ( subject ) ,
crossed : negated && i === 0 ,
} ;
} ) ;
// Lugar montado por peças quando o texto diz onde é (ou quando a história tem elenco/paleta: tudo vira lugar).
const technical = /funciona|liga\b|desliga|inversor|rede eletrica|circuito|sistema|corrente/ . test ( subject ) ;
const built = technical ? null : placeFor ( subject , shot . index * 7 + 1 , variant )
? ? ( cast ( ctx ) . length || ctx . palette ? placeFor ( "rua" , shot . index * 7 + 1 , variant ) : null ) ;
const arkX = built ? . place . elements . find ( ( e ) = > e . kind === "ark" || e . kind === "ark_frame" ) ? . x ? ? null ;
const animals = animalsFor ( subject , arkX ) ;
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 ? ? [ ] ;
// Elenco da história: quem é citado pelo nome (na ordem do texto) ; 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 all = cast ( ctx ) ;
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 ) = > {
// Nome de uma palavra só casa com MAIÚSCULA (o filho "Sem" ≠ a palavra "sem"); nome composto ("Esposa de Noé")
// casa inteiro, sem olhar maiúscula.
const cased = ( hint ? ` ${ shot . visualHint } ${ shot . onScreen } ` : original ) . normalize ( "NFD" ) . replace ( /[̀-ͯ]/g , "" ) ;
const findName = ( name : string ) = > {
const plain = name . normalize ( "NFD" ) . replace ( /[̀-ͯ]/g , "" ) . trim ( ) ;
if ( /\s/ . test ( plain ) ) return subject . search ( new RegExp ( ` \\ b ${ norm ( plain ) . replace ( /\s+/g , "\\s+" ) } \\ b ` ) ) ;
const m = new RegExp ( ` (^|[^ \\ p{L}]) ${ plain . replace ( /[.*+?^${}()|[\]\\]/g , "\\$&" ) } (?![ \\ p{L}]) ` , "u" ) . exec ( cased ) ;
return m ? m . index : - 1 ;
} ;
let castIn = all . map ( ( c ) = > ( { c , i : findName ( c . name ) } ) ) . filter ( ( p ) = > p . i >= 0 ) . sort ( ( p , q ) = > p . i - q . i ) . map ( ( p ) = > p . c ) ;
if ( ! castIn . length && all . length === 1 && ! crowd && ( shot . index % 2 === 0 || /\b(ele|ela)\b/ . test ( text ) ) ) castIn = [ all [ 0 ] ] ;
// Família/grupo do elenco já em cena: "8 pessoas" não vira multidão atrás deles.
if ( castIn . length >= 3 ) crowd = false ;
const tl0 = timelineFor ( spoken , 0.5 , hint ) ;
const talking = tl0 . some ( ( a ) = > a . do === "talk" ) ;
// Quem fala sozinho vai de perto (close) e a cena fica só com ele.
const close = talking && castIn . length > 0 && ( castIn . length === 1 || /\bfala\b|\bclose\b|de perto/ . test ( subject ) ) ;
if ( close ) castIn = castIn . slice ( 0 , 1 ) ;
castIn = castIn . slice ( 0 , 5 ) ;
const n = castIn . length ;
const group = n > 2 ;
const xs = n === 1 ? [ props . length || animals . some ( ( a ) = > ! a . fly ) ? 0.34 : 0.5 ] : n === 2 ? [ 0.3 , 0.7 ] : castIn . map ( ( _ , i ) = > 0.14 + ( 0.72 * i ) / ( n - 1 ) ) ;
if ( n === 1 && animals . some ( ( a ) = > ! a . fly ) && arkX !== null ) xs [ 0 ] = 0.8 ;
let ys : number [ ] = castIn . map ( ( _ , i ) = > ( group ? 0.8 + ( i % 2 ) * 0.03 : n === 2 ? 0.8 : 0.78 ) ) ;
let scales : ( number | undefined ) [ ] = castIn . map ( ( ) = > ( n >= 4 ? 0.6 : group ? 0.72 : n === 2 ? 0.9 : undefined ) ) ;
// Assunto do trecho: o objeto ou bicho de que a NARRAÇÃO fala vai para o centro, grande; o personagem fica ao
// lado dele, ou DENTRO (arca, carro) quando o texto diz — nunca o personagem sozinho tomando a cena.
const focus = built ? focusOf ( norm ( spoken ) , subject ) : null ;
if ( focus && built && ! close ) {
const placed = stageFocus ( built . place , focus , ` ${ norm ( spoken ) } ${ subject } ` , n ) ;
if ( focus . kind === "animal" && ! animals . some ( ( a ) = > ! a . fly ) ) animals . push ( . . . animalsFor ( norm ( spoken ) , null ) ) ;
if ( focus . kind === "animal" ) for ( const a of animals ) if ( ! a . fly ) { a . scale = ( a . scale ? ? 1 ) * 1.35 ; a . x = 0.18 + ( a . x - 0.18 ) * 0.7 ; }
if ( placed ) {
for ( let i = 0 ; i < n ; i ++ ) { xs [ i ] = placed . xs [ i ] ; ys [ i ] = placed . ys [ i ] ; }
ys = ys . slice ( 0 , n ) ;
scales = castIn . map ( ( ) = > placed . scale ) ;
}
}
// Martelar: vai para quem é citado logo antes de "martel…" (os outros só seguram o martelo).
const hammerAt = subject . search ( /martel(ando|ou|ava)/ ) ;
let hammerer = - 1 ;
if ( hammerAt >= 0 ) {
let bestPos = - 1 ;
castIn . forEach ( ( c , i ) = > { const p = subject . lastIndexOf ( firstName ( c . name ) , hammerAt ) ; if ( p > bestPos ) { bestPos = p ; hammerer = i ; } } ) ;
}
const everyone = GROUP_VERB . test ( subject ) ;
// Close das mãos (vista "insert"): só as mãos de quem é citado primeiro, segurando o objeto.
const insert = n >= 1 && /close (das|nas) maos|maos segurando|maos de \w+ segurando|insert / . test ( subject ) ;
castIn . forEach ( ( c , i ) = > {
const x = xs [ i ] ;
const own = timelineFor ( spoken , x , hint ) . filter ( ( a ) = > a . do !== "hammer" ) ;
const timeline = i === 0 ? own : everyone ? own . filter ( ( a ) = > a . do !== "talk" ) : [ ] ;
if ( i === hammerer ) timeline . push ( { do : "hammer" , atP : 0.1 , dur : 3 } ) ;
const holds = props . find ( ( p ) = > HANDHELD . includes ( p . icon ) ) ? . icon ? ? ( hammerer === i || ( i === 0 && /\bmartelo\b/ . test ( subject ) ) ? "hammer" : undefined ) ;
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 ,
kind : "person" , x , y : ys [ i ] , scale : scales [ i ] , enterS : 0.15 + i * 0.2 ,
character : { name : c.name , caption : i === 0 && shot . index === 0 ? c.caption : undefined , look : c.look } ,
// Começa neutro e a emoção/movimento entram na palavra (linha do tempo); sem gatilho no texto, fica a
// expressão geral do trecho desde o início.
expression : timelineFor ( original , 0.5 ) . some ( ( a ) = > a . do === "express" ) ? "neutral" : expressionOf ( text ) ,
pose : i === 0 ? poseOf ( text , props . length > 0 ) : "stand" ,
. . . ( i === 0 ? { timeline : timelineFor ( original , castIn . length > 1 ? 0.3 : props.length ? 0.34 : 0.5 ) } : { } ) ,
// Enquadramento: de perto quando fala; meio corpo sozinho em cena; corpo inteiro com mais gente/objetos.
framing : i === 0 && timelineFor ( original , 0.5 ) . some ( ( a ) = > a . do === "talk" ) && castIn . length === 1 ? "close"
: castIn . length === 1 && ! crowd && props . length === 0 ? "medium" : "full" ,
item : i === 0 && props . length === 1 && [ "phone" , "fuel" , "battery" , "money" , "bulb" ] . includes ( props [ 0 ] . icon ) ? props [ 0 ] . icon : undefined ,
flip : i === 1 ,
expression : timeline.some ( ( a ) = > a . do === "express" ) ? "neutral" : expressionOf ( subject ) ,
pose : i === 0 || everyone ? poseOf ( subject , props . length > 0 ) : "stand" ,
. . . ( timeline . length ? { timeline } : { } ) ,
// Enquadramento: de perto quando fala; meio corpo sozinho em cena; corpo inteiro com mais gente/objetos/bichos .
framing : insert && i === 0 ? "insert" : close && i === 0 ? "close" : n === 1 && ! focus && ! crowd && props . length === 0 && ! animals . length ? "medium" : "full" ,
item : i === 0 || i === hammerer ? holds : undefined ,
flip : n === 2 ? i === 1 : group ? x > 0.5 : false ,
} ) ;
} ) ;
// 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 ; } ) ;
props . forEach ( ( p ) = > { p . x = actors [ 0 ] && "x" in actors [ 0 ] && actors [ 0 ] . x > 0.5 ? 0.26 : 0.74 ; p . y = 0.5 ; } ) ;
}
if ( named && ! castIn . length ) {
const older = /^(Dona|Tia)$/ . test ( named [ 1 ] ) ;
@@ -231,41 +496,137 @@ export function planCartoon(shot: ShotText, ctx: PlanContext = {}, variant = 0):
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 per sonagem: entra primeiro (desenhada antes) e co m os pés acima dos dele.
// Bichos e pes soas desenhados de trás para a frente (quem te m o pé mais alto na tela fica atrás); o close vai
// por cima de tudo. Multidão atrás do personagem: entra primeiro e com os pés acima dos dele.
const depth = ( a : ( typeof actors ) [ number ] ) = > ( a . kind === "person" && a . framing && a . framing !== "full" ? 2 : a.kind === "animal" && a . fly ? 3 : "y" in a ? a.y : 0 ) ;
actors . push ( . . . animals ) ;
actors . sort ( ( a , b ) = > depth ( a ) - depth ( b ) ) ;
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" ] )
: named || crowd ? ( /portao|porta|frente|calcada/ . test ( subject ) ? [ "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 ( ) ;
// Cena "ocupada" (pessoa ou objeto): a cartela flutua; vazia, vai em tela cheia.
const busy = actors . some ( ( a ) = > a . kind === "person" ) || props . length > 0 ;
// Texto na tela vira cartela: número (stat), porcentagem (barra), itens com ";" (lista); o resto, etiqueta.
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" } ) ;
texts . push ( onScreenCard ( onScreen , danger , busy )
? ? { kind : "tag" , text : onScreen.slice ( 0 , 40 ) , x : 0.5 , y : close ? 0.12 : 0.17 , atS : 0.1 , tone : danger ? "danger" : "info" } ) ;
}
texts . push ( . . . nameCardsFor ( actors , shot . index ) ) ;
// 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 } ) ;
// Paleta: a do lugar quando ele manda (tempestade, arco-íris, museu) > hora dita na coluna Imagem (noite,
// amanhecer) > a da série > a do lugar > a da hora.
const timePalette : PaletteId = time === "day" ? "day" : time === "dawn" ? "dusk" : "night" ;
const explicitPalette : PaletteId | undefined = explicitTime === "night" ? "night" : explicitTime === "dawn" ? "dusk" : undefined ;
const palette = built ? ( built . override ? built.palette : undefined ) ? ? ( hint ? explicitPalette : undefined ) ? ? ctx . palette ? ? built . palette ? ? timePalette : undefined ;
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 } : { } ) ,
scene : { kind , time , litHouse : kind === "street" && /acesa|aceso|luz|iluminad|gerador/ . test ( subject ) } ,
. . . ( built ? { place : built.place , palette , . . . ( 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 ,
} ;
}
const cast = ( ctx : PlanContext ) = > ctx . cast ? ? [ ] ;
type TextItem = NonNullable < CartoonScene [ "texts" ] > [ number ] ;
type CheckState = NonNullable < NonNullable < TextItem [ "items" ] > [ number ] [ "state" ] > ;
/**
* Texto na tela curto com número → cartela. "Na fila: 297" → stat (rótulo = palavras antes do número; vermelho com
* palavra de perigo ou número negativo); "Talento 97%" → barra de progresso; "Gerador; Gasolina; Lanterna" → lista
* que se marca em sequência. Cena vazia (sem pessoa nem objeto): cartela em tela cheia (fundo escuro); senão, flutua no
* alto, longe do rosto. Nada reconhecido → null (vira etiqueta).
*/
export function onScreenCard ( onScreen : string , danger : boolean , busy : boolean ) : TextItem | null {
const text = onScreen . trim ( ) ;
if ( text . includes ( ";" ) ) {
const items = text . split ( ";" ) . map ( checkItem ) . filter ( ( i ) : i is NonNullable < ReturnType < typeof checkItem > > = > ! ! i ) . slice ( 0 , 8 ) ;
if ( items . length >= 2 ) return checklistCard ( items , busy ) ;
}
if ( text . length > 34 ) return null ;
// Rótulo (sem dígitos) + número no fim: "-R$ 47.312.904", "R$ 0", "297", "20 L", "97%".
const m = / ^ ( [ ^ \ d ] * ? ) [ \ s : – — ] * ( ( ? : - ( ? = R | \ d ) ) ? ( ? : R \ $ \ s ? ) ? \ d [ \ d . , ] * \ s ? ( ? : % | [ \ p { L } $ ] { 1 , 8 } \ . ? ) ? ) $ / u . e x e c ( t e x t ) ;
if ( ! m ) return null ;
const label = m [ 1 ] . replace ( /[\s:–—-]+$/ , "" ) . trim ( ) ;
const value = m [ 2 ] . trim ( ) ;
if ( /\d/ . test ( label ) ) return null ;
const pct = /^(\d{1,3}(?:[.,]\d+)?)\s?%$/ . exec ( value ) ;
if ( pct && label && Number ( pct [ 1 ] . replace ( "," , "." ) ) <= 100 ) {
return { kind : "progress" , text : label , value : Number ( pct [ 1 ] . replace ( "," , "." ) ) , x : 0.5 , y : 0.25 , atS : 0.2 , . . . ( danger ? { tone : "danger" as const } : { } ) } ;
}
// Vermelho: palavra de perigo, número negativo ou zerado ("R$ 0", como o caixa vazio da referência).
const tone = danger || /^-/ . test ( value ) || /^\D*0+(?:[.,]0+)?\D*$/ . test ( value ) || DANGER . test ( norm ( label ) ) ? { tone : "danger" as const } : { } ;
return busy
? { kind : "stat" , text : label , value , x : 0.5 , y : 0.25 , atS : 0.2 , size : 0.8 , . . . tone }
: { kind : "stat" , text : label , value , x : 0.5 , y : 0.4 , atS : 0.2 , panel : true , . . . tone } ;
}
/** Item da lista: "✓ x"/"[x] x" marcado, "✗ x"/"não x"/"sem x" riscado, "[ ] x" vazio; sem marca, marcado. */
function checkItem ( raw : string ) : { text : string ; state : CheckState } | null {
let t = raw . trim ( ) ;
let state : CheckState = "checked" ;
const mark = /^(\[x\]|✓|✔|☑)\s*|^(\[ \]|☐)\s*|^(✗|✘|❌|\[-\])\s*/i . exec ( t ) ;
if ( mark ) { state = mark [ 1 ] ? "checked" : mark [ 2 ] ? "empty" : "crossed" ; t = t . slice ( mark [ 0 ] . length ) . trim ( ) ; }
else if ( /^(nao|sem|nunca)\b/ . test ( norm ( t ) ) ) state = "crossed" ;
return t ? { text : t.slice ( 0 , 28 ) , state } : null ;
}
function checklistCard ( items : { text : string ; state : CheckState } [ ] , busy : boolean ) : TextItem {
// Largura/altura aproximadas em unidades de u() (% da largura de um vertical), para caber no quadro.
const longest = Math . max ( . . . items . map ( ( i ) = > i . text . length ) ) ;
const width = 25.6 + longest * 6.1 * 0.58 ;
if ( ! busy ) {
const size = Math . min ( 1 , 84 / width ) ;
return { kind : "checklist" , text : "" , items , x : 0.5 , y : 0.42 , atS : 0.1 , panel : true , . . . ( size < 1 ? { size : Number ( size . toFixed ( 2 ) ) } : { } ) } ;
}
// Cena ocupada: lista pequena no canto de cima, logo abaixo do painel do topo (como a referência).
const size = 0.52 ;
const height = size * ( 10 + items . length * 8.2 + ( items . length - 1 ) * 3.3 ) ;
return { kind : "checklist" , text : "" , items , size , atS : 0.2 ,
x : Number ( ( ( 4 + ( size * width ) / 2 ) / 100 ) . toFixed ( 3 ) ) , y : Number ( ( 0.124 + ( height * 0.005625 ) / 2 ) . toFixed ( 3 ) ) } ;
}
/**
* Cartão de nome de quem aparece pela 1ª vez (1º trecho ou com `caption`): nome + função. Sozinho em cena, o cartão
* vai para o lado com mais espaço (oposto ao rosto) na altura do peito/cabeça; com mais gente, acima da cabeça. Quem
* ganha cartão perde a etiqueta amarela (label vazio), para o nome não aparecer duas vezes.
*/
export function nameCardsFor ( actors : NonNullable < CartoonScene [ "actors" ] > , shotIndex : number ) : TextItem [ ] {
const people = actors . filter ( ( a ) = > a . kind === "person" ) ;
const cards : TextItem [ ] = [ ] ;
for ( const a of people ) {
if ( a . kind !== "person" || ! a . character || cards . length >= 2 ) continue ;
const caption = a . character . caption ? . trim ( ) ;
if ( ! caption && shotIndex !== 0 ) continue ;
const lines = caption ? caption . split ( /\s*[;·|]\s*/ ) . filter ( Boolean ) . slice ( 0 , 2 ) : [ ] ;
const clamp = ( v : number ) = > Math . max ( 0.24 , Math . min ( 0.76 , v ) ) ;
const scale = a . scale ? ? 1 ;
let x : number ; let y : number ;
if ( people . length === 1 ) {
x = clamp ( a . x >= 0.5 ? a . x - 0.3 : a.x + 0.3 ) ;
y = a . framing === "close" ? 0.585 : a.framing === "medium" ? 0.62 : a.y - 0.27 * scale ;
} else {
x = clamp ( a . x ) ;
y = a . y - 0.42 * scale - 0.05 ;
}
cards . push ( { kind : "namecard" , text : a.character.name , . . . ( lines . length ? { lines } : { } ) , x : Number ( x . toFixed ( 3 ) ) , y : Number ( Math . max ( 0.2 , y ) . toFixed ( 3 ) ) ,
atS : ( a . enterS ? ? 0 ) + 0.35 } ) ;
a . label = "" ;
}
return cards ;
}
/** 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 ;