Block generated by node tools/gen-docs.mjs. Source: the command in the right column of each row
diff --git a/public/docs/en/instrumentacao-ai/index.html b/public/docs/en/instrumentacao-ai/index.html
index c124023f94..935897c93d 100644
--- a/public/docs/en/instrumentacao-ai/index.html
+++ b/public/docs/en/instrumentacao-ai/index.html
@@ -4,8 +4,8 @@
AI instrumentation: how the work gets done | CORO SOLTO — Docs do Dev
-
-
+
+
diff --git a/public/docs/en/quality-gates/index.html b/public/docs/en/quality-gates/index.html
index 46431eaaf4..59dfff9704 100644
--- a/public/docs/en/quality-gates/index.html
+++ b/public/docs/en/quality-gates/index.html
@@ -4,8 +4,8 @@
The gate: invariants, provenance and mutation | CORO SOLTO — Docs do Dev
-
-
+
+
diff --git a/public/docs/en/sonda-processos/index.html b/public/docs/en/sonda-processos/index.html
index ffd65af777..2917e162f3 100644
--- a/public/docs/en/sonda-processos/index.html
+++ b/public/docs/en/sonda-processos/index.html
@@ -4,8 +4,8 @@
Três desfechos: medir, reprovar e não conseguir medir | CORO SOLTO — Docs do Dev
-
-
+
+
diff --git a/public/docs/en/stack/index.html b/public/docs/en/stack/index.html
index 50fbba1a21..8b48a9f0d8 100644
--- a/public/docs/en/stack/index.html
+++ b/public/docs/en/stack/index.html
@@ -4,8 +4,8 @@
Stack and tools | CORO SOLTO — Docs do Dev
-
-
+
+
diff --git a/public/docs/estado/index.html b/public/docs/estado/index.html
index 856567c78a..dad4c094f1 100644
--- a/public/docs/estado/index.html
+++ b/public/docs/estado/index.html
@@ -4,8 +4,8 @@
Estado atual: produção, dados e dívidas | CORO SOLTO — Docs do Dev
-
-
+
+
diff --git a/public/docs/index.html b/public/docs/index.html
index 3ec14f95f1..5e63056d76 100644
--- a/public/docs/index.html
+++ b/public/docs/index.html
@@ -4,8 +4,8 @@
O que é, e como rodar | CORO SOLTO — Docs do Dev
-
-
+
+
@@ -23,7 +23,7 @@
esta página envelhecia no primeiro commit — ver
o que é gerado, e o que não é.
-
Bloco gerado por node tools/gen-docs.mjs. Fonte: o comando da coluna direita de cada linha
diff --git a/public/docs/instrumentacao-ai/index.html b/public/docs/instrumentacao-ai/index.html
index bde94145d3..f52aef6072 100644
--- a/public/docs/instrumentacao-ai/index.html
+++ b/public/docs/instrumentacao-ai/index.html
@@ -4,8 +4,8 @@
Instrumentação de IA: como o trabalho é feito | CORO SOLTO — Docs do Dev
-
-
+
+
diff --git a/public/docs/quality-gates/index.html b/public/docs/quality-gates/index.html
index cdf0ab39ef..bb5f6db948 100644
--- a/public/docs/quality-gates/index.html
+++ b/public/docs/quality-gates/index.html
@@ -4,8 +4,8 @@
O quality gate: invariantes, procedência e mutação | CORO SOLTO — Docs do Dev
-
-
+
+
diff --git a/public/docs/sonda-processos/index.html b/public/docs/sonda-processos/index.html
index 34f14f87f4..4d9d729871 100644
--- a/public/docs/sonda-processos/index.html
+++ b/public/docs/sonda-processos/index.html
@@ -4,8 +4,8 @@
Três desfechos: medir, reprovar e não conseguir medir | CORO SOLTO — Docs do Dev
-
-
+
+
diff --git a/public/docs/stack/index.html b/public/docs/stack/index.html
index 6bfb8689e6..dbe2590f2d 100644
--- a/public/docs/stack/index.html
+++ b/public/docs/stack/index.html
@@ -4,8 +4,8 @@
Stack e ferramentas | CORO SOLTO — Docs do Dev
-
-
+
+
diff --git a/public/img/textures/hd_sertao/FONTE.md b/public/img/textures/hd_sertao/FONTE.md
new file mode 100644
index 0000000000..9af95d13aa
--- /dev/null
+++ b/public/img/textures/hd_sertao/FONTE.md
@@ -0,0 +1,29 @@
+# Texturas HD do Sertão (kit `?hd=1`)
+
+Todas vêm do Poly Haven, licença **CC0 1.0** (domínio público, sem atribuição obrigatória).
+Baixadas em 10/11/2026 pela API `https://api.polyhaven.com/files/`, mapas JPG 2K nos conjuntos
+anteriores e JPG 1K para `dry_ground_01`, e convertidas para WebP 1024 px (`sharp.resize(1024)` +
+`.webp`, cor q82, normal/rough q86).
+
+`*_cor.webp` = difuso multiplicado pela oclusão (AO × 0,75 + 0,25) do mesmo conjunto; `dry_ground_01_cor.webp` usa o difuso CC0 direto.
+`*_normal.webp` = normal OpenGL (`nor_gl`); `*_rough.webp` preserva o mapa de rugosidade.
+
+| Arquivo | Slug | Página | Peso |
+|---|---|---|---|
+| `white_rough_plaster_cor.webp` | `white_rough_plaster` | https://polyhaven.com/a/white_rough_plaster | 303 KB |
+| `white_rough_plaster_normal.webp` | `white_rough_plaster` | https://polyhaven.com/a/white_rough_plaster | 246 KB |
+| `clay_block_wall_cor.webp` | `clay_block_wall` | https://polyhaven.com/a/clay_block_wall | 184 KB |
+| `dry_ground_rocks_cor.webp` | `dry_ground_rocks` | https://polyhaven.com/a/dry_ground_rocks | 350 KB |
+| `old_planks_02_cor.webp` | `old_planks_02` | https://polyhaven.com/a/old_planks_02 | 76 KB |
+| `old_planks_02_normal.webp` | `old_planks_02` | https://polyhaven.com/a/old_planks_02 | 158 KB |
+| `clay_roof_tiles_02_cor.webp` | `clay_roof_tiles_02` | https://polyhaven.com/a/clay_roof_tiles_02 | 164 KB |
+| `clay_roof_tiles_02_normal.webp` | `clay_roof_tiles_02` | https://polyhaven.com/a/clay_roof_tiles_02 | 257 KB |
+
+| `dry_ground_01_cor.webp` | `dry_ground_01` | https://polyhaven.com/a/dry_ground_01 | 227 KB |
+| `dry_ground_01_normal.webp` | `dry_ground_01` | https://polyhaven.com/a/dry_ground_01 | 206 KB |
+| `dry_ground_01_rough.webp` | `dry_ground_01` | https://polyhaven.com/a/dry_ground_01 | 143 KB |
+
+Origem dos conjuntos antigos: `https://dl.polyhaven.org/file/ph-assets/Textures/jpg/2k//_{diff,ao,nor_gl}_2k.jpg`.
+Origem de `dry_ground_01`: `https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/dry_ground_01/dry_ground_01_{diff,nor_gl,rough}_1k.jpg`.
+Uso em `public/js/map_sertao_hd.js`: reboco (detalhe e relevo por cima da cor autoral), adobe sob o
+reboco caído, terra do chão, tábua das caixas de madeira e telha das águas de caixa.
diff --git a/public/img/textures/hd_sertao/clay_block_wall_cor.webp b/public/img/textures/hd_sertao/clay_block_wall_cor.webp
new file mode 100644
index 0000000000..98b652ed15
Binary files /dev/null and b/public/img/textures/hd_sertao/clay_block_wall_cor.webp differ
diff --git a/public/img/textures/hd_sertao/clay_roof_tiles_02_cor.webp b/public/img/textures/hd_sertao/clay_roof_tiles_02_cor.webp
new file mode 100644
index 0000000000..dd5fe0926f
Binary files /dev/null and b/public/img/textures/hd_sertao/clay_roof_tiles_02_cor.webp differ
diff --git a/public/img/textures/hd_sertao/clay_roof_tiles_02_normal.webp b/public/img/textures/hd_sertao/clay_roof_tiles_02_normal.webp
new file mode 100644
index 0000000000..5e061f33e5
Binary files /dev/null and b/public/img/textures/hd_sertao/clay_roof_tiles_02_normal.webp differ
diff --git a/public/img/textures/hd_sertao/dry_ground_01_cor.webp b/public/img/textures/hd_sertao/dry_ground_01_cor.webp
new file mode 100644
index 0000000000..a896d4541c
Binary files /dev/null and b/public/img/textures/hd_sertao/dry_ground_01_cor.webp differ
diff --git a/public/img/textures/hd_sertao/dry_ground_01_normal.webp b/public/img/textures/hd_sertao/dry_ground_01_normal.webp
new file mode 100644
index 0000000000..c383a2b036
Binary files /dev/null and b/public/img/textures/hd_sertao/dry_ground_01_normal.webp differ
diff --git a/public/img/textures/hd_sertao/dry_ground_01_rough.webp b/public/img/textures/hd_sertao/dry_ground_01_rough.webp
new file mode 100644
index 0000000000..9eb9887401
Binary files /dev/null and b/public/img/textures/hd_sertao/dry_ground_01_rough.webp differ
diff --git a/public/img/textures/hd_sertao/dry_ground_rocks_cor.webp b/public/img/textures/hd_sertao/dry_ground_rocks_cor.webp
new file mode 100644
index 0000000000..f73c992f16
Binary files /dev/null and b/public/img/textures/hd_sertao/dry_ground_rocks_cor.webp differ
diff --git a/public/img/textures/hd_sertao/old_planks_02_cor.webp b/public/img/textures/hd_sertao/old_planks_02_cor.webp
new file mode 100644
index 0000000000..f1e4e53a14
Binary files /dev/null and b/public/img/textures/hd_sertao/old_planks_02_cor.webp differ
diff --git a/public/img/textures/hd_sertao/old_planks_02_normal.webp b/public/img/textures/hd_sertao/old_planks_02_normal.webp
new file mode 100644
index 0000000000..517c40677f
Binary files /dev/null and b/public/img/textures/hd_sertao/old_planks_02_normal.webp differ
diff --git a/public/img/textures/hd_sertao/white_rough_plaster_cor.webp b/public/img/textures/hd_sertao/white_rough_plaster_cor.webp
new file mode 100644
index 0000000000..2c93d4bceb
Binary files /dev/null and b/public/img/textures/hd_sertao/white_rough_plaster_cor.webp differ
diff --git a/public/img/textures/hd_sertao/white_rough_plaster_normal.webp b/public/img/textures/hd_sertao/white_rough_plaster_normal.webp
new file mode 100644
index 0000000000..68718b1c00
Binary files /dev/null and b/public/img/textures/hd_sertao/white_rough_plaster_normal.webp differ
diff --git a/public/js/account-entry.js b/public/js/account-entry.js
index d29653177b..0c9c08131f 100644
--- a/public/js/account-entry.js
+++ b/public/js/account-entry.js
@@ -1,4 +1,4 @@
-import {analyticsAllowed,mountPrivacyChoice,setPrivacyChoice} from './privacy-preferences.js';
+import {privacyChoice,mountPrivacyChoice,setPrivacyChoice} from './privacy-preferences.js';
import {accountVerifiedBadge} from './account-verified.js';
const REQUIRED_PROVIDERS=['google','discord','x','linkedin_oidc'];
const providerChoices=config=>[...new Set([...REQUIRED_PROVIDERS.map(p=>p==='x' && config.providers?.includes('twitter') && !config.providers?.includes('x')?'twitter':p),...(config.providers || [])])];
@@ -35,8 +35,10 @@ export function loadAuthOptions() {
export function accountError(e){return ERRORS[e.message] || 'A conta não respondeu. Tente novamente; você pode continuar como convidado.';}
export function guestProof() {
if(accountActive)return undefined;
- const uid=localStorage.getItem('cs_anon'),token=localStorage.getItem('awpbr_token');
- return uid && token?{uid,token}:undefined;
+ try {
+ const uid=localStorage.getItem('cs_anon'),token=localStorage.getItem('awpbr_token');
+ return uid && token?{uid,token}:undefined;
+ } catch { return undefined; }
}
export function acceptAccount(auth) {
accountActive=!!auth?.authenticated;
@@ -89,11 +91,11 @@ export function mountAccountEntry(container,{auth=null,config={providers:[]},ret
consentLabel.append(consent,document.createTextNode('Quero receber novidades do Coro Solto por e-mail. Opcional; vou confirmar meu e-mail e posso sair quando quiser.'));
const privacy=node('a','Como usamos seus dados','account-privacy');privacy.href='/privacidade';privacy.target='_blank';privacy.rel='noopener';
choiceColumn.append(consentLabel);
- const analytics=mountPrivacyChoice(choiceColumn);
+ mountPrivacyChoice(choiceColumn,{onChange:async value=>{try{await setPrivacyChoice(value);}catch(e){say(value?'Não foi possível salvar a escolha neste navegador.':'Medição desligada somente nesta aba; não foi possível salvar a escolha neste navegador.');throw e;}}});
const terms=node('a','Termos de uso','account-privacy');terms.href='/termos';terms.target='_blank';terms.rel='noopener';
choiceColumn.append(privacy,document.createTextNode(' · '),terms);
let linkGuest=true;
- const payload=()=>{setPrivacyChoice(analytics.checked);newsletterDraft=consent.checked;return {returnTo,newsletter:consent.checked,analytics:analytics.checked,...(linkGuest && guestProof()?{guest:guestProof()}:{})};};
+ const payload=()=>{newsletterDraft=consent.checked;const choice=privacyChoice();return {returnTo,newsletter:consent.checked,...(typeof choice?.analytics==='boolean'?{analytics:choice.analytics}:{}),...(linkGuest && guestProof()?{guest:guestProof()}:{})};};
const entryAttempts=new Map();
const perform=fn=>{
if(entryAttempts.has(fn))return entryAttempts.get(fn);
@@ -124,7 +126,7 @@ export function mountAccountEntry(container,{auth=null,config={providers:[]},ret
const submit=button('ENTRAR NA CONTA DE TESTE',async()=>{if(!form.reportValidity())return;await socialApi('/api/social-auth',{action:'password',email:email.value,password:password.value});password.value='';const session=await loadAccount();acceptAccount(session);await onAuthenticated(session);});
form.append(eLabel,pLabel,submit);form.onsubmit=e=>{e.preventDefault();submit.click();};details.append(summary,form);entryColumn.append(details);
}
- container.append(status,button('CONTINUAR COMO CONVIDADO',()=>{setPrivacyChoice(analytics.checked);newsletterDraft=consent.checked;onGuest();},'account-guest'));
+ container.append(status,button('CONTINUAR COMO CONVIDADO',()=>{newsletterDraft=consent.checked;onGuest();},'account-guest'));
}
export function mountAccountIntegrations(container,auth,config,message=()=>{}) {
const section=node('section','','account-integrations');section.append(node('h3','Logins vinculados'),node('p','Entre com qualquer rede vinculada e caia na mesma conta.','social-muted'));
@@ -154,7 +156,7 @@ export async function mountProfilePreferences(container,{auth=null,message=()=>{
const note=node('p','','account-entry-status');note.setAttribute('role','status');
const say=text=>{note.textContent=text;message(text);};
let current=auth;
- const control=mountPrivacyChoice(section,{onChange:async value=>{try{setPrivacyChoice(value);if(current?.authenticated){await socialApi('/api/social-auth',{action:'privacy',analytics:value});current.privacy={analytics:value};}say(value?'Permissão salva neste navegador.':'Coleta opcional desativada neste navegador.');}catch(e){say('Escolha local aplicada; o registro na conta não respondeu. Tente novamente.');throw e;}}});
+ const control=mountPrivacyChoice(section,{pageUsage:true,onPageChange:value=>say(value?'Contagem de páginas permitida neste navegador.':'Contagem de páginas desligada neste navegador.'),onPageError:()=>say('Não foi possível salvar a escolha neste navegador.'),onChange:async value=>{let saved;try{saved=await setPrivacyChoice(value);}catch(e){say(value?'Não foi possível salvar a escolha neste navegador.':'Medição desligada somente nesta aba; não foi possível salvar a escolha neste navegador.');throw e;}if(!saved)return;try{if(current?.authenticated){await socialApi('/api/social-auth',{action:'privacy',analytics:value});current.privacy={analytics:value};}say(value?'Permissão salva neste navegador.':'Coleta opcional desativada neste navegador.');}catch(e){say('Escolha salva neste navegador; o registro na conta não respondeu. Tente novamente.');throw e;}}});
const newsletter=node('div');
const mountGuestNewsletter=()=>{
const label=node('label','','account-consent'),check=node('input');check.type='checkbox';check.name='newsletter';check.checked=newsletterDraft;check.onchange=()=>{newsletterDraft=check.checked;say(check.checked?'Entre ou crie sua conta e confirme seu e-mail para receber novidades.':'Você não será inscrito na newsletter.');};label.append(check,document.createTextNode('Quero receber novidades por e-mail. Opcional; preciso entrar na conta e confirmar meu e-mail.'));
diff --git a/public/js/data/character-palm-fits.js b/public/js/data/character-palm-fits.js
new file mode 100644
index 0000000000..87ebae85a0
--- /dev/null
+++ b/public/js/data/character-palm-fits.js
@@ -0,0 +1,41 @@
+export const CHARACTER_PALM_FITS = {
+ "chupa-cabra": {
+ "modelSha256": "d5f6ac0609129d88f84771ec42b579a34bd66e7d01aba9082fb89a7ffa18ae6a",
+ "skinSha256": "16eebfb7326a3b18d95cb64ea13e7750202a1e41b3e0b8d9dd0818d1f4d8f804",
+ "mesh": "Body",
+ "right": {
+ "vertices": [
+ 1215,
+ 1175,
+ 1180
+ ],
+ "barycentric": [
+ 0.4671620495143709,
+ 0.4594545024719787,
+ 0.07338344801365038
+ ]
+ },
+ "left": {
+ "vertices": [
+ 6321,
+ 6218,
+ 6216
+ ],
+ "barycentric": [
+ 0.06585153033896651,
+ 0.3802182721483085,
+ 0.553930197512725
+ ]
+ },
+ "offset": [
+ -0.04,
+ -0.15,
+ -0.04
+ ],
+ "previewOffset": [-0.04, -0.25, -0.04],
+ "gunOffset": [0, 0.04, 0.08],
+ "previewCarry": [-25, 50],
+ "previewSupportProbe": [0.005, -1, 0.1946],
+ "previewTurn": 1.5707963267948966
+ }
+};
diff --git a/public/js/data/fp-maos.js b/public/js/data/fp-maos.js
new file mode 100644
index 0000000000..7d6c9acc67
--- /dev/null
+++ b/public/js/data/fp-maos.js
@@ -0,0 +1,4 @@
+/* Corpos fora do humano não cabem no rig de mãos compartilhado de `buildFPArms` (#1119).
+ Para eles o `?hands=1` cai no só-arma em vez de pendurar uma mão grande e solta. */
+export const SEM_MAOS_FP = Object.freeze(['lobisomem']);
+export const maosFpSuportadas = (id) => !SEM_MAOS_FP.includes(id);
diff --git a/public/js/game.js b/public/js/game.js
index b424a5a3fe..6dbb2a174c 100644
--- a/public/js/game.js
+++ b/public/js/game.js
@@ -13,6 +13,7 @@ import { buildCharacter, poseCharacter, byId, CHARACTERS, buildRifle, charWeapon
import { buildCharacterModel, hasModel, preloadCharacterAssets, setEmoteDriver, getGloveHandle, GloveManifestUnavailable } from './glbchars.js';
import { weaponModel, weaponCFG, hasWeapon, preloadWeapons, ONE_HANDED, WEAPON_IDS, PISTOLS, gripPoints } from './weapons.js';
import { buildFPArms, poseToWeapon, FP_OFF } from './fparms.js';
+import { maosFpSuportadas } from './data/fp-maos.js';
import { gloveSkinStyle } from './data/glove-skin-definitions.js';
import { EMOTES_ENABLED } from './emote-features.js';
import { VM_FRAME } from './vmattach.js';
@@ -1957,7 +1958,7 @@ export class Game {
const _qsHands = new URLSearchParams(location.search).get('hands');
// SÓ-ARMA por padrão, estilo UNREAL TOURNAMENT. Skins usam as mãos do viewmodel
// autorado; o legado conserva as mãos procedurais apenas como fallback de carga.
- const WEAPON_ONLY = _qsHands !== '1';
+ const WEAPON_ONLY = _qsHands !== '1' || !maosFpSuportadas(this.playerCharId);
if (!FP_OFF && !WEAPON_ONLY) arms = buildFPArms({ id: this.playerCharId, team: this.playerFaction });
if (arms) {
root.add(arms.group);
@@ -3404,9 +3405,10 @@ export class Game {
this.el.matchEnd.classList.toggle('lose', !mine && !draw);
this.el.matchEnd.classList.toggle('draw', draw);
this.el.matchTitle.textContent = draw ? tr('EMPATE') : mine ? tr('VITÓRIA') : tr('DERROTA');
- this.el.matchSub.textContent = draw ? 'As equipes terminaram empatadas.' : mine
+ const fimDoObjetivo = this.objective?.fraseDoFim?.(winner);
+ this.el.matchSub.textContent = (fimDoObjetivo ? `${fimDoObjetivo} · ` : '') + (draw ? 'As equipes terminaram empatadas.' : mine
? frase('venceu', this._teamName(winner))
- : frase('perdeu', this._teamName(winner));
+ : frase('perdeu', this._teamName(winner)));
this.el.matchStats.innerHTML = escort
? frase('statsFim', this.roundsWon.E, this.roundsWon.B, this.player.kills, this.player.name, this.player.deaths)
: timesTerritorio
@@ -7083,14 +7085,17 @@ export class Game {
const shoulder = this.camView === 'shoulder';
const ads = p.scoped ? Math.min(1, (this._tpAdsF || 0) + dt / 0.11) : Math.max(0, (this._tpAdsF || 0) - dt / 0.11);
this._tpAdsF = ads;
+ // Abre o enquadramento do Reborn vivo sem alterar a câmera de morte nem a mira estabilizada.
+ const rebornHip = !shoulder && p.alive && p.def?.id === 'bebe-reborn' ? 1 - ads : 0;
const orbitBlend = Math.min(1, Math.abs(this._tpOrbitYaw) / 0.45);
/* Dancando, a camera de COMBATE cola nas costas e esconde o passo: afasta e sobe
enquanto o emote roda (rampa pra nao dar solavanco). */
this._emoteCamK = (this._emoteCamK || 0) + ((this._emoteAtual ? 1 : 0) - (this._emoteCamK || 0)) * Math.min(1, dt * 5);
const danca = this._emoteCamK;
- const TP_DIST = (shoulder ? 0.85 : 1.7) + (shoulder ? 0.30 : 0.50) * ads + (shoulder ? 0.85 : 0) * orbitBlend + 1.5 * danca;
- const TP_UP = shoulder ? 0.10 : 0.18;
- const TP_SIDE = (shoulder ? 0.34 : 0.28) + (shoulder ? 0.16 : 0.22) * ads;
+ const TP_DIST = (shoulder ? 0.85 : 1.7) + 0.35 * rebornHip
+ + (shoulder ? 0.30 : 0.50) * ads + (shoulder ? 0.85 : 0) * orbitBlend + 1.5 * danca;
+ const TP_UP = shoulder ? 0.10 : 0.18 - 0.14 * rebornHip;
+ const TP_SIDE = (shoulder ? 0.34 : 0.28 - 0.06 * rebornHip) + (shoulder ? 0.16 : 0.22) * ads;
const eyePos = this._tpEyePos || (this._tpEyePos = new THREE.Vector3());
if (anchor) eyePos.copy(anchor);
else eyePos.set(p.pos.x, p.pos.y + eye, p.pos.z);
@@ -10125,7 +10130,7 @@ export class Game {
}
/* ================= main update ================= */
- update(dt, render = true) {
+ update(dt, render = true, dtObjetivo = dt) {
/* Descartado continua em `game` durante o preload do próximo ("jogar de novo"), e o rAF
segue chamando: sem esta saída o puffFx já nulo derrubava o loop (#1407/#1408). */
if (this.paused || this._disposed) return;
@@ -10151,7 +10156,7 @@ export class Game {
CTF"). Antes DISSO, o CAPTURA não fechava partida nenhuma. As duas coisas estão
cobradas agora pela UI4, cada uma com a sua mutação. */
if (this.objective) {
- this.objective.update(dt);
+ this.objective.update(dt, dtObjetivo);
if (this.world.mode === 'escort' && this.state === 'live') {
this.timeLeft -= dt;
if (this.timeLeft <= 0) this._endRound(this.objective.state?.winner || 'E');
diff --git a/public/js/glbchars.js b/public/js/glbchars.js
index f13df82d27..e1cf1c387c 100644
--- a/public/js/glbchars.js
+++ b/public/js/glbchars.js
@@ -28,6 +28,7 @@ import { marcarRef, refsDoCorpo, REFS_PADRAO } from './anim-speed-ref.js';
import { CHARACTER_RELEASES, STUDIO_CHARACTER_STATES, characterRelease } from './data/content-releases.js';
import { resolveStudioCharacter, StudioCharacterError } from './studio-character.js';
import { studioSkeletonMismatch } from './studio-skeleton.js';
+import { CHARACTER_PALM_FITS } from './data/character-palm-fits.js';
// Character ids that have a real model under public/models/characters/.glb.
export const GLB_CHARS = new Set([
@@ -223,6 +224,7 @@ const TINT_3P = {
};
let _clips = null; // { idle: AnimationClip, ... } shared fallback
+let _sharedClipsRequest;
const _clipsByChar = {}; // id -> per-character retargeted clip set (fallback to _clips)
const _extraClips = {};
const _upperClips = new Map();
@@ -785,41 +787,9 @@ const torsoRadiusAt = (prof, y) => {
// Release do Studio é tudo ou nada: falha rejeita esta chamada depois que os outros ids
// assentam (StudioCharacterError, ou AggregateError para vários).
export async function preloadCharacterAssets(ids, opts = {}) {
- /* Armas FORA do bootstrap de clipes: a 1ª chamada é a da tela de carregamento, e prender as
- armas ao `if (!_clips)` fazia a partida herdar a lista errada (ou as 26). Idempotente. */
- const armas = preloadWeapons(opts.weapons);
- if (!_clips) {
- _clips = {};
- await Promise.all([
- armas,
- // Pack compartilhado em 1 GLB MESCLADO (tools/merge-anims.mjs): os 11 requests de
- // clipe viram 1. O THREE amarra o clipe no esqueleto pelo NOME do osso, então
- // basta ler as animações nomeadas. Se o mesclado faltar (deploy velho, ?animdir=
- // experimental), o per-estado de sempre cobre o que faltou.
- (async () => {
- try {
- const g = await loadGLB(assetUrl(`${ANIM_DIR}.glb`));
- for (const c of g.animations) _clips[c.name] = c;
- } catch (e) { /* fallback: per-estado abaixo */ }
- await Promise.all([
- ...STATES.filter((s) => !_clips[s]).map(async (s) => {
- try {
- const g = await loadGLB(assetUrl(`${ANIM_DIR}/${s}.glb`));
- if (g.animations[0]) { g.animations[0].name = s; _clips[s] = g.animations[0]; }
- } catch (e) { console.warn('anim load failed', s, e); }
- }),
- // Opcionais (idle/walk de 1 mão p/ pistolas): ausência NÃO é erro — sem warn.
- ...OPT_STATES.filter((s) => !_clips[s]).map(async (s) => {
- try {
- const g = await loadGLB(assetUrl(`${ANIM_DIR}/${s}.glb`));
- if (g.animations[0]) { g.animations[0].name = s; _clips[s] = g.animations[0]; }
- } catch (e) { /* fallback: idle/walk de 2 mãos */ }
- }),
- ]);
- })(),
- ]);
- } else await armas;
- const wanted = [...new Set(ids)].filter((id) => GLB_CHARS.has(id) && !_base.has(id));
+ const armas = opts.weapons?.length === 0 ? null : preloadWeapons(opts.weapons);
+ await Promise.all([armas, _sharedClipsRequest ??= preloadSharedClips()]);
+ const wanted = [...new Set(ids)].filter(id => GLB_CHARS.has(id) && !_base.has(id));
const studioFailures = [];
await Promise.all(wanted.map(async (id) => {
const release = characterRelease(id);
@@ -828,17 +798,35 @@ export async function preloadCharacterAssets(ids, opts = {}) {
catch (e) { console.error(`[studio] ${id}@${release.version}: ${e?.code || 'studio_load_failed'}`, e); studioFailures.push(e); }
return;
}
+ await preloadLegacyCharacter(id);
+ }));
+ if (studioFailures.length === 1) throw studioFailures[0];
+ if (studioFailures.length) throw new AggregateError(studioFailures, 'studio_character_preload_failed');
+}
+
+async function preloadSharedClips() {
+ _clips = {};
+ try {
+ const g = await loadGLB(assetUrl(`${ANIM_DIR}.glb`));
+ for (const c of g.animations) _clips[c.name] = c;
+ } catch { /* fallback: per-estado */ }
+ await Promise.all([...STATES, ...OPT_STATES].filter(s => !_clips[s]).map(async s => {
try {
- const path = `models/characters/${id}.glb`;
- const origin = Object.freeze({ kind: 'base', character: id, path: `public/${path}`, revision: revDe(path) });
- const g = await loadGLB(assetUrl(path));
- _bodyOrigins.set(g.scene, origin);
- _base.set(id, g.scene);
- } catch (e) { console.warn('model load failed', id, e); }
- // Clipes retargetados POR PERSONAGEM (models/anims//): cada rig do Meshy tem
- // proporção de esqueleto diferente, então o pack único (assado contra 1 referência)
- // deformava quem divergia (doutora agachada, dollynho dobrado). Aqui cada char usa
- // seus próprios clipes; qualquer estado ausente cai no pack compartilhado (_clips).
+ const g = await loadGLB(assetUrl(`${ANIM_DIR}/${s}.glb`));
+ if (g.animations[0]) { g.animations[0].name = s; _clips[s] = g.animations[0]; }
+ } catch (e) { if (STATES.includes(s)) console.warn('anim load failed', s, e); }
+ }));
+}
+
+const _legacyRequests = new Map();
+function preloadLegacyCharacter(id) {
+ const pending = _legacyRequests.get(id);
+ if (pending) return pending;
+ const request = (async () => {
+ const path = `models/characters/${id}.glb`;
+ let body;
+ try { body = (await loadGLB(assetUrl(path))).scene; }
+ catch (e) { console.warn('model load failed', id, e); }
const set = { ..._clips };
// GUARDA DE DISPONIBILIDADE — ver o comentário do animIndex(). `disponiveis === null`
// (manifesto ausente ou fetch falhou) mantém o comportamento antigo: pede tudo.
@@ -867,9 +855,13 @@ export async function preloadCharacterAssets(ids, opts = {}) {
} catch (e) { /* fallback: clipe compartilhado */ }
}));
_clipsByChar[id] = set;
- }));
- if (studioFailures.length === 1) throw studioFailures[0];
- if (studioFailures.length) throw new AggregateError(studioFailures, 'studio_character_preload_failed');
+ if (body) {
+ _bodyOrigins.set(body, Object.freeze({ kind: 'base', character: id, path: `public/${path}`, revision: revDe(path) }));
+ _base.set(id, body);
+ }
+ })().finally(() => _legacyRequests.delete(id));
+ _legacyRequests.set(id, request);
+ return request;
}
/* Modelo e 11 clipes só das Blob URLs verificadas (sem animIndex, mesclado ou compartilhado);
@@ -915,6 +907,15 @@ const _gq = new THREE.Quaternion(), _wq = new THREE.Quaternion(), _pq = new THRE
const _qLean = new THREE.Quaternion(), _axisF = new THREE.Vector3();
const _right = new THREE.Vector3();
const _ikTgt = new THREE.Vector3(), _ancoraPalma = new THREE.Vector3();
+const _palmPoint = new THREE.Vector3(), _palmVertex = new THREE.Vector3();
+function palmSurface(mesh, landmark, target) {
+ target.set(0, 0, 0);
+ for (let i = 0; i < 3; i++) {
+ mesh.getVertexPosition(landmark.vertices[i], _palmVertex).applyMatrix4(mesh.matrixWorld);
+ target.addScaledVector(_palmVertex, landmark.barycentric[i]);
+ }
+ return target;
+}
function orientTpMount(t) {
t.handBone.updateWorldMatrix(true, false);
t.model.getWorldQuaternion(_gq);
@@ -1080,6 +1081,7 @@ export function buildCharacterModel(def, opts = {}) {
// Skins assam contato no próprio clipe; offsets da base têm outro rig.
const ctrl = new CharController(mixer, actions, group, headBone, head, skin ? def.skinId : def.id, model, def.id);
+ ctrl.previewWalkfire = opts.preview === true;
ctrl.shadow = shadow; // antes do settle loop abaixo (ctrl.update já a atualiza)
// Arma de 1 mão (pistol/deagle/revolver38/knife): usa idle1h/walk1h quando carregados.
ctrl.oneHanded = !!(opts.weaponId && ONE_HANDED.has(opts.weaponId));
@@ -1336,6 +1338,22 @@ export function buildCharacterModel(def, opts = {}) {
ctrl.tpMount.pegadaAtiva = true;
orientTpMount(ctrl.tpMount);
}
+ const palmFit = !skin && opts.weaponId === 'ak' && CHARACTER_PALM_FITS[def.id];
+ if (palmFit && bodyOrigin?.sha256 === palmFit.modelSha256 && ctrl.tpMount && ctrl.ikL) {
+ let mesh = null;
+ model.traverse(o => { if (o.isSkinnedMesh && o.name === palmFit.mesh) mesh = o; });
+ if (mesh && [...palmFit.right.vertices, ...palmFit.left.vertices].every(i => i < mesh.geometry.attributes.position.count)) {
+ const ik = ctrl.ikL, gunScale = ik.gun.scale.x || 1;
+ ik.gun.updateWorldMatrix(true, true);
+ const probe = new THREE.Vector3().fromArray(palmFit.previewSupportProbe).divideScalar(gunScale);
+ const ray = new THREE.Raycaster(ik.gun.localToWorld(probe), new THREE.Vector3(0, 1, 0).transformDirection(ik.gun.matrixWorld));
+ const hit = ray.intersectObject(ik.gun, true)[0];
+ const previewSupport = hit ? ik.gun.worldToLocal(hit.point.clone()) : null;
+ ctrl.palmFit = { ...palmFit, mesh, previewSupport, mountOffset: ctrl.tpMount.palmLocal.clone(), supportOffset: ik.endOffset.clone(),
+ supportFore: ik.fore.clone(), gunOrigin: ik.gun.position.clone(), carry: ctrl.tpMount.carry.clone(),
+ previewGrip: ctrl.tpMount.pegada?.clone(), active: false };
+ }
+ }
return { group, parts: { head }, isGLB: true, mixer, ctrl, skinId: skin ? def.skinId : null, gloveHandle,
setGloveSkin(id) {
const removed = gloveMeshes;
@@ -1363,6 +1381,7 @@ export function setEmoteDriver(api) { _emoteDriver = (api && api.pose) ? api : n
export function temEmoteDriver() { return !!_emoteDriver; }
const FADE = 0.16;
+const SHOOT_FADE = 0.06;
class CharController {
constructor(mixer, actions, group, headBone, head, charId, model, bodyId = charId) {
@@ -1376,6 +1395,7 @@ class CharController {
// Ref por clipe × escala do modelo (anim-speed-ref.js); clipe sem ref usa a global.
this.refs = refsDoCorpo(actions, model ? model.scale.x : 0, REFS_GLOBAIS);
this.cur = null; this.dead = false; this.shooting = false; this.crouch = false; this.jumping = false;
+ this._legsMoving = false; this._movingShot = false; this.previewWalkfire = false;
this._reloadT = 0; this._reloadDur = 0; this.reloadK = 0; this._leanK = 0; this._porte1hK = 0;
this._flinchT = 0; this._flinchDur = 0; this._flinchDir = null; this._fireT = 0; this._fireDur = 0;
this._drawT = 0; this._drawBone = null; this._drawBase = new THREE.Quaternion();
@@ -1396,7 +1416,7 @@ class CharController {
this._loco = 'idle'; // current locomotion state (hysteresis memory for walk/run choice)
for (const name of EXTRA_STATES) if (_extraClips[name]) actions[name] = mixer.clipAction(_extraClips[name]);
mixer.addEventListener('finished', (e) => {
- if (e.action === actions.shoot) this.shooting = false;
+ if (e.action === actions.shoot && this.cur === e.action) this.shooting = false;
if (e.action === actions.jump) this.jumping = false;
});
this._to('idle');
@@ -1525,14 +1545,14 @@ class CharController {
if (!this._setLocoPar(nomes[setor], nomes[(setor + 1) % 4], mix)) this._to(base);
}
- _to(name, once = false, restart = true) {
+ _to(name, once = false, restart = true, fade = FADE) {
const a = this.actions[name];
if (!a || (this.cur === a && !this._locoA && !this._locoB)) return;
// Sair do par 8-way para um clipe que já toca nele (fallback sem strafe, LOD≥2) segue a
// fase: reiniciar ali congelava o ciclo de pernas a cada troca de setor.
const herda = !once && (a === this._locoA || a === this._locoB) && a.isRunning();
- if (this._locoA && this._locoA !== a) this._locoA.fadeOut(FADE);
- if (this._locoB && this._locoB !== a) this._locoB.fadeOut(FADE);
+ if (this._locoA && this._locoA !== a) this._locoA.fadeOut(fade);
+ if (this._locoB && this._locoB !== a) this._locoB.fadeOut(fade);
this._locoA = null; this._locoB = null; this._locoAName = null; this._locoBName = null; this._locoMix = 0;
if (a !== this.actions.jump) this.jumping = false;
// O par escreve `weight` (1−mix / mix): sem devolver 1, o clipe voltava com o peso velho
@@ -1544,9 +1564,9 @@ class CharController {
a.setLoop(once ? THREE.LoopOnce : THREE.LoopRepeat, once ? 1 : Infinity);
a.clampWhenFinished = once;
}
- a.enabled = true; a.fadeIn(FADE); a.play();
+ a.enabled = true; a.fadeIn(fade); a.play();
}
- if (this.cur && this.cur !== a) this.cur.fadeOut(FADE);
+ if (this.cur && this.cur !== a) this.cur.fadeOut(fade);
this.cur = a;
this.curName = name; // nome do estado atual — o clamp de frente do mount lê daqui
// pé no chão: o offset do clipe que ENTRA (ver footOffset)
@@ -1714,20 +1734,26 @@ class CharController {
// Agachado não troca de clipe (a pose já mira), mas ganha recuo aditivo: antes o
// bot agachado atirava completamente imóvel. Ver docs/ANIM-3P.md.
if (this.crouch || !this.actions.shoot) { this._fireDur = 0.12; this._fireT = 0; return; }
+ const shot = this.actions.shoot;
+ this.shooting = true;
+ this._shootUntil = this.mixer.time + shot.getClip().duration;
+ shot.setLoop(THREE.LoopOnce, 1);
+ shot.clampWhenFinished = true;
+ this._movingShot = this._legsMoving && !this.previewWalkfire;
+ if (this._movingShot) {
+ this._fireDur = 0.12; this._fireT = 0;
+ return;
+ }
this.jumping = false;
- if (this._locoA) this._locoA.fadeOut(0.06);
- if (this._locoB) this._locoB.fadeOut(0.06);
+ if (this._locoA) this._locoA.fadeOut(SHOOT_FADE);
+ if (this._locoB) this._locoB.fadeOut(SHOOT_FADE);
this._locoA = null; this._locoB = null; this._locoAName = null; this._locoBName = null; this._locoMix = 0;
- this.shooting = true;
this.curName = 'shoot';
- this._shootUntil = this.mixer.time + this.actions.shoot.getClip().duration;
- if (this.cur === this.actions.shoot) { this.cur.time = 0; this.cur.paused = false; return; }
- this.actions.shoot.reset();
- this.actions.shoot.setLoop(THREE.LoopOnce, 1);
- this.actions.shoot.clampWhenFinished = true;
- this.actions.shoot.enabled = true; this.actions.shoot.fadeIn(0.06).play();
- if (this.cur && this.cur !== this.actions.shoot) this.cur.fadeOut(0.06);
- this.cur = this.actions.shoot;
+ if (this.cur === shot) { shot.time = 0; shot.paused = false; return; }
+ shot.reset();
+ shot.enabled = true; shot.fadeIn(SHOOT_FADE).play();
+ if (this.cur && this.cur !== shot) this.cur.fadeOut(SHOOT_FADE);
+ this.cur = shot;
}
die(dir = null) {
@@ -1749,6 +1775,8 @@ class CharController {
this._stopUpper(); this._ceremonyPending = null; this._drawPending = false; this._drawRequested = false; this._grenadePending = null;
this._drawT = 0;
this._flinchDur = 0;
+ this._fireDur = this._fireT = 0;
+ this._legsMoving = this._movingShot = false;
this._leanK = 0;
this.aimPitch = 0;
this._to('death', true);
@@ -1781,7 +1809,20 @@ class CharController {
// picks the locomotion state, and scales the leg-cycle rate to the actual ground speed
// so the feet plant instead of ice-skating (root-motion-free clips have no built-in
// stride, so we drive the cycle rate from how fast the body is really moving).
+ _guardarTpPose(bone) {
+ if (!bone) return;
+ if (!this._tpFrontPose) this._tpFrontPose = [];
+ if (!this._tpFrontPosePool) this._tpFrontPosePool = [];
+ let entry = null;
+ for (const saved of this._tpFrontPosePool) if (saved[0] === bone) { entry = saved; break; }
+ if (!entry) { entry = [bone, new THREE.Quaternion()]; this._tpFrontPosePool.push(entry); }
+ if (this._tpFrontPose.includes(entry)) return;
+ entry[1].copy(bone === this._drawBone ? this._drawBase : bone.quaternion);
+ this._tpFrontPose.push(entry);
+ }
+
update(dt, moving, hasTarget, speed = 0, back = false, lateral = 0) {
+ this._legsMoving = moving > 0.05;
this._restaurarPoseMorte();
if (this._drawBone) { this._drawBone.quaternion.copy(this._drawBase); this._drawBone = null; }
this._drawT = Math.max(0, this._drawT - dt);
@@ -1790,7 +1831,7 @@ class CharController {
if (freeHand?.applied) { freeHand.bone.quaternion.copy(freeHand.before); freeHand.applied = false; }
this._tickUpper(dt);
if (!this.dead) {
- if (this.shooting && this.mixer.time >= (this._shootUntil || 0)) this.shooting = false;
+ if (this.shooting && this.mixer.time >= (this._shootUntil || 0)) this.shooting = this._movingShot = false;
if (/^(victory|defeat)$/.test(this.curName || '')) {
// A cerimônia segura o corpo inteiro até a próxima rodada.
} else if (this._mantleF !== null && this.actions.jump) {
@@ -1806,15 +1847,16 @@ class CharController {
else this._tocarEmoteClipe();
} else if (this.crouch) {
this._to(moving > 0.05 ? 'crouchwalk' : 'crouch');
- } else if (this.shooting && moving > 0.05 && this.actions.walkfire) {
- // Atirar EM MOVIMENTO: o clipe combinado (walk+fire) mantém as pernas andando —
- // antes as pernas congelavam ~1s a cada disparo (usuário reprovou).
+ } else if (this.previewWalkfire && this.shooting && this._legsMoving && this.actions.walkfire) {
this._to('walkfire');
- } else if (this.shooting && moving <= 0.05
- && this.cur === this.actions.walkfire && this.actions.shoot) {
+ } else if (this.shooting && !this._legsMoving
+ && (this._movingShot || this.cur === this.actions.walkfire) && this.actions.shoot) {
+ const fade = this._movingShot ? SHOOT_FADE : FADE;
+ this._movingShot = false;
+ this._fireDur = this._fireT = 0;
this.actions.shoot.time = this.actions.shoot.getClip().duration - (this._shootUntil - this.mixer.time);
this.actions.shoot.paused = false;
- this._to('shoot', true, false);
+ this._to('shoot', true, false, fade);
} else if (this._ar && this.actions.jump) {
if (this.cur !== this.actions.jump) { this._to('jump'); this.jumping = false; }
const jump = this.actions.jump;
@@ -1823,7 +1865,7 @@ class CharController {
} else if (this._landT > 0 && this.actions.crouch) {
this._landT = Math.max(0, this._landT - dt);
this._to('crouch');
- } else if (!this.shooting && !this.jumping) {
+ } else if ((!this.shooting || (this._legsMoving && !this.previewWalkfire)) && !this.jumping) {
const usaClipe1h = this.oneHanded && !P1H_BASE_CLIP.has(this.bodyId);
if (moving <= 0.05) {
if (this.weaponId === 'knife' && this.lod < 2) this._requestExtras();
@@ -1832,6 +1874,10 @@ class CharController {
if (this.weaponId === 'knife' && this.lod < 2 && this.actions.knife_idle && !this._upperName) this._playUpper('knife_idle', 0, true);
this._loco = 'idle';
} else {
+ if (this.shooting && !this._movingShot) {
+ this._movingShot = true;
+ this._fireDur = 0.12; this._fireT = 0;
+ }
if (this._upperName === 'knife_idle') this._stopUpper();
if (this._loco !== 'run' && speed > 1.45) this._loco = 'run';
else if (this._loco !== 'walk' && speed < 1.15) this._loco = 'walk';
@@ -1854,6 +1900,11 @@ class CharController {
if (this.actions.walk_back_pistol) this.actions.walk_back_pistol.timeScale = rate(1.16);
if (this.actions.run_back) this.actions.run_back.timeScale = rate(3.826);
}
+ if (this._tpFrontPoseAtiva) {
+ for (const [bone, pose] of this._tpFrontPose) bone.quaternion.copy(pose);
+ this._tpFrontPoseAtiva = false;
+ }
+ if (this._tpFrontPose) this._tpFrontPose.length = 0;
this.mixer.update(dt);
// Emote de captura tocando: o clipe manda no corpo, então mira/coluna não o torcem.
const clipeEmote = this._emoteClipeInfo ? this.actions[`emote_${this._emoteClipeInfo.id}`] : null;
@@ -1914,6 +1965,20 @@ class CharController {
}
for (const n of this._armaNos) n.visible = !this.emotando;
}
+ if (this.palmFit?.active && (this.dead || this.emotando || this.curName !== 'idle' || this.weaponId !== 'ak' || this.lod >= 1 || this._upperName || this._drawT > 0)) {
+ const t = this.tpMount;
+ t.palmLocal.copy(this.palmFit.mountOffset);
+ t.mount.position.copy(t.palmLocal);
+ this.ikL.endOffset.copy(this.palmFit.supportOffset);
+ this.ikL.fore.copy(this.palmFit.supportFore);
+ this.ikL.gun.position.copy(this.palmFit.gunOrigin);
+ t.carry.copy(this.palmFit.carry);
+ if (this.palmFit.previewGrip) {
+ t.pegada.copy(this.palmFit.previewGrip);
+ t.pegadaInv.copy(t.pegada).invert();
+ }
+ this.palmFit.active = false;
+ }
if (this.tpMount && !this.dead && !this.emotando) {
const t = this.tpMount;
if (t.pegada) t.pegadaAtiva = /^(idle|idle1h|crouch|knife_idle)$/.test(this.curName || '');
@@ -1938,13 +2003,41 @@ class CharController {
t.handBone.localToWorld(_v);
t.model.worldToLocal(_v);
if (_v.z < TP_FRONT_MIN) {
+ this._guardarTpPose(t.rArm);
+ this._guardarTpPose(t.rFore);
_v.z = TP_FRONT_MIN;
t.model.localToWorld(_v);
solveCCDIK([t.rArm, t.rFore], t.handBone, _v, { iterations: 6, endOffset: t.palmLocal });
+ this._tpFrontPoseAtiva = this._tpFrontPose.some(([bone, pose]) => !bone.quaternion.equals(pose));
orientTpMount(t); // reorienta o cano pós-IK
}
}
}
+ if (this.palmFit && this.curName === 'idle' && this.weaponId === 'ak' && this.lod < 1 && !this.dead && !this.emotando && !this._upperName && this._drawT <= 0 && this.tpMount?.rArm && this.tpMount?.rFore) {
+ const fit = this.palmFit, t = this.tpMount;
+ if (!fit.active) {
+ if (fit.previewSupport) this.ikL.fore.copy(fit.previewSupport);
+ if (this.previewWalkfire && fit.previewSupport) {
+ t.carry.setFromEuler(new THREE.Euler(fit.previewCarry[0] * Math.PI / 180, fit.previewCarry[1] * Math.PI / 180, 0, 'YXZ'));
+ }
+ this.ikL.gun.position.copy(fit.gunOrigin).add(_v.fromArray(fit.gunOffset));
+ if (fit.previewGrip) {
+ t.pegada.copy(fit.previewGrip).multiply(_qLean.setFromAxisAngle(_axisF.set(0, 0, 1), fit.previewTurn));
+ t.pegadaInv.copy(t.pegada).invert();
+ orientTpMount(t);
+ }
+ }
+ this.group.updateMatrixWorld(true);
+ t.palmLocal.copy(t.handBone.worldToLocal(palmSurface(fit.mesh, fit.right, _palmPoint)));
+ t.mount.position.copy(t.palmLocal);
+ t.handBone.localToWorld(_palmPoint.copy(t.palmLocal));
+ t.model.getWorldQuaternion(_gq);
+ _v.fromArray(this.previewWalkfire ? fit.previewOffset : fit.offset).applyQuaternion(_gq);
+ _palmPoint.add(_v);
+ solveCCDIK([t.rArm, t.rFore], t.handBone, _palmPoint, { iterations: 20, endOffset: t.palmLocal });
+ orientTpMount(t);
+ fit.active = true;
+ }
const drawArm = this._drawT > 0 && !this.dead && this.lod < 1 && !this.emotando && this.corpo?.get('RightArm');
if (drawArm?.parent) {
this._drawBone = drawArm;
@@ -1959,10 +2052,13 @@ class CharController {
// Roda depois do mixer/pose — corrige o contato por arma sem tocar na orientação.
if (this.ikL && !this.dead && this.lod < 1 && !this.emotando && !this._upperName) {
const ik = this.ikL;
+ if (this.palmFit?.active) {
+ ik.endOffset.copy(ik.end.worldToLocal(palmSurface(this.palmFit.mesh, this.palmFit.left, _palmPoint)));
+ }
ik.gun.updateWorldMatrix(true, false);
_ikTgt.copy(ik.fore);
ik.gun.localToWorld(_ikTgt);
- solveCCDIK(ik.chain, ik.end, _ikTgt, { iterations: 8, endOffset: ik.endOffset });
+ solveCCDIK(ik.chain, ik.end, _ikTgt, { iterations: this.palmFit?.active ? 20 : 8, endOffset: ik.endOffset });
}
/* Overlays de tronco por ÚLTIMO; eixo em MUNDO via quadro do pai e undo antes do
mixer. As duas armadilhas estão contadas em docs/ANIM-3P.md. */
@@ -2066,12 +2162,17 @@ class CharController {
if (this._porte1hK > 0.004 && this.reloadK <= 0.05 && (!this._upperName || this._upperName === 'knife_idle') && this.corpo?.size) {
const k1 = this._porte1hK;
const rArm = this.corpo.get('RightArm'), rFore = this.corpo.get('RightForeArm');
+ this._guardarTpPose(rArm);
+ this._guardarTpPose(rFore);
+ this._tpFrontPoseAtiva = !!this._tpFrontPose?.length;
if (rArm) _deltaMundo(rArm, cosY, 0, -sinY, (canarinho1h ? CANARINHO_P1H_ARM : P1H_ARM) * k1);
if (rFore) _deltaMundo(rFore, cosY, 0, -sinY, (canarinho1h ? CANARINHO_P1H_FORE : P1H_FORE) * k1);
/* Mascote de braço-toco (IK_L_SKIP) fica de fora: IK neles vira mão gigante
flutuando, a mesma razão por que o guarda-mão de 2 mãos já os pula. */
if (torso.lArm && torso.lFore && torso.lHand && torso.hips && this.model
&& !IK_L_SKIP.has(this.bodyId)) {
+ this._guardarTpPose(torso.lArm);
+ this._guardarTpPose(torso.lFore);
_ikTgt.copy(torso.hips.getWorldPosition(_ikTgt));
this.model.worldToLocal(_ikTgt);
_ikTgt.set(_ikTgt.x + P1H_MAO_L[0], _ikTgt.y + P1H_MAO_L[1], _ikTgt.z + P1H_MAO_L[2]);
@@ -2116,7 +2217,7 @@ class CharController {
_deltaMundo(torso.spines[0], -d.z / n, 0, d.x / n, fk * 0.26);
if (torso.spines[1]) _deltaMundo(torso.spines[1], -d.z / n, 0, d.x / n, fk * 0.13);
}
- // RECUO AGACHADO: tiro agachado não troca de clipe, então o recuo é aditivo.
+ // Recuo aditivo: atirar andando ou agachado não toma o clipe das pernas.
if (this._fireDur > 0) {
this._fireT += dt;
if (this._fireT >= this._fireDur) { this._fireDur = 0; this._fireT = 0; }
diff --git a/public/js/hd_cenografia_sertao.js b/public/js/hd_cenografia_sertao.js
new file mode 100644
index 0000000000..b3ec43525b
--- /dev/null
+++ b/public/js/hd_cenografia_sertao.js
@@ -0,0 +1,895 @@
+// Cenografia HD do Sertão (demo ?hd=1). Nada aqui tem colisão: só existe fora de bounds, rente ao chão
+// (até 12 cm), em cima ou colado em colisor que já existe, ou acima de 2,2 m. Tudo sai por desfaz(); `opts.bordas=false` omite a vegetação de borda.
+import * as THREE from 'three';
+import { mergeVertices } from 'three/addons/utils/BufferGeometryUtils.js';
+import { placeProp } from './mapprops.js';
+import { mandacaruSertao } from './map_sertao_flora.js';
+
+const rngDe = (semente) => { let s = semente >>> 0; return () => { s = (s + 0x6D2B79F5) >>> 0; let t = Math.imul(s ^ (s >>> 15), 1 | s);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; };
+const suave = (a, b, x) => { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); };
+// Mesma fórmula de sertaoLandscape (map_sertao_landscape.js): se o relevo de lá mudar, isto flutua.
+const terreno = (x, z) => { const t = Math.min(1, Math.max(0, (Math.max(Math.abs(x) / 65, Math.abs(z) / 85) - 1) / 1.6));
+ return t * t * (3 - 2 * t) * (12 + 7 * Math.sin(x * .018) * Math.cos(z * .021) + 3 * Math.sin(x * .07 + z * .045)) - .04; };
+
+function pedraGeo(detalhe, semente, forca, oito = false) {
+ const bruta = oito ? new THREE.OctahedronGeometry(1, 0) : new THREE.IcosahedronGeometry(1, detalhe); bruta.deleteAttribute('uv'); bruta.deleteAttribute('normal');
+ const g = mergeVertices(bruta, 1e-4); bruta.dispose();
+ const p = g.attributes.position, rnd = rngDe(semente), fase = [rnd() * 9, rnd() * 9, rnd() * 9];
+ for (let i = 0; i < p.count; i++) { const x = p.getX(i), y = p.getY(i), z = p.getZ(i);
+ const k = 1 + forca * (Math.sin(x * 2.3 + fase[0]) * Math.cos(y * 2.9 + fase[1]) + .5 * Math.sin(z * 5.1 + x * 3.3 + fase[2]) + .25 * Math.sin(y * 9.7 + z * 7.1));
+ p.setXYZ(i, x * k, y * k, z * k); }
+ g.computeVertexNormals(); g.computeBoundingSphere(); return g;
+}
+
+// Tufo de capim seco: lâminas afiladas em leque, base escura e ponta palha; normal para cima (não escurece o verso).
+function tufoGeo(semente, laminas = 6, { larg0 = .045, base = [.55, .48, .30], ponta = [.2, .16, .06] } = {}) {
+ const rnd = rngDe(semente), P = [], N = [], C = [], I = [];
+ for (let i = 0; i < laminas; i++) {
+ const a = rnd() * Math.PI * 2, incl = .12 + rnd() * .75, h = .55 + rnd() * .45, larg = larg0 + rnd() * larg0 * .8, r0 = rnd() * .16, giro = a + (rnd() - .5) * 1.2;
+ const dx = Math.cos(a), dz = Math.sin(a), lx = -Math.sin(giro) * larg, lz = Math.cos(giro) * larg, b = P.length / 3;
+ const ponto = (t, w) => { const fora = r0 + incl * h * t * t * 1.1 + incl * h * t * .25, y = h * t * (1 - .28 * incl * t);
+ for (const s of [-1, 1]) { P.push(dx * fora + lx * w * s, y, dz * fora + lz * w * s); N.push(dx * .35, .93, dz * .35);
+ const c = .42 + .58 * t; C.push(base[0] * c + ponta[0] * t, base[1] * c + ponta[1] * t, base[2] * c + ponta[2] * t); } };
+ ponto(0, 1); ponto(.5, .7); ponto(1, .06);
+ I.push(b, b + 1, b + 2, b + 1, b + 3, b + 2, b + 2, b + 3, b + 4);
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(N, 3));
+ g.setAttribute('color', new THREE.Float32BufferAttribute(C, 3)); g.setIndex(I); g.computeBoundingSphere(); return g;
+}
+
+// Acumulador de peças de madeira/arame numa malha só (1 draw call): UV em metros; veio longo fica no V da tábua.
+function oficina() {
+ const P = [], N = [], U = [], C = [], I = [], v = new THREE.Vector3(), n = new THREE.Vector3(), nm = new THREE.Matrix3();
+ const api = {
+ tipo: 0,
+ caixa(m, w, h, d, cor, so = null) {
+ nm.getNormalMatrix(m);
+ const faces = [[[1, 0, 0], [0, 0, -1], [0, 1, 0], d, h, w], [[-1, 0, 0], [0, 0, 1], [0, 1, 0], d, h, w], [[0, 1, 0], [1, 0, 0], [0, 0, -1], w, d, h],
+ [[0, -1, 0], [1, 0, 0], [0, 0, 1], w, d, h], [[0, 0, 1], [1, 0, 0], [0, 1, 0], w, h, d], [[0, 0, -1], [-1, 0, 0], [0, 1, 0], w, h, d]];
+ for (const [nn, tu, tv, su, sv, sn] of so ? so.map((i) => faces[i]) : faces) { const b = P.length / 3, fase = (P.length % 97) * .013;
+ for (const [a, c] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {
+ v.set(nn[0] * sn / 2 + tu[0] * a * su / 2 + tv[0] * c * sv / 2, nn[1] * sn / 2 + tu[1] * a * su / 2 + tv[1] * c * sv / 2, nn[2] * sn / 2 + tu[2] * a * su / 2 + tv[2] * c * sv / 2).applyMatrix4(m);
+ n.set(nn[0], nn[1], nn[2]).applyMatrix3(nm).normalize(); P.push(v.x, v.y, v.z); N.push(n.x, n.y, n.z); C.push(cor[0], cor[1], cor[2]);
+ const uu = a * su / 2 / 1.1 + fase, vv = c * sv / 2 / 1.1 + fase * 3; if (su >= sv) U.push(vv + api.tipo * 100, uu); else U.push(uu + api.tipo * 100, vv); }
+ I.push(b, b + 1, b + 2, b, b + 2, b + 3); }
+ },
+ // Tronco de cone entre a e b; `aneis` opcional = [[t, fatorDeRaio]] para barriga de barril.
+ cilindro(a, b, r0, r1, lados, cor, { tampas = true, aneis = null, giro = 0 } = {}) {
+ const eixo = new THREE.Vector3().subVectors(b, a), L = eixo.length(); eixo.normalize();
+ const q = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), eixo), base = P.length / 3;
+ const perfil = aneis || [[0, 1], [1, 1]];
+ perfil.forEach(([t, k], j) => { const r = (r0 + (r1 - r0) * t) * k;
+ for (let i = 0; i <= lados; i++) { const ang = i / lados * Math.PI * 2 + giro;
+ v.set(Math.cos(ang) * r, t * L, Math.sin(ang) * r).applyQuaternion(q).add(a); n.set(Math.cos(ang), 0, Math.sin(ang)).applyQuaternion(q);
+ P.push(v.x, v.y, v.z); N.push(n.x, n.y, n.z); C.push(cor[0], cor[1], cor[2]); U.push(i / lados * Math.max(.35, r * 5.7) + api.tipo * 100, t * L / 1.1); }
+ if (j) for (let i = 0; i < lados; i++) { const p0 = base + (j - 1) * (lados + 1) + i, p1 = p0 + lados + 1; I.push(p0, p1, p0 + 1, p0 + 1, p1, p1 + 1); } });
+ if (tampas) for (const [t, k, sinal] of [[1, perfil[perfil.length - 1][1], 1], [0, perfil[0][1], -1]]) { const c0 = P.length / 3, r = (r0 + (r1 - r0) * t) * k;
+ n.set(0, sinal, 0).applyQuaternion(q); v.set(0, t * L, 0).applyQuaternion(q).add(a); P.push(v.x, v.y, v.z); N.push(n.x, n.y, n.z); C.push(cor[0] * .8, cor[1] * .8, cor[2] * .8); U.push(.5 + api.tipo * 100, .5);
+ for (let i = 0; i <= lados; i++) { const ang = i / lados * Math.PI * 2 + giro; v.set(Math.cos(ang) * r, t * L, Math.sin(ang) * r).applyQuaternion(q).add(a);
+ P.push(v.x, v.y, v.z); N.push(n.x, n.y, n.z); C.push(cor[0] * .8, cor[1] * .8, cor[2] * .8); U.push(.5 + Math.cos(ang) * r / 1.1 + api.tipo * 100, .5 + Math.sin(ang) * r / 1.1); }
+ for (let i = 0; i < lados; i++) if (sinal > 0) I.push(c0, c0 + 2 + i, c0 + 1 + i); else I.push(c0, c0 + 1 + i, c0 + 2 + i); }
+ },
+ // Pano sem espessura: os dois lados na mesma malha, cada um com a sua normal.
+ tri(a, b, c, cor) { n.subVectors(b, a).cross(v.subVectors(c, a)).normalize();
+ for (const s of [1, -1]) { const b0 = P.length / 3; for (const q of (s > 0 ? [a, b, c] : [a, c, b])) { P.push(q.x, q.y, q.z); N.push(n.x * s, n.y * s, n.z * s); C.push(cor[0], cor[1], cor[2]); U.push(api.tipo * 100, 0); } I.push(b0, b0 + 1, b0 + 2); } },
+ // Polígono no plano xy de m (anti-horário, visível do ponto c) extrudado `esp` em z.
+ prisma(m, pts, esp, cor, c = [0, 0]) {
+ nm.getNormalMatrix(m); const k = pts.length, h = esp / 2;
+ for (const s of [1, -1]) { const b = P.length / 3; n.set(0, 0, s).applyMatrix3(nm).normalize();
+ for (const [x, y] of [c, ...pts]) { v.set(x, y, s * h).applyMatrix4(m); P.push(v.x, v.y, v.z); N.push(n.x, n.y, n.z); C.push(cor[0], cor[1], cor[2]); U.push(x / 1.1 + api.tipo * 100, y / 1.1); }
+ for (let i = 0; i < k; i++) { const a = b + 1 + i, d = b + 1 + (i + 1) % k; if (s > 0) I.push(b, a, d); else I.push(b, d, a); } }
+ for (let i = 0; i < k; i++) { const [x0, y0] = pts[i], [x1, y1] = pts[(i + 1) % k], L = Math.hypot(x1 - x0, y1 - y0); if (L < 1e-5) continue; const b = P.length / 3;
+ n.set((y1 - y0) / L, -(x1 - x0) / L, 0).applyMatrix3(nm).normalize();
+ for (const [x, y, z, u] of [[x0, y0, h, 0], [x1, y1, h, L], [x1, y1, -h, L], [x0, y0, -h, 0]]) { v.set(x, y, z).applyMatrix4(m); P.push(v.x, v.y, v.z); N.push(n.x, n.y, n.z); C.push(cor[0], cor[1], cor[2]); U.push(u / 1.1 + api.tipo * 100, z / 1.1); }
+ I.push(b, b + 2, b + 1, b, b + 3, b + 2); }
+ },
+ geo() { const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(N, 3));
+ g.setAttribute('uv', new THREE.Float32BufferAttribute(U, 2)); g.setAttribute('color', new THREE.Float32BufferAttribute(C, 3));
+ g.setIndex(I); if (I.length) g.computeBoundingSphere(); return g; },
+ };
+ return api;
+}
+
+// Quatro oficinas, uma por quadrante do mapa: cada malha tem a sua esfera e sai do quadro com o frustum.
+function oficinas() {
+ const q = [oficina(), oficina(), oficina(), oficina()], de = (x, z) => q[(x < 0 ? 0 : 1) + (z < 0 ? 0 : 2)];
+ return { caixa: (m, ...r) => de(m.elements[12], m.elements[14]).caixa(m, ...r), cilindro: (a, ...r) => de(a.x, a.z).cilindro(a, ...r), tri: (a, ...r) => de(a.x, a.z).tri(a, ...r), prisma: (m, ...r) => de(m.elements[12], m.elements[14]).prisma(m, ...r), tipo: (t) => { for (const o of q) o.tipo = t; }, geos: () => q.map((o) => o.geo()) };
+}
+
+export function cenografiaSertaoHD(scene, renderer, opts = {}, kit = {}) {
+ const mundo = (typeof window !== 'undefined' && window.__game?.world) || {};
+ const B = mundo.bounds || { minX: -33.2, maxX: 33.2, minZ: -45.2, maxZ: 45.2 };
+ const cols = (mundo.colliders || []).filter((c) => c.minY < .5 && c.maxY > .12);
+ const grupo = new THREE.Group(); grupo.name = 'sertao-hd-cenografia'; grupo.userData.nonCollider = true; scene.add(grupo);
+ const lixo = [], desfaz = [], rnd = rngDe(4099), obj = new THREE.Object3D(), cor = new THREE.Color();
+ const xiques = [], interiores = []; scene.traverse((o) => { if (o.userData?.interior) { const p = o.getWorldPosition(new THREE.Vector3()); interiores.push([p.x, p.z]); } });
+ const dentroDeCasa = (x, z) => interiores.some(([ix, iz]) => Math.hypot(x - ix, z - iz) < 5.4);
+ const livre = (x, z, folga = 0) => !cols.some((c) => x > c.minX - folga && x < c.maxX + folga && z > c.minZ - folga && z < c.maxZ + folga);
+ const zonas = (mundo.ctfPoints || []).map((q) => [q.x, q.z]);
+ const naArena = (x, z, m = .3) => x > B.minX + m && x < B.maxX - m && z > B.minZ + m && z < B.maxZ - m;
+ const lote = (geo, mat, n, nome, sombra = false) => { const im = new THREE.InstancedMesh(geo, mat, n); im.name = `sertao-hd-${nome}`; im.receiveShadow = true; im.castShadow = sombra;
+ im.userData.nonSolidSurface = true; grupo.add(im); lixo.push(im); return im; };
+ // Pé de parede: ponto na aresta de um colisor, longe das pontas (quina e ombreira de porta ficam nas pontas).
+ const paredes = cols.filter((c) => c.maxY - c.minY > .8 && Math.max(c.maxX - c.minX, c.maxZ - c.minZ) > 1.5);
+ const peDeParede = (afasta0, afasta1, margem = .45) => { for (let t = 0; t < 30 && paredes.length; t++) {
+ const c = paredes[Math.floor(rnd() * paredes.length)], emX = rnd() < (c.maxX - c.minX) / ((c.maxX - c.minX) + (c.maxZ - c.minZ)), lado = rnd() < .5 ? -1 : 1, d = afasta0 + rnd() * (afasta1 - afasta0);
+ const L = emX ? c.maxX - c.minX : c.maxZ - c.minZ; if (L < margem * 2 + .3) continue; const s = margem + rnd() * (L - margem * 2);
+ const x = emX ? c.minX + s : (lado < 0 ? c.minX - d : c.maxX + d), z = emX ? (lado < 0 ? c.minZ - d : c.maxZ + d) : c.minZ + s;
+ if (naArena(x, z) && livre(x, z, .03) && !dentroDeCasa(x, z)) return [x, z]; } return null; };
+
+ const matLiso = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: .82, name: 'hd-cen-barro' }); lixo.push(matLiso);
+ // O tipo de superfície vem no U do vértice (+100 aniagem, +200 adobe com junta): um programa só para barro, pano e tijolo.
+ matLiso.onBeforeCompile = (sh) => {
+ sh.vertexShader = sh.vertexShader.replace('#include ', '#include \nvarying vec3 vHdPos; varying vec2 vHdUv;').replace('#include ', '#include \nvHdPos = (modelMatrix * vec4(transformed, 1.0)).xyz; vHdUv = uv;');
+ sh.fragmentShader = sh.fragmentShader.replace('#include ', `#include \nvarying vec3 vHdPos; varying vec2 vHdUv;${kit.RUIDO_GLSL || ''}`).replace('#include ', `#include
+ { float hdTipo = floor(vHdUv.x / 100.0 + 0.5); vec2 hdU = vec2(vHdUv.x - hdTipo * 100.0, vHdUv.y) * 1.1;
+ if (hdTipo > 0.5 && hdTipo < 1.5) { vec2 hdT = hdU / 0.012; float hdF = smoothstep(0.7, 0.3, max(fwidth(hdT.x), fwidth(hdT.y)));
+ float hdTr = (0.5 + 0.5 * sin(hdT.x * 6.2832)) * (0.5 + 0.5 * sin(hdT.y * 6.2832));
+ diffuseColor.rgb *= mix(1.0, 0.66 + 0.5 * hdTr, hdF) * mix(0.8, 1.08, hdN(hdU * 11.0)) * mix(0.88, 1.04, hdN(hdU * vec2(4.0, 70.0)));
+ } else if (hdTipo > 1.5) { vec2 hdQ = vec2(vHdPos.x + vHdPos.z, vHdPos.y), hdB = vec2(hdQ.x / 0.4 + 0.5 * floor(hdQ.y / 0.14), hdQ.y / 0.14), hdBf = abs(fract(hdB) - 0.5);
+ float hdJ = (1.0 - smoothstep(0.011, 0.02 + fwidth(hdQ.y), min((0.5 - hdBf.x) * 0.4, (0.5 - hdBf.y) * 0.14))) * smoothstep(0.6, 0.25, fwidth(hdB.y));
+ diffuseColor.rgb *= (0.82 + 0.36 * hdH(floor(hdB))) * mix(0.8, 1.12, hdN(hdQ * 37.0));
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.6, 0.55, 0.47), hdJ * 0.92); } }`); };
+ matLiso.customProgramCacheKey = () => 'sertao-hd-cen-liso1';
+ // Material de pedra sem textura: mancha por posição local e base escurecida (assenta no chão sem sombra própria).
+ const matPedra = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: .96, metalness: 0, name: 'hd-cen-pedra' });
+ matPedra.onBeforeCompile = (sh) => {
+ sh.vertexShader = sh.vertexShader.replace('#include ', '#include \nvarying vec3 vHdL;').replace('#include ', '#include \nvHdL = position;');
+ sh.fragmentShader = sh.fragmentShader.replace('#include ', `#include \nvarying vec3 vHdL;${kit.RUIDO_GLSL || ''}`)
+ .replace('#include ', `#include
+ { float a = hdN(vHdL.xy * 3.1 + vHdL.z * 2.3) * 0.6 + hdN(vHdL.zx * 9.0 + vHdL.y * 5.0) * 0.4;
+ diffuseColor.rgb *= mix(0.5, 1.25, a) * mix(0.45, 1.0, smoothstep(-0.75, 0.15, vHdL.y)) * mix(0.7, 1.0, smoothstep(0.35, 0.5, hdN(vHdL.xz * 21.0 + vHdL.y * 17.0)));
+ diffuseColor.rgb = mix(diffuseColor.rgb, diffuseColor.rgb * vec3(1.05, 1.0, 0.95), smoothstep(0.55, 0.8, hdN(vHdL.yz * 2.0 + 4.0))); }`);
+ };
+ matPedra.customProgramCacheKey = () => 'sertao-hd-cen-pedra3';
+ lixo.push(matPedra);
+
+ if (opts.pedras !== false) {
+ const n = opts.pedras?.n ?? 190, g = pedraGeo(0, 11, .22, true), im = lote(g, matPedra, n, 'pedrinhas'); lixo.push(g);
+ const nucleos = Array.from({ length: 46 }, () => [B.minX + rnd() * (B.maxX - B.minX), B.minZ + rnd() * (B.maxZ - B.minZ)]);
+ let k = 0;
+ for (let t = 0; t < n * 12 && k < n; t++) {
+ let x, z;
+ if (rnd() < .42) { const p = peDeParede(.04, .7, .1); if (!p) continue; [x, z] = p; }
+ else { const c = nucleos[Math.floor(rnd() * nucleos.length)], a = rnd() * 6.283, r = Math.pow(rnd(), .7) * 2.4; x = c[0] + Math.cos(a) * r; z = c[1] + Math.sin(a) * r; }
+ if (!naArena(x, z, .1) || !livre(x, z, .02) || dentroDeCasa(x, z)) continue;
+ const r = .011 + Math.pow(rnd(), 2.2) * .039, achat = .5 + rnd() * .35;
+ obj.position.set(x, r * achat * .45, z); obj.rotation.set(rnd() * .5, rnd() * 6.283, rnd() * .5); obj.scale.set(r * (.8 + rnd() * .5), r * achat, r * (.8 + rnd() * .5)); obj.updateMatrix();
+ const v = .13 + rnd() * .2, w = rnd(); im.setMatrixAt(k, obj.matrix); im.setColorAt(k++, cor.setRGB(v * (.93 + .06 * w), v * .93, v * (.97 - .05 * w)));
+ }
+ im.count = k; im.instanceMatrix.needsUpdate = true; if (im.instanceColor) im.instanceColor.needsUpdate = true; im.computeBoundingSphere();
+ // Pedra chata de até 11 cm no meio da rua: o cascalho miúdo some a 8 m e o chão da praça ficava liso.
+ const n2 = opts.pedras?.chatas ?? 90, g2 = pedraGeo(0, 31, .26), im2 = lote(g2, matPedra, n2, 'pedras-chatas'); lixo.push(g2); let k2 = 0;
+ for (let t = 0; t < n2 * 14 && k2 < n2; t++) { const x = (rnd() * 2 - 1) * 24, z = (rnd() * 2 - 1) * 40;
+ if (!livre(x, z, .35) || dentroDeCasa(x, z) || zonas.some(([zx, zz]) => Math.hypot(x - zx, z - zz) < 5.8)) continue;
+ const r = .1 + Math.pow(rnd(), 1.8) * .2, alt = Math.min(.055, r * (.22 + rnd() * .14));
+ obj.position.set(x, alt * .5, z); obj.rotation.set(0, rnd() * 6.283, 0); obj.scale.set(r * (.8 + rnd() * .6), alt, r * (.8 + rnd() * .5)); obj.updateMatrix();
+ const v = .12 + rnd() * .12, w = rnd(); im2.setMatrixAt(k2, obj.matrix); im2.setColorAt(k2++, cor.setRGB(v * (.94 + .05 * w), v * .94, v * (.99 - .04 * w))); }
+ im2.count = k2; im2.instanceMatrix.needsUpdate = true; if (im2.instanceColor) im2.instanceColor.needsUpdate = true; im2.computeBoundingSphere();
+ }
+
+ if (opts.mato !== false) {
+ const n = opts.mato?.n ?? 160, g = tufoGeo(5), mat = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 1, side: THREE.DoubleSide, name: 'hd-cen-capim' });
+ const im = lote(g, mat, n, 'capim'); lixo.push(g, mat); let k = 0;
+ const poe = (x, z, h, larg = 1) => { if (k >= n) return; obj.position.set(x, -.01, z); obj.rotation.set(0, rnd() * 6.283, 0); obj.scale.set(h * larg, h, h * larg); obj.updateMatrix();
+ const v = .8 + rnd() * .45, w = rnd(); im.setMatrixAt(k, obj.matrix); im.setColorAt(k++, cor.setRGB(v * (1 + .1 * w), v * (.96 + .02 * w), v * (.9 - .25 * w))); };
+ if (opts.bordas !== false) for (const [x, z] of [[-19, -8], [-17, -5], [19, -8], [18, -5], [-18, 16]]) {
+ if (naArena(x, z, .4) && livre(x, z, .1) && !dentroDeCasa(x, z)) poe(x, z, .16 + rnd() * .12, .9 + rnd() * .35);
+ }
+ for (let t = 0; t < 400 && k < n * .70; t++) { const emX = rnd() < .43, s = rnd() < .5 ? -1 : 1;
+ const x = emX ? B.minX + rnd() * (B.maxX - B.minX) : s * (B.maxX - .05 - rnd() * .5), z = emX ? s * (B.maxZ - .25 - rnd() * .5) : B.minZ + rnd() * (B.maxZ - B.minZ);
+ if (emX && Math.abs(x) < 7) continue; if (livre(x, z, .05)) poe(x, z, .13 + rnd() * .17, .8 + rnd() * .5); }
+ for (let t = 0; t < 400 && k < n * .78; t++) { const x = B.minX + rnd() * (B.maxX - B.minX), z = B.minZ + rnd() * (B.maxZ - B.minZ);
+ if (naArena(x, z, 1) && livre(x, z, 1.3) && !dentroDeCasa(x, z)) poe(x, z, .08 + rnd() * .1, .7 + rnd() * .3); }
+ for (let t = 0; t < 600 && k < n; t++) { const emX = rnd() < .45, s = rnd() < .5 ? -1 : 1, fora = 5.2 + Math.pow(rnd(), 1.6) * 14;
+ const x = emX ? (rnd() * 2 - 1) * (B.maxX + 12) : s * (B.maxX + fora), z = emX ? s * (B.maxZ + fora) : (rnd() * 2 - 1) * (B.maxZ + 12);
+ poe(x, z, .22 + rnd() * .3, .9 + rnd() * .5); }
+ im.count = k; im.instanceMatrix.needsUpdate = true; if (im.instanceColor) im.instanceColor.needsUpdate = true; im.computeBoundingSphere();
+ // Macambira (roseta de folha dura) nos fundos das casas de pau a pique: até 45 cm, colada na parede e fora de porta.
+ const fundos = (mundo.colliders || []).filter((c) => /^sertao-casa-paupique-\d$/.test(c.tag || '') && c.maxY > 3).map((c) => { const s = c.minX + c.maxX < 0 ? -1 : 1; return [s, s < 0 ? c.minX : c.maxX, c.minZ, c.maxZ]; });
+ if (fundos.length && opts.macambira !== false) { const gr = tufoGeo(19, 13, { larg0: .07, base: [.3, .37, .27], ponta: [.16, -.06, -.1] }), imr = lote(gr, mat, fundos.length * 5, 'macambira'); lixo.push(gr); let kr = 0;
+ for (const [s, xf, z0, z1] of fundos) for (const f of [.16, .24, .3, .78, .86]) { const h = .3 + rnd() * .14;
+ obj.position.set(xf + s * (.22 + rnd() * .22), -.01, z0 + (z1 - z0) * (f + (rnd() - .5) * .04)); obj.rotation.set(0, rnd() * 6.283, 0); obj.scale.set(h * 1.25, h, h * 1.25); obj.updateMatrix();
+ const v = .85 + rnd() * .3; imr.setMatrixAt(kr, obj.matrix); imr.setColorAt(kr++, cor.setRGB(v, v, v)); }
+ imr.instanceMatrix.needsUpdate = true; imr.instanceColor.needsUpdate = true; imr.computeBoundingSphere(); xiques.push(...fundos); }
+ }
+
+ // Madeira: reaproveita a imagem de madeira que o mapa já carregou (sem textura nova na GPU).
+ let mapaMadeira = null; scene.traverse((o) => { if (!mapaMadeira && o.isMesh) { const m = Array.isArray(o.material) ? o.material[0] : o.material; if (/oeste-wood-real$/.test(m?.map?.name || '')) mapaMadeira = m.map; } });
+ const cercaX = B.maxX + 7.3, cercaZ = B.maxZ + 7.6;
+ if (opts.cerca !== false) {
+ const of = oficinas(), mapa = mapaMadeira ? mapaMadeira.clone() : null;
+ if (mapa) { mapa.repeat.set(1, 1); mapa.needsUpdate = true; mapa.name = 'hd-cen-madeira'; lixo.push(mapa); }
+ const mat = new THREE.MeshStandardMaterial({ color: 0xffffff, map: mapa, vertexColors: true, roughness: .92, name: 'hd-cen-madeira' });
+ if (mapa && kit.relevoDeCor) { mat.normalMap = kit.relevoDeCor(mapa, 2.8); mat.normalScale.set(2.6, 2.6); lixo.push(mat.normalMap); }
+ lixo.push(mat);
+ const a = new THREE.Vector3(), b = new THREE.Vector3();
+ const lados = [[-cercaX, -cercaZ, cercaX, -cercaZ], [cercaX, -cercaZ, cercaX, cercaZ], [cercaX, cercaZ, -cercaX, cercaZ], [-cercaX, cercaZ, -cercaX, -cercaZ]];
+ let indice = 0;
+ for (const [x0, z0, x1, z1] of lados) {
+ const L = Math.hypot(x1 - x0, z1 - z0), nP = Math.round(L / 2.7), nx = -(z1 - z0) / L, nz = (x1 - x0) / L;
+ for (let i = 0; i <= nP; i++, indice++) {
+ const t = i / nP, onda = Math.sin(t * 9.1 + x0) * .9 + Math.sin(t * 23 + z0) * .35;
+ const x = x0 + (x1 - x0) * t + nx * onda, z = z0 + (z1 - z0) * t + nz * onda, sorte = rngDe(700 + Math.floor(indice / 3) * 31)();
+ // Vão onde as estradas saem pelos portões e em trechos sorteados; trecho caído deita o mourão.
+ const vao = (Math.abs(z0) === cercaZ && z0 === z1 && Math.abs(x) < 8.5) || sorte < .13, caido = !vao && sorte < .27;
+ if (vao) continue;
+ const h = 1.32 + rnd() * .3, incl = caido ? 1.05 + rnd() * .35 : rnd() * .1, rumo = caido ? Math.atan2(z1 - z0, x1 - x0) + (rnd() - .5) * 1.4 : rnd() * 6.283, y0 = terreno(x, z);
+ a.set(x, y0 - .12, z); b.set(x + Math.cos(rumo) * Math.sin(incl) * h, y0 + Math.cos(incl) * h, z + Math.sin(rumo) * Math.sin(incl) * h);
+ const v = .78 + rnd() * .34; of.cilindro(a, b, .062 + rnd() * .014, .046, 4, [.50 * v, .46 * v, .42 * v], { tampas: false });
+ }
+ }
+ const barril = (x, z, h = .92, r = .31, deitado = 0) => { const y = terreno(x, z), v = .8 + rnd() * .3, tom = [.62 * v, .47 * v, .34 * v];
+ const eixo = deitado ? new THREE.Vector3(Math.cos(deitado), 0, Math.sin(deitado)) : new THREE.Vector3(0, 1, 0), p0 = new THREE.Vector3(x, y + (deitado ? r * 1.08 : 0), z);
+ const p1 = p0.clone().addScaledVector(eixo, h), bojo = [[0, .86], [.2, 1], [.5, 1.09], [.8, 1], [1, .86]];
+ of.cilindro(p0, p1, r, r, 9, tom, { aneis: bojo });
+ for (const f of [.17, .83]) of.cilindro(p0.clone().addScaledVector(eixo, h * (f - .022)), p0.clone().addScaledVector(eixo, h * (f + .022)), r * 1.015, r * 1.015, 9, [.13, .12, .115], { tampas: false }); };
+ const caixote = (x, z, s = .9, ry = 0, y = null) => { const y0 = y ?? terreno(x, z), v = .78 + rnd() * .3, tom = [.66 * v, .52 * v, .38 * v], ripa = [.5 * v, .38 * v, .27 * v];
+ const R = new THREE.Matrix4().makeRotationY(ry), em = (px, py, pz) => R.clone().setPosition(new THREE.Vector3(px, py, pz).applyMatrix4(R).add(new THREE.Vector3(x, y0, z)));
+ of.caixa(em(0, s / 2, 0), s, s, s, tom); const e = .07, m = s / 2;
+ for (const sx of [-1, 1]) for (const sz of [-1, 1]) of.caixa(em(sx * m, s / 2, sz * m), e, s + e, e, ripa);
+ for (const sy of [0, 1]) { for (const sz of [-1, 1]) of.caixa(em(0, sy * s, sz * m), s + e, e, e, ripa); for (const sx of [-1, 1]) of.caixa(em(sx * m, sy * s, 0), e, e, s + e, ripa); }
+ return y0 + s; };
+ const oeste = B.minX - 5.9, leste = B.maxX + 5.9, norte = B.minZ - 6.1, sul = B.maxZ + 6.1;
+ barril(oeste - .3, 7.6); barril(oeste - 1.1, 7.2, .9, .3); caixote(oeste - .5, 9.2, .95, .3); barril(oeste - 1.5, 9.6, .92, .31, 1.1);
+ const topo = caixote(leste + .4, -9, 1.05, .2); caixote(leste + .5, -9.1, .8, .7, topo); caixote(leste + .2, -7.4, .85, -.3); barril(leste + 1.3, -10.6); barril(leste + .2, -11.2, .95, .32);
+ barril(-12.4, norte - .2); barril(-13.3, norte - .7, .88, .3); caixote(-10.9, norte - .5, .9, .5);
+ caixote(14.2, sul + .3, 1, -.2); caixote(15.6, sul + .5, .8, .4); barril(12.6, sul + .4); barril(-20, sul + .6, .9, .3, .4);
+ caixote(oeste - .6, -22, .9, .15); barril(oeste - .4, -20.4); barril(leste + .5, 21.5); caixote(leste + .7, 23.2, .95, .6);
+
+ // Árvore seca em galhos de cilindro na mesma malha (o GLB custa 5 mil triângulos por pé; fica só no primeiro plano).
+ const arvoreSeca = (x, z, h, sem) => { const r = rngDe(sem);
+ const ramo = (p, dir, L, raio0, nivel) => { const raio = Math.max(raio0, .075), lados = nivel === 0 ? 5 : nivel === 1 ? 4 : 3, v = .8 + r() * .3, tom = [.43 * v, .37 * v, .32 * v];
+ const meio = p.clone().addScaledVector(dir, L * .5).add(new THREE.Vector3(r() - .5, (r() - .5) * .5, r() - .5).multiplyScalar(L * .2));
+ const fim = meio.clone().addScaledVector(dir, L * .5).add(new THREE.Vector3(r() - .5, r() * .3, r() - .5).multiplyScalar(L * .18));
+ of.cilindro(p, meio, raio, raio * .8, lados, tom, { tampas: false }); of.cilindro(meio, fim, raio * .8, raio * .6, lados, tom, { tampas: false });
+ if (nivel >= 3) return;
+ for (let i = 0, n = nivel === 0 ? 3 : 2 + (r() < .4 ? 1 : 0); i < n; i++) { const ang = r() * 6.283, abre = .5 + r() * .55;
+ ramo(fim, dir.clone().multiplyScalar(Math.cos(abre)).add(new THREE.Vector3(Math.cos(ang), .3 * (r() - .2), Math.sin(ang)).multiplyScalar(Math.sin(abre))).normalize(), L * (.64 + r() * .2), raio * .6, nivel + 1); } };
+ ramo(new THREE.Vector3(x, terreno(x, z) - .12, z), new THREE.Vector3((r() - .5) * .3, 1, (r() - .5) * .3).normalize(), h * .36, h * .03, 0); };
+ if (opts.flora !== false) [[-41.2, -41, 6.6], [-45.5, 9, 5.2], [-40.6, 28, 7.4], [41.4, -31, 6.2], [46, -5, 7.8], [40.8, 41, 5.6], [-9, -57, 6.4], [11, 55.5, 7], [-30, 55, 5.4],
+ ...(opts.silhueta === false ? [] : [[-12.5, -52.5, 11], [14, -53.5, 11.5]])].forEach(([x, z, h], i) => arvoreSeca(x, z, h, 300 + i * 17));
+
+ // Placa de rumo: três tábuas com ponta de seta num mourão, fora do alambrado do mapa.
+ const px = oeste - .2, pz = 3.4, tabuas = [];
+ if (opts.placa !== false) {
+ of.cilindro(new THREE.Vector3(px, -.15, pz), new THREE.Vector3(px + .03, 2.75, pz - .02), .075, .06, 7, [.46, .41, .36]);
+ [[2.42, .32, 1.35, 1], [2.05, -.22, 1.2, -1], [1.68, .12, 1.28, 1]].forEach(([y, ry, larg, mao], i) => {
+ const R = new THREE.Matrix4().makeRotationY(Math.PI / 2 + ry), em = (lx, ly, lz) => R.clone().setPosition(new THREE.Vector3(lx, ly, lz).applyMatrix4(R).add(new THREE.Vector3(px, y, pz)));
+ const tom = [[.74, .63, .5], [.66, .56, .46], [.7, .58, .44]][i];
+ of.caixa(em(mao * .12, 0, .1), larg, .27, .035, tom);
+ const bico = new THREE.Matrix4().makeRotationY(Math.PI / 2 + ry).multiply(new THREE.Matrix4().makeRotationZ(Math.PI / 4));
+ bico.setPosition(new THREE.Vector3(mao * (larg / 2 + .12), 0, .1).applyMatrix4(R).add(new THREE.Vector3(px, y, pz))); of.caixa(bico, .19, .19, .033, tom);
+ tabuas.push({ m: em(mao * .12, 0, .1 + .019), larg, i });
+ });
+ const cv = document.createElement('canvas'); cv.width = 512; cv.height = 256; const c2 = cv.getContext('2d');
+ c2.textAlign = 'center'; c2.textBaseline = 'middle'; c2.font = '900 54px Georgia, serif';
+ ['PRAÇA DA MATRIZ', 'FORRÓ', 'AÇUDE 2 LÉGUAS'].forEach((txt, i) => { c2.fillStyle = ['#efe6cf', '#e9dfc6', '#efe2c2'][i]; c2.fillText(txt, 256, 43 + i * 85, 480); });
+ const img = c2.getImageData(0, 0, 512, 256), gasto = rngDe(77);
+ for (let i = 3; i < img.data.length; i += 4) if (img.data[i] && gasto() < .16) img.data[i] *= gasto() * .7;
+ c2.putImageData(img, 0, 0);
+ const tex = new THREE.CanvasTexture(cv); tex.colorSpace = THREE.SRGBColorSpace; tex.anisotropy = 4; tex.name = 'hd-cen-placa';
+ const P = [], U = [], I = [], v = new THREE.Vector3();
+ for (const { m, larg, i } of tabuas) { const b = P.length / 3;
+ for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { v.set(sx * (larg / 2 - .06), sy * .105, 0).applyMatrix4(m); P.push(v.x, v.y, v.z); U.push(sx > 0 ? 1 : 0, 1 - (i + (sy > 0 ? .08 : .92)) / 3); }
+ I.push(b, b + 1, b + 2, b, b + 2, b + 3); }
+ const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(U, 2)); g.setIndex(I); g.computeVertexNormals();
+ const matTxt = new THREE.MeshStandardMaterial({ map: tex, transparent: true, alphaTest: .25, roughness: 1, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2 });
+ const letras = new THREE.Mesh(g, matTxt); letras.name = 'sertao-hd-placa-letras'; grupo.add(letras); lixo.push(g, matTxt, tex);
+ }
+ const liso = oficinas(), V3 = (x, y, z) => new THREE.Vector3(x, y, z);
+ const TINTAS = [[.17, .27, .43], [.15, .3, .17], [.33, .31, .22]], pin = oficinas(), FERRO = [.1, .095, .09], BREU = [.02, .02, .024], BARRO = [.4, .26, .15], CAL = [1.1, 1.08, 1.04], ANIL = [.07, .16, .42], ANIL_PORTA = [.11, .2, .43], DEGRAU = [.5, .47, .43], I4 = () => new THREE.Matrix4();
+ const pl = oficina(), tl = oficina(), panos = [], escondidos = [];
+ // Recortes do atlas de letreiros (px num canvas de 1024): [x, y, largura, altura].
+ const RT = { bodega: [0, 0, 512, 150], barbearia: [512, 0, 512, 150], mercearia: [0, 150, 512, 150], vote: [512, 150, 512, 150], forro: [0, 300, 1024, 170], queijo: [0, 470, 640, 220], fiado: [640, 470, 384, 220],
+ secos: [0, 690, 1024, 70], cabelo: [0, 760, 420, 64], n27: [420, 760, 150, 64], n104: [570, 760, 170, 64], n12: [740, 760, 100, 64], exvoto: [0, 830, 170, 194], graca: [170, 830, 300, 194], chita: [470, 830, 280, 194], fitas: [750, 830, 274, 194] };
+ // Quadro de uma face de parede: x corre para a direita de quem olha de fora, z sai da parede.
+ const quadro = (W, ox, oz, th) => { const F = I4().makeRotationY(th).setPosition(ox, 0, oz).premultiply(W);
+ return { m: (x, y, z) => F.clone().multiply(I4().setPosition(x, y, z)), p: (x, y, z) => V3(x, y, z).applyMatrix4(F) }; };
+ const quebra = (q, x, y, w, h, sem) => { const rq = rngDe(sem), pts = Array.from({ length: 11 }, (_, i) => { const a = i / 11 * 6.2832, f = .6 + rq() * .5; return [Math.cos(a) * w / 2 * f, Math.sin(a) * h / 2 * f]; });
+ liso.tipo(2); liso.prisma(q.m(x, y, .011), pts, .016, [.36, .22, .12]); liso.tipo(0); };
+ const QUEBRAS = { 'sertao-praca-casa-interior-0': -1, 'sertao-praca-casa-interior-1': 1 };
+ const letreiro = (q, nome, x, y, larg, z = .02) => panos.push({ m: q.m(x, y, z), w: larg, h: larg * RT[nome][3] / RT[nome][2], r: RT[nome] });
+ const tinge = (t, g) => [t[0] * g, t[1] * g, t[2] * g];
+ // Folha de porta ou janela: `base` põe a origem na dobradiça; sx diz para que lado a folha cresce.
+ const folha = (base, sx, lf, h, tinta, tipo, r) => {
+ const em = (x, y, z) => base(sx * x, y, z), g0 = .86 + r() * .24;
+ const tab = (m, w, hh, d, k = 1) => r() < .07 ? of.caixa(m, w, hh, d, [1.3 * k, 1.15 * k, k]) : pin.caixa(m, w, hh, d, tinge(tinta, g0 * k * (.9 + r() * .2)));
+ if (tipo === 'almofada') { tab(em(lf / 2, h / 2, 0), lf, h, .035, .78);
+ const np = h > 1.5 ? 3 : 1, ph = (h - .16 - (np - 1) * .1) / np;
+ for (let i = 0; i < np; i++) { const y = .08 + ph / 2 + i * (ph + .1); tab(em(lf / 2, y, .026), lf - .18, ph, .022, .55); tab(em(lf / 2, y, .044), lf - .3, ph - .12, .02, 1.15); }
+ } else if (tipo === 'rotula') { const e = .06, nua = r() < .07, c0 = nua ? [1.3, 1.15, 1] : tinge(tinta, g0 * (.9 + r() * .2)), alvo = nua ? of : pin, passo = .15, X0 = e, X1 = lf - e, Y0 = e, Y1 = h - e;
+ for (const [x, y, w, hh] of [[e / 2, h / 2, e, h], [lf - e / 2, h / 2, e, h], [lf / 2, e / 2, lf, e], [lf / 2, h - e / 2, lf, e]]) alvo.caixa(em(x, y, 0), w, hh, .04, c0);
+ for (let c = Y0 - X1 + passo / 2; c < Y1 - X0; c += passo) { const a = Math.max(X0, Y0 - c), b = Math.min(X1, Y1 - c); if (b - a > .04) alvo.caixa(em((a + b) / 2, (a + b) / 2 + c, -.006).multiply(I4().makeRotationZ(sx * Math.PI / 4)), (b - a) * 1.414, .034, .012, c0, [4, 5]); }
+ for (let c = X0 + Y0 + passo / 2; c < X1 + Y1; c += passo) { const a = Math.max(X0, c - Y1), b = Math.min(X1, c - Y0); if (b - a > .04) alvo.caixa(em((a + b) / 2, c - (a + b) / 2, .006).multiply(I4().makeRotationZ(-sx * Math.PI / 4)), (b - a) * 1.414, .034, .012, c0, [4, 5]); }
+ } else { const nt = Math.max(2, Math.round(lf / .2)), lt = lf / nt;
+ for (let t = 0; t < nt; t++) tab(em((t + .5) * lt, h / 2 - r() * .02, 0), lt - .014, h, .035);
+ for (const fy of [.14, .86]) tab(em(lf / 2, h * fy, .028), lf - .04, .1, .022, .8);
+ if (h > 1.5 && tipo !== 'postigo') tab(em(lf / 2, h * .5, .027).multiply(I4().makeRotationZ(sx * Math.atan2(h * .72 - .1, lf - .08))), Math.hypot(h * .72 - .1, lf - .08), .09, .02, .8);
+ if (tipo === 'postigo') { const py = Math.min(h - .34, 1.5); tab(em(lf / 2, py, .03), Math.min(.4, lf - .1), .44, .03, .65); tab(em(lf / 2, py, .05), Math.min(.3, lf - .2), .34, .016, 1.14); liso.caixa(em(lf / 2, py - .1, .064), .07, .02, .02, FERRO); } }
+ const tabuas = tipo === 'tabua' || tipo === 'postigo';
+ for (const fy of [.17, .83]) liso.caixa(em(.07, h * fy + (tabuas ? .09 : 0), .03), .14, .04, .03, FERRO);
+ if (h > 1.5) { liso.caixa(em(lf - .1, h * .52, .04), .18, .028, .028, FERRO); liso.caixa(em(lf - .06, h * .52, .05), .03, .07, .03, FERRO); }
+ else tab(em(lf - .04, h * .5, .042).multiply(I4().makeRotationZ(.6)), .15, .045, .02, .72);
+ };
+ const LETREIROS = { 'sertao-praca-casa-interior-0': [[1, 'mercearia', 2.15, 3.13, 1.9], [1, 'secos', -2.25, 3.2, 2.5], [1, 'n27', -2.9, 2.2, .4]],
+ 'sertao-praca-casa-interior-1': [[1, 'barbearia', -2.15, 3.13, 1.9], [1, 'cabelo', 2.2, 3.2, 1.3], [1, 'n104', 2.9, 2.2, .46]],
+ 'sertao-casa-platibanda-0': [[-1, 'exvoto', 2.85, 2.56, .5], [-1, 'graca', 2.85, 1.98, .7]], 'sertao-casa-platibanda-1': [[-1, 'vote', 2.78, 2.62, 1.3], [-1, 'n12', -2.9, 2.2, .3]],
+ 'sertao-casa-pedra-7': [[-1, 'secos', 0, 3.12, 3.3]], 'sertao-casa-pedra-8': [[-1, 'queijo', -2.35, 3.08, 1.9]], 'sertao-casa-geminada-9': [[-1, 'forro', 0, 4.7, 4.4]] };
+ let casaN = 0;
+ if (opts.marcenaria !== false) scene.traverse((root) => {
+ const planta = root.userData?.interior; if (!planta || !/^sertao-(casa-|praca-casa-)/.test(root.name)) return;
+ root.updateWorldMatrix(true, false);
+ const daPraca = /praca-casa/.test(root.name), frente = daPraca ? -1 : 1, bp = root.userData.boxParts || {}, { halfW, halfD } = planta, r = rngDe(root.name.length * 97 + Math.round(root.position.x * 7)), W = root.matrixWorld;
+ const k = casaN++, tinta = TINTAS[k % 3], tPorta = ['postigo', 'almofada', 'tabua'][k % 3], tJan = k % 2 ? 'rotula' : 'tabua', faces = {};
+ const em = (x, y, z, ry = 0) => I4().makeRotationY(ry).setPosition(x, y, z).premultiply(W);
+ // vão = [eixo da parede, sinal para fora, centro ao longo da parede, largura, y0, y1]
+ const vaos = [['z', frente, 0, 1.9, 0, 2.73], ['z', -frente, 0, daPraca ? 1.4 : 2, .82, 2.57]];
+ for (const lado of [-1, 1]) vaos.push(bp[`${root.name}-peitoril-lateral-${lado}`] ? ['x', lado, .1, 1.44, .88, 2.55] : ['x', lado, 0, 1.9, 0, 2.55]);
+ for (const [eixo, sinal, c, larg, y0, y1] of vaos) {
+ const face = (eixo === 'z' ? halfD : halfW) + .14, v = .8 + r() * .3, tom = [.62 * v, .56 * v, .5 * v], escuro = [.4 * v, .35 * v, .31 * v];
+ const q = eixo === 'z' ? quadro(W, c, sinal * face, sinal > 0 ? 0 : Math.PI) : quadro(W, sinal * face, c, sinal * Math.PI / 2);
+ if (eixo === 'z') faces[sinal * frente] = q;
+ of.caixa(q.m(0, y1 + .09, .03), larg + .44, .18, .14, escuro);
+ if (y0 > .1) of.caixa(q.m(0, y0 - .02, .05), larg + .2, .05, .18, tom);
+ const porta = y0 < .1, h = y1 - y0 - .06, lf = larg / 2 - .02;
+ for (const s2 of [-1, 1]) folha((x, y, z) => q.m(s2 * (larg / 2 + .03) + x, y0 + .03 + y, .035 + z), s2, lf, h, tinta, porta ? tPorta : tJan, r);
+ // Bandô de fitas ou de chita na verga da porta da frente: fica todo acima de 2,2 m.
+ if (porta && eixo === 'z' && sinal === frente && k % 3 && opts.letreiros !== false) panos.push({ m: q.m(0, y1 - .25, -.12), w: larg, h: .5, r: k % 3 === 1 ? RT.fitas : RT.chita });
+ }
+ if (opts.letreiros !== false) for (const [lado, nome, x, y, w] of LETREIROS[root.name] || []) if (faces[lado]) letreiro(faces[lado], nome, x, y, w);
+ if (QUEBRAS[root.name] && faces[1] && opts.quebras !== false) { const sq = QUEBRAS[root.name]; quebra(faces[1], sq * 1.52, 2.86, .8, .44, 31 + k); quebra(faces[1], -sq * 1.3, 2.84, .42, .3, 47 + k); }
+ // Lampião e chifres acima de 2,2 m: enfeite de fachada sem tocar a faixa de tiro.
+ const zf = frente * (halfD + .14), lx = (r() < .5 ? -1 : 1) * 1.32;
+ of.caixa(em(lx, 2.74, zf + frente * .17), .04, .04, .34, [.2, .18, .17]);
+ liso.cilindro(V3(lx, 2.42, zf + frente * .3).applyMatrix4(root.matrixWorld), V3(lx, 2.72, zf + frente * .3).applyMatrix4(root.matrixWorld), .06, .06, 6, [.09, .085, .08], { aneis: [[0, 1], [.12, 1.05], [.14, .78], [.72, .78], [.74, 1.1], [.9, .5], [1, .12]] });
+ liso.cilindro(V3(lx, 2.47, zf + frente * .3).applyMatrix4(root.matrixWorld), V3(lx, 2.63, zf + frente * .3).applyMatrix4(root.matrixWorld), .052, .052, 6, [3.2, 1.9, .7], { tampas: false });
+ for (const s2 of [-1, 1]) { const a = V3(s2 * .07, 3.08, zf + frente * .06), b = V3(s2 * .3, 3.05, zf + frente * .2), c2 = V3(s2 * .46, 3.24, zf + frente * .26);
+ for (const q of [a, b, c2]) q.applyMatrix4(root.matrixWorld);
+ liso.cilindro(a, b, .048, .036, 5, [.7, .64, .5], { tampas: false }); liso.cilindro(b, c2, .036, .008, 5, [.62, .55, .42], { tampas: false }); }
+ liso.caixa(em(0, 3.08, zf + frente * .05), .2, .16, .1, [.5, .44, .34]);
+ });
+ // Objetos de calçada: tudo encostado em parede ou esteio que já colide, em cima de peitoril, ou acima de 2,2 m.
+ const moringa = (p, s = 1) => { const v = .8 + rnd() * .35; liso.cilindro(p, p.clone().add(V3(0, .3 * s, 0)), .11 * s, .11 * s, 9, tinge(BARRO, v), { aneis: [[0, .5], [.12, .86], [.38, 1], [.58, .8], [.72, .36], [.9, .3], [1, .42]] }); };
+ const filtro = (p, e = .72) => { const t = tinge(BARRO, 1.3), em = (y) => p.clone().add(V3(0, y * e, 0)); liso.cilindro(p, em(.24), .13 * e, .125 * e, 10, t, { aneis: [[0, .88], [.08, 1], [.94, 1], [1, .9]] });
+ liso.cilindro(em(.24), em(.45), .12 * e, .115 * e, 10, tinge(BARRO, 1.18), { aneis: [[0, .92], [.08, 1], [.92, 1], [1, .9]] });
+ liso.cilindro(em(.45), em(.52), .12 * e, .12 * e, 10, t, { aneis: [[0, 1], [.5, .6], [.8, .2], [1, .25]] }); };
+ const cuia = (p) => liso.cilindro(p, p.clone().add(V3(0, .05, 0)), .045, .095, 8, [.46, .36, .16]);
+ const banco = (q, x, z, L = 1.3) => { const v = .8 + rnd() * .3, t = [.66 * v, .54 * v, .4 * v];
+ of.caixa(q.m(x, .43, z), L, .045, .27, t); of.caixa(q.m(x, .2, z), L - .3, .04, .04, tinge(t, .8));
+ for (const sx of [-1, 1]) for (const sz of [-1, 1]) of.caixa(q.m(x + sx * (L / 2 - .13), .205, z + sz * .09).multiply(I4().makeRotationZ(sx * .1)), .05, .42, .05, tinge(t, .8)); };
+ const tamborete = (q, x, z) => { const v = .8 + rnd() * .3, t = [.6 * v, .5 * v, .38 * v]; of.cilindro(q.p(x, .37, z), q.p(x, .41, z), .16, .16, 9, t);
+ for (let i = 0; i < 3; i++) { const a = i * 2.094 + .4; of.cilindro(q.p(x + Math.cos(a) * .17, 0, z + Math.sin(a) * .17), q.p(x + Math.cos(a) * .09, .37, z + Math.sin(a) * .09), .022, .022, 4, tinge(t, .8), { tampas: false }); } };
+ const gaiola = (q, x, z) => { const y = 2.3, mad = [.5, .4, .24], f = (dx, yy, dz, w, h, d, c = mad) => liso.caixa(q.m(x + dx, yy, z + dz), w, h, d, c);
+ f(0, y, 0, .24, .02, .24); f(0, y + .3, 0, .24, .02, .24); f(0, y + .42, 0, .012, .2, .012, FERRO);
+ liso.cilindro(q.p(x, y + .3, z), q.p(x, y + .38, z), .15, .02, 4, mad, { giro: Math.PI / 4 });
+ for (const [dx, dz] of [[-1, -1], [1, -1], [1, 1], [-1, 1], [0, -1], [1, 0], [0, 1], [-1, 0]]) f(dx * .11, y + .15, dz * .11, .012, .3, .012);
+ f(0, y + .1, 0, .2, .012, .012); f(.02, y + .14, 0, .05, .055, .08, [1.7, 1.35, .25]); f(.02, y + .18, .04, .035, .035, .035, [1.7, 1.35, .25]); };
+ const rede = (q, x, z) => { const cores = [[1.3, 1.22, 1.05], [.3, .5, 1.05], [1.3, 1.22, 1.05], [.95, .3, .22], [1.3, 1.22, 1.05]];
+ cores.forEach((c, i) => liso.cilindro(q.p(x, 1.2 + i * .15, z), q.p(x, 1.35 + i * .15, z), .085, .085, 7, c, { tampas: i === 0 || i === 4, aneis: [[0, i === 0 ? .6 : 1], [1, i === 4 ? .6 : 1]] }));
+ for (const y of [1.3, 1.62, 1.88]) liso.cilindro(q.p(x, y, z), q.p(x, y + .025, z), .092, .092, 7, [.3, .25, .18], { tampas: false });
+ liso.cilindro(q.p(x, 1.95, z), q.p(x + .1, 2.4, z), .014, .014, 3, [.5, .45, .35], { tampas: false }); liso.cilindro(q.p(x, 1.2, z), q.p(x, .95, z), .03, .012, 4, [1.2, 1.1, .95], { tampas: false }); };
+ const pilao = (q, x, z) => { const v = .8 + rnd() * .3, t = [.6 * v, .5 * v, .4 * v]; of.cilindro(q.p(x, 0, z), q.p(x, .62, z), .19, .19, 9, t, { aneis: [[0, 1], [.12, .92], [.42, .6], [.6, .66], [1, 1.05]] });
+ of.cilindro(q.p(x + .03, .45, z), q.p(x + .12, .98, z - .16), .034, .034, 6, tinge(t, 1.15), { aneis: [[0, 1.5], [.22, 1], [.78, 1], [1, 1.5]] }); };
+ const feixe = (q, x, z) => { for (const [dz, dy] of [[0, .05], [.1, .05], [-.1, .05], [.05, .13], [-.05, .13], [0, .21]]) { const v = .7 + rnd() * .4, e = (rnd() - .5) * .08;
+ of.cilindro(q.p(x - .42 + e, dy, z + dz), q.p(x + .42 + e, dy, z + dz), .05, .045, 5, [.5 * v, .43 * v, .36 * v]); }
+ for (const dx of [-.22, .22]) liso.cilindro(q.p(x + dx, .14, z - .17), q.p(x + dx, .14, z + .17), .012, .012, 3, [.3, .25, .18], { tampas: false }); };
+ const fogao = (q, x) => { const c = (o, dx, y, z, w, h, d, cor = CAL) => o.caixa(q.m(x + dx, y, z), w, h, d, cor);
+ c(pl, 0, .36, .34, 1.15, .72, .6); c(pl, 0, .755, .34, 1.25, .07, .68); c(pl, .43, 1.3, .16, .24, 1.05, .24); c(pl, .43, 1.86, .16, .32, .07, .32);
+ c(liso, -.18, .3, .645, .36, .32, .02, BREU); for (const dx of [-.3, .1]) liso.cilindro(q.p(x + dx, .79, .36), q.p(x + dx, .795, .36), .11, .11, 10, BREU);
+ liso.cilindro(q.p(x - .3, .795, .36), q.p(x - .3, 1.02, .36), .15, .15, 9, tinge(BARRO, .7), { aneis: [[0, .6], [.2, 1], [.7, .95], [.85, .7], [1, .78]] }); };
+ const couro = (q, x, y) => { const pts = [[-.5, -.42], [-.38, -.3], [-.2, -.36], [0, -.4], [.2, -.36], [.38, -.3], [.5, -.42], [.52, -.2], [.36, -.05], [.38, .15], [.55, .38], [.4, .44], [.22, .3], [.08, .42], [0, .5], [-.08, .42], [-.22, .3], [-.4, .44], [-.55, .38], [-.38, .15], [-.36, -.05], [-.52, -.2]];
+ liso.prisma(q.m(x, y, .05), pts, .012, [.2, .14, .09]); liso.prisma(q.m(x + .03, y + .02, .058), pts.map(([a, b]) => [a * .5, b * .55]), .008, [.42, .36, .27]);
+ for (const [x0, y0, x1, y1] of [[-.66, -.55, .66, -.55], [-.66, .58, .66, .58], [-.62, -.6, -.62, .63], [.62, -.6, .62, .63]]) of.cilindro(q.p(x + x0, y + y0, .04), q.p(x + x1, y + y1, .04), .022, .02, 4, [.5, .44, .36], { tampas: false });
+ for (const [a, b] of [[-.5, -.42], [.5, -.42], [.55, .38], [-.55, .38], [0, .5], [0, -.4]]) liso.cilindro(q.p(x + a, y + b, .05), q.p(x + a * 1.2, y + (b > 0 ? .58 : -.55), .045), .008, .008, 3, [.45, .4, .3], { tampas: false }); };
+ // Casa maciça de pau a pique: porta e janelas de verdade por cima das caixas escuras do mapa, cada casa com o seu arranjo.
+ const ARRANJO = { 2: { porta: 'postigo', jan: ['tabua', 'meia'], frente: ['bodega', 0, 2.68, 1.4], lado: ['queijo', 1.95, 2.52, 2.1] }, 3: { porta: 'holandesa', pano: 'chita', jan: ['rotula', 'rotula'], lado: ['fiado', -1.95, 2.5, 1.45] },
+ 4: { porta: 'almofada', jan: ['filtro', 'tabua'], lado: ['vote', 1.9, 2.5, 1.7] }, 5: { porta: 'holandesa', pano: 'fitas', jan: ['meia', 'tabua'], lado: ['exvoto', 1.9, 2.5, .5] }, 6: { porta: 'tabua', jan: ['rotula', 'tabua'], frente: ['n12', 1.0, 2.2, .3] } };
+ if (opts.marcenaria !== false) scene.traverse((root) => { if (!/^sertao-casa-paupique-\d+$/.test(root.name)) return;
+ const parede = root.children.find((c) => /^parede-casa-/.test(c.name)), g = parede?.geometry?.parameters; if (!g) return;
+ root.updateWorldMatrix(true, false); const W = root.matrixWorld, id = +root.name.split('-').pop(), E = ARRANJO[id] || ARRANJO[2 + id % 5], r = rngDe(id * 131 + 7), tinta = TINTAS[id % 3], v = .8 + r() * .25, escuro = [.4 * v, .35 * v, .31 * v], tom = [.62 * v, .56 * v, .5 * v];
+ for (const c of root.children) { const p = c.geometry?.parameters; if (c.isMesh && c.visible && p && Math.abs(p.width - .8) < .01 && Math.abs(p.height - .8) < .01) { c.visible = false; escondidos.push(c); } }
+ const q = quadro(W, 0, g.depth / 2 + .02, 0), hol = E.porta === 'holandesa', hp = hol ? .98 : 2.03;
+ for (const sx of [-1, 1]) of.caixa(q.m(sx * .64, 1.21, .09), .12, 2.14, .14, escuro);
+ of.caixa(q.m(0, 2.33, .09), 1.52, .14, .17, escuro);
+ for (const sx of [-1, 1]) folha((x, y, z) => q.m(-sx * .575 + x, .17 + y, .12 + z), sx, .57, hp, tinta, hol ? 'tabua' : E.porta, r);
+ if (hol) { of.caixa(q.m(0, 1.17, .15), 1.2, .04, .16, tom); if (opts.letreiros !== false) panos.push({ m: q.m(0, 1.7, .1), w: 1.15, h: 1.0, r: RT[E.pano] }); }
+ [-1.55, 1.55].forEach((cx, i) => { const t = E.jan[i], fora = cx < 0 ? -1 : 1;
+ liso.caixa(q.m(cx, 2.05, .075), .82, .82, .02, BREU);
+ for (const sx of [-1, 1]) of.caixa(q.m(cx + sx * .44, 2.05, .1), .08, .96, .12, escuro);
+ of.caixa(q.m(cx, 2.49, .1), .96, .08, .12, escuro); of.caixa(q.m(cx, 1.61, .12), 1.0, .07, .22, tom);
+ for (const sx of [-1, 1]) { if (t === 'filtro' || (t === 'meia' && sx === fora)) folha((x, y, z) => q.m(cx + sx * .5 + x, 1.65 + y, .05 + z), sx, .35, .8, tinta, 'tabua', r);
+ else folha((x, y, z) => q.m(cx - sx * .4 + x, 1.65 + y, .11 + z), sx, .395, .8, tinta, t === 'rotula' ? 'rotula' : 'tabua', r); }
+ if (t === 'filtro' && opts.objetos !== false) filtro(q.p(cx - .1, 1.645, .14)); });
+ const lado = Math.sign((0 - root.position.x) * W.elements[0] + (2 - root.position.z) * W.elements[2]) || 1, qL = quadro(W, lado * (g.width / 2 + .05), 0, lado * Math.PI / 2), qF = quadro(W, 0, -(g.depth / 2 + .04), Math.PI);
+ if (opts.letreiros !== false) { if (E.frente) letreiro(q, ...E.frente, .03); if (E.lado) letreiro(qL, ...E.lado, .03); }
+ if ((id === 4 || id === 5) && opts.quebras !== false) { const sq = id === 4 ? 1 : -1; quebra(q, sq * 1.0, 2.44, .62, .72, 60 + id); quebra(q, -sq * .9, 2.62, .4, .34, 70 + id); }
+ if (opts.objetos === false) return;
+ if (id === 2) { banco(q, 1.55, .32); cuia(q.p(1.25, .455, .32)); cuia(q.p(1.8, .455, .36)); moringa(q.p(-1.9, 0, .3)); moringa(q.p(-2.25, 0, .34), .8); }
+ if (id === 3) { gaiola(q, 1.5, .85); tamborete(q, -1.4, .34); tamborete(q, -2.0, .4); feixe(qF, 1.2, .3); }
+ if (id === 4) { rede(q, 2.08, 1.1); pilao(q, -1.85, .36); couro(qL, -1.85, 2.55); }
+ if (id === 5) { banco(q, -1.55, .32, 1.1); moringa(q.p(-1.5, .455, .32), .8); gaiola(q, -1.2, .9); couro(qL, -1.8, 2.55); }
+ if (id === 6) { feixe(q, 1.6, .3); pilao(q, -1.8, .36); fogao(qF, .4); }
+ });
+ if (opts.objetos !== false) {
+ // Mourão de amarrar montaria logo depois do limite oeste, com sela, manta e arreio.
+ const hx = B.minX - .75, hz = 10.5;
+ for (const dz of [-1.1, 1.1]) of.cilindro(V3(hx, -.1, hz + dz), V3(hx, 1.1, hz + dz), .06, .05, 5, [.5, .45, .4], { tampas: false });
+ of.cilindro(V3(hx, 1.02, hz - 1.3), V3(hx, 1.02, hz + 1.3), .045, .045, 5, [.52, .46, .4]);
+ liso.caixa(I4().setPosition(hx, 1.085, hz), .52, .03, .62, [.5, .16, .12]); liso.caixa(I4().setPosition(hx, 1.09, hz), .53, .03, .2, [.75, .7, .55]);
+ liso.cilindro(V3(hx, 1.15, hz - .26), V3(hx, 1.15, hz + .26), .16, .16, 8, [.19, .115, .07], { aneis: [[0, 1.3], [.16, .95], [.5, .78], [.84, 1], [1, 1.4]] });
+ for (const sx of [-1, 1]) { liso.caixa(I4().setPosition(hx + sx * .21, .82, hz), .02, .52, .045, [.14, .09, .06]); liso.caixa(I4().setPosition(hx + sx * .21, .54, hz), .03, .09, .13, FERRO); }
+ liso.cilindro(V3(hx, 1.06, hz + .8), V3(hx + .1, .55, hz + .86), .012, .012, 3, [.14, .09, .06], { tampas: false }); liso.cilindro(V3(hx, 1.06, hz + .9), V3(hx - .08, .6, hz + .82), .012, .012, 3, [.14, .09, .06], { tampas: false });
+ }
+ // Capela caiada: frontão triangular, torre sineira baixa no eixo, barra e guarnições de anil, cruz de ferro.
+ const matriz = (M, k) => {
+ const mz = (x, y, z) => M.clone().multiply(I4().setPosition(x, y, z)), P = (x, y, z) => V3(x, y, z).applyMatrix4(M), cx = (o, x, y, z, w, h, d, cor = CAL) => o.caixa(mz(x, y, z), w, h, d, cor), r = rngDe(53);
+ cx(pl, 0, 1.6, -.55, 4, 3.2, 5); pl.prisma(mz(0, 0, -3.02), [[-2, 3.2], [2, 3.2], [0, 4.16]], .06, CAL, [0, 3.4]);
+ for (const s of [-1, 1]) tl.caixa(M.clone().multiply(I4().makeRotationZ(-s * .43).setPosition(s * 1.08, 3.69, -.5)), 2.55, .1, 5.35, CAL);
+ tl.cilindro(P(0, 4.2, -3.2), P(0, 4.2, 2.05), .1 * k, .1 * k, 6, CAL);
+ cx(pl, 0, .43, -3.065, 4.04, .86, .03, ANIL);
+ for (const s of [-1, 1]) { cx(pl, s * 1.4, 1.75, 2.3, 1.5, 3.5, .6); cx(pl, s * 1.97, 1.75, 2.63, .36, 3.5, .07);
+ cx(pl, s * 1.3, .43, 2.615, 1.3, .86, .03, ANIL); cx(pl, s * 1.97, .43, 2.68, .38, .86, .03, ANIL); cx(pl, s * 2.015, .43, -.55, .03, .86, 5, ANIL);
+ cx(pl, s * .74, 1.33, 2.63, .16, 2.22, .08, ANIL);
+ pl.caixa(M.clone().multiply(I4().makeRotationZ(-s * .388).setPosition(s * 1.2, 4.06, 2.32)), 2.06, .1, .7, CAL);
+ for (const zc of [-2.2, -.6]) { const F = M.clone().multiply(I4().makeRotationY(s * Math.PI / 2).setPosition(s * 2.0, 0, zc)), fm = (x, y, z) => F.clone().multiply(I4().setPosition(x, y, z));
+ pl.caixa(fm(0, 2.52, .04), .74, .1, .1, ANIL); pl.caixa(fm(0, 1.56, .04), .7, .07, .12, ANIL);
+ for (const sx of [-1, 1]) folha((x, y, z) => fm(-sx * .27 + x, 1.6 + y, .03 + z), sx, .265, .86, ANIL_PORTA, 'tabua', r); } }
+ cx(pl, 0, 2.95, 2.3, 1.3, 1.1, .6); cx(liso, 0, 1.3, 2.04, 1.3, 2.2, .04, BREU);
+ pl.prisma(mz(0, 0, 2.64), [[-.84, 2.42], [.84, 2.42], [.84, 2.5], [.6, 2.62], [.3, 2.7], [0, 2.72], [-.3, 2.7], [-.6, 2.62], [-.84, 2.5]], .09, ANIL, [0, 2.45]);
+ pl.cilindro(P(0, 3.08, 2.6), P(0, 3.08, 2.67), .31 * k, .31 * k, 16, ANIL); liso.cilindro(P(0, 3.08, 2.665), P(0, 3.08, 2.676), .21 * k, .21 * k, 16, [.03, .04, .07]);
+ for (const [w, h] of [[.42, .03], [.03, .42]]) liso.caixa(mz(0, 3.08, 2.682), w, h, .012, FERRO);
+ for (const sx of [-1, 1]) folha((x, y, z) => mz(-sx * .64 + x, .23 + y, 2.1 + z), sx, .635, 2.16, ANIL_PORTA, 'almofada', r);
+ cx(pl, 0, 3.56, 2.34, 4.5, .12, .72); pl.prisma(mz(0, 0, 2.3), [[-2.15, 3.62], [2.15, 3.62], [0, 4.5]], .56, CAL, [0, 3.9]);
+ cx(pl, 0, 3.47, 2.35, 4.4, .06, .66); cx(pl, 0, 3.4, 2.64, 4.3, .09, .07); cx(pl, 0, 3.31, 2.63, 4.24, .035, .05, ANIL);
+ for (const s of [-1, 1]) { cx(pl, s * 1.97, 3.28, 2.655, .46, .1, .1); cx(pl, s * 1.97, .92, 2.655, .44, .08, .1);
+ for (const [dy, w, h, d, z] of [[-.075, 1.96, .06, .62, 2.33], [.07, 2.14, .04, .78, 2.33]]) pl.caixa(M.clone().multiply(I4().makeRotationZ(-s * .388).setPosition(s * (1.2 + .378 * dy), 4.06 + .926 * dy, z)), w, h, d, CAL);
+ pl.prisma(mz(0, 0, 2.585), s > 0 ? [[.9, 3.74], [1.6, 3.74], [.9, 4.03]] : [[-1.6, 3.74], [-.9, 3.74], [-.9, 4.03]], .05, CAL, [s * 1.1, 3.8]); }
+ cx(pl, 0, 4.14, 2, 1.6, .72, 1.6); for (const sx of [-1, 1]) for (const sz of [-1, 1]) cx(pl, sx * .6, 4.75, 2 + sz * .6, .4, .5, .4);
+ const arco = (a, b) => { const pts = b > a ? [[-b, 5], [-a, 5]] : [[-a, 5]]; for (let i = 1; i < 8; i++) pts.push([-a * Math.cos(i / 8 * Math.PI), 5 + a * Math.sin(i / 8 * Math.PI)]);
+ pts.push([a, 5]); if (b > a) pts.push([b, 5]); pts.push([b, 5.5], [-b, 5.5]); return pts; };
+ for (const sz of [-1, 1]) pl.prisma(mz(0, 0, 2 + sz * .6), arco(.4, .8), .4, CAL, [0, 5.48]);
+ for (const sx of [-1, 1]) pl.prisma(M.clone().multiply(I4().makeRotationY(Math.PI / 2).setPosition(sx * .6, 0, 2)), arco(.4, .4), .4, CAL, [0, 5.48]);
+ cx(pl, 0, 5.54, 2, 1.72, .08, 1.72, ANIL); cx(pl, 0, 5.64, 2, 1.9, .12, 1.9);
+ const cant = [[-.8, 2.8], [.8, 2.8], [.8, 1.2], [-.8, 1.2]].map(([x, z]) => P(x, 5.7, z)), apice = P(0, 6.5, 2);
+ for (let i = 0; i < 4; i++) pl.tri(cant[i], cant[(i + 1) % 4], apice, CAL);
+ liso.cilindro(P(0, 6.46, 2), P(0, 6.58, 2), .07 * k, .07 * k, 6, FERRO, { aneis: [[0, .3], [.5, 1], [1, .3]] }); cx(liso, 0, 6.98, 2, .05, .86, .05, FERRO); cx(liso, 0, 7.1, 2, .5, .05, .05, FERRO);
+ cx(of, 0, 5.02, 2, 1.3, .08, .08, [.5, .42, .34]); liso.cilindro(P(0, 4.98, 2), P(0, 4.54, 2), .27 * k, .27 * k, 10, [.2, .15, .07], { aneis: [[0, .3], [.12, .52], [.55, .68], [.85, .88], [1, 1.08]] });
+ liso.cilindro(P(0, 4.62, 2), P(0, 4.46, 2), .035 * k, .05 * k, 5, FERRO);
+ for (const [y, z, d, larguras] of [[.055, 3.05, 1.3, [.9, .7, 1.0, .8]], [.165, 2.8, .7, [.6, .85, .65]]]) { let x0 = -larguras.reduce((a, b) => a + b, 0) / 2;
+ for (const w of larguras) { const g = .8 + r() * .32; pl.caixa(mz(x0 + w / 2, y - r() * .012, z + (r() - .5) * .03).multiply(I4().makeRotationZ((r() - .5) * .012)), w - .018, .11, d - r() * .05, tinge(DEGRAU, g)); x0 += w; } }
+ };
+ const igreja = opts.matriz !== false && scene.getObjectByName('sertao-igrejinha-0'), quinasCal = [];
+ if (igreja) { igreja.updateWorldMatrix(true, false); for (const [x, z] of [[-2, -3.05], [2, -3.05], [-2.15, 2.6], [2.15, 2.6], [-.65, 2.6], [.65, 2.6], [-2.15, 2], [2.15, 2]]) { const c = V3(x, 0, z).applyMatrix4(igreja.matrixWorld); quinasCal.push(new THREE.Vector2(c.x, c.z)); } for (const c of igreja.children) if (c.visible) { c.visible = false; escondidos.push(c); } matriz(igreja.matrixWorld.clone(), 1); }
+ if (opts.matriz !== false && opts.capela !== false) { const [mx, mz2, mh, mr] = opts.capela?.pos ?? [-24, -56.5, 2.2, 10.5], esc = (opts.capela?.altura ?? 19) / 7.3;
+ matriz(I4().makeRotationY(opts.capela?.ry ?? .36).scale(V3(esc, esc, esc)).setPosition(mx, mh - .45, mz2), esc); }
+ desfaz.push(() => { for (const c of escondidos) c.visible = true; });
+ if (opts.praca !== false) {
+ // Só em cima de colisor que já existe ou rente ao chão (até 12 cm): nenhum volume novo na linha de tiro ou de passo.
+ const sobre = (X, Z, ry) => (lx, y, lz) => V3(X + Math.cos(ry) * lx + Math.sin(ry) * lz, y, Z - Math.sin(ry) * lx + Math.cos(ry) * lz);
+ const pote = (p, s = 1) => { const v = .8 + rnd() * .35; liso.cilindro(p, p.clone().add(V3(0, .36 * s, 0)), .17 * s, .17 * s, 9, [.38 * v, .25 * v, .15 * v],
+ { aneis: [[0, .5], [.1, .82], [.38, 1], [.62, .88], [.8, .5], [.9, .42], [1, .56]] }); };
+ const saca = (p, rumo, s = 1) => { const v = .8 + rnd() * .3, e = V3(Math.cos(rumo), 0, Math.sin(rumo)), a = p.clone().addScaledVector(e, -.33 * s).add(V3(0, .17 * s, 0));
+ liso.tipo(1); liso.cilindro(a, a.clone().addScaledVector(e, .66 * s), .2 * s, .2 * s, 10, [.52 * v, .43 * v, .29 * v], { aneis: [[0, .42], [.06, .8], [.2, .98], [.5, 1.06], [.8, .98], [.94, .8], [1, .42]] });
+ for (const f of [-.02, .68]) liso.cilindro(a.clone().addScaledVector(e, f * s), a.clone().addScaledVector(e, (f - .04) * s).add(V3(0, .05 * s, 0)), .07 * s, .03 * s, 5, [.48 * v, .4 * v, .26 * v]); liso.tipo(0); };
+ // Feixe de capim e raquetes de palma: a carga da carroça de tração animal.
+ const capim = (p, rumo) => { const e = V3(Math.cos(rumo), 0, Math.sin(rumo)), t = V3(-e.z, 0, e.x);
+ [[0, .07], [.13, .07], [-.13, .07], [.07, .19], [-.07, .19], [0, .3], [.2, .16], [-.2, .15]].forEach(([dx, dy]) => { const v = .75 + rnd() * .4, a = p.clone().addScaledVector(t, dx).add(V3(0, dy, 0)).addScaledVector(e, -.6 + (rnd() - .5) * .14);
+ liso.cilindro(a, a.clone().addScaledVector(e, 1.2 + (rnd() - .5) * .16).add(V3(0, (rnd() - .5) * .06, 0)), .075, .05, 5, [.5 * v, .5 * v, .2 * v], { aneis: [[0, .8], [.5, 1.1], [1, .5]] }); });
+ for (const f of [-.3, .25]) { const c = p.clone().addScaledVector(e, f).add(V3(0, .17, 0)); liso.cilindro(c.clone().addScaledVector(e, -.02), c.clone().addScaledVector(e, .02), .25, .25, 8, [.42, .34, .2], { tampas: false }); } };
+ const palma = (p, rumo) => { const oval = Array.from({ length: 9 }, (_, i) => [Math.cos(i / 9 * 6.2832) * .15, Math.sin(i / 9 * 6.2832) * .21]);
+ [[0, .03, 0, 1.45, 0], [.2, .05, .1, 1.3, .9], [-.12, .08, .22, 1.2, 2.1], [.1, .2, .05, .5, .4], [-.05, .23, -.12, .35, 1.7]].forEach(([dx, dy, dz, deita, gira]) => { const v = .8 + rnd() * .35;
+ liso.prisma(I4().makeRotationY(rumo + gira).multiply(I4().makeRotationX(deita)).setPosition(p.x + dx, p.y + dy + .04, p.z + dz), oval, .03, [.2 * v, .34 * v, .15 * v]); }); };
+ const lenha = (p, rumo) => { const e = V3(Math.cos(rumo), 0, Math.sin(rumo)), t = V3(-e.z, 0, e.x);
+ [[0, .05], [.1, .05], [-.1, .05], [.05, .13], [-.05, .13], [0, .21]].forEach(([dx, dy]) => { const v = .7 + rnd() * .4, a = p.clone().addScaledVector(t, dx).add(V3(0, dy, 0)).addScaledVector(e, -.42 + (rnd() - .5) * .08);
+ of.cilindro(a, a.clone().addScaledVector(e, .84), .05, .045, 5, [.5 * v, .43 * v, .36 * v]); }); };
+ // Calçada das casas da praça: mercadoria e tralha encostadas na parede da frente e no oitão que dá para o largo.
+ [['sertao-praca-casa-interior-0', 1], ['sertao-praca-casa-interior-1', -1]].forEach(([nome, s]) => { const casa = scene.getObjectByName(nome), pc = casa?.userData?.interior; if (!pc || opts.objetos === false) return;
+ casa.updateWorldMatrix(true, false); const q = quadro(casa.matrixWorld, 0, -(pc.halfD + .14), Math.PI), o0 = q.p(0, 0, 0), o1 = q.p(1, 0, 0), rumo = Math.atan2(o1.z - o0.z, o1.x - o0.x);
+ saca(q.p(s * 2.2, 0, .36), rumo); saca(q.p(s * 2.95, 0, .38), rumo + .15);
+ const b = q.p(s * 1.42, 0, .38), cb = (y) => b.clone().add(V3(0, y, 0)); liso.cilindro(b, cb(.3), .19, .25, 10, [.6, .47, .24], { aneis: [[0, .9], [.15, 1], [.85, 1], [1, 1.07]] }); liso.cilindro(cb(.27), cb(.37), .23, .08, 8, [.82, .56, .16]);
+ lenha(q.p(-s * 2.55, 0, .32), rumo); pote(q.p(-s * 1.5, 0, .36), .95); pote(q.p(-s * 1.92, 0, .32), .66);
+ const c0 = q.p(-s * 3.3, 0, .42); pote(V3(c0.x, caixote(c0.x, c0.z, .34, rumo + .12, 0), c0.z), .4);
+ const qL = quadro(casa.matrixWorld, s * (pc.halfW + .14), 0, s * Math.PI / 2); feixe(qL, 2.3, .3); pote(qL.p(-2.4, 0, .34), 1.05); pote(qL.p(-2.0, 0, .3), .7); });
+ const naZona = (x, z, L) => zonas.some(([zx, zz]) => Math.hypot(x - zx, z - zz) < 5.4 + L / 2);
+ const tabua = (x, z, L, ry, esteira = false) => { if (!naArena(x, z, 1) || naZona(x, z, L) || (!esteira && dentroDeCasa(x, z))) return; const v = .8 + rnd() * .3;
+ of.caixa(new THREE.Matrix4().makeRotationY(ry).setPosition(x, esteira ? .015 : .03, z), L, esteira ? .03 : .05, esteira ? 1 : .2, esteira ? [.8 * v, .68 * v, .4 * v] : [.6 * v, .53 * v, .46 * v]); };
+ const mureta = sobre(4, -8, .04), carga = sobre(-9, -8, .16), feira = sobre(-3, 9, -.12);
+ pote(mureta(-2.1, 1.45, 0)); pote(mureta(-1.6, 1.45, .05), .8); pote(mureta(2.1, 1.45, -.03), 1.1); saca(mureta(.7, 1.45, 0), .04);
+ saca(carga(-.9, 1.1, .35), .5); saca(carga(-.75, 1.1, -.35), .1); pote(carga(1.05, 1.05, .55)); lenha(carga(.75, 1.05, -.2), 1.3);
+ saca(feira(-.85, 1.05, .3), 1.2); pote(feira(-.9, 1.05, -.4), .9); pote(feira(-.35, 1.05, -.45), .7);
+ for (const [x, z] of [[12, -12], [-17, 13], [-12, -33], [14, 34]]) { pote(V3(x - .18, 1.08, z + .12), .85); saca(V3(x + .2, 1.08, z - .15), x * .7, .75); }
+ scene.traverse((o) => { if (o.name !== 'carroca') return; o.updateWorldMatrix(true, false); const w = (x, z) => V3(x, opts.carroca === false ? 1.575 : 1.03, z).applyMatrix4(o.matrixWorld), ry = o.rotation.y;
+ saca(w(-1.0, .55), .4 - ry); saca(w(-.95, -.3), 1.5 - ry, .9); saca(w(-.9, .15).add(V3(0, .36, 0)), .9 - ry, .9); saca(w(-.3, 1.0), .1 - ry, .85); pote(w(1.15, .95), .8); capim(w(.5, -.55), 1.5708 - ry); palma(w(.75, .5), -ry); });
+ [[-2.2, 6.2, 1.9, .5], [-1.7, 6.5, 1.6, .62], [5.2, 4.6, 2.1, -.3], [-6.2, -5.4, 1.8, 1.2], [-5.6, -5.1, 1.5, 1.05], [2.4, -10.2, 2, .1], [10.4, 6.4, 1.7, -.9], [-11.5, 3.3, 2.2, .2],
+ [6.3, -3.2, 1.6, 2.1], [-4.4, 12.3, 1.9, -.4], [12.6, -4.2, 1.8, .8], [-12.8, -11.3, 2, -.2]].forEach(([x, z, L, ry]) => tabua(x, z, L, ry));
+ [[-11.5, 10.7, 1.7, 0], [11.5, 10.7, 1.7, .05], [-9.7, -29.8, 1.6, .12], [10.3, -30.2, 1.6, -.17]].forEach(([x, z, L, ry]) => tabua(x, z, L, ry, true));
+ // Cerca de faxina logo depois dos limites leste e oeste: mourão de 15 cm para não cintilar visto da praça.
+ for (const sx of [-1, 1]) { let trecho = null;
+ for (let z = B.minZ - 1; z < B.maxZ + 1;) { const passo = .42 + rnd() * .2, x = sx * (B.maxX + 1.05 + Math.sin(z * .21) * .25), portao = [-1.6, 20.2, -33].some((zp) => Math.abs(z - zp) < 2.6) || rngDe(900 + Math.floor(z / 5.5) * 13 + sx)() < .16;
+ if (portao) { trecho = null; z += passo; continue; }
+ const h = 1.2 + rnd() * .55, v = .7 + rnd() * .4, a = V3(x, -.1, z), b = V3(x + (rnd() - .5) * .16, h, z + (rnd() - .5) * .16);
+ of.cilindro(a, b, .085, .065, 3, [.5 * v, .45 * v, .4 * v], { tampas: false });
+ if (!trecho) trecho = z; else if (z - trecho > 3.2) { for (const y of [.5, 1.02]) of.caixa(new THREE.Matrix4().makeRotationZ((rnd() - .5) * .05).setPosition(x + sx * .09, y, (z + trecho) / 2), .07, .11, z - trecho + .3, [.42, .37, .33]); trecho = z; }
+ z += passo; } }
+ }
+ if (opts.carroca !== false) {
+ // Carroça no mesmo volume do colisor; a malha de caixas do mapa fica oculta enquanto o kit estiver ligado.
+ const cars = [], sombras = [], ocultos = [], ferro = [.15, .14, .14]; let car = null;
+ scene.traverse((o) => { if (o.name !== 'carroca') return; o.updateWorldMatrix(true, false); cars.push(car = oficina());
+ const W = o.matrixWorld, r = rngDe(Math.round(o.position.x * 13 + o.position.z * 7) + 99), I4 = () => new THREE.Matrix4();
+ for (const c of o.children) if (c.visible) { c.visible = false; ocultos.push(c); }
+ const em = (x, y, z) => I4().setPosition(x, y, z).premultiply(W), P = (x, y, z) => V3(x, y, z).applyMatrix4(W), tom = (k = 1) => { const v = (.8 + r() * .35) * k; return [1.05 * v, .92 * v, .76 * v]; };
+ // Carroça de tração animal: um eixo só, caixa baixa de tábua pintada com filete, dois varais retos e descanso.
+ const pintura = tinge([[.15, .26, .4], [.19, .33, .22], [.15, .26, .4]][(cars.length - 1) % 3], 1), filete = [.6, .5, .26];
+ const roda = (x, cy, cz) => { const n = 16, R = .6, rc = R - .065, passo = 2 * rc * Math.tan(Math.PI / n) + .012, fora = Math.sign(x); let camba = tom();
+ for (let i = 0; i < n; i++) { const a = (i + .5) / n * 6.2832, sn = Math.sin(a), cs = Math.cos(a); if (i % 4 === 0) camba = tom(sn < -.5 ? 1.15 : .95);
+ car.caixa(I4().makeBasis(V3(1, 0, 0), V3(0, sn, cs), V3(0, -cs, sn)).setPosition(x, cy + rc * sn, cz + rc * cs).premultiply(W), .13, .13, passo, camba, [0, 1, 2, 3]); }
+ car.cilindro(P(x - .07, cy, cz), P(x + .07, cy, cz), R + .004, R + .004, n, ferro, { tampas: false });
+ for (let i = 0; i < 8; i++) { const a = (i + .5) / 8 * 6.2832, sn = Math.sin(a), cs = Math.cos(a);
+ car.cilindro(P(x, cy + .1 * sn, cz + .1 * cs), P(x, cy + (R - .12) * sn, cz + (R - .12) * cs), .046, .046, 5, tom(), { tampas: false, aneis: [[0, 1.3], [.14, 1.3], [.2, .95], [1, .9]] }); }
+ car.cilindro(P(x - .17, cy, cz), P(x + .17, cy, cz), .12, .12, 10, tom(.8), { aneis: [[0, .6], [.14, .8], [.24, 1.08], [.42, 1.2], [.58, 1.2], [.76, 1.08], [.86, .8], [1, .6]] });
+ car.cilindro(P(x + fora * .15, cy, cz), P(x + fora * .23, cy, cz), .05, .04, 6, ferro); };
+ for (let i = 0; i < 10; i++) car.caixa(em(-1.395 + i * .31, 1 + r() * .014, (r() - .5) * .05), .284, .05, 2.96 + r() * .07, tom());
+ for (const sx of [-1, 1]) { for (let j = 0; j < 2; j++) pin.caixa(em(sx * 1.55, 1.125 + j * .185, (r() - .5) * .04), .04, .175, 3.04, tinge(pintura, .85 + r() * .3));
+ pin.caixa(em(sx * 1.574, 1.345, 0), .012, .028, 2.9, filete);
+ for (const z of [-1.25, 0, 1.25]) car.caixa(em(sx * 1.6, 1.24, z), .06, .62, .07, tom(.9)); }
+ for (const sz of [-1, 1]) { for (let j = 0; j < 2; j++) pin.caixa(em((r() - .5) * .04, 1.125 + j * .185, sz * 1.5), 3.06, .175, .04, tinge(pintura, .85 + r() * .3));
+ pin.caixa(em(0, 1.345, sz * 1.524), 2.9, .028, .012, filete); for (const sx of [-1, 1]) car.caixa(em(sx * 1.5, 1.24, sz * 1.545), .07, .62, .05, tom(.9)); }
+ for (const x of [-.9, .9]) { car.caixa(em(x, .92, 0), .11, .13, 3, tom(.85)); car.caixa(em(x, .76, 0), .12, .2, .46, tom(.8)); }
+ for (const z of [-1.3, 1.3]) car.caixa(em(0, .92, z), 3.1, .1, .1, tom(.85));
+ car.caixa(em(0, .62, 0), 3.3, .13, .13, tom(.8)); for (const sx of [-1, 1]) roda(sx * 1.74, .6, 0);
+ for (const sx of [-1, 1]) { car.cilindro(P(sx * .36, .93, 1.35), P(sx * .34, .76, -4.7), .05, .038, 6, tom()); car.cilindro(P(sx * .34, .765, -4.56), P(sx * .34, .757, -4.72), .044, .042, 6, ferro); }
+ car.caixa(em(0, .86, -1.72), .86, .07, .09, tom(.9)); car.caixa(em(0, .79, -3.4), .78, .05, .06, tom(.9));
+ car.cilindro(P(.3, .78, -3.9), P(.36, 0, -4.05), .028, .024, 5, tom(.9)); car.cilindro(P(-.6, .9, 1.38), P(-.64, 0, 1.46), .03, .026, 5, tom(.9));
+ const corda = [.52, .44, .28]; for (let i = 0; i < 8; i++) { const a0 = i / 8 * 6.2832, a1 = (i + 1) / 8 * 6.2832, pt = (a) => P(-.34 + Math.sin(a) * .02, .62 + Math.cos(a) * .15, -2.6 + Math.sin(a) * .13); car.cilindro(pt(a0), pt(a1), .02, .02, 4, corda, { tampas: false }); }
+ // Só esta malha magra, escondida dentro das peças, lança sombra: a carroça detalhada triplicava o passe de sombra.
+ const sb = oficina(), c0 = [.3, .3, .3]; sombras.push(sb); sb.caixa(em(0, 1, 0), 3, .02, 2.9, c0); sb.cilindro(P(0, .9, 1.3), P(0, .76, -4.7), .03, .02, 4, c0);
+ for (const s of [-1, 1]) { sb.caixa(em(s * 1.55, 1.22, 0), .015, .36, 3, c0); sb.caixa(em(0, 1.22, s * 1.5), 3, .36, .015, c0); }
+ for (const sx of [-1, 1]) { const x = sx * 1.74; sb.cilindro(P(x - .03, .6, 0), P(x + .03, .6, 0), .6, .6, 16, c0, { tampas: false });
+ for (let i = 0; i < 4; i++) { const a = (i + .5) / 8 * 6.2832, sn = Math.sin(a), cs = Math.cos(a); sb.caixa(I4().makeBasis(V3(1, 0, 0), V3(0, sn, cs), V3(0, -cs, sn)).setPosition(x, .6, 0).premultiply(W), .02, 1.1, .02, c0); } } });
+ // Barris do mapa eram cilindros lisos quase pretos: aduelas com bojo e arcos de ferro no mesmo volume.
+ scene.traverse((o) => { if (o.name !== 'obstaculo-barris-empilhados') return; o.updateWorldMatrix(true, true); cars.push(car = oficina()); const r = rngDe(417), bojo = [[0, .86], [.2, 1], [.5, 1.09], [.8, 1], [1, .86]];
+ for (const c of o.children) { const g = c.geometry?.parameters; if (!c.isMesh || !c.visible || c.geometry.type !== 'CylinderGeometry') continue; c.visible = false; ocultos.push(c);
+ const a = V3(0, -g.height / 2, 0).applyMatrix4(c.matrixWorld), b = V3(0, g.height / 2, 0).applyMatrix4(c.matrixWorld), rr = g.radiusTop * .915, v = .85 + r() * .3;
+ car.cilindro(a, b, rr, rr, 14, [1.0 * v, .82 * v, .62 * v], { aneis: bojo });
+ for (const [f, kb] of [[.08, .93], [.27, 1.03], [.73, 1.03], [.92, .93]]) car.cilindro(a.clone().lerp(b, f - .022), a.clone().lerp(b, f + .022), rr * kb * 1.012, rr * kb * 1.012, 14, ferro, { tampas: false }); } });
+ for (const c of [...cars, ...sombras]) { const gc = c.geo(), mc = new THREE.Mesh(gc, mat), magra = sombras.includes(c); mc.name = magra ? 'sertao-hd-carrocas-sombra' : 'sertao-hd-carrocas';
+ mc.castShadow = magra || c === cars[cars.length - 1]; mc.receiveShadow = !magra; mc.userData.nonSolidSurface = true; grupo.add(mc); lixo.push(gc); }
+ desfaz.push(() => { for (const c of ocultos) c.visible = true; });
+ }
+ if (opts.contato !== false) {
+ // Sombra de contato: borrão escuro rente ao chão em volta de todo colisor que pisa nele (parede, caixote, carroça).
+ const cv = document.createElement('canvas'); cv.width = cv.height = 64; const cx = cv.getContext('2d'), im = cx.createImageData(64, 64);
+ for (let y = 0; y < 64; y++) for (let x = 0; x < 64; x++) { const u = Math.min(x, 63 - x) / 31.5, w = Math.min(y, 63 - y) / 31.5, i = (y * 64 + x) * 4; im.data[i] = im.data[i + 1] = im.data[i + 2] = 255; im.data[i + 3] = 255 * suave(0, .3, u) * suave(0, .3, w); }
+ cx.putImageData(im, 0, 0); const tex = new THREE.CanvasTexture(cv); tex.name = 'hd-cen-contato';
+ const pisam = cols.filter((c) => c.minY < .15 && Math.max(c.maxX - c.minX, c.maxZ - c.minZ) < 13), gp = new THREE.PlaneGeometry(1, 1); gp.rotateX(-Math.PI / 2);
+ const mp = new THREE.MeshBasicMaterial({ color: 0x140b06, map: tex, transparent: true, opacity: opts.contato?.forca ?? .3, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -1, polygonOffsetUnits: -1, name: 'hd-cen-contato' });
+ const im2 = lote(gp, mp, pisam.length, 'contato'); im2.receiveShadow = false; lixo.push(gp, mp, tex);
+ pisam.forEach((c, i) => { const w = c.hx ? c.hx * 2 : c.maxX - c.minX, d = c.hz ? c.hz * 2 : c.maxZ - c.minZ, m = .5 + Math.min(.45, .12 * Math.min(w, d));
+ obj.position.set(c.hx ? c.cx : (c.minX + c.maxX) / 2, .014, c.hz ? c.cz : (c.minZ + c.maxZ) / 2); obj.rotation.set(0, c.hx ? c.ry || 0 : 0, 0); obj.scale.set(w + m, 1, d + m); obj.updateMatrix(); im2.setMatrixAt(i, obj.matrix); });
+ im2.instanceMatrix.needsUpdate = true; im2.computeBoundingSphere();
+ }
+ if (opts.festa !== false) {
+ // Poste de lampião colado na quina das casas da praça e bandeirolas entre eles: tudo que é novo fica acima de 2,2 m.
+ const quina = (tag, sx, sz) => { const c = (mundo.colliders || []).find((q) => q.tag === tag); return c ? V3(sx > 0 ? c.maxX + .13 : c.minX - .13, 0, sz > 0 ? c.maxZ + .13 : c.minZ - .13) : null; };
+ const pts = [[3, 1, -1], [2, 1, 1], [4, -1, 1], [5, -1, -1], [6, -1, 1]].map(([id, sx, sz]) => quina(`sertao-casa-paupique-${id}`, sx, sz));
+ const TOPO = 4.75, panos = [[.5, .15, .11], [.6, .47, .18], [.18, .3, .4], [.6, .55, .46], [.24, .36, .26]], DESBOTE = [.5, .46, .4];
+ for (const p of pts) { if (!p) continue; const v = .8 + rnd() * .3, para = V3(-p.x, 0, -p.z).normalize();
+ of.cilindro(V3(p.x, -.1, p.z), V3(p.x + (rnd() - .5) * .08, TOPO + .1, p.z + (rnd() - .5) * .08), .085, .06, 6, [.52 * v, .46 * v, .4 * v]);
+ const braco = V3(p.x, 4.05, p.z).addScaledVector(para, .55); of.cilindro(V3(p.x, 4.12, p.z), braco, .03, .025, 4, [.2, .18, .17], { tampas: false });
+ liso.cilindro(braco.clone().add(V3(0, -.42, 0)), braco.clone().add(V3(0, -.04, 0)), .075, .075, 6, [.09, .085, .08], { aneis: [[0, 1], [.12, 1.05], [.14, .78], [.72, .78], [.74, 1.1], [.9, .5], [1, .12]] });
+ liso.cilindro(braco.clone().add(V3(0, -.36, 0)), braco.clone().add(V3(0, -.16, 0)), .066, .066, 6, [3.4, 2.1, .8], { tampas: false }); }
+ for (const [i, j] of [[0, 1], [1, 2], [2, 3], [2, 4]]) { const a = pts[i], b = pts[j]; if (!a || !b) continue;
+ const L = a.distanceTo(b), nseg = Math.ceil(L / .52), cede = Math.min(1.15, L * .05), em = (t) => V3(a.x + (b.x - a.x) * t, TOPO - cede * 4 * t * (1 - t), a.z + (b.z - a.z) * t);
+ for (let k = 0; k < nseg; k++) { const p0 = em(k / nseg), p1 = em((k + 1) / nseg); liso.cilindro(p0, p1, .012, .012, 3, [.2, .18, .16], { tampas: false });
+ if (k % 7 === 6) continue; const u0 = p0.clone().lerp(p1, .1), u1 = p0.clone().lerp(p1, .9), base = panos[(k * 3 + i) % panos.length], g = .7 + rnd() * .4, d = .3 + rnd() * .3;
+ const tom = base.map((c, j) => (c + (DESBOTE[j] - c) * d) * g), h = .3 + rnd() * .07, n = V3(-(b.z - a.z) / L, 0, (b.x - a.x) / L), vento = (rnd() - .5) * .22, dobra = .02 + rnd() * .03;
+ const pt = (t, y, f) => u0.clone().lerp(u1, t).add(V3(0, -h * y, 0)).addScaledVector(n, vento * y + dobra * f);
+ const m0 = pt(.02, .55, -1), mc = pt(.5, .5, 1.3), m1 = pt(.98, .55, -1), b0 = pt(.06 + rnd() * .08, 1, .4), b1 = pt(.94 - rnd() * .08, .96 + rnd() * .1, -.6), claro = tom.map((c) => c * 1.12);
+ liso.tri(u0, u1, mc, tom); liso.tri(u0, mc, m0, claro); liso.tri(u1, m1, mc, tom); liso.tri(m0, mc, b0, tom); liso.tri(mc, m1, b1, claro); } }
+ }
+ // Xique-xique: touceira de cacto baixo (até 45 cm) junto das macambiras.
+ for (const [s, xf, z0, z1] of xiques) for (const f of [.2, .82]) { const cx0 = xf + s * .34, cz0 = z0 + (z1 - z0) * f;
+ for (let i = 0; i < 6; i++) { const ang = i / 6 * 6.283 + rnd(), d = .08 + rnd() * .14, h = .2 + rnd() * .24, v = .8 + rnd() * .35, ca = Math.cos(ang), sa = Math.sin(ang) * .6;
+ const p0 = V3(cx0 + ca * d * .3, 0, cz0 + sa * d * .3), p1 = V3(cx0 + ca * d, .07, cz0 + sa * d), p2 = V3(cx0 + ca * (d + .05), h, cz0 + sa * (d + .05));
+ liso.cilindro(p0, p1, .04, .042, 5, [.2 * v, .3 * v, .17 * v], { tampas: false }); liso.cilindro(p1, p2, .042, .03, 5, [.22 * v, .33 * v, .18 * v]); } }
+ if (opts.chamines !== false) scene.traverse((o) => { const g = o.geometry?.parameters;
+ if (!o.isMesh || o.isInstancedMesh || !/^parede-casa-\d+$/.test(o.name) || !(g?.width > 2.5) || !/paupique/.test(o.parent?.name || '')) return;
+ o.updateWorldMatrix(true, false); const id = +o.name.slice(-1), x = (id % 2 ? 1 : -1) * g.width * .2, z = (id % 3 - 1) * g.depth * .24, y = g.height / 2, em = (dy) => new THREE.Matrix4().setPosition(x, y + dy, z).premultiply(o.matrixWorld);
+ liso.caixa(em(.95), .46, 1.15, .46, [.6, .52, .43]); liso.caixa(em(1.56), .6, .08, .6, [.3, .21, .16]); liso.caixa(em(1.67), .3, .14, .3, [.17, .14, .12]); });
+ if (opts.flora !== false && opts.arbustos !== false) {
+ const ga = pedraGeo(0, 41, .3), n = 47, im = lote(ga, matPedra, n, 'arbustos'); lixo.push(ga);
+ const arbusto = (i, x, z) => {
+ if (!naArena(x, z, .6) || !livre(x, z, .7) || dentroDeCasa(x, z) || zonas.some(([zx, zz]) => Math.hypot(x - zx, z - zz) < 5.4)) { obj.scale.setScalar(0); obj.updateMatrix(); im.setMatrixAt(i, obj.matrix); return; }
+ const r0 = .5 + rnd() * .65, y = terreno(x, z);
+ obj.position.set(x, y + r0 * .42, z); obj.rotation.set(0, rnd() * 6.283, 0); obj.scale.set(r0 * (1 + rnd() * .5), r0 * (.62 + rnd() * .3), r0 * (1 + rnd() * .4)); obj.updateMatrix(); im.setMatrixAt(i, obj.matrix);
+ const v = .22 + rnd() * .14, w = rnd(); im.setColorAt(i, cor.setRGB(v * (1.15 + .2 * w), v * (1.05 + .05 * w), v * (.62 - .12 * w)));
+ for (let k = 0; k < 3; k++) { const ang = rnd() * 6.283, abre = .35 + rnd() * .7, L = r0 * (1.5 + rnd() * .7), d = V3(Math.cos(ang) * Math.sin(abre), Math.cos(abre), Math.sin(ang) * Math.sin(abre)), a = V3(x, y, z), m2 = a.clone().addScaledVector(d, L * .55);
+ of.cilindro(a, m2, .055, .045, 3, [.36, .31, .26], { tampas: false }); of.cilindro(m2, m2.clone().addScaledVector(d, L * .45).add(V3((rnd() - .5) * .3, .12, (rnd() - .5) * .3)), .045, .03, 3, [.4, .34, .28], { tampas: false }); }
+ };
+ if (opts.bordas !== false) [[-18, -8], [18, -8], [-17, 16]].forEach(([x, z], i) => arbusto(i, x, z));
+ else for (let i = 0; i < 3; i++) { obj.scale.setScalar(0); obj.updateMatrix(); im.setMatrixAt(i, obj.matrix); }
+ for (let i = 3; i < n; i++) { const emX = i % 2 === 0, s = rnd() < .5 ? -1 : 1, fora = 1.7 + Math.pow(rnd(), 1.4) * 4.2;
+ const x = emX ? (rnd() * 2 - 1) * (B.maxX + 2) : s * (B.maxX + fora), z = emX ? s * (B.maxZ + fora + 1.2) : (rnd() * 2 - 1) * (B.maxZ + 2);
+ if (emX && Math.abs(x) < 9.5) { obj.scale.setScalar(0); obj.updateMatrix(); im.setMatrixAt(i, obj.matrix); continue; }
+ arbusto(i, x, z); }
+ im.instanceMatrix.needsUpdate = true; im.instanceColor.needsUpdate = true; im.computeBoundingSphere();
+ }
+ if (panos.length) {
+ // Letreiro de pintor de parede: um atlas só, letra a letra com tremor, falha de tinta e escorrido.
+ const cv = document.createElement('canvas'); cv.width = cv.height = 1024; const c = cv.getContext('2d', { willReadFrequently: true }), rg = rngDe(1877), escorridos = [];
+ c.textAlign = 'center'; c.textBaseline = 'middle';
+ const ANIL = '#1c3f8f', OXIDO = '#8a5316', PRETO = '#191613', SERIFA = { fonte: 'Georgia, "Times New Roman", serif', peso: '900' }, GROSSA = { fonte: '"Arial Black", Impact, sans-serif', peso: '900', folga: 1.04 };
+ const pinta = (txt, [x, y, w, h], cor, { sombra = null, fonte = 'Impact, "Arial Black", sans-serif', peso = '', escorre = .25, folga = 1.08 } = {}) => {
+ const linhas = txt.split('\n'), lh = h / linhas.length;
+ linhas.forEach((ln, li) => { let px = lh * .74; c.font = `${peso} ${px}px ${fonte}`; const larg = c.measureText(ln).width * folga; if (larg > w - 28) px *= (w - 28) / larg; c.font = `${peso} ${px}px ${fonte}`;
+ let cx = x + (w - c.measureText(ln).width * folga) / 2; const by = y + li * lh + lh * .5;
+ for (const ch of ln) { const cw = c.measureText(ch).width * folga, jy = (rg() - .5) * px * .06, ja = (rg() - .5) * .08, js = 1 + (rg() - .5) * .08;
+ c.save(); c.translate(cx + cw / 2, by + jy); c.rotate(ja); c.scale(js, js);
+ if (sombra) { c.fillStyle = sombra; c.fillText(ch, px * .045, px * .045); }
+ c.fillStyle = cor; c.fillText(ch, 0, 0); c.restore();
+ if (ch !== ' ' && ch !== '·' && rg() < escorre) escorridos.push([cx + cw * (.3 + rg() * .4), by + px * .3, Math.min(px * (.2 + rg() * .55), y + h - 4 - (by + px * .3)), cor]);
+ cx += cw; } }); };
+ pinta('BODEGA', RT.bodega, ANIL, GROSSA); pinta('BARBEARIA', RT.barbearia, PRETO, SERIFA); pinta('MERCEARIA', RT.mercearia, PRETO, { ...GROSSA, escorre: .12 });
+ pinta('VOTE 00', [RT.vote[0] + 14, RT.vote[1] + 8, RT.vote[2] - 28, RT.vote[3] - 16], PRETO); c.strokeStyle = ANIL; c.lineWidth = 7; c.strokeRect(RT.vote[0] + 9, RT.vote[1] + 9, RT.vote[2] - 18, RT.vote[3] - 18);
+ pinta('FORRÓ HOJE', RT.forro, ANIL, { ...GROSSA, sombra: OXIDO, escorre: .3 }); pinta('VENDE-SE\nQUEIJO E RAPADURA', RT.queijo, OXIDO, { ...GROSSA, sombra: PRETO }); pinta('FIADO\nSÓ AMANHÃ', RT.fiado, PRETO, SERIFA);
+ pinta('FARINHA · FEIJÃO · CARNE DE SOL', RT.secos, ANIL, { ...GROSSA, escorre: .1 }); pinta('CABELO E BARBA', RT.cabelo, PRETO, { ...GROSSA, escorre: 0 });
+ pinta('Nº 27', RT.n27, PRETO, { escorre: 0 }); pinta('Nº 104', RT.n104, ANIL, { escorre: 0 }); pinta('12', RT.n12, PRETO, { escorre: 0 });
+ pinta('GRAÇA\nALCANÇADA', RT.graca, ANIL, { fonte: 'Georgia, serif', peso: 'italic 700', escorre: .1 });
+ { const [x, y, w, h] = RT.exvoto; c.fillStyle = ANIL; c.save(); c.translate(x + w / 2, y + h * .45); c.rotate(-.03); c.fillRect(-9, -h * .36, 18, h * .72); c.fillRect(-w * .27, -h * .17, w * .54, 17); c.restore();
+ c.beginPath(); c.ellipse(x + w / 2, y + h * .86, w * .3, 11, 0, Math.PI, 0); c.fill(); for (const a of [-1, 1]) for (const b of [0, 1]) c.fillRect(x + w / 2 + a * (w * .24 + b * 12) - 2, y + h * .1 + b * 10, 4, 13); }
+ for (const [dx, dy, len, cor] of escorridos) { if (len < 6) continue; const g = c.createLinearGradient(0, dy, 0, dy + len); g.addColorStop(0, cor); g.addColorStop(1, `${cor}00`); c.fillStyle = g; c.fillRect(dx - 1.5, dy, 3, len); c.beginPath(); c.arc(dx, dy + len * .8, 2.2, 0, 6.3); c.fill(); }
+ const img = c.getImageData(0, 0, 1024, 1024), d = img.data, G = 48, grade = Float32Array.from({ length: (G + 2) * (G + 2) }, () => rg());
+ for (let yy = 0; yy < 1024; yy++) { const fy = yy / 1024 * G, iy = fy | 0, ty = fy - iy, faixa = .86 + .14 * Math.sin(yy * 1.9 + Math.sin(yy * .13) * 4);
+ for (let xx = 0; xx < 1024; xx++) { const i = (yy * 1024 + xx) * 4 + 3; if (!d[i]) continue; const fx = xx / 1024 * G, ix = fx | 0, tx = fx - ix, a = iy * (G + 2) + ix, b = a + G + 2;
+ const nn = (grade[a] * (1 - tx) + grade[a + 1] * tx) * (1 - ty) + (grade[b] * (1 - tx) + grade[b + 1] * tx) * ty;
+ d[i] *= Math.min(1, .82 + nn * .36) * (.62 + .38 * faixa) * (rg() < .05 ? rg() : 1); } }
+ c.putImageData(img, 0, 0);
+ { const [x, y, w, h] = RT.chita; c.fillStyle = '#1e5f86'; c.fillRect(x + 4, y + 4, w - 8, h - 8);
+ for (let i = 0; i < 46; i++) { const fx = x + 16 + rg() * (w - 32), fy = y + 14 + rg() * (h - 44), rr = 7 + rg() * 7;
+ c.fillStyle = '#2f7a46'; c.beginPath(); c.ellipse(fx + rr, fy + rr * .8, rr * .9, rr * .4, .6, 0, 6.3); c.fill();
+ c.fillStyle = ['#e9d9b0', '#d9892a', '#c95a7a', '#f2efe2'][i % 4]; for (let p = 0; p < 5; p++) { c.beginPath(); c.arc(fx + Math.cos(p * 1.257) * rr * .6, fy + Math.sin(p * 1.257) * rr * .6, rr * .5, 0, 6.3); c.fill(); }
+ c.fillStyle = '#e8c53a'; c.beginPath(); c.arc(fx, fy, rr * .3, 0, 6.3); c.fill(); }
+ c.globalCompositeOperation = 'destination-out'; for (let i = 0; i <= 9; i++) { c.beginPath(); c.arc(x + 4 + i * (w - 8) / 9, y + h - 4, (w - 8) / 18 * .72, 0, 6.3); c.fill(); } c.globalCompositeOperation = 'source-over'; }
+ { const [x, y, w, h] = RT.fitas; let fx = x + 6, n = 0; while (fx < x + w - 20) { const fw = 9 + rg() * 7; c.fillStyle = ['#b8432f', '#e0b33a', '#2f6fa8', '#2e8a57', '#d2c9b2', '#d4578a'][n++ % 6]; c.fillRect(fx, y + 4, fw, h * (.7 + rg() * .27) - 8); fx += fw + 3 + rg() * 3; } }
+ const tex = new THREE.CanvasTexture(cv); tex.colorSpace = THREE.SRGBColorSpace; tex.anisotropy = 8; tex.name = 'hd-cen-letreiros'; tex.onUpdate = () => { cv.width = cv.height = 0; tex.onUpdate = null; };
+ const Pq = [], Uq = [], Nq = [], Iq = [], vq = new THREE.Vector3(), nq = new THREE.Vector3();
+ for (const { m, w, h, r: [rx, ry, rw, rh] } of panos) { const b = Pq.length / 3; nq.set(0, 0, 1).transformDirection(m);
+ for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { vq.set(sx * w / 2, sy * h / 2, 0).applyMatrix4(m); Pq.push(vq.x, vq.y, vq.z); Nq.push(nq.x, nq.y, nq.z); Uq.push((rx + (sx > 0 ? rw - 2 : 2)) / 1024, 1 - (ry + (sy > 0 ? 2 : rh - 2)) / 1024); }
+ Iq.push(b, b + 1, b + 2, b, b + 2, b + 3); }
+ const gq = new THREE.BufferGeometry(); gq.setAttribute('position', new THREE.Float32BufferAttribute(Pq, 3)); gq.setAttribute('normal', new THREE.Float32BufferAttribute(Nq, 3)); gq.setAttribute('uv', new THREE.Float32BufferAttribute(Uq, 2)); gq.setIndex(Iq); gq.computeBoundingSphere();
+ const matL = new THREE.MeshStandardMaterial({ map: tex, transparent: true, alphaTest: .03, roughness: 1, depthWrite: false, side: THREE.DoubleSide, forceSinglePass: true, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2, name: 'hd-cen-letreiro' });
+ // A tinta herda o grão do reboco e falha em placas presas ao mundo; o pano (canto do atlas) fica inteiro.
+ matL.onBeforeCompile = (sh) => { sh.uniforms.hdDet = { value: kit.pbrTex('hd_sertao/white_rough_plaster_cor') };
+ sh.vertexShader = sh.vertexShader.replace('#include ', '#include \nvarying vec3 vHdPos;').replace('#include ', '#include \nvHdPos = (modelMatrix * vec4(transformed, 1.0)).xyz;');
+ sh.fragmentShader = sh.fragmentShader.replace('#include ', `#include \nvarying vec3 vHdPos; uniform sampler2D hdDet;${kit.RUIDO_GLSL || ''}`).replace('#include ', `#include
+ { float hdPano = step(0.455, vMapUv.x) * step(vMapUv.y, 0.193); vec2 hdQ = vec2(vHdPos.x + vHdPos.z, vHdPos.y);
+ float hdG = dot(texture2D(hdDet, hdQ / 1.1).rgb, vec3(0.3, 0.59, 0.11)) / 0.61;
+ float hdF = smoothstep(0.2, 0.4, hdN(hdQ * 2.3 + 7.0) * 0.6 + hdN(hdQ * 9.0) * 0.4 + clamp(hdG, 0.0, 1.2) * 0.25);
+ diffuseColor.rgb *= mix(0.86 * clamp(hdG, 0.75, 1.12), 0.8, hdPano); diffuseColor.a *= mix(mix(0.72, 1.0, hdF), 1.0, hdPano); }`); };
+ matL.customProgramCacheKey = () => 'sertao-hd-letreiro4';
+ const letras = new THREE.Mesh(gq, matL); letras.name = 'sertao-hd-letreiros'; letras.receiveShadow = true; letras.userData.nonSolidSurface = true; grupo.add(letras); lixo.push(gq, matL, tex);
+ const placa = grupo.getObjectByName('sertao-hd-placa-letras');
+ if (placa) { const m2 = matL.clone(); m2.map = placa.material.map; m2.onBeforeCompile = matL.onBeforeCompile; m2.customProgramCacheKey = matL.customProgramCacheKey; placa.material = m2; lixo.push(m2); }
+ }
+ let matTelha = null; scene.traverse((o) => { if (!o.isMesh) return; for (const m of Array.isArray(o.material) ? o.material : [o.material]) if (!matTelha && m?.userData?.hdLaje) matTelha = m; });
+ // Cal nova sobre reboco: branca, com a pincelada da brocha e só o pé descascado e respingado de terra.
+ const matCal = new THREE.MeshStandardMaterial({ color: 0xffffff, vertexColors: true, roughness: .95, normalMap: kit.pbrTex('hd_sertao/white_rough_plaster_normal'), name: 'hd-cen-cal' }); matCal.normalScale.set(1.5, 1.5); lixo.push(matCal);
+ if (kit.projetaMundo) { kit.projetaMundo(matCal, 1.3); const uvMundo = matCal.onBeforeCompile;
+ while (quinasCal.length < 8) quinasCal.push(new THREE.Vector2(9999, 9999));
+ matCal.onBeforeCompile = (sh) => { uvMundo(sh); sh.uniforms.hdDet = { value: kit.pbrTex('hd_sertao/white_rough_plaster_cor') }; sh.uniforms.hdQuinas = { value: quinasCal };
+ sh.vertexShader = sh.vertexShader.replace('#include ', '#include \nvarying vec3 vHdPos;').replace('#include ', '#include \nvHdPos = (modelMatrix * vec4(transformed, 1.0)).xyz;');
+ sh.fragmentShader = sh.fragmentShader.replace('#include ', `#include \nvarying vec3 vHdPos; uniform sampler2D hdDet; uniform vec2 hdQuinas[8];${kit.RUIDO_GLSL || ''}`).replace('#include ', `#include
+ { vec2 hdQ = vec2(vHdPos.x + vHdPos.z, vHdPos.y); float hdD = dot(texture2D(hdDet, vNormalMapUv).rgb, vec3(0.3, 0.59, 0.11)) / 0.61;
+ float hdBrocha = hdN(vec2(hdQ.x * 1.4, hdQ.y * 11.0)) * 0.6 + hdN(hdQ * vec2(0.5, 0.9) + 7.0) * 0.4;
+ diffuseColor.rgb *= mix(0.93, 1.04, hdBrocha) * mix(1.0, clamp(hdD, 0.75, 1.12), 0.5) * mix(0.94, 1.03, hdN(hdQ * 0.6 + 3.0));
+ float hdChuva = smoothstep(0.5, 0.8, hdN(vec2(hdQ.x * 5.0, hdQ.y * 0.35))) * smoothstep(2.3, 3.3, vHdPos.y) * (1.0 - smoothstep(3.4, 3.6, vHdPos.y));
+ diffuseColor.rgb *= 1.0 - 0.13 * hdChuva;
+ float hdPe = 1.0 - smoothstep(0.06, 0.5, vHdPos.y + (hdN(vec2(hdQ.x * 2.3, 0.0)) - 0.5) * 0.22);
+ float hdDq = 9.0; for (int i = 0; i < 8; i++) hdDq = min(hdDq, length(vHdPos.xz - hdQuinas[i]));
+ float hdQn = (1.0 - smoothstep(0.02, 0.26, hdDq)) * smoothstep(2.0, 2.2, vHdPos.y) * (1.0 - smoothstep(3.3, 3.5, vHdPos.y));
+ float hdVc = hdN(hdQ * vec2(6.0, 9.0)) * 0.6 + hdN(hdQ * 23.0) * 0.4 + hdPe * 0.3 + hdQn * 0.27, hdMc = max(hdPe, hdQn);
+ float hdCasca = smoothstep(0.52, 0.6, hdVc) * hdMc;
+ diffuseColor.rgb *= 1.0 - 0.3 * (smoothstep(0.46, 0.52, hdVc) - smoothstep(0.52, 0.6, hdVc)) * hdMc;
+ diffuseColor.rgb = mix(diffuseColor.rgb, mix(vec3(0.3, 0.24, 0.19), vec3(0.5, 0.43, 0.35), hdQn) * mix(0.8, 1.15, hdN(hdQ * 41.0)), hdCasca * 0.85);
+ diffuseColor.rgb = mix(diffuseColor.rgb, diffuseColor.rgb * vec3(0.78, 0.66, 0.54), hdPe * 0.5); }`); };
+ matCal.customProgramCacheKey = () => 'sertao-hd-cal2'; }
+ for (const [o, m, nome] of [[pl, matCal, 'matriz'], [tl, matTelha, 'matriz-telha']]) { const g = o.geo(); lixo.push(g); if (!g.index.count) continue;
+ const malha = new THREE.Mesh(g, m || matLiso); malha.name = `sertao-hd-${nome}`; malha.castShadow = true; malha.receiveShadow = true; malha.userData.nonSolidSurface = true; grupo.add(malha); }
+ // Tinta a óleo queimada de sol sobre a tábua: o veio clareia a cor e a lasca miúda mostra a madeira, mais no pé.
+ const matTinta = new THREE.MeshStandardMaterial({ color: 0xffffff, map: mapa, normalMap: mat.normalMap, vertexColors: true, roughness: .8, name: 'hd-cen-tinta' }); matTinta.normalScale.set(1.4, 1.4); lixo.push(matTinta);
+ // Madeira crua e pintada dividem o mesmo programa: só o uniforme hdTinta muda.
+ if (mapa) for (const [m, tinta] of [[mat, 0], [matTinta, 1]]) { m.onBeforeCompile = (sh) => { sh.uniforms.hdTinta = { value: tinta };
+ sh.vertexShader = sh.vertexShader.replace('#include ', '#include \nvarying vec3 vHdPos;').replace('#include ', '#include \nvHdPos = (modelMatrix * vec4(transformed, 1.0)).xyz;');
+ sh.fragmentShader = sh.fragmentShader.replace('#include ', `#include \nvarying vec3 vHdPos; uniform float hdTinta;${kit.RUIDO_GLSL || ''}`).replace('#include ', '').replace('#include ', `
+ if (hdTinta > 0.5) { vec3 hdTx = texture2D(map, vMapUv).rgb, hdL = vec3(0.3, 0.59, 0.11); float hdV = clamp(dot(hdTx, hdL) / max(dot(texture2D(map, vMapUv, 9.0).rgb, hdL), 0.01), 0.3, 1.8);
+ vec2 hdQ = vec2(vHdPos.x + vHdPos.z, vHdPos.y); float hdPe = 1.0 - smoothstep(0.04, 0.5, vHdPos.y);
+ float hdLasca = smoothstep(0.55, 0.62, hdN(hdQ * vec2(23.0, 11.0)) * 0.5 + hdN(hdQ * vec2(61.0, 33.0)) * 0.3 + (1.0 - hdV) * 0.32 + hdPe * 0.34);
+ vec3 hdNua = mix(vec3(dot(hdTx, hdL)), hdTx, 0.45) * min(1.8, 0.9 * dot(vColor, hdL) / max(dot(texture2D(map, vMapUv, 9.0).rgb, hdL), 0.01));
+ vec3 hdPint = vColor * mix(0.84, 1.03, clamp(hdV - 0.3, 0.0, 1.0)) * mix(0.88, 1.04, hdN(vec2(hdQ.x * 27.0, hdQ.y * 0.8)));
+ diffuseColor.rgb = mix(hdPint, hdNua, hdLasca) * mix(0.74, 1.0, smoothstep(0.0, 0.35, vHdPos.y)); } else {
+ #include
+ #include
+ }`); };
+ m.customProgramCacheKey = () => 'sertao-hd-tinta5'; }
+ for (const [geos, m, nome] of [[liso.geos(), matLiso, 'barro'], [of.geos(), mat, 'cerca'], [pin.geos(), matTinta, 'tinta']]) for (const g of geos) { lixo.push(g); if (!g.index.count) continue;
+ const malha = new THREE.Mesh(g, m); malha.name = `sertao-hd-${nome}`; malha.receiveShadow = true; malha.userData.nonSolidSurface = true; grupo.add(malha); }
+ }
+
+ if (opts.flora !== false) {
+ if (opts.arvoreGrande !== false) {
+ // Árvore de primeiro plano da vista da praça (GLB do juazeiro, que já é um esqueleto seco): tronco fora de bounds, copa acima dos telhados.
+ const molde = placeProp('sertao_juazeiro', { targetH: 1 }), fontes = [];
+ if (molde) { molde.updateMatrixWorld(true); molde.traverse((m) => { if (m.isMesh) fontes.push(m); }); }
+ if (fontes.length === 1 && !Array.isArray(fontes[0].material)) { const f = fontes[0], [x, z, h, ry] = opts.arvoreGrande?.pos ?? [B.minX - 5.6, -31, 15, 1.9];
+ // Galho de 1 px contra o sol cintilava: incha ~5 cm ao longo da normal (o tronco nem nota).
+ const mg = f.material.clone(), incha = (opts.arvoreGrande?.incha ?? .05) / (h * 1.1 * (f.matrixWorld.getMaxScaleOnAxis() || 1));
+ mg.onBeforeCompile = (sh) => { sh.vertexShader = sh.vertexShader.replace('#include ', `#include \ntransformed += normalize(objectNormal) * ${incha.toFixed(6)};`); };
+ mg.customProgramCacheKey = () => `sertao-hd-arvore-${incha.toFixed(6)}`; lixo.push(mg);
+ const grande = new THREE.Mesh(f.geometry, mg); obj.position.set(x, -.15, z); obj.rotation.set(0, ry, 0); obj.scale.set(h * 1.25, h, h * 1.25); obj.updateMatrix();
+ grande.matrixAutoUpdate = false; grande.matrix.multiplyMatrices(obj.matrix, f.matrixWorld); grande.name = 'sertao-hd-arvore-grande'; grande.castShadow = true; grande.receiveShadow = true; grupo.add(grande); }
+ }
+ let matCacto = null; scene.traverse((o) => { if (!matCacto && o.isMesh && o.name === 'cacto-ramos') matCacto = o.material; });
+ if (matCacto) { const tmp = new THREE.Group(), gm = mandacaruSertao(tmp, matCacto, 1, 1).geometry;
+ const lugares = [[42.6, 8, 1.45], [-2, 54, 1.35], ...(opts.mandacarusPerto === false ? [] : [
+ [-35.6, -9, 1.5], [36.3, 3, 1.6], [-20, 48.8, 1.45], [-7.7, -49.4, 2.1], [9.3, -48.7, 1.85]])];
+ const im = lote(gm, matCacto, lugares.length, 'mandacarus');
+ lugares.forEach(([x, z, s], i) => { obj.position.set(x, terreno(x, z) - .05, z); obj.rotation.set(0, i * 2.4, 0); obj.scale.setScalar(s); obj.updateMatrix(); im.setMatrixAt(i, obj.matrix); });
+ im.instanceMatrix.needsUpdate = true; im.computeBoundingSphere();
+ // Flor branca na ponta dos braços mais altos (a posição sai dos vértices do próprio mandacaru).
+ const pg = gm.attributes.position, pontas = [];
+ for (let i = 0; i < pg.count; i++) { const x = pg.getX(i), y = pg.getY(i), z = pg.getZ(i), q = pontas.find((t) => Math.hypot(t[0] - x, t[2] - z) < .28); if (!q) pontas.push([x, y, z]); else if (y > q[1]) { q[0] = x; q[1] = y; q[2] = z; } }
+ pontas.sort((a, b) => b[1] - a[1]); const tp = pontas.filter((t) => t[1] > pontas[0][1] * .6).slice(0, 3);
+ if (tp.length && opts.objetos !== false) { const fl = oficina(), M4 = new THREE.Matrix4(), a = new THREE.Vector3(), b = new THREE.Vector3();
+ lugares.forEach(([, , e], i) => { im.getMatrixAt(i, M4); for (const [x, y, z] of tp) { a.set(x, y - .01, z).applyMatrix4(M4); b.set(x + .02, y + .07, z).applyMatrix4(M4);
+ fl.cilindro(a, b, .02 * e, .075 * e, 6, [2.3, 2.25, 2.0], { tampas: false }); fl.cilindro(a, a.clone().lerp(b, .6), .012 * e, .02 * e, 4, [2.2, 1.7, .4]); } });
+ const gf = fl.geo(), mf = new THREE.Mesh(gf, matLiso); mf.name = 'sertao-hd-flores'; mf.userData.nonSolidSurface = true; grupo.add(mf); lixo.push(gf); } }
+ const gp = pedraGeo(1, 23, .3), lugares = [[-39.2, -28.5, 1.5], [-40.6, -29.6, .8], [-38.6, -33.4, .6], [-40, 2, 1.1], [-41.4, 3.1, .6], [-39.5, 21, .9], [39.6, -15, 1.3], [40.9, -13.6, .7], [40, 34, 1.0],
+ [41, 35.6, .55], [-16, -52.6, 1.2], [-17.6, -53.4, .65], [20, 52.4, 1.4], [18.2, 53.3, .7], [-34, 53, .9], [36, -53, 1.1]];
+ const im = lote(gp, matPedra, lugares.length, 'pedras-grandes'); lixo.push(gp);
+ lugares.forEach(([x, z, r], i) => { obj.position.set(x, terreno(x, z) + r * .22, z); obj.rotation.set(rnd() * .4, rnd() * 6.283, rnd() * .4); obj.scale.set(r * (.9 + rnd() * .5), r * (.55 + rnd() * .3), r * (.9 + rnd() * .4)); obj.updateMatrix();
+ const v = .17 + rnd() * .1; im.setMatrixAt(i, obj.matrix); im.setColorAt(i, cor.setRGB(v * 1.08, v * .95, v * .84)); });
+ im.instanceMatrix.needsUpdate = true; im.instanceColor.needsUpdate = true; im.computeBoundingSphere();
+ }
+
+ if (opts.pe !== false && scene.getObjectByName('sertao-solo')?.material) {
+ // Terra juntada no pé das paredes: cunha de até 12 cm com o material e a UV do chão; não entra nas casas.
+ const casas = [], v = new THREE.Vector3(), P = [], U = [], I = [];
+ scene.traverse((o) => { if (o.userData?.interior) { o.updateWorldMatrix(true, false); casas.push([o.matrixWorld.clone().invert(), o.userData.interior]); } });
+ const dentro = (x, z) => casas.some(([inv, pc]) => { v.set(x, 0, z).applyMatrix4(inv); return Math.abs(v.x) < pc.halfW && Math.abs(v.z) < pc.halfD; });
+ const tira = (x0, z0, x1, z1, nx, nz) => { const mx = (x0 + x1) / 2 + nx * .3, mz = (z0 + z1) / 2 + nz * .3; if (!naArena(mx, mz, .2) || dentro(mx, mz) || !livre(mx, mz)) return;
+ const n = Math.max(1, Math.round(Math.hypot(x1 - x0, z1 - z0) / .9)), b = P.length / 3, sobe = nz * (x1 - x0) - nx * (z1 - z0) > 0;
+ for (let i = 0; i <= n; i++) { const t = i / n, x = x0 + (x1 - x0) * t, z = z0 + (z1 - z0) * t, ponta = i === 0 || i === n, h = ponta ? .0 : .07 + rnd() * .05, w = ponta ? .16 : .38 + rnd() * .3;
+ for (const [f, y] of [[.09, h], [w, -.012]]) { const X = x + nx * f, Z = z + nz * f; P.push(X, y, Z); U.push((X + 600) / 1200, (600 - Z) / 1200); }
+ if (i) { const a = b + 2 * (i - 1); if (sobe) I.push(a, a + 1, a + 2, a + 2, a + 1, a + 3); else I.push(a, a + 2, a + 1, a + 2, a + 3, a + 1); } } };
+ for (const c of paredes) { if (c.hx || c.minY > .08) continue;
+ if (c.maxX - c.minX > 1.2) { tira(c.minX, c.minZ, c.maxX, c.minZ, 0, -1); tira(c.minX, c.maxZ, c.maxX, c.maxZ, 0, 1); }
+ if (c.maxZ - c.minZ > 1.2) { tira(c.minX, c.minZ, c.minX, c.maxZ, -1, 0); tira(c.maxX, c.minZ, c.maxX, c.maxZ, 1, 0); } }
+ if (I.length) { const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(U, 2)); g.setIndex(I); g.computeVertexNormals();
+ const pe = new THREE.Mesh(g, scene.getObjectByName('sertao-solo').material); pe.name = 'sertao-hd-pe-terra'; pe.receiveShadow = true; pe.userData.nonSolidSurface = true; grupo.add(pe); lixo.push(g); }
+ }
+
+ if (opts.capela !== false) {
+ // Outeiro com a mesma terra do chão (UV casada com o plano de 1200 m) e a matriz no alto, logo depois do limite norte.
+ const [cx, cz, H, R] = opts.capela?.pos ?? [-24, -56.5, 2.2, 10.5], solo = scene.getObjectByName('sertao-solo');
+ const topo = (r, ang) => H * (1 - suave(4.5, R, r)) * (1 + .12 * Math.sin(ang * 3 + 1) * suave(4.5, 14, r)) - .35;
+ if (solo?.material) { const P = [], U = [], I = [], AN = 9, SE = 28;
+ for (let j = 0; j <= AN; j++) for (let i = 0; i <= SE; i++) { const r = j / AN * R, ang = i / SE * Math.PI * 2, x = cx + Math.cos(ang) * r, z = cz + Math.sin(ang) * r;
+ P.push(x, Math.max(terreno(x, z) - .3, topo(r, ang)), z); U.push((x + 600) / 1200, (600 - z) / 1200); }
+ for (let j = 0; j < AN; j++) for (let i = 0; i < SE; i++) { const a = j * (SE + 1) + i, b = a + SE + 1; I.push(a, b, a + 1, a + 1, b, b + 1); }
+ const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(U, 2)); g.setIndex(I); g.computeVertexNormals();
+ const outeiro = new THREE.Mesh(g, solo.material); outeiro.name = 'sertao-hd-outeiro'; outeiro.receiveShadow = true; grupo.add(outeiro); lixo.push(g); }
+ const alvo = { x: cx, y: topo(0, 0) - .1, z: cz, targetH: opts.capela?.altura ?? 19, ry: opts.capela?.ry ?? .36 }, capela = opts.matriz !== false && opts.cerca !== false ? null : placeProp('igrejinha', alvo) || placeProp('sertao_capelinha', alvo);
+ if (capela) { capela.name = 'sertao-hd-capelinha'; capela.traverse((m) => { if (m.isMesh) m.castShadow = false; }); grupo.add(capela); }
+ }
+
+ if (opts.serra !== false) {
+ // Serra em malha: três anéis de crista, cada um mais dentro da névoa. O far da câmera é 400 m, então o último fica em ~330 m.
+ const aneis = opts.serra?.aneis ?? [[176, 9, 21, .16, 31], [252, 15, 31, .34, 57], [326, 22, 45, .52, 83]];
+ const SEG = 100, perfil = [[-50, -.05], [-30, .2], [-15, .6], [-5, .9], [0, 1], [22, .4]], P = [], NV = [], AL = [], I = [];
+ const onda = (semente, n) => { const r = rngDe(semente), v = Array.from({ length: n }, () => r()); return (t) => { const u = ((t % 1) + 1) % 1 * n, i = Math.floor(u), f = u - i, s = f * f * (3 - 2 * f); return v[i % n] * (1 - s) + v[(i + 1) % n] * s; }; };
+ aneis.forEach(([raio, h0, h1, nev, sem], ia) => {
+ const o1 = onda(sem, 7), o2 = onda(sem + 1, 19), o3 = onda(sem + 2, 53), r1 = onda(sem + 3, 37), r2 = onda(sem + 4, 97), base = P.length / 3;
+ const alturaEm = (t) => h0 + (h1 - h0) * Math.min(1, Math.pow(o1(t) * .58 + o2(t) * .29 + (1 - Math.abs(o3(t) * 2 - 1)) * .13, 1.5) * 1.45);
+ for (let i = 0; i <= SEG; i++) { const t = i / SEG, ang = t * Math.PI * 2, h = alturaEm(t);
+ perfil.forEach(([recuo, fr], j) => { const meio = j > 0 && j < 3 ? 1 : 0, rr = raio + recuo + meio * ((r1(t + j * .013) - .5) * 20 + (r2(t) - .5) * 9), x = Math.cos(ang) * rr, z = Math.sin(ang) * rr;
+ P.push(x, terreno(x, z) - 2.5 + h * fr * (1 + meio * (r2(t + .31) - .5) * .3), z); NV.push(nev); AL.push(Math.max(0, fr)); }); }
+ const K = perfil.length; for (let i = 0; i < SEG; i++) for (let j = 0; j < K - 1; j++) { const a = base + i * K + j, b = a + K; I.push(a, a + 1, b, b, a + 1, b + 1); }
+ // Mandacaru, xique-xique e juazeiro em recorte chapado sobre a crista: dois planos, o de trás mais dentro da névoa.
+ if (ia > 1 || opts.serra?.caatinga === false) return;
+ const rp = rngDe(sem * 7 + 3), esc = ia ? 1.5 : 1, nv = nev + .1;
+ for (let k = 0; k < (ia ? 110 : 96); k++) { const t = (k + rp() * .9) / (ia ? 110 : 96), ang = t * Math.PI * 2, rr = raio - 2, ox = Math.cos(ang) * rr, oz = Math.sin(ang) * rr, tx = -Math.sin(ang), tz = Math.cos(ang);
+ const y0 = terreno(ox, oz) - 2.5 + alturaEm(t) - .8, tipo = rp(), H = (tipo < .42 ? 5.5 + rp() * 3.5 : tipo < .68 ? 6.5 + rp() * 3 : 3 + rp() * 1.6) * esc;
+ const v = (u, y) => { P.push(ox + tx * u, y0 + y, oz + tz * u); NV.push(nv); AL.push(1.3); return P.length / 3 - 1; };
+ const faixa = (u0, ya, u1, yb, w) => { const horiz = Math.abs(yb - ya) < Math.abs(u1 - u0), a = v(u0 - (horiz ? 0 : w), ya - (horiz ? w : 0)), b = v(u0 + (horiz ? 0 : w), ya + (horiz ? w : 0)), c = v(u1 + (horiz ? 0 : w), yb + (horiz ? w : 0)), d = v(u1 - (horiz ? 0 : w), yb - (horiz ? w : 0)); I.push(a, b, c, a, c, d); };
+ if (tipo < .42) { const w = H * .045; faixa(0, 0, 0, H, w);
+ for (let b = 0, nb = 2 + Math.floor(rp() * 3); b < nb; b++) { const lado = b % 2 ? 1 : -1, hb = H * (.28 + rp() * .3), d = lado * H * (.13 + rp() * .1), topo = H * (.7 + rp() * .32); faixa(0, hb, d, hb, w * .8); faixa(d, hb - w * .8, d, topo, w * .8); }
+ } else if (tipo < .68) { faixa(0, 0, H * .04, H * .5, H * .03); faixa(H * .04, H * .4, -H * .2, H * .62, H * .02); const c0 = v(0, H * .7), n = 12, anel = [];
+ for (let i = 0; i < n; i++) { const a = i / n * 6.2832, f = .86 + rp() * .26; anel.push(v(Math.cos(a) * H * .6 * f, H * .7 + Math.sin(a) * H * .26 * f)); }
+ for (let i = 0; i < n; i++) I.push(c0, anel[i], anel[(i + 1) % n]);
+ } else for (let b = 0, nb = 4 + Math.floor(rp() * 3); b < nb; b++) { const d = (b / (nb - 1) - .5) * H * 1.5, w = H * .055; faixa(d * .25, 0, d, H * .22, w); faixa(d, H * .22 - w, d * 1.08, H * (.6 + rp() * .4), w); } }
+ });
+ const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('aNev', new THREE.Float32BufferAttribute(NV, 1));
+ g.setAttribute('aAlt', new THREE.Float32BufferAttribute(AL, 1)); g.setIndex(I); g.computeVertexNormals(); g.computeBoundingSphere();
+ let sol = null; scene.traverse((o) => { if (o.isDirectionalLight && o.castShadow) sol = o; });
+ const dirSol = sol ? sol.position.clone().sub(sol.target.position).normalize() : new THREE.Vector3(-.84, .17, -.5);
+ const mat = new THREE.ShaderMaterial({ fog: false, side: THREE.DoubleSide,
+ uniforms: { uSol: { value: dirSol }, uNevoa: { value: new THREE.Color(scene.fog?.color?.getHex() ?? 0xd7a477) }, uRocha: { value: new THREE.Color(opts.serra?.rocha ?? 0x8a6a52) },
+ uMato: { value: new THREE.Color(opts.serra?.mato ?? 0x4f5140) }, uLuz: { value: new THREE.Color(opts.serra?.luz ?? 0xffb070) }, uSombra: { value: new THREE.Color(opts.serra?.sombra ?? 0x6a6f8c) }, uBruma: { value: new THREE.Color(opts.serra?.bruma ?? 0xf6cf9c) } },
+ vertexShader: `attribute float aNev, aAlt; varying vec3 vN, vP; varying float vNev, vAlt;
+ void main(){ vN = normal; vP = position; vNev = aNev; vAlt = aAlt; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,
+ fragmentShader: `varying vec3 vN, vP; varying float vNev, vAlt; uniform vec3 uSol, uNevoa, uRocha, uMato, uLuz, uSombra, uBruma;${kit.RUIDO_GLSL || ''}
+ void main(){ vec2 p = vP.xz; float m = hdN(p * 0.028 + vP.y * 0.06) * 0.5 + hdN(p * 0.09 + 3.0) * 0.3 + hdN(p * 0.31 + vP.y * 0.2) * 0.2;
+ vec3 alb = mix(uRocha, uMato, smoothstep(0.36, 0.6, m)) * mix(0.72, 1.2, hdN(p * 0.7 + vP.y * 0.9)) * (1.0 - 0.5 * smoothstep(1.05, 1.25, vAlt));
+ alb *= 1.0 - 0.3 * smoothstep(0.55, 0.9, hdN(vec2(atan(p.y, p.x) * 140.0, vP.y * 0.12)));
+ vec3 n = normalize(vN); if (n.y < 0.0) n = -n;
+ float l = max(dot(n, uSol), 0.0) * (1.0 - 0.85 * smoothstep(1.05, 1.25, vAlt));
+ vec3 c = alb * (uSombra * 0.55 + uLuz * l * 2.2);
+ c = mix(c, uNevoa, clamp(vNev + (1.0 - vAlt) * 0.3, 0.0, 0.97));
+ float lado = pow(max(dot(normalize(vP.xz - cameraPosition.xz), normalize(uSol.xz)), 0.0), 2.5);
+ c = mix(c, uBruma, (1.0 - min(vAlt, 1.0) * 0.75) * ${(opts.serra?.brumaForca ?? .5).toFixed(3)} * (0.3 + 0.7 * lado));
+ gl_FragColor = vec4(c, 1.0);
+ #include
+ #include
+ }` });
+ const malha = new THREE.Mesh(g, mat); malha.name = 'sertao-hd-serra'; malha.frustumCulled = false; malha.renderOrder = 900; grupo.add(malha); lixo.push(g, mat);
+ }
+
+ if (opts.anel !== false) {
+ // Anel, disco e pano são do JOGO: ele recria os três a cada rodada e reescreve cor/opacidade por quadro.
+ // O ajuste entra no shader (cor e símbolo do objetivo ficam intactos) e um relógio reaplica nos novos.
+ const vistos = new Map(), jogo = typeof window !== 'undefined' ? window.__game : null, tempo = { value: 0 }, LUMA = 'vec3(0.3, 0.59, 0.11)';
+ const pano = new THREE.PlaneGeometry(1.7, 1.05, 14, 8), faixa = new THREE.RingGeometry(.911, 1.089, 96, 1); faixa.translate(0, 0, .02); lixo.push(pano, faixa);
+ const soloTex = kit.pbrTex('hd_sertao/dry_ground_rocks_cor', true), mundoXZ = (sh, extra = '') => { sh.uniforms.hdSolo = { value: soloTex };
+ sh.vertexShader = sh.vertexShader.replace('#include ', '#include \nvarying vec2 vHdW; varying vec2 vHdL;').replace('#include ', '#include \nvHdW = (modelMatrix * vec4(transformed, 1.0)).xz * vec2(1.0, -1.0); vHdL = position.xy;');
+ sh.fragmentShader = sh.fragmentShader.replace('#include ', `#include \nvarying vec2 vHdW; varying vec2 vHdL; uniform sampler2D hdSolo;${extra}`); };
+ const troca = (m, obc, chave) => { const s0 = { m, obc: m.onBeforeCompile, key: m.customProgramCacheKey }; m.dispose(); m.onBeforeCompile = obc; m.customProgramCacheKey = () => chave; m.needsUpdate = true; return s0; };
+ const aplica = () => { for (const pt of jogo?.ctfPts || []) { const m = pt.ring?.material; if (!m || m.userData.hdCal || vistos.has(m)) continue;
+ const s0 = { mats: [], anel: pt.ring, mat0: m, ageo: pt.ring.geometry, ro: pt.ring.renderOrder, rs: pt.ring.receiveShadow, flag: pt.flag, geo: pt.flag?.geometry, obr: pt.flag?.onBeforeRender, sombra: [pt.pole, pt.flag].filter((o) => o && !o.castShadow) }; vistos.set(m, s0);
+ for (const o of s0.sombra) o.castShadow = true;
+ // Faixa de cal gasta e íntegra: material iluminado (pega sombra como o chão); cor e opacidade seguem vindo do jogo.
+ const cal = new THREE.MeshStandardMaterial({ color: m.color.clone(), transparent: true, opacity: m.opacity, depthWrite: false, roughness: 1, metalness: 0, side: THREE.DoubleSide, forceSinglePass: true, polygonOffset: true, polygonOffsetFactor: -3, polygonOffsetUnits: -3, name: 'hd-cen-anel' });
+ cal.userData.hdCal = true; s0.cal = cal;
+ cal.onBeforeCompile = (sh) => { mundoXZ(sh, kit.RUIDO_GLSL || ''); sh.fragmentShader = sh.fragmentShader.replace('#include ', `#include
+ { float hdAng = atan(vHdL.y, vHdL.x), hdR = (length(vHdL) - 1.0) / 0.089;
+ float hdT = dot(texture2D(hdSolo, vHdW / 4.0).rgb, ${LUMA}) / 0.0793, hdT3 = dot(texture2D(hdSolo, vHdW / 1.333 + 0.37).rgb, ${LUMA}) / 0.0793;
+ float hdPinc = hdN(vec2(hdAng * 30.0, hdR * 1.6 + 3.0)) * 0.6 + hdN(vec2(hdAng * 110.0, hdR * 4.0)) * 0.4, hdGasto = hdN(vHdW * 1.3) * 0.6 + hdN(vHdW * 5.0 + 4.0) * 0.4;
+ diffuseColor.rgb *= ${(opts.anel?.cal ?? 1.82).toFixed(3)} * vec3(0.86, 0.98, 1.14) * mix(0.84, 1.08, hdPinc) * mix(0.86, 1.06, hdGasto) * mix(1.0, clamp(hdT, 0.6, 1.25), 0.42) * mix(1.0, clamp(hdT3, 0.7, 1.2), 0.34);
+ diffuseColor.rgb *= 1.0 - 0.14 * (1.0 - smoothstep(0.05, 0.13, abs(abs(hdR) - 0.58)));
+ float hdBd = 0.7 + 0.16 * hdN(vec2(hdAng * 45.0, hdR + 2.0)) + 0.1 * hdN(vHdW * 6.0) + 0.06 * hdN(vHdW * 19.0);
+ float hdFalha = smoothstep(0.66, 0.74, hdN(vHdW * 3.7 + 9.0) * 0.5 + hdN(vHdW * 11.0) * 0.3 + clamp(hdT3 - 0.6, 0.0, 1.0) * 0.3);
+ diffuseColor.a = mix(0.93, 1.0, diffuseColor.a) * (1.0 - smoothstep(hdBd, hdBd + 0.1, abs(hdR))) * (1.0 - 0.6 * hdFalha); }`); };
+ cal.customProgramCacheKey = () => `sertao-hd-anel10-${opts.anel?.cal ?? 1.82}`;
+ pt.ring.material = cal; pt.ring.geometry = faixa; pt.ring.renderOrder = 2; pt.ring.receiveShadow = true;
+ if (pt.zone?.material) s0.mats.push(troca(pt.zone.material, (sh) => { mundoXZ(sh); sh.fragmentShader = sh.fragmentShader.replace('#include ', `#include
+ { float hdT = dot(texture2D(hdSolo, vHdW / 4.0).rgb, ${LUMA}) / 0.0793, hdT3 = dot(texture2D(hdSolo, vHdW / 1.333 + 0.37).rgb, ${LUMA}) / 0.0793;
+ diffuseColor.rgb *= mix(1.0, clamp(hdT, 0.45, 1.7), 0.6) * mix(1.0, clamp(hdT3, 0.5, 1.6), 0.45); diffuseColor.a *= ${(opts.anel?.disco ?? .5).toFixed(3)}; }`); }, `sertao-hd-disco3-${opts.anel?.disco ?? .5}`));
+ if (pt.flag?.material && opts.pano !== false) { pt.flag.geometry = pano; pt.flag.onBeforeRender = () => { tempo.value = performance.now() / 1000; };
+ s0.mats.push(troca(pt.flag.material, (sh) => { sh.uniforms.hdT = tempo;
+ sh.vertexShader = sh.vertexShader.replace('#include ', '#include \nuniform float hdT; varying float vHdDobra;').replace('#include ', `#include
+ { float hdU = uv.x, hdA = hdU * (0.04 + 0.13 * hdU), hdF = hdU * 7.0 - hdT * 4.6 + uv.y * 3.4 + modelMatrix[3].x;
+ transformed.z += (sin(hdF) + 0.5 * sin(hdF * 1.7 + 1.3 - uv.y * 4.0)) * hdA;
+ transformed.y += cos(hdF * 0.5) * 0.35 * hdA - hdU * hdU * (0.1 + 0.16 * uv.y);
+ transformed.x -= hdU * hdU * 0.13;
+ vHdDobra = (cos(hdF) + 0.85 * cos(hdF * 1.7 + 1.3 - uv.y * 4.0)) * smoothstep(0.0, 0.3, hdU); }`);
+ // Pano: sombra da dobra, bainha e trama (some quando o fio fica menor que ~2 px); cor e emblema são do jogo.
+ sh.fragmentShader = sh.fragmentShader.replace('#include ', '#include \nvarying float vHdDobra;')
+ .replace('#include ', `#include
+ diffuseColor.rgb *= clamp(0.74 + 0.27 * vHdDobra * (gl_FrontFacing ? 1.0 : -1.0), 0.4, 1.0) * vec3(0.96, 0.92, 0.88);
+ #ifdef USE_MAP
+ { vec2 hdTr = vMapUv * vec2(64.0, 40.0); float hdFt = smoothstep(0.55, 0.2, max(fwidth(hdTr.x), fwidth(hdTr.y)));
+ diffuseColor.rgb *= 1.0 - 0.2 * hdFt * (1.0 - (0.5 + 0.5 * sin(hdTr.x * 6.2832)) * (0.5 + 0.5 * sin(hdTr.y * 6.2832)));
+ diffuseColor.rgb *= mix(0.84, 1.0, smoothstep(0.0, 0.035, min(min(vMapUv.x, 1.0 - vMapUv.x), min(vMapUv.y, 1.0 - vMapUv.y)))) * (0.88 + 0.12 * vMapUv.y); }
+ #endif`); }, 'sertao-hd-pano3')); } } };
+ aplica(); const relogio = setInterval(aplica, 1500);
+ desfaz.push(() => { clearInterval(relogio); for (const s0 of vistos.values()) { for (const t of s0.mats) { t.m.dispose(); t.m.onBeforeCompile = t.obc; t.m.customProgramCacheKey = t.key; t.m.needsUpdate = true; }
+ s0.mat0.color.copy(s0.cal.color); s0.mat0.opacity = s0.cal.opacity; s0.anel.material = s0.mat0; s0.cal.dispose(); s0.anel.geometry = s0.ageo; s0.anel.renderOrder = s0.ro; s0.anel.receiveShadow = s0.rs;
+ for (const o of s0.sombra) o.castShadow = false; if (s0.flag && opts.pano !== false) { s0.flag.geometry = s0.geo; s0.flag.onBeforeRender = s0.obr; } } });
+ }
+
+ return () => { while (desfaz.length) desfaz.pop()(); scene.remove(grupo); for (const d of lixo) d.dispose(); };
+}
diff --git a/public/js/i18n.js b/public/js/i18n.js
index 87841af898..fc0328c6e3 100644
--- a/public/js/i18n.js
+++ b/public/js/i18n.js
@@ -833,7 +833,7 @@ const DICT = {
'Seu progresso já está contando.': 'Your progress is already counting.',
'Para ganhar XP e resgatar as recompensas, entre na sua conta.': 'Sign in to earn XP and claim the rewards.',
'VER O PASSE': 'SEE THE PASS', 'ENTRAR E JOGAR O PASSE': 'SIGN IN AND PLAY THE PASS', 'ENTRAR PARA JOGAR': 'SIGN IN TO PLAY',
- 'SEU NÍVEL': 'YOUR LEVEL', 'XP do nível': 'Level XP', 'NÍVEL MÁXIMO': 'MAX LEVEL', 'Níveis do passe': 'Pass levels',
+ 'SEU NÍVEL': 'YOUR LEVEL', 'ATUAL': 'CURRENT', 'XP do nível': 'Level XP', 'NÍVEL MÁXIMO': 'MAX LEVEL', 'Níveis do passe': 'Pass levels',
'Entre na sua conta para ganhar XP nas partidas e nas missões e resgatar as recompensas. O passe é grátis.':
'Sign in to earn XP from matches and missions and claim the rewards. The pass is free.',
'RESGATAR': 'CLAIM', 'RESGATANDO…': 'CLAIMING…', 'RESGATADO': 'CLAIMED', 'ENTRE PARA LIBERAR': 'SIGN IN TO UNLOCK',
diff --git a/public/js/javaporcos_intro.js b/public/js/javaporcos_intro.js
index 4d27bdd0ad..8b7d49fda5 100644
--- a/public/js/javaporcos_intro.js
+++ b/public/js/javaporcos_intro.js
@@ -1,3 +1,4 @@
+import { ONDAS_SOLO } from './javaporcos_partida.js';
import { wallpaperJavaporcos } from './javaporcos_apresentacao.js';
import { startVisibleRotation } from './media-rotation.js';
let pending = null;
@@ -29,7 +30,7 @@ export function apresentarJavaporcos(signal) {
INVASÃO DOS JAVAPORCOS
A praga chegou ao bairro.
O javaporco é o cruzamento do javali europeu com o porco doméstico. Invasor no Brasil, revira o solo, destrói lavouras e se multiplica rápido. Pode atacar.
-
Mantenha seu time vivo. Mesmo com a cidade toda ocupada, um sobrevivente mantém a resistência. Proteja as lojas e retome os setores invadidos. Limpe os setores para reduzir a ocupação.
Explore a mata, procure os bandos e impeça que cheguem às lojas. O relógio da partida continua; a contagem de cada onda aparece separada.
+
São ${ONDAS_SOLO} ondas. Segure a cidade até a última. Mantenha seu time vivo. Mesmo com a cidade toda ocupada, um sobrevivente mantém a resistência. Proteja as lojas e retome os setores invadidos. Limpe os setores para reduzir a ocupação.
Explore a mata, procure os bandos e impeça que cheguem às lojas.
`;
let wall = 0;
const art = dialog.querySelector('.ji-art');
diff --git a/public/js/javaporcos_ondas.js b/public/js/javaporcos_ondas.js
new file mode 100644
index 0000000000..70c4401e98
--- /dev/null
+++ b/public/js/javaporcos_ondas.js
@@ -0,0 +1,3 @@
+export const WAVE_COUNTS = Object.freeze([24, 36, 48, 64, 80, 96, 120, 150]);
+export const PREP_SECONDS = 12;
+export const COMBAT_SECONDS = 75;
diff --git a/public/js/javaporcos_opcoes.js b/public/js/javaporcos_opcoes.js
index 136cc516d1..79f93581c5 100644
--- a/public/js/javaporcos_opcoes.js
+++ b/public/js/javaporcos_opcoes.js
@@ -1,3 +1,4 @@
+import { ONDAS_SOLO } from './javaporcos_partida.js';
export function sincronizarOpcoesJavaporcos(host, ativo, settings, salvar) {
if (!host) return;
let panel = host.querySelector('[data-javaporcos-opcoes]');
@@ -7,7 +8,7 @@ export function sincronizarOpcoesJavaporcos(host, ativo, settings, salvar) {
panel.style.cssText = 'display:flex;gap:16px;flex-wrap:wrap;flex-basis:100%';
panel.innerHTML = `
-
+
@@ -25,7 +26,7 @@ export function sincronizarOpcoesJavaporcos(host, ativo, settings, salvar) {
}
panel.hidden = !ativo;
panel.style.display = ativo ? 'flex' : 'none';
- const regras = {times:2,defensores:Math.max(4,Math.min(8,1+(settings.allyBots||0))),fim:'infinito',abates:1000,mortes:20,minutos:30,wipe:'time',criterio:'territorio',...settings.javaporcos};
+ const regras = {times:2,defensores:Math.max(4,Math.min(8,1+(settings.allyBots||0))),fim:'ondas',abates:1000,mortes:20,minutos:30,wipe:'time',criterio:'territorio',...settings.javaporcos};
const inimigos = host.querySelector('#ms-enemy-bots')?.parentElement;
if (inimigos) inimigos.hidden = ativo && regras.times !== 3;
for (const control of panel.querySelectorAll('[data-regra]')) control.value = String(regras[control.dataset.regra]);
diff --git a/public/js/javaporcos_partida.js b/public/js/javaporcos_partida.js
index fc76a833fc..ce3f2a2136 100644
--- a/public/js/javaporcos_partida.js
+++ b/public/js/javaporcos_partida.js
@@ -1,8 +1,11 @@
+import { WAVE_COUNTS, PREP_SECONDS, COMBAT_SECONDS } from './javaporcos_ondas.js';
const natural = (value, fallback = 0) => Number.isSafeInteger(Number(value)) && Number(value) >= 0 ? Number(value) : fallback;
+export const ONDAS_SOLO = WAVE_COUNTS.length;
export function regrasDaInvasao(raw = {}, multiplayer = false) {
- const fim = ['infinito', 'abates', 'mortes', 'tempo'].includes(raw.fim) ? raw.fim : 'infinito';
+ const fim = ['ondas', 'infinito', 'abates', 'mortes', 'tempo'].includes(raw.fim) ? raw.fim : 'ondas';
return {
times: raw.coop === true ? 2 : multiplayer || raw.times === 3 ? 3 : 2,
+ ondas: !multiplayer && fim === 'ondas' ? ONDAS_SOLO : 0,
abates: multiplayer ? natural(raw.abates, 1000) || 1000 : fim === 'abates' ? natural(raw.abates, 1000) || 1000 : 0,
mortes: !multiplayer && fim === 'mortes' ? natural(raw.mortes, 20) || 20 : 0,
segundos: multiplayer ? (natural(raw.minutos, 30) || 30) * 60 : fim === 'tempo' ? (natural(raw.minutos, 30) || 30) * 60 : 0,
@@ -10,6 +13,10 @@ export function regrasDaInvasao(raw = {}, multiplayer = false) {
criterio: raw.criterio === 'abates' ? 'abates' : 'territorio',
};
}
+export const RESUMO_ONDAS = `${ONDAS_SOLO} ONDAS · ~${Math.round(ONDAS_SOLO * (PREP_SECONDS + COMBAT_SECONDS) / 60)} MIN · SOBREVIVA À ÚLTIMA`;
+export function resumoDoFimJavaporcos(raw = {}) {
+ return regrasDaInvasao(raw).ondas ? RESUMO_ONDAS : '';
+}
export function vencedorPorLimite(state, regras) {
const times = regras.times === 3 ? ['E', 'B', 'J'] : ['E', 'J'];
const valor = team => regras.criterio === 'abates' ? state.teamKills?.[team] || 0 : state.territorio?.[team] || 0;
diff --git a/public/js/login-prompt.js b/public/js/login-prompt.js
index e88125084b..6dd1743c91 100644
--- a/public/js/login-prompt.js
+++ b/public/js/login-prompt.js
@@ -143,7 +143,7 @@ export function initLoginPrompt({auth=null,config=null,accountBusy=()=>false,ski
list.append(button('account-button account-provider login-prompt-provider',`Continuar com ${name}`,provider,async linkGuest=>{
const choice=privacyChoice();
const proof=linkGuest?guestProof():null;
- const out=await socialApi('/api/social-auth',{action:'start',provider,returnTo:'game',newsletter:false,...(choice?{analytics:choice.analytics}:{}),...(proof?{guest:proof}:{})});
+ const out=await socialApi('/api/social-auth',{action:'start',provider,returnTo:'game',newsletter:false,...(typeof choice?.analytics==='boolean'?{analytics:choice.analytics}:{}),...(proof?{guest:proof}:{})});
leaveTo(out.url);
}));
}
diff --git a/public/js/main.js b/public/js/main.js
index a925e6994e..449675ad97 100644
--- a/public/js/main.js
+++ b/public/js/main.js
@@ -11,7 +11,7 @@ import {initLoginPrompt,noteLoginPromptMatch} from './login-prompt.js';
import {analyticsAllowed} from './privacy-preferences.js';
import { contagem } from './contagem.js'; // contagem agregada sem id, independe do consentimento
import { clientUuid, getAnonId } from './client-id.js';
-import {initTretaStore,equippedTretaSkin,equippedTretaEyewear,equippedTretaGlove,equippedTretaWeaponSkin,equippedTretaPack,tretaSkinPresentation,tretaWeaponPresentation,tretaVitrine,tretaSkinsDoArmario,equiparTretaSkin,desequiparTretaSkin} from './treta-store.js';
+import {initTretaStore,equippedTretaSkin,equippedTretaEyewear,equippedTretaGlove,equippedTretaWeaponSkin,equippedTretaPack,tretaSkinPresentation,tretaWeaponPresentation,tretaVitrine,tretaSkinsDoArmario,equiparTretaSkin,desequiparTretaSkin,tretaEquipmentReady} from './treta-store.js';
import {carregarPasse,trocarContaPasse,acompanharPartidaPasse,personagemTravado as travadoNoPasse,nivelDoPersonagem,PASSE_EVENTO} from './passe.js';
import { passeDebugAtivo } from './passe-debug.js';
/* QA local (passe-debug.js): só loopback + ?debug=1&passeDev=1 joga com o elenco do passe sem resgate. */
@@ -1067,6 +1067,8 @@ function pvSetFailureUi(active) {
}
function clearStaticPreview({finishPending=false}={}) {
const my=++pvImageToken;pvStaticKey='';pvPosterFailure=null;pvSetFailureUi(false);
+ const placeholder = $('char-preview-placeholder');
+ if (placeholder) placeholder.hidden = true;
const image=$('char-preview-static');
if(image){
const release=()=>{if(my!==pvImageToken)return;image.onload=image.onerror=null;image.removeAttribute('src');};
@@ -1127,6 +1129,8 @@ function pvSetVideo(def) {
box.classList.add('has-video');
pvSetFailureUi(false);
video.classList.remove('hidden');
+ const placeholder = $('char-preview-placeholder');
+ if (placeholder) placeholder.hidden = true;
const label=$('char-preview-skin');if(label){label.textContent=skin?.name || '';label.hidden=!skin;}
if (hints) hints.classList.add('hidden');
};
@@ -1143,6 +1147,11 @@ function showStaticPreview(def) {
if(label){label.textContent=skin?.name || '';label.hidden=!skin;}
if(weaponLabel){weaponLabel.textContent=paint?previewPaintCaption(weapon,paint):'';weaponLabel.hidden=!paint;}
if (canvas) canvas.classList.add('hidden');
+ const placeholder = $('char-preview-placeholder');
+ if (placeholder) {
+ placeholder.textContent = skin?.name || def.name;
+ placeholder.hidden = false;
+ }
if (image) {
const my=++pvImageToken;
image.onload=image.onerror=null;image.removeAttribute('src');image.classList.add('hidden');
@@ -1150,7 +1159,7 @@ function showStaticPreview(def) {
const src=portraitUrl(def);
image.alt = skin?.name || def.name;
if(src){
- image.onload=()=>{if(my!==pvImageToken)return;image.classList.remove('hidden');pvPosterFailure=null;pvSetFailureUi(false);if(label && !previewVideoVisible()){label.textContent=skin?.name || '';label.hidden=!skin;}};
+ image.onload=()=>{if(my!==pvImageToken)return;image.classList.remove('hidden');if(placeholder)placeholder.hidden=true;pvPosterFailure=null;pvSetFailureUi(false);if(label && !previewVideoVisible()){label.textContent=skin?.name || '';label.hidden=!skin;}};
image.onerror = () => {if(my!==pvImageToken)return;image.onerror=null;if(skin)unavailable();else{image.onerror=()=>{if(my===pvImageToken)unavailable();};image.src=portraitFallbackUrl(def);}};
image.src=src;
}else unavailable();
@@ -1386,7 +1395,8 @@ function pvSetChar(def) {
const p = ensurePreview();
if (!p) { showStaticPreview(def); return; }
const showCanvas=()=>{
- p.renderDirty = true;
+ p.r.render(p.scene, p.cam);
+ p.renderDirty = false;
clearStaticPreview({finishPending:true});pvStopVideo();
$('char-preview')?.classList.remove('hidden');$('char-preview-static')?.classList.add('hidden');
document.querySelector('.pv-hints')?.classList.remove('hidden');
@@ -1400,6 +1410,9 @@ function pvSetChar(def) {
p.model = buildCharacter(def).group;
p.model.rotation.y = -0.4;
p.scene.add(p.model);
+ const { dataset } = $('char-preview');
+ delete dataset.glb;
+ dataset.character = def.id;
showCanvas();
};
// ?nav=1 mantém o preview procedural; web-assets.spec.js cobre o GLB real.
@@ -1408,7 +1421,7 @@ function pvSetChar(def) {
// O retrato mantém a identidade selecionada enquanto o GLB carrega ou falha.
const arma = armaDoPreview(def.id);
Promise.all([preloadCharacterAssets([def.id], { weapons:[arma.weaponId] }),preloadCosmeticAssets([def.skinId]),preloadEyewearAssets([def.eyewearId]),
- preloadWeapons([arma.weaponId]),preloadWeaponSkinCandidate(arma.weaponSkinId)])
+ preloadWeaponSkinCandidate(arma.weaponSkinId)])
.then(() => {
const pending = arma.gloveSkinId ? getGloveHandle(def.id, def.skinId)?.preload() : null;
return pending?.catch((e) => { if (!(e instanceof GloveManifestUnavailable)) throw e; e.warn(); });
@@ -1420,7 +1433,6 @@ function pvSetChar(def) {
// nada muda.
const m = hasModel(def.id, def.skinId) ? buildCharacterModel(def, { weaponId: arma.weaponId, weaponSkinId: arma.weaponSkinId, gloveSkinId: arma.gloveSkinId, preview: true }) : null;
if (!m) return;
- showCanvas();
if (p.model) p.scene.remove(p.model);
// Evidência do que foi montado na mão (régua LB20): os valores saem do objeto 3D,
// não da intenção - canvas não se lê e intenção não prova nada.
@@ -1432,6 +1444,7 @@ function pvSetChar(def) {
if (!luvaNaMao && o.userData?.gloveSkin) luvaNaMao = o.userData.gloveSkin;
});
cv.dataset.glb = '1';
+ cv.dataset.character = def.id;
cv.dataset.skin = m.skinId || '';
cv.dataset.arma = armaNaMao ? arma.weaponId : '';
cv.dataset.armaSkin = pinturaNaMao;
@@ -1447,6 +1460,7 @@ function pvSetChar(def) {
// ?pvcam=maos (régua): câmera na mão e idle congelado - com o preview animando, duas
// capturas do MESMO equipamento já saem diferentes e nenhuma comparação vale.
if (PV_CAM_MAOS) enquadrarMaos(p, m);
+ showCanvas();
}).catch(() => { if (my === pvToken && previewHeroVisible()) showStaticPreview(def); });
} else {
showBox();
@@ -1560,7 +1574,9 @@ function openHubRoster(updateRoute = true) {
hubRosterLado = ladoValido(CHARACTERS.find((c) => c.id === currentChar) || CHARACTERS[0], currentTeam);
const temPoliticos = (lado) => CHARACTERS.some((c) => c.team === 'P' && podeNoLado(c, lado));
hubRosterCat = temPoliticos(hubRosterLado) ? 'P' : null;
+ let rosterActionRevision = 0;
const lados = $('hub-roster-lados'), filters = $('hub-roster-factions'), grid = $('hub-roster-grid');
+ // O redesenho após gravar na loja não pode cancelar a intenção que o disparou.
const render = () => {
lados.replaceChildren(); filters.replaceChildren(); grid.replaceChildren();
for (const lado of ['E', 'B']) {
@@ -1569,7 +1585,7 @@ function openHubRoster(updateRoute = true) {
button.append(crest, tr(FACTION_NAME[lado]));
button.style.setProperty('--lado', PALETA[lado].base);
button.setAttribute('aria-selected', String(lado === hubRosterLado));
- button.onclick = () => { hubRosterLado = lado; hubRosterCat = temPoliticos(lado) ? 'P' : null; render(); };
+ button.onclick = () => { ++rosterActionRevision; hubRosterLado = lado; hubRosterCat = temPoliticos(lado) ? 'P' : null; render(); };
lados.appendChild(button);
}
const doLado = CHARACTERS.filter((c) => podeNoLado(c, hubRosterLado));
@@ -1582,7 +1598,7 @@ function openHubRoster(updateRoute = true) {
const button = document.createElement('button'); button.type = 'button';
button.textContent = cat ? tr(FACTION_NAME[cat] || cat) : tr('TODOS');
button.setAttribute('aria-pressed', String(cat === hubRosterCat));
- button.onclick = () => { hubRosterCat = cat; render(); };
+ button.onclick = () => { ++rosterActionRevision; hubRosterCat = cat; render(); };
filters.appendChild(button);
}
/* Armário: skin de personagem comprada é personagem selecionável aqui (dono, 23/10).
@@ -1623,13 +1639,21 @@ function openHubRoster(updateRoute = true) {
button.append(trava);
}
button.onclick = async () => {
+ const action = ++rosterActionRevision;
ui.click();
if (personagemTravado(def)) { $('hub-roster-selected').textContent = frase('passeTravadoAviso', def.name, nivel || '?'); return; }
- // Voltar ao personagem base com skin equipada TIRA a skin no servidor antes de trocar.
- if (equipada) {
- try { if (!await desequiparTretaSkin()) throw new Error('unequip_recusado'); }
- catch { $('hub-roster-selected').textContent = frase('skinTirarErro'); return; }
+ // A gravação pode ter começado antes de o redesenho ler a skin equipada.
+ try {
+ await tretaEquipmentReady();
+ if (action !== rosterActionRevision) return;
+ const equipadaAgora = tretaSkinsDoArmario().find(s => s.equipped && s.character === def.id);
+ if (equipadaAgora && !await desequiparTretaSkin()) throw new Error('unequip_recusado');
+ if (action !== rosterActionRevision) return;
+ } catch {
+ if (action === rosterActionRevision) $('hub-roster-selected').textContent = frase('skinTirarErro');
+ return;
}
+ if (action !== rosterActionRevision) return;
escolher(def.id);
};
cell.appendChild(button);
@@ -1649,7 +1673,7 @@ function openHubRoster(updateRoute = true) {
settings.pinnedChars = ehPin
? settings.pinnedChars.filter((id) => id !== def.id)
: [...settings.pinnedChars, def.id];
- saveSettings(); ui.click(); render();
+ saveSettings(); ui.click(); ++rosterActionRevision; render();
};
cell.appendChild(pin);
}
@@ -1657,15 +1681,21 @@ function openHubRoster(updateRoute = true) {
for (const skin of skinsDoChar) {
const skinCell = document.createElement('div'); skinCell.className = 'hub-roster-cell hub-roster-cell--skin';
const skinButton = document.createElement('button'); skinButton.type = 'button';
- skinButton.setAttribute('aria-pressed', String(skin.equipped && def.id === currentChar));
+ skinButton.setAttribute('aria-pressed', String(skin.equipped && def.id === efetivo));
const skinArt = document.createElement('img'); skinArt.src = skin.poster;
skinArt.alt = ''; skinArt.loading = 'lazy';
const skinName = document.createElement('span'); skinName.textContent = skin.name;
skinButton.append(skinArt, skinName);
skinButton.onclick = async () => {
+ const action = ++rosterActionRevision;
ui.click();
- try { if (!await equiparTretaSkin(skin.id)) throw new Error('equip_recusado'); }
- catch { $('hub-roster-selected').textContent = frase('skinEquiparErro'); return; }
+ try {
+ if (!await equiparTretaSkin(skin.id)) throw new Error('equip_recusado');
+ if (action !== rosterActionRevision) return;
+ } catch {
+ if (action === rosterActionRevision) $('hub-roster-selected').textContent = frase('skinEquiparErro');
+ return;
+ }
escolher(def.id);
};
skinCell.appendChild(skinButton);
@@ -2271,7 +2301,7 @@ async function _startGame(meuLancamento, team, charId, enemyFaction, online = fa
enemy: _escalados.filter((id) => !_podeNoLadoSp(id)),
};
const matchRoster = sessao
- ? rosterDoServidor(side, charId)
+ ? rosterDoServidor(sessao, side, charId)
: pickMatchRoster(faction, enemyFac, { allies: settingsDaPartida.allyBots, enemies: settingsDaPartida.enemyBots }, charId, false, _pinned);
// Operação Flávio: VIP é corpo a mais em B; Zero Um escolhido no B é o próprio VIP. Só
// offline — online o elenco do servidor já traz o VIP.
@@ -2390,6 +2420,13 @@ async function _startGame(meuLancamento, team, charId, enemyFaction, online = fa
onTrainingFrames: sendTrainingFrames,
});
window.__game = game;
+ // Demo de gráficos: kit HD por mapa só com ?hd=1 (map_*_hd.js); sem a flag nada carrega.
+ const kitHD = {
+ velho_oeste: ['./map_sertao_hd.js', 'aplicaSertaoHD', {}],
+ }[game._mapId];
+ if (kitHD && new URLSearchParams(location.search).get('hd') === '1') {
+ void import(kitHD[0]).then((m) => { if (window.__game === game) window.__kitHD = m[kitHD[1]](game.scene, game.renderer, kitHD[2]); }).catch((error) => { console.error('[kit-hd] falha', game._mapId, kitHD[0], error); });
+ }
/* RÉGUA:launch-race nascimento fim */
if (ADAPTATIVA && escada.degrau) aplicaDegrau(escada.degrau); // Game.applySettings não pode desfazer o perfil móvel
/* Resto das armas em ocioso no desktop usa malha real em cada drop. Mobile conserva
@@ -4337,57 +4374,46 @@ function pickTeam(faction) {
if (b) b.setAttribute('aria-pressed', String(f.toUpperCase() === faction));
}
const chars = CHARACTERS.filter(c => (lado ? podeNoLado(c, lado) : c.team === faction));
- // ?nav=1 pula o preload 3D do roster (lento) — thumbnails caem no fallback pvThumb, que
- // nunca dispara GLB. A transição #char-select é o que o smoke de navegação quer provar.
- const mountCharList = () => {
- hideLoading();
- const list = $('char-list');
- list.innerHTML = '';
- let firstRow = null, firstChar = null;
- chars.forEach((c) => {
- const row = document.createElement('button');
- row.className = 'char-row';
- // Avatar = busto cortado da ARTE APROVADA (molde/neutro), não do GLB low-poly —
- // referência 03: a coluna da esquerda é uma fileira de retratos, não de modelos 3D.
- const thumb0 = `/img/chars/avatars/${c.id}.webp?v=${VERSION}`;
- row.type = 'button'; row.setAttribute('role', 'option'); row.setAttribute('aria-selected', 'false'); row.title = c.name;
- row.innerHTML = `${c.name}`;
- if (personagemTravado(c)) {
- row.classList.add('char-row--travado'); row.setAttribute('aria-disabled', 'true');
- const trava = document.createElement('b'); trava.className = 'hub-roster-trava';
- trava.dataset.passeNivel = String(nivelDoPersonagem(c) || '');
- trava.innerHTML = ICONE_CADEADO_PASSE; trava.append(frase('passeTravado', nivelDoPersonagem(c) || '?'));
- row.append(trava);
- }
- row.onmouseenter = () => ui.hover();
- // A faixa é horizontal, mas ↑↓ continuam aceitos para quem já usava o fluxo antigo.
- row.onkeydown = (e) => {
- const rows = [...list.children];
- const k = rows.indexOf(row);
- let n = -1;
- if (e.key === 'ArrowRight' || e.key === 'ArrowDown') n = (k + 1) % rows.length;
- else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') n = (k - 1 + rows.length) % rows.length;
- if (n < 0) return;
- e.preventDefault(); rows[n].focus(); rows[n].click();
- };
- row.onclick = () => {
- if (personagemTravado(c)) { $('char-info-blurb').textContent = frase('passeTravadoAviso', c.name, nivelDoPersonagem(c) || '?'); return; }
- selectCharacterFromAvatar(c, row, chars);
- };
- list.appendChild(row);
- if (!firstRow && !personagemTravado(c)) { firstRow = row; firstChar = c; }
- });
- // seleciona DEPOIS de gerar todos os thumbs — senão o preview fica com o último
- show('char-select');
- if (firstRow) selectChar(firstChar, firstRow);
- };
- if (navOnly || previewUsesStills()) { mountCharList(); return; }
- // LOADING REAL da seleção de personagem: os GLBs do roster entram ANTES da tela abrir —
- // nada de thumbnails de caixa montando aos poucos (o "minecraft" que o dono viu)
- showLoading('CARREGANDO PERSONAGENS…');
- /* Travado pelo passe não é escolhível (o clique só explica o nível): a fileira usa o avatar
- estático e o pack Studio dele não é baixado aqui. */
- preloadCharacterAssets(chars.filter(c => !personagemTravado(c)).map(c => c.id)).catch(() => {}).then(mountCharList);
+ hideLoading();
+ const list = $('char-list');
+ list.innerHTML = '';
+ let firstRow = null, firstChar = null;
+ for (const c of chars) {
+ const row = document.createElement('button');
+ row.className = 'char-row';
+ const thumb0 = `/img/chars/avatars/${c.id}.webp?v=${VERSION}`;
+ row.type = 'button'; row.setAttribute('role', 'option'); row.setAttribute('aria-selected', 'false'); row.title = c.name;
+ row.innerHTML = `${c.name}`;
+ if (personagemTravado(c)) {
+ row.classList.add('char-row--travado'); row.setAttribute('aria-disabled', 'true');
+ const trava = document.createElement('b'); trava.className = 'hub-roster-trava';
+ trava.dataset.passeNivel = String(nivelDoPersonagem(c) || '');
+ trava.innerHTML = ICONE_CADEADO_PASSE; trava.append(frase('passeTravado', nivelDoPersonagem(c) || '?'));
+ row.append(trava);
+ }
+ row.onmouseenter = () => {
+ ui.hover();
+ if (navOnly || previewUsesStills() || !GLB_CHARS.has(c.id) || hasModel(c.id) || personagemTravado(c)) return;
+ void preloadCharacterAssets([c.id], { weapons: [] }).catch(() => {});
+ };
+ row.onkeydown = (e) => {
+ const rows = [...list.children];
+ const k = rows.indexOf(row);
+ let n = -1;
+ if (e.key === 'ArrowRight' || e.key === 'ArrowDown') n = (k + 1) % rows.length;
+ else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') n = (k - 1 + rows.length) % rows.length;
+ if (n < 0) return;
+ e.preventDefault(); rows[n].focus(); rows[n].click();
+ };
+ row.onclick = () => {
+ if (personagemTravado(c)) { $('char-info-blurb').textContent = frase('passeTravadoAviso', c.name, nivelDoPersonagem(c) || '?'); return; }
+ selectCharacterFromAvatar(c, row, chars);
+ };
+ list.appendChild(row);
+ if (!firstRow && !personagemTravado(c)) { firstRow = row; firstChar = c; }
+ }
+ show('char-select');
+ if (firstRow) selectChar(firstChar, firstRow);
}
/* Ficha do personagem (tela de seleção): raridade + atributos derivados da arma inicial
(charWeapon) e de um hash estável do id. É FLAVOR de apresentação no estilo CS2/Valorant —
@@ -4628,6 +4654,8 @@ addEventListener('resize', aplicarResize);
addEventListener('orientationchange', () => { aplicarResize(); setTimeout(aplicarResize, 250); setTimeout(aplicarResize, 600); });
if (window.visualViewport) visualViewport.addEventListener('resize', aplicarResize);
const clock = new THREE.Clock();
+// Descarte o intervalo da aba oculta ao retomar o quadro.
+document.addEventListener('visibilitychange', () => clock.getDelta());
let menuAngle = 0;
/* #295: o clamp de 50 ms é teto POR PASSO, não por frame. Como teto por frame ele
descartava metade do tempo real abaixo de 20 FPS e o jogo virava câmera lenta.
@@ -4687,7 +4715,9 @@ function loop(agoraMs = performance.now()) {
for (let n = 0; n < PASSO_TETO && resto > 1e-6; n++) {
const passo = Math.min(0.05, resto);
resto -= passo;
- game.update(passo, resto <= 1e-6 || n === PASSO_TETO - 1); // só o último passo desenha, inclusive ao esgotar o teto
+ const ultimo = resto <= 1e-6 || n === PASSO_TETO - 1;
+ // O último passo desenha e entrega ao cronômetro os segundos que a física descartou.
+ game.update(passo, ultimo, passo + (ultimo ? resto : 0));
}
} else if (!game) {
if (!splashAtiva) {
@@ -4794,9 +4824,11 @@ async function openInspectionScreen(target) {
/* `matchRoster` a partir do elenco do servidor. Personagem desconhecido cai no fallback em
vez de sumir e desalinhar o casamento de ids. */
-function rosterDoServidor(lado, charId) {
- const roster = mpSessao.net.meta.roster || [];
- const meu = mpSessao.net.yourEnt;
+/* Recebe a sessão capturada no início do lançamento: uma queda durante o `await` do preload zera
+ `mpSessao`, e ler o global aqui derrubava a abertura (#1383). Quem perdeu a corrida sai logo depois. */
+function rosterDoServidor(sessao, lado, charId) {
+ const roster = sessao.net.meta.roster || [];
+ const meu = sessao.net.yourEnt;
const def = (r) => ({...(CHARACTERS.find((c) => c.id === r.char) || CHARACTERS[0]), skinId:r.skinId || null,eyewearId:r.eyewearId || null});
return {
allyDefs: roster.filter((r) => r.team === lado && r.id !== meu).map(def),
diff --git a/public/js/map_sertao_hd.js b/public/js/map_sertao_hd.js
new file mode 100644
index 0000000000..9f9b702184
--- /dev/null
+++ b/public/js/map_sertao_hd.js
@@ -0,0 +1,809 @@
+// Kit visual HD do Sertão, atrás de ?hd=1 (demo de gráficos, desligado por padrão).
+// Opções `opts.ceu`, `opts.chao`, `opts.base` e `opts.reboco` controlam cada frente; o céu novo é opt-in por ?hdceu=1 ou `opts.ceu`; ?hdceu=0 é o kill-switch reversível.
+import * as THREE from 'three';
+import { cenografiaSertaoHD } from './hd_cenografia_sertao.js';
+
+const TEX = '/img/textures/pbr_';
+const loader = new THREE.TextureLoader();
+const cacheTex = new Map();
+// Caminho inteiro da textura: os kits que importam pbrTex pedem por aqui, que é a forma que o eval:assetinventory lê.
+export const texHD = (nome) => `/img/textures/${nome}.webp`;
+export function pbrTex(nome, srgb = false, rep = 1) {
+ if (nome.endsWith('.webp')) nome = nome.slice('/img/textures/'.length, -'.webp'.length);
+ const [rx, ry] = Array.isArray(rep) ? rep : [rep, rep], chave = `${nome}|${rx}|${ry}`;
+ if (!cacheTex.has(chave)) {
+ const t = loader.load(nome.startsWith('/') ? `/img/textures${nome}.webp` : nome.includes('/') ? `/img/textures/${nome}.webp` : `${TEX}${nome}.webp`);
+ t.wrapS = t.wrapT = THREE.RepeatWrapping; t.repeat.set(rx, ry); t.anisotropy = 8;
+ if (srgb) t.colorSpace = THREE.SRGBColorSpace;
+ t.name = `hd-${nome}`;
+ cacheTex.set(chave, t);
+ }
+ return cacheTex.get(chave);
+}
+
+// Conjuntos antigos só têm cor: deriva o relevo da luminância (Sobel) uma vez, na carga.
+const cacheRelevo = new WeakMap();
+export function relevoDeCor(tex, forca = 2.2, lado = 512) {
+ // Uma tela por IMAGEM (tex.source): clones do mesmo mapa dividem a mesma textura na GPU.
+ const copia = (base) => { const c = base.clone(); c.repeat.copy(tex.repeat); c.needsUpdate = true; return c; };
+ if (cacheRelevo.has(tex.source)) return copia(cacheRelevo.get(tex.source));
+ const cv = document.createElement('canvas'); cv.width = cv.height = lado;
+ const saida = new THREE.CanvasTexture(cv);
+ saida.wrapS = saida.wrapT = THREE.RepeatWrapping; saida.anisotropy = 8; saida.name = `hd-relevo-${tex.name || 'cor'}`;
+ const ctx = cv.getContext('2d', { willReadFrequently: true }); ctx.fillStyle = '#8080ff'; ctx.fillRect(0, 0, lado, lado);
+ const gera = () => {
+ const img = tex.image; if (!img || !img.width) return false;
+ ctx.drawImage(img, 0, 0, lado, lado);
+ const src = ctx.getImageData(0, 0, lado, lado), d = src.data, L = new Float32Array(lado * lado);
+ for (let i = 0; i < L.length; i++) L[i] = (d[i * 4] * .299 + d[i * 4 + 1] * .587 + d[i * 4 + 2] * .114) / 255;
+ const at = (x, y) => L[((y + lado) % lado) * lado + ((x + lado) % lado)];
+ for (let y = 0; y < lado; y++) for (let x = 0; x < lado; x++) {
+ const dx = (at(x + 1, y - 1) + 2 * at(x + 1, y) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2 * at(x - 1, y) + at(x - 1, y + 1));
+ const dy = (at(x - 1, y + 1) + 2 * at(x, y + 1) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2 * at(x, y - 1) + at(x + 1, y - 1));
+ const nx = -dx * forca, ny = dy * forca, inv = 1 / Math.hypot(nx, ny, 1), i = (y * lado + x) * 4;
+ d[i] = (nx * inv * .5 + .5) * 255; d[i + 1] = (ny * inv * .5 + .5) * 255; d[i + 2] = (inv * .5 + .5) * 255; d[i + 3] = 255;
+ }
+ ctx.putImageData(src, 0, 0); saida.needsUpdate = true; return true;
+ };
+ if (!gera()) { const t0 = performance.now(); const espera = () => { if (!gera() && performance.now() - t0 < 15000) setTimeout(espera, 120); }; espera(); }
+ cacheRelevo.set(tex.source, saida); return copia(saida);
+}
+
+// Ruído de valor barato (sem leitura de textura) para mancha, escorrido e poça.
+export const RUIDO_GLSL = `
+ float hdH(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
+ float hdN(vec2 p){ vec2 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(hdH(i), hdH(i + vec2(1.0, 0.0)), f.x), mix(hdH(i + vec2(0.0, 1.0)), hdH(i + vec2(1.0, 1.0)), f.x), f.y); }
+`;
+// Grão fino de superfície; some quando o passo vira menor que o pixel, para não cintilar ao longe.
+export const GRAO_GLSL = `
+ float hdGrao(vec2 q){ float a = smoothstep(0.5, 0.12, fwidth(q.x) * 34.0);
+ return 1.0 + a * ((hdN(q * 34.0) - 0.5) * 0.22 + (hdN(q * 87.0) - 0.5) * 0.13); }
+ // Trinca: uma linha por faixa de 1,7 m que serpenteia ao longo de q.y. Curva de nível de ruído fechava
+ // laço e lia como rabisco; aqui a linha nunca volta sobre si. Some de longe (passo maior que o pixel).
+ float hdTrincaL(vec2 q){ float c = floor(q.x / 1.7), fx = q.x - (c + 0.5) * 1.7, l = fwidth(q.x);
+ float w = (hdN(vec2(c * 7.31, q.y * 1.1)) - 0.5) + (hdN(vec2(c * 3.7 + 9.0, q.y * 4.3)) - 0.5) * 0.18;
+ float existe = step(0.5, hdH(vec2(c, 3.0))) * smoothstep(0.42, 0.6, hdN(vec2(c * 5.1, q.y * 0.35)));
+ return (1.0 - smoothstep(0.003, 0.005 + l * 1.2, abs(fx - w))) * existe * smoothstep(0.03, 0.008, l); }
+`;
+// `sub` = material de baixo do reboco ({ tex, metros, cor }): o reboco descasca no pé e no alto
+// e mostra o tijolo ou o adobe. Na faixa do corpo quase não descasca (leitura de inimigo).
+export function ligaSub(shader, sub) {
+ if (!sub) return;
+ shader.uniforms.hdSub = { value: sub.tex };
+ shader.fragmentShader = shader.fragmentShader.replace('#include ', '#include \nuniform sampler2D hdSub;');
+}
+// `liso` (0..1): na faixa do corpo (0,45–2,1 m) a cor da textura vai para a sua média local (mip +6) e fica só o grão fino
+// (razão 0,95–1,05); mancha, umidade e pé zeram ali. Mancha de albedo do tamanho de cabeça na faixa lia como inimigo.
+export const idadeDaParede = (rodape, piso = '0.0', suave = false, sub = null, pe = null, leve = false, grao = 1, macro = 1, liso = 0) => `
+ { float hdY = vHdPos.y - ${piso}; vec2 hdQ = vec2(vHdPos.x + vHdPos.z, hdY);
+ float hdMacro = hdN(hdQ * 0.55) * 0.6 + hdN(hdQ * 1.9) * 0.4;
+ float hdCorpo = smoothstep(0.6, 0.9, hdY) * (1.0 - smoothstep(1.7, 2.0, hdY));
+ ${liso > 0 ? `float hdLiso = ${liso.toFixed(3)} * smoothstep(0.42, 0.58, hdY) * (1.0 - smoothstep(1.92, 2.12, hdY));
+ #ifdef USE_MAP
+ { vec3 hdMed = diffuse * texture2D(map, vMapUv, 6.0).rgb;
+ diffuseColor.rgb = mix(diffuseColor.rgb, hdMed * clamp(diffuseColor.rgb / max(hdMed, vec3(1e-4)), 0.95, 1.05), hdLiso); }
+ #endif` : ''}
+ ${suave ? `#ifdef USE_MAP
+ diffuseColor.rgb = mix(diffuseColor.rgb, diffuse * texture2D(map, vMapUv, 4.5).rgb, 0.7 * hdCorpo);
+ #endif` : ''}
+ float hdMedio = hdN(hdQ * 5.5) * 0.55 + hdN(hdQ * 13.0) * 0.45;
+ diffuseColor.rgb *= ${liso > 0 ? 'mix(' : ''}${macro === 1 ? '' : `mix(1.0, `}mix(mix(0.72, 1.12, hdMacro), mix(0.93, 1.05, hdMacro), hdCorpo)${macro === 1 ? '' : `, ${macro.toFixed(3)})`} * mix(mix(0.88, 1.08, hdMedio), mix(0.96, 1.03, hdMedio), hdCorpo)${liso > 0 ? ', 1.0, hdLiso)' : ''} * ${grao === 1 ? 'hdGrao(hdQ)' : `mix(1.0, hdGrao(hdQ), ${grao.toFixed(3)})`};
+ float hdEsc = smoothstep(0.66, 0.86, hdN(vec2(hdQ.x * 1.05 + hdN(hdQ * 0.31) * 2.3, hdY * 0.2))) * smoothstep(1.9, 3.1, hdY)${liso > 0 ? ' * (1.0 - hdLiso)' : ''};
+ diffuseColor.rgb *= 1.0 - 0.27 * hdEsc;
+ float hdTrinca = hdTrincaL(vec2(hdQ.x, hdY));
+ diffuseColor.rgb *= 1.0 - mix(0.42, 0.2, hdCorpo) * hdTrinca;
+ float hdPele = 0.0;
+ ${sub ? `vec2 hdP = hdQ + 3.7, hdP2 = hdP + vec2(0.0, max(0.02, length(fwidth(hdQ)) * 1.6));
+ ${leve ? `float hdFbA = hdN(hdP * 8.0) * 0.14, hdFb = hdN(hdP * 1.1) * 0.56 + hdN(hdP * 3.0) * 0.30 + hdFbA;
+ float hdFb2 = hdN(hdP2 * 1.1) * 0.56 + hdN(hdP2 * 3.0) * 0.30 + hdFbA;` : `float hdFb = hdN(hdP * 1.1) * 0.56 + hdN(hdP * 3.0) * 0.30 + hdN(hdP * 8.0) * 0.10 + hdN(hdP * 25.0) * 0.04;
+ float hdFb2 = hdN(hdP2 * 1.1) * 0.56 + hdN(hdP2 * 3.0) * 0.30 + hdN(hdP2 * 8.0) * 0.10 + hdN(hdP2 * 25.0) * 0.04;`}
+ float hdLim = mix(mix(mix(${(sub.pe ?? .56).toFixed(3)}, 0.73, smoothstep(${(sub.y0 ?? 0).toFixed(3)}, ${((sub.y0 ?? 0) + .75).toFixed(3)}, hdY)), ${(sub.alto ?? .71).toFixed(3)}, smoothstep(1.9, 2.4, hdY)), 0.80, hdCorpo);
+ float hdW = max(0.004, fwidth(hdFb) * 0.5);
+ hdPele = smoothstep(hdLim, hdLim + hdW, hdFb); float hdPele2 = smoothstep(hdLim, hdLim + hdW, hdFb2);
+ ${sub.foraDoCorpo ? `float hdFora = smoothstep(2.1, 2.25, hdY) + 1.0 - smoothstep(0.38, 0.5, hdY); hdPele *= hdFora; hdPele2 *= hdFora;` : ''}
+ ${sub.tijolo ? `// Tijolo com junta desenhada (fiada de 20 cm, amarração): buraco sem junta lia como mancha de pele ou sangue.
+ vec2 hdBr = vec2(hdQ.x / 0.30 + 0.5 * floor(hdY / 0.20), hdY / 0.20), hdBf = abs(fract(hdBr) - 0.5);
+ float hdJa = smoothstep(0.5, 0.15, fwidth(hdBr.y));
+ float hdJ = (1.0 - smoothstep(0.006, 0.013, min((0.5 - hdBf.x) * 0.30, (0.5 - hdBf.y) * 0.20))) * hdJa;
+ vec3 hdSubC = texture2D(hdSub, hdQ / ${sub.metros.toFixed(3)}, 6.0).rgb * vec3(${sub.cor.map((c) => c.toFixed(3)).join(', ')})
+ * (1.0 + 0.3 * (hdH(floor(hdBr)) - 0.5) * hdJa) * (1.0 - 0.1 * hdJa * step(0.5, fract(hdBr.y * 4.0)));
+ hdSubC = mix(hdSubC, vec3(0.50, 0.48, 0.45) * mix(0.8, 1.1, hdMedio), hdJ * 0.9);` : sub.adobe ? `// Adobe: brilho preso ao da parede (contraste fixo); a fiada some sozinha no mip quando passa de ~3 px.
+ float hdAl = dot(texture2D(hdSub, hdQ / ${sub.metros.toFixed(3)}).rgb, vec3(0.3, 0.59, 0.11)) / ${(sub.media ?? .1).toFixed(4)};
+ vec3 hdSubC = vec3(${sub.cor.map((c) => c.toFixed(3)).join(', ')}) * (dot(diffuseColor.rgb, vec3(0.3, 0.59, 0.11)) * ${(sub.razao ?? .77).toFixed(3)})
+ * clamp(1.0 + (1.0 - hdAl) * ${(sub.junta ?? .5).toFixed(3)}, 0.72, 1.3) * mix(0.93, 1.07, hdN(hdP * 0.6 + 9.0));` : sub.taipa ? `// Taipa: barro escuro acinzentado com a trama de varas à mostra; nunca tom de pele.
+ float hdTa = smoothstep(0.6, 0.15, fwidth(hdY) / 0.17);
+ float hdVh = smoothstep(0.26, 0.4, abs(fract(hdY / 0.17 + 0.2 * hdN(vec2(hdQ.x * 0.7, floor(hdY / 0.17)))) - 0.5));
+ float hdVv = smoothstep(0.34, 0.44, abs(fract(hdQ.x / 0.31) - 0.5));
+ float hdBarro = dot(texture2D(hdSub, hdQ / ${sub.metros.toFixed(3)}).rgb, vec3(0.3, 0.59, 0.11)) * 2.2;
+ vec3 hdSubC = vec3(${sub.cor.map((c) => c.toFixed(3)).join(', ')}) * mix(0.75, 1.25, clamp(hdBarro, 0.0, 1.0)) * mix(0.8, 1.15, hdN(hdQ * 21.0));
+ hdSubC = mix(hdSubC, hdSubC * 1.45, hdVh * hdTa * (1.0 - 0.5 * hdVv));
+ hdSubC *= 1.0 - 0.45 * hdVv * hdTa * (1.0 - hdVh);` : `vec3 hdSubC = texture2D(hdSub, hdQ / ${sub.metros.toFixed(3)}).rgb * vec3(${sub.cor.map((c) => c.toFixed(3)).join(', ')});`}
+ // Cada buraco com seu tom (quente ou frio) e menos saturado: mancha toda igual lia como tinta, não como parede.
+ ${sub.adobe ? '' : `hdSubC = mix(vec3(dot(hdSubC, vec3(0.3, 0.59, 0.11))), hdSubC, ${(sub.sat ?? 1).toFixed(3)}) * mix(vec3(1.06, 0.98, 0.9), vec3(0.9, 0.97, 1.04), hdN(hdP * 0.45 + 2.0)) * mix(0.82, 1.1, hdN(hdP * 0.6 + 9.0));`}
+ // Espessura do reboco: 2 cm acima ainda é reboco = sombra do beiço no buraco; o beiço de baixo pega luz de cima.
+ hdSubC *= 1.0 - ${(sub.beico ?? .55).toFixed(3)} * (1.0 - hdPele2);
+ diffuseColor.rgb *= 1.0 + 0.16 * hdPele2 * (1.0 - hdPele);
+ diffuseColor.rgb = mix(diffuseColor.rgb, mix(diffuseColor.rgb, hdSubC, ${(sub.forca ?? 1).toFixed(3)}), hdPele);` : ''}
+ ${pe ? `float hdSuj = smoothstep(${pe.altura.toFixed(3)}, 0.04, hdY + (hdN(hdQ * vec2(2.3, 0.0)) - 0.5) * 0.22) * (0.62 + 0.38 * hdN(hdQ * 1.3))${liso > 0 ? ' * (1.0 - hdLiso)' : ''};
+ vec3 hdTerra = vec3(${pe.cor.map((c) => c.toFixed(3)).join(', ')});
+ hdTerra *= ${(1 - pe.escuro).toFixed(3)} * dot(diffuseColor.rgb, vec3(0.3, 0.59, 0.11)) / dot(hdTerra, vec3(0.3, 0.59, 0.11));
+ diffuseColor.rgb = mix(diffuseColor.rgb, hdTerra * mix(0.86, 1.12, hdMedio), hdSuj); }` : `float hdSuj = smoothstep(${rodape.toFixed(3)}, 0.05, hdY) * (0.5 + 0.5 * hdN(hdQ * 1.3)) * (1.0 - 0.6 * hdPele)${liso > 0 ? ' * (1.0 - hdLiso)' : ''};
+ diffuseColor.rgb = mix(diffuseColor.rgb, diffuseColor.rgb * vec3(0.55, 0.45, 0.36), hdSuj); }`}`;
+
+// Caixas instanciadas têm UV 0..1 por face: sem projeção no mundo o relevo estica com a parede.
+export function projetaMundo(material, metros, { rodape = 0, metrosCor = metros, sub = null, pe = null, extra = null, leve = false, grao = 1, macro = 1, corpoLiso = 0 } = {}) {
+ material.onBeforeCompile = (shader) => {
+ if (rodape > 0) {
+ shader.vertexShader = shader.vertexShader.replace('#include ', `#include \nvarying vec3 vHdPos;${extra?.vertCabeca || ''}`);
+ shader.fragmentShader = shader.fragmentShader.replace('#include ', `#include \nvarying vec3 vHdPos;${RUIDO_GLSL}${GRAO_GLSL}${extra?.cabeca || ''}`)
+ .replace('#include ', `#include \n${extra?.antes || ''}${idadeDaParede(rodape, '0.0', false, sub, pe, leve, grao, macro, corpoLiso)}${extra?.depois || ''}`);
+ if (extra?.normal) shader.fragmentShader = shader.fragmentShader.replace('#include ', `#include \n${extra.normal}`);
+ ligaSub(shader, sub);
+ if (extra?.uniforms) Object.assign(shader.uniforms, extra.uniforms);
+ }
+ shader.vertexShader = shader.vertexShader.replace('#include ', `#include
+ {
+ vec4 hdMundo = vec4(position, 1.0);
+ vec3 hdN3 = normal;
+ #ifdef USE_INSTANCING
+ hdMundo = instanceMatrix * hdMundo;
+ hdN3 = mat3(instanceMatrix) * hdN3;
+ #endif
+ hdMundo = modelMatrix * hdMundo;
+ hdN3 = abs(normalize(mat3(modelMatrix) * hdN3));
+ vec2 hdUv = (hdN3.y > max(hdN3.x, hdN3.z) ? hdMundo.xz : (hdN3.x > hdN3.z ? hdMundo.zy : hdMundo.xy)) / ${metros.toFixed(3)};
+ #ifdef USE_MAP
+ vMapUv = hdUv * ${(metros / metrosCor).toFixed(4)};
+ #endif
+ #ifdef USE_NORMALMAP
+ vNormalMapUv = hdUv;
+ #endif
+ #ifdef USE_ROUGHNESSMAP
+ vRoughnessMapUv = hdUv;
+ #endif
+ #ifdef USE_BUMPMAP
+ vBumpMapUv = hdUv;
+ #endif
+ ${rodape > 0 ? `vHdPos = hdMundo.xyz;${extra?.vert || ''}` : ''}
+ }`);
+ };
+ material.customProgramCacheKey = () => `sertao-hd-mundo10-${metros}-${rodape}-${metrosCor}-${sub ? `${sub.metros}${sub.cor}${sub.pe}${sub.alto}${sub.y0}${sub.sat}${sub.forca}${sub.tijolo}${sub.taipa}${sub.foraDoCorpo}${sub.adobe ? `a${sub.razao}${sub.junta}${sub.media}${sub.beico}` : ''}` : 0}-${pe ? `${pe.cor}${pe.altura}${pe.escuro}` : 0}${extra ? `-${extra.chave}` : ''}${leve ? '-leve' : ''}${grao === 1 && macro === 1 ? '' : `-g${grao}-${macro}`}${corpoLiso > 0 ? `-liso${corpoLiso}` : ''}`;
+}
+
+export const materiaisDe = (o) => (Array.isArray(o.material) ? o.material : [o.material]).filter(Boolean);
+
+// Adobe aparente por baixo do reboco caiado (mesma imagem que o mapa já usa nas paredes sem reboco).
+// A sapata de pedra cobre até 0,42 m: o descascado começa acima dela (y0).
+const adobeDeBaixo = (extra = {}) => ({ tex: extra.tex || pbrTex('/tex_adobe', true), metros: 1.5, cor: [.82, .74, .66], y0: .38, pe: .55, alto: .66, sat: .85, ...extra });
+// Terra do pé da parede no matiz que o chão mostra sob o sol da tarde; mais vermelha lia como ferrugem.
+const TERRA = [.16, .118, .09];
+// Barrado de tinta gasta por casa: anil, verde-água e ocre desbotados (linear). Nada verde-escuro (escondia perna).
+const BARRADOS = [[.17, .26, .40], [.28, .42, .35], [.50, .36, .12]];
+const LUMA = 'vec3(0.3, 0.59, 0.11)';
+function acabamentoParede(scene, { albedo = .7, barrado = true, sujeira = .9, dessat = .4, fino = 1.1, perto = 2.45, grao2 = 1, realce = 1.16, ceu = .42, sol = .15 } = {}) {
+ const casas = []; scene.traverse((o) => { if (/^sertao-(casa-[a-z]+|praca-casa-interior)-\d+$/.test(o.name)) { const p = o.getWorldPosition(new THREE.Vector3()); casas.push(new THREE.Vector4(p.x, p.z, 56, casas.length % 3)); } });
+ const matriz = scene.getObjectByName('sertao-igrejinha-0'); if (matriz) casas.push(new THREE.Vector4(matriz.position.x, matriz.position.z, 30, 0));
+ const n = barrado ? casas.length : 0, cor = (c) => `vec3(${c.map((v) => v.toFixed(3)).join(', ')})`;
+ return { chave: `parede17-${albedo}-${n}-${sujeira}-${dessat}-${fino}-${perto}-${grao2}-${realce}-${ceu}-${sol}`,
+ uniforms: { hdDet: { value: pbrTex('hd_sertao/white_rough_plaster_cor') }, ...(n ? { hdCasas: { value: casas } } : {}) },
+ vertCabeca: `varying vec4 vHdBarra;${n ? `uniform vec4 hdCasas[${n}];` : ''}`,
+ vert: `vHdBarra = vec4(0.0);${n ? `{ float hdPerto = 1e9; for (int i = 0; i < ${n}; i++) { vec2 hdDc = hdMundo.xz - hdCasas[i].xy; float hdD2c = dot(hdDc, hdDc);
+ if (hdD2c < hdCasas[i].z && hdD2c < hdPerto) { hdPerto = hdD2c; vHdBarra = vec4(hdCasas[i].w < 0.5 ? ${cor(BARRADOS[0])} : (hdCasas[i].w < 1.5 ? ${cor(BARRADOS[1])} : ${cor(BARRADOS[2])}), 1.0); } } }` : ''}`,
+ cabeca: 'uniform sampler2D hdDet; varying vec4 vHdBarra;',
+ // Faixa do corpo (0,6 a 1,9 m): detalhe e mancha contidos; o grosso da sujeira fica acima de 2,1 m e abaixo de 0,5 m.
+ antes: `float hdD1 = 1.0, hdD2 = 1.0, hdD3 = 1.0;
+ { float hdYa = vHdPos.y; vec2 hdQa = vec2(vHdPos.x + vHdPos.z, hdYa);
+ float hdCa = smoothstep(0.5, 0.62, hdYa) * (1.0 - smoothstep(1.95, 2.12, hdYa)), hdTorso = 0.85 * smoothstep(0.4, 0.6, hdYa) * (1.0 - 0.6 * smoothstep(2.2, 2.9, hdYa));
+ #ifdef USE_NORMALMAP
+ hdD1 = dot(texture2D(hdDet, vNormalMapUv).rgb, ${LUMA}) / 0.61;
+ hdD1 = mix(hdD1, hdD1 / clamp(dot(texture2D(hdDet, vNormalMapUv, 3.0).rgb, ${LUMA}) / 0.61, 0.5, 1.6), hdTorso);
+ hdD3 = mix(1.0, dot(texture2D(hdDet, vNormalMapUv * 3.1 + 0.23).rgb, ${LUMA}) / 0.61, smoothstep(4.0, 1.5, length(fwidth(vNormalMapUv)) * 3174.0));
+ #endif
+ hdD2 = dot(texture2D(hdDet, hdQa / 4.7 + 0.37).rgb, ${LUMA}) / 0.61;
+ #ifdef USE_MAP
+ diffuseColor.rgb *= mix(1.0, clamp(dot(texture2D(map, vMapUv, 7.0).rgb, ${LUMA}) / max(dot(texture2D(map, vMapUv, 3.0).rgb, ${LUMA}), 0.02), 0.6, 1.6), hdTorso);
+ #endif
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(dot(diffuseColor.rgb, ${LUMA})), ${dessat.toFixed(3)}) * vec3(1.0, 0.995, 0.98);
+ diffuseColor.rgb *= ${albedo.toFixed(3)} * min(${realce.toFixed(3)}, mix(1.0, clamp(hdD1, 0.5, 1.25), mix(0.95, 0.85, hdCa)) * mix(1.0, clamp(hdD3, 0.6, 1.15), ${(0.5 * fino).toFixed(3)})) * mix(1.0, clamp(hdD2, 0.45, 1.25), mix(0.42, 0.07, hdCa));
+ if (vHdBarra.a > 0.5) { float hdTopo = 0.9 + (hdN(vec2(hdQa.x * 0.8, 3.0)) - 0.5) * 0.06;
+ float hdGasto = smoothstep(0.42, 0.72, hdN(hdQa * vec2(1.7, 2.9) + 11.0) * 0.55 + hdN(hdQa * 7.0 + 5.0) * 0.25 + (1.0 - clamp(hdD1, 0.0, 1.0)) * 0.9);
+ float hdTinta = (1.0 - smoothstep(hdTopo - 0.01, hdTopo + 0.01, hdYa)) * mix(0.8, 0.2, hdGasto);
+ diffuseColor.rgb = mix(diffuseColor.rgb, vHdBarra.rgb * (dot(diffuseColor.rgb, ${LUMA}) * 0.93 / dot(vHdBarra.rgb, ${LUMA})), hdTinta); } }`,
+ depois: `{ float hdYb = vHdPos.y; vec2 hdQb = vec2(vHdPos.x + vHdPos.z, hdYb);
+ float hdAlto = smoothstep(2.5, 3.2, hdYb), hdBaixo = 1.0 - smoothstep(0.15, 0.5, hdYb);
+ float hdEsc0 = smoothstep(0.66, 0.86, hdN(vec2(hdQb.x * 1.05 + hdN(hdQb * 0.31) * 2.3, hdYb * 0.2))) * smoothstep(1.9, 3.1, hdYb);
+ diffuseColor.rgb *= (1.0 - 0.27 * hdEsc0 * hdAlto) / (1.0 - 0.27 * hdEsc0);
+ float hdFio = hdN(vec2(hdQb.x * 2.6, hdYb * 0.3)) * 0.55 + hdN(vec2(hdQb.x * 9.0, hdYb * 0.7 + 4.0)) * 0.45;
+ float hdEscB = smoothstep(0.4, 0.72, hdFio + (1.0 - hdD2) * 0.5) * hdAlto;
+ diffuseColor.rgb *= mix(vec3(1.0), vec3(0.66, 0.58, 0.5), min(1.0, hdEscB * ${(0.8 * sujeira).toFixed(3)}));
+ float hdResp = hdBaixo * smoothstep(0.35, 0.7, hdN(hdQb * vec2(5.0, 8.0)) * 0.55 + hdN(hdQb * 19.0) * 0.45 + hdBaixo * 0.3);
+ diffuseColor.rgb = mix(diffuseColor.rgb, ${cor(TERRA)} * (dot(diffuseColor.rgb, ${LUMA}) * 0.8 / ${(TERRA[0] * .3 + TERRA[1] * .59 + TERRA[2] * .11).toFixed(4)}), min(1.0, hdResp * ${(0.6 * sujeira).toFixed(3)})); }`,
+ // Relevo fino do reboco (grão de ~1 cm) pela derivada de tela; some de longe para não cintilar.
+ normal: `{ float hdFw = length(fwidth(vNormalMapUv)), hdP1 = smoothstep(1.0, 0.5, hdFw * 55.0), hdP2 = smoothstep(1.0, 0.5, hdFw * 170.0), hdSolN = 1.0;
+ #if NUM_DIR_LIGHTS > 0
+ hdSolN = 1.0 - ${sol.toFixed(3)} * smoothstep(0.3, 0.7, dot(nonPerturbedNormal, directionalLights[0].direction));
+ #endif
+ #ifdef USE_NORMALMAP_TANGENTSPACE
+ vec3 hdM2 = texture2D(normalMap, vNormalMapUv * 3.1 + 0.23).xyz * 2.0 - 1.0;
+ normal = normalize(tbn * vec3(mapN.xy * (mix(0.88, 1.0, smoothstep(12.0, 4.0, hdFw * 1024.0)) * mix(1.0, ${perto.toFixed(3)}, hdP1) * hdSolN) + hdM2.xy * normalScale * (${grao2.toFixed(3)} * hdP2 * hdSolN), mapN.z));
+ diffuseColor.rgb *= 1.0 + ${ceu.toFixed(3)} * hdSolN * mix(0.3, 1.0, hdP1) * clamp(mapN.y * mix(1.0, ${perto.toFixed(3)}, hdP1) + hdM2.y * normalScale.y * ${grao2.toFixed(3)} * hdP2, -3.0, 0.9) / 3.0;
+ #endif
+ float hdAltP = (hdD3 - 1.0) * ${(0.017 * fino).toFixed(4)} * smoothstep(26.0, 9.0, length(vViewPosition));
+ vec3 hdSx = dFdx(-vViewPosition), hdSy = dFdy(-vViewPosition), hdR1 = cross(hdSy, normal), hdR2 = cross(normal, hdSx); float hdDt = dot(hdSx, hdR1);
+ normal = normalize(abs(hdDt) * normal - sign(hdDt) * (dFdx(hdAltP) * hdR1 + dFdy(hdAltP) * hdR2));
+ // Face quase de costas para o sol: o relevo não pode acender ponto que a parede lisa não acenderia.
+ #if NUM_DIR_LIGHTS > 0
+ { vec3 hdLd = directionalLights[0].direction; float hdLim = max(dot(nonPerturbedNormal, hdLd), 0.0) * ${realce.toFixed(3)} + 0.02, hdPl = dot(normal, hdLd);
+ if (hdPl > hdLim) normal = normalize(normal - hdLd * (hdPl - hdLim)); }
+ #endif
+ }` };
+}
+function rebocoHD(scene, { metros = 1.1, relevo = 3.65, rodape = .75, adobe = true, pe = { cor: TERRA, altura: .62, escuro: .34 }, parede = {} } = {}) {
+ const alvos = new Set();
+ scene.traverse((o) => { if (o.isMesh) for (const m of materiaisDe(o)) if (m.map?.name === 'oeste-adobe-paupique' || m.map?.name === 'oeste-adobe-real') alvos.add(m); });
+ const antes = [...alvos].map((m) => ({ m, map: m.map, bumpMap: m.bumpMap, normalMap: m.normalMap, roughnessMap: m.roughnessMap,
+ roughness: m.roughness, ns: m.normalScale.x, obc: m.onBeforeCompile, key: m.customProgramCacheKey }));
+ const extra = parede === false ? null : acabamentoParede(scene, parede);
+ for (const m of alvos) {
+ // A cor autoral fica: trocá-la pelo reboco limpo apagava a pátina que dá idade à parede.
+ m.bumpMap = null; m.normalMap = pbrTex('hd_sertao/white_rough_plaster_normal'); m.normalScale.set(relevo, relevo);
+ m.roughnessMap = null; m.roughness = .96;
+ projetaMundo(m, metros, { rodape, metrosCor: 3, pe: pe || null, extra, leve: true, macro: .6,
+ sub: m.map?.name === 'oeste-adobe-paupique' ? adobeDeBaixo(adobe ? { adobe: true, foraDoCorpo: true, tex: pbrTex('hd_sertao/clay_block_wall_cor', true), metros: 1.6, media: .1178,
+ cor: [1.38, .86, .5], razao: .56, junta: .9, alto: .725, pe: .66 } : {}) : null }); m.needsUpdate = true;
+ }
+ return () => { for (const s of antes) { Object.assign(s.m, { map: s.map, bumpMap: s.bumpMap, normalMap: s.normalMap,
+ roughnessMap: s.roughnessMap, roughness: s.roughness, onBeforeCompile: s.obc, customProgramCacheKey: s.key }); s.m.normalScale.set(s.ns, s.ns); s.m.needsUpdate = true; } };
+}
+
+// Base de pedra, madeira e chão: os três ainda eram 512 px só cor, com bumpMap = a própria cor.
+function baseHD(scene, { pedraMetros = 1.6, madeira = 2.2, chao = 150, telha = 2.6 } = {}) {
+ const porMapa = new Map();
+ scene.traverse((o) => { if (o.isMesh) for (const m of materiaisDe(o)) if (m.map?.name && m.isMeshStandardMaterial) (porMapa.get(m.map.name) || porMapa.set(m.map.name, new Set()).get(m.map.name)).add(m); });
+ const antes = [], guarda = (m) => antes.push({ m, cor: m.color.clone(), map: m.map, bumpMap: m.bumpMap, normalMap: m.normalMap, roughnessMap: m.roughnessMap, roughness: m.roughness,
+ ns: m.normalScale.x, obc: m.onBeforeCompile, key: m.customProgramCacheKey });
+ for (const m of porMapa.get('oeste-pedra-real') || []) { guarda(m);
+ m.map = pbrTex('cobblestone_floor_01_color', true); m.bumpMap = null; m.normalMap = pbrTex('cobblestone_floor_01_normal'); m.normalScale.set(3.1, 3.1);
+ m.roughnessMap = pbrTex('cobblestone_floor_01_rough'); m.roughness = 1; m.color.setRGB(1.45, 1.36, 1.2); projetaMundo(m, pedraMetros); suavizaDetalheHD(m, `pedra-${pedraMetros}`); m.needsUpdate = true; }
+ for (const m of telha ? porMapa.get('oeste-roof-real') || [] : []) { guarda(m); m.userData.hdLaje = true;
+ m.map = pbrTex('hd_sertao/clay_roof_tiles_02_cor', true); m.bumpMap = null; m.normalMap = pbrTex('hd_sertao/clay_roof_tiles_02_normal'); m.normalScale.set(3.4, 3.4); m.color.setRGB(.66, .7, .74);
+ // Fiada da telha segue a queda da água: a direção sai da componente horizontal da normal do plano.
+ m.onBeforeCompile = (shader) => { shader.fragmentShader = shader.fragmentShader.replace('#include ', '#include \nvarying float vHdBaixo;')
+ .replace('#include ', '#include \nif (vHdBaixo < -0.3) normal = nonPerturbedNormal;');
+ shader.vertexShader = shader.vertexShader.replace('#include ', '#include \nvarying float vHdBaixo;').replace('#include ', `#include
+ { vec4 hdW = vec4(position, 1.0); vec3 hdNt = normal;
+ #ifdef USE_INSTANCING
+ hdW = instanceMatrix * hdW; hdNt = mat3(instanceMatrix) * hdNt;
+ #endif
+ hdW = modelMatrix * hdW; hdNt = normalize(mat3(modelMatrix) * hdNt); vHdBaixo = hdNt.y;
+ float hdLs = length(hdNt.xz); vec2 hdE = hdLs > 0.04 ? hdNt.xz / hdLs : vec2(0.0, 1.0);
+ vec2 hdUv = (abs(hdNt.y) > 0.5 ? vec2(dot(hdW.xz, vec2(-hdE.y, hdE.x)), dot(hdW.xz, hdE) / max(abs(hdNt.y), 0.3)) : (abs(hdNt.x) > abs(hdNt.z) ? hdW.zy : hdW.xy)) / ${telha.toFixed(3)};
+ #ifdef USE_MAP
+ vMapUv = hdUv;
+ #endif
+ #ifdef USE_NORMALMAP
+ vNormalMapUv = hdUv;
+ #endif
+ }`); };
+ m.customProgramCacheKey = () => `sertao-hd-telha2-${telha}`; suavizaDetalheHD(m, `telha-${telha}`); m.needsUpdate = true; }
+ for (const nome of [...(telha ? [] : ['oeste-roof-real']), 'oeste-hay-real', 'oeste-cactus-real'])
+ for (const m of porMapa.get(nome) || []) { guarda(m); m.bumpMap = null; m.normalMap = relevoDeCor(m.map, madeira); m.normalScale.set(1, 1); m.needsUpdate = true; }
+ for (const m of porMapa.get('oeste-sand-real') || []) { guarda(m);
+ // Terra seca usa escala de 8 m: trinca fina e pedrinhas esparsas, sem placa de cascalho.
+ m.map = pbrTex('hd_sertao/dry_ground_01_cor', true, chao); m.normalMap = pbrTex('hd_sertao/dry_ground_01_normal', false, chao); m.normalScale.set(.34, .34);
+ m.roughnessMap = pbrTex('hd_sertao/dry_ground_01_rough', false, chao); m.roughness = 1; m.bumpMap = null;
+ m.color.setRGB(.74, .61, .5); m.needsUpdate = true; }
+ return () => { for (const s of antes) { Object.assign(s.m, { map: s.map, bumpMap: s.bumpMap, normalMap: s.normalMap, roughnessMap: s.roughnessMap,
+ roughness: s.roughness, onBeforeCompile: s.obc, customProgramCacheKey: s.key }); s.m.color.copy(s.cor); s.m.normalScale.set(s.ns, s.ns); delete s.m.userData.hdLaje; s.m.needsUpdate = true; } };
+}
+
+// Atenua normal e albedo de materiais repetidos quando o passo UV fica menor que um pixel.
+function suavizaDetalheHD(material, chave = '') {
+ const obc = material.onBeforeCompile, key = material.customProgramCacheKey;
+ material.onBeforeCompile = (shader, renderer) => {
+ obc?.call(material, shader, renderer);
+ shader.fragmentShader = shader.fragmentShader.replace('#include ', `#include
+ { float hdPasso = max(fwidth(vNormalMapUv.x), fwidth(vNormalMapUv.y));
+ float hdFino = smoothstep(0.055, 0.012, hdPasso);
+ normal = normalize(mix(nonPerturbedNormal, normal, hdFino)); }`);
+ };
+ material.customProgramCacheKey = () => `sertao-hd-antimoire-${chave}-${key ? key.call(material) : ''}`;
+}
+
+
+// Só vale para caixa sem subdivisão: em todo vértice |position| é meia dimensão, e a dimensão
+// da face sai do próprio atributo. Barril e tronco seguem no material original.
+function madeiraHD(scene, { metros = 1.3, relevo = 3.4 } = {}) {
+ const TINTAS = { '3b2115': 0x6a4a36, 'd9b17a': 0xa88f72 };
+ const clones = new Map(), trocas = [];
+ const cloneDe = (m) => {
+ if (clones.has(m)) return clones.get(m);
+ const c = m.clone();
+ c.map = pbrTex('hd_sertao/old_planks_02_cor', true); c.bumpMap = null; c.normalMap = pbrTex('hd_sertao/old_planks_02_normal'); c.normalScale.set(relevo, relevo);
+ const tinta = TINTAS[m.color.getHexString()]; if (tinta) c.color.setHex(tinta);
+ // Tábua CC0 é mais escura que a madeira autoral: o ganho devolve a média de cor de cada peça.
+ c.color.setRGB(c.color.r * 2.1, c.color.g * 1.9, c.color.b * 1.65);
+ c.onBeforeCompile = (shader) => {
+ shader.vertexShader = shader.vertexShader.replace('#include ', `#include
+ {
+ vec3 hdS = vec3(1.0);
+ #ifdef USE_INSTANCING
+ hdS = vec3(length(instanceMatrix[0].xyz), length(instanceMatrix[1].xyz), length(instanceMatrix[2].xyz));
+ #endif
+ vec3 hdP = position * hdS, hdDim = 2.0 * abs(hdP), hdAn = abs(normal);
+ vec2 hdA = hdAn.x > 0.5 ? hdP.zy : (hdAn.y > 0.5 ? hdP.xz : hdP.xy);
+ vec2 hdD = hdAn.x > 0.5 ? hdDim.zy : (hdAn.y > 0.5 ? hdDim.xz : hdDim.xy);
+ vec2 hdUv = (hdD.x >= hdD.y ? hdA.yx : hdA) / ${metros.toFixed(3)};
+ #ifdef USE_MAP
+ vMapUv = hdUv;
+ #endif
+ #ifdef USE_NORMALMAP
+ vNormalMapUv = hdUv;
+ #endif
+ }`);
+ };
+ c.customProgramCacheKey = () => `sertao-hd-madeira2-${metros}`;
+ clones.set(m, c); return c;
+ };
+ scene.traverse((o) => {
+ if (!o.isMesh || o.geometry?.type !== 'BoxGeometry' || Array.isArray(o.material)) return;
+ const m = o.material, p = o.geometry.parameters;
+ if (!m?.isMeshStandardMaterial || !/^oeste-wood(-pale)?-real$/.test(m.map?.name || '')) return;
+ if ((p.widthSegments || 1) > 1 || (p.heightSegments || 1) > 1 || (p.depthSegments || 1) > 1) return;
+ trocas.push({ o, m }); o.material = cloneDe(m);
+ });
+ return () => { for (const { o, m } of trocas) o.material = m; for (const c of clones.values()) c.dispose(); };
+}
+
+let matPedraBase = null;
+function pedraDeBase(scene) {
+ let pronto = null; scene?.traverse((o) => { if (!pronto && o.isInstancedMesh && !o.instanceColor) { const m = materiaisDe(o)[0]; if (m?.map?.name === 'hd-cobblestone_floor_01_color') pronto = m; } });
+ if (pronto) return pronto;
+ if (matPedraBase) return matPedraBase;
+ matPedraBase = new THREE.MeshStandardMaterial({ color: 0xf2e8d8, map: pbrTex('cobblestone_floor_01_color', true), normalMap: pbrTex('cobblestone_floor_01_normal'),
+ roughnessMap: pbrTex('cobblestone_floor_01_rough'), roughness: 1, normalScale: new THREE.Vector2(1.6, 1.6), name: 'hd-embasamento' });
+ projetaMundo(matPedraBase, 1.6);
+ return matPedraBase;
+}
+
+// Embasamento de pedra: cada trecho de parede que toca o chão ganha uma sapata saliente com
+// capa. Vão de porta não tem parede no chão, então a sapata se interrompe sozinha.
+function embasamentoHD(scene) {
+ const M = new THREE.Matrix4(), L = new THREE.Matrix4(), p = new THREE.Vector3(), q = new THREE.Quaternion(), s = new THREE.Vector3(), pecas = [];
+ scene.traverse((root) => {
+ if (!root.userData?.interior) return;
+ root.traverse((c) => {
+ const g = c.geometry?.parameters;
+ if (!c.isInstancedMesh || !g?.width || !/adobe|paupique/.test(materiaisDe(c)[0]?.map?.name || '')) return;
+ c.updateWorldMatrix(true, false);
+ for (let i = 0; i < c.count; i++) { c.getMatrixAt(i, M); M.decompose(p, q, s);
+ if (p.y - s.y * g.height / 2 > .3) continue;
+ pecas.push({ mundo: c.matrixWorld.clone(), x: p.x, z: p.z, w: s.x * g.width, d: s.z * g.depth, q: q.clone() }); }
+ });
+ // Soleira de pedra na porta da frente: laje de 9 cm, fora do colisor e abaixo do degrau de passo.
+ if (/^sertao-(casa-|praca-casa-)/.test(root.name)) { const pl = root.userData.interior, fr = /praca-casa/.test(root.name) ? -1 : 1; root.updateWorldMatrix(true, false);
+ pecas.push({ mundo: root.matrixWorld.clone(), x: 0, z: fr * (pl.halfD + .22), w: 2.15, d: .62, q: new THREE.Quaternion(), h: .09 }); }
+ });
+ // Casa maciça (caixa única): sapata em tiras nos quatro lados, com o vão da porta livre na frente (+z local).
+ scene.traverse((o) => { const g = o.geometry?.parameters;
+ if (!o.isMesh || o.isInstancedMesh || !/^parede-casa-\d+$/.test(o.name) || !(g?.width > 2.5) || o.material?.map?.name !== 'oeste-adobe-paupique') return;
+ o.updateWorldMatrix(true, false); const mundo = o.matrixWorld.clone(), y0 = -g.height / 2 - .15, tira = (x, z, w, d) => pecas.push({ mundo, x, z, w, d, q: new THREE.Quaternion(), y0 });
+ pecas.push({ mundo, x: 0, z: g.depth / 2 + .32, w: 1.5, d: .52, q: new THREE.Quaternion(), y0, h: .1 });
+ tira(0, -g.depth / 2, g.width, .02); for (const sx of [-1, 1]) { tira(sx * g.width / 2, 0, .02, g.depth); tira(sx * (g.width / 4 + .46), g.depth / 2, g.width / 2 - .92, .02); } });
+ if (!pecas.length) return () => {};
+ const lote = new THREE.InstancedMesh(new THREE.BoxGeometry(1, 1, 1), pedraDeBase(scene), pecas.length); let k = 0;
+ for (const c of pecas) { const h = c.h ?? .4, y = h / 2, folga = c.h ? 0 : .18, quina = c.h ? 0 : folga + .2, emX = c.w >= c.d;
+ L.compose(p.set(c.x, y + (c.y0 || 0), c.z), c.q, s.set(c.w + (emX ? quina : folga), h, c.d + (emX ? folga : quina))); lote.setMatrixAt(k++, M.multiplyMatrices(c.mundo, L)); }
+ lote.instanceMatrix.needsUpdate = true; lote.computeBoundingSphere(); lote.receiveShadow = true; lote.name = 'sertao-hd-embasamento'; scene.add(lote);
+ return () => { scene.remove(lote); lote.geometry.dispose(); };
+}
+
+// Cunhal abaulado: meia-coluna de reboco que sai até 8 cm da quina e alarga no pé. Tira a aresta de caixa.
+function quinasHD(scene) {
+ const pontos = [], v = new THREE.Vector3(); let mat = null;
+ scene.traverse((o) => {
+ const pl = o.userData?.interior, g = o.geometry?.parameters;
+ if (pl && /^sertao-(casa-|praca-casa-)/.test(o.name)) { o.updateWorldMatrix(true, false);
+ for (const sx of [-1, 1]) for (const sz of [-1, 1]) pontos.push([v.set(sx * (pl.halfW + .02), .42, sz * (pl.halfD + .02)).applyMatrix4(o.matrixWorld).clone(), 2.95]); }
+ else if (o.isMesh && !o.isInstancedMesh && /^parede-casa-\d+$/.test(o.name) && g?.width > 2.5 && g?.depth > 2.5 && o.material?.map?.name === 'oeste-adobe-paupique') { o.updateWorldMatrix(true, false); mat ||= o.material;
+ for (const sx of [-1, 1]) for (const sz of [-1, 1]) pontos.push([v.set(sx * (g.width / 2 - .11), -g.height / 2 + .27, sz * (g.depth / 2 - .11)).applyMatrix4(o.matrixWorld).clone(), g.height - .17]); }
+ });
+ if (!pontos.length || !mat) return () => {};
+ const geo = new THREE.CylinderGeometry(.17, .21, 1, 8, 1, true), lote = new THREE.InstancedMesh(geo, mat, pontos.length), o3 = new THREE.Object3D();
+ pontos.forEach(([p, h], i) => { o3.position.set(p.x, p.y + h / 2, p.z); o3.scale.set(1, h, 1); o3.rotation.y = i * .7; o3.updateMatrix(); lote.setMatrixAt(i, o3.matrix); });
+ lote.instanceMatrix.needsUpdate = true; lote.computeBoundingSphere(); lote.receiveShadow = true; lote.name = 'sertao-hd-quinas'; lote.userData.nonCollider = true; scene.add(lote);
+ return () => { scene.remove(lote); geo.dispose(); };
+}
+
+// Esteio: a caixa de 16 cm vira tronco de 8 lados sobre uma pedra de apoio.
+function esteiosHD(scene) {
+ const M = new THREE.Matrix4(), L = new THREE.Matrix4(), p = new THREE.Vector3(), q = new THREE.Quaternion(), s = new THREE.Vector3(), itens = [];
+ let mapaMadeira = null;
+ scene.traverse((o) => { if (!mapaMadeira && o.isMesh) { const m = materiaisDe(o)[0]; if (/oeste-wood-real$/.test(m?.map?.name || '')) mapaMadeira = m.map; }
+ const bp = o.userData?.boxParts; if (bp) for (const [chave, v] of Object.entries(bp)) if (/esteio/.test(chave) && v?.mesh?.isInstancedMesh) itens.push(v); });
+ if (!itens.length || !mapaMadeira) return () => {};
+ const mapa = mapaMadeira.clone(); mapa.rotation = Math.PI / 2; mapa.repeat.set(2.2, .5); mapa.needsUpdate = true;
+ const relevo = relevoDeCor(mapa, 2.4); relevo.rotation = Math.PI / 2;
+ const mat = new THREE.MeshStandardMaterial({ color: 0x6a4a36, map: mapa, normalMap: relevo, normalScale: new THREE.Vector2(2.6, 2.6), roughness: .9, name: 'hd-esteio' });
+ const troncos = new THREE.InstancedMesh(new THREE.CylinderGeometry(.075, .095, 1, 8), mat, itens.length);
+ const pes = new THREE.InstancedMesh(new THREE.BoxGeometry(1, 1, 1), pedraDeBase(scene), itens.length), antes = [];
+ itens.forEach(({ mesh, index }, i) => {
+ const g = mesh.geometry.parameters; mesh.getMatrixAt(index, M); antes.push([mesh, index, M.clone()]); M.decompose(p, q, s);
+ const h = s.y * g.height; mesh.updateWorldMatrix(true, false);
+ L.compose(p, q, s.set(1, h, 1)); troncos.setMatrixAt(i, L.premultiply(mesh.matrixWorld));
+ L.compose(p.set(p.x, p.y - h / 2 + .08, p.z), q, s.set(.30, .16, .30)); pes.setMatrixAt(i, L.premultiply(mesh.matrixWorld));
+ M.decompose(p, q, s); mesh.setMatrixAt(index, L.compose(p, q, s.set(0, 0, 0))); mesh.instanceMatrix.needsUpdate = true;
+ });
+ for (const lote of [troncos, pes]) { lote.instanceMatrix.needsUpdate = true; lote.computeBoundingSphere(); lote.receiveShadow = true; scene.add(lote); }
+ troncos.castShadow = true; troncos.name = 'sertao-hd-esteios';
+ return () => { for (const [mesh, index, m] of antes) { mesh.setMatrixAt(index, m); mesh.instanceMatrix.needsUpdate = true; }
+ scene.remove(troncos); scene.remove(pes); troncos.geometry.dispose(); pes.geometry.dispose(); mat.dispose(); mapa.dispose(); };
+}
+
+// Telha capa: meia-cana afunilada, eixo em z, barriga em +y. 3 gomos = 6 triângulos.
+let geoTelha = null;
+function telhaGeo() {
+ if (geoTelha) return geoTelha;
+ const S = 3, len = .48, r1 = .09, r2 = .112, pos = [], nor = [], uv = [], idx = [];
+ for (let e = 0; e < 2; e++) {
+ const z = e ? len / 2 : -len / 2, r = e ? r2 : r1;
+ for (let i = 0; i <= S; i++) { const a = Math.PI * i / S; pos.push(Math.cos(a) * r, Math.sin(a) * r, z); nor.push(Math.cos(a), Math.sin(a), 0); uv.push(i / S, e); }
+ }
+ for (let i = 0; i < S; i++) idx.push(i, S + 1 + i, i + 1, i + 1, S + 1 + i, S + 2 + i);
+ geoTelha = new THREE.BufferGeometry();
+ geoTelha.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
+ geoTelha.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));
+ geoTelha.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));
+ geoTelha.setIndex(idx);
+ return geoTelha;
+}
+
+function rngDe(semente) { let s = semente; return () => { s = (s * 16807) % 2147483647; return s / 2147483647; }; }
+
+function telhadoCasaLaje(root, semente) {
+ const M0 = new THREE.Matrix4(), p0 = new THREE.Vector3(), q0 = new THREE.Quaternion(), s0 = new THREE.Vector3();
+ const rnd = rngDe(semente);
+ const kit = new THREE.Group(); kit.name = 'sertao-hd-kit'; root.add(kit);
+ // baseHD troca o mapa da laje antes: a marca hdLaje mantém a laje reconhecível.
+ const lajes = []; root.traverse((o) => { const m = o.isMesh && materiaisDe(o)[0]; if (m && (m.map?.name === 'oeste-roof-real' || m.userData.hdLaje)) lajes.push(o); });
+ lajes.forEach((o) => { o.visible = false; });
+ // Testeira e cornija da platibanda atravessariam as águas do telhado: saem enquanto o kit estiver ligado.
+ const ocultas = [], zero = new THREE.Matrix4().makeScale(0, 0, 0);
+ for (const [chave, v] of Object.entries(root.userData.boxParts || {})) if (/platibanda-testeira$|cornija$/.test(chave) && v?.mesh?.isInstancedMesh) {
+ const m0 = new THREE.Matrix4(); v.mesh.getMatrixAt(v.index, m0); ocultas.push([v, m0]); v.mesh.setMatrixAt(v.index, zero); v.mesh.instanceMatrix.needsUpdate = true; }
+ let madeira = null, parede = null;
+ root.traverse((o) => { if (!o.isMesh) return; const m = materiaisDe(o)[0];
+ if (!madeira && /oeste-wood-real$/.test(m?.map?.name || '') && o.geometry?.type === 'BoxGeometry') madeira = m;
+ if (!parede && o.isInstancedMesh && /adobe|paupique/.test(m?.map?.name || '')) parede = m; });
+ madeira ||= new THREE.MeshStandardMaterial({ color: 0x3b2115, roughness: 1 });
+ // Medidas saem da própria casa: laje de telhado (instância mais alta) e planta em userData.interior.
+ let laje = null;
+ for (const o of lajes) if (o.isInstancedMesh) for (let i = 0; i < o.count; i++) { o.getMatrixAt(i, M0); M0.decompose(p0, q0, s0);
+ const g = o.geometry.parameters; if (!laje || p0.y > laje.y) laje = { y: p0.y, w: s0.x * g.width, h: s0.y * g.height }; }
+ const planta = root.userData.interior || { halfW: 3.6, halfD: 3.2 };
+ const xParede = planta.halfW, D = planta.halfD + .14, beiral = .62, y0 = (laje ? laje.y - laje.h / 2 : 3.45), W = (laje ? laje.w : 7.7) + .4, H = D * .374;
+ const th = Math.atan(H / D), cume = y0 + H, Ls = (D + beiral) / Math.cos(th), px = .25, ex = .41;
+ const cols = Math.floor(W / px), rows = Math.ceil(Ls / ex);
+ const matTelha = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: .88, side: THREE.DoubleSide,
+ normalMap: pbrTex('paintedplaster017_normal', false, .35), normalScale: new THREE.Vector2(1.7, 1.7) });
+ const matFundo = new THREE.MeshStandardMaterial({ color: 0x6b3d2a, roughness: 1 });
+ const capas = new THREE.InstancedMesh(telhaGeo(), matTelha, cols * rows * 2 + Math.ceil(W / .36));
+ // Duas águas numa chamada só por peça (forro, caibros, oitões): o kit custa 4 draw calls por casa, não 7.
+ const nc = Math.floor(W / .58), o3 = new THREE.Object3D();
+ const forro = new THREE.InstancedMesh(new THREE.BoxGeometry(W - .04, .05, Ls), matFundo, 2), caibros = new THREE.InstancedMesh(new THREE.BoxGeometry(.07, .1, Ls + .06), madeira, (nc + 1) * 2);
+ const M = new THREE.Matrix4(), R = new THREE.Matrix4(), cor = new THREE.Color(), eul = new THREE.Euler(), pecas = [];
+ const tinta = () => { const v = .72 + rnd() * .3, w = rnd();
+ if (w < .07) cor.setRGB(.20 * v, .13 * v, .10 * v); else if (w < .16) cor.setRGB(.46 * v, .26 * v, .17 * v); else cor.setRGB(.36 * v, .17 * v, .10 * v); };
+ for (const s of [1, -1]) {
+ const d = new THREE.Vector3(0, -Math.sin(th), s * Math.cos(th)), n = new THREE.Vector3(0, Math.cos(th), s * Math.sin(th)), X = new THREE.Vector3(s, 0, 0);
+ for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) {
+ // Beiral ondulado: a fiada cede mais perto da ponta (ripa empenada), nunca uma régua.
+ const cede = (Math.sin(c * .43 + semente) * .022 + Math.sin(c * 1.9 + semente * .7) * .008) * (r / rows);
+ const p = new THREE.Vector3((c + .5) * px - W / 2, cume, 0).addScaledVector(d, Math.min(r * ex + .25, Ls - .21) + cede * 1.5).addScaledVector(n, .05 + cede);
+ M.makeBasis(X, n, d); R.makeRotationFromEuler(eul.set(-.06 + (rnd() - .5) * .03, (rnd() - .5) * .05, (rnd() - .5) * .06));
+ M.multiply(R).setPosition(p); tinta(); pecas.push([M.clone(), cor.clone(), r >= rows - 2]);
+ }
+ const lado = s > 0 ? 0 : 1; o3.rotation.set(s * th, 0, 0);
+ o3.position.set(0, cume - Math.sin(th) * Ls / 2 + .005, s * Math.cos(th) * Ls / 2); o3.updateMatrix(); forro.setMatrixAt(lado, o3.matrix);
+ for (let i = 0; i <= nc; i++) { o3.position.set(-W / 2 + .08 + i * ((W - .16) / nc), cume - Math.sin(th) * Ls / 2 - .08, s * Math.cos(th) * Ls / 2); o3.updateMatrix(); caibros.setMatrixAt(lado * (nc + 1) + i, o3.matrix); }
+ }
+ forro.castShadow = true; forro.receiveShadow = true; forro.frustumCulled = false; caibros.frustumCulled = false; kit.add(forro, caibros);
+ for (let i = 0; i < Math.ceil(W / .36); i++) {
+ M.makeBasis(new THREE.Vector3(0, 0, -1), new THREE.Vector3(0, 1, 0), new THREE.Vector3(1, 0, 0));
+ R.makeRotationFromEuler(eul.set(-.05, (rnd() - .5) * .04, (rnd() - .5) * .05)); M.multiply(R).scale(new THREE.Vector3(1.5, 1.35, 1));
+ M.setPosition(-W / 2 + .23 + i * .36, cume + .06, 0); tinta(); pecas.push([M.clone(), cor.clone(), true]);
+ }
+ // De longe só a fiada do beiral e a cumeeira são telha de verdade; o resto vira a textura de telha no forro.
+ pecas.sort((a, b) => b[2] - a[2]).forEach(([m, c], i) => { capas.setMatrixAt(i, m); capas.setColorAt(i, c); });
+ const k = pecas.length, kLonge = pecas.filter((q) => q[2]).length, centro = root.getWorldPosition(new THREE.Vector3()), olho = new THREE.Vector3();
+ const matLonge = lajes.map((o) => materiaisDe(o)[0]).find((m) => m?.userData.hdLaje) || null;
+ forro.onBeforeRender = (r, sc, cam) => { const perto = olho.setFromMatrixPosition(cam.matrixWorld).distanceToSquared(centro) < 324;
+ capas.count = perto ? k : kLonge; if (matLonge) forro.material = perto ? matFundo : matLonge; };
+ capas.count = k; capas.instanceMatrix.needsUpdate = true; capas.instanceColor.needsUpdate = true;
+ capas.receiveShadow = true; capas.computeBoundingSphere(); capas.name = 'sertao-hd-telhas'; kit.add(capas);
+ if (parede) { const G = new THREE.BufferGeometry(), P = [], N = [];
+ for (const sx of [1, -1]) { const x = sx * xParede;
+ P.push(x - .14, y0, -D, x - .14, y0, D, x - .14, cume - .02, 0, x + .14, y0, -D, x + .14, y0, D, x + .14, cume - .02, 0); N.push(-1, 0, 0, -1, 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0); }
+ G.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); G.setAttribute('normal', new THREE.Float32BufferAttribute(N, 3));
+ G.setAttribute('uv', new THREE.Float32BufferAttribute(new Array(24).fill(0), 2)); G.setIndex([0, 1, 2, 3, 5, 4, 6, 7, 8, 9, 11, 10]);
+ const oitao = new THREE.Mesh(G, parede); oitao.receiveShadow = true; kit.add(oitao);
+ }
+ return () => { root.remove(kit); kit.traverse((o) => { if (o.geometry && o.geometry !== geoTelha) o.geometry.dispose(); }); matTelha.dispose(); matFundo.dispose();
+ lajes.forEach((o) => { o.visible = true; }); for (const [v, m0] of ocultas) { v.mesh.setMatrixAt(v.index, m0); v.mesh.instanceMatrix.needsUpdate = true; } };
+}
+
+// Casa maciça tem o telhado em placa: uma fiada de telha de verdade na borda baixa quebra a aresta reta.
+function beiraisHD(scene) {
+ const itens = [], v = new THREE.Vector3(), c = new THREE.Vector3(), rnd = rngDe(911);
+ scene.traverse((root) => { if (!/^sertao-casa-paupique-\d+$/.test(root.name)) return;
+ root.traverse((o) => { const g = o.geometry?.parameters, m = o.isMesh && !o.isInstancedMesh && materiaisDe(o)[0];
+ if (!m || o.geometry.type !== 'BoxGeometry' || !(m.userData.hdLaje || m.map?.name === 'oeste-roof-real') || g.height > .3 || g.width * g.depth < 2) return;
+ o.updateWorldMatrix(true, false); const yc = c.set(0, g.height / 2, 0).applyMatrix4(o.matrixWorld).y;
+ for (const [ex, ez, comp] of [[1, 0, g.depth], [-1, 0, g.depth], [0, 1, g.width], [0, -1, g.width]])
+ if (v.set(ex * g.width / 2, g.height / 2, ez * g.depth / 2).applyMatrix4(o.matrixWorld).y < yc - .08) itens.push({ o, ex, ez, n: Math.floor(comp / .25), g }); }); });
+ if (!itens.length) return () => {};
+ const mat = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: .88, side: THREE.DoubleSide, normalMap: pbrTex('paintedplaster017_normal', false, .35), normalScale: new THREE.Vector2(1.1, 1.1) });
+ const lote = new THREE.InstancedMesh(telhaGeo(), mat, itens.reduce((a, i) => a + i.n, 0)), M = new THREE.Matrix4(), R = new THREE.Matrix4(), eul = new THREE.Euler(), cor = new THREE.Color(), Y = new THREE.Vector3(0, 1, 0); let k = 0;
+ for (const { o, ex, ez, n, g } of itens) { const Z = new THREE.Vector3(ex, 0, ez), X = new THREE.Vector3().crossVectors(Y, Z);
+ for (let i = 0; i < n; i++) { const ao = (i + .5 - n / 2) * .25;
+ M.makeBasis(X, Y, Z); R.makeRotationFromEuler(eul.set(-.05 + (rnd() - .5) * .07, (rnd() - .5) * .09, (rnd() - .5) * .09));
+ M.multiply(R).setPosition(ex ? ex * (g.width / 2 - .13) : ao, g.height / 2 + .03 + rnd() * .018, ez ? ez * (g.depth / 2 - .13) : ao).premultiply(o.matrixWorld);
+ const t = .72 + rnd() * .3, w = rnd(); lote.setMatrixAt(k, M); lote.setColorAt(k++, w < .12 ? cor.setRGB(.46 * t, .26 * t, .17 * t) : cor.setRGB(.36 * t, .17 * t, .10 * t)); } }
+ lote.instanceMatrix.needsUpdate = true; lote.instanceColor.needsUpdate = true; lote.computeBoundingSphere(); lote.receiveShadow = true; lote.name = 'sertao-hd-beirais'; lote.userData.nonCollider = true; scene.add(lote);
+ return () => { scene.remove(lote); mat.dispose(); };
+}
+
+// Céu em gradiente + halo do sol virando ambiente por imagem: dá direção à luz indireta
+// (frio de cima, quente do chão) e deixa relevo e rugosidade aparecerem na sombra.
+export function ambienteDoCeu(renderer, sol, { zenite = 0x7f9cc4, horizonte = 0xf3c79a, chao = 0xa9825a, halo = 1, ganho = 1 } = {}) {
+ const cena = new THREE.Scene(), geo = new THREE.SphereGeometry(50, 32, 16);
+ const mat = new THREE.ShaderMaterial({ side: THREE.BackSide,
+ uniforms: { uZ: { value: new THREE.Color(zenite) }, uH: { value: new THREE.Color(horizonte) }, uC: { value: new THREE.Color(chao) },
+ uSol: { value: sol.clone().normalize() }, uHalo: { value: halo }, uGanho: { value: ganho } },
+ vertexShader: 'varying vec3 vDir; void main(){ vDir = normalize(position); gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
+ fragmentShader: `varying vec3 vDir; uniform vec3 uZ, uH, uC, uSol; uniform float uHalo, uGanho;
+ void main(){ vec3 dir = normalize(vDir); float y = dir.y;
+ vec3 c = y > 0.0 ? mix(uH, uZ, pow(y, 0.55)) : mix(uH, uC, pow(-y, 0.35));
+ float s = max(dot(dir, uSol), 0.0); c += vec3(1.0, 0.78, 0.52) * uHalo * (pow(s, 6.0) * 0.9 + pow(s, 60.0) * 5.0);
+ gl_FragColor = vec4(c * uGanho, 1.0); }` });
+ cena.add(new THREE.Mesh(geo, mat));
+ const pmrem = new THREE.PMREMGenerator(renderer), rt = pmrem.fromScene(cena, 0.02);
+ pmrem.dispose(); geo.dispose(); mat.dispose();
+ return rt;
+}
+
+// Cúpula de céu: gradiente por direção, halo do sol e nuvens em ruído. Só pinta pixel de céu.
+export function ceuHD(scene, sol, { zenite = 0x23407e, horizonte = null, solCor = 0x8a5a34, nuvem = 0xd9c2b0, nuvemSombra = 0x5a5f78, cobertura = .5, raio = 100, ganho = 1, curva = .8, morro = null } = {}) {
+ // O horizonte usa a cor da névoa do mapa: o relevo distante some nela, e céu de outra cor vira faixa.
+ horizonte ??= scene.fog?.color?.getHex() ?? 0xd7a477;
+ const mat = new THREE.ShaderMaterial({ side: THREE.BackSide, depthWrite: false, fog: false,
+ uniforms: { uZ: { value: new THREE.Color(zenite) }, uH: { value: new THREE.Color(horizonte) }, uSolCor: { value: new THREE.Color(solCor) },
+ uNuvem: { value: new THREE.Color(nuvem) }, uNuvemSombra: { value: new THREE.Color(nuvemSombra) }, uSol: { value: sol.clone().normalize() },
+ uCobertura: { value: cobertura }, uGanho: { value: ganho }, uCurva: { value: curva },
+ uMorro: { value: new THREE.Color(morro?.cor ?? 0x808080) }, uMorroAlt: { value: morro?.altura ?? 0 }, uCasas: { value: morro?.casas ? 1 : 0 } },
+ vertexShader: 'varying vec3 vDir; void main(){ vDir = position; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
+ fragmentShader: `varying vec3 vDir; uniform vec3 uZ, uH, uSolCor, uNuvem, uNuvemSombra, uSol; uniform vec3 uMorro; uniform float uCobertura, uGanho, uCurva, uMorroAlt, uCasas;${RUIDO_GLSL}
+ float hdFbm(vec2 p){ float a = 0.5, s = 0.0; for (int i = 0; i < 4; i++) { s += a * hdN(p); p = p * 2.03 + 17.0; a *= 0.5; } return s; }
+ void main(){ vec3 d = normalize(vDir); float y = max(d.y, 0.0), s = max(dot(d, uSol), 0.0);
+ vec3 c = mix(uH, uZ, pow(y, uCurva)) + uSolCor * (pow(s, 5.0) * 0.5 + pow(s, 90.0) * 2.5);
+ float f = hdFbm(d.xz / (d.y + 0.16) * 1.15);
+ float n = smoothstep(1.0 - uCobertura, 1.0 - uCobertura + 0.22, f) * smoothstep(0.02, 0.2, d.y);
+ vec3 nu = mix(uNuvemSombra, uNuvem, clamp(0.3 + 0.7 * pow(s, 2.0) + (f - 0.55) * 1.4, 0.0, 1.0));
+ c = mix(c, nu, n * 0.85);
+ // Relevo no horizonte (morro com casario no Lajes, serra no Sertão): duas cristas, a de trás mais na névoa.
+ if (uMorroAlt > 0.0) { vec2 cz = normalize(d.xz + 1e-5);
+ float h2 = uMorroAlt * 1.5 * (0.3 + 0.7 * hdFbm(cz * 1.4 + 11.0));
+ c = mix(c, mix(uH, uMorro, 0.84), smoothstep(h2, h2 - 0.006, d.y));
+ float h1 = uMorroAlt * (0.25 + 0.75 * hdFbm(cz * 2.3 + 5.0)) + uMorroAlt * 0.12 * hdN(cz * 9.0);
+ vec3 mc = mix(uH, uMorro * 0.8, 0.8 + 0.18 * smoothstep(0.0, h1, d.y));
+ if (uCasas > 0.5) { vec2 g = vec2(atan(d.z, d.x) * 70.0, d.y * 110.0), id = floor(g);
+ float casa = step(0.4, hdH(id)) * step(0.18, fract(g.x)) * step(0.25, fract(g.y));
+ mc = mix(mc, mix(uMorro * 1.9, vec3(0.62, 0.36, 0.26), hdH(id + 7.0)), casa * 0.7) * (0.8 + 0.4 * hdN(g * 0.11)); }
+ c = mix(c, mc, smoothstep(h1, h1 - 0.005, d.y)); }
+ if (d.y < 0.0) c = uH * 0.9;
+ gl_FragColor = vec4(c * uGanho, 1.0); }` });
+ const cupula = new THREE.Mesh(new THREE.SphereGeometry(raio, 32, 16), mat);
+ cupula.name = 'hd-ceu'; cupula.renderOrder = -1000; cupula.frustumCulled = false; cupula.castShadow = false;
+ cupula.onBeforeRender = (r, sc, camera) => { cupula.position.copy(camera.position); cupula.scale.setScalar(camera.far * .9 / raio); cupula.updateMatrixWorld(); };
+ // Mapa que já tem cúpula própria (Lajes) a desenharia por cima da nova: fica oculta enquanto o kit estiver ligado.
+ const ocultas = []; scene.traverse((o) => { if (o.isMesh && /SKY_DOME/i.test(o.name) && o.visible) { o.visible = false; ocultas.push(o); } });
+ scene.add(cupula);
+ return () => { scene.remove(cupula); cupula.geometry.dispose(); mat.dispose(); for (const o of ocultas) o.visible = true; };
+}
+
+export function luzHD(scene, renderer, { hemi = .38, solGanho = 1.3, ceu = {}, cupula = null, solDir = null, solCor = null, ambiente = true, rebote = null } = {}) {
+ let sol = null, hemisferio = null;
+ scene.traverse((o) => { if (o.isDirectionalLight && o.castShadow) sol = o; if (o.isHemisphereLight) hemisferio = o; });
+ if (!sol || !hemisferio) return () => {};
+ const antes = { env: scene.environment, hemi: hemisferio.intensity, sol: sol.intensity, cor: sol.color.getHex(), chao: hemisferio.groundColor.getHex() };
+ if (solCor !== null) sol.color.set(solCor);
+ if (rebote !== null) hemisferio.groundColor.set(rebote);
+ // Direção do sol: o foco de sombra (bloom.js) guarda a dele em scene.userData.__sf.dir e reposiciona
+ // a luz todo quadro; trocar o azimute tem de ser lá. `solDir` é opcional (decisão de arte do mapa).
+ const sf = scene.userData.__sf, dir = sol.position.clone().sub(sol.target.position).normalize(), dirAntes = dir.clone();
+ if (solDir) { dir.set(solDir[0], solDir[1], solDir[2]).normalize();
+ sol.position.copy(sol.target.position).addScaledVector(dir, Math.max(20, sol.position.distanceTo(sol.target.position)));
+ if (sf && sf.dir) sf.dir.copy(dir); }
+ const rt = ambiente ? ambienteDoCeu(renderer, dir, ceu) : null;
+ if (rt) scene.environment = rt.texture; hemisferio.intensity = antes.hemi * hemi; sol.intensity = antes.sol * solGanho;
+ const tiraCeu = cupula ? ceuHD(scene, dir, cupula) : () => {};
+ return () => { scene.environment = antes.env; hemisferio.intensity = antes.hemi; sol.intensity = antes.sol; sol.color.setHex(antes.cor); hemisferio.groundColor.setHex(antes.chao); rt?.dispose(); tiraCeu();
+ if (solDir) { const f = scene.userData.__sf; if (f && f.dir) f.dir.copy(dirAntes);
+ sol.position.copy(sol.target.position).addScaledVector(dirAntes, Math.max(20, sol.position.distanceTo(sol.target.position))); } };
+}
+
+// Chão do Sertão: o detalhe mora no ALBEDO (o relevo some na sombra). Variação por posição de mundo,
+// sulcos de roda e terra rachada; encadeia o onBeforeCompile que o mapa já pôs (untileSertaoSoil).
+function chaoHD(scene, { cor = [.58, .49, .41], chao = 150, sulcos = true, rachado = true, contraste = .44, detalhe = .12, dessat = .58, fino = .06 } = {}) {
+ const solo = scene.getObjectByName('sertao-solo'), m = solo?.material;
+ if (!m?.isMeshStandardMaterial) return () => {};
+ const antes = { cor: m.color.clone(), obc: m.onBeforeCompile, key: m.customProgramCacheKey };
+ m.color.setRGB(cor[0], cor[1], cor[2]);
+ m.onBeforeCompile = (shader, r) => {
+ antes.obc?.call(m, shader, r);
+ shader.uniforms.hdSolo = { value: pbrTex('hd_sertao/dry_ground_01_cor', true, chao) };
+ shader.vertexShader = shader.vertexShader.replace('#include ', '#include \nvarying vec3 vHdPos;')
+ .replace('#include ', '#include \nvHdPos = (modelMatrix * vec4(transformed, 1.0)).xyz;');
+ shader.fragmentShader = shader.fragmentShader.replace('#include ', `#include \nvarying vec3 vHdPos;\nuniform sampler2D hdSolo;${RUIDO_GLSL}
+ float hdVor(vec2 p){ vec2 i = floor(p), f = fract(p); float d1 = 8.0, d2 = 8.0;
+ for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) { vec2 g = vec2(float(x), float(y));
+ float d = length(g + vec2(hdH(i + g), hdH(i + g + 17.3)) - f); if (d < d1) { d2 = d1; d1 = d; } else if (d < d2) d2 = d; }
+ return d2 - d1; }
+ // Par de rodas (bitola 1,44 m): x = fundo do sulco, y = faixa larga (ombro de poeira solta).
+ vec2 hdRoda(float d, float existe){ float r = abs(abs(d) - 0.72); return vec2(1.0 - smoothstep(0.07, 0.24, r), 1.0 - smoothstep(0.2, 0.62, r)) * existe; }
+ vec2 hdSulcos(vec2 p0){
+ // Rastro serpenteia: o plano é deformado por ruído grave antes de medir a distância ao eixo.
+ vec2 p = p0 + (vec2(hdN(p0 * 0.055 + 3.0), hdN(p0 * 0.055 + 41.0)) - 0.5) * 7.5 + (vec2(hdN(p0 * 0.23 + 7.0), hdN(p0 * 0.23 + 29.0)) - 0.5) * 1.5;
+ float w = (hdN(p0 * 0.9) - 0.5) * 0.24; vec2 s = vec2(0.0);
+ #define HD_E(a, id) smoothstep(-0.5, 0.1, sin((a) * 0.13 + id * 2.3) + 0.6 * sin((a) * 0.31 + id) + (hdN(p0 * 0.12 + id) - 0.5) * 1.4)
+ s = max(s, hdRoda(p.x + 2.6 - 2.6 * sin(p.y * 0.045 + 0.6) - 0.05 * p.y + w, HD_E(p.y, 1.5)));
+ s = max(s, hdRoda(p.x - 6.4 - 1.9 * sin(p.y * 0.06 + 2.0) + 0.09 * p.y + w, HD_E(p.y, 4.5)));
+ s = max(s, hdRoda(p.x + 25.5 - 2.2 * sin(p.y * 0.05) + w, HD_E(p.y, 7.5)));
+ s = max(s, hdRoda(p.x - 28.0 - 1.8 * sin(p.y * 0.04 + 1.0) + w, HD_E(p.y, 10.5)));
+ s = max(s, hdRoda(p.y + 1.6 - 2.4 * sin(p.x * 0.05 + 1.0) - 0.07 * p.x + w, HD_E(p.x, 13.5)));
+ s = max(s, hdRoda(p.y + 33.0 - 1.5 * sin(p.x * 0.05 + 2.0) + w, HD_E(p.x, 19.5)));
+ s = max(s, hdRoda(length(p - vec2(0.6, 1.0)) - 9.2 + w, smoothstep(0.3, 0.6, hdN(p0 * 0.09 + 5.0))));
+ return s * smoothstep(64.0, 52.0, abs(p0.x)) * smoothstep(110.0, 80.0, abs(p0.y)); }
+ // Trilha de pisoteio: terra batida e clara das portas até o largo.
+ float hdSeg(vec2 p, vec2 a, vec2 b){ vec2 pa = p - a, ba = b - a; return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0)); }
+ float hdTrilha(vec2 p0){ vec2 p = p0 + (vec2(hdN(p0 * 0.31 + 3.0), hdN(p0 * 0.31 + 19.0)) - 0.5) * 1.6;
+ float d = min(min(hdSeg(p, vec2(-11.5, 10.6), vec2(-2.5, 4.0)), hdSeg(p, vec2(11.5, 10.6), vec2(2.5, 4.0))), min(hdSeg(p, vec2(0.0, -11.2), vec2(0.0, -2.5)), min(hdSeg(p, vec2(-12.6, -7.2), vec2(-3.0, 0.5)), hdSeg(p, vec2(12.4, 7.0), vec2(3.0, 3.0)))));
+ return (1.0 - smoothstep(0.28, 0.95, d)) * (0.6 + 0.4 * hdN(p0 * 1.7)); }`)
+ .replace('#include ', `float hdAlt = 0.0;
+ { vec2 hdP = vHdPos.xz; float hdL = length(vViewPosition), hdPx = fwidth(hdP.x) + fwidth(hdP.y);
+ float hdLum = dot(diffuseColor.rgb, vec3(0.3, 0.59, 0.11)), hdRef = dot(diffuse * vec3(0.32666, 0.17893, 0.0758), vec3(0.3, 0.59, 0.11));
+ diffuseColor.rgb *= clamp(pow(max(hdLum, 1e-4) / hdRef, ${contraste.toFixed(3)}), 0.5, 1.9);
+ float hdMa2 = hdN(hdP * 0.37 + 5.0), hdMac = hdN(hdP * 0.09) * 0.6 + hdMa2 * 0.4, hdMed = hdN(hdP * 2.9);
+ diffuseColor.rgb *= mix(0.76, 1.2, hdMac) * mix(0.9, 1.1, hdMed * smoothstep(0.9, 0.2, hdPx * 2.9));
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(dot(diffuseColor.rgb, vec3(0.3, 0.59, 0.11))) * vec3(1.14, 1.04, 0.9), 0.4 * smoothstep(0.5, 0.8, hdMa2));
+ // Pedrisco e torrão: mesma UV do relevo, para o albedo casar com a normal.
+ #ifdef USE_NORMALMAP
+ float hdT1 = dot(texture2D(hdSolo, vNormalMapUv).rgb, vec3(0.3, 0.59, 0.11)) / 0.11;
+ float hdPertoC = smoothstep(0.03, 0.012, hdPx);
+ diffuseColor.rgb *= mix(1.0, clamp(hdT1, 0.55, 1.5), ${detalhe.toFixed(3)} * mix(0.45, 1.0, smoothstep(0.09, 0.025, hdPx)) * (1.0 + 0.5 * hdPertoC)) * (1.0 + 0.18 * smoothstep(1.2, 1.7, hdT1) * hdPertoC);
+ float hdF3 = smoothstep(0.05, 0.012, hdPx), hdT3 = dot(texture2D(hdSolo, vNormalMapUv * 3.0 + 0.37).rgb, vec3(0.3, 0.59, 0.11)) / 0.11;
+ diffuseColor.rgb *= mix(1.0, clamp(hdT3, 0.65, 1.4), ${fino.toFixed(3)} * hdF3); hdAlt += (clamp(hdT3, 0.6, 1.5) - 1.0) * 0.004 * hdF3;
+ #endif
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(dot(diffuseColor.rgb, vec3(0.3, 0.59, 0.11))), ${dessat.toFixed(3)});
+ ${sulcos ? `if (hdPx < 0.9) { vec2 hdS = hdSulcos(hdP) * smoothstep(0.9, 0.2, hdPx);
+ diffuseColor.rgb *= (1.0 - 0.5 * hdS.x) * (1.0 + 0.3 * (hdS.y - hdS.x));
+ hdAlt += -0.045 * hdS.x + 0.016 * (hdS.y - hdS.x);
+ float hdTr = hdTrilha(hdP) * smoothstep(0.9, 0.2, hdPx) * (1.0 - hdS.x);
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(dot(diffuseColor.rgb, vec3(0.3, 0.59, 0.11))) * vec3(1.2, 1.1, 0.96), 0.55 * hdTr); hdAlt -= 0.012 * hdTr; }` : ''}
+ ${rachado ? `if (hdPx < 0.4) { float hdV = hdVor(hdP * 1.25 + 3.0);
+ float hdR = (1.0 - smoothstep(0.012, 0.04 + hdPx * 1.25, hdV)) * smoothstep(0.25, 0.5, hdMac) * smoothstep(0.4, 0.1, hdPx);
+ diffuseColor.rgb *= 1.0 - 0.42 * hdR; hdAlt -= 0.01 * hdR; }` : ''}
+ hdAlt *= smoothstep(45.0, 18.0, hdL); }
+ #include `)
+ // Sol rasante num chão com rugosidade < 1 acende um espelho no horizonte que lê como açude.
+ .replace('#include ', '#include \nroughnessFactor = mix(roughnessFactor, 1.0, 0.85);')
+ .replace('#include ', `#include
+ { vec3 hdSx = dFdx(-vViewPosition), hdSy = dFdy(-vViewPosition), hdR1 = cross(hdSy, normal), hdR2 = cross(normal, hdSx);
+ float hdDet = dot(hdSx, hdR1);
+ normal = normalize(abs(hdDet) * normal - sign(hdDet) * (dFdx(hdAlt) * hdR1 + dFdy(hdAlt) * hdR2) * 1.6);
+ float hdPasso = max(fwidth(vNormalMapUv.x), fwidth(vNormalMapUv.y));
+ normal = normalize(mix(nonPerturbedNormal, normal, smoothstep(0.055, 0.012, hdPasso))); }`);
+ };
+ m.customProgramCacheKey = () => `sertao-hd-chao9-${chao}-${sulcos}-${rachado}-${contraste}-${detalhe}-${dessat}-${fino}-${antes.key ? antes.key.call(m) : ''}`;
+ m.needsUpdate = true;
+ return () => { m.color.copy(antes.cor); m.onBeforeCompile = antes.obc; m.customProgramCacheKey = antes.key; m.needsUpdate = true; };
+}
+
+// Céu de fim de tarde do Sertão: zênite âmbar empoeirado, horizonte quente puxando para o sol,
+// disco solar e duas camadas de nuvem com a borda voltada ao sol iluminada.
+export function ceuTardeHD(scene, sol, { zenite = 0x3f4778, horizonte = 0xc6815c, horizonteSol = 0xf49b47, solCor = 0xe47a36, disco = 6, bruma = 0xd8985f, brumaForca = .32,
+ nuvem = 0xd89b68, nuvemSombra = 0x5a4f68, cobertura = .56, curva = .42, ganho = .9, raio = 100, morro = null } = {}) {
+ horizonte ??= scene.fog?.color?.getHex() ?? 0xd7a477;
+ const mat = new THREE.ShaderMaterial({ side: THREE.BackSide, depthWrite: false, fog: false,
+ uniforms: { uZ: { value: new THREE.Color(zenite) }, uH: { value: new THREE.Color(horizonte) }, uHS: { value: new THREE.Color(horizonteSol) },
+ uSolCor: { value: new THREE.Color(solCor) }, uNuvem: { value: new THREE.Color(nuvem) }, uNuvemSombra: { value: new THREE.Color(nuvemSombra) },
+ uSol: { value: sol.clone().normalize() }, uCob: { value: cobertura }, uCurva: { value: curva }, uGanho: { value: ganho }, uDisco: { value: disco },
+ uMorro: { value: new THREE.Color(morro?.cor ?? 0x808080) }, uMorroAlt: { value: morro?.altura ?? 0 }, uBruma: { value: new THREE.Color(bruma) }, uBrumaF: { value: brumaForca } },
+ vertexShader: 'varying vec3 vDir; void main(){ vDir = position; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
+ fragmentShader: `varying vec3 vDir; uniform vec3 uZ, uH, uHS, uSolCor, uNuvem, uNuvemSombra, uSol, uMorro, uBruma; uniform float uCob, uCurva, uGanho, uDisco, uMorroAlt, uBrumaF;${RUIDO_GLSL}
+ float hdFbm(vec2 p){ float a = 0.5, s = 0.0; for (int i = 0; i < 4; i++) { s += a * hdN(p); p = p * 2.03 + 17.0; a *= 0.5; } return s; }
+ float hdFbm2(vec2 p){ return 0.5 * hdN(p) + 0.25 * hdN(p * 2.03 + 17.0); }
+ void main(){ vec3 d = normalize(vDir); float y = max(d.y, 0.0), s = max(dot(d, uSol), 0.0);
+ vec2 az = normalize(d.xz + 1e-5), azSol = normalize(uSol.xz);
+ float lado = pow(max(dot(az, azSol), 0.0), 2.5);
+ vec3 hz = mix(uH, uHS, lado * 0.85);
+ vec3 c = mix(hz, uZ, smoothstep(0.0, uCurva, y) * (0.82 + 0.18 * smoothstep(uCurva, 0.9, y)));
+ c += uSolCor * (pow(s, 3.0) * 0.16 + pow(s, 7.0) * 0.34 + pow(s, 18.0) * 0.3 + pow(s, 40.0) * 0.9 + pow(s, 600.0) * 2.5) + vec3(1.0, 0.9, 0.72) * uDisco * smoothstep(0.99975, 0.99990, dot(d, uSol));
+ vec2 q1 = d.xz / (d.y + 0.3) * 2.2, q2 = d.xz / (d.y + 0.42) * 2.4, lz = azSol * 0.2;
+ vec2 k1 = vec2(0.8, 1.2); mat2 r1 = mat2(0.83, -0.56, 0.56, 0.83), r2 = mat2(0.6, 0.8, -0.8, 0.6); q1 = r1 * q1; q1 += (vec2(hdN(q1 * 0.4 + 9.0), hdN(q1 * 0.4 + 23.0)) - 0.5) * 1.1; q2 = r2 * q2 * vec2(0.7, 1.2);
+ vec2 lz1 = r1 * lz, lz2 = r2 * lz * vec2(0.7, 1.2);
+ float f1 = hdFbm(q1 * k1 + 3.0), f2 = hdFbm(q2 * 2.3 + 40.0);
+ float e1 = 1.0 - uCob, n1 = smoothstep(e1, e1 + 0.07, f1) * smoothstep(0.03, 0.12, d.y), m1 = smoothstep(e1 + 0.02, e1 + 0.17, f1);
+ float n2 = smoothstep(e1 + 0.07, e1 + 0.2, f2) * smoothstep(0.1, 0.32, d.y) * 0.6;
+ // Borda acesa: só as duas oitavas graves decidem o lado do sol; a camada alta acende pela borda rala.
+ float b1 = clamp((hdFbm2(q1 * k1 + 3.0) - hdFbm2((q1 + lz1) * k1 + 3.0)) * 7.0, 0.0, 1.0), b2 = clamp((hdFbm2(q2 * 2.3 + 40.0) - hdFbm2((q2 + lz2) * 2.3 + 40.0)) * 6.0, 0.0, 1.0);
+ vec3 quente = mix(uNuvem, uNuvem * vec3(1.25, 0.9, 0.5), lado) * (1.0 + 0.5 * pow(s, 4.0));
+ vec3 c1 = mix(uNuvemSombra * (0.95 + 0.3 * y), quente, clamp(b1 * 0.7 + 1.0 - m1 * 0.93, 0.0, 1.0));
+ vec3 c2 = mix(uNuvemSombra * 1.15, quente, clamp(0.35 + b2 * 0.7 + pow(s, 3.0) * 0.4, 0.0, 1.0));
+ c = mix(c, c2, n2 * 0.7); c = mix(c, c1, n1 * 0.92);
+ if (uMorroAlt > 0.0) { float h1 = uMorroAlt * (0.25 + 0.75 * hdFbm(az * 2.3 + 5.0)) + uMorroAlt * 0.12 * hdN(az * 9.0);
+ c = mix(c, mix(uH, uMorro * 0.8, 0.85), smoothstep(h1, h1 - 0.005, d.y)); }
+ float alto = smoothstep(0.1, 0.34, d.y); c = mix(c, vec3(dot(c, vec3(0.3, 0.59, 0.11))) * vec3(1.03, 1.0, 0.95), 0.42 * alto) * (1.0 - 0.25 * alto);
+ // Poeira dourada rente ao horizonte, mais densa contra o sol: mora no céu, sem quad nem overdraw.
+ c = mix(c, uBruma, exp(-y / 0.05) * uBrumaF * (0.35 + 0.65 * lado));
+ if (d.y < 0.0) c = mix(hz * 0.9, uBruma, uBrumaF * (0.35 + 0.65 * lado));
+ gl_FragColor = vec4(c * uGanho, 1.0); }` });
+ const cupula = new THREE.Mesh(new THREE.SphereGeometry(raio, 32, 16), mat);
+ cupula.name = 'hd-ceu'; cupula.renderOrder = 1000; cupula.frustumCulled = false; cupula.castShadow = false;
+ cupula.onBeforeRender = (r, sc, camera) => { cupula.position.copy(camera.position); cupula.scale.setScalar(camera.far * .9 / raio); cupula.updateMatrixWorld(); };
+ const ocultas = []; scene.traverse((o) => { if (o.isMesh && /SKY_DOME/i.test(o.name) && o.visible) { o.visible = false; ocultas.push(o); } });
+ scene.add(cupula);
+ return () => { scene.remove(cupula); cupula.geometry.dispose(); mat.dispose(); for (const o of ocultas) o.visible = true; };
+}
+
+// Sol rasante: o foco de sombra só cobria ~37 m a montante do centro (dist da luz do mapa); com a luz
+// quase horizontal isso corta sombra dentro da área de jogo. Afasta a luz e força o recálculo de near/far.
+function sombraRasante(scene, dist = 52) {
+ let sol = null; scene.traverse((o) => { if (o.isDirectionalLight && o.castShadow) sol = o; });
+ if (!sol) return () => {};
+ const dir = sol.position.clone().sub(sol.target.position), sf = scene.userData.__sf, d0 = sf && sf.dir ? sf.dist : Math.max(20, dir.length());
+ if (sf && sf.dir) { sf.dist = dist; sol.shadow.camera.right = 0; } else sol.position.copy(sol.target.position).addScaledVector(dir.normalize(), dist);
+ return () => { const f = scene.userData.__sf; if (f && f.dir) { f.dist = d0; sol.shadow.camera.right = 0; } };
+}
+
+// A névoa do mapa lavava o casario a 30 m; o kit rarefaz e devolve na saída.
+function nevoaHD(scene, fator = .5) { const f = scene.fog; if (!f?.isFogExp2) return () => {}; const d0 = f.density; f.density = d0 * fator; return () => { f.density = d0; }; }
+
+// Azimute girado ~13° para o norte em relação ao sol do mapa: o disco entra no quadro da praça, atrás da árvore.
+const SOL_TARDE = [-.708, .29, -.684];
+// O three guarda em cada material todo programa que ele já usou; trocar ambiente e shader dobrava a conta.
+function soltaProgramas(scene) { const vistos = new Set();
+ scene.traverse((o) => { if (o.isMesh) for (const m of materiaisDe(o)) if (m.isMeshStandardMaterial && !vistos.has(m)) { vistos.add(m); m.dispose(); } }); }
+export function aplicaSertaoHD(scene, renderer, opts = {}) {
+ const q = new URLSearchParams(typeof location === 'undefined' ? '' : location.search), desfaz = [];
+ soltaProgramas(scene);
+ const cen = q.get('hdcen') === '0' || opts.cenografia === false ? null : (opts.cenografia || {});
+ if (opts.reboco !== false) desfaz.push(rebocoHD(scene, opts.reboco || {}));
+ if (opts.base !== false) desfaz.push(baseHD(scene, opts.base || {}));
+ if (opts.chao !== false) desfaz.push(chaoHD(scene, { sulcos: !!cen && cen.sulcos !== false, rachado: !!cen && cen.rachado !== false, ...(opts.chao || {}) }));
+ if (opts.madeira !== false) desfaz.push(madeiraHD(scene, opts.madeira || {}));
+ if (opts.embasamento !== false) { desfaz.push(embasamentoHD(scene)); desfaz.push(esteiosHD(scene)); }
+ if (opts.quinas !== false) desfaz.push(quinasHD(scene));
+ if (opts.telhado !== false) {
+ const casas = ['sertao-praca-casa-interior-0', 'sertao-praca-casa-interior-1', 'sertao-casa-pedra-7', 'sertao-casa-pedra-8', 'sertao-casa-geminada-9', 'sertao-casa-platibanda-0', 'sertao-casa-platibanda-1'];
+ casas.forEach((nome, i) => { const root = scene.getObjectByName(nome); if (root && (opts.platibandas !== false || !/platibanda/.test(nome))) desfaz.push(telhadoCasaLaje(root, 7 + i * 131)); });
+ if (opts.beirais !== false) desfaz.push(beiraisHD(scene));
+ // A placa da venda ficava na testeira da platibanda; sem ela, desce para baixo do beiral, acima da porta.
+ const placa = opts.platibandas !== false && scene.getObjectByName('sertao-venda-placa');
+ if (placa) { const y0 = placa.position.y, e0 = placa.scale.clone(); placa.position.y = 2.98; placa.scale.multiplyScalar(.7); desfaz.push(() => { placa.position.y = y0; placa.scale.copy(e0); }); }
+ }
+ const serra = !!cen && cen.serra !== false;
+ if (opts.luz !== false) {
+ const tarde = q.get('hdsol') !== '0' && opts.solTarde !== false, ceuNovo = q.get('hdceu') === '0' || opts.ceu === false ? false : (q.get('hdceu') === '1' || opts.ceu !== undefined);
+ desfaz.push(luzHD(scene, renderer, { hemi: .16, solGanho: 1.5, ceu: { ganho: .34, halo: .6 }, cupula: ceuNovo ? null : { morro: { cor: 0x5e3f38, altura: .16 } },
+ ...(tarde ? { solDir: SOL_TARDE, solCor: 0xffc088, solGanho: 3.19, hemi: 1.13, ambiente: false, rebote: 0xa08468 } : {}), ...(opts.luz || {}) }));
+ if (tarde) desfaz.push(sombraRasante(scene));
+ if (opts.nevoa !== false) desfaz.push(nevoaHD(scene, opts.nevoa));
+ if (ceuNovo) { let sol = null; scene.traverse((o) => { if (o.isDirectionalLight && o.castShadow) sol = o; });
+ const dir = sol ? sol.position.clone().sub(sol.target.position).normalize() : new THREE.Vector3(...SOL_TARDE);
+ desfaz.push(ceuTardeHD(scene, dir, { morro: serra ? null : { cor: 0x5e3f38, altura: .12 }, ...(opts.ceu || {}) })); }
+ }
+ if (cen) desfaz.push(cenografiaSertaoHD(scene, renderer, cen, { pbrTex, relevoDeCor, RUIDO_GLSL, projetaMundo }));
+ return { desliga() { while (desfaz.length) desfaz.pop()(); soltaProgramas(scene); } };
+}
diff --git a/public/js/map_upa.js b/public/js/map_upa.js
index 1606170cf9..6b8d238506 100644
--- a/public/js/map_upa.js
+++ b/public/js/map_upa.js
@@ -6,6 +6,8 @@ import { grafitar } from './graffiti_pass.js';
import { createFavelaAmbience } from './ambientlife.js';
import { AMB_LOOPS } from './soundscape.js';
import { hasProp, placeProp } from './mapprops.js';
+import { TEXEL_ALVO, metrosPorUV, caixaUV } from './map_uv.js';
+import { withSurfaceAllocation } from './map_surface_finish.js';
export const UPA_PROPS = ['upa_maca', 'upa_monitor', 'upa_soro', 'upa_oxigenio', 'upa_biombo', 'upa_longarina', 'upa_cadeira_rodas', 'upa_armario', 'upa_balcao'];
@@ -38,50 +40,87 @@ export function buildUpa(scene, T) {
const mkCanvas = (w, h) => { const c = document.createElement('canvas'); c.width = w; c.height = h; return [c, c.getContext('2d')]; };
const tex = (c) => { const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8; return t; };
- // PISO: vinílico creme com ladrilho + tons por setor + FAIXAS coloridas de sinalização no chão
- function floorTex() {
- const W = 1024, H = 1229; // aspecto 60:72
- const [c, x] = mkCanvas(W, H);
- const px = (wx) => (wx + HALF_X) / (HALF_X * 2) * W, py = (wz) => (wz + HALF_Z) / (HALF_Z * 2) * H;
- x.fillStyle = '#dad4c8'; x.fillRect(0, 0, W, H);
- x.fillStyle = '#d2c6b1'; x.fillRect(0, 0, px(-3.5), py(-14)); // recepção (tan)
- x.fillStyle = '#cdd2d4'; x.fillRect(0, py(14), px(-3.5), H); // enfermaria (cinza)
- x.fillStyle = '#cdd2d4'; x.fillRect(px(3.5), py(14), W - px(3.5), H); // emergência (cinza)
- x.fillStyle = '#cfcabb'; x.fillRect(px(3.5), 0, W - px(3.5), py(-14)); // farmácia
- x.strokeStyle = 'rgba(120,120,120,.16)'; x.lineWidth = 1; // ladrilho ~1,2 m
- for (let wx = -HALF_X; wx <= HALF_X; wx += 1.2) { x.beginPath(); x.moveTo(px(wx), 0); x.lineTo(px(wx), H); x.stroke(); }
- for (let wz = -HALF_Z; wz <= HALF_Z; wz += 1.2) { x.beginPath(); x.moveTo(0, py(wz)); x.lineTo(W, py(wz)); x.stroke(); }
- // CADA cor é o CAMINHO até um setor: desce o corredor na sua faixa e VIRA pra dentro da porta
- // (portas do corredor em x=∓3,5, z ∈ {-25, 0, 25}). Fina e sem cruzar parede.
- const linha = (cor, pts) => { x.strokeStyle = cor; x.lineWidth = 3; x.lineJoin = 'round'; x.lineCap = 'round'; x.beginPath(); pts.forEach(([a, b], i) => i ? x.lineTo(px(a), py(b)) : x.moveTo(px(a), py(b))); x.stroke(); };
- linha('#2f9e5e', [[-2.6, -33], [-2.6, -25], [-7, -25]]); // verde → RECEPÇÃO (oeste-sul)
- linha('#2f6fb0', [[-1.7, -33], [-1.7, 0], [-7, 0]]); // azul → CONSULTÓRIOS (oeste)
- linha('#8e44ad', [[-0.8, -33], [-0.8, 25], [-7, 25]]); // roxo → ENFERMARIA (oeste-norte)
- linha('#e0a92a', [[2.6, -33], [2.6, -25], [7, -25]]); // amarelo→ FARMÁCIA (leste-sul)
- linha('#e07b2a', [[1.7, -33], [1.7, 0], [7, 0]]); // laranja→ TRIAGEM / RAIO-X (leste)
- linha('#c0392b', [[0.8, -33], [0.8, 25], [7, 25]]); // vermelho→ EMERGÊNCIA (leste-norte)
- return tex(c);
+ const semente = (n) => () => ((n = Math.imul(n, 1664525) + 1013904223 >>> 0) / 4294967296);
+ const ladrilho = (t) => { t.wrapS = t.wrapT = THREE.RepeatWrapping; return t; };
+ // Textura extra não pode sortear uuid no RNG da partida (eval:map-surface-upgrade).
+ const texIsolada = (c) => withSurfaceAllocation(() => { const t = ladrilho(tex(c)); t.anisotropy = 4; return t; }, true);
+ // Repete a pincelada nas bordas para o ladrilho não mostrar emenda.
+ const emVolta = (S, px, py, r, desenha) => { for (const ox of [-S, 0, S]) for (const oy of [-S, 0, S]) if (px + ox > -r && px + ox < S + r && py + oy > -r && py + oy < S + r) desenha(px + ox, py + oy); };
+
+ // Granilite: 512 px cobrem 4 m, com junta de dilatação a cada metro.
+ function granilite() {
+ const S = 512, [c, x] = mkCanvas(S, S), r = semente(4127);
+ x.fillStyle = '#a9a69b'; x.fillRect(0, 0, S, S);
+ for (let i = 0; i < 9; i++) {
+ const px = r() * S, py = r() * S, raio = S * (.16 + r() * .2), cor = i % 2 ? '84,80,72' : '204,200,188';
+ emVolta(S, px, py, raio, (ax, ay) => { const g = x.createRadialGradient(ax, ay, 0, ax, ay, raio); g.addColorStop(0, `rgba(${cor},.16)`); g.addColorStop(1, `rgba(${cor},0)`); x.fillStyle = g; x.fillRect(0, 0, S, S); });
+ }
+ const pedras = ['#e9e6dc', '#d6d1c2', '#77736a', '#4c4a45', '#b08f62', '#8f9794', '#f4f2ea', '#5f5a50'];
+ for (let i = 0; i < 9000; i++) {
+ const px = r() * S, py = r() * S, w = .8 + r() * r() * 4.2, h = .8 + r() * r() * 3.4, cor = pedras[(r() * pedras.length) | 0], giro = r() * Math.PI;
+ emVolta(S, px, py, 6, (ax, ay) => { x.save(); x.translate(ax, ay); x.rotate(giro); x.fillStyle = cor; x.globalAlpha = .55 + r() * .4; x.fillRect(-w / 2, -h / 2, w, h); x.restore(); });
+ }
+ x.globalAlpha = 1;
+ for (let j = 0; j < 4; j++) for (const [cor, dx, lw] of [['rgba(52,48,40,.75)', 0, 1.6], ['rgba(232,226,208,.35)', 1.4, 1]]) {
+ x.strokeStyle = cor; x.lineWidth = lw; const p = j * S / 4 + dx + .8;
+ x.beginPath(); x.moveTo(p, 0); x.lineTo(p, S); x.moveTo(0, p); x.lineTo(S, p); x.stroke();
+ }
+ const t = ladrilho(tex(c)); t.repeat.set(HALF_X * 2 * TEXEL_ALVO / S, HALF_Z * 2 * TEXEL_ALVO / S); return t;
+ }
+ // Barra hospitalar: o perfil ocupa a altura inteira da parede e o comprimento corre em metros.
+ function paredeTex() {
+ const S = 512, [c, x] = mkCanvas(S, S), r = semente(977), y = (m) => S - m / WH * S;
+ x.fillStyle = '#e4e2d8'; x.fillRect(0, 0, S, S);
+ for (let i = 0; i < 2600; i++) { x.fillStyle = i % 2 ? 'rgba(255,255,250,.07)' : 'rgba(120,116,104,.06)'; x.fillRect(r() * S, r() * y(1.2), 1 + r() * 2, 4 + r() * 26); }
+ for (let i = 0; i < 3; i++) { const px = r() * S, w = 26 + r() * 70, g = x.createLinearGradient(0, 0, 0, y(1.2)); g.addColorStop(0, 'rgba(96,88,66,.08)'); g.addColorStop(.5 + r() * .4, 'rgba(96,88,66,0)'); x.fillStyle = g; emVolta(S, px, 0, w, (ax) => x.fillRect(ax - w / 2, 0, w, y(1.2))); }
+ x.fillStyle = '#84b8a3'; x.fillRect(0, y(1.2), S, y(.1) - y(1.2));
+ for (let i = 0; i < 2200; i++) { x.fillStyle = i % 2 ? 'rgba(214,236,226,.09)' : 'rgba(40,70,58,.08)'; x.fillRect(r() * S, y(1.2) + r() * (y(.1) - y(1.2)), 2 + r() * 16, 1 + r() * 2); }
+ const friso = x.createLinearGradient(0, y(1.2) - 4, 0, y(1.2) + 5); friso.addColorStop(0, 'rgba(228,226,216,1)'); friso.addColorStop(.45, '#6f9a89'); friso.addColorStop(1, 'rgba(132,184,163,1)'); x.fillStyle = friso; x.fillRect(0, y(1.2) - 4, S, 9);
+ for (let i = 0; i < 46; i++) { const px = r() * S, py = y(.25 + r() * .8), w = 10 + r() * 70; x.strokeStyle = `rgba(48,52,50,${.1 + r() * .22})`; x.lineWidth = .6 + r() * 1.6; emVolta(S, px, py, w, (ax, ay) => { x.beginPath(); x.moveTo(ax, ay); x.lineTo(ax + w, ay + (r() - .5) * 3); x.stroke(); }); }
+ x.fillStyle = 'rgba(30,34,32,.35)'; x.fillRect(0, y(.82), S, 5);
+ const maca = x.createLinearGradient(0, y(.98), 0, y(.83)); maca.addColorStop(0, '#aab6bc'); maca.addColorStop(.25, '#8795a0'); maca.addColorStop(1, '#5d6973');
+ x.fillStyle = maca; x.fillRect(0, y(.98), S, y(.83) - y(.98));
+ for (const px of [64, 320]) { x.fillStyle = 'rgba(38,44,50,.5)'; x.fillRect(px, y(.98), 2, y(.83) - y(.98)); }
+ x.fillStyle = '#5b5d5a'; x.fillRect(0, y(.1), S, S - y(.1)); x.fillStyle = 'rgba(214,214,206,.3)'; x.fillRect(0, y(.1), S, 1.5);
+ const pe = x.createLinearGradient(0, y(.55), 0, S); pe.addColorStop(0, 'rgba(28,30,26,0)'); pe.addColorStop(1, 'rgba(28,30,26,.5)'); x.fillStyle = pe; x.fillRect(0, y(.55), S, S - y(.55));
+ const alto = x.createLinearGradient(0, 0, 0, y(WH - .45)); alto.addColorStop(0, 'rgba(40,44,46,.3)'); alto.addColorStop(1, 'rgba(40,44,46,0)'); x.fillStyle = alto; x.fillRect(0, 0, S, y(WH - .45));
+ const t = ladrilho(tex(c)); t.anisotropy = 4; return t;
}
- // PAREDE: perfil vertical bicolor (rodapé escuro · creme · faixa lilás na altura do peito · branco)
- function wallTex() {
- const H = 256, [c, x] = mkCanvas(8, H);
- x.fillStyle = '#f2f0ea'; x.fillRect(0, 0, 8, H); // branco (topo)
- x.fillStyle = '#e8e2d4'; x.fillRect(0, H * 0.78, 8, H * 0.19); // creme (miolo)
- x.fillStyle = '#a8a9ba'; x.fillRect(0, H * 0.74, 8, H * 0.05); // faixa lilás (peito ~1 m)
- x.fillStyle = '#5c4d3b'; x.fillRect(0, H * 0.97, 8, H * 0.03); // rodapé de madeira
- return tex(c);
+ function vergaTex() {
+ const W = 512, H = 256, [c, x] = mkCanvas(W, H), r = semente(613);
+ x.fillStyle = '#e4e2d8'; x.fillRect(0, 0, W, H);
+ for (let i = 0; i < 1300; i++) { x.fillStyle = i % 2 ? 'rgba(255,255,250,.07)' : 'rgba(120,116,104,.06)'; x.fillRect(r() * W, r() * H, 1 + r() * 2, 4 + r() * 26); }
+ const alto = x.createLinearGradient(0, 0, 0, H * .25); alto.addColorStop(0, 'rgba(40,44,46,.3)'); alto.addColorStop(1, 'rgba(40,44,46,0)'); x.fillStyle = alto; x.fillRect(0, 0, W, H * .25);
+ const vao = x.createLinearGradient(0, H * .86, 0, H); vao.addColorStop(0, 'rgba(40,44,46,0)'); vao.addColorStop(1, 'rgba(40,44,46,.4)'); x.fillStyle = vao; x.fillRect(0, H * .86, W, H * .14);
+ return texIsolada(c);
+ }
+ // Forro mineral em placas: 4×4 placas por textura, perfil T claro com sombra de encaixe.
+ function forroTex() {
+ const S = 512, N = 4, P = S / N, [c, x] = mkCanvas(S, S), r = semente(2203);
+ for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) {
+ const v = 236 + Math.round((r() - .5) * 14); x.fillStyle = `rgb(${v},${v},${v - 5})`; x.fillRect(i * P, j * P, P, P);
+ for (let k = 0; k < 150; k++) { x.fillStyle = `rgba(92,92,84,${.14 + r() * .3})`; x.fillRect(i * P + 5 + r() * (P - 10), j * P + 5 + r() * (P - 10), 1 + r() * 3.5, 1 + r() * 1.4); }
+ }
+ for (let i = 0; i <= N; i++) for (const [cor, dx, lw] of [['rgba(70,72,70,.55)', 3.2, 2.2], ['#fbfbf6', 0, 4.6]]) {
+ x.strokeStyle = cor; x.lineWidth = lw; const p = i * P + dx;
+ x.beginPath(); x.moveTo(p, 0); x.lineTo(p, S); x.moveTo(0, p); x.lineTo(S, p); x.stroke();
+ }
+ return texIsolada(c);
}
const MAT = {
- piso: lam({ map: floorTex() }), parede: lam({ map: wallTex() }), paredeAlta: lam({ color: 0xd4d8ce }),
- teto: lam({ color: 0x91989b }), maca: lam({ color: 0xf2f5f7 }), aco: lam({ color: 0x9aa0a6 }),
+ piso: lam({ map: granilite() }), parede: lam({ map: paredeTex() }), paredeAlta: lam({ map: vergaTex() }),
+ teto: lam({ color: 0xc6cac4, map: forroTex() }), maca: lam({ color: 0xf2f5f7 }), aco: lam({ color: 0x9aa0a6 }),
mesa: lam({ color: 0xc9b896 }), cadeira: lam({ color: 0x2f4a63 }), armario: lam({ color: 0xd6dbe0 }),
verde: lam({ color: 0x3f9a86 }), vermelho: lam({ color: 0xc0392b }), vidro: lam({ color: 0x9fd0e6, transparent: true, opacity: 0.4 }),
};
+ MAT.parede.userData.uvElevacao = MAT.paredeAlta.userData.uvElevacao = true;
+ // 192 px/m: quatro placas de 2/3 m por textura; o passo de 8 m das luminárias cai sempre em encaixe.
+ const UV_METROS = new Map([[MAT.parede, metrosPorUV(MAT.parede)], [MAT.paredeAlta, metrosPorUV(MAT.paredeAlta)], [MAT.teto, metrosPorUV(MAT.teto, 192)]]);
const LUZ = new THREE.MeshBasicMaterial({ color: 0xfbfdff });
function addBox(w, h, d, mat, x, y, z, opts = {}) {
- const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), mat);
+ const m = new THREE.Mesh(caixaUV(new THREE.BoxGeometry(w, h, d), w, h, d, UV_METROS.get(mat)), mat);
m.position.set(x, y + h / 2, z); m.castShadow = opts.cast !== false; m.receiveShadow = true;
if (opts.ry) m.rotation.y = opts.ry;
if (opts.name) m.name = opts.name;
@@ -157,7 +196,7 @@ export function buildUpa(scene, T) {
panelPositions.forEach(([x, z], i) => panels.setMatrixAt(i, panelMatrix.compose(new THREE.Vector3(x, CEIL - 0.05, z), panelQuat, new THREE.Vector3(1, 1, 1))));
panels.name = 'upa-clinical-ceiling-panels'; root.add(panels);
for (const [x, z, color] of [[-18, -23, 0xf0fbff], [18, -23, 0xe9fff4], [-18, 0, 0xf0fbff], [18, 0, 0xfff5e0], [-18, 24, 0xf0fbff], [18, 24, 0xffeeee]]) {
- const light = new THREE.PointLight(color, 0.32, 24, 2); light.position.set(x, CEIL - 0.35, z); root.add(light);
+ const light = new THREE.PointLight(color, 0.9, 30, 2); light.position.set(x, CEIL - 0.35, z); root.add(light);
}
const wX = HALF_X - 0.4, wZ = HALF_Z - 0.4;
@@ -310,8 +349,8 @@ export function buildUpa(scene, T) {
ARSENAL.forEach((k, i) => place(k, 25 - i * 3, 34, Math.PI)); // emergência (Time B), faixa junto à parede norte
place('ak', -1.6, 3, 0); place('m4', 1.6, -3, 0); // disputadas no cruzamento central
- const hemi = new THREE.HemisphereLight(0xf4f8ff, 0xb8c0c8, 0.92); scene.add(hemi);
- const sun = new THREE.DirectionalLight(0xffffff, 0.68);
+ const hemi = new THREE.HemisphereLight(0xf1f8f4, 0xd9d5c8, 0.7); scene.add(hemi);
+ const sun = new THREE.DirectionalLight(0xffffff, 0.4);
// Ambiente integralmente coberto: iluminação setorial dá volume sem redesenhar o mapa
// inteiro num shadow pass a cada quadro (diferença relevante no 8×8 WebGL).
sun.position.set(6, 30, -8); sun.castShadow = false; scene.add(sun);
@@ -344,6 +383,47 @@ export function buildUpa(scene, T) {
],
});
+ // Faixas de setor e sombra de contato numa camada só, esticada no piso inteiro por cima do granilite.
+ function pisoCamada() {
+ const W = 1024, H = 1229, [c, x] = mkCanvas(W, H);
+ const px = (wx) => (wx + HALF_X) / (HALF_X * 2) * W, py = (wz) => (wz + HALF_Z) / (HALF_Z * 2) * H;
+ for (const [cor, x0, z0, x1, z1] of [['#c9a86a', -HALF_X, -HALF_Z, -3.5, -14], ['#8fa3ad', -HALF_X, 14, -3.5, HALF_Z], ['#8fa3ad', 3.5, 14, HALF_X, HALF_Z], ['#b9ad84', 3.5, -HALF_Z, HALF_X, -14]]) {
+ x.globalAlpha = .16; x.fillStyle = cor; x.fillRect(px(x0), py(z0), px(x1) - px(x0), py(z1) - py(z0));
+ }
+ x.globalAlpha = 1; x.fillStyle = '#000';
+ // O retângulo é desenhado fora da tela: só a sombra borrada cai no canvas.
+ const LONGE = 4 * W; x.shadowOffsetX = LONGE;
+ for (const col of colliders) {
+ if (col.minY > .45) continue;
+ const parede = col.maxY - col.minY > 3;
+ x.shadowColor = parede ? 'rgba(14,16,14,.5)' : 'rgba(14,16,14,.42)'; x.shadowBlur = parede ? 10 : 6;
+ const m = parede ? .3 : .1;
+ x.fillRect(px(col.minX - m) - LONGE, py(col.minZ - m), px(col.maxX + m) - px(col.minX - m), py(col.maxZ + m) - py(col.minZ - m));
+ }
+ x.shadowColor = 'transparent'; x.shadowBlur = 0; x.shadowOffsetX = 0;
+ // CADA cor é o CAMINHO até um setor: desce o corredor na sua faixa e VIRA pra dentro da porta
+ // (portas do corredor em x=∓3,5, z ∈ {-25, 0, 25}). Fina e sem cruzar parede.
+ const linha = (cor, pts) => { x.strokeStyle = cor; x.lineWidth = 3; x.lineJoin = 'round'; x.lineCap = 'round'; x.beginPath(); pts.forEach(([a, b], i) => i ? x.lineTo(px(a), py(b)) : x.moveTo(px(a), py(b))); x.stroke(); };
+ linha('#2f9e5e', [[-2.6, -33], [-2.6, -25], [-7, -25]]);
+ linha('#2f6fb0', [[-1.7, -33], [-1.7, 0], [-7, 0]]);
+ linha('#8e44ad', [[-0.8, -33], [-0.8, 25], [-7, 25]]);
+ linha('#e0a92a', [[2.6, -33], [2.6, -25], [7, -25]]);
+ linha('#e07b2a', [[1.7, -33], [1.7, 0], [7, 0]]);
+ linha('#c0392b', [[0.8, -33], [0.8, 25], [7, 25]]);
+ // Sem espaço de cor: o sampler entrega o RGB premultiplicado ainda em sRGB e o shader desfaz nessa ordem.
+ const t = withSurfaceAllocation(() => tex(c), true); t.colorSpace = THREE.NoColorSpace; t.premultiplyAlpha = true; t.anisotropy = 4; return t;
+ }
+ // O slot de emissão carrega a camada com a UV crua do piso; o shader a compõe sobre o albedo.
+ MAT.piso.emissiveMap = pisoCamada();
+ MAT.piso.onBeforeCompile = (shader) => {
+ shader.fragmentShader = shader.fragmentShader.replace('#include ',
+ `vec4 upaCamada = texture2D( emissiveMap, vEmissiveMapUv );
+ vec3 upaCor = upaCamada.rgb / max( upaCamada.a, 0.004 );
+ upaCor = mix( pow( ( upaCor + 0.055 ) / 1.055, vec3( 2.4 ) ), upaCor / 12.92, vec3( lessThanEqual( upaCor, vec3( 0.04045 ) ) ) );
+ diffuseColor.rgb = mix( diffuseColor.rgb, upaCor, upaCamada.a );`);
+ };
+ MAT.piso.customProgramCacheKey = () => 'upa-piso-camada';
+
const spawns = {
E: [-25, -20, -15, -10].map(x => ({ x, z: -31, yaw: 0 })),
B: [10, 15, 20, 25].map(x => ({ x, z: 31, yaw: Math.PI })),
diff --git a/public/js/mode_javaporcos.js b/public/js/mode_javaporcos.js
index ba55d160e3..e5e7ed45d8 100644
--- a/public/js/mode_javaporcos.js
+++ b/public/js/mode_javaporcos.js
@@ -1,5 +1,7 @@
+import { WAVE_COUNTS, PREP_SECONDS, COMBAT_SECONDS } from './javaporcos_ondas.js';
+export { WAVE_COUNTS } from './javaporcos_ondas.js';
import * as THREE from 'three';
-import { regrasDaInvasao, avaliarFimDaInvasao, repartirTerritorio } from './javaporcos_partida.js';
+import { regrasDaInvasao, avaliarFimDaInvasao, repartirTerritorio, vencedorPorLimite } from './javaporcos_partida.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { assetUrl } from './data/asseturl.js';
import { MODELOS_JAVAPORCOS, varianteJavaporco } from './data/javaporcos_modelos.js';
@@ -9,7 +11,6 @@ import { DIRECAO_FLUIDA, direcaoDaHorda, curvarRumo } from './javaporcos_direcao
/* Teto de vivos MEDIDO em tools/eval/javaporcos-perf.mjs (64 vivos = 0,22 ms/quadro).
Subir daqui sem medir de novo é chutar o orçamento de quadro. */
export const MAX_ALIVE = 64;
-export const WAVE_COUNTS = Object.freeze([24, 36, 48, 64, 80, 96, 120, 150]);
export const BOAR_POINTS = Object.freeze({ jovem: 100, adulto: 180, matriarca: 300, ariete: 500 });
/* Vida baixa é o que faz horda GIGANTE ler como horda e não como esponja de bala:
618 bichos na partida inteira só funcionam se cada um cai em poucos tiros. */
@@ -38,8 +39,6 @@ const VAGAR_RITMO = 0.55;
const VAGAR_TROCA = 5;
const DEFAULT_MAX_ALIVE = MAX_ALIVE;
-const PREP_SECONDS = 12;
-const COMBAT_SECONDS = 75;
const DEATH_SECONDS = 120;
const MAX_CORPSES = 8;
const MODEL_SPEEDS = Object.freeze({ jovem: 1.08, adulto: 1, matriarca: 0.88, ariete: 0.8 });
@@ -81,7 +80,7 @@ function scoreDe(state, playerId) {
return state.scores[playerId] ||= { points: 0, kills: 0, assists: 0, combo: 0, bestCombo: 0, damagePrevented: 0, lastKillAt: -Infinity };
}
-export function criarHorda({ seed = 1, maxAlive = DEFAULT_MAX_ALIVE, entradas = FRENTES, becos = 0, setores = 16, maxWaves = 8, mutante = '' } = {}) {
+export function criarHorda({ seed = 1, maxAlive = DEFAULT_MAX_ALIVE, entradas = FRENTES, becos = 0, setores = 16, maxWaves = WAVE_COUNTS.length, mutante = '' } = {}) {
const magra = mutante === 'horda-magra';
return {
seed: seed >>> 0,
@@ -195,37 +194,37 @@ function ondaLimpa(state) {
}
}
-/* Onda inteira na rua e o relógio dela zerou: a próxima vem com as sobras ainda vivas; na última, sobreviveu. */
function venceuOTempo(state) {
- if (!state.alive.length) return;
if (state.maxWaves && state.wave === state.maxWaves) {
state.teamBonus += Math.round(3000 * (1 - (state.dominio || 0)));
state.phase = 'finished';
state.winner = 'E';
return;
}
+ state.remaining = 0;
state.phase = 'prep';
state.prepLeft = PREP_SECONDS;
}
-export function passoHorda(state, dt) {
+export function passoHorda(state, dt, dtOnda = dt) {
if (state.winner) return state;
- state.clock += dt;
+ // O cronômetro acompanha o quadro do navegador. Os spawns acompanham a simulação.
+ state.clock += dtOnda;
recalcularFuria(state);
if (state.phase === 'prep') {
- state.prepLeft = Math.max(0, state.prepLeft - dt);
+ state.prepLeft = Math.max(0, state.prepLeft - dtOnda);
if (!state.prepLeft) iniciarOnda(state);
return state;
}
if (state.phase !== 'combat') return state;
- state.combatLeft = Math.max(0, state.combatLeft - dt);
+ state.combatLeft = Math.max(0, state.combatLeft - dtOnda);
state.spawnClock += dt;
const cadencia = cadenciaDeSpawn(state);
while (state.remaining > 0 && state.alive.length < state.maxAlive && state.spawnClock >= cadencia) {
state.spawnClock -= cadencia;
spawnAnimal(state);
}
- if (!state.combatLeft && !state.remaining && state.mutante !== 'onda-eterna') venceuOTempo(state);
+ if (!state.combatLeft && state.mutante !== 'onda-eterna') venceuOTempo(state);
ondaLimpa(state);
return state;
}
@@ -262,7 +261,6 @@ export function registrarAbate(state, animalId, killerId, mutant = '') {
score.points += Math.round(pool * damage / danoAssistente);
score.assists++;
}
- ondaLimpa(state);
return true;
}
@@ -823,7 +821,7 @@ class InvasaoJavaporcos {
entradas: this.horda.frentes.length,
becos: this.horda.becos.length,
setores: this.horda.setores.length,
- maxWaves: 0,
+ maxWaves: this.regras.ondas,
});
}
get frentes() { return this.horda.frentes; }
@@ -1060,13 +1058,16 @@ class InvasaoJavaporcos {
return ctx;
}
- update(dt) {
+ update(dt, dtOnda = dt) {
if (this.game.state !== 'live') return;
this.orcamentoCampo = 1;
this.listarJogadores();
if (!this.game.online || this.game.dedicated) {
const phase = this.state.phase, winner = this.state.winner, wave = this.state.wave;
- passoHorda(this.state, dt);
+ if (this.state.mutante !== 'sem-derrota') this.state.winner ||= avaliarFimDaInvasao(this.state, this.regras, this.game.combatants, this.game.playerTeam);
+ passoHorda(this.state, dt, dtOnda);
+ /* A fábrica fecha a última onda com 'E'; na disputa tripla quem leva é o critério do limite. */
+ if (this.state.winner === 'E' && this.regras.times === 3) this.state.winner = vencedorPorLimite(this.state, this.regras);
this.tickDominio(this.game.time);
if (this.state.mutante !== 'sem-derrota') this.state.winner ||= avaliarFimDaInvasao(this.state, this.regras, this.game.combatants, this.game.playerTeam);
if (this.state.winner) this.state.phase = 'finished';
@@ -1504,11 +1505,17 @@ class InvasaoJavaporcos {
}
if (!forcar && this.game.time < this.hudAte) return;
this.hudAte = this.game.time + .12;
- const phase = this.state.phase === 'prep' ? `PRÓXIMA ONDA EM ${Math.ceil(this.state.prepLeft)}s` : `PRÓXIMA ONDA EM ${Math.ceil(this.state.combatLeft)}s · ${this.state.remaining + this.state.alive.length} RESTANTES`;
+ const total = this.state.maxWaves || 0, faltam = this.state.remaining ? ` · FALTAM ${this.state.remaining}` : '';
+ const onda = `ONDA ${Math.max(1, this.state.wave)}${total ? `/${total}` : ''}`;
+ const phase = this.state.phase === 'prep'
+ ? `${total && this.state.wave === total - 1 ? 'ÚLTIMA ONDA' : 'PRÓXIMA ONDA'} EM ${Math.ceil(this.state.prepLeft)}s`
+ : total && this.state.wave === total
+ ? `ÚLTIMA ONDA${faltam} · SEGURE ${Math.ceil(this.state.combatLeft)}s`
+ : `PRÓXIMA ONDA EM ${Math.ceil(this.state.combatLeft)}s${faltam}`;
const score = this.state.scores[this.idDo(this.game.player)]?.points || 0;
const comida = (this.game.world.foodSpots || []).length;
const lixo = comida ? ` · LIXO ${this.state.foodRevirada}/${comida}` : '';
- this.hudTexto.textContent = `ONDA ${Math.max(1, this.state.wave)} · ${phase} · ${this.state.alive.length} NA RUA · FÚRIA ${Math.round((this.state.fury || 0) * 100)}%${lixo} · ${score} PTS`;
+ this.hudTexto.textContent = `${onda} · ${phase} · ${this.state.alive.length} NA RUA · FÚRIA ${Math.round((this.state.fury || 0) * 100)}%${lixo} · ${score} PTS`;
if (this.state.waitingForPlayers) this.hudTexto.textContent = `AGUARDANDO DEFENSORES · ${this.state.players || 0}/${this.state.minPlayers || 4} PARA COMEÇAR · MÁXIMO 8`;
if (this.state.mutante === 'mapa-mudo') return;
const dominio = Math.round((this.state.dominio || 0) * 100);
@@ -1555,11 +1562,32 @@ class InvasaoJavaporcos {
return {x:refugio.x+deslocamento,z:refugio.z,yaw:team === 'E' ? -Math.PI / 2 : Math.PI / 2};
}
+ /* Partida de ondas: em que onda o time caiu, ou que sobreviveu a todas. Vazio no INFINITO e nos limites. */
+ fraseDoFim(winner) {
+ const total = this.state.maxWaves || 0;
+ if (!total || !winner) return '';
+ if (winner === 'J') {
+ if (this.regras.times === 3) {
+ const humanos = this.game.combatants.filter(c => !c._objectiveNpc && (c.team === 'E' || c.team === 'B'));
+ const caiu = c => this.state.eliminados.includes(c.team);
+ const wipe = this.regras.wipe === 'partida'
+ ? humanos.some(caiu)
+ : humanos.length > 0 && humanos.every(caiu);
+ if (!wipe) return '';
+ }
+ return `CAÍRAM NA ONDA ${Math.max(1, Math.min(total, this.state.wave))}/${total}`;
+ }
+ if (this.regras.times === 3 && winner !== 'E') return '';
+ return this.state.wave >= total ? `SOBREVIVEU ${total}/${total}` : '';
+ }
+
roundResult(winner) {
+ const ondas = this.fraseDoFim(winner), tripla = this.regras.times === 3;
+ const detail = `${this.state.kills} javaporcos abatidos · ${Math.round((this.state.dominio || 0) * 100)}% ocupado pela horda`;
return {
duration: winner === 'J' ? 6 : 10,
- title: winner === 'draw' ? 'DISPUTA EMPATADA' : winner === 'J' ? 'JAVAPORCOS VENCERAM' : `${this.game._teamName(winner)} VENCEU`,
- detail: `${this.state.kills} javaporcos abatidos · ${Math.round((this.state.dominio || 0) * 100)}% ocupado pela horda`,
+ title: ondas && !tripla ? ondas : winner === 'draw' ? 'DISPUTA EMPATADA' : winner === 'J' ? 'JAVAPORCOS VENCERAM' : `${this.game._teamName(winner)} VENCEU`,
+ detail: ondas && tripla ? `${ondas} · ${detail}` : detail,
};
}
renderScoreboard() {
diff --git a/public/js/privacy-preferences.js b/public/js/privacy-preferences.js
index 22e6c57739..985505b180 100644
--- a/public/js/privacy-preferences.js
+++ b/public/js/privacy-preferences.js
@@ -2,11 +2,21 @@ import './privacy-runtime.js';
export const analyticsAllowed=()=>window.__csPrivacy.allowed();
export const privacyChoice=()=>window.__csPrivacy.choice();
export const setPrivacyChoice=value=>window.__csPrivacy.set(value);
-export function mountPrivacyChoice(container,{onChange=()=>{}}={}) {
+export function mountPrivacyChoice(container,{onChange=()=>{},pageUsage=false,onPageChange=()=>{},onPageError=()=>{}}={}) {
const label=document.createElement('label');label.className='account-consent';
const check=document.createElement('input');check.type='checkbox';check.name='analytics';check.checked=analyticsAllowed();
label.append(check,document.createTextNode('Medir uso e desempenho do jogo com um identificador anônimo deste navegador (sem IP, sem e-mail). Vem ligado; desmarque para parar a qualquer momento.'));
const note=document.createElement('p');note.className='social-muted';note.textContent='Sessão, segurança, preferências e progresso usam armazenamento necessário para jogar e manter a conta.';
check.onchange=async()=>{check.disabled=true;try{await onChange(check.checked);}catch{check.checked=analyticsAllowed();}finally{check.disabled=false;}};
- container.append(label,note);return check;
+ window.addEventListener('cs-privacy-change',()=>{if(!check.disabled)check.checked=analyticsAllowed();});
+ container.append(label,note);if(pageUsage)mountPageUsageChoice(container,{onChange:onPageChange,onError:onPageError});return check;
+}
+
+function mountPageUsageChoice(container,{onChange=()=>{},onError=()=>{}}={}) {
+ const label=document.createElement('label');label.className='account-consent';
+ const check=document.createElement('input');check.type='checkbox';check.name='page-usage';check.checked=window.__csPrivacy.pageAllowed();
+ label.append(check,document.createTextNode('Permitir contagem opcional de visualizações de página neste navegador. Desmarque para revogar.'));
+ check.onchange=async()=>{check.disabled=true;try{const saved=await window.__csPrivacy.setPageUsage(check.checked);if(saved===null)return;check.checked=saved;onChange(check.checked);}catch{check.checked=window.__csPrivacy.pageAllowed();onError();}finally{check.disabled=false;}};
+ window.addEventListener('cs-page-usage-change',()=>{check.checked=window.__csPrivacy.pageAllowed();});
+ container.append(label);return check;
}
diff --git a/public/js/privacy-runtime.js b/public/js/privacy-runtime.js
index 9c66e22707..fdd7324ecb 100644
--- a/public/js/privacy-runtime.js
+++ b/public/js/privacy-runtime.js
@@ -1,76 +1,183 @@
-/* Medição LIGADA por padrão (dono, 09/11/2026): só recusa gravada em `cs_privacy` desliga;
- storage corrompido/antigo vale como padrão. Cloudflare Web Analytics só entra por este gate.
- Réguas: privacy-choice-check, privacy-ops-check. */
+/* A telemetria do jogo mantém a escolha padrão. A contagem de páginas exige consentimento gravado. */
(function () {
if (window.__csPrivacy) return;
- const VERSION='corosolto-analytics-v1',KEY='cs_privacy';
- const CLOUDFLARE_TOKENS=Object.freeze({
- 'corosolto.com.br':'5f7f6c1ab01c4e2fb6b326dbab3e7197',
- 'www.corosolto.com.br':'5f7f6c1ab01c4e2fb6b326dbab3e7197',
- 'csbrasil.online':'b777fa448ebe48d8a635e74e9902be19',
- 'www.csbrasil.online':'b777fa448ebe48d8a635e74e9902be19',
- });
+ const VERSION='corosolto-analytics-v2',KEY='cs_privacy_v2',LEGACY_KEY='cs_privacy',PAGE_VERSION='corosolto-page-view-v1';
+ let pageBlocked=false,localRefusal=false,localPageRefusal=false,knownRefusal=false,invalidatePage=false,telemetryRevision=0,pageRevision=0;
+ let migrationSeed;
+ function parseRecord(raw) {
+ try { const value=JSON.parse(raw || 'null');return value && typeof value==='object' && !Array.isArray(value)?value:null; } catch { return null; }
+ }
+ function readRecord() {
+ const raw=localStorage.getItem(KEY);
+ if(raw===null)return migrationSeed || null;
+ migrationSeed=undefined;
+ return parseRecord(raw);
+ }
+ function telemetry(value) {
+ return ['corosolto-analytics-v1',VERSION].includes(value?.version) && typeof value.analytics==='boolean'?value:null;
+ }
+ function legacySeed() {
+ const record=parseRecord(localStorage.getItem(LEGACY_KEY));
+ const seed=telemetry(record)?{version:VERSION,analytics:record.analytics}: {};
+ if(typeof record?.updatedAt==='string' && 'analytics' in seed)seed.updatedAt=record.updatedAt;
+ if(record?.analytics!==false && record?.pageUsage?.version===PAGE_VERSION && typeof record.pageUsage.enabled==='boolean'){
+ seed.pageUsage={version:PAGE_VERSION,enabled:record.pageUsage.enabled};
+ }
+ return seed;
+ }
function choice() {
+ if(localRefusal)return {version:VERSION,analytics:false};
try {
- const value=JSON.parse(localStorage.getItem(KEY) || 'null');
- return value?.version===VERSION && typeof value.analytics==='boolean'?value:null;
- } catch { return null; }
+ const value=telemetry(readRecord());
+ knownRefusal=value?.analytics===false;
+ return value;
+ } catch { return knownRefusal?{version:VERSION,analytics:false}:null; }
}
function allowed() { return choice()?.analytics!==false; }
- function cloudflareToken() {
- return CLOUDFLARE_TOKENS[location.hostname.toLowerCase()] || '';
+ function pageAllowed() {
+ if(pageBlocked || localRefusal || localPageRefusal)return false;
+ try {
+ const record=parseRecord(localStorage.getItem(KEY)),page=record?.pageUsage;
+ return record?.analytics!==false && page?.version===PAGE_VERSION && page.enabled===true;
+ } catch { pageBlocked=true;return false; }
}
- let cloudflareLoaded=false,cloudflareScript=null;
- function enableCloudflareAnalytics() {
- const token=cloudflareToken();
- if(!allowed() || !token)return;
- window.__cfBeacon={token};
- if(cloudflareLoaded){
- // Se o script ainda não executou, restaura o token no mesmo elemento; nunca cria uma segunda instância.
- cloudflareScript.dataset.cfBeacon=JSON.stringify({token});
- return;
- }
- cloudflareLoaded=true;
- const script=document.createElement('script');
- cloudflareScript=script;
- /* Clássico, como no snippet da Cloudflare (#1425). Este arquivo roda antes do importmap: um
- `type=module` injetado aqui faz o Firefox ignorar o importmap, e `import 'three'` derruba o boot. */
- script.defer=true;
- script.src='https://static.cloudflareinsights.com/beacon.min.js';
- script.dataset.cfBeacon=JSON.stringify({token});
- script.addEventListener('load',()=>{
- if(!allowed())window.__cfBeacon=null;
+ function withLock(callback) {
+ return new Promise((resolve,reject)=>{
+ let db,transaction,finished=false;
+ const timer=setTimeout(()=>fail(new Error('privacy_lock_timeout')),2000);
+ function finish() {
+ finished=true;
+ clearTimeout(timer);
+ db?.close();
+ }
+ function fail(error) {
+ if(finished)return;
+ finish();
+ try { transaction?.abort(); } catch {}
+ reject(error);
+ }
+ try {
+ const open=indexedDB.open('cs-privacy-choice',1);
+ open.onupgradeneeded=()=>{
+ if(finished)open.transaction.abort();
+ else open.result.createObjectStore('lock');
+ };
+ open.onblocked=()=>fail(new Error('privacy_lock_blocked'));
+ open.onerror=()=>fail(open.error);
+ open.onsuccess=()=>{
+ db=open.result;
+ if(finished){db.close();return;}
+ try {
+ transaction=db.transaction('lock','readwrite');
+ transaction.onabort=()=>fail(transaction.error || new Error('privacy_lock_aborted'));
+ const request=transaction.objectStore('lock').get(0);
+ // O callback roda com a transação ativa. A gravação no localStorage é o commit.
+ request.onsuccess=()=>{
+ if(finished)return;
+ try {
+ const result=callback();
+ finish();
+ resolve(result);
+ } catch(error) { fail(error); }
+ };
+ } catch(error) { fail(error); }
+ };
+ } catch(error) { fail(error); }
});
+ }
+ function setPageUsage(enabled) {
+ if(typeof enabled!=='boolean')return Promise.reject(new TypeError('privacy_invalid'));
+ const revision=++pageRevision;
+ if(!enabled){localPageRefusal=true;pageBlocked=true;notifyPage();}
+ const telemetryAt=telemetryRevision;
+ return withLock(()=>{
+ if(revision!==pageRevision || (enabled && telemetryAt!==telemetryRevision))return null;
+ if(localRefusal){pageBlocked=true;notifyPage();return false;}
+ const record=readRecord();
+ if(enabled && record?.analytics===false){pageBlocked=true;notifyPage();return false;}
+ localStorage.setItem(KEY,JSON.stringify({...record,pageUsage:{version:PAGE_VERSION,enabled}}));
+ if(revision===pageRevision){localPageRefusal=false;pageBlocked=!enabled;notifyPage();}
+ return enabled;
+ }).then(result=>revision===pageRevision && (!enabled || telemetryAt===telemetryRevision)?result:null).catch(e=>{if(revision!==pageRevision || (enabled && telemetryAt!==telemetryRevision))return null;pageBlocked=true;notifyPage();throw e;});
+ }
+ let usageScript;
+ function enableUsage() {
+ if (usageScript || !pageAllowed() || location.protocol !== 'https:' || location.port || !['corosolto.com.br','www.corosolto.com.br'].includes(location.hostname)) return;
+ const script = document.createElement('script');
+ usageScript = script;
+ script.src = '/api/usage-script.js';
+ script.referrerPolicy = 'no-referrer';
+ script.onerror = () => { usageScript = null; };
document.head.appendChild(script);
}
- function stopCloudflareAnalytics() {
- // O beacon consulta este global antes de cada envio; anulá-lo preserva o fluxo atual.
- window.__cfBeacon=null;
- // Se o script ainda não executou, ele também não pode capturar um token válido.
- if(cloudflareScript)cloudflareScript.dataset.cfBeacon='{"token":""}';
+ function clearSessionStorage() {
+ try { sessionStorage.removeItem('cs_session');sessionStorage.removeItem('cs_invite_landing'); } catch {}
}
function clearOptionalStorage() {
- try { localStorage.removeItem('cs_acq');localStorage.removeItem('cs_ops_last');sessionStorage.removeItem('cs_session');sessionStorage.removeItem('cs_invite_landing'); } catch {}
+ try { localStorage.removeItem('cs_acq');localStorage.removeItem('cs_ops_last'); } catch {}
+ clearSessionStorage();
}
function notify(value) { window.dispatchEvent(new CustomEvent('cs-privacy-change',{detail:value})); }
+ function notifyPage() { window.dispatchEvent(new CustomEvent('cs-page-usage-change',{detail:null})); }
function set(analytics) {
- if(typeof analytics!=='boolean')throw new TypeError('privacy_invalid');
+ if(typeof analytics!=='boolean')return Promise.reject(new TypeError('privacy_invalid'));
+ const revision=++telemetryRevision;
const value={version:VERSION,analytics,updatedAt:new Date().toISOString()};
- localStorage.setItem(KEY,JSON.stringify(value));
- if(!analytics)clearOptionalStorage();
- notify(value);
- if(!analytics)stopCloudflareAnalytics();
- return value;
+ if(!analytics){pageRevision++;invalidatePage=true;localRefusal=true;pageBlocked=true;clearOptionalStorage();notify(value);notifyPage();}
+ return withLock(()=>{
+ if(revision!==telemetryRevision)return null;
+ const record=analytics?readRecord():null;
+ if(analytics && !invalidatePage && record?.analytics!==false && record?.pageUsage)value.pageUsage=record.pageUsage;
+ localStorage.setItem(KEY,JSON.stringify(value));
+ knownRefusal=!analytics;
+ if(revision===telemetryRevision){
+ localRefusal=false;invalidatePage=false;
+ if(!analytics)localPageRefusal=false;
+ if(analytics)notify(value);
+ }
+ return value;
+ }).then(result=>revision===telemetryRevision?result:null).catch(e=>{if(revision!==telemetryRevision)return null;if(analytics){pageBlocked=true;notifyPage();}throw e;});
}
+ try { if(localStorage.getItem(KEY)===null)migrationSeed=legacySeed(); } catch {}
if(!allowed())clearOptionalStorage();
- enableCloudflareAnalytics();
- window.addEventListener('cs-privacy-change',enableCloudflareAnalytics);
+ window.addEventListener('cs-page-usage-change', enableUsage);
window.addEventListener('storage',event=>{
if(event.key!==KEY && event.key!==null)return;
- const value=choice() || {version:VERSION,analytics:true};
- if(!allowed())clearOptionalStorage();
- notify(value);
- if(!allowed())stopCloudflareAnalytics();
+ try {
+ const raw=localStorage.getItem(KEY),record=parseRecord(raw);
+ if(telemetry(record)?.analytics===false){knownRefusal=true;clearSessionStorage();}
+ if(event.key===KEY && raw===event.newValue) {
+ if(!localRefusal && !localPageRefusal && record?.analytics!==false && record?.pageUsage?.version===PAGE_VERSION && record.pageUsage.enabled===true)pageBlocked=false;
+ const before=telemetry(parseRecord(event.oldValue))?.analytics;
+ const after=telemetry(record)?.analytics;
+ if(before!==after)notify(choice() || {version:VERSION,analytics:true});
+ }
+ } catch { pageBlocked=true; }
+ if(!allowed())clearSessionStorage();
+ notifyPage();
});
- window.__csPrivacy={allowed,choice,set};
+ window.__csPrivacy={allowed,choice,set,pageAllowed,setPageUsage};
+ if(migrationSeed) {
+ const seed=migrationSeed;
+ void withLock(()=>{
+ if(localStorage.getItem(KEY)===null){
+ const current=legacySeed();
+ const record=current.analytics===false?current:seed;
+ if(record.analytics!==false && current.pageUsage?.enabled===false)record.pageUsage=current.pageUsage;
+ const lateRefusal=record.analytics===false && seed.analytics!==false && !localRefusal;
+ migrationSeed=record;
+ try { localStorage.setItem(KEY,JSON.stringify(record)); }
+ finally {
+ if(lateRefusal){
+ knownRefusal=true;
+ clearOptionalStorage();
+ notify(record);
+ }
+ }
+ }
+ migrationSeed=undefined;
+ notifyPage();
+ }).catch(()=>{});
+ }
+ enableUsage();
})();
diff --git a/public/js/qa-mobile.js b/public/js/qa-mobile.js
index 44ff4fa8c9..15fa6f2821 100644
--- a/public/js/qa-mobile.js
+++ b/public/js/qa-mobile.js
@@ -7,7 +7,6 @@ const CANAL = 'coro-qa';
const PRAZO_LIVE_MS = 180_000; // celular fraco em rede ruim leva minutos para montar o mapa
const PRAZO_HUD_MS = 20_000; // o #touch-ui nasce junto com a partida; 20 s é folga
const TETO_MENSAGENS = 5;
-const CHAVE_PRIVACIDADE = 'cs_privacy';
/* Passo e duração. Os prazos são ABSOLUTOS (t0 + soma): com prazo relativo o atraso de cada
passo se somava e o roteiro de 20 s terminava em 31 s (docs/mobile/QA-MOBILE.md). */
@@ -104,20 +103,7 @@ async function esperaAte(condicao, prazoMs, intervalo = 200) {
}
}
-/* O ops.js mede FPS só com analytics permitido. Liga para o roteiro e devolve um
- restaurador que repõe EXATAMENTE a escolha anterior (inclusive "nunca escolheu"). */
-function ligaMedicao() {
- let antes = null;
- try { antes = localStorage.getItem(CHAVE_PRIVACIDADE); } catch { /* storage bloqueado */ }
- try { window.__csPrivacy?.set(true); } catch { /* sem runtime de privacidade */ }
- return () => {
- try {
- if (antes === null) localStorage.removeItem(CHAVE_PRIVACIDADE);
- else localStorage.setItem(CHAVE_PRIVACIDADE, antes);
- window.dispatchEvent(new CustomEvent('cs-privacy-change', { detail: null }));
- } catch { /* storage bloqueado */ }
- };
-}
+function ligaMedicao() { return () => {}; }
function vigiaErros() {
const conta = { js: 0, rejeicoes: 0, mensagens: [] };
@@ -169,14 +155,23 @@ function leEscada() {
return { degrau: numero(e?.escada?.degrau), nome: e?.DEGRAUS?.[e?.escada?.degrau]?.nome ?? null };
} catch { return { degrau: null, nome: null }; }
}
-function leFps() {
- try {
- const r = window.__csbOps?.resumo?.();
- return {
- p50: numero(r?.fps?.p50), p5: numero(r?.fps?.p5), min: numero(r?.fps?.min),
- amostras: numero(r?.fps?.amostras), travadas: numero(r?.fps?.travadas), congeladas: numero(r?.fps?.congeladas),
- };
- } catch { return { p50: null, p5: null, min: null, amostras: null, travadas: null, congeladas: null }; }
+function vigiaFps() {
+ const amostras=[];let ativo=true,ultimo=0,inicio=0,comeco=0,frames=0,travadas=0,congeladas=0;
+ function quadro(t) {
+ if(!ativo)return;
+ if(!comeco)comeco=t;
+ if(t-comeco>DURACAO_ROTEIRO_MS+PRAZO_HUD_MS){ativo=false;return;}
+ if(ultimo && !document.hidden){const dt=t-ultimo;if(dt>100 && dt<5000){travadas++;if(dt>1000)congeladas++;}}
+ ultimo=t;frames++;if(!inicio)inicio=t;
+ if(t-inicio>=1000){if(!document.hidden)amostras.push(frames);frames=0;inicio=t;}
+ requestAnimationFrame(quadro);
+ }
+ requestAnimationFrame(quadro);
+ return {parar(){
+ ativo=false;const ordenadas=amostras.slice().sort((a,b)=>a-b);
+ const percentil=p=>ordenadas.length?ordenadas[Math.floor((ordenadas.length-1)*p)]:null;
+ return {p50:percentil(.5),p5:percentil(.05),min:ordenadas[0]??null,amostras:amostras.length,travadas,congeladas};
+ }};
}
function leJogo(g) {
const p = g?.player;
@@ -301,6 +296,7 @@ async function rodar(origem) {
}
if (!await esperaAte(() => noHud('.touch-joy-l'), PRAZO_HUD_MS)) falhas.push('o HUD de toque (#touch-ui) não apareceu');
+ const fpsVigia = vigiaFps();
const vigia = vigiaErros();
const desenho = vigiaDesenho(window.__escada?.renderer, jogo);
const antes = leJogo(jogo);
@@ -324,7 +320,7 @@ async function rodar(origem) {
const depois = leJogo(jogo);
const erros = vigia.parar();
const render = desenho.parar();
- const fps = leFps();
+ const fps = fpsVigia.parar();
const escadaFinal = leEscada();
let dpr = null;
try { dpr = numero(window.__escada?.renderer?.getPixelRatio?.()); } catch { /* renderer sumiu com a partida */ }
diff --git a/public/js/tp/lobby.js b/public/js/tp/lobby.js
index 693b5b20e6..307d307267 100644
--- a/public/js/tp/lobby.js
+++ b/public/js/tp/lobby.js
@@ -5,6 +5,7 @@ import { VERSION } from '../version.js';
import { tretaLoja, abrirTretaSkin } from '../treta-store.js';
import { montarPlacar } from './ranking.js';
import { wallpaperJavaporcos } from '../javaporcos_apresentacao.js';
+import { RESUMO_ONDAS } from '../javaporcos_partida.js';
import { anunciarJavaporcos } from '../javaporcos_novidade.js';
import { montarPainelFlavio } from './flavio.js';
import { abrirPasse } from './passe.js';
@@ -279,7 +280,7 @@ function montarEsquerda(play) {
const invasao = no('button', 'tp-lobby-painel tp-lobby-invasao');
invasao.type='button';invasao.id='tp-lobby-invasao';
const arte=no('img');arte.src=wallpaperJavaporcos(0);arte.alt='';arte.loading='lazy';arte.decoding='async';
- invasao.append(arte,no('span','tp-chip tp-chip--novo',tr('INVASÃO')),no('strong','tp-disp',tr('CAÇA AO JAVAPORCO')),no('span','',tr('Defenda a cidade · 4 a 8 defensores')),no('span','tp-lobby-link',tr('DEFENDER A CIDADE ▸')));
+ invasao.append(arte,no('span','tp-chip tp-chip--novo',tr('INVASÃO')),no('strong','tp-disp',tr('CAÇA AO JAVAPORCO')),no('span','',tr('Defenda a cidade · 4 a 8 defensores')),no('span','',tr(RESUMO_ONDAS)),no('span','tp-lobby-link',tr('DEFENDER A CIDADE ▸')));
invasao.addEventListener('click',()=>{$('hub-sp')?.click();window.__tpModos?.irMapa('invasao_javaporcos');});
esq.appendChild(invasao);
const novidades = no('section', 'tp-lobby-painel tp-lobby-novidades');
diff --git a/public/js/tp/modos.js b/public/js/tp/modos.js
index 3aa66aadc4..7046cda066 100644
--- a/public/js/tp/modos.js
+++ b/public/js/tp/modos.js
@@ -1,6 +1,7 @@
/* Treta Pop · 03 modo e mapa, 19 mobile. Carregado por tp/ligar.js só com ?ui=v3. */
import { tr } from '../i18n.js';
import { retratoFontes } from '../data/retratos.js';
+import { resumoDoFimJavaporcos } from '../javaporcos_partida.js';
const CHAVE_FAV = 'tp-modos-favoritos';
/* Selo NOVO: mapa que entrou no jogo (mapcat.js MAP_DATA) há no máximo 30 dias. */
@@ -236,7 +237,7 @@ function pintar() {
}
}
for (const c of tela.lista.querySelectorAll('.tp-modos__mapa')) c.querySelector('.tp-modos__mapa-btn').setAttribute('aria-pressed', String(c.dataset.id === est.mapa));
- const modo = tr(horda ? 'INVASÃO · DISPUTA TERRITORIAL' : est.objetivo === 'escort' ? 'ESCOLTA' : est.modo === 'arena' ? 'VIRA-CASACA' : (est.modo === 'ctf' ? 'CAPTURA' : 'MATA-MATA'));
+ const modo = tr(horda ? `INVASÃO · ${resumoDoFimJavaporcos(est.javaporcos) || 'DISPUTA TERRITORIAL'}` : est.objetivo === 'escort' ? 'ESCOLTA' : est.modo === 'arena' ? 'VIRA-CASACA' : (est.modo === 'ctf' ? 'CAPTURA' : 'MATA-MATA'));
tela.ficha.querySelector('.tp-modos__olho').textContent = mapa ? `${modo} · ${mapa.cats.map(tr).join(' · ')}` : modo;
tela.ficha.querySelector('.tp-modos__nome').textContent = mapa?.nome || '';
tela.ficha.querySelector('.tp-modos__desc').textContent = mapa?.desc || '';
diff --git a/public/js/tp/passe.js b/public/js/tp/passe.js
index b366455ea1..19dbd5b6d6 100644
--- a/public/js/tp/passe.js
+++ b/public/js/tp/passe.js
@@ -211,9 +211,10 @@ function cartaoNivel(l, s) {
const card = no('li', 'tp-passe-nivel');
card.dataset.nivel = String(l.n);
card.dataset.estado = estado;
- if (s.authenticated && (s.level === l.n || (!s.level && l.n === 1))) card.dataset.atual = '';
+ if (s.authenticated && s.level === l.n) card.dataset.atual = '';
const cab = no('div', 'tp-passe-nivel__cab');
cab.append(no('span', 'tp-disp tp-passe-nivel__n', frase('passeNivel', l.n)), no('span', 'tp-num tp-passe-nivel__xp', `${numero(l.xp)} XP`));
+ if (s.authenticated && s.level === l.n) cab.appendChild(no('span', 'tp-passe-nivel__atual', tr('ATUAL')));
if (estado === 'resgatado') { const ok = no('span', 'tp-passe-nivel__ok'); ok.innerHTML = ICONE_CHECK; ok.setAttribute('aria-hidden', 'true'); cab.appendChild(ok); }
const lista = no('ul', 'tp-passe-nivel__premios');
const ordem = { character: 0, weapon_skin: 1, coins: 2, xp_boost: 3 };
@@ -300,7 +301,7 @@ function desenhar() {
barra.setAttribute('aria-label', tr('XP do nível'));
barra.appendChild(no('i'));
const legenda = no('div', 'tp-passe__xp-legenda');
- legenda.append(no('span', 'tp-num', s.nextLevelXp ? `${numero(s.xp)} / ${numero(s.nextLevelXp)} XP` : `${numero(s.xp)} XP`),
+ legenda.append(no('span', 'tp-num', s.nextLevelXp ? `${numero(p.de)} / ${numero(p.ate)} XP` : `${numero(s.xp)} XP`),
no('span', '', s.nextLevelXp ? frase('passeFaltaProximo', numero(s.nextLevelXp - s.xp), s.level + 1) : tr('NÍVEL MÁXIMO')));
meio.append(barra, legenda);
topo.append(nivel, meio);
diff --git a/public/js/tp/resultado.js b/public/js/tp/resultado.js
index 7ca21acf17..6e9be089b7 100644
--- a/public/js/tp/resultado.js
+++ b/public/js/tp/resultado.js
@@ -58,6 +58,7 @@ function dados(fim) {
const timesTerritorio = timesComTerritorio(g.objective);
const abates = g.player.kills | 0;
return {
+ ondas: g.objective?.fraseDoFim?.(vencedorObjetivo) || '',
nomes: g.world?.mode === 'horde' ? { E: g._teamName('E'), B: g._teamName('B'), J: g._teamName('J') } : null,
empate: vencedorObjetivo === 'draw',
territorio: timesTerritorio ? timesTerritorio.map(team=>[g._teamName(team),Math.round((g.objective.state.territorio[team] || 0)*100)]) : null,
@@ -180,7 +181,7 @@ export function ligar() {
frase.hidden = !d.vencedor;
if (d.vencedor) {
const modelo = vit ? 'A {time} levou a treta. O pastel da vitória está pago.' : 'A {time} levou a melhor. Já pediram CPI da partida.';
- frase.textContent = d.empate ? 'As equipes terminaram empatadas.' : d.nomes ? `${d.nomes[d.vencedor]} venceram a partida.` : tr(modelo).replace('{time}', tr(TIME[d.vencedor]));
+ frase.textContent = (d.ondas ? `${d.ondas}. ` : '') + (d.empate ? 'As equipes terminaram empatadas.' : d.nomes ? `${d.nomes[d.vencedor]} venceram a partida.` : tr(modelo).replace('{time}', tr(TIME[d.vencedor])));
}
const stats = q('.tp-res__stats');
diff --git a/public/js/treta-store.js b/public/js/treta-store.js
index 73723a2a88..8ea7f00575 100644
--- a/public/js/treta-store.js
+++ b/public/js/treta-store.js
@@ -36,6 +36,16 @@ let state=null,manifest={skins:{}},eyeManifest={eyewear:{}},selected=null,filter
let onEquip=()=>{},infoStage=null,infoVersion=0;
let equipmentRevision='';
const inventoryWaiters=new Set();
+// Ignorar uma resposta atrasada não corrige gravações fora de ordem no servidor.
+let equipmentMutation=Promise.resolve();
+const queueEquipmentMutation=operation=>{
+ const next=equipmentMutation.catch(()=>{}).then(operation);
+ equipmentMutation=next.catch(()=>{});
+ return next;
+};
+export function tretaEquipmentReady() {
+ return equipmentMutation;
+}
let accountEpoch=0,refreshEpoch=-1,loading=false,refreshFailed=false,purchasePending=false,view='characters',detailVersion=0,previewReady=false,previewLoading=false;
const $=id=>document.getElementById(id);
const owned=id=>state?.inventory?.some(s=>s.skin_id===id);
@@ -152,12 +162,15 @@ export function tretaSkinsDoArmario() {
}
export async function desequiparTretaSkin() {
const epoch=accountEpoch,owner=state?.accountId;
- const result=await socialApi('/api/treta',{action:'unequip',slot:'character'});
- if(epoch!==accountEpoch || result.accountId!==owner)return false;
- state=result;
- draw();updateBuy();notifyEquipment();
- document.dispatchEvent(new CustomEvent('cs-skin-equipped',{detail:{skinId:null,characterId:null,model:null}}));
- return true;
+ return queueEquipmentMutation(async()=>{
+ if(epoch!==accountEpoch || state?.accountId!==owner)return false;
+ const result=await socialApi('/api/treta',{action:'unequip',slot:'character'});
+ if(epoch!==accountEpoch || result.accountId!==owner)return false;
+ state=result;
+ draw();updateBuy();notifyEquipment();
+ document.dispatchEvent(new CustomEvent('cs-skin-equipped',{detail:{skinId:null,characterId:null,model:null}}));
+ return true;
+ });
}
function notifyEquipment() {
// A skin pode ser removida do inventário antes de seu manifesto chegar.
@@ -409,16 +422,19 @@ function updateBuy() {
}
async function equip(skin) {
const epoch=accountEpoch,owner=state?.accountId;
- const result=await socialApi('/api/treta',{action:'equip',skinId:skin.id});
- if(epoch!==accountEpoch || result.accountId!==owner)return false;
- state=result;
- draw();updateBuy();notifyEquipment();
- if(skin.slot==='weapon')document.dispatchEvent(new CustomEvent('cs-weapon-skin-equipped',{detail:{skinId:skin.id,weaponId:skin.weapon}}));
- else if(skin.slot==='eyewear')document.dispatchEvent(new CustomEvent('cs-eyewear-equipped',{detail:{eyewearId:skin.id}}));
- else if(skin.slot==='glove')document.dispatchEvent(new CustomEvent('cs-glove-equipped',{detail:{gloveId:skin.id}}));
- else if(skin.slot==='pack')document.dispatchEvent(new CustomEvent('cs-pack-equipped',{detail:{packId:skin.id}}));
- else {onEquip({...skin,model:asset(skin.id).model});document.dispatchEvent(new CustomEvent('cs-skin-equipped',{detail:{skinId:skin.id,characterId:skin.character,model:asset(skin.id).model}}));}
- return true;
+ return queueEquipmentMutation(async()=>{
+ if(epoch!==accountEpoch || state?.accountId!==owner)return false;
+ const result=await socialApi('/api/treta',{action:'equip',skinId:skin.id});
+ if(epoch!==accountEpoch || result.accountId!==owner)return false;
+ state=result;
+ draw();updateBuy();notifyEquipment();
+ if(skin.slot==='weapon')document.dispatchEvent(new CustomEvent('cs-weapon-skin-equipped',{detail:{skinId:skin.id,weaponId:skin.weapon}}));
+ else if(skin.slot==='eyewear')document.dispatchEvent(new CustomEvent('cs-eyewear-equipped',{detail:{eyewearId:skin.id}}));
+ else if(skin.slot==='glove')document.dispatchEvent(new CustomEvent('cs-glove-equipped',{detail:{gloveId:skin.id}}));
+ else if(skin.slot==='pack')document.dispatchEvent(new CustomEvent('cs-pack-equipped',{detail:{packId:skin.id}}));
+ else {onEquip({...skin,model:asset(skin.id).model});document.dispatchEvent(new CustomEvent('cs-skin-equipped',{detail:{skinId:skin.id,characterId:skin.character,model:asset(skin.id).model}}));}
+ return true;
+ });
}
async function buy() {
if(purchasePending || loading || refreshFailed || !selected || !available(selected.id) || (!owned(selected.id) && !previewReady))return;
diff --git a/public/style.css b/public/style.css
index 0ffe6b13f4..e146fec34b 100644
--- a/public/style.css
+++ b/public/style.css
@@ -1008,6 +1008,11 @@ html[data-ui="legacy"] .char-spec small::before,html[data-ui="legacy"] .char-att
#char-preview-static{width:auto;height:min(72vh,calc(100% - 28px));max-width:100%;max-height:calc(100% - 28px);object-fit:contain;object-position:center bottom;
-webkit-mask-image:radial-gradient(78% 92% at 50% 56%,#000 52%,transparent 96%);
mask-image:radial-gradient(78% 92% at 50% 56%,#000 52%,transparent 96%)}
+#char-preview-placeholder:not([hidden]){display:grid;justify-items:center;align-content:center;gap:var(--s-3);
+ width:min(320px,100%);min-height:min(240px,75%);color:var(--ink-300);font-weight:700;text-align:center}
+#char-preview-placeholder::before{content:"";width:var(--s-8);aspect-ratio:1;
+ background:radial-gradient(circle at 50% 27%,var(--line-2) 21%,transparent 23%),
+ radial-gradient(ellipse 48% 38% at 50% 94%,var(--line-2) 98%,transparent 100%)}
/* O loop de vídeo (640×854, do molde) toma o lugar do canvas: mais alto que largo,
ancorado embaixo como o retrato estático. `.has-video` esconde os dois rivais. */
#char-preview-video{width:auto;max-width:100%;height:min(60vh,calc(100% - 28px));max-height:calc(100% - 28px);aspect-ratio:640/854;object-fit:contain;object-position:center bottom;
diff --git a/scripts/ci/gatilho.mjs b/scripts/ci/gatilho.mjs
index bc311feab9..625faa304d 100644
--- a/scripts/ci/gatilho.mjs
+++ b/scripts/ci/gatilho.mjs
@@ -73,7 +73,12 @@ export const GATILHOS = {
padroes: [
...COMUM,
/^tools\/eval\/(serve|passe-mock|passe-browser|harness|three-node|ak-manga-gpu-check|graffiti-census|graffiti-census-accept|ego-graffiti-census|graffiti-current-ci-check|graffiti-current-accept|graffiti-current-browser-check|graffiti-curation-measure|graffiti-global-accept|graffiti-art-inventory|graffiti-audit|select-inflate|entrada-check|armas-check|selected-weapon-probe|boot-check|perfil-mobile-browser|bots-perf-browser|sertao-livestock-runtime-check|treta-vitrine-browser|lobby-arma-mao-check|mira-alinhada-check|gate-accept|toque-controles-check|vm-autorado-vivo|viewmodel-network-fixture)\.mjs$/,
+ /^tools\/eval\/privacy-(?:browser|choice|explicit-consent|mutations|workflow|storage|worker|transitions|effective|atomic|concurrency)-check\.mjs$/,
+ /^tools\/eval\/lib\/privacy-indexeddb-fixture\.mjs$/,
+ /^src\/pages\/privacidade\.astro$/,
+ /^src\/cf\/worker\.ts$/,
/^tools\/eval\/with-browser-lock\.sh$/,
+ /^tools\/eval\/lib\/serve-eval\.mjs$/,
/^tools\/eval\/(graffiti_census|graffiti_audit|select_inflate|select_inflate_debt)\.json$/,
/^tools\/eval\/assets-check\.mjs$/,
/^tools\/eval\/map-fauna-curated(?:-(?:ci|collector|browser|capture))?\.(?:mjs|json)$/,
diff --git a/scripts/ci/pr_attestation.py b/scripts/ci/pr_attestation.py
index 716a1bddee..e4f8aac5f8 100755
--- a/scripts/ci/pr_attestation.py
+++ b/scripts/ci/pr_attestation.py
@@ -7,10 +7,15 @@
import sys
SCHEMA_VERSION = 1
+CLASSIFY_ATTEMPTS = 3
OID = re.compile(r"[0-9a-f]{40}")
DIGEST = re.compile(r"[0-9a-f]{64}")
+class BaseMovedError(ValueError):
+ """The live base changed after the Git evidence was fetched."""
+
+
def _oid(value, field):
if not isinstance(value, str) or not OID.fullmatch(value):
raise ValueError(f"{field} must be a canonical Git OID")
@@ -143,8 +148,11 @@ def validate_attestation(attestation, pr, expected_repository, pr_number,
# pr["baseRefOid"] does not follow the base branch; the live base is remote_base_oid.
if head_oid != pr.get("headRefOid"):
raise ValueError("attestation does not match the current PR head OID")
+ official_batch = base_ref == "main" and head_ref == "staging" and _repository(pr) == expected_repository
+ if official_batch and head_oid != _oid(remote_staging_oid, "remote staging OID"):
+ raise ValueError("official release batch head is not the live staging OID")
if base_oid != _oid(remote_base_oid, "remote base OID"):
- raise ValueError("attestation base is stale")
+ raise BaseMovedError("attestation base is stale")
if staging_oid != _oid(remote_staging_oid, "remote staging OID"):
raise ValueError("attestation staging-disjoint evidence is stale")
if main_oid != _oid(remote_main_oid, "remote main OID"):
@@ -189,9 +197,6 @@ def validate_attestation(attestation, pr, expected_repository, pr_number,
if attestation.get("hotfix_main_only") is not expected_hotfix_main_only:
raise ValueError("hotfix_main_only is inconsistent with the ancestry facts")
- official_batch = base_ref == "main" and head_ref == "staging" and _repository(pr) == expected_repository
- if official_batch and head_oid != staging_oid:
- raise ValueError("official release batch head is not the attested staging OID")
return attestation
@@ -303,6 +308,22 @@ def emit_attestation(payload, fetch_oids=_fetch_oids, resolve_remote=_remote_oid
return attestation
+def classify_attestation(payload, fetch_oids=_fetch_oids, resolve_remote=_remote_oid,
+ diff_files=_diff_files, diff_digest=_diff_digest,
+ ancestry_facts=_ancestry_facts):
+ evidence = dict(resolve_remote=resolve_remote, diff_files=diff_files,
+ diff_digest=diff_digest, ancestry_facts=ancestry_facts)
+ for attempt in range(1, CLASSIFY_ATTEMPTS + 1):
+ try:
+ attestation = emit_attestation(payload, fetch_oids=fetch_oids, **evidence)
+ return apply_attestation(dict(payload, attestation=attestation), **evidence)
+ except BaseMovedError:
+ if attempt == CLASSIFY_ATTEMPTS:
+ raise
+ print(f"Base moved during attestation. Retrying ({attempt + 1}/{CLASSIFY_ATTEMPTS}).",
+ file=sys.stderr)
+
+
def _fixture():
pr = {
"baseRefName": "main",
@@ -480,6 +501,59 @@ def emit_rejected(name, message, pr, head, files=None):
"release batch head moved", dict(batch, headRefOid="e" * 40), "e" * 40)
emit_rejected("empty release batch is rejected", "release batch diff is empty",
batch, "c" * 40, files=[])
+
+ def classify_race(name, retry_pr, change_on_read, changes, expected_fetches,
+ expected_error=None, change_head=False):
+ nonlocal failures
+ refs = dict(live)
+ fetches = 0
+ reads = 0
+ base_name = retry_pr["baseRefName"]
+
+ def fetch(ref, number):
+ nonlocal fetches, reads
+ fetches += 1
+ reads = 0
+ head = "e" * 40 if change_head and fetches > 1 else retry_pr["headRefOid"]
+ return refs[ref], head, refs["staging"], refs["main"]
+
+ def resolve(ref):
+ nonlocal reads
+ reads += 1
+ if reads == change_on_read and fetches <= changes:
+ refs[base_name] = str(fetches) * 40
+ if retry_pr["headRefName"] == "staging":
+ refs["staging"] = "f" * 40
+ return refs[ref]
+
+ try:
+ result = classify_attestation(
+ {"pr": retry_pr, "expected_repository": "corosolto/client", "pr_number": 42},
+ **dict(emit_kwargs, fetch_oids=fetch, resolve_remote=resolve,
+ diff_files=lambda base, head: [f"docs/{base[0]}.md"]),
+ )
+ except ValueError as error:
+ passed = expected_error is not None and expected_error in str(error)
+ else:
+ passed = (
+ expected_error is None
+ and result["full_diff_verified"] is True
+ and result["files"] == [{"path": f"docs/{refs[base_name][0]}.md"}]
+ )
+ if passed and fetches == expected_fetches:
+ print(f" ok {name}")
+ else:
+ failures += 1
+ print(f" FALHOU {name} ({fetches} fetches, expected {expected_fetches})")
+
+ classify_race("refreshes base changed after fetch", frozen_base, 1, 1, 2)
+ classify_race("refreshes base changed between emit and apply", frozen_base, 4, 1, 2)
+ classify_race("stops after three stale base snapshots", frozen_base, 1, 3, 3,
+ "attestation base is stale")
+ classify_race("rejects moved head on second fetch", frozen_base, 1, 1, 2,
+ "PR head moved", change_head=True)
+ classify_race("rejects moved release head even when main moves", batch, 1, 1, 1,
+ "official release batch head is not the live staging OID")
return 0 if not failures else 1
@@ -493,11 +567,14 @@ def main():
if "--apply" in sys.argv:
print(json.dumps(apply_attestation(payload)))
return 0
+ if "--classify" in sys.argv:
+ print(json.dumps(classify_attestation(payload)))
+ return 0
if "--validate" in sys.argv:
apply_attestation(payload)
print(json.dumps({"valid": True, "head_oid": payload["attestation"]["head_oid"]}))
return 0
- raise ValueError("choose --emit, --apply, --validate, or --selftest")
+ raise ValueError("choose --emit, --apply, --classify, --validate, or --selftest")
if __name__ == "__main__":
diff --git a/scripts/prune-dist.mjs b/scripts/prune-dist.mjs
index 22fd967cb6..da7774766f 100644
--- a/scripts/prune-dist.mjs
+++ b/scripts/prune-dist.mjs
@@ -14,11 +14,12 @@
============================================================================ */
import { existsSync, readFileSync, rmSync, statSync, readdirSync } from 'node:fs';
import path from 'node:path';
+import { fileURLToPath } from 'node:url';
/* Lista fechada e literal. Poda dirigida por padrão (glob, regex) num script que
roda `rmSync(recursive)` é como se apaga a pasta errada — o alvo tem que ser
legível numa olhada. */
-const ALVOS = [
+export const ALVOS = [
// Bancadas locais não fazem parte do site publicado.
'dist/client/dev.html',
'.vercel/output/static/dev.html',
@@ -38,38 +39,47 @@ function tamanho(dir) {
}
const mb = (b) => (b / 1024 / 1024).toFixed(1) + ' MB';
-let total = 0, podados = 0;
-for (const alvo of ALVOS) {
- if (!existsSync(alvo)) continue;
- const st = statSync(alvo);
- const b = st.isDirectory() ? tamanho(alvo) : st.size;
- rmSync(alvo, { recursive: true, force: true });
- total += b; podados++;
- console.log(` poda: ${alvo} (${mb(b)})`);
-}
-if (!podados) {
- console.log(' poda: nada a podar.');
-} else {
- console.log(` poda: ${mb(total)} fora do publicado.`);
+function podaBancadas() {
+ let total = 0, podados = 0;
+ for (const alvo of ALVOS) {
+ if (!existsSync(alvo)) continue;
+ const st = statSync(alvo);
+ const b = st.isDirectory() ? tamanho(alvo) : st.size;
+ rmSync(alvo, { recursive: true, force: true });
+ total += b; podados++;
+ console.log(` poda: ${alvo} (${mb(b)})`);
+ }
+ if (!podados) {
+ console.log(' poda: nada a podar.');
+ } else {
+ console.log(` poda: ${mb(total)} fora do publicado.`);
+ }
}
/* Viewmodel privado: só sai publicado o que está no manifesto (tools/viewmodels/
vm-assets.manifest.json). Build local pelo symlink copiaria também clipes crus e
relatórios do assado. Manifesto ilegível reprova: publicar às cegas não é opção. */
-const VM_DIRS = ['dist/client/private-assets/viewmodels', '.vercel/output/static/private-assets/viewmodels'];
-if (VM_DIRS.some((d) => existsSync(d))) {
- const lista = new Set(JSON.parse(readFileSync('tools/viewmodels/vm-assets.manifest.json', 'utf8')).files.map((f) => f.path));
- if (!lista.size) throw new Error('prune-dist: manifesto do viewmodel vazio');
- for (const raiz of VM_DIRS.filter((d) => existsSync(d))) {
- let fora = 0, bytes = 0;
- const varre = (dir, rel) => {
- for (const e of readdirSync(dir, { withFileTypes: true })) {
- const p = path.join(dir, e.name), r = rel ? `${rel}/${e.name}` : e.name;
- if (e.isDirectory()) { varre(p, r); if (!readdirSync(p).length) rmSync(p, { recursive: true }); }
- else if (!lista.has(r)) { bytes += statSync(p).size; rmSync(p, { force: true }); fora++; }
- }
- };
- varre(raiz, '');
- console.log(` poda: ${raiz} — ${fora} arquivo(s) fora do manifesto (${mb(bytes)})`);
+function podaViewmodels() {
+ const VM_DIRS = ['dist/client/private-assets/viewmodels', '.vercel/output/static/private-assets/viewmodels'];
+ if (VM_DIRS.some((d) => existsSync(d))) {
+ const lista = new Set(JSON.parse(readFileSync('tools/viewmodels/vm-assets.manifest.json', 'utf8')).files.map((f) => f.path));
+ if (!lista.size) throw new Error('prune-dist: manifesto do viewmodel vazio');
+ for (const raiz of VM_DIRS.filter((d) => existsSync(d))) {
+ let fora = 0, bytes = 0;
+ const varre = (dir, rel) => {
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
+ const p = path.join(dir, e.name), r = rel ? `${rel}/${e.name}` : e.name;
+ if (e.isDirectory()) { varre(p, r); if (!readdirSync(p).length) rmSync(p, { recursive: true }); }
+ else if (!lista.has(r)) { bytes += statSync(p).size; rmSync(p, { force: true }); fora++; }
+ }
+ };
+ varre(raiz, '');
+ console.log(` poda: ${raiz} — ${fora} arquivo(s) fora do manifesto (${mb(bytes)})`);
+ }
}
}
+
+if (path.resolve(process.argv[1] || '') === fileURLToPath(import.meta.url)) {
+ podaBancadas();
+ podaViewmodels();
+}
diff --git a/src/cf/worker.ts b/src/cf/worker.ts
index 79b311dfa9..334f090f52 100644
--- a/src/cf/worker.ts
+++ b/src/cf/worker.ts
@@ -6,6 +6,7 @@ import bordaJson from "../../borda.json";
import manifestoVm from '../../tools/viewmodels/vm-assets.manifest.json';
import { compilarHeader, compilarRedirect, headersPara, redirectPara } from '../lib/regras-borda.mjs';
import { PREFIXO_VM, indiceViewmodels, politicaCache, redirectDeHost, ttlBorda, viewmodelDoBucket } from './borda.mjs';
+import { USAGE_EVENT_PATH, USAGE_SCRIPT_PATH } from '../lib/usage-script.mjs';
const REDIRECTS = bordaJson.redirects.map(compilarRedirect);
const HEADERS = bordaJson.headers.map(compilarHeader);
@@ -141,7 +142,8 @@ export default {
async fetch(request: Request, env: Env, ctx: Ctx): Promise {
const url = new URL(request.url);
ponteEnv(env);
- if (request.method !== 'GET' && request.method !== 'HEAD')
+ if (url.pathname === USAGE_SCRIPT_PATH || url.pathname === USAGE_EVENT_PATH ||
+ (request.method !== 'GET' && request.method !== 'HEAD'))
return (prepararResposta(await astro.fetch(request, env, ctx), url.pathname)).saida;
const apex = redirectDeHost(url);
if (apex) return apex;
diff --git a/src/lib/borda/modulos.d.ts b/src/lib/borda/modulos.d.ts
index 48fe077701..3efea8ce22 100644
--- a/src/lib/borda/modulos.d.ts
+++ b/src/lib/borda/modulos.d.ts
@@ -6,5 +6,10 @@ declare module '*.wasm' {
// Tipos mínimos do runtime do Workers usados aqui (o repo não gera `wrangler types`).
declare module 'cloudflare:workers' {
- export const env: { ASSETS: { fetch(url: string | URL): Promise } };
+ export const env: {
+ ASSETS: { fetch(url: string | URL): Promise };
+ USAGE_ORIGIN?: string;
+ USAGE_EVENTS?: { writeDataPoint(point: { blobs: string[] }): void };
+ USAGE_EVENTS_LIMIT?: { limit(input: { key: string }): Promise<{ success: boolean }> };
+ };
}
diff --git a/src/lib/error-provenance.mjs b/src/lib/error-provenance.mjs
index 83e3f7432f..8ec6fa4172 100644
--- a/src/lib/error-provenance.mjs
+++ b/src/lib/error-provenance.mjs
@@ -54,7 +54,7 @@ const AMBIENTE_RE = /^sem_webgl:/i;
const CARTEIRA_RE = /\b(?:window|globalThis|self)\.(?:ethereum|solana|tronWeb|tronLink|phantom|keplr|BinanceChain|coinbaseWalletExtension|web3)\b|\bCannot redefine property:\s*(?:ethereum|solana|web3)\b|\bFailed to connect to MetaMask\b/i;
// Ponte de navegador/WebView/extensão injetada no documento: o filename vira a própria
// página, e same-origin não inocenta. Nome de terceiro, com a caixa dele (BUG-76).
-const PONTE_INJETADA_RE = /\b(?:__gCrWeb[A-Za-z0-9_$]*|__firefox__|DarkReader|__REACT_DEVTOOLS_GLOBAL_HOOK__|__VUE_DEVTOOLS_GLOBAL_HOOK__|webkit\.messageHandlers)\b/;
+const PONTE_INJETADA_RE = /\b(?:__gCrWeb[A-Za-z0-9_$]*|__firefox__|DarkReader|__REACT_DEVTOOLS_GLOBAL_HOOK__|__VUE_DEVTOOLS_GLOBAL_HOOK__|__XL_CALLBACK_xl(?:ReportStatistics|GetAppMetaData)_[0-9a-f]+|addEL_hook|webkit\.messageHandlers)\b/;
const normalizedOrigin = (value, base) => {
if (!value) return null;
diff --git a/src/lib/usage-script.mjs b/src/lib/usage-script.mjs
new file mode 100644
index 0000000000..5ad7837f74
--- /dev/null
+++ b/src/lib/usage-script.mjs
@@ -0,0 +1,81 @@
+export const USAGE_SCRIPT_PATH = '/api/usage-script.js';
+export const USAGE_EVENT_PATH = '/api/usage-event';
+
+const PAGE_VIEW = 'page_view';
+const PAYLOAD = JSON.stringify({ event: PAGE_VIEW });
+const PAYLOAD_BYTES = new TextEncoder().encode(PAYLOAD);
+
+export const usageScript = `(() => {
+ let sent = false;
+ let pending;
+ function update() {
+ if (window.__csPrivacy?.pageAllowed() !== true) {
+ if (pending) {
+ const request = pending;
+ pending = null;
+ request.abort();
+ }
+ return;
+ }
+ if (sent) return;
+ sent = true;
+ const request = new AbortController();
+ pending = request;
+ fetch(${JSON.stringify(USAGE_EVENT_PATH)}, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: ${JSON.stringify(PAYLOAD)},
+ mode: 'same-origin',
+ credentials: 'omit',
+ redirect: 'error',
+ referrer: '',
+ referrerPolicy: 'strict-origin',
+ signal: request.signal,
+ }).catch(() => {}).finally(() => { pending = null; });
+ }
+ window.addEventListener('cs-page-usage-change', update);
+ update();
+})();`;
+
+export function usageBindings(env, url) {
+ if (!['https://corosolto.com.br', 'https://www.corosolto.com.br'].includes(url.origin) ||
+ !env.USAGE_ORIGIN || url.origin !== env.USAGE_ORIGIN ||
+ typeof env.USAGE_EVENTS?.writeDataPoint !== 'function' ||
+ typeof env.USAGE_EVENTS_LIMIT?.limit !== 'function') return;
+ return { events: env.USAGE_EVENTS, rate: env.USAGE_EVENTS_LIMIT };
+}
+
+async function isPageView(body) {
+ if (!body) return false;
+ const reader = body.getReader();
+ let offset = 0;
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) return offset === PAYLOAD_BYTES.length;
+ for (const byte of value) {
+ if (byte !== PAYLOAD_BYTES[offset++]) {
+ void reader.cancel().catch(() => {});
+ return false;
+ }
+ }
+ }
+ } finally {
+ reader.releaseLock();
+ }
+}
+
+export async function recordUsage(request, env) {
+ const url = new URL(request.url);
+ const bindings = usageBindings(env, url);
+ if (!bindings || url.search || request.headers.get('origin') !== url.origin ||
+ request.headers.get('content-type') !== 'application/json') return;
+ try {
+ const budget = await bindings.rate.limit({ key: PAGE_VIEW });
+ if (budget?.success !== true || request.signal.aborted) return;
+ if (await isPageView(request.body) && !request.signal.aborted)
+ bindings.events.writeDataPoint({ blobs: [PAGE_VIEW] });
+ } catch {
+ // A medição opcional devolve a mesma resposta em qualquer resultado.
+ }
+}
diff --git a/src/pages/api/usage-event.ts b/src/pages/api/usage-event.ts
new file mode 100644
index 0000000000..a11e5fca25
--- /dev/null
+++ b/src/pages/api/usage-event.ts
@@ -0,0 +1,10 @@
+import type { APIRoute } from 'astro';
+import { env } from 'cloudflare:workers';
+import { recordUsage } from '../../lib/usage-script.mjs';
+
+export const prerender = false;
+
+export const POST: APIRoute = async ({ request }) => {
+ await recordUsage(request, env);
+ return new Response(null, { status: 204, headers: { 'cache-control': 'no-store' } });
+};
diff --git a/src/pages/api/usage-script.js.ts b/src/pages/api/usage-script.js.ts
new file mode 100644
index 0000000000..4da923bbec
--- /dev/null
+++ b/src/pages/api/usage-script.js.ts
@@ -0,0 +1,17 @@
+import type { APIRoute } from 'astro';
+import { env } from 'cloudflare:workers';
+import { usageBindings, usageScript } from '../../lib/usage-script.mjs';
+
+export const prerender = false;
+
+export const GET: APIRoute = ({ request }) => new Response(
+ usageBindings(env, new URL(request.url)) ? usageScript : null,
+ {
+ headers: {
+ 'cache-control': 'no-store',
+ 'content-type': 'application/javascript; charset=utf-8',
+ 'cross-origin-resource-policy': 'same-origin',
+ 'x-content-type-options': 'nosniff',
+ },
+ },
+);
diff --git a/src/pages/index.astro b/src/pages/index.astro
index 75952d62d7..df94e545c7 100644
--- a/src/pages/index.astro
+++ b/src/pages/index.astro
@@ -319,7 +319,7 @@ window.__GEO_LANG__ = (function () {
if (carteira.test(sourceText + '\n' + String(stack || '') + '\n' + String(mensagem || ''))) return false;
// MESMA redação da `PONTE_INJETADA_RE` de `src/lib/error-provenance.mjs` - se os dois
// lados discordarem, a ponte come cota aqui ou volta a abrir issue lá (BUG-76).
- var injetado = /\b(?:__gCrWeb[A-Za-z0-9_$]*|__firefox__|DarkReader|__REACT_DEVTOOLS_GLOBAL_HOOK__|__VUE_DEVTOOLS_GLOBAL_HOOK__|webkit\.messageHandlers)\b/;
+ var injetado = /\b(?:__gCrWeb[A-Za-z0-9_$]*|__firefox__|DarkReader|__REACT_DEVTOOLS_GLOBAL_HOOK__|__VUE_DEVTOOLS_GLOBAL_HOOK__|__XL_CALLBACK_xl(?:ReportStatistics|GetAppMetaData)_[0-9a-f]+|addEL_hook|webkit\.messageHandlers)\b/;
if (injetado.test(sourceText + '\n' + String(stack || '') + '\n' + String(mensagem || ''))) return false;
// MESMA redação da `AUTOMACAO_RE` de `src/lib/error-provenance.mjs`: se os dois lados
// discordarem, o arnês come cota aqui ou volta a abrir issue lá (BUG-151).
@@ -1383,6 +1383,7 @@ if (document.documentElement.dataset.ui === 'v3') TP_CSS.arquivos.forEach(functi
+
diff --git a/src/pages/privacidade.astro b/src/pages/privacidade.astro
index d50ccb6bcd..d6bc827799 100644
--- a/src/pages/privacidade.astro
+++ b/src/pages/privacidade.astro
@@ -35,6 +35,7 @@ import LegalPage from '../layouts/LegalPage.astro';
O serviço usa cookies e armazenamento local para sessão, retorno do login, identificação do convidado e preferências, como idioma e configurações do jogo. O fluxo de conta usa uma sessão de até 30 dias e um estado temporário de login de até uma hora, sujeitos a expiração e encerramento.
Preferências e progresso local podem permanecer até você limpar o armazenamento do navegador. Bloquear ou apagar esses dados pode encerrar a sessão e remover o progresso de convidado daquele dispositivo. No passo a passo de entrada e em Comunidade → Privacidade, o checkbox de medição controla as medições de uso e desempenho neste navegador. Vem ligado na primeira visita; a newsletter tem uma escolha separada e continua desligada até você pedir. Você pode jogar com a medição desligada e mudar de ideia na mesma tela.
Enquanto a medição está ligada, o identificador persistente de convidado acompanha registros de início e fim de partidas, modo e nickname para medir o uso e o funcionamento do jogo. Esse identificador é pseudônimo e não torna os registros automaticamente anônimos. A base de tratamento dos dados não dispensa consentimento para acesso ao armazenamento do dispositivo quando a lei o exigir; a preferência da newsletter não substitui essa escolha. Desligar a medição interrompe novas medições e remove o marcador de aquisição e a sessão de medição deste navegador, preservando o progresso e a autenticação. O registro de escolha da conta não autoriza automaticamente outro dispositivo.
+
Contagem opcional de páginas: quando disponível e depois de você marcar a opção separada de contagem de páginas em Comunidade → Privacidade, o site envia uma contagem de visualização ao próprio domínio. Um prestador de infraestrutura processa esse registro estatístico em nome do jogo por até três meses. A contagem não inclui identificador, IP, URL da página, referência ou dados de desempenho. Desmarcar a opção de contagem ou desligar a medição interrompe novos envios neste navegador.
Contagem agregada, sem identificador: independentemente dessa escolha, o servidor soma por hora as requisições de páginas HTML do site, com uma categoria de caminho, domínio de origem, origem UTM quando presente e uma classe aproximada do programa que acessou a página. Para estimar navegadores distintos em cada dia, a borda combina temporariamente IP e user-agent com uma chave secreta e a data e envia ao banco somente um registro estatístico. Dias diferentes não são associados nessa estimativa. Não guardamos URL de origem completa, endereço IP, cookie ou identificador persistente nessa contagem.
Funil diário de jogadores: para distinguir visita, início e conclusão de partida, inclusive sem cookies opcionais, o servidor transforma IP e user-agent em um HMAC que muda a cada dia. A tabela estatística recebe somente esses HMACs, a etapa, o estado da escolha de medição, versão, domínio e categorias de campanha. Se houver uma sessão de conta válida, uma tabela operacional privada também registra o identificador da conta, o dia, a etapa e quantas vezes ela ocorreu, permitindo à equipe saber quais contas estão jogando. Quando a medição foi desligada neste navegador, origem, meio e campanha dessa atividade autenticada não são guardados. Nenhuma das duas tabelas recebe IP, user-agent, cookie ou código individual de clique publicitário. O HMAC de dispositivo é uma estimativa: aparelhos com o mesmo IP e user-agent podem ser unidos, e mudança de rede ou programa pode duplicar o mesmo aparelho. Esses registros ficam por até 90 dias e não permitem reconstruir o histórico anterior ao início desta coleta.
Se você ativar a opção de contribuir com dados para treinar bots, o jogo envia amostras de movimentos e ações da partida ligadas ao seu identificador. Essa contribuição é opcional e pode ser desativada nas configurações.
diff --git a/tests/character-preview-media.test.mjs b/tests/character-preview-media.test.mjs
index 9c50218e21..e60cc97915 100644
--- a/tests/character-preview-media.test.mjs
+++ b/tests/character-preview-media.test.mjs
@@ -51,7 +51,7 @@ function fixture({ lang = 'pt', reduced = false, compact = false, narrow = false
show({selection:'char-select',hub:'main-menu',team:'team-select'}[screen]);
node('main-menu').dataset.hubTab='jogar';node('main-menu').dataset.hubNet='sp';
const box = node('box'), video = node('char-preview-video'), hints = node('hints');
- const previewState={scene:{add(){},remove(){}},model:previousModel};
+ const previewState={scene:{add(){},remove(){}},r:{render(){}},model:previousModel};
box.checkVisibility=()=>!compactQuery.matches && (!node('char-select').classList.contains('hidden') || (!node('main-menu').classList.contains('hidden')&&!narrowQuery.matches));
const block = raw.slice(raw.indexOf('const screens ='),raw.indexOf('const $ = id =>'))
+ '\n' + raw.slice(raw.indexOf('const ORDEM_ARMA_EQUIPADA'),raw.indexOf('let pvToken ='))
@@ -304,6 +304,48 @@ test('first team selection opens before it starts the visible static video',()=>
assert.equal(f.node('char-select').classList.contains('hidden'),false);
assert.equal(f.video.src,presentation.video.webm+'?v=fixture');
});
+
+test('selection opens and shows a named silhouette while the first GLB is pending', async () => {
+ let release;
+ const pending = new Promise(resolve => { release = resolve; });
+ const f = fixture({ screen:'team', lean:false, threeD:true, realModel:true, preload:() => pending });
+ f.api.pickTeam('E');
+ const placeholder = f.node('char-preview-placeholder');
+ assert.equal(f.node('char-select').classList.contains('hidden'), false);
+ assert.equal(placeholder.hidden, false);
+ assert.equal(placeholder.textContent, presentation.name);
+ assert.equal(f.node('char-preview').classList.contains('hidden'), true);
+ release();
+ await tick();
+ assert.equal(placeholder.hidden, true);
+ assert.equal(f.node('char-preview').dataset.character, 'barbudo');
+});
+
+test('hover and click share the in-flight GLB and wait for the shared idle clip', async () => {
+ let finishAnimations, finishBody;
+ const animations = new Promise(resolve => { finishAnimations = resolve; });
+ const body = new Promise(resolve => { finishBody = resolve; });
+ const loads = [], weapons = [];
+ const start = glbRaw.indexOf('export async function preloadCharacterAssets(');
+ const end = glbRaw.indexOf('/* Modelo e 11 clipes', start);
+ const preload = vm.runInNewContext('let _clips, _sharedClipsRequest;\n'
+ + glbRaw.slice(start, end).replace('export ', '') + '\npreloadCharacterAssets', {
+ ANIM_DIR:'shared', STATES:['idle'], OPT_STATES:[], GLB_CHARS:new Set(['barbudo']),
+ _base:new Map(), _bodyOrigins:new WeakMap(), _clipsByChar:{},
+ preloadWeapons:async ids=>{weapons.push(ids);}, characterRelease:()=>null, assetUrl:id=>id, revDe:()=>null,
+ animIndex:async()=>({clipes:{}}),
+ loadGLB:url=>{loads.push(url);return url==='shared.glb'?animations:body;},
+ });
+ const hover = preload(['barbudo'], {weapons:[]}), click = preload(['barbudo'], {weapons:['pistol']});
+ await tick();
+ assert.deepEqual(loads, ['shared.glb']);
+ assert.deepEqual(weapons, [['pistol']], 'hover não dispara o preload padrão do catálogo de armas');
+ finishAnimations({animations:[{name:'idle'}]});
+ await tick();
+ assert.deepEqual(loads, ['shared.glb','models/characters/barbudo.glb']);
+ finishBody({scene:{}});
+ await Promise.all([hover,click]);
+});
test('compact media assigns only the visible card and leaves the hidden hero without an image',()=>{
const f=fixture({compact:true});f.api.pvSetChar(base);
assert.equal(f.node('char-preview-static').src,'');
@@ -398,7 +440,7 @@ for(const [name,mutate,probe,options={}] of [
['3D return leaves canvas hidden',replace("$('char-preview')?.classList.remove('hidden');$('char-preview-static')?.classList.add('hidden');",''),f=>{f.api.pvSetChar(base);f.compact(false);f.api.refreshMenuEquipment();assert.equal(f.node('char-preview').classList.contains('hidden'),false);},{compact:true,lean:false,threeD:true}],
['team preview preloads hidden models',replace('const ready = previewUsesStills() ?','const ready = false ?'),async f=>{f.api.ensureTeamPreviews();await tick();assert.equal(f.preloads(),0);},{compact:true,lean:false,teamVisible:true}],
['width change listener removed',replace("pvNarrow.addEventListener?.('change',()=>refreshMenuEquipment());",''),f=>{f.narrow(false);assert.equal(f.homeRefreshes(),1);},{narrow:true,screen:'hub'}],
- ['selection opens after video setup',replace("show('char-select');\n if (firstRow) selectChar(firstChar, firstRow);","if (firstRow) selectChar(firstChar, firstRow);\n show('char-select');"),f=>{f.api.pickTeam('E');assert.equal(f.video.src,presentation.video.webm+'?v=fixture');},{screen:'team'}],
+ ['selection opens after video setup',replace("show('char-select');\n if (firstRow) selectChar(firstChar, firstRow);","if (firstRow) selectChar(firstChar, firstRow);\n show('char-select');"),f=>{f.api.pickTeam('E');assert.equal(f.video.src,presentation.video.webm+'?v=fixture');},{screen:'team'}],
['hidden hero image still loads',replace('if(!previewHeroVisible()){','if(false){'),f=>{f.api.pvSetChar(base);assert.equal(f.node('char-preview-static').src,'');},{compact:true}],
['inactive compact card still loads',replace('if(!active){','if(false){'),f=>{f.api.pvSetChar(base);assert.equal(f.node('hub-character-portrait').src,'');},{compact:true}],
['idle overwrites the selected angle',replace('if (!pv.travado && !pvReducedMotion.matches) {\n if (pv.ctrl)','pv.model.rotation.y += pvDt * 0.9;\n if (!pv.travado && !pvReducedMotion.matches) {\n if (pv.ctrl)'),f=>{const model={rotation:{y:0}};f.api.preview({model,r:{render(){}}});f.api.frame(0.05);assert.equal(model.rotation.y,0);}],
@@ -631,11 +673,16 @@ test('causal mutant rejects redrawing an unchanged reduced-motion frame',()=>{
f.api.preview({model:{rotation:{y:0}},r:{render(){renders++;}}});f.api.frame(.05);f.api.frame(.05);
assert.throws(()=>assert.equal(renders,1),{name:'AssertionError'});
});
-test('new model invalidates an already rendered reduced-motion preview',async()=>{
- const f=fixture({reduced:true,lean:false,threeD:true,realModel:true});let renders=0;
- const p=f.previewDescriptor();p.r={render(){renders++;}};f.api.preview(p);f.api.frame(.05);
- f.api.pvSetChar(cyborg);await tick();assert.equal(f.renderDirty(),true);
- f.api.frame(.05);f.api.frame(.05);assert.equal(renders,2);
+test('the new 3D model is painted while the canvas is still hidden',async()=>{
+ const f=fixture({reduced:true,lean:false,threeD:true,realModel:true}),canvas=f.node('char-preview');
+ const samples=[];
+ const p=f.previewDescriptor();p.r={render(){samples.push({hidden:canvas.classList.contains('hidden'),model:p.model});}};f.api.preview(p);
+ f.api.pvSetChar(cyborg);await tick();
+ assert.deepEqual(samples,[{hidden:true,model:p.model}]);
+ assert.ok(p.model);
+ assert.equal(canvas.classList.contains('hidden'),false);
+ f.api.frame(.05);
+ assert.equal(samples.length,1);
});
function previewInput(mutate=value=>value){
@@ -668,10 +715,11 @@ test('causal mutant rejects checkVisibility-only team thumbnails on older browse
f.api.ensureTeamPreviews();await tick();assert.throws(()=>assert.equal(f.preloads(),2),{name:'AssertionError'});
});
-test('causal mutant rejects mounting a new model without invalidating its frame',async()=>{
- const f=fixture({reduced:true,lean:false,threeD:true,realModel:true,mutate:replace(' p.renderDirty = true;\n','')});
- const p=f.previewDescriptor();p.r={render(){}};f.api.preview(p);f.api.frame(.05);
- f.api.pvSetChar(cyborg);await tick();assert.throws(()=>assert.equal(f.renderDirty(),true),{name:'AssertionError'});
+test('causal mutant rejects exposing the canvas without painting the new model',async()=>{
+ const f=fixture({reduced:true,lean:false,threeD:true,realModel:true,mutate:replace(' p.r.render(p.scene, p.cam);\n','')});
+ let renders=0;
+ const p=f.previewDescriptor();p.r={render(){renders++;}};f.api.preview(p);
+ f.api.pvSetChar(cyborg);await tick();assert.throws(()=>assert.equal(renders,1),{name:'AssertionError'});
});
async function emoteFixture({reduced=false,mutate=value=>value,mutateListener=value=>value}={}){
diff --git a/tests/eval-suites.test.mjs b/tests/eval-suites.test.mjs
index 4d2ef43069..6a645580f2 100644
--- a/tests/eval-suites.test.mjs
+++ b/tests/eval-suites.test.mjs
@@ -7,6 +7,7 @@ import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
import { SUITES, passosDaSuite } from '../tools/eval/suites.mjs';
import { selecionarPorArquivos, validarMapaWorkflows } from '../tools/eval/selecao-pre-push.mjs';
+import { problemaDoNode } from '../tools/eval/lib/node-minimo.mjs';
/* Baseline congelado das duas linhas que existiam antes do manifesto, legível em
* tests/fixtures/eval-suites-baseline.json e preso ao MESMO sha256 de sempre (a lista não
@@ -481,3 +482,33 @@ test('mapa de workflows rejeita passo fantasma fora de fast e deploy', () => {
/passo fantasma/,
);
});
+
+const binarioAntigo = '/usr/local/bin/node';
+
+test('Node antigo é reprovado com versão, binário e correção', () => {
+ const mensagem = problemaDoNode({ versao: '16.13.0', temFetch: false, binario: binarioAntigo });
+ assert.match(mensagem, /Node 16\.13\.0 \(\/usr\/local\/bin\/node\) é anterior ao 20/);
+ assert.match(mensagem, /\/opt\/homebrew\/bin\/node/);
+});
+
+test('Node 18 com fetch experimental continua reprovado', () => {
+ assert.match(problemaDoNode({ versao: '18.20.0', temFetch: true, binario: binarioAntigo }), /anterior ao 20/);
+});
+
+test('Node novo sem fetch global é reprovado', () => {
+ assert.match(problemaDoNode({ versao: '22.11.0', temFetch: false, binario: binarioAntigo }), /não tem fetch global/);
+});
+
+test('Node novo com fetch passa', () => {
+ assert.equal(problemaDoNode({ versao: '22.11.0', temFetch: true, binario: binarioAntigo }), null);
+ assert.equal(problemaDoNode({ versao: '20.0.0', temFetch: true, binario: binarioAntigo }), null);
+});
+
+test('runner e prod-coherence importam a guarda de Node antes de qualquer outro módulo', () => {
+ for (const arquivo of ['tools/eval/runner.mjs', 'tools/eval/prod-coherence.mjs']) {
+ const primeiro = readFileSync(new URL(`../${arquivo}`, import.meta.url), 'utf8').match(/^import .*$/m)?.[0];
+ assert.equal(primeiro, "import './lib/node-minimo.mjs';", arquivo);
+ }
+});
+
+import "./prepush-metal-platform.test.mjs";
diff --git a/tests/fixtures/serve-eval/filho-dono.mjs b/tests/fixtures/serve-eval/filho-dono.mjs
new file mode 100644
index 0000000000..87e512192b
--- /dev/null
+++ b/tests/fixtures/serve-eval/filho-dono.mjs
@@ -0,0 +1,4 @@
+import http from 'node:http';
+const porta = Number(process.argv[2]);
+const ruido = 'x'.repeat(Number(process.env.FILHO_RUIDO || 0));
+http.createServer((_, res) => res.end('dono')).listen(porta, '127.0.0.1', () => process.stdout.write(`eval server -> http://localhost:${porta}\n${ruido}\n`));
diff --git a/tests/fixtures/serve-eval/filho-sem-porta.mjs b/tests/fixtures/serve-eval/filho-sem-porta.mjs
new file mode 100644
index 0000000000..4467554ebf
--- /dev/null
+++ b/tests/fixtures/serve-eval/filho-sem-porta.mjs
@@ -0,0 +1,2 @@
+// Filho que nunca liga a porta nem anuncia `eval server ->`: quem responde é o intruso do teste.
+setTimeout(() => process.exit(1), Number(process.env.FILHO_VIVE_MS || 1500));
diff --git a/tests/fp-maos.test.mjs b/tests/fp-maos.test.mjs
new file mode 100644
index 0000000000..64e9c30c60
--- /dev/null
+++ b/tests/fp-maos.test.mjs
@@ -0,0 +1,61 @@
+/* #1119: personagem fora do rig compartilhado de mãos cai no só-arma mesmo com ?hands=1. */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { SEM_MAOS_FP, maosFpSuportadas } from '../public/js/data/fp-maos.js';
+
+const ler = (f) => readFileSync(new URL(`../${f}`, import.meta.url), 'utf8');
+
+test('o Lobisomem fica fora das mãos de primeira pessoa', () => {
+ assert.ok(SEM_MAOS_FP.includes('lobisomem'));
+ assert.equal(maosFpSuportadas('lobisomem'), false);
+ assert.equal(maosFpSuportadas('mariabonita'), true);
+});
+
+test('todo id da lista existe no elenco', () => {
+ const elenco = ler('public/js/characters.js');
+ for (const id of SEM_MAOS_FP) assert.match(elenco, new RegExp(`\\bid: '${id}'`), id);
+});
+
+test('hands=1 exibe as mãos legadas só para um personagem compatível', async () => {
+ const { Game, THREE } = await import('../tools/eval/harness.mjs');
+ const search = location.search;
+ location.search = '?hands=1';
+ try {
+ for (const [playerCharId, handsVisible] of [['lobisomem', false], ['mariabonita', true]]) {
+ const player = { playerCharId, playerWeaponSkins: {}, camera: new THREE.PerspectiveCamera() };
+ const vm = Game.prototype._buildViewModels.call(player, { fallback: true });
+ assert.equal(vm.pistol.getObjectByName('handR').visible, handsVisible, playerCharId);
+ }
+ } finally {
+ location.search = search;
+ }
+});
+
+test('o rig dedicado entra apenas no personagem compatível com hands=1', async () => {
+ await import('../tools/eval/lib/glbchars-node.mjs');
+ const { Game, THREE } = await import('../tools/eval/harness.mjs');
+ const { preloadFPArms } = await import('../public/js/fparms.js');
+ const { preloadCharacterAssets } = await import('../public/js/glbchars.js');
+ await Promise.all([preloadFPArms(), preloadCharacterAssets([], { weapons: ['pistol'] })]);
+
+ const search = location.search;
+ try {
+ for (const [query, playerCharId, hasRig] of [
+ ['?hands=1', 'mariabonita', true],
+ ['?hands=1', 'lobisomem', false],
+ ['', 'mariabonita', false],
+ ['', 'lobisomem', false],
+ ]) {
+ location.search = query;
+ const player = { playerCharId, playerFaction: 'E', playerWeaponSkins: {}, camera: new THREE.PerspectiveCamera() };
+ const vm = Game.prototype._buildViewModels.call(player, { fallback: true });
+ const label = `${playerCharId} ${query}`;
+ assert.equal(Boolean(vm.arms), hasRig, label);
+ if (hasRig) assert.equal(vm.arms.group.parent, vm.root, label);
+ assert.equal(vm.pistol.getObjectByName('handR').visible, false, label);
+ }
+ } finally {
+ location.search = search;
+ }
+});
diff --git a/tests/hd-kit-diagnostic.test.mjs b/tests/hd-kit-diagnostic.test.mjs
new file mode 100644
index 0000000000..3f20027a8f
--- /dev/null
+++ b/tests/hd-kit-diagnostic.test.mjs
@@ -0,0 +1,49 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { test } from 'node:test';
+import vm from 'node:vm';
+
+const source = readFileSync(new URL('../public/js/main.js', import.meta.url), 'utf8');
+const start = source.indexOf(' const kitHD = {');
+const end = source.indexOf(' /* RÉGUA:launch-race nascimento fim */', start);
+assert.ok(start >= 0 && end > start, 'HD loader must exist in main.js');
+const loader = source.slice(start, end).replace('import(kitHD[0])', 'importa(kitHD[0])');
+assert.notEqual(loader, source.slice(start, end), 'test must substitute the real dynamic import');
+
+async function run({ importa, search = '?hd=1', map = 'velho_oeste', active = true }) {
+ const game = { _mapId: map, scene: {}, renderer: {} };
+ const errors = [];
+ const window = { __game: active ? game : {} };
+ vm.runInNewContext(loader, {
+ game, window, location: { search }, URLSearchParams, importa,
+ console: { error: (...args) => errors.push(args) },
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+ return { errors, window, game };
+}
+
+for (const phase of ['import', 'initialization']) {
+ test(`HD ${phase} failure reports its URL and original error`, async () => {
+ const error = new Error(`${phase} failed`);
+ const importa = phase === 'import'
+ ? () => Promise.reject(error)
+ : () => Promise.resolve({ aplicaSertaoHD() { throw error; } });
+ const result = await run({ importa });
+ assert.equal(result.errors.length, 1);
+ assert.ok(result.errors[0].includes('./map_sertao_hd.js'));
+ assert.ok(result.errors[0].includes(error));
+ });
+}
+
+test('HD loader applies only to the active game when enabled', async () => {
+ let calls = 0;
+ const kit = {};
+ const importa = () => { calls++; return Promise.resolve({ aplicaSertaoHD: () => kit }); };
+ const enabled = await run({ importa });
+ assert.equal(enabled.window.__kitHD, kit);
+ await run({ importa, search: '' });
+ await run({ importa, map: 'lajes' });
+ const stale = await run({ importa, active: false });
+ assert.equal(stale.window.__kitHD, undefined);
+ assert.equal(calls, 2);
+});
diff --git a/tests/javaporcos-wave-schedule.test.mjs b/tests/javaporcos-wave-schedule.test.mjs
new file mode 100644
index 0000000000..fa924584a9
--- /dev/null
+++ b/tests/javaporcos-wave-schedule.test.mjs
@@ -0,0 +1,32 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { WAVE_COUNTS, PREP_SECONDS, COMBAT_SECONDS } from '../public/js/javaporcos_ondas.js';
+await import('../tools/eval/three-node.mjs');
+const { criarHorda } = await import('../public/js/mode_javaporcos.js');
+import { ONDAS_SOLO, regrasDaInvasao, resumoDoFimJavaporcos } from '../public/js/javaporcos_partida.js';
+import { sincronizarOpcoesJavaporcos } from '../public/js/javaporcos_opcoes.js';
+import { apresentarJavaporcos } from '../public/js/javaporcos_intro.js';
+
+test('programação determina regras, fábrica e textos apresentados', async () => {
+ const count = WAVE_COUNTS.length;
+ assert.equal(ONDAS_SOLO, count);
+ assert.equal(regrasDaInvasao().ondas, count);
+ assert.equal(criarHorda().maxWaves, count);
+ assert.equal(resumoDoFimJavaporcos(), `${count} ONDAS · ~${Math.round(count * (PREP_SECONDS + COMBAT_SECONDS) / 60)} MIN · SOBREVIVA À ÚLTIMA`);
+ const art = { style: {} }, button = { addEventListener() {} };
+ const panel = { dataset: {}, style: {}, addEventListener() {}, querySelectorAll: () => [] };
+ const dialog = { setAttribute() {}, querySelector: s => s === '.ji-art' ? art : button, addEventListener() {}, showModal() { this.open = true; }, close() {}, remove() {} };
+ globalThis.document = { createElement: tag => tag === 'dialog' ? dialog : panel, body: { append() {} }, hidden: false };
+ globalThis.matchMedia = () => ({ matches: true });
+ const host = { querySelector: () => null, append() {} };
+ sincronizarOpcoesJavaporcos(host, true, {}, () => {});
+ assert.match(panel.innerHTML, new RegExp(``));
+ const controller = new AbortController();
+ const intro = apresentarJavaporcos(controller.signal);
+ try {
+ assert.match(dialog.innerHTML, new RegExp(`São ${count} ondas\\.`));
+ } finally {
+ controller.abort();
+ await intro;
+ }
+});
diff --git a/tests/prepush-metal-platform.test.mjs b/tests/prepush-metal-platform.test.mjs
new file mode 100644
index 0000000000..1b8fd03619
--- /dev/null
+++ b/tests/prepush-metal-platform.test.mjs
@@ -0,0 +1,46 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { planejarPrepushPlataforma } from '../tools/eval/selecao-pre-push.mjs';
+
+const metal = 'eval:operacao-flavio:browser-gate';
+const sha = 'a'.repeat(40);
+const refs = `refs/heads/work ${sha} refs/heads/work ${'0'.repeat(40)}\n`;
+
+test('Linux excludes only the Metal gate and binds its notice to the pushed head', () => {
+ const steps = ['syntax', metal, 'eval:ui-v3:lobby-flavio:gate'];
+ const plan = planejarPrepushPlataforma(steps, 'linux', refs);
+ assert.deepEqual(plan.passos, ['syntax', 'eval:ui-v3:lobby-flavio:gate']);
+ assert.deepEqual(plan.avisos, [`metal: pendente no Mac @ ${sha}`]);
+ assert.deepEqual(steps, ['syntax', metal, 'eval:ui-v3:lobby-flavio:gate']);
+});
+
+test('other platforms and selections without the Metal gate remain unchanged', () => {
+ assert.deepEqual(planejarPrepushPlataforma(['syntax', metal], 'darwin', refs), { passos: ['syntax', metal], avisos: [] });
+ assert.deepEqual(planejarPrepushPlataforma(['syntax'], 'linux', refs), { passos: ['syntax'], avisos: [] });
+});
+
+test('Linux cannot defer Metal without exactly one verifiable pushed head', () => {
+ for (const bad of ['', 'bad', refs + `refs/heads/other ${'b'.repeat(40)} refs/heads/other ${'0'.repeat(40)}\n`]) {
+ assert.throws(() => planejarPrepushPlataforma([metal], 'linux', bad));
+ }
+});
+
+test('Linux hook executes every selected step except Metal', async () => {
+ if (process.platform !== 'linux') return;
+ const { mkdtempSync, writeFileSync, readFileSync, rmSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ const { join, delimiter } = await import('node:path');
+ const { spawnSync } = await import('node:child_process');
+ const { SUITES } = await import('../tools/eval/suites.mjs');
+ const dir = mkdtempSync(join(tmpdir(), 'prepush-metal-'));
+ try {
+ writeFileSync(join(dir, 'npm'), '#!/bin/sh\nprintf "%s\\n" "$3" >> "$TEST_STEPS"\n', { mode: 0o755 });
+ const out = join(dir, 'steps');
+ const result = spawnSync(process.execPath, ['tools/eval/selecao-pre-push.mjs', '--files=tools/eval/fixtures/surface-floor-uv.mjs'], {
+ encoding: 'utf8', env: { ...process.env, PATH: dir + delimiter + process.env.PATH, PREPUSH_REFS: refs, TEST_STEPS: out },
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.match(result.stdout, new RegExp(`metal: pendente no Mac @ ${sha}`));
+ assert.deepEqual(readFileSync(out, 'utf8').trim().split('\n'), SUITES.deploy.filter(step => step !== metal));
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+});
diff --git a/tests/roster-sessao.test.mjs b/tests/roster-sessao.test.mjs
new file mode 100644
index 0000000000..1bf8e6a7c7
--- /dev/null
+++ b/tests/roster-sessao.test.mjs
@@ -0,0 +1,24 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import vm from 'node:vm';
+
+/* #1383: a queda do socket no meio do preload zera `mpSessao`; o roster tem que sair da sessão
+ que o lançamento capturou, não do global. */
+const main = fs.readFileSync(new URL('../public/js/main.js', import.meta.url), 'utf8');
+const ini = main.indexOf('function rosterDoServidor(');
+const fim = main.indexOf('\n}\n', ini);
+assert.ok(ini > 0 && fim > ini, 'rosterDoServidor não encontrado no main.js');
+
+test('roster usa a sessão capturada mesmo depois da queda', () => {
+ const ctx = vm.createContext({ mpSessao: null, CHARACTERS: [{ id: 'a' }, { id: 'b' }] });
+ vm.runInContext(main.slice(ini, fim + 2), ctx);
+ const sessao = { net: { yourEnt: 1, meta: { roster: [
+ { id: 1, team: 'E', char: 'a' }, { id: 2, team: 'E', char: 'b' }, { id: 3, team: 'B', char: 'a' },
+ ] } } };
+ const chamada = main.match(/\?\s*rosterDoServidor\(([^)]*)\)/)[1];
+ assert.equal(chamada.split(',')[0].trim(), 'sessao', '_startGame passa a sessão capturada');
+ const r = vm.runInContext('rosterDoServidor', ctx)(sessao, 'E', 'a');
+ assert.deepEqual(r.allyDefs.map((d) => d.id), ['b']);
+ assert.deepEqual(r.enemyDefs.map((d) => d.id), ['a']);
+});
diff --git a/tests/serve-eval-posse.test.mjs b/tests/serve-eval-posse.test.mjs
new file mode 100644
index 0000000000..adceb38e9d
--- /dev/null
+++ b/tests/serve-eval-posse.test.mjs
@@ -0,0 +1,42 @@
+// subirServe só aceita a resposta HTTP depois que o PRÓPRIO filho anuncia que ligou a porta.
+import assert from 'node:assert/strict';
+import http from 'node:http';
+import net from 'node:net';
+import test from 'node:test';
+import { fileURLToPath } from 'node:url';
+import { subirServe } from '../tools/eval/lib/serve-eval.mjs';
+
+const fixture = (nome) => fileURLToPath(new URL(`./fixtures/serve-eval/${nome}`, import.meta.url));
+const portaLivre = () => new Promise((resolve) => {
+ const s = net.createServer();
+ s.listen(0, '127.0.0.1', () => { const { port } = s.address(); s.close(() => resolve(port)); });
+});
+
+test('intruso que pega a porta entre a sonda e o spawn não vira servidor pronto', async () => {
+ const porta = await portaLivre();
+ let atendidas = 0;
+ const intruso = http.createServer((_, res) => { atendidas++; res.end('intruso'); });
+ // Tenta ligar a cada 2 ms: entra assim que a sonda do subirServe solta a porta.
+ const insiste = setInterval(() => { if (!intruso.listening) intruso.listen(porta, '127.0.0.1').once('error', () => {}); }, 2);
+ try {
+ await assert.rejects(
+ subirServe(porta, { script: fixture('filho-sem-porta.mjs') }),
+ /filho-sem-porta\.mjs saiu com código 1/,
+ );
+ assert.ok(atendidas > 0, 'o intruso precisa ter respondido ao subirServe para o teste medir a corrida');
+ } finally {
+ clearInterval(insiste);
+ await new Promise((resolve) => (intruso.listening ? intruso.close(resolve) : resolve()));
+ }
+});
+
+test('filho que liga a porta e anuncia é aceito, mesmo com saída longa colada no anúncio', async () => {
+ const porta = await portaLivre();
+ const srv = await subirServe(porta, { script: fixture('filho-dono.mjs'), env: { ...process.env, FILHO_RUIDO: '400' } });
+ try {
+ assert.equal(await (await fetch(`${srv.base}/`)).text(), 'dono');
+ } finally {
+ srv.kill();
+ await srv.saiu;
+ }
+});
diff --git a/tests/smoke/web-assets.spec.js b/tests/smoke/web-assets.spec.js
index 45e069d66f..68a40b02cf 100644
--- a/tests/smoke/web-assets.spec.js
+++ b/tests/smoke/web-assets.spec.js
@@ -12,7 +12,7 @@ test.afterEach(async ({ page }, testInfo) => {
});
});
-test('preload 3D real do elenco termina e renderiza GLB na vitrine', async ({ page }, testInfo) => {
+test('preview 3D renderiza o GLB do personagem escolhido', async ({ page }, testInfo) => {
test.slow();
const base = process.env.BASE_URL || 'http://127.0.0.1:4321';
const t0 = Date.now();
@@ -30,13 +30,20 @@ test('preload 3D real do elenco termina e renderiza GLB na vitrine', async ({ pa
await expect(page.locator('#team-select')).toBeVisible({ timeout: 30_000 });
await page.locator('#btn-team-e').click();
- // A seleção só abre depois que o preload real do elenco termina.
- await expect(page.locator('#char-select')).toBeVisible({ timeout: 360_000 });
+ await expect(page.locator('#char-select')).toBeVisible();
+
+ // A lista abre antes da carga. A marca pertence ao canvas já renderizado, não ao placeholder.
+ const preview = page.locator('#char-preview[data-glb="1"]');
+ await expect(preview).toBeVisible({ timeout: 60_000 });
+ const punk = page.locator('#char-list .char-row[title="Punk"]');
+ await expect(punk).toHaveAttribute('aria-selected', 'false');
+ await punk.click();
+ await expect(preview).toHaveAttribute('data-character', 'punk', { timeout: 60_000 });
+ await expect(preview).toBeVisible();
const ficha = await page.evaluate(() => ({
rows: document.querySelectorAll('#char-list .char-row').length,
- // Somente o GLB real marca data-glb; o fallback procedural não marca.
- preview_glb: document.getElementById('char-preview')?.dataset.glb === '1',
+ preview_character: document.getElementById('char-preview')?.dataset.character,
info_name: document.getElementById('char-info-name')?.textContent || '',
}));
await testInfo.attach('asset-check.json', {
@@ -46,11 +53,10 @@ test('preload 3D real do elenco termina e renderiza GLB na vitrine', async ({ pa
console.log('ASSETS', JSON.stringify(ficha));
expect(ficha.rows).toBeGreaterThan(0);
- expect(ficha.preview_glb).toBe(true);
- expect(ficha.info_name.length).toBeGreaterThan(0);
+ expect(ficha.info_name).toBe('Punk');
await expect(page.locator('#crash-overlay')).toBeHidden();
- // partida também abre com o caminho real (já com elenco/modelos batidos em cache)
+ // Confirmar o personagem também precisa abrir a partida com o caminho real de assets.
await page.locator('#char-confirm').click();
await expect(page.locator('#hud')).toBeVisible({ timeout: 180_000 });
});
diff --git a/tests/treta-manifest-readiness.test.mjs b/tests/treta-manifest-readiness.test.mjs
index 0dd851fcc9..ece2514dd1 100644
--- a/tests/treta-manifest-readiness.test.mjs
+++ b/tests/treta-manifest-readiness.test.mjs
@@ -13,8 +13,8 @@ const model = '/models/skins/lula-cyborg.glb';
const manifest = { skins: { 'lula-cyborg': { approved: true, character: 'barbudo', model } } };
const equipped = { authenticated: true, accountId: 'fixture', inventory: [{ skin_id: 'lula-cyborg', equipped: true }], catalog: [{ id: 'lula-cyborg', slot: 'character', available: true, character_id: 'barbudo', model_path: model }] };
-function fixture({ inventory = equipped, accountReady = Promise.resolve(), readInventory, timeoutAPI = true, weaponSkins = [{ id: 'ouro-ak', name: 'AK Ouro', slot: 'weapon', weapon: 'ak', model: '/models/weapons/ak.glb', ready: true }], mutate = value => value } = {}) {
- const media = deferred(), controllers = [], deadlines = [], nodes = new Map(), listeners = new Map(), timers=new Map(), fetches=[];
+function fixture({ inventory = equipped, accountReady = Promise.resolve(), readInventory, socialApi, timeoutAPI = true, weaponSkins = [{ id: 'ouro-ak', name: 'AK Ouro', slot: 'weapon', weapon: 'ak', model: '/models/weapons/ak.glb', ready: true }], mutate = value => value } = {}) {
+ const media = deferred(), controllers = [], deadlines = [], nodes = new Map(), listeners = new Map(), timers=new Map(), fetches=[], events=[];
let timerID=0;
const node = id => ({ id, open: false, close(){this.open=false;}, textContent: '', dataset: {}, classList: { add: noop, remove: noop, contains: () => false }, setAttribute: noop, append: noop, replaceChildren: noop, addEventListener: noop });
const context = vm.createContext({
@@ -23,7 +23,7 @@ function fixture({ inventory = equipped, accountReady = Promise.resolve(), readI
getElementById: id => { if (!nodes.has(id)) nodes.set(id, node(id)); return nodes.get(id); },
createElement: () => node(''), querySelectorAll: () => [], querySelector: () => null,
addEventListener: (name, callback) => { if (!listeners.has(name)) listeners.set(name, []); listeners.get(name).push(callback); },
- dispatchEvent: event => { for (const callback of listeners.get(event.type) || []) callback(event); }, documentElement: { dataset: { ui: 'v3' } },
+ dispatchEvent: event => { events.push(event); for (const callback of listeners.get(event.type) || []) callback(event); }, documentElement: { dataset: { ui: 'v3' } },
},
window: {}, location: { search: '', href: 'https://fixture.invalid/', origin: 'https://fixture.invalid' },
localStorage: { getItem: () => null, setItem: noop }, sessionStorage: { getItem: () => 'recorded', setItem: noop },
@@ -36,7 +36,7 @@ function fixture({ inventory = equipped, accountReady = Promise.resolve(), readI
TRETA_DEFAULT_REWARDS: {}, TRETA_COIN_ART: { poster: '/fixture.webp' },
initTretaRewards: noop, updateTretaRewards: noop, ligarCompartilhar: noop,
estadoDaUrl: () => null, loadAccount: async () => ({ authenticated: true }),
- socialApi: readInventory || (async () => { await accountReady; return inventory; }), assetUrl: p => '/' + p,
+ socialApi: socialApi || readInventory || (async () => { await accountReady; return inventory; }), assetUrl: p => '/' + p,
fetch: async (url, options) => {
assert.equal(url, '/models/skins/manifest.json');
fetches.push({url,signal:options?.signal});
@@ -44,11 +44,119 @@ function fixture({ inventory = equipped, accountReady = Promise.resolve(), readI
return media.promise;
},
});
- const api = new vm.Script(mutate(source) + '\ndraw=()=>{};initProposals=()=>{};updateBuy=()=>{};({initTretaStore,equippedTretaSkin,desequiparTretaSkin,tretaSkinPresentation,tretaWeaponPresentation,buyForTest:async skin=>{selected=skin;previewReady=true;visual=async()=>({dispose(){}});openDialog=()=>{};await buy();}});').runInContext(context);
+ const api = new vm.Script(mutate(source) + '\ndraw=()=>{};initProposals=()=>{};updateBuy=()=>{};({initTretaStore,refresh,equiparTretaSkin,equippedTretaWeaponSkin,desequiparTretaSkin,equippedTretaSkin,tretaSkinPresentation,tretaWeaponPresentation,buyForTest:async skin=>{selected=skin;previewReady=true;visual=async()=>({dispose(){}});openDialog=()=>{};await buy();}});').runInContext(context);
let settled = false;
const ready = api.initTretaStore().then(() => { settled = true; });
- return { api, ready, media, deadlines, controllers, timers, fetches, settled: () => settled, emit: type => context.document.dispatchEvent({ type }), accountChanged: detail => context.document.dispatchEvent({ type: 'cs-account-change', detail }) };
+ return { api, ready, media, deadlines, controllers, timers, fetches, events, settled: () => settled, emit: type => context.document.dispatchEvent({ type }), accountChanged: detail => context.document.dispatchEvent({ type: 'cs-account-change', detail }) };
}
+const raceCharacter = { id: 'lula-cyborg', name: 'Barbudo Cyborg', slot: 'character', character: 'barbudo' };
+const raceSkins = [
+ { id: 'ouro-ak', name: 'AK Ouro', slot: 'weapon', weapon: 'ak', model: '/models/weapons/ak.glb', ready: true },
+ { id: 'prata-ak', name: 'AK Prata', slot: 'weapon', weapon: 'ak', model: '/models/weapons/ak-prata.glb', ready: true },
+];
+const raceCatalog = [
+ { id: raceCharacter.id, slot: 'character', available: true, character_id: raceCharacter.character, model_path: model },
+ ...raceSkins.map(s => ({ id: s.id, slot: 'weapon', available: true, weapon_id: s.weapon, model_path: s.model })),
+];
+const raceState = accountId => ({ authenticated: true, accountId, inventory: [raceCharacter, ...raceSkins].map(s => ({ skin_id: s.id, equipped: false })), catalog: raceCatalog });
+const raceStateWith = (accountId, ...skinIds) => ({ ...raceState(accountId), inventory: [raceCharacter, ...raceSkins].map(s => ({ skin_id: s.id, equipped: skinIds.includes(s.id) })) });
+async function equipmentFixture() {
+ let serverState = raceState('fixture');
+ const writes = [];
+ const socialApi = async (_path, body) => {
+ if (!body || body.action === 'refresh') return serverState;
+ if (body.action !== 'equip' && body.action !== 'unequip') return serverState;
+ const operation = deferred();
+ writes.push({ body, operation });
+ const next = await operation.promise;
+ if (next?.accountId === serverState.accountId) serverState = next;
+ return next;
+ };
+ const f = fixture({ inventory: serverState, weaponSkins: raceSkins, socialApi });
+ f.media.resolve({ ok: true, json: async () => ({ skins: { 'lula-cyborg': { approved: true, character: 'barbudo', model } } }) });
+ await f.ready;
+ return { f, writes, setServerState: value => { serverState = value; }, state: raceStateWith };
+}
+test('equipment intents serialize server writes and refresh preserves the latest choice', async () => {
+ const h = await equipmentFixture();
+ const first = h.f.api.equiparTretaSkin('ouro-ak');
+ await tick();
+ assert.equal(h.writes.length, 1);
+ const second = h.f.api.equiparTretaSkin('prata-ak');
+ await tick();
+ assert.equal(h.writes.length, 1);
+ assert.equal(h.writes[0].body.skinId, 'ouro-ak');
+ h.writes[0].operation.resolve(h.state('fixture', 'ouro-ak'));
+ assert.equal(await first, true);
+ await tick();
+ assert.equal(h.writes.length, 2);
+ assert.equal(h.writes[1].body.skinId, 'prata-ak');
+ h.writes[1].operation.resolve(h.state('fixture', 'prata-ak'));
+ assert.equal(await second, true);
+ assert.equal(h.f.api.equippedTretaWeaponSkin('ak'), 'prata-ak');
+ await h.f.api.refresh();
+ assert.equal(h.f.api.equippedTretaWeaponSkin('ak'), 'prata-ak');
+});
+test('confirmed snapshots and events survive intents from different slots', async () => {
+ const h = await equipmentFixture();
+ const character = h.f.api.equiparTretaSkin('lula-cyborg');
+ await tick();
+ assert.equal(h.writes[0].body.skinId, 'lula-cyborg');
+ const weapon = h.f.api.equiparTretaSkin('ouro-ak');
+ await tick();
+ assert.equal(h.writes.length, 1, 'weapon waits for the character write');
+ h.writes[0].operation.resolve(h.state('fixture', 'lula-cyborg'));
+ assert.equal(await character, true);
+ assert.ok(h.f.events.some(event => event.type === 'cs-skin-equipped' && event.detail?.skinId === 'lula-cyborg'));
+ await tick();
+ h.writes[1].operation.resolve(h.state('fixture', 'lula-cyborg', 'ouro-ak'));
+ assert.equal(await weapon, true);
+ assert.equal(h.f.api.equippedTretaSkin('barbudo'), 'lula-cyborg');
+ assert.equal(h.f.api.equippedTretaWeaponSkin('ak'), 'ouro-ak');
+});
+
+
+test('a confirmed equip survives a failed follow-up unequip', async () => {
+ const h = await equipmentFixture();
+ const first = h.f.api.equiparTretaSkin('ouro-ak');
+ await tick();
+ assert.equal(h.writes.length, 1);
+ const second = h.f.api.desequiparTretaSkin();
+ await tick();
+ assert.equal(h.writes.length, 1, 'unequip waits for the equip response');
+ h.writes[0].operation.resolve(h.state('fixture', 'ouro-ak'));
+ assert.equal(await first, true);
+ await tick();
+ assert.equal(h.writes.length, 2);
+ assert.equal(h.writes[1].body.action, 'unequip');
+ h.writes[1].operation.reject(new Error('server_down'));
+ await assert.rejects(second, /server_down/);
+ assert.equal(h.f.api.equippedTretaWeaponSkin('ak'), 'ouro-ak');
+ await h.f.api.refresh();
+ assert.equal(h.f.api.equippedTretaWeaponSkin('ak'), 'ouro-ak');
+});
+
+test('an old account write drains before a new account intent', async () => {
+ const h = await equipmentFixture();
+ const old = h.f.api.equiparTretaSkin('ouro-ak');
+ await tick();
+ assert.equal(h.writes.length, 1);
+ h.setServerState(h.state('next-account', null));
+ h.f.accountChanged({ authenticated: true, accountId: 'next-account' });
+ await tick();
+ const next = h.f.api.equiparTretaSkin('prata-ak');
+ await tick();
+ assert.equal(h.writes.length, 1, 'new account waits for the old request to settle');
+ h.writes[0].operation.resolve(h.state('fixture', 'ouro-ak'));
+ assert.equal(await old, false);
+ await tick();
+ assert.equal(h.writes.length, 2);
+ assert.equal(h.writes[1].body.skinId, 'prata-ak');
+ h.writes[1].operation.resolve(h.state('next-account', 'prata-ak'));
+ assert.equal(await next, true);
+ assert.equal(h.f.api.equippedTretaWeaponSkin('ak'), 'prata-ak');
+});
+
async function ownedWaits(mutate) {
const f = fixture({ mutate });
diff --git a/tools/eval/ARCH.md b/tools/eval/ARCH.md
index 67dec4b0c7..93404107ce 100644
--- a/tools/eval/ARCH.md
+++ b/tools/eval/ARCH.md
@@ -10,8 +10,8 @@
| Arquivo | Linhas | Símbolos |
|---|---:|---:|
| `public/js/game.js` | 10303 | 438 |
-| `public/js/main.js` | 5804 | 449 |
-| `public/js/glbchars.js` | 2170 | 156 |
+| `public/js/main.js` | 5811 | 449 |
+| `public/js/glbchars.js` | 2187 | 157 |
| `public/js/characters.js` | 1243 | 40 |
| `public/js/vmattach.js` | 353 | 3 |
| `public/js/springs.js` | 260 | 28 |
diff --git a/tools/eval/KNOWN-RED.json b/tools/eval/KNOWN-RED.json
index bdc4439e2b..9492580d7f 100644
--- a/tools/eval/KNOWN-RED.json
+++ b/tools/eval/KNOWN-RED.json
@@ -14,6 +14,7 @@
"BOT8": "comportamento de bot fora do alvo no protocolo botsim — backlog de rotas/mira",
"CHR1": "antropometria do elenco Mint fora de ±35% (cabeça/ombro/perna) — corrigir exigiria re-gerar/escalar o roster",
"CHR3": "pés no chão, 93 personagens × 7 poses (crouchwalk entrou em 11/11): afundando 6 (esbirro -0,198 crouchwalk · ancap -0,151 crouchwalk · caminhoneiro -0,083 · palhacomal -0,037 …), flutuando 55 (mst +0,098 · doutora +0,057 · farialimer +0,050 …). A régua lê o quadro de maior |desvio| do clipe, e desde 11/11 o C3 amostra o clipe INTEIRO (24 quadros; antes eram 5 em 0…0,8 s) e a tabela compensa pelo pé MAIS BAIXO do ciclo: o 'flutua 0' de antes era o offset descendo o corpo pelo pico do balanço e enterrando o pé de apoio (mandrake/run -0,103 no jogo, adjim/walk -0,104). O que sobra é raiz oscilando no clipe (classe c, 14 suspeitos em foot-offsets.json, 7 com o offset da staging por exceção medida) — exige clipe novo (#1279). Packs Studio no crouch: satanista-talkshow +0,333 → +0,006, dracula +0,311 → +0,006, vlad +0,135 → +0,004 (bake do Studio erguia o quadril pela barra do sobretudo/capa; conserto no Studio à parte). Ver tools/gen-foot-offsets.mjs e KNOWN-BUGS.md BUG-10/CHR3.",
+ "CHR3C": "malha × piso no crouch: rabo/quadril de proerd (-0,43) e canarinho cruzam o chão com o pé plantado, e lobisomem/palhacomal também; com os packs Studio medidos entram dracula, satanista-talkshow e vlad — exige clipe ou rig novo (#1117)",
"CHR4": "proporções do elenco — mesmo lote do CHR1",
"CTF1": "geometria de bandeira fora do critério em mapa(s) legado(s) — ajuste de layout pendente",
"GRAF1": "grafite: 272 peças com vão atrás em 5 mapas (brasília 68 · quebrada 102 · ferro 51 · loja H 28 · piscina 23) e 145 sobrepostas. Saiu de 698/540 em 07/08 alinhando o limiar das duas réguas; o resto é peça em quina de GLB e em superfície curva. Régua: `npm run eval:grafite:ar`. Ver docs/LICOES.md §1 e §2.",
diff --git a/tools/eval/README.md b/tools/eval/README.md
index 09dd7099bd..62a41e374a 100644
--- a/tools/eval/README.md
+++ b/tools/eval/README.md
@@ -162,6 +162,7 @@ com mutante que restaura o raio central apesar do erro sorteado.
| Arquivo | O que faz |
|---|---|
| `serve.mjs` | Servidor estático pro harness. `npm run eval:serve` |
+| `lib/serve-eval.mjs` | `subirServe(porta, { url })`: sobe o `serve.mjs` para a régua e espera responder num prazo único, `EVAL_BOOT_TIMEOUT_MS` (padrão 180000). Porta ocupada reprova antes do spawn; filho que sai antes de responder reprova na hora com o código de saída. Toda régua que sobe o próprio `serve.mjs` passa por aqui. |
| `harness.mjs` | Base compartilhada dos capturadores com Chrome. |
| `measure.mjs` | Utilitários de medição. |
| `shot.mjs`, `vmshot.mjs` | Screenshot simples. |
diff --git a/tools/eval/ads-visibility-check.mjs b/tools/eval/ads-visibility-check.mjs
index 86516fdcf0..69a9952a0f 100644
--- a/tools/eval/ads-visibility-check.mjs
+++ b/tools/eval/ads-visibility-check.mjs
@@ -1,13 +1,14 @@
#!/usr/bin/env node
import fs from 'node:fs';
import path from 'node:path';
-import { spawn, execFileSync } from 'node:child_process';
+import { execFileSync } from 'node:child_process';
import net from 'node:net';
import os from 'node:os';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { ASPECTOS, mascara, salvarMascaraPng } from './lib/vm-palco.mjs';
import { ocupacao } from './lib/vm-analise.mjs';
import * as L from './lib/vm-limiares.mjs';
+import { subirServe } from './lib/serve-eval.mjs';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const mutant = process.argv.includes('--mutante=ads-antigo');
@@ -41,7 +42,7 @@ const port = remote ? null : await new Promise((resolve, reject) => {
});
});
const base = remote || `http://127.0.0.1:${port}`;
-const server = remote ? null : spawn(process.execPath, ['tools/eval/serve.mjs', String(port)], { cwd: root, stdio: 'ignore' });
+let server = null;
let browser;
const failures = [];
const check = (name, pass, details) => {
@@ -49,12 +50,7 @@ const check = (name, pass, details) => {
if (!pass) failures.push(name);
};
try {
- let ready = false;
- for (let i = 0; i < 80; i += 1) {
- try { ready = (await fetch(base)).ok; if (ready) break; } catch { /* boot */ }
- await new Promise((resolve) => setTimeout(resolve, 500));
- }
- if (!ready) throw new Error('servidor local não subiu');
+ if (!remote) server = await subirServe(port, { url: base, cwd: root });
console.log(`jogo: ${base}`);
browser = await chromium.launch({ args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--mute-audio'] });
const page = await browser.newPage({ viewport: { width: ASPECTOS[ASPECTO][0], height: ASPECTOS[ASPECTO][1] } });
diff --git a/tools/eval/apis-migradas-check.mjs b/tools/eval/apis-migradas-check.mjs
index 296e51a6e1..d9705f9a6a 100644
--- a/tools/eval/apis-migradas-check.mjs
+++ b/tools/eval/apis-migradas-check.mjs
@@ -48,6 +48,8 @@ if (mut === 'proxy-vaza-cookie') proxy = proxy.replace(
/* As rotas que ficam, e o motivo de cada uma. Esta lista é a documentação executável do
recorte: acrescentar rota aqui é uma decisão, não um esquecimento. */
const FICAM = {
+ 'usage-script.js.ts': 'script próprio de medição, servido pelo domínio do site',
+ 'usage-event.ts': 'valida contagem de páginas na mesma origem e usa o binding do Worker',
'geo-lang.ts': 'lê o país no header da borda da Vercel; fora de lá não há o que ler',
og: 'cartão social DO SITE; servi-lo de outro domínio faria o compartilhamento depender de uma VM',
badge: 'crachá DO SITE, mesma razão do og',
diff --git a/tools/eval/armas-check.mjs b/tools/eval/armas-check.mjs
index 29793fd4f9..26144909c0 100644
--- a/tools/eval/armas-check.mjs
+++ b/tools/eval/armas-check.mjs
@@ -28,10 +28,11 @@
Mutantes: sem-lazy acende ARM3; awp-fallback acende ARM4; fallback-unshared acende ARM6.
Uso: node tools/eval/armas-check.mjs [--mutante=sem-lazy|awp-fallback|fallback-unshared] [--porta=8137] [--foto=/tmp/armas.png]
============================================================================ */
-import { execSync, spawn } from 'node:child_process';
+import { execSync } from 'node:child_process';
import { writeFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
import { probeSelectedWeapon } from './selected-weapon-probe.mjs';
+import { subirServe } from './lib/serve-eval.mjs';
const arg = (n) => (process.argv.find((a) => a.startsWith(`--${n}=`)) || '').split('=')[1] || '';
const MUT = arg('mutante');
@@ -45,12 +46,7 @@ const gRoot = execSync('npm root -g').toString().trim();
const _pw = await import(pathToFileURL(`${gRoot}/playwright/index.js`).href);
const chromium = _pw.chromium || _pw.default?.chromium;
-const srv = spawn('node', ['tools/eval/serve.mjs', PORTA], { stdio: 'ignore' });
-process.on('exit', () => srv.kill());
-for (let i = 0; i < 60; i++) {
- try { if ((await fetch(BASE)).ok) break; } catch { /* subindo */ }
- await new Promise((r) => setTimeout(r, 500));
-}
+const srv = await subirServe(PORTA, { url: BASE });
const browser = await chromium.launch({ args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--mute-audio'] });
const page = await browser.newPage({ viewport: { width: 1280, height: 720 } });
const ARMA_GLB = /\/models\/weapons\/([a-z0-9-]+)\.glb/;
diff --git a/tools/eval/authored-ads-check.mjs b/tools/eval/authored-ads-check.mjs
index 0900c7cd4d..12d3bfe140 100644
--- a/tools/eval/authored-ads-check.mjs
+++ b/tools/eval/authored-ads-check.mjs
@@ -31,8 +31,9 @@
Uso: node tools/eval/authored-ads-check.mjs [--armas=ak] [--porta=8156]
Requer private-assets — régua LOCAL (check:vm), fora do check:fast.
============================================================================ */
-import { execSync, spawn } from 'node:child_process';
+import { execSync } from 'node:child_process';
import { pathToFileURL } from 'node:url';
+import { subirServe } from './lib/serve-eval.mjs';
import { VM_WEAPON } from '../../public/js/data/vmconfig.js';
@@ -53,12 +54,7 @@ const gRoot = execSync('npm root -g').toString().trim();
const _pw = await import(pathToFileURL(`${gRoot}/playwright/index.js`).href);
const chromium = _pw.chromium || _pw.default?.chromium;
-const srv = spawn('node', ['tools/eval/serve.mjs', PORTA], { stdio: 'ignore' });
-process.on('exit', () => srv.kill());
-for (let i = 0; i < 60; i++) {
- try { if ((await fetch(BASE)).ok) break; } catch { /* subindo */ }
- await new Promise((r) => setTimeout(r, 500));
-}
+const srv = await subirServe(PORTA, { url: BASE });
const browser = await chromium.launch({ args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--mute-audio'] });
const falhas = [];
diff --git a/tools/eval/authored-identity-check.mjs b/tools/eval/authored-identity-check.mjs
index 142f6386e6..cab158ec78 100644
--- a/tools/eval/authored-identity-check.mjs
+++ b/tools/eval/authored-identity-check.mjs
@@ -23,8 +23,9 @@
Uso: node tools/eval/authored-identity-check.mjs [--armas=ak,akm] [--mutante=…] [--porta=8154]
Requer private-assets (symlink public/private-assets) — régua LOCAL, fora do check:fast.
============================================================================ */
-import { execSync, spawn } from 'node:child_process';
+import { execSync } from 'node:child_process';
import { pathToFileURL } from 'node:url';
+import { subirServe } from './lib/serve-eval.mjs';
import { VM_WEAPON } from '../../public/js/data/vmconfig.js';
import { weaponCFG } from '../../public/js/weapons.js';
@@ -41,12 +42,7 @@ const gRoot = execSync('npm root -g').toString().trim();
const _pw = await import(pathToFileURL(`${gRoot}/playwright/index.js`).href);
const chromium = _pw.chromium || _pw.default?.chromium;
-const srv = spawn('node', ['tools/eval/serve.mjs', PORTA], { stdio: 'ignore' });
-process.on('exit', () => srv.kill());
-for (let i = 0; i < 60; i++) {
- try { if ((await fetch(BASE)).ok) break; } catch { /* subindo */ }
- await new Promise((r) => setTimeout(r, 500));
-}
+const srv = await subirServe(PORTA, { url: BASE });
const browser = await chromium.launch({ args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--mute-audio'] });
const falhas = [];
diff --git a/tools/eval/boca-cano-prancha.mjs b/tools/eval/boca-cano-prancha.mjs
index 85b5f27024..0ca1273a89 100644
--- a/tools/eval/boca-cano-prancha.mjs
+++ b/tools/eval/boca-cano-prancha.mjs
@@ -14,7 +14,7 @@
Uso: node tools/eval/boca-cano-prancha.mjs --porta=8512 [--saida=evidence/boca-cano] */
import fs from 'node:fs';
import path from 'node:path';
-import { spawn } from 'node:child_process';
+import { subirServe } from './lib/serve-eval.mjs';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';
import sharp from 'sharp';
@@ -27,7 +27,7 @@ const OUT = path.resolve(ROOT, arg('saida', 'evidence/boca-cano'));
fs.mkdirSync(OUT, { recursive: true });
const W = 1280, H = 720;
const base = `http://127.0.0.1:${port}`;
-const server = spawn(process.execPath, ['tools/eval/serve.mjs', String(port)], { cwd: ROOT, stdio: 'ignore' });
+let server = null;
let browser;
// roda DENTRO da página: helpers de medida + congelamento do laço
@@ -212,9 +212,7 @@ async function prancha(resAntes, resDepois) {
}
try {
- let up = false;
- for (let i = 0; i < 80 && !up; i++) { try { up = (await fetch(base)).ok; } catch { await new Promise((r) => setTimeout(r, 500)); } }
- if (!up) throw new Error('servidor não subiu');
+ server = await subirServe(port, { url: base, cwd: ROOT });
browser = await chromium.launch({ headless: true, args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--mute-audio'] });
const antes = await lado('antes', '&bocacano=0');
const depois = await lado('depois', '');
@@ -224,5 +222,5 @@ try {
console.log('prancha:', path.join(OUT, 'prancha-boca-cano.png'));
} finally {
await browser?.close().catch(() => {});
- server.kill();
+ server?.kill();
}
diff --git a/tools/eval/boot-orcamento-check.mjs b/tools/eval/boot-orcamento-check.mjs
index 28e9fcce83..f7fb1467b9 100644
--- a/tools/eval/boot-orcamento-check.mjs
+++ b/tools/eval/boot-orcamento-check.mjs
@@ -11,6 +11,7 @@ import {createGuestProfileObserver,readGuestPageIdentity} from './boot-guest-pro
import {instrumentPosterIntent,collectPosterProof,lazyPosterSubset} from './boot-poster-intent.mjs';
import {awaitLocalModuleProof} from './boot-local-proof.mjs';
+const EGO_CONFIG=globalThis.__BOOT_EGO_CONFIG__||null;
const args = process.argv.slice(2), vistos = new Set(), opcoes = {};
for (const a of args) {
const m=a.match(/^--(base|api-base|mutante)=(.+)$/);
@@ -18,17 +19,21 @@ for (const a of args) {
if (!k || vistos.has(k)) { console.error('uso: --base=URL --api-base=ORIGIN --mutante=cartaz-ansioso|fauna-cedo --self-test (sem duplicatas)'); process.exit(2); }
vistos.add(k); opcoes[k]=m?.[2] ?? true;
}
-const MUTANTE=opcoes.mutante || '', BASE=opcoes.base ?? process.env.BOOT_CANDIDATE_BASE ?? process.env.BASE ?? 'https://www.corosolto.com.br';
+const MUTANTE=EGO_CONFIG?.MUTANTE ?? opcoes.mutante ?? '', BASE=EGO_CONFIG?.BASE ?? opcoes.base ?? process.env.BOOT_CANDIDATE_BASE ?? process.env.BASE ?? 'https://www.corosolto.com.br';
if (!['','cartaz-ansioso','fauna-cedo'].includes(MUTANTE)) { console.error('mutante desconhecido');process.exit(2); }
try { if (!['http:','https:'].includes(new URL(BASE).protocol)) throw Error(); }
catch { console.error('BASE inválida');process.exit(2); }
let API_BASE;
-try { API_BASE=publicApiOrigin(opcoes['api-base'] ?? process.env.BOOT_API_BASE ?? new URL(BASE).origin); }
+try { API_BASE=publicApiOrigin(EGO_CONFIG?.API_BASE ?? opcoes['api-base'] ?? process.env.BOOT_API_BASE ?? new URL(BASE).origin); }
catch { console.error('API_BASE inválida');process.exit(2); }
if (opcoes['self-test']) {
if (args.length !== 1) { console.error('--self-test exige uso isolado');process.exit(2); }
const {selfTest}=await import('./boot-overlay.mjs');process.exit(selfTest().length?1:0);
}
+if (!EGO_CONFIG && process.env.EGO_TASK_SPACE !== undefined) {
+ const { runEgo } = await import('./boot-orcamento-ego.mjs');
+ process.exit(await runEgo({ BASE, API_BASE, MUTANTE, proofDir: process.env.BOOT_PROOF_DIR || null }));
+}
// Tetos e procedência: docs/visual-consistency/BOOT-COHERENT-OVERLAY.md.
const TETO_BYTES = 8_200_000;
@@ -67,17 +72,22 @@ try {SNAPSHOT=snapshotPublicJs(PUBLIC_ROOT);}catch(e){console.error('INFRA78 sna
const RUN_ID=randomUUID();
let browser;
try {
- const gRoot=execSync('npm root -g').toString().trim();
- const pw=await import(pathToFileURL(`${gRoot}/playwright/index.js`).href);
- const chromium=pw.chromium||pw.default?.chromium;
- const softwareGLArgs=process.platform==='darwin'?[]:['--use-angle=swiftshader','--enable-unsafe-swiftshader'];
- browser=await chromium.launch({executablePath:process.env.CHROME_BIN||'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
- args:[...softwareGLArgs,'--headless=new','--mute-audio','--disable-dev-shm-usage']});
+ if (EGO_CONFIG) {
+ const { createEgoBrowser } = await import('./boot-orcamento-ego-adapter.mjs');
+ browser = await createEgoBrowser(EGO_CONFIG);
+ } else {
+ const gRoot=execSync('npm root -g').toString().trim();
+ const pw=await import(pathToFileURL(`${gRoot}/playwright/index.js`).href);
+ const chromium=pw.chromium||pw.default?.chromium;
+ const softwareGLArgs=process.platform==='darwin'?[]:['--use-angle=swiftshader','--enable-unsafe-swiftshader'];
+ browser=await chromium.launch({executablePath:process.env.CHROME_BIN||'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ args:[...softwareGLArgs,'--headless=new','--mute-audio','--disable-dev-shm-usage']});
+ }
} catch(e) {console.error(`INFRA78 browser indisponível: ${e.message}`);process.exit(78);}
async function mede({ refPoolAnsioso = false, mutante = '' } = {}) {
assertSnapshotLive(SNAPSHOT);
- const label=refPoolAnsioso?'reference':mutante||'nominal',passId=label+'-'+randomUUID(),proofDir=process.env.BOOT_PROOF_DIR?process.env.BOOT_PROOF_DIR+'/'+RUN_ID+'/'+passId:null;
+ const label=refPoolAnsioso?'reference':mutante||'nominal',passId=label+'-'+randomUUID(),proofRoot=EGO_CONFIG?.BOOT_PROOF_DIR ?? process.env.BOOT_PROOF_DIR,proofDir=proofRoot?proofRoot+'/'+RUN_ID+'/'+passId:null;
if(proofDir)mkdirSync(proofDir,{recursive:true});
console.log('BOOT_PASS '+JSON.stringify({runId:RUN_ID,passId,label,proofDir,snapshot:SNAPSHOT.fingerprint}));
let context,origin,page,guest,terminalCapture=null,localProof=null,diagnostic=()=>({});
@@ -336,9 +346,15 @@ async function mede({ refPoolAnsioso = false, mutante = '' } = {}) {
if(proofDir) {
const abortTrace=terminalCapture?terminalCapture.abortTrace:page?await page.evaluate(()=>window.__bootTrace||[]).catch(e=>({error:e.message})):null;
const fetchBodies=terminalCapture?terminalCapture.fetchBodies:page?await page.evaluate(()=>window.__bootFetchBodies||[]).catch(e=>({error:e.message})):null;
- writeFileSync(proofDir+'/diagnostic.json',JSON.stringify({runId:RUN_ID,passId,label,origin:origin?.url,...diagnostic(),abortTrace,fetchBodies,readyExact:terminalCapture?.readyExact??null},null,2));
+ writeFileSync(proofDir+'/diagnostic.json',JSON.stringify({runId:RUN_ID,passId,label,origin:origin?.url,...diagnostic(),abortTrace,fetchBodies,readyExact:terminalCapture?.readyExact??null,transport:page?.transportDiagnostics?.()},null,2));
}
- } finally {await context?.close().catch(()=>{});await origin?.close();}
+ } finally {
+ try {
+ const cleanup = context?.close();
+ if (EGO_CONFIG) await cleanup;
+ else await cleanup?.catch(()=>{});
+ } finally { await origin?.close(); }
+ }
}
}
diff --git a/tools/eval/boot-orcamento-ego-adapter.mjs b/tools/eval/boot-orcamento-ego-adapter.mjs
new file mode 100644
index 0000000000..8e14026485
--- /dev/null
+++ b/tools/eval/boot-orcamento-ego-adapter.mjs
@@ -0,0 +1,232 @@
+const OWN_PROFILES = new Set(['rubenmarcus.dev', 'ruben marcus']);
+const isBlank = (url) => ['about:blank', 'chrome://newtab/'].includes(url);
+const resourceType = (type) => String(type || 'other').toLowerCase();
+
+class EgoRequest {
+ constructor(event) {
+ this._event = event;
+ this._failure = null;
+ }
+ url() { return this._event.params.request.url; }
+ method() { return this._event.params.request.method; }
+ resourceType() { return resourceType(this._event.params.type); }
+ failure() { return this._failure; }
+}
+
+class EgoResponse {
+ constructor(page, request, event) {
+ this._page = page;
+ this._request = request;
+ this._event = event;
+ this._body = null;
+ }
+ request() { return this._request; }
+ url() { return this._event.params.response.url; }
+ status() { return this._event.params.response.status; }
+ headers() {
+ const headers = this._event.params.response.headers || {};
+ return Object.fromEntries(Object.entries(headers).map(([name, value]) => [String(name).toLowerCase(), value]));
+ }
+ async body() {
+ this._body ||= this._page.bodyFor(this._request._event.params.requestId);
+ return this._body;
+ }
+ async text() { return (await this.body()).toString('utf8'); }
+}
+
+class EgoFrame {
+ constructor(page, frameId) { this._page = page; this._frameId = frameId; }
+ url() { return this._page._frameUrls.get(this._frameId) || ''; }
+}
+
+class EgoConsoleMessage {
+ constructor(event) { this._event = event; }
+ type() { return String(this._event.params.type || 'log'); }
+ text() { return (this._event.params.args || []).map((arg) => arg.value ?? arg.description ?? '').join(' '); }
+}
+
+class EgoCDP {
+ constructor(page) { this._page = page; this._listeners = new Map(); }
+ on(method, listener) { const rows = this._listeners.get(method) || []; rows.push(listener); this._listeners.set(method, rows); }
+ off(method, listener) { const rows = this._listeners.get(method) || []; const index = rows.indexOf(listener); if (index >= 0) rows.splice(index, 1); }
+ async send(method, params = {}) {
+ const effective = method === 'Network.enable'
+ ? { maxTotalBufferSize: 64 * 1024 * 1024, maxResourceBufferSize: 8 * 1024 * 1024, ...params }
+ : params;
+ const value = await this._page._raw.cdp(method, effective);
+ if (method === 'Runtime.evaluate') await this._page.drain();
+ return value;
+ }
+ dispatch(event) { for (const listener of this._listeners.get(event.method) || []) listener(event.params || {}); }
+}
+
+class EgoPage {
+ constructor(raw) {
+ this._raw = raw;
+ this._listeners = new Map();
+ this._requests = new Map();
+ this._finished = new Map();
+ this._bodyPromises = new Map();
+ this._frameUrls = new Map();
+ this._mainFrame = new EgoFrame(this, 'main');
+ this._cdps = new Set();
+ this._transportError = null;
+ this._batch = null;
+ this._closed = false;
+ this._pumping = true;
+ this._pumpPromise = this._pump().catch(error => { this._transportError = error; });
+ }
+ on(event, listener) { const rows = this._listeners.get(event) || []; rows.push(listener); this._listeners.set(event, rows); }
+ off(event, listener) { const rows = this._listeners.get(event) || []; const index = rows.indexOf(listener); if (index >= 0) rows.splice(index, 1); }
+ _emit(event, value) { for (const listener of this._listeners.get(event) || []) listener(value); }
+ _readBatch() {
+ if (this._transportError) throw this._transportError;
+ if (!this._batch) {
+ this._batch = this._raw.events().then(events => {
+ for (const event of events) this._dispatch(event);
+ }).finally(() => { this._batch = null; });
+ }
+ return this._batch;
+ }
+ async _pump() {
+ while (this._pumping) {
+ await this._readBatch();
+ await new Promise(resolve => setTimeout(resolve, 10));
+ }
+ }
+ _dispatch(event) {
+ const params = event.params || {};
+ for (const cdp of this._cdps) cdp.dispatch(event);
+ if (event.method === 'Page.frameNavigated') {
+ const frameId = params.frame?.id || 'main';
+ const frameUrl = params.frame?.url || '';
+ const frame = params.frame?.parentId ? new EgoFrame(this, frameId) : this._mainFrame;
+ this._frameUrls.set(frameId, frameUrl);
+ if (!params.frame?.parentId) this._frameUrls.set('main', frameUrl);
+ this._emit('framenavigated', frame);
+ return;
+ }
+ if (event.method === 'Runtime.consoleAPICalled') {
+ this._emit('console', new EgoConsoleMessage(event));
+ return;
+ }
+ if (event.method === 'Runtime.exceptionThrown') {
+ const details = params.exceptionDetails || {};
+ const error = new Error(details.exception?.description || details.text || 'Runtime exception');
+ error.name = details.exception?.className || 'Error';
+ this._emit('pageerror', error);
+ return;
+ }
+ if (event.method === 'Network.requestWillBeSent' && params.request) {
+ const request = new EgoRequest(event);
+ if (!this._requests.has(params.requestId)) {
+ this._requests.set(params.requestId, request);
+ this._emit('request', request);
+ }
+ return;
+ }
+ const request = this._requests.get(params.requestId);
+ if (!request) return;
+ if (event.method === 'Network.responseReceived' && params.response) {
+ const response = new EgoResponse(this, request, event);
+ this._emit('response', response);
+ return;
+ }
+ if (event.method === 'Network.loadingFinished') {
+ this._finished.set(params.requestId, event);
+ return;
+ }
+ if (event.method === 'Network.loadingFailed') {
+ request._failure = { errorText: params.errorText || 'loadingFailed' };
+ this._finished.set(params.requestId, event);
+ this._emit('requestfailed', request);
+ }
+ }
+ async bodyFor(requestId) {
+ if (this._bodyPromises.has(requestId)) return this._bodyPromises.get(requestId);
+ const promise = (async () => {
+ const deadline = Date.now() + 30000;
+ while (!this._finished.has(requestId) && Date.now() < deadline) await this._raw.waitForTimeout(5);
+ if (!this._finished.has(requestId)) throw Error('Network.getResponseBody antes de loadingFinished: ' + requestId);
+ const finished = this._finished.get(requestId);
+ if (finished.method === 'Network.loadingFailed') throw Error('corpo indisponível após loadingFailed: ' + requestId);
+ const result = await this._raw.cdp('Network.getResponseBody', { requestId });
+ return Buffer.from(result.body, result.base64Encoded ? 'base64' : 'utf8');
+ })();
+ this._bodyPromises.set(requestId, promise);
+ return promise;
+ }
+ async drain() {
+ await this._batch;
+ await this._readBatch();
+ if (this._transportError) throw this._transportError;
+ }
+ async goto(url, options) {
+ const dest = new URL(url);
+ if (dest.protocol !== 'http:' || dest.hostname !== '127.0.0.1' || !dest.port || dest.username || dest.password) {
+ throw Error('Boot Ego só pode navegar para sua fixture loopback');
+ }
+ return this._raw.goto(url, options);
+ }
+ async waitForFunction(fn, arg, options) {
+ await this._raw.waitForFunction(fn, arg ?? null, options);
+ return { jsonValue: () => this.evaluate(fn, arg) };
+ }
+ async waitForTimeout(ms) { return this._raw.waitForTimeout(ms); }
+ async evaluate(fn, arg) { const value = await this._raw.evaluate(fn, arg ?? null); await this.drain(); return value; }
+ isClosed() { return this._closed; }
+ async close() { if (!this._closed) { this._closed = true; this._pumping = false; await this._pumpPromise; } }
+ mainFrame() { return this._mainFrame; }
+ async newCDPSession() { const cdp = new EgoCDP(this); this._cdps.add(cdp); return cdp; }
+}
+
+class EgoContext {
+ constructor(page) { this._page = page; this._scripts = []; this._closed = false; }
+ async addInitScript(fn) {
+ const source = `(${fn.toString()})();`;
+ const result = await this._page._raw.cdp('Page.addScriptToEvaluateOnNewDocument', { source });
+ this._scripts.push(result.identifier);
+ }
+ async newPage() { return this._page; }
+ async newCDPSession(page) { return page.newCDPSession(); }
+ async close() {
+ if (this._closed) return;
+ this._closed = true;
+ for (const identifier of this._scripts.splice(0)) await this._page._raw.cdp('Page.removeScriptToEvaluateOnNewDocument', { identifier }).catch(() => {});
+ await this._page.close();
+ await this._page._raw.cdp('Network.disable');
+ await this._page._raw.goto('about:blank', { waitUntil: 'commit', timeout: 30000 });
+ await this._page._raw.cdp('Emulation.clearDeviceMetricsOverride');
+ await this._page._raw.cdp('Emulation.setAutomationOverride', { enabled: false });
+ if (this._page._transportError) throw this._page._transportError;
+ }
+}
+
+export async function createEgoBrowser(config) {
+ if (!Number.isSafeInteger(config.space) || config.space <= 0 || !/^p\d+$/.test(config.page)) throw Error('Ego config TaskSpace/Page inválido');
+ const spaces = await listTaskSpaces();
+ const space = spaces.find((item) => item.id === config.space);
+ if (!space || space.ownership !== 'agent' || !OWN_PROFILES.has(String(space.profileName || '').toLowerCase())) throw Error('TaskSpace Ego deve pertencer ao agente no perfil CORO SOLTO');
+ const task = await taskSpace(config.space);
+ const tabs = await task.tabs();
+ const tab = tabs.find((item) => item.label === config.page);
+ if (!tab || tab.openedBy !== 'agent' || !isBlank(tab.url)) throw Error('EGO_PAGE deve ser uma página vazia aberta pelo agente');
+ const raw = task.page(config.page);
+ await raw.cdp('egoAutomated.disable');
+ await raw.cdp('Runtime.enable');
+ await raw.cdp('Page.enable');
+ let context;
+ return {
+ async newContext({ viewport, deviceScaleFactor }) {
+ if (context && !context._closed) throw Error('Ego boot precisa de contextos serializados');
+ await raw.cdp('Emulation.setDeviceMetricsOverride', { ...viewport, deviceScaleFactor, mobile: false });
+ // Playwright Chromium exposes navigator.webdriver on test pages. Preserve
+ // that signal so aggregate metrics don't POST during the read-only gate.
+ await raw.cdp('Emulation.setAutomationOverride', { enabled: true });
+ await raw.events();
+ context = new EgoContext(new EgoPage(raw));
+ return context;
+ },
+ async close() { await context?.close(); },
+ };
+}
diff --git a/tools/eval/boot-orcamento-ego.mjs b/tools/eval/boot-orcamento-ego.mjs
new file mode 100644
index 0000000000..538219c3f3
--- /dev/null
+++ b/tools/eval/boot-orcamento-ego.mjs
@@ -0,0 +1,45 @@
+import { spawn } from 'node:child_process';
+import { pathToFileURL } from 'node:url';
+
+const CHECK = new URL('./boot-orcamento-check.mjs', import.meta.url).href;
+const ALLOWED_ENV = ['PATH', 'HOME', 'TMPDIR'];
+
+function integerEnv(name) {
+ const value = Number(process.env[name]);
+ return Number.isSafeInteger(value) && value > 0 ? value : null;
+}
+
+export async function runEgo({ BASE, API_BASE, MUTANTE = '', proofDir = process.env.BOOT_PROOF_DIR || null }) {
+ const space = integerEnv('EGO_TASK_SPACE');
+ const page = process.env.EGO_PAGE;
+ if (!space || !/^p\d+$/.test(page || '')) {
+ console.error('INFRA78 Ego exige EGO_TASK_SPACE numérico e EGO_PAGE=pN');
+ return 78;
+ }
+ const config = {
+ BASE,
+ API_BASE,
+ MUTANTE,
+ space,
+ page,
+ BOOT_PROOF_DIR: proofDir,
+ };
+ const source = `globalThis.__BOOT_EGO_CONFIG__=${JSON.stringify(config)}; await import(${JSON.stringify(CHECK)});`;
+ const child = spawn('ego-browser', ['nodejs', '-e', source], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: Object.fromEntries(ALLOWED_ENV.filter((name) => process.env[name] != null).map((name) => [name, process.env[name]])),
+ });
+ child.stdout.on('data', (chunk) => process.stdout.write(chunk));
+ child.stderr.on('data', (chunk) => process.stderr.write(chunk));
+ return await new Promise((resolve) => {
+ let settled = false;
+ const finish = (code) => { if (!settled) { settled = true; resolve([0, 1, 78].includes(code) ? code : 78); } };
+ child.once('error', (error) => { console.error(`INFRA78 Ego indisponível: ${error.message}`); finish(78); });
+ child.once('close', (code, signal) => {
+ if (signal) console.error(`INFRA78 Ego encerrado por ${signal}`);
+ finish(code ?? 78);
+ });
+ const timer = setTimeout(() => { console.error('INFRA78 Ego excedeu 30 minutos'); child.kill('SIGTERM'); finish(78); }, 1_800_000);
+ child.once('close', () => clearTimeout(timer));
+ });
+}
diff --git a/tools/eval/boot-waterfall.mjs b/tools/eval/boot-waterfall.mjs
index d7422fad2e..d77fd43da5 100644
--- a/tools/eval/boot-waterfall.mjs
+++ b/tools/eval/boot-waterfall.mjs
@@ -6,18 +6,20 @@
//
// Uso: node tools/eval/boot-waterfall.mjs
// Sobe tools/eval/serve.mjs sozinho na 8123 (mata ao sair). Um browser só — regra da casa.
-import { execSync, spawn } from 'node:child_process';
+// BASE= mede um servidor externo já no ar, sem subir nada.
+import { execSync } from 'node:child_process';
import { writeFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
+import { subirServe } from './lib/serve-eval.mjs';
const BASE = process.env.BASE || 'http://127.0.0.1:8123';
const gRoot = execSync('npm root -g').toString().trim();
const _pw = await import(pathToFileURL(`${gRoot}/playwright/index.js`).href);
const chromium = _pw.chromium || _pw.default?.chromium;
-const srv = spawn('node', ['tools/eval/serve.mjs', '8123'], { stdio: 'ignore' });
-process.on('exit', () => srv.kill());
-await new Promise((r) => setTimeout(r, 600));
+// BASE explícita é servidor externo e tem de estar no ar; sem BASE a régua sobe o próprio serve.mjs.
+const srv = process.env.BASE ? null : await subirServe(8123, { url: BASE });
+if (!srv && !(await fetch(BASE).then((r) => r.ok, () => false))) throw new Error(`boot-waterfall: BASE=${BASE} não respondeu ok`);
const kind = (u) =>
/\.glb(\?|$)/.test(u) ? 'glb' :
@@ -80,5 +82,5 @@ const quente = report('QUENTE (reload, cache on)', await pass(page, cdp, false))
console.log(`\nRESUMO: fria ${(fria.bytes / 1e6).toFixed(1)}MB/${fria.reqs}req/${(fria.liveMs / 1000).toFixed(1)}s → quente ${(quente.bytes / 1e6).toFixed(1)}MB/${quente.reqs}req/${(quente.liveMs / 1000).toFixed(1)}s`);
await browser.close();
-srv.kill();
+srv?.kill();
process.exit(0);
diff --git a/tools/eval/bots-perf-browser.mjs b/tools/eval/bots-perf-browser.mjs
index 2e16689efc..591f38d32c 100644
--- a/tools/eval/bots-perf-browser.mjs
+++ b/tools/eval/bots-perf-browser.mjs
@@ -12,10 +12,11 @@
node tools/eval/bots-perf-browser.mjs --medir --maps=operacao_flavio,lajes,amazonia --bots=4,8,12 [--cpu=4] [--profile] [--alloc]
Servidor: sobe tools/eval/serve.mjs na --porta (9613) ou usa --base/BASE. Rode com
tools/eval/with-browser-lock.sh (um browser por vez). */
-import { spawn, spawnSync } from 'node:child_process';
+import { spawnSync } from 'node:child_process';
import { mkdirSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';
+import { subirServe } from './lib/serve-eval.mjs';
const SELF = fileURLToPath(import.meta.url);
const option = (name, fallback) => process.argv.find(a => a.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback;
@@ -188,16 +189,7 @@ function resumoAlloc(p, seconds) {
return { folha: top(folha), jogo: top(jogo) };
}
-const servidor = baseExterna ? null : spawn(process.execPath, ['tools/eval/serve.mjs', porta], { stdio: 'ignore' });
-process.on('exit', () => servidor?.kill());
-if (servidor) {
- let pronto = false;
- for (let i = 0; i < 120 && !pronto; i++) {
- try { pronto = (await fetch(base)).ok; } catch { /* subindo */ }
- if (!pronto) await new Promise(r => setTimeout(r, 500));
- }
- if (!pronto) throw new Error(`servidor não respondeu em ${base}`);
-}
+const servidor = baseExterna ? null : await subirServe(porta, { url: base });
const browser = await chromium.launch({ channel: 'chrome', headless: true, args: ['--mute-audio', '--enable-precise-memory-info'] });
const linhas = [];
diff --git a/tools/eval/camera-reborn-composition-check.mjs b/tools/eval/camera-reborn-composition-check.mjs
new file mode 100644
index 0000000000..645b04280c
--- /dev/null
+++ b/tools/eval/camera-reborn-composition-check.mjs
@@ -0,0 +1,94 @@
+import assert from 'node:assert/strict';
+import { THREE, Game } from './harness.mjs';
+
+const { Box3, Euler, Group, PerspectiveCamera, Raycaster, Vector3 } = THREE;
+const { _updatePlayerTPCamera: update, _updateCrosshairParallax: reticle, _tpDeath: death } = Game.prototype;
+const dt = 1 / 60, eye = 1.62;
+const wall = new Box3(new Vector3(-3, 0, 0.46), new Vector3(3, 3, 0.65));
+const nearWall = new Box3(new Vector3(-3, 0, 0.26), new Vector3(3, 3, 0.34));
+const ids = ['bebe-reborn', 'capitao-caveira', 'vlad', 'muro-de-caco'];
+
+function boot(id, { mode = 'third', orbit = 0, side = 1 } = {}) {
+ return {
+ player: { def: { id }, pos: new Vector3(), yaw: 0, pitch: 0, crouchF: 0, scoped: false, alive: true },
+ playerTP: { group: new Group(), selfMeshes: [{ object: { visible: true }, visible: true }] },
+ world: { groundHeightAt: () => 0, camBlockers: [], occluders: [] },
+ camView: mode, camera: new PerspectiveCamera(70, 16 / 9, 0.06, 1000),
+ el: { crosshair: { style: {} } }, bots: [], ray: new Raycaster(), _eyeWorld: new Vector3(0, eye, 0),
+ _tpEul: new Euler(), _tpAimEul: new Euler(), _tpFwd: new Vector3(), _tpRight: new Vector3(),
+ _ensurePlayerTP() {},
+ _updatePlayerTPCamera: update,
+ _tpOrbitYaw: orbit, _tpOrbitPitch: 0, _tpShoulderSide: side,
+ };
+}
+function step(g, frames = 1) {
+ for (let i = 0; i < frames; i++) update.call(g, dt, eye);
+ reticle.call(g);
+ const { visibility, left, top } = g.el.crosshair.style;
+ return {
+ position: g.camera.position.toArray().map(x => +x.toFixed(10)),
+ aim: g.camera.quaternion.toArray().map(x => +x.toFixed(10)),
+ cross: visibility === 'hidden' ? { visibility } : { visibility, left, top },
+ visible: g.playerTP.selfMeshes[0].object.visible,
+ };
+}
+for (const orbit of [0, Math.PI / 4, Math.PI / 2, 3 * Math.PI / 4, Math.PI]) {
+ const [short, medium, tall, bulk] = ids.map(id => boot(id, { orbit }));
+ const standard = step(medium, 20);
+ assert.deepEqual(step(tall, 20), standard, 'tall defaults unchanged');
+ assert.deepEqual(step(bulk, 20), standard, 'voluminous defaults unchanged');
+ const hip = step(short, 20);
+ assert.ok(hip.position[1] < standard.position[1], 'Reborn hip camera is lower at every orbit angle');
+ assert.ok(short._tpBoomClear > medium._tpBoomClear, 'Reborn hip boom exposes more of the short body');
+ assert.equal(short.player.yaw, 0, 'free orbit must not turn the body');
+ assert.equal(short.camera.fov, 70);
+ short.player.scoped = medium.player.scoped = true;
+ let previous = 0;
+ for (let i = 0; i < 8; i++) {
+ step(short);
+ assert.ok(short._tpAdsF >= previous, 'aim blends in monotonically');
+ previous = short._tpAdsF;
+ }
+ assert.equal(short._tpAdsF, 1, 'aim reaches the settled legacy geometry');
+ assert.deepEqual(step(short, 20), step(medium, 28), 'settled ADS keeps the shared camera and reticle');
+ short.player.scoped = false;
+ assert.deepEqual(step(short, 28), hip, 'leaving ADS restores hip composition');
+}
+for (const side of [-1, 1]) {
+ assert.deepEqual(step(boot(ids[0], { mode: 'shoulder', side })), step(boot(ids[1], { mode: 'shoulder', side })));
+ const g = boot(ids[0], { side });
+ step(g);
+ const free = g._tpBoomClear;
+ g.world.camBlockers = [wall];
+ assert.ok(step(g).position[2] < wall.min.z, 'camera stays on the player side of an occluding box');
+ assert.ok(g._tpBoomClear < free);
+ g.world.camBlockers = [nearWall];
+ assert.equal(step(g).visible, false, 'very short boom masks the own mesh');
+ g.world.camBlockers = [];
+ assert.equal(step(g, 30).visible, true, 'mesh and boom recover after leaving the wall');
+ assert.equal(g._tpBoomClear, free);
+}
+function fallen(id) {
+ const g = boot(id, { mode: 'first' });
+ g.player.alive = false;
+ const head = new Group();
+ head.position.set(0.12, 0.52, 0);
+ g.playerTP.group.add(head);
+ g.playerTP.parts = { head };
+ death.call(g, dt);
+ assert.equal(g.playerTP.group.visible, false, 'the first-person death view hides the self mesh');
+ g.camView = 'third';
+ g.world.camBlockers = [nearWall];
+ death.call(g, dt);
+ assert.equal(g.playerTP.selfOccluded, true, 'the corpse follows the same obstruction guard');
+ assert.equal(g._eyeWorld.y, 0.52, 'the death camera uses the animated head height');
+ g.world.camBlockers = [];
+ for (let i = 0; i < 30; i++) death.call(g, dt);
+ assert.equal(g.playerTP.selfMeshes[0].object.visible, true, 'pull-in releases the corpse mask');
+ return [g._eyeWorld.toArray(), g.camera.position.toArray(), g.camera.quaternion.toArray()];
+}
+assert.deepEqual(fallen(ids[0]), fallen(ids[1]), 'Reborn does not override the corpse view');
+const fp = boot(ids[0], { mode: 'first' });
+reticle.call(fp);
+assert.deepEqual(fp.el.crosshair.style, { visibility: 'visible', left: '50%', top: '50%' });
+console.log('Reborn camera: hip/orbit, controls, ADS, shoulders, occlusion/recovery and 1P reticle');
diff --git a/tools/eval/char-gauntlet.mjs b/tools/eval/char-gauntlet.mjs
index 4e408cda1d..a7d1a4431f 100644
--- a/tools/eval/char-gauntlet.mjs
+++ b/tools/eval/char-gauntlet.mjs
@@ -20,10 +20,11 @@
manifest.json (+ verdicts.json com --judge).
- Zero é a régua numérica: este script é EVIDÊNCIA. Exit 1 só em erro
de infra (servidor/browser/GLB que não carregou). */
-import { execSync, spawn, spawnSync } from 'node:child_process';
+import { execSync, spawnSync } from 'node:child_process';
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
+import { subirServe } from './lib/serve-eval.mjs';
const ROOT = fileURLToPath(new URL('../..', import.meta.url));
const arg = (n, d = '') => {
@@ -45,16 +46,7 @@ const gRoot = execSync('npm root -g').toString().trim();
const pw = await import(pathToFileURL(`${gRoot}/playwright/index.js`).href);
const chromium = pw.chromium || pw.default?.chromium;
-const servidor = SEM_SERVIDOR ? null : spawn('node', ['tools/eval/serve.mjs', PORTA], { stdio: 'ignore' });
-process.on('exit', () => servidor?.kill());
-if (servidor) {
- let pronto = false;
- for (let i = 0; i < 60 && !pronto; i++) {
- try { pronto = (await fetch(`${BASE}/eval-character.html`)).ok; } catch { /* subindo */ }
- if (!pronto) await new Promise((r) => setTimeout(r, 500));
- }
- if (!pronto) throw new Error(`servidor não respondeu em ${BASE}`);
-}
+const servidor = SEM_SERVIDOR ? null : await subirServe(PORTA, { url: `${BASE}/eval-character.html` });
const browser = await chromium.launch({
...(process.env.CHROME_BIN ? { executablePath: process.env.CHROME_BIN } : { executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' }),
diff --git a/tools/eval/character-assets-node.mjs b/tools/eval/character-assets-node.mjs
new file mode 100644
index 0000000000..c603c48438
--- /dev/null
+++ b/tools/eval/character-assets-node.mjs
@@ -0,0 +1,102 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { createHash } from 'node:crypto';
+import { pathToFileURL } from 'node:url';
+
+const STATES = ['idle', 'walk', 'run', 'shoot', 'death', 'crouch', 'crouchwalk', 'jump', 'idle1h', 'walk1h', 'walkfire'];
+const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
+
+export async function characterAssets(root, runtime, packRoot) {
+ const publicDir = path.join(root, 'public');
+ const { CHARACTER_RELEASES } = await import(pathToFileURL(path.join(publicDir, 'js/data/content-releases.js')));
+ const { isSafePackPath } = await import(pathToFileURL(path.join(publicDir, 'js/studio-character.js')));
+ const index = JSON.parse(fs.readFileSync(path.join(publicDir, 'models/anims/index.json')));
+ const skins = JSON.parse(fs.readFileSync(path.join(publicDir, 'models/skins/manifest.json'))).skins;
+ const files = new Map();
+ const characters = new Map();
+ const loadedSkins = new Set();
+ const glb = async (file) => {
+ if (!files.has(file)) files.set(file, await runtime.load(file));
+ return files.get(file);
+ };
+ const optional = async (file) => fs.existsSync(file) ? glb(file) : null;
+ const sharedPath = path.join(publicDir, 'models/anims/mixamo.glb');
+ const shared = {};
+ for (const clip of (await glb(sharedPath)).animations) shared[clip.name] = clip;
+ for (const state of STATES) {
+ if (shared[state]) continue;
+ const g = await optional(path.join(publicDir, `models/anims/mixamo/${state}.glb`));
+ if (g?.animations[0]) { g.animations[0].name = state; shared[state] = g.animations[0]; }
+ }
+
+ async function studio(pin) {
+ if (!packRoot) throw new Error(`${pin.id}: STUDIO_PACK_ROOT ausente`);
+ if (!pin.manifestUrl.startsWith('/packs/')) throw new Error(`${pin.id}: pin fora de /packs/`);
+ const relative = pin.manifestUrl.slice('/packs/'.length);
+ if (!isSafePackPath(relative)) throw new Error(`${pin.id}: caminho de manifesto inválido`);
+ const manifestPath = path.join(packRoot, relative);
+ const bytes = fs.readFileSync(manifestPath);
+ if (hash(bytes) !== pin.manifestSha256) throw new Error(`${pin.id}: SHA do manifesto diverge do pin`);
+ const manifest = JSON.parse(bytes);
+ if (manifest.id !== pin.id || manifest.version !== pin.version || manifest.kind !== pin.kind) throw new Error(`${pin.id}: identidade do manifesto divergente`);
+ const file = (relativePath) => {
+ if (!isSafePackPath(relativePath)) throw new Error(`${pin.id}: caminho inválido`);
+ const entry = manifest.files.find((item) => item.path === relativePath);
+ if (!entry) throw new Error(`${pin.id}: arquivo fora do manifesto`);
+ const absolute = path.join(path.dirname(manifestPath), relativePath);
+ const content = fs.readFileSync(absolute);
+ if (content.length !== entry.bytes || hash(content) !== entry.sha256) throw new Error(`${pin.id}: bytes ou SHA divergentes em ${relativePath}`);
+ return absolute;
+ };
+ const body = await glb(file(manifest.model));
+ const clips = {};
+ for (const state of STATES) {
+ const animation = await glb(file(manifest.animations[state]));
+ const clip = animation.animations.find((item) => item.name === state);
+ if (!clip) throw new Error(`${pin.id}: clipe ${state} ausente`);
+ clips[state] = clip;
+ }
+ const modelSha256 = manifest.files.find((entry) => entry.path === manifest.model).sha256;
+ return { body, clips, refs: {}, origin: { kind: 'studio', character: pin.id, sha256: modelSha256, manifestSha256: pin.manifestSha256 } };
+ }
+
+ async function legacy(id) {
+ const body = await glb(path.join(publicDir, `models/characters/${id}.glb`));
+ const clips = { ...shared }, refs = {};
+ const available = index.clipes?.[id] || [];
+ const merged = available.length ? await optional(path.join(publicDir, `models/anims/${id}.glb`)) : null;
+ for (const state of available) {
+ const clip = merged?.animations.find((item) => item.name === state);
+ if (clip) { clips[state] = clip; refs[state] = index.refs?.[id]?.[state]; }
+ else if (!merged) {
+ const animation = await optional(path.join(publicDir, `models/anims/${id}/${state}.glb`));
+ if (animation?.animations[0]) { animation.animations[0].name = state; clips[state] = animation.animations[0]; refs[state] = index.refs?.[id]?.[state]; }
+ }
+ }
+ return { body, clips, refs };
+ }
+
+ async function seed(id, skinId = null) {
+ if (!characters.has(id)) characters.set(id, await (CHARACTER_RELEASES[id] ? studio(CHARACTER_RELEASES[id]) : legacy(id)));
+ const { body, clips, refs, origin } = characters.get(id);
+ runtime.G.__seed(id, body.scene, clips, refs, origin);
+ if (skinId && !loadedSkins.has(skinId)) {
+ const entry = skins[skinId];
+ if (!entry?.approved || entry.character !== id || !/^\/models\/skins\/[a-z0-9-]+\.glb$/.test(entry.model || '')) throw new Error(`${skinId}: skin indisponível para ${id}`);
+ const file = path.join(publicDir, entry.model.slice(1));
+ const bytes = fs.readFileSync(file);
+ if (hash(bytes) !== entry.sha256 || bytes.length !== entry.bytes) throw new Error(`${skinId}: bytes ou SHA divergentes`);
+ const model = await glb(file);
+ const ownClips = {};
+ for (const state of STATES) {
+ const clip = model.animations.find((item) => item.name === (entry.animationNames?.[state] || state));
+ if (clip) ownClips[state] = clip;
+ }
+ if (entry.rigCompatibleWith !== id && STATES.slice(0, 8).some((state) => !ownClips[state])) throw new Error(`${skinId}: faltam animações`);
+ runtime.G.__seedSkin(skinId, { character: id, model: model.scene,
+ clips: entry.rigCompatibleWith === id ? null : ownClips, gripProfile: entry.gripProfile, metalFinish: entry.metalFinish });
+ loadedSkins.add(skinId);
+ }
+ }
+ return { seed, skins };
+}
diff --git a/tools/eval/character-model-node.mjs b/tools/eval/character-model-node.mjs
new file mode 100644
index 0000000000..5596187761
--- /dev/null
+++ b/tools/eval/character-model-node.mjs
@@ -0,0 +1,65 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { tmpdir } from 'node:os';
+import { pathToFileURL } from 'node:url';
+
+function stripTextures(bytes) {
+ let json, bin;
+ for (let offset = 12; offset < bytes.length;) {
+ const size = bytes.readUInt32LE(offset), type = bytes.readUInt32LE(offset + 4);
+ if (type === 0x4e4f534a) json = JSON.parse(bytes.subarray(offset + 8, offset + 8 + size));
+ if (type === 0x004e4942) bin = bytes.subarray(offset + 8, offset + 8 + size);
+ offset += 8 + size;
+ }
+ if (!json) throw new Error('GLB sem JSON');
+ delete json.images; delete json.textures; delete json.samplers;
+ json.materials = json.materials?.map((material) => ({ name: material.name,
+ pbrMetallicRoughness: { baseColorFactor: [1, 1, 1, 1], metallicFactor: 0, roughnessFactor: 1 } }));
+ const pad = (buffer, fill = 0) => Buffer.concat([buffer, Buffer.alloc((4 - buffer.length % 4) % 4, fill)]);
+ const jb = pad(Buffer.from(JSON.stringify(json)), 32), bb = pad(bin || Buffer.alloc(0));
+ const result = Buffer.alloc(28 + jb.length + bb.length);
+ result.writeUInt32LE(0x46546c67, 0); result.writeUInt32LE(2, 4); result.writeUInt32LE(result.length, 8);
+ result.writeUInt32LE(jb.length, 12); result.writeUInt32LE(0x4e4f534a, 16); jb.copy(result, 20);
+ result.writeUInt32LE(bb.length, 20 + jb.length); result.writeUInt32LE(0x004e4942, 24 + jb.length); bb.copy(result, 28 + jb.length);
+ return result;
+}
+
+export async function createCharacterRuntime(root, source) {
+ const publicDir = path.join(root, 'public');
+ const workDir = fs.mkdtempSync(path.join(tmpdir(), 'character-node-'));
+ const depDir = path.join(workDir, 'deps');
+ fs.mkdirSync(depDir);
+ const cleanup = () => fs.rmSync(workDir, { recursive: true, force: true });
+ process.once('exit', cleanup);
+ const depCache = new Map();
+ const rewrite = (dir) => (text) => text.replace(/from '([^']+)'/g, (all, specifier) =>
+ specifier === 'three' ? `from '${pathToFileURL(path.join(publicDir, 'vendor/three.module.js'))}'`
+ : specifier.startsWith('three/') ? `from '${pathToFileURL(path.join(publicDir, 'vendor', specifier.slice(6)))}'`
+ : specifier.startsWith('.') ? `from '${dependency(specifier, dir)}'` : all);
+ function dependency(rel, fromDir) {
+ const file = path.resolve(fromDir, rel);
+ if (!file.startsWith(`${publicDir}${path.sep}`)) throw new Error(`dependência fora de public/: ${rel}`);
+ const key = path.relative(publicDir, file);
+ if (!depCache.has(key)) {
+ const dst = path.join(depDir, key.replace(/[/.]/g, '_') + '.mjs');
+ fs.writeFileSync(dst, rewrite(path.dirname(file))(fs.readFileSync(file, 'utf8')));
+ depCache.set(key, pathToFileURL(dst).href);
+ }
+ return depCache.get(key);
+ }
+ const jsDir = path.join(publicDir, 'js');
+ const modelPath = path.join(workDir, 'model.mjs');
+ fs.writeFileSync(modelPath, rewrite(jsDir)(source)
+ + '\nexport function __seed(id, scene, clips, refs = {}, origin = null){_base.set(id,scene);if(origin)_bodyOrigins.set(scene,origin);_clips=clips;_clipsByChar[id]=clips;for(const name of Object.keys(refs)) if(clips[name]) marcarRef(clips[name],refs[name]);}\n'
+ + 'export function __origin(id){return _bodyOrigins.get(_base.get(id)) || null;}\n'
+ + 'export function __seedSkin(id, entry){_skins.set(id,entry);}\n'
+ + `export { setWeaponModel } from '${dependency('./weapons.js', jsDir)}';\n`);
+ const { THREE, CHARACTERS } = await import(pathToFileURL(path.join(root, 'tools/eval/harness.mjs')));
+ const { GLTFLoader } = await import(pathToFileURL(path.join(publicDir, 'vendor/addons/loaders/GLTFLoader.js')));
+ const G = await import(pathToFileURL(modelPath));
+ const load = async (file) => {
+ const bytes = stripTextures(fs.readFileSync(path.isAbsolute(file) ? file : path.join(publicDir, file)));
+ return new GLTFLoader().parseAsync(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), '');
+ };
+ return { THREE, CHARACTERS, G, load, cleanup };
+}
diff --git a/tools/eval/chupa-support-contact.test.mjs b/tools/eval/chupa-support-contact.test.mjs
new file mode 100644
index 0000000000..380c528479
--- /dev/null
+++ b/tools/eval/chupa-support-contact.test.mjs
@@ -0,0 +1,63 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import path from 'node:path';
+import test from 'node:test';
+import { pathToFileURL } from 'node:url';
+import { createCharacterRuntime } from './character-model-node.mjs';
+import { characterAssets } from './character-assets-node.mjs';
+import { posedSurfaceLandmark } from './posed-surface-landmark.mjs';
+
+const root = process.env.ITEM153_GAME_ROOT || process.cwd();
+const packRoot = process.env.STUDIO_PACK_ROOT;
+// Lampião, item 153: left palm to the handguard mesh, at most 2 cm in menu and 3P.
+const SUPPORT_MAX_M = 0.02;
+
+async function measure(mutated) {
+ const file = process.env.ITEM153_SOURCE_FILE || path.join(root, 'public/js/glbchars.js');
+ let source = fs.readFileSync(file, 'utf8');
+ if (mutated) {
+ const current = 'if (fit.previewSupport) this.ikL.fore.copy(fit.previewSupport);';
+ assert.ok(source.includes(current), 'mutation must target the live assignment');
+ source = source.replace(current, 'if (this.previewWalkfire && fit.previewSupport) this.ikL.fore.copy(fit.previewSupport);');
+ }
+ const rt = await createCharacterRuntime(root, source);
+ try {
+ const { G, THREE } = rt;
+ await (await characterAssets(root, rt, packRoot)).seed('chupa-cabra');
+ G.setWeaponModel('ak', (await rt.load('models/weapons/ak.glb')).scene);
+ const { CHARACTER_PALM_FITS } = await import(pathToFileURL(path.join(root, 'public/js/data/character-palm-fits.js')));
+ const fit = CHARACTER_PALM_FITS['chupa-cabra'];
+ const result = {};
+ for (const preview of [true, false]) {
+ const b = G.buildCharacterModel(rt.CHARACTERS.find(c => c.id === 'chupa-cabra'), { weaponId: 'ak', weaponSkinId: 'ouro-ak', preview });
+ assert.ok(b?.ctrl?.palmFit, 'the approved rig and AK must be present');
+ b.group.rotation.y = preview ? -0.4 : 0;
+ let max = 0;
+ for (let i = 1; i <= 240; i++) {
+ b.ctrl.update(1 / 60, 0, false, 0);
+ if (i % 4) continue;
+ b.group.updateMatrixWorld(true);
+ const gun = b.ctrl.ikL.gun, scale = gun.scale.x || 1;
+ const origin = gun.localToWorld(new THREE.Vector3().fromArray(fit.previewSupportProbe).divideScalar(scale));
+ const direction = new THREE.Vector3(0, 1, 0).transformDirection(gun.matrixWorld);
+ const hit = new THREE.Raycaster(origin, direction).intersectObject(gun, true)[0];
+ assert.ok(hit, 'the handguard probe must hit the AK mesh');
+ const palm = posedSurfaceLandmark(b.ctrl.tpMount.model, { ...fit.left, mesh: fit.mesh, skinSha256: fit.skinSha256, source: 'Lampião item 153' });
+ assert.ok(palm, 'the approved palm landmark must match the rig');
+ max = Math.max(max, palm.distanceTo(hit.point));
+ }
+ result[preview ? 'jogar' : '3p'] = max;
+ }
+ return result;
+ } finally { rt.cleanup(); }
+}
+
+test('Chupa AK support reaches the handguard in both poses and rejects the old 3P target', async () => {
+ assert.ok(packRoot && fs.existsSync(packRoot), 'STUDIO_PACK_ROOT must point to the verified Studio packs');
+ const actual = await measure(false);
+ for (const [context, distance] of Object.entries(actual)) {
+ assert.ok(distance <= SUPPORT_MAX_M, `${context}: palm to handguard ${distance.toFixed(4)} m`);
+ }
+ const mutant = await measure(true);
+ assert.ok(mutant['3p'] > SUPPORT_MAX_M, `3P mutant escaped: ${mutant['3p']} m`);
+});
diff --git a/tools/eval/emote-partida-check.mjs b/tools/eval/emote-partida-check.mjs
index 9ecbf766b7..b2404649a5 100755
--- a/tools/eval/emote-partida-check.mjs
+++ b/tools/eval/emote-partida-check.mjs
@@ -27,9 +27,10 @@
Uso: BASE=http://127.0.0.1:9351 node tools/eval/emote-partida-check.mjs
============================================================================ */
-import { execSync, spawn } from 'node:child_process';
+import { execSync } from 'node:child_process';
import { pathToFileURL } from 'node:url';
import { EMOTE_IDS } from '../../public/js/data/emote-catalog.js';
+import { subirServe } from './lib/serve-eval.mjs';
const BASE_EXTERNA = process.env.BASE;
const PORTA = process.env.PORTA || '9352';
@@ -49,16 +50,7 @@ const gRoot = execSync('npm root -g').toString().trim();
const pw = await import(pathToFileURL(`${gRoot}/playwright/index.js`).href);
const chromium = pw.chromium || pw.default?.chromium;
-const servidor = BASE_EXTERNA ? null : spawn('node', ['tools/eval/serve.mjs', PORTA], { stdio: 'ignore' });
-process.on('exit', () => servidor?.kill());
-if (servidor) {
- let pronto = false;
- for (let i = 0; i < 60 && !pronto; i++) {
- try { pronto = (await fetch(BASE)).ok; } catch { /* subindo */ }
- if (!pronto) await new Promise((r) => setTimeout(r, 500));
- }
- if (!pronto) throw new Error(`servidor não respondeu em ${BASE}`);
-}
+const servidor = BASE_EXTERNA ? null : await subirServe(PORTA, { url: BASE });
const STUB = 'export default {};export const createHotContext=()=>({accept(){},dispose(){},prune(){},on(){},off(){},send(){},invalidate(){},data:{}});'
+ 'export const updateStyle=()=>{};export const removeStyle=()=>{};export const injectQuery=(u)=>u;export class ErrorOverlay{}';
diff --git a/tools/eval/emotes-check.mjs b/tools/eval/emotes-check.mjs
index 1ff3cea39d..64c8e799a0 100755
--- a/tools/eval/emotes-check.mjs
+++ b/tools/eval/emotes-check.mjs
@@ -40,8 +40,9 @@
Uso: BASE=http://127.0.0.1:9321 node tools/eval/emotes-check.mjs
============================================================================ */
-import { execSync, spawn } from 'node:child_process';
+import { execSync } from 'node:child_process';
import { pathToFileURL } from 'node:url';
+import { subirServe } from './lib/serve-eval.mjs';
const BASE_EXTERNA = process.env.BASE;
const PORTA = process.env.PORTA || '9342';
@@ -60,16 +61,7 @@ const gRoot = execSync('npm root -g').toString().trim();
const pw = await import(pathToFileURL(`${gRoot}/playwright/index.js`).href);
const chromium = pw.chromium || pw.default?.chromium;
-const servidor = BASE_EXTERNA ? null : spawn('node', ['tools/eval/serve.mjs', PORTA], { stdio: 'ignore' });
-process.on('exit', () => servidor?.kill());
-if (servidor) {
- let pronto = false;
- for (let i = 0; i < 60 && !pronto; i++) {
- try { pronto = (await fetch(BASE)).ok; } catch { /* subindo */ }
- if (!pronto) await new Promise((r) => setTimeout(r, 500));
- }
- if (!pronto) throw new Error(`servidor não respondeu em ${BASE}`);
-}
+const servidor = BASE_EXTERNA ? null : await subirServe(PORTA, { url: BASE });
const STUB = 'export default {};export const createHotContext=()=>({accept(){},dispose(){},prune(){},on(){},off(){},send(){},invalidate(){},data:{}});'
+ 'export const updateStyle=()=>{};export const removeStyle=()=>{};export const injectQuery=(u)=>u;export class ErrorOverlay{}';
diff --git a/tools/eval/entrada-check.mjs b/tools/eval/entrada-check.mjs
index 055b03bfe8..5b851e3633 100644
--- a/tools/eval/entrada-check.mjs
+++ b/tools/eval/entrada-check.mjs
@@ -26,8 +26,9 @@
Uso: node tools/eval/entrada-check.mjs [--mutante=sem-guarda] [--porta=8131]
============================================================================ */
-import { execSync, spawn } from 'node:child_process';
+import { execSync } from 'node:child_process';
import { pathToFileURL } from 'node:url';
+import { subirServe } from './lib/serve-eval.mjs';
const arg = (nome) => (process.argv.find((a) => a.startsWith(`--${nome}=`)) || '').split('=')[1] || '';
const MUT = arg('mutante');
@@ -38,16 +39,8 @@ const gRoot = execSync('npm root -g').toString().trim();
const _pw = await import(pathToFileURL(`${gRoot}/playwright/index.js`).href);
const chromium = _pw.chromium || _pw.default?.chromium;
-const srv = spawn('node', ['tools/eval/serve.mjs', PORTA], { stdio: 'ignore' });
-process.on('exit', () => srv.kill());
-const vivo = async () => {
- for (let i = 0; i < 60; i++) {
- try { if ((await fetch(BASE)).ok) return true; } catch { /* subindo */ }
- await new Promise((r) => setTimeout(r, 500));
- }
- return false;
-};
-if (!(await vivo())) { console.log(` \x1b[31m✗\x1b[0m ENTRADA1 servidor não subiu na ${PORTA} (porta ocupada?)`); process.exit(1); }
+let srv;
+try { srv = await subirServe(PORTA, { url: BASE }); } catch (e) { console.log(` \x1b[31m✗\x1b[0m ENTRADA1 ${e.message}`); process.exit(1); }
const browser = await chromium.launch({ args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--mute-audio'] });
const page = await browser.newPage({ viewport: { width: 1280, height: 720 } });
diff --git a/tools/eval/escala-lajes-baseline.mjs b/tools/eval/escala-lajes-baseline.mjs
new file mode 100644
index 0000000000..4d5e84f1f0
--- /dev/null
+++ b/tools/eval/escala-lajes-baseline.mjs
@@ -0,0 +1,47 @@
+import { createHash } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+
+export const baseline = {
+ staging: 'b856a6f4c250f761b4754f628f4208c99a0be12c',
+ fontes: {
+ mapa: '2f9276457a9933ff11060da957ea812ce197094ac801e63a6e0dc7f7bb60780d',
+ arquitetura: 'a4daf5e1ea25a3a6434dbe8a9ff017d6cb2119fc831d0cf10fd3282bfc562f16',
+ },
+ casas: [
+ [-9, -4.5, 7.6, 7, 3.1], [-9, -11, 7.6, 6, 3.1], [-9, -17, 7.6, 6, 3.1],
+ [-9, 4.5, 7.6, 7, 3.1], [-9, 11, 7.6, 6, 3.1], [-9, 17, 7.6, 6, 3.1],
+ [9, -4.5, 7.6, 7, 3.1], [9, -11, 7.6, 6, 3.1], [9, -17, 7.6, 6, 3.1],
+ [9, 4.5, 7.6, 7, 3.1], [9, 11, 7.6, 6, 3.1], [9, 17, 7.6, 6, 3.1],
+ [-17.85, -4.5, 6, 7, 6.12], [-17.875, -11, 6, 6, 9.12], [-17.9, -17, 6, 6, 6.12],
+ [-17.85, 4.5, 6, 7, 6.12], [-17.875, 11, 6, 6, 9.12], [-17.9, 17, 6, 6, 6.12],
+ [17.85, -4.5, 6, 7, 6.12], [17.875, -11, 6, 6, 9.12], [17.9, -17, 6, 6, 6.12],
+ [17.85, 4.5, 6, 7, 6.12], [17.875, 11, 6, 6, 9.12], [17.9, 17, 6, 6, 6.12],
+ [-3.1, -11.375, 4.2, 5.75, 6.12], [-3.1, -17.125, 4.2, 5.75, 6.42],
+ [-3.1, 11.375, 4.2, 5.75, 6.12], [-3.1, 17.125, 4.2, 5.75, 6.42],
+ [3.1, -11.375, 4.2, 5.75, 6.12], [3.1, -17.125, 4.2, 5.75, 6.42],
+ [3.1, 11.375, 4.2, 5.75, 6.12], [3.1, 17.125, 4.2, 5.75, 6.42],
+ ],
+};
+
+const chave = (xs) => xs.map((n) => Number(n.toFixed(6))).join(',');
+
+export function fontesAtuais() {
+ const hash = (path) => createHash('sha256').update(readFileSync(new URL(path, import.meta.url))).digest('hex');
+ return { mapa: hash('../../public/js/map_lajes_authored.js'), arquitetura: hash('../../public/js/lajes_houses.js') };
+}
+
+export function comparaBaseline(casas, fontes) {
+ if (fontes.mapa !== baseline.fontes.mapa || fontes.arquitetura !== baseline.fontes.arquitetura)
+ return { ok: false, motivo: 'fontes do mapa diferem do staging documentado' };
+ const esperado = new Map(baseline.casas.map(([x, z, w, d, h]) => [chave([x, z, w, d, 0]), h]));
+ if (casas.length !== esperado.size) return { ok: false, motivo: 'inventário de casas mudou' };
+ for (const c of casas) {
+ const id = chave([(c.minX + c.maxX) / 2, (c.minZ + c.maxZ) / 2, c.maxX - c.minX, c.maxZ - c.minZ, c.minY]);
+ const altura = c.maxY - c.minY, anterior = esperado.get(id);
+ if (anterior == null || !Number.isFinite(altura)) return { ok: false, motivo: `casa inesperada ou duplicada: ${id}` };
+ const valida = anterior === 3.1 ? altura >= 2.7 - 1e-9 && altura <= 3.1 + 1e-9 : Math.abs(altura - anterior) <= 1e-9;
+ if (!valida) return { ok: false, motivo: `altura divergiu do baseline: ${id} (${altura})` };
+ esperado.delete(id);
+ }
+ return { ok: esperado.size === 0, motivo: esperado.size ? 'casa ausente' : 'objetos e fontes correspondem ao staging' };
+}
diff --git a/tools/eval/escala-lajes-check.mjs b/tools/eval/escala-lajes-check.mjs
new file mode 100644
index 0000000000..474229dfde
--- /dev/null
+++ b/tools/eval/escala-lajes-check.mjs
@@ -0,0 +1,100 @@
+/* escala-lajes-check.mjs — ESCALA HUMANA DAS CASAS DO FY_LAJES (#1127, BUG-55).
+ O dono reclamou da escala dos barracos do Lajes no mesmo teste do Córrego (17/08), e a
+ `escala-favela-check` só mede o Córrego: lá a porta é cluster da malha de vão e as
+ fileiras têm x fixo. No Lajes V4 a casa sai do `home()` de `lajes_houses.js`, com
+ porta própria (tag `lajesDoor`) e collider marcado `casa: 'lajes-unidade-terrea'`.
+
+ REFERÊNCIA: a receita da V4 (docs/maps/LAJES-V4-ESCALA.md, removido da árvore em
+ 7dd1c2bba e lido no 70f524937): folha de porta 2,10 m; térreo 0,05 + 2,60 + 0,15 =
+ 2,80 m; segundo pavimento com passo 2,75 m. O teto de 2,80 m laje-a-laje é o mesmo do
+ ESC2 do Córrego. O documento chama esses números de valor inicial, e a régua mede
+ contra eles sem decidir sozinha a geometria: o H do Lajes amarra plataformas, pontes e
+ pulos da jogabilidade pelas lajes (#1113), então baixar o pé-direito é decisão do dono.
+
+ ESCL1 PORTA: toda malha `lajesDoor` com altura 2,00–2,20 m e base ≤ 0,15 m.
+ ESCL2 TÉRREO: casa de um pavimento (collider ≤ 4,5 m) com altura total 2,70–2,90 m.
+ ESCL3 ANDAR: não medido; o mundo não identifica lajes de cada pavimento por casa.
+ ESCL1 e ESCL2 ficam vermelhas sem alvo mensurável; ESCL3 não é asserção.
+
+ REPRODUZ: node tools/eval/escala-lajes-check.mjs
+ MUTANTE: --mutante=porta-ana (portas com altura ×0,5) → ESCL1
+ --mutante=casa-alta (uma casa acima do baseline) → BASELINE
+ SIMULAÇÃO: --simula=receita-v4 (alturas hipotéticas; não mede lajes) → precisa passar */
+import { THREE, initTextures, bootGame } from './harness.mjs';
+import { mutanteDetectado } from './escala-lajes-mutante.mjs';
+import { baseline, comparaBaseline, fontesAtuais } from './escala-lajes-baseline.mjs';
+
+const arg = (nome) => (process.argv.find((a) => a.startsWith(`--${nome}=`)) || '').split('=')[1] || null;
+const mutante = arg('mutante'), simula = arg('simula');
+if (mutante && !['porta-ana', 'casa-alta'].includes(mutante)) { console.error(`mutante desconhecido: ${mutante}`); process.exit(78); }
+if (simula && simula !== 'receita-v4') { console.error(`simulação desconhecida: ${simula}`); process.exit(78); }
+
+const PORTA_MIN = 2.00, PORTA_MAX = 2.20;
+const TERREO_MIN = 2.70, TERREO_MAX = 2.90;
+const ANDAR_UNICO = 4.5;
+
+const game = bootGame('lajes', { textures: initTextures(), ctf: true, seed: 13007 });
+const world = game.world;
+
+const portas = [];
+world.root.traverse((o) => { if (o.isMesh && o.userData.lajesDoor) portas.push(o); });
+if (mutante === 'porta-ana') for (const p of portas) p.scale.y *= 0.5;
+world.root.updateMatrixWorld(true);
+
+const casas = world.colliders.filter((c) => c.casa === 'lajes-unidade-terrea');
+const fontes = fontesAtuais();
+const antesMutante = comparaBaseline(casas, fontes);
+if (mutante === 'casa-alta' && antesMutante.ok) {
+ const alvo = casas.find((c) => Math.abs((c.minX + c.maxX) / 2 + 9) < 1e-6 && Math.abs((c.minZ + c.maxZ) / 2 + 4.5) < 1e-6);
+ if (alvo) alvo.maxY = alvo.minY + 3.11;
+}
+const comparacao = comparaBaseline(casas, fontes);
+const cm = (x) => Math.round(x * 100) / 100;
+let alturas = casas.map((c) => Number((c.maxY - c.minY).toFixed(6)));
+if (simula === 'receita-v4') alturas = alturas.map((h) => {
+ const andares = Math.max(1, Math.round((h - 0.12) / 3));
+ return cm(2.80 + (andares - 1) * 2.75);
+});
+
+const caixa = new THREE.Box3();
+const medidas = portas.map((p) => { caixa.setFromObject(p); return { base: cm(caixa.min.y), h: cm(caixa.max.y - caixa.min.y) }; });
+const portasOk = medidas.filter((m) => m.base <= 0.15 && m.h >= PORTA_MIN && m.h <= PORTA_MAX);
+
+const terreas = alturas.filter((h) => h <= ANDAR_UNICO);
+const terreasOk = terreas.filter((h) => h >= TERREO_MIN && h <= TERREO_MAX);
+
+const niveis = [...new Set(alturas)].sort((a, b) => a - b);
+const passos = niveis.slice(1).map((n, i) => Number((n - niveis[i]).toFixed(6)));
+
+const fmt = (x) => (x == null || !isFinite(x)) ? '—' : x.toFixed(2).replace('.', ',');
+const fmtPasso = (x) => String(x).replace('.', ',');
+const distintos = (xs) => [...new Set(xs)].sort((a, b) => a - b).map(fmt).join(' · ');
+console.log(`portas: ${medidas.length} (ok ${portasOk.length}) · alturas ${distintos(medidas.map((m) => m.h))} m · bases ${distintos(medidas.map((m) => m.base))} m`);
+console.log(`casas: ${casas.length} · alturas ${distintos(alturas)} m · térreas ${terreas.length} (ok ${terreasOk.length})`);
+console.log(`alturas distintas: ${niveis.map(fmtPasso).join(' · ')} m · diferenças entre casas (informativas) ${passos.map(fmtPasso).join(' · ') || '—'} m`);
+
+const checks = [
+ ['ESCL1 porta 2,00–2,20 m com base no piso',
+ medidas.length >= 8 && portasOk.length === medidas.length,
+ medidas.length < 8 ? `${medidas.length} portas encontradas — régua sem alvo` : `${portasOk.length}/${medidas.length} na faixa`],
+ ['ESCL2 casa térrea com 2,70–2,90 m (receita V4: 2,80)',
+ terreas.length >= 4 && terreasOk.length === terreas.length,
+ terreas.length < 4 ? `${terreas.length} casas térreas — régua sem alvo` : `${terreasOk.length}/${terreas.length} na faixa`],
+];
+
+for (const [nome, ok, det] of checks) console.log(`${ok ? '✓' : '✗'} ${nome} — ${det}`);
+console.log('? ESCL3 não medido — lajes de cada pavimento não identificadas por casa');
+console.log(`BASELINE staging ${baseline.staging}: ${comparacao.ok ? 'correspondente' : 'divergente'} — ${comparacao.motivo}`);
+const efetivos = [checks[0][1], checks[1][1] || comparacao.ok, comparacao.ok];
+const falhas = efetivos.filter((ok) => !ok).length;
+const portaDetectada = mutante === 'porta-ana' && mutanteDetectado(efetivos, medidas.length);
+const casaDetectada = mutante === 'casa-alta' && antesMutante.ok && !comparacao.ok && comparacao.motivo.startsWith('altura divergiu') && efetivos[0];
+if (portaDetectada || casaDetectada) {
+ console.log(`ESCALA-LAJES MUTANTE DETECTADO: ${mutante}`);
+} else if (falhas) {
+ console.error(`ESCALA-LAJES FALHA: ${falhas}/${efetivos.length}${mutante ? ` (mutante ${mutante} sem detecção válida)` : ''}${simula ? ` (simulação ${simula})` : ''}`);
+ process.exitCode = 1;
+} else if (mutante) {
+ console.error(`MUTANTE ${mutante} sobreviveu.`);
+ process.exitCode = 1;
+} else console.log(`ESCALA-LAJES OK (ESCL3 não medido)${simula ? ` (simulação ${simula})` : ''}`);
diff --git a/tools/eval/escala-lajes-contract.test.mjs b/tools/eval/escala-lajes-contract.test.mjs
new file mode 100644
index 0000000000..5db4d72ff1
--- /dev/null
+++ b/tools/eval/escala-lajes-contract.test.mjs
@@ -0,0 +1,112 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { spawnSync } from 'node:child_process';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { executaMutante, mutanteDetectado } from './escala-lajes-mutante.mjs';
+import { baseline, comparaBaseline } from './escala-lajes-baseline.mjs';
+
+test('baseline exige correspondência por objeto e rejeita agravamentos', () => {
+ const casas = () => baseline.casas.map(([x, z, w, d, h]) => ({
+ minX: x - w / 2, maxX: x + w / 2, minZ: z - d / 2, maxZ: z + d / 2, minY: 0, maxY: h,
+ }));
+ const compara = (cs, hashes = baseline.fontes) => comparaBaseline(cs, hashes).ok;
+ assert.equal(compara(casas()), true);
+ for (const altura of [2.7, 2.9, 3.1]) {
+ const cs = casas(); cs[0].maxY = altura;
+ assert.equal(compara(cs), true, `altura permitida ${altura}`);
+ }
+ for (const altura of [2.69, 3.1001, 3.11, 4.6]) {
+ const cs = casas(); cs[0].maxY = altura;
+ assert.equal(compara(cs), false, `altura inválida ${altura}`);
+ }
+ const alturaAndar = casas(); alturaAndar[12].maxY += 0.01;
+ assert.equal(compara(alturaAndar), false);
+ const trocadas = casas(); [trocadas[12].maxY, trocadas[13].maxY] = [trocadas[13].maxY, trocadas[12].maxY];
+ assert.equal(compara(trocadas), false);
+ const deslocada = casas(); deslocada[0].minX += 0.01; deslocada[0].maxX += 0.01;
+ assert.equal(compara(deslocada), false);
+ const removida = casas(); removida.pop();
+ assert.equal(compara(removida), false);
+ const duplicada = casas(); duplicada[1] = { ...duplicada[0] };
+ assert.equal(compara(duplicada), false);
+ const adicionada = casas(); adicionada.push({ ...adicionada[0], minX: 90, maxX: 97.6 });
+ assert.equal(compara(adicionada), false);
+ assert.equal(compara(casas(), { ...baseline.fontes, arquitetura: 'alterada' }), false);
+});
+
+test('apenas ESCL1 com alvo presente pode comprovar o mutante', () => {
+ assert.equal(mutanteDetectado([false, true, true], 8), true);
+ assert.equal(mutanteDetectado([true, false, true], 8), false);
+ assert.equal(mutanteDetectado([false, false, true], 8), false);
+ assert.equal(mutanteDetectado([false, true, false], 8), false);
+ assert.equal(mutanteDetectado([false, true, true], 0), false);
+ assert.equal(mutanteDetectado([true, true, true], 8), false);
+});
+
+test('verificador real detecta os dois mutantes no mundo sintético', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'escala-mundo-'));
+ try {
+ const evalDir = join(dir, 'tools', 'eval'), jsDir = join(dir, 'public', 'js');
+ mkdirSync(evalDir, { recursive: true }); mkdirSync(jsDir, { recursive: true });
+ for (const file of ['escala-lajes-check.mjs', 'escala-lajes-mutante.mjs', 'escala-lajes-baseline.mjs'])
+ copyFileSync(new URL(file, import.meta.url), join(evalDir, file));
+ for (const file of ['map_lajes_authored.js', 'lajes_houses.js'])
+ copyFileSync(new URL(`../../public/js/${file}`, import.meta.url), join(jsDir, file));
+ const harness = (sobrevive, alturas = null, primeira = null) => `
+ import { baseline } from './escala-lajes-baseline.mjs';
+ export const THREE = { Box3: class { setFromObject(p) { this.min = {y: 0.04}; this.max = {y: 0.04 + 2.05 * p.scale.y}; } } };
+ export const initTextures = () => ({});
+ export function bootGame() {
+ const portas = Array.from({length: 8}, () => ({isMesh:true, userData:{lajesDoor:true}, scale:${sobrevive ? '{get y(){return 1}, set y(v){}}' : '{y:1}'}}));
+ const alturas = ${JSON.stringify(alturas)};
+ const primeira = ${JSON.stringify(primeira)};
+ const colliders = baseline.casas.map(([x,z,w,d,h],i) => ({casa:'lajes-unidade-terrea', minX:x-w/2, maxX:x+w/2, minZ:z-d/2, maxZ:z+d/2, minY:0, maxY:alturas ? alturas[i % alturas.length] : i === 0 && primeira !== null ? primeira : h}));
+ return {world:{colliders, root:{traverse:f=>portas.forEach(f), updateMatrixWorld(){}}}};
+ }`;
+ const checker = join(evalDir, 'escala-lajes-check.mjs');
+ writeFileSync(join(evalDir, 'harness.mjs'), harness(false));
+ const normal = spawnSync(process.execPath, [checker], { encoding: 'utf8' });
+ assert.equal(normal.status, 0, normal.stdout + normal.stderr);
+ assert.match(normal.stdout, /✗ ESCL2/); assert.match(normal.stdout, /\? ESCL3 não medido/);
+ assert.match(normal.stdout, /ESCALA-LAJES OK \(ESCL3 não medido\)/);
+ assert.match(normal.stdout, /diferenças entre casas \(informativas\) 3,02 · 0,3 · 2,7 m/);
+ assert.equal(executaMutante(checker, false, 'porta-ana'), true);
+ assert.equal(executaMutante(checker, false, 'casa-alta'), true);
+ writeFileSync(join(evalDir, 'harness.mjs'), harness(false, null, 2.9));
+ const melhoria = spawnSync(process.execPath, [checker], { encoding: 'utf8' });
+ assert.equal(melhoria.status, 0, melhoria.stdout + melhoria.stderr);
+ assert.match(melhoria.stdout, /\? ESCL3 não medido/);
+ assert.match(melhoria.stdout, /BASELINE staging .* correspondente/);
+ writeFileSync(join(evalDir, 'harness.mjs'), harness(true));
+ assert.equal(executaMutante(checker, false, 'porta-ana'), false);
+ for (const alturas of [
+ [3, 4, 6, 6.5, 9], [3, 5.5, 8, 9],
+ [3, 5.4], [3, 5.8], [3, 5.399], [3, 5.801], [3],
+ ]) {
+ writeFileSync(join(evalDir, 'harness.mjs'), harness(false, alturas));
+ const resultado = spawnSync(process.execPath, [checker], { encoding: 'utf8' });
+ assert.match(resultado.stdout, /\? ESCL3 não medido/, JSON.stringify(alturas));
+ assert.doesNotMatch(resultado.stdout, /[✓✗] ESCL3/, JSON.stringify(alturas));
+ assert.equal(resultado.status, 1, 'inventário não corresponde ao baseline');
+ }
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+});
+
+test('mutante exige conclusão comprovada e processo bem-sucedido', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'escala-mutante-'));
+ try {
+ const fixture = join(dir, 'fixture.mjs');
+ for (const [source, esperado] of [
+ ["console.log('ESCALA-LAJES MUTANTE DETECTADO: porta-ana')", true],
+ ["throw new Error('quebrou antes do fim')", false],
+ ["process.exit(0)", false],
+ ["console.log('ESCALA-LAJES MUTANTE DETECTADO: porta-ana'); process.exit(1)", false],
+ ["console.log('mutante sobreviveu')", false],
+ ]) {
+ writeFileSync(fixture, source);
+ assert.equal(executaMutante(fixture, false), esperado, source);
+ }
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+});
diff --git a/tools/eval/escala-lajes-mutante.mjs b/tools/eval/escala-lajes-mutante.mjs
new file mode 100644
index 0000000000..5cba704139
--- /dev/null
+++ b/tools/eval/escala-lajes-mutante.mjs
@@ -0,0 +1,25 @@
+import { spawnSync } from 'node:child_process';
+import { resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+export function mutanteDetectado(checks, portas) {
+ return portas >= 8 && checks.length === 3 && !checks[0] && checks.slice(1).every(Boolean);
+}
+
+export function executaMutante(script, exibir = true, tipo = 'porta-ana') {
+ const conclusao = `ESCALA-LAJES MUTANTE DETECTADO: ${tipo}`;
+ const resultado = spawnSync(process.execPath, [script, `--mutante=${tipo}`], { encoding: 'utf8' });
+ if (exibir) {
+ if (resultado.stdout) process.stdout.write(resultado.stdout);
+ if (resultado.stderr) process.stderr.write(resultado.stderr);
+ }
+ return !resultado.error && resultado.status === 0 && resultado.stdout.split(/\r?\n/).includes(conclusao);
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const tipo = process.argv[2] || 'porta-ana';
+ if (!['porta-ana', 'casa-alta'].includes(tipo) || !executaMutante(fileURLToPath(new URL('./escala-lajes-check.mjs', import.meta.url)), true, tipo)) {
+ console.error('Mutante não concluiu com detecção válida.');
+ process.exitCode = 1;
+ }
+}
diff --git a/tools/eval/external-surface-binding-check.mjs b/tools/eval/external-surface-binding-check.mjs
index a247be30bd..e7a83b03e1 100644
--- a/tools/eval/external-surface-binding-check.mjs
+++ b/tools/eval/external-surface-binding-check.mjs
@@ -114,7 +114,9 @@ for (const file of files) {
{
const { measureSurfaceFloors, FLOOR_MUTANTS } = await import('./fixtures/surface-floor-uv.mjs');
- const baseline = JSON.parse(readFileSync(new URL('./fixtures/surface-floor-uv-baseline.json', import.meta.url), 'utf8'));
+ const baselineFile = process.platform === 'linux' && process.arch === 'x64'
+ ? './fixtures/surface-floor-uv-baseline-linux-x64.json' : './fixtures/surface-floor-uv-baseline.json';
+ const baseline = JSON.parse(readFileSync(new URL(baselineFile, import.meta.url), 'utf8'));
const nominal = measureSurfaceFloors();
const preservation = JSON.stringify(nominal.signatures) === JSON.stringify(baseline.expected);
const pass = nominal.failed.length === 0 && preservation;
diff --git a/tools/eval/fixtures/surface-floor-uv-baseline-linux-x64.json b/tools/eval/fixtures/surface-floor-uv-baseline-linux-x64.json
new file mode 100644
index 0000000000..1a40f62931
--- /dev/null
+++ b/tools/eval/fixtures/surface-floor-uv-baseline-linux-x64.json
@@ -0,0 +1,54 @@
+{
+ "schema": "surface-floor-uv-baseline/1",
+ "sourceRef": "f86367b3d5b29c1adef34e5fae0ca9fd0ed05316",
+ "sourcePins": [
+ {
+ "path": "public/js/map_escadao.js",
+ "baseRef": "416af25b2b491d8ffb9d068659a2c715f57db80f",
+ "sha256": "73fc25eecd2f4befd18fc0007308b3c11f154b62b573820798b29bd5bcc16e81"
+ },
+ {
+ "path": "public/js/map_quebrada.js",
+ "baseRef": "416af25b2b491d8ffb9d068659a2c715f57db80f",
+ "sha256": "89b30c7dddce0350070fc16e86ffc73179fe374291783c53f80f3e72a902ae46"
+ }
+ ],
+ "method": "Actual MAPS builders/harness, deterministic RNG1153; TextureLoader boundary delayed; no renderer/GLB/pixel approval. Hash excludes only the UV attributes of the three identified private floors.",
+ "expected": {
+ "quebrada": {
+ "fallback": {
+ "nonTargetUVGeometryAndMaterials": "ebdc391c5ab58d9673dc76ff3d07da3d6ab43dd9b13288e1b698202f208a6039",
+ "contracts": "580faf1784fb521e84bf6239acc4ab60a519416fffffe8b21a8ab9ae35c867fd",
+ "sharedGroundTextures": "018cc4fb3a4aa4c65e413052cb994f576b44a538bfc886fa7a925d1cc6846b6d",
+ "nextRandom": 0.31385004660114646
+ }
+ },
+ "escadao": {
+ "fallback": {
+ "nonTargetUVGeometryAndMaterials": "2176d554d0ff7ec9b69fe09129052f9c6b7c603b256e2fc444fbb9fc2afc5fb3",
+ "contracts": "1abf68cb19f71bda2c4e773b5bf214dbd4e15443f50ff9dee09130f1103fd390",
+ "sharedGroundTextures": "018cc4fb3a4aa4c65e413052cb994f576b44a538bfc886fa7a925d1cc6846b6d",
+ "nextRandom": 0.5276809704955667
+ },
+ "external": {
+ "nonTargetUVGeometryAndMaterials": "46a465e17384ba0426c00cef5a1f5245e71fd253f6c02c7b2899e1715d5d8c82",
+ "contracts": "1abf68cb19f71bda2c4e773b5bf214dbd4e15443f50ff9dee09130f1103fd390",
+ "sharedGroundTextures": "018cc4fb3a4aa4c65e413052cb994f576b44a538bfc886fa7a925d1cc6846b6d",
+ "nextRandom": 0.5276809704955667
+ },
+ "changedSampler": {
+ "nonTargetUVGeometryAndMaterials": "00d590b19bba93b64852c4d8b6791e67ce3bd0905f6378c869bd439dcf17b40c",
+ "contracts": "1abf68cb19f71bda2c4e773b5bf214dbd4e15443f50ff9dee09130f1103fd390",
+ "sharedGroundTextures": "018cc4fb3a4aa4c65e413052cb994f576b44a538bfc886fa7a925d1cc6846b6d",
+ "nextRandom": 0.5276809704955667
+ }
+ }
+ },
+ "previousSourceRef": "9414b56cedcdc80383becb448b6fc621ab6a3339",
+ "curationBaseline": {
+ "reason": "Global artwork ownership and rebake changed rendered graffiti and its RNG consumption. Actual comparison against db0cdee3ff83edc113aa97b2b02475d000edd4d9 reproduced the prior baseline exactly; all non-art geometry/material bytes, physics contracts and shared ground texture hashes remain identical. The original full-scene signature check is retained.",
+ "sourceRef": "416af25b2b491d8ffb9d068659a2c715f57db80f",
+ "artMerge": "75815ad3cb2bfd392577e72851b970b5bb8d6a5a"
+ },
+ "platform": "linux-x64"
+}
diff --git a/tools/eval/invariants.mjs b/tools/eval/invariants.mjs
index c749dc72aa..9beb7c7d53 100644
--- a/tools/eval/invariants.mjs
+++ b/tools/eval/invariants.mjs
@@ -1802,10 +1802,10 @@ bloco('fonte', ['MOD1'], async () => {
Os tetos do CHR2 e do CHR6 saem do PRÓPRIO JOGO: 0,15 m é meia hitbox de cabeça
(glbchars.js:296, BoxGeometry(0.26, 0.30, 0.26)) e 0,98 de IoU é o mesmo patamar que a
PX2 já usa para silhueta de arma. Nenhum deles é palpite novo. */
-bloco('chars-mat', ['CHR1','CHR2','CHR3','CHR5','CHR5B','CHR6','CHR7'], async () => {
+bloco('chars-mat', ['CHR1','CHR2','CHR3','CHR3C','CHR5','CHR5B','CHR6','CHR7'], async () => {
const { data: j, error } = await REL_CHAR;
if (error) {
- for (const id of ['CHR1', 'CHR2', 'CHR3', 'CHR5', 'CHR6']) {
+ for (const id of ['CHR1', 'CHR2', 'CHR3', 'CHR3C', 'CHR5', 'CHR6']) {
skip(id, 'régua de personagem', 'char-probe.mjs: ' + error);
}
} else {
@@ -1903,6 +1903,25 @@ bloco('chars-mat', ['CHR1','CHR2','CHR3','CHR5','CHR5B','CHR6','CHR7'], async ()
+ `flutuando ${flutua.length} [${flutua.slice(0, 4).map((c) => `${c.id} +${ef.get(c.id).max.toFixed(3)}`).join(', ') || '-'}] `
+ '| o sinal separa dois defeitos diferentes: y<0 é pé DENTRO do chão, y>0 é boneco no ar');
+ /* CHR3C MALHA × PISO (#1117): com o pé plantado, rabo, capa ou quadril ainda cruzam o
+ chão. A sonda só grava `corpoPorPose` quando a bbox diverge do pé por mais de 5 cm,
+ e esse mesmo corte é o teto aqui, já somado ao offset de runtime da CHR3.
+ `--mutante=rabo-limpo` zera o corpo medido e tem que deixar a cláusula verde. */
+ const TOL3C = 0.05;
+ const raboLimpo = process.argv.includes('--mutante=rabo-limpo');
+ const cruzaPiso = [];
+ for (const c of P) for (const [pose, y] of Object.entries((c.C3 && c.C3.corpoPorPose) || {})) {
+ const efetivoCorpo = (raboLimpo ? 0 : y) + ((footOff[c.id] || {})[pose] || 0);
+ if (efetivoCorpo < -TOL3C) cruzaPiso.push({ id: c.id, pose, y: efetivoCorpo });
+ }
+ cruzaPiso.sort((a, b) => a.y - b.y);
+ put('CHR3C', 'malha × piso: com o pé no chão, nenhuma parte do corpo cruza o piso além de 0,05 m',
+ cruzaPiso.length === 0,
+ `${cruzaPiso.length} personagem×pose com o corpo abaixo do piso `
+ + `[${cruzaPiso.slice(0, 6).map((r) => `${r.id}/${r.pose} ${r.y.toFixed(3)}`).join(', ') || '-'}]`
+ + (raboLimpo ? ' | MUTANTE rabo-limpo: corpo zerado' : '')
+ + ' | é a malha (rabo, capa, quadril), não o pé: o pé fica na CHR3');
+
// ── CHR5 ACABAMENTO ───────────────────────────────────────────────────────
// Crítico só o que é sempre verificável (personagem tem geometria e material).
// A contagem de MAPAS é aviso porque, sem os GLB nesta árvore, o caminho medido é o
diff --git a/tools/eval/javaporcos-browser.mjs b/tools/eval/javaporcos-browser.mjs
index b6e67e334f..d2c238066f 100755
--- a/tools/eval/javaporcos-browser.mjs
+++ b/tools/eval/javaporcos-browser.mjs
@@ -2,6 +2,7 @@
import assert from 'node:assert/strict';
import { mkdirSync, writeFileSync } from 'node:fs';
import { chromium } from 'playwright';
+import { WAVE_COUNTS } from '../../public/js/javaporcos_ondas.js';
await import('./three-node.mjs');
const { MAX_ALIVE } = await import('../../public/js/mode_javaporcos.js');
@@ -88,7 +89,7 @@ try {
assert.equal(runtime.webgl2, true);
assert.match(runtime.gpu || '', /Apple M4 Pro|Metal/i);
assert.match(runtime.modeLabel || '', /HORDAS/);
- assert.match(runtime.objectiveLabel || '', /^ONDA 1 · /);
+ assert.ok(runtime.objectiveLabel?.startsWith(`ONDA 1/${WAVE_COUNTS.length} · `), runtime.objectiveLabel);
for (const file of ['javali_jovem.glb', 'javaporco_adulto.glb', 'matriarca_javali.glb', 'ariete_javali.glb']) {
assert.ok(glbs.some((url) => url.includes(file)), `${file} não carregou por HTTP 200`);
}
diff --git a/tools/eval/javaporcos-check.mjs b/tools/eval/javaporcos-check.mjs
index 42501e2dd8..b9c9ac4778 100644
--- a/tools/eval/javaporcos-check.mjs
+++ b/tools/eval/javaporcos-check.mjs
@@ -76,6 +76,7 @@ const {
alturaDoChao, espacializarJavaporco, registrarModeloJavaporco, criarInvasaoJavaporcos,
} = await import('../../public/js/mode_javaporcos.js');
const { encodeSnapshot, decodeSnapshot } = await import('../../public/js/netcodec.js');
+const { avaliarFimDaInvasao, vencedorPorLimite } = await import('../../public/js/javaporcos_partida.js');
const { MODELOS_JAVAPORCOS, varianteJavaporco } = await import('../../public/js/data/javaporcos_modelos.js');
const mutante = process.argv.find((arg) => arg.startsWith('--mutante='))?.split('=')[1] || '';
@@ -179,7 +180,7 @@ function mundoFalso({ horda = false } = {}) {
/* ------------------------------------------------------------------ jogo falso */
const VEL_BASE = 5.35; // PLAYER_SPEED do game.js; a faca tem MOVE_MUL 1,0
-function jogoFalso({ mundo = mundoFalso(), jogadorEm = [0, 0] } = {}) {
+function jogoFalso({ mundo = mundoFalso(), jogadorEm = [0, 0], settings } = {}) {
const sons = [], eventos = [], danos = [];
const player = {
isPlayer: true, team: 'E', alive: true, hp: 100, yaw: 0, def: { id: 'sertanejo' },
@@ -193,7 +194,7 @@ function jogoFalso({ mundo = mundoFalso(), jogadorEm = [0, 0] } = {}) {
};
const game = {
world: mundo, scene: new THREE.Scene(), camera: { position: new THREE.Vector3() },
- time: 0, state: 'live', online: false, dedicated: false, matchSeed: 7,
+ time: 0, state: 'live', online: false, dedicated: false, matchSeed: 7, settings,
player, bots: [semente], combatants: [player, semente],
el: { hud: { dataset: {}, append() {} } },
sfx: { javaporco(kind, vol = 1, pan = 0, delay = 0) { sons.push({ kind, vol, pan, delay }); return true; } },
@@ -233,12 +234,29 @@ const passo = (ctx, dt) => {
for (const bot of ctx.modo.boars) ctx.modo.updateBot(bot, dt);
};
const vivos = (modo) => modo.boars.filter((bot) => bot._boarId && bot.alive);
+/* A horda como o MODO a cria (menu → regrasDaInvasao → novaHorda), não a fábrica pura com o padrão
+ dela: o runtime rodou com maxWaves 0 enquanto as cláusulas de oito ondas passavam na fábrica. */
+const hordaDoModo = (seed, settings) => {
+ const { game, modo } = jogoFalso({ settings });
+ game.matchSeed = seed;
+ const horda = modo.novaHorda();
+ horda.mutante = mutante;
+ return horda;
+};
regra('um sobrevivente mantém a resistência; wipe encerra a invasão', () => {
const ctx=jogoFalso(), aliado={...ctx.player,isPlayer:false,pos:ctx.player.pos.clone()};
ctx.game.combatants.push(aliado);ctx.player.alive=false;
ctx.modo.update(.016);assert.equal(ctx.modo.state.winner,null);
aliado.alive=false;ctx.modo.update(.016);assert.equal(ctx.modo.state.winner,'J');
});
+regra('wipe no mesmo quadro do fim da última onda não dá vitória', () => {
+ const ctx = jogoFalso(), s = ctx.modo.state;
+ ctx.game._endRound = () => {};
+ s.wave = WAVE_COUNTS.length; s.phase = 'combat'; s.combatLeft = 0.01; s.remaining = 1;
+ ctx.player.alive = false;
+ ctx.modo.update(0.1);
+ assert.equal(s.winner, 'J');
+});
/* Bicho já fora da trilha: as cláusulas de rumo, comida e muro medem o comportamento na cidade. */
const soltar = (bots) => { for (const bot of bots) { bot._boarPasso = bot._boarPlano?.length || 0; bot._boarExplorarAte = 0; } };
/* 2,5 s de onda: a cadência base é um bicho a cada 0,18 s, então um quadro só não
@@ -262,11 +280,11 @@ regra('oito ondas gigantes: 24 na primeira, 150 na última, 618 no total', () =>
assert.ok(BOAR_HP.ariete >= 600, `ariete fraco demais para ser o peso da onda: ${BOAR_HP.ariete}`);
});
-regra('vinte sementes fecham as oito ondas, enchem o teto de 64 e nunca passam dele', () => {
+regra('vinte sementes fecham a sequência de ondas, enchem o teto de 64 e nunca passam dele', () => {
for (let seed = 1; seed <= 20; seed++) {
- const horda = criarHorda({ seed, mutante });
+ const horda = hordaDoModo(seed);
let pico = 0;
- for (let onda = 1; onda <= 8; onda++) {
+ for (let onda = 1; onda <= WAVE_COUNTS.length; onda++) {
iniciarOnda(horda);
let guarda = 0;
while (horda.phase === 'combat' && guarda++ < 40000) {
@@ -298,7 +316,7 @@ regra('as três frentes entram no rodízio e os IDs são estáveis', () => {
regra('as ondas reais alcançam todas as oito aparências', () => {
const horda = criarHorda({ seed: 319 }), vistas = new Set();
const pools = { jovem: ['javali_jovem','leitao_listrado'], adulto: ['javaporco_adulto','javaporco_malhado','javaporco_ruivo'], matriarca: ['matriarca_javali','javaporco_velho_cicatrizado'], ariete: ['ariete_javali'] };
- for(let onda=0;onda<8;onda++) {
+ for(let onda=0;onda0&&guarda++<10000) {
passoHorda(horda,.25);
@@ -312,9 +330,9 @@ regra('as ondas reais alcançam todas as oito aparências', () => {
assert.deepEqual([...vistas].sort(),Object.values(MODELOS_JAVAPORCOS).sort());
});
-regra('dois clientes fecham as oito ondas com o mesmo estado', () => {
+regra('dois clientes fecham a sequência de ondas com o mesmo estado', () => {
const clientes = [criarHorda({ seed: 551, mutante }), criarHorda({ seed: 551, mutante })];
- for (const horda of clientes) for (let onda = 0; onda < 8; onda++) {
+ for (const horda of clientes) for (let onda = 0; onda < WAVE_COUNTS.length; onda++) {
iniciarOnda(horda);
while (horda.phase === 'combat') {
passoHorda(horda, 0.25);
@@ -675,7 +693,7 @@ regra('a partir da onda 3 parte da horda entra pelo BECO e explora o quarteirão
});
regra('onda que não é limpa no relógio não trava: a próxima vem com as sobras vivas', () => {
- const horda = criarHorda({ seed: 31, mutante });
+ const horda = hordaDoModo(31);
iniciarOnda(horda);
let guarda = 0;
while (horda.wave === 1 && guarda++ < 2000) passoHorda(horda, 0.1);
@@ -686,7 +704,86 @@ regra('onda que não é limpa no relógio não trava: a próxima vem com as sobr
passoHorda(horda, 0.1);
if (horda.remaining && horda.alive.length >= horda.maxAlive) registrarAbate(horda, horda.alive[0].id, 'defensor');
}
- assert.equal(horda.winner, 'E', 'sobreviver à última onda no relógio não deu vitória');
+ for (let g = 0; g < 4000 && !horda.winner; g++) {
+ passoHorda(horda, 0.1);
+ for (const animal of [...horda.alive]) registrarAbate(horda, animal.id, 'defensor');
+ }
+ assert.equal(horda.winner, 'E', 'limpar a última onda não deu vitória');
+});
+
+regra('relógio descarta pendentes da onda intermediária e preserva vivos; última encerra no relógio ou limpa', () => {
+ const horda = hordaDoModo(33);
+ horda.maxAlive = 1;
+ iniciarOnda(horda);
+ passoHorda(horda, 1);
+ const vivo = horda.alive[0].id;
+ assert.ok(horda.remaining > 0);
+ horda.combatLeft = 0.1;
+ passoHorda(horda, 0.1);
+ assert.equal(horda.phase, 'prep');
+ assert.equal(horda.remaining, 0, 'pendentes não foram descartados no fim da onda');
+ assert.equal(horda.alive[0].id, vivo);
+ iniciarOnda(horda);
+ assert.equal(horda.remaining, WAVE_COUNTS[1]);
+ registrarAbate(horda, vivo, 'defensor');
+ passoHorda(horda, 1);
+ assert.match(horda.alive[0].id, /^2\./);
+ assert.equal(horda.alive.length, 1);
+ horda.wave = WAVE_COUNTS.length;
+ horda.combatLeft = 0.1;
+ passoHorda(horda, 0.1);
+ assert.equal(horda.winner, 'E');
+ const limpa = hordaDoModo(34);
+ limpa.wave = WAVE_COUNTS.length - 1;
+ iniciarOnda(limpa);
+ for (let i = 0; i < 4000 && !limpa.winner; i++) {
+ passoHorda(limpa, 0.1);
+ for (const animal of [...limpa.alive]) registrarAbate(limpa, animal.id, 'defensor');
+ }
+ assert.equal(limpa.winner, 'E');
+ assert.ok(limpa.combatLeft > 0);
+});
+
+regra('um quadro lento avança os relógios do modo pelo tempo real e preserva a cadência de spawn', () => {
+ const { game, modo } = jogoFalso({ jogadorEm: [60, 60] });
+ const horda = modo.state;
+ horda.mutante = '';
+ const atualizar = (dt, dtOnda) => {
+ game.time += dt;
+ modo.update(dt, dtOnda);
+ };
+ atualizar(0.05, 0.8);
+ assert.ok(Math.abs(horda.prepLeft - 11.2) < 1e-9, `preparo restante: ${horda.prepLeft} s`);
+ iniciarOnda(horda);
+ const inicioCombate = horda.combatLeft;
+ for (let quadro = 0; quadro < 25; quadro++) {
+ for (let passo = 0; passo < 3; passo++) atualizar(0.05, 0.05);
+ atualizar(0.05, 0.65);
+ if (quadro === 0) assert.equal(horda.spawnOrdinal, 1, 'spawn usou o tempo real em vez dos 200 ms simulados');
+ }
+ assert.ok(Math.abs(horda.combatLeft - (inicioCombate - 20)) < 1e-9,
+ `combate avançou ${inicioCombate - horda.combatLeft} s em 20 s reais`);
+ assert.ok(Math.abs(horda.clock - 20.8) < 1e-9, `tempo total da horda: ${horda.clock} s`);
+});
+
+regra('partida solo padrão termina na última onda e chama o fim da rodada; INFINITO continua', () => {
+ const ctx = jogoFalso({ jogadorEm: [60, 60] }), s = ctx.modo.state, fins = [];
+ ctx.game._endRound = (vencedor) => { fins.push(vencedor); ctx.game.state = 'roundEnd'; };
+ assert.equal(s.maxWaves, WAVE_COUNTS.length, `o modo nasceu com maxWaves ${s.maxWaves}`);
+ s.wave = WAVE_COUNTS.length - 1; s.phase = 'prep'; s.prepLeft = 0.1;
+ for (let i = 0; i < 4000 && ctx.game.state === 'live'; i++) {
+ passo(ctx, 0.1);
+ for (const animal of [...s.alive]) registrarAbate(s, animal.id, 'defensor');
+ if (s.winner && ctx.game.state === 'live') passo(ctx, 0.1);
+ }
+ assert.equal(s.winner, 'E', `a última onda não fechou: onda ${s.wave}, fase ${s.phase}`);
+ assert.deepEqual(fins, ['E']);
+ assert.ok(ctx.eventos.some((e) => e.k === 'HORDE_FINISHED' && e.wave === WAVE_COUNTS.length), 'HORDE_FINISHED não saiu');
+ const infinito = hordaDoModo(31, { javaporcos: { fim: 'infinito' } });
+ assert.equal(infinito.maxWaves, 0);
+ infinito.wave = WAVE_COUNTS.length; infinito.phase = 'prep';
+ assert.equal(iniciarOnda(infinito), true, 'INFINITO parou no fim da sequência');
+ assert.equal(infinito.wave, WAVE_COUNTS.length + 1);
});
regra('o relógio da partida esquenta a horda: aos 10 min ela vem mais rápido e mais forte que aos 2', () => {
@@ -825,6 +922,84 @@ regra('o HUD mostra a fúria e quantos javaporcos estão na rua', () => {
assert.ok(/LIXO \d+\/\d+/.test(texto), `HUD sem placar de lixo revirado: ${texto}`);
});
+regra('o HUD mostra o total desde a primeira onda e anuncia a última; INFINITO segue sem teto', () => {
+ const ctx = jogoFalso({ jogadorEm: [60, 60] }), s = ctx.modo.state;
+ const total = WAVE_COUNTS.length;
+ const hud = (modo = ctx.modo) => { modo.atualizaHud(true); return modo.hudTexto.textContent; };
+ assert.match(hud(), new RegExp(`^ONDA 1/${total} · PRÓXIMA ONDA EM 12s`));
+ iniciarOnda(s);
+ assert.match(hud(), new RegExp(`^ONDA 1/${total} · PRÓXIMA ONDA EM \\d+s · FALTAM ${WAVE_COUNTS[0]} · `));
+ s.wave = total - 1; s.phase = 'prep'; s.prepLeft = 12; s.remaining = 0;
+ assert.match(hud(), new RegExp(`^ONDA ${total - 1}/${total} · ÚLTIMA ONDA EM 12s`));
+ iniciarOnda(s);
+ assert.match(hud(), new RegExp(`^ONDA ${total}/${total} · ÚLTIMA ONDA · FALTAM ${WAVE_COUNTS.at(-1)} · SEGURE \\d+s · `));
+ s.remaining = 0;
+ assert.doesNotMatch(hud(), /FALTAM/, 'FALTAM deve sumir quando não há bicho por nascer');
+ const infinito = jogoFalso({ jogadorEm: [60, 60], settings: { javaporcos: { fim: 'infinito' } } }).modo;
+ infinito.state.wave = total; infinito.state.phase = 'prep';
+ assert.match(hud(infinito), new RegExp(`^ONDA ${total} · PRÓXIMA ONDA EM`));
+});
+
+regra('o resultado mostra SOBREVIVEU na vitória e a onda atual no wipe; INFINITO mantém o título antigo', () => {
+ const modo = jogoFalso({ jogadorEm: [60, 60] }).modo;
+ modo.state.wave = WAVE_COUNTS.length;
+ assert.equal(modo.roundResult('E').title, `SOBREVIVEU ${WAVE_COUNTS.length}/${WAVE_COUNTS.length}`);
+ modo.state.wave = 5;
+ assert.equal(modo.roundResult('J').title, `CAÍRAM NA ONDA 5/${WAVE_COUNTS.length}`);
+ assert.match(modo.roundResult('J').detail, /javaporcos abatidos/);
+ const infinito = jogoFalso({ jogadorEm: [60, 60], settings: { javaporcos: { fim: 'infinito' } } }).modo;
+ infinito.state.wave = 9;
+ assert.equal(infinito.roundResult('J').title, 'JAVAPORCOS VENCERAM');
+ assert.equal(infinito.fraseDoFim('J'), '');
+});
+
+regra('na disputa tripla só o time da onda recebe SOBREVIVEU no resultado', () => {
+ const modo = jogoFalso({ jogadorEm: [60, 60], settings: { javaporcos: { times: 3 } } }).modo;
+ modo.game._teamName = (team) => team;
+ modo.state.wave = WAVE_COUNTS.length;
+ assert.equal(modo.regras.times, 3);
+ modo.state.territorio = { E: 0.1, B: 0.5, J: 0.4 };
+ const vencedor = vencedorPorLimite(modo.state, modo.regras);
+ assert.equal(vencedor, 'B');
+ assert.doesNotMatch(modo.roundResult(vencedor).detail, /SOBREVIVEU/);
+ assert.match(modo.roundResult(vencedor).title, /VENCEU/);
+ assert.match(modo.roundResult('E').detail, new RegExp(`SOBREVIVEU ${WAVE_COUNTS.length}/${WAVE_COUNTS.length}`));
+ assert.doesNotMatch(modo.roundResult('draw').detail, /SOBREVIVEU/);
+});
+
+regra('na disputa tripla, CAÍRAM só aparece quando um wipe encerra a partida', () => {
+ const { modo, game, player } = jogoFalso({ settings: { javaporcos: { times: 3 } } });
+ const rival = { team: 'B', alive: true };
+ game.combatants.push(rival);
+ modo.state.wave = WAVE_COUNTS.length;
+ modo.state.territorio = { E: 0.2, B: 0.3, J: 0.5 };
+ const porTerritorio = vencedorPorLimite(modo.state, modo.regras);
+ assert.equal(porTerritorio, 'J');
+ assert.equal(modo.fraseDoFim(porTerritorio), '');
+ assert.equal(modo.roundResult(porTerritorio).title, 'JAVAPORCOS VENCERAM');
+ assert.doesNotMatch(modo.roundResult(porTerritorio).detail, /CAÍRAM/);
+
+ player.alive = false;
+ assert.equal(avaliarFimDaInvasao(modo.state, modo.regras, game.combatants), null);
+ assert.deepEqual(modo.state.eliminados, ['E']);
+ assert.equal(modo.fraseDoFim(porTerritorio), '');
+
+ rival.alive = false;
+ const porWipe = avaliarFimDaInvasao(modo.state, modo.regras, game.combatants);
+ assert.equal(porWipe, 'J');
+ assert.match(modo.roundResult(porWipe).detail, new RegExp(`^CAÍRAM NA ONDA ${WAVE_COUNTS.length}/${WAVE_COUNTS.length}`));
+});
+
+regra('wipe da partida na disputa tripla mantém CAÍRAM quando uma equipe é eliminada', () => {
+ const { modo, game, player } = jogoFalso({ settings: { javaporcos: { times: 3, wipe: 'partida' } } });
+ game.combatants.push({ team: 'B', alive: true });
+ modo.state.wave = 5;
+ player.alive = false;
+ const vencedor = avaliarFimDaInvasao(modo.state, modo.regras, game.combatants);
+ assert.equal(vencedor, 'J');
+ assert.match(modo.roundResult(vencedor).detail, new RegExp(`^CAÍRAM NA ONDA 5/${WAVE_COUNTS.length}`));
+});
+
regra('snapshot v8 replica o estado completo da horda', () => {
const horda = criarHorda({ seed: 91, mutante });
iniciarOnda(horda); passoHorda(horda, 1);
diff --git a/tools/eval/javaporcos-disputa-check.mjs b/tools/eval/javaporcos-disputa-check.mjs
index 987a88d896..df65b6538e 100644
--- a/tools/eval/javaporcos-disputa-check.mjs
+++ b/tools/eval/javaporcos-disputa-check.mjs
@@ -1,14 +1,15 @@
import assert from 'node:assert/strict';
import {bootGame,initTextures} from './harness.mjs';
-import {passoDominio,iniciarOnda} from '../../public/js/mode_javaporcos.js';
+import {passoDominio,iniciarOnda,WAVE_COUNTS} from '../../public/js/mode_javaporcos.js';
+import {PREP_SECONDS,COMBAT_SECONDS} from '../../public/js/javaporcos_ondas.js';
import {encodeSnapshot,decodeSnapshot} from '../../public/js/netcodec.js';
-import {regrasDaInvasao,avaliarFimDaInvasao,repartirTerritorio} from '../../public/js/javaporcos_partida.js';
+import {regrasDaInvasao,avaliarFimDaInvasao,repartirTerritorio,resumoDoFimJavaporcos} from '../../public/js/javaporcos_partida.js';
import {makeNetcode} from '../../public/js/netgame.js';
const g=bootGame('invasao_javaporcos',{textures:initTextures(),bots:3,settings:{javaporcos:{times:3,fim:'infinito'}}});
let failed=0;const test=(n,fn)=>{try{fn();console.log('✓ DISPUTA '+n);}catch(e){failed++;console.log('✗ DISPUTA '+n+': '+e.message.slice(0,160));}};
test('dois times humanos e uma horda independente',()=>{assert.ok(g.combatants.some(c=>c.team==='B'&&!c._objectiveNpc));assert.equal(g.combatants.filter(c=>c.team==='J'&&c._objectiveNpc).length,64);});
test('100% de domínio não encerra a partida',()=>{const s=g.objective.state;s.controle.fill(1);passoDominio(s,g.world.horda.setores,s.controle.map(()=>3),s.controle.map(()=>0),1);assert.equal(s.dominio,1);assert.equal(s.winner,null);});
-test('singleplayer infinito ultrapassa oito ondas',()=>{const s=g.objective.state;s.winner=null;s.wave=8;s.phase='prep';assert.equal(iniciarOnda(s),true);assert.equal(s.wave,9);assert.ok(s.remaining>0);});
+test('singleplayer infinito ultrapassa a sequência padrão',()=>{const s=g.objective.state;s.winner=null;s.wave=WAVE_COUNTS.length;s.phase='prep';assert.equal(iniciarOnda(s),true);assert.equal(s.wave,WAVE_COUNTS.length+1);assert.ok(s.remaining>0);});
const packet={type:'snapshot',room:'j',tick:1,t:1,state:'live',owner:'',players:2,spectators:0,livre:{E:0,B:0},timeLeft:30,roundNum:1,scoreE:0,scoreB:0,roundKillsE:0,roundKillsB:0,ents:Array.from({length:80},(_,i)=>({id:i+1,name:'NPC',team:i<8?'E':i<16?'B':'J',bot:1,alive:true,x:0,y:0,z:0,yaw:0,pitch:0,hp:100,k:0,d:0}))};
test('snapshot v8 comporta humanos e 64 javaporcos',()=>{const snap=decodeSnapshot(encodeSnapshot(packet,8));assert.equal(snap.ents.length,80);assert.equal(snap.ents.filter(e=>e.team==='J').length,64);});
test('protocolos antigos recusam terceira facção',()=>{for(let v=2;v<=7;v++)assert.throws(()=>encodeSnapshot({...packet,ents:[packet.ents.at(-1)]},v),/objective_requires_v8/);});
@@ -17,7 +18,9 @@ test('fim da invasão independe do contador de rodadas',()=>{const s=g.objective
test('um sobrevivente mantém o time mesmo com baixas',()=>{const s=estado();assert.equal(avaliarFimDaInvasao(s,regrasDaInvasao(),[{team:'E',alive:false},{team:'E',alive:true}]),null);assert.deepEqual(s.eliminados,[]);});
test('wipe elimina só o time derrotado na disputa tripla',()=>{const s=estado();assert.equal(avaliarFimDaInvasao(s,regrasDaInvasao({times:3}),[{team:'E',alive:false},{team:'B',alive:true}]),null);assert.deepEqual(s.eliminados,['E']);assert.equal(avaliarFimDaInvasao(s,regrasDaInvasao({times:3}),[{team:'E',alive:false},{team:'B',alive:false}]),'J');});
test('alternativa wipe da partida encerra na primeira equipe eliminada',()=>assert.equal(avaliarFimDaInvasao(estado(),regrasDaInvasao({times:3,wipe:'partida'}),[{team:'E',alive:false},{team:'B',alive:true}]),'J'));
-test('infinito ignora abates e relógio altos',()=>assert.equal(avaliarFimDaInvasao({...estado(),kills:10000,clock:100000},regrasDaInvasao(),[{team:'E',alive:true}]),null));
+test('infinito ignora abates e relógio altos',()=>assert.equal(avaliarFimDaInvasao({...estado(),kills:10000,clock:100000},regrasDaInvasao({fim:'infinito'}),[{team:'E',alive:true}]),null));
+test('solo padrão usa a programação de ondas; INFINITO, limites e multiplayer não têm teto',()=>{assert.equal(regrasDaInvasao().ondas,WAVE_COUNTS.length);assert.equal(regrasDaInvasao({fim:'ondas'}).ondas,WAVE_COUNTS.length);for(const fim of ['infinito','abates','mortes','tempo'])assert.equal(regrasDaInvasao({fim}).ondas,0,fim);assert.equal(regrasDaInvasao({},true).ondas,0);assert.equal(regrasDaInvasao({coop:true},true).ondas,0);});
+test('resumo apresenta total de ondas e duração só no preset de ondas',()=>{assert.equal(resumoDoFimJavaporcos(),`${WAVE_COUNTS.length} ONDAS · ~${Math.round(WAVE_COUNTS.length*(PREP_SECONDS+COMBAT_SECONDS)/60)} MIN · SOBREVIVA À ÚLTIMA`);assert.equal(resumoDoFimJavaporcos({fim:'infinito'}),'');});
test('limites multiplayer são 1000 abates ou 30 minutos',()=>{for(const patch of [{kills:1000},{clock:1800}])assert.equal(avaliarFimDaInvasao({...estado(),...patch,territorio:{E:.2,B:.6,J:.2}},regrasDaInvasao({},true),[{team:'E',alive:true},{team:'B',alive:true}]),'B');});
test('limite singleplayer configurável e empate sem favorecer um lado',()=>{assert.equal(avaliarFimDaInvasao({...estado(),kills:12},regrasDaInvasao({fim:'abates',abates:12}),[{team:'E',alive:true}]),'draw');assert.equal(avaliarFimDaInvasao(estado(),regrasDaInvasao({fim:'mortes',mortes:4}),[{team:'E',alive:true,deaths:4}]),'draw');});
test('limite de mortes solo conta apenas o time do jogador, E ou B',()=>{const regras=regrasDaInvasao({times:3,fim:'mortes',mortes:4});for(const team of ['E','B']){const cs=[{team,alive:true,deaths:0},{team:team==='E'?'B':'E',alive:true,deaths:20}];assert.equal(avaliarFimDaInvasao(estado(),regras,cs,team),null);cs[0].deaths=4;assert.equal(avaliarFimDaInvasao(estado(),regras,cs,team),'draw');}});
@@ -40,4 +43,5 @@ test('join tardio casa animal com entidade reciclada e interpola posição',()=>
o.state.winner='J';mp._netTick=1;mp.transicaoDeEstado('live','roundEnd',{E:0,B:0});assert.equal(resultado,'J');
} finally {mp.dispose();g.online=false;}
});
+test('disputa tripla entrega a última onda ao critério do limite, não ao time E',()=>{const o=g.objective,s=o.state,estadoJogo=g.state,end=g._endRound;const salvo={winner:s.winner,phase:s.phase,wave:s.wave,maxWaves:s.maxWaves,remaining:s.remaining,alive:s.alive,territorio:s.territorio,teamKills:s.teamKills,eliminados:s.eliminados};let fim;g._endRound=w=>{fim=w;};try{Object.assign(s,{winner:null,phase:'combat',wave:WAVE_COUNTS.length,maxWaves:WAVE_COUNTS.length,remaining:0,alive:[],territorio:{E:.1,B:.5,J:.4},teamKills:{E:3,B:9,J:1},eliminados:[]});g.state='live';o.update(.016);assert.equal(s.winner,'B');assert.equal(fim,'B');}finally{Object.assign(s,salvo);g.state=estadoJogo;g._endRound=end;}});
process.exitCode=failed?1:0;
diff --git a/tools/eval/lab-publico-check.mjs b/tools/eval/lab-publico-check.mjs
new file mode 100644
index 0000000000..5cf5b6a846
--- /dev/null
+++ b/tools/eval/lab-publico-check.mjs
@@ -0,0 +1,372 @@
+#!/usr/bin/env node
+/* ============================================================================
+ lab-publico-check.mjs: NADA DE LABORATÓRIO EM public/js
+ ----------------------------------------------------------------------------
+ POR QUE EXISTE
+ public/ é servido inteiro: qualquer navegador importa /js/.js. A
+ bancada de captura HD (hd_lab.js) ficou ali e o revisor do lote #1476 mostrou
+ que `(await import('/js/hd_lab.js')).liga()` punha HP 1e9 e teleportava bots.
+ Gate no cliente não é gate; ferramenta de desenvolvimento mora fora de public/.
+
+ LP1 · arquivo de public/js com marca de laboratório (nome com lab, debug,
+ cheat ou dev; ou cabeçalho "só desenvolvimento" / "não entra em commit
+ de produto") fora da allowlist PRODUTO.
+ LP2 · arquivo de public/js fora do grafo de imports dos scripts em páginas
+ Astro e HTML e que escreve estado de jogo (hp, pos de entidade por
+ método, eixo ou atribuição, __game, __escada).
+ LP3 · entrada da allowlist que sumiu, perdeu a marca ou saiu do grafo de
+ imports: a justificativa não vale mais. Menção em comentário ou
+ string não é import.
+
+ Uso: node tools/eval/lab-publico-check.mjs
+ node tools/eval/lab-publico-check.mjs --mutante=hd-lab|orfao-hp|orfao-pos|orfao-citado|orfao-em-par|allowlist-orfa|allowlist-comentada
+ (o mutante sai 0 quando a cláusula esperada reprova)
+ ============================================================================ */
+import { readFileSync, readdirSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { parse as parseAstro } from '@astrojs/compiler-rs';
+import { parse } from 'acorn';
+import { parseHTML } from 'linkedom';
+import { ALVOS as PODADOS } from '../../scripts/prune-dist.mjs';
+
+const RAIZ = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
+
+/* Marcado e legítimo: precisa de motivo, e LP3 confere que o jogo ainda o importa. */
+export const PRODUTO = {
+ 'public/js/vmlab.js': 'tabela de poses do modo ?vmlab=1, importada por game.js; só dados, coberta por eval:vmlabhud',
+ 'public/js/passe-debug.js': 'predicado de QA lido por main.js; só lê location, não escreve estado; coberto por eval:passe-debug',
+};
+
+/* Substring, como o pedido (*lab*, *debug*, *cheat*, *dev*); `label` e `device` não são marca.
+ * Medido nos 263 módulos de 28/11/2026: só clan-label.js colidia. */
+const NOME_LAB = /lab(?!el)|debug|cheat|dev(?!ice)/i;
+const CABECALHO_LAB = /só desenvolvimento|não entra em commit de produto|development only|dev[- ]only/i;
+const METODO_POS = /^(?:set|copy|add|sub|lerp|multiply|apply)\w*$/;
+const HTML_LOCAL = new Set(PODADOS.filter((alvo) => alvo.endsWith('.html'))
+ .map((alvo) => alvo.replace(/^(?:dist\/client|\.vercel\/output\/static)\//, 'public/')));
+
+function arquivos(dir, extensoes, saida = []) {
+ for (const e of readdirSync(path.join(RAIZ, dir), { withFileTypes: true })) {
+ const rel = `${dir}/${e.name}`;
+ if (e.isDirectory()) arquivos(rel, extensoes, saida);
+ else if (extensoes.some((x) => e.name.endsWith(x))) saida.push(rel);
+ }
+ return saida;
+}
+
+export function carregar() {
+ const fontes = new Map();
+ for (const rel of [
+ ...arquivos('public/js', ['.js', '.mjs']),
+ ...arquivos('public', ['.html']),
+ ...arquivos('src', ['.astro']),
+ ]) fontes.set(rel, readFileSync(path.join(RAIZ, rel), 'utf8'));
+ return fontes;
+}
+
+const marcado = (rel, texto) => NOME_LAB.test(path.basename(rel, path.extname(rel)))
+ || CABECALHO_LAB.test(texto.split('\n').slice(0, 5).join('\n'));
+
+function especificador(no) {
+ if (no?.type === 'Literal' && typeof no.value === 'string') return no.value;
+ if (no?.type === 'TemplateLiteral') {
+ const inicio = no.quasis[0].value.cooked;
+ if (!no.expressions.length || /[?#]/.test(inicio)) return inicio;
+ }
+ return null;
+}
+
+function visitar(no, fn, pais = []) {
+ fn(no, pais);
+ pais.push(no);
+ for (const valor of Object.values(no)) {
+ if (Array.isArray(valor)) {
+ for (const filho of valor) if (filho?.type) visitar(filho, fn, pais);
+ } else if (valor?.type) visitar(valor, fn, pais);
+ }
+ pais.pop();
+}
+
+function membro(no) {
+ if (no?.type !== 'MemberExpression') return '';
+ return no.computed ? especificador(no.property) || '' : no.property.name || '';
+}
+
+function escritaDeEstado(texto) {
+ let escrita;
+ visitar(parse(texto, { ecmaVersion: 'latest', sourceType: 'module' }), (no) => {
+ const alvo = no.type === 'AssignmentExpression' ? no.left : no.type === 'UpdateExpression' ? no.argument : null;
+ const propriedade = membro(alvo);
+ if (propriedade === 'hp' || propriedade === 'pos') escrita ??= propriedade;
+ if (membro(alvo?.object) === 'pos' && /^[xyz]$/.test(propriedade)) escrita ??= `pos.${propriedade}`;
+ if (no.type === 'CallExpression' && membro(no.callee.object) === 'pos' && METODO_POS.test(membro(no.callee))) {
+ escrita ??= `pos.${membro(no.callee)}()`;
+ }
+ if (no.type === 'MemberExpression' && no.object.name === 'window' && ['__game', '__escada'].includes(membro(no))) {
+ escrita ??= `window.${membro(no)}`;
+ }
+ });
+ return escrita;
+}
+
+/* O kit HD indexa uma tabela literal pelo mapa e importa um campo da tupla.
+ * Só os valores do campo que o import() lê entram no grafo. */
+function importDaTabela(origem, pais) {
+ const { object, property, computed } = origem;
+ if (!computed || object.type !== 'Identifier' || !Number.isInteger(property.value)) return [];
+ for (const bloco of pais.toReversed()) {
+ if (!Array.isArray(bloco.body)) continue;
+ const declaracao = bloco.body
+ .filter((no) => no.type === 'VariableDeclaration' && no.kind === 'const' && no.start < origem.start)
+ .flatMap((no) => no.declarations)
+ .find((no) => no.id.type === 'Identifier' && no.id.name === object.name);
+ if (!declaracao) continue;
+ const init = declaracao.init;
+ if (init?.type !== 'MemberExpression' || init.object.type !== 'ObjectExpression') return [];
+ return init.object.properties.flatMap((entrada) => entrada.value?.type === 'ArrayExpression'
+ ? [especificador(entrada.value.elements[property.value])]
+ : []);
+ }
+ return [];
+}
+
+function referenciasJs(ast) {
+ const refs = [];
+ visitar(ast, (no, pais) => {
+ if (no.type === 'ImportDeclaration' || no.type === 'ExportNamedDeclaration' || no.type === 'ExportAllDeclaration') {
+ refs.push(especificador(no.source));
+ } else if (no.type === 'ImportExpression') {
+ refs.push(especificador(no.source));
+ if (no.source.type === 'MemberExpression') refs.push(...importDaTabela(no.source, pais));
+ } else if (no.type === 'NewExpression' && ['Worker', 'SharedWorker'].includes(no.callee.name)) {
+ const alvo = no.arguments[0];
+ const spec = especificador(alvo);
+ if (spec?.startsWith('/')) refs.push(spec);
+ if (alvo?.type === 'NewExpression' && alvo.callee.name === 'URL') {
+ const base = alvo.arguments[1];
+ if (base?.object?.type === 'MetaProperty' && base.object.meta.name === 'import' && base.property.name === 'url') {
+ refs.push(especificador(alvo.arguments[0]));
+ }
+ }
+ }
+ });
+ return refs.filter(Boolean);
+}
+
+const scriptJs = (tipo) => ['', 'module', 'text/javascript', 'application/javascript'].includes(tipo?.trim().toLowerCase() ?? '');
+const tagAstro = (no) => no?.openingElement?.name?.name;
+
+function referenciasAstro(rel, texto) {
+ const { ast, diagnostics } = parseAstro(texto);
+ if (diagnostics.length) throw new Error(rel + ': ' + diagnostics.map((d) => d.message).join(', '));
+ const scripts = [];
+ const componentes = [];
+ const tags = new Set();
+ const frontmatter = ast.frontmatter?.program?.body ?? [];
+ const constantes = new Map(frontmatter
+ .filter((no) => no.type === 'VariableDeclaration' && no.kind === 'const')
+ .flatMap((no) => no.declarations.filter(({ id }) => id.type === 'Identifier')
+ .map(({ id, init }) => [id.name, especificador(init)])));
+ for (const raiz of ast.body) {
+ visitar(raiz, (no, pais) => {
+ const tag = tagAstro(no);
+ if (!tag || pais.some((pai) => tagAstro(pai) === 'template')) return;
+ tags.add(tag);
+ if (tag !== 'script') return;
+ const attrs = new Map(no.openingElement.attributes
+ .filter((attr) => attr.type === 'JSXAttribute')
+ .map(({ name, value }) => [name.name, value?.type === 'JSXExpressionContainer' ? value.expression : value]));
+ if (!scriptJs(especificador(attrs.get('type')))) return;
+ if (attrs.has('src')) {
+ const src = attrs.get('src');
+ scripts.push(src?.type === 'Identifier' ? constantes.get(src.name) : especificador(src));
+ } else {
+ for (const filho of no.children) {
+ if (filho.type === 'AstroScript' && filho.program) scripts.push(...referenciasJs(filho.program));
+ }
+ }
+ });
+ }
+ for (const no of frontmatter) {
+ if (no.type === 'ImportDeclaration' && no.importKind !== 'type' && /^\..+\.astro$/.test(no.source.value)
+ && no.specifiers.some(({ local }) => tags.has(local.name))) {
+ componentes.push(path.posix.join(path.posix.dirname(rel), no.source.value));
+ }
+ }
+ return { scripts: scripts.filter(Boolean), componentes };
+}
+
+function referenciasPagina(rel, texto) {
+ if (rel.endsWith('.astro')) return referenciasAstro(rel, texto);
+ const { document } = parseHTML(texto);
+ const scripts = [];
+ for (const script of document.querySelectorAll('script')) {
+ if (script.closest('template')) continue;
+ const tipo = script.getAttribute('type')?.trim().toLowerCase() || '';
+ if (!scriptJs(tipo)) continue;
+ const src = script.getAttribute('src');
+ if (src !== null) {
+ scripts.push(src);
+ } else {
+ try {
+ const ast = parse(script.textContent, { ecmaVersion: 'latest', sourceType: tipo === 'module' ? 'module' : 'script' });
+ scripts.push(...referenciasJs(ast));
+ } catch (erro) {
+ throw new Error(rel + ': script inline: ' + erro.message, { cause: erro });
+ }
+ }
+ }
+ return { scripts: scripts.filter(Boolean), componentes: [] };
+}
+
+function alvos(rel, referencias, modulos) {
+ const achados = [];
+ for (const bruto of referencias) {
+ const [spec] = bruto.split(/[?#]/, 1);
+ if (!spec || spec.startsWith('//')) continue;
+ let caminho;
+ if (spec.startsWith('/')) caminho = path.posix.join('public', spec);
+ else if (rel.startsWith('public/') && (spec.startsWith('.') || rel.endsWith('.html'))) {
+ caminho = path.posix.join(path.posix.dirname(rel), spec);
+ }
+ if (caminho !== rel && modulos.has(caminho)) achados.push(caminho);
+ }
+ return achados;
+}
+
+/* Alcançável a partir do que o site serve: páginas de src/ e HTML de public/. Dois módulos
+ * de bancada que só se importam entre si continuam órfãos. */
+function alcancaveis(fontes) {
+ const modulos = new Set([...fontes.keys()].filter((rel) => rel.startsWith('public/js/') && /\.m?js$/.test(rel)));
+ const fila = [];
+ const paginas = new Set([...fontes.keys()].filter((rel) =>
+ (rel.startsWith('public/') && rel.endsWith('.html') && !HTML_LOCAL.has(rel))
+ || (rel.startsWith('src/pages/') && rel.endsWith('.astro'))));
+ for (const rel of paginas) {
+ const { scripts, componentes } = referenciasPagina(rel, fontes.get(rel));
+ fila.push(...alvos(rel, scripts, modulos));
+ for (const componente of componentes) if (fontes.has(componente)) paginas.add(componente);
+ }
+ const vistos = new Set(fila);
+ while (fila.length) {
+ const atual = fila.pop();
+ const ast = parse(fontes.get(atual), { ecmaVersion: 'latest', sourceType: 'module' });
+ for (const proximo of alvos(atual, referenciasJs(ast), modulos)) {
+ if (!vistos.has(proximo)) { vistos.add(proximo); fila.push(proximo); }
+ }
+ }
+ return vistos;
+}
+
+export function auditar(fontes, produto = PRODUTO) {
+ const falhas = [];
+ const importados = alcancaveis(fontes);
+ const modulos = [...fontes.keys()].filter((rel) => rel.startsWith('public/js/') && /\.m?js$/.test(rel));
+ if (!modulos.length) falhas.push('LP0 nenhum módulo em public/js: a régua não mediu nada');
+ if (!importados.has('public/js/main.js')) falhas.push('LP0 main.js fora do grafo: as entradas do site não foram lidas');
+ for (const rel of modulos) {
+ const texto = fontes.get(rel);
+ if (marcado(rel, texto) && !(rel in produto)) {
+ falhas.push(`LP1 ${rel}: marca de laboratório em public/js; mova para tools/lab/ ou justifique em PRODUTO`);
+ }
+ if (!importados.has(rel)) {
+ const escrita = escritaDeEstado(texto);
+ if (escrita) falhas.push(`LP2 ${rel}: fora do grafo de imports do jogo e escreve estado de jogo (${escrita})`);
+ }
+ }
+ for (const [rel, motivo] of Object.entries(produto)) {
+ const texto = fontes.get(rel);
+ if (typeof motivo !== 'string' || !motivo.trim()) falhas.push(`LP3 ${rel}: justificativa vazia na allowlist`);
+ else if (texto == null) falhas.push(`LP3 ${rel}: allowlist aponta para arquivo que não existe`);
+ else if (!marcado(rel, texto)) falhas.push(`LP3 ${rel}: sem marca de laboratório; tire da allowlist`);
+ else if (!importados.has(rel)) falhas.push(`LP3 ${rel}: allowlist diz produto, mas está fora do grafo de imports do jogo`);
+ }
+ return falhas;
+}
+
+const ESCRITA_FOCAL = 'export const ajusta = (estado) => { estado.hp += 1; };\n';
+const SCRIPT_FOCAL = '';
+
+const MUTANTES = {
+ 'hd-lab': ['LP1',
+ (f) => f.set('public/js/hd_lab.js', '// Só desenvolvimento\nexport const captura = true;\n'),
+ (f) => f.set('public/js/hd_lab.js', 'export const captura = true;\n'),
+ (f) => f.set('public/js/captura.js', '// Só desenvolvimento\nexport const captura = true;\n'),
+ ],
+ 'orfao-hp': ['LP2', ...[
+ 'b.hp = 1;', 'b["hp"] += 1;', 'b.hp++;',
+ ].map((escrita) => (f) => f.set('public/js/sub/vendor/captura.mjs', `export function ajusta(b) { ${escrita} }\n`))],
+ 'orfao-pos': ['LP2', ...[
+ 'b.pos.x = 400;', 'b.pos.z += 1;', 'b.pos.y++;', 'b.pos.copy(alvo);', 'b.pos = alvo;',
+ ].map((escrita) => (f) => f.set('public/js/captura.js', `export function leva(b, alvo) { ${escrita} }\n`))],
+ 'orfao-citado': ['LP2', ...[
+ "// ver captura.js\nconst dica = 'captura.js';",
+ "const exemplo = \"import './captura.js'\";",
+ "const dica = './captura.js';",
+ ].map((texto) => (f) => {
+ f.set('public/js/captura.js', 'export function escreve(estado) { estado.hp = 1; }\n');
+ f.set('public/js/main.js', `${texto}\n${f.get('public/js/main.js')}`);
+ }), (f) => {
+ f.set('public/js/captura.js', ESCRITA_FOCAL);
+ f.set('public/dev.html', SCRIPT_FOCAL);
+ }, (f) => {
+ f.set('public/js/captura.js', ESCRITA_FOCAL);
+ f.set('src/components/Captura.astro', [
+ '---', "const src: string = '/js/captura.js';", '---',
+ '',
+ ].join('\n'));
+ const rel = 'src/pages/captura.astro';
+ const pagina = "---\nimport Captura from '../components/Captura.astro';\n---\n";
+ f.set(rel, pagina + '');
+ if (!alcancaveis(f).has('public/js/captura.js')) throw new Error('controle: script do componente renderizado ficou fora do grafo');
+ f.set(rel, pagina);
+ }, (f) => {
+ f.set('public/js/captura.js', ESCRITA_FOCAL);
+ f.set('src/pages/captura.astro', `${SCRIPT_FOCAL}`);
+ }],
+ 'orfao-em-par': ['LP2', (f) => {
+ f.set('public/js/captura.js', 'export function liga(g) { g.player.hp = 1e9; }\n');
+ f.set('public/js/captura_ui.js', "import { liga } from './captura.js';\nexport const abre = liga;\n");
+ }],
+ 'allowlist-comentada': ['LP3', (f) => f.set('public/js/main.js',
+ f.get('public/js/main.js').replace(/^import .*passe-debug\.js.*$/m, '// import removido: passe-debug.js'))],
+ 'allowlist-orfa': ['LP3',
+ (f) => f.set('public/js/main.js', f.get('public/js/main.js').replaceAll('passe-debug.js', 'passe-qa.js')),
+ (f) => f.delete('public/js/passe-debug.js'),
+ (f, produto) => { produto['public/js/passe-debug.js'] = ' '; },
+ (f, produto) => { produto['public/js/main.js'] = 'Teste de entrada sem marca de laboratório'; },
+ ],
+};
+
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const nomeMutante = (process.argv.find((a) => a.startsWith('--mutante=')) || '').slice('--mutante='.length);
+ const fontes = carregar();
+ if (nomeMutante) {
+ const mutante = MUTANTES[nomeMutante];
+ if (!mutante) { console.error(`mutante desconhecido: ${nomeMutante}`); process.exit(2); }
+ const [clausula, ...variantes] = mutante;
+ const antes = auditar(fontes);
+ let exemplo;
+ for (const [i, aplica] of variantes.entries()) {
+ const mutadas = new Map(fontes);
+ const produto = { ...PRODUTO };
+ aplica(mutadas, produto);
+ const novas = auditar(mutadas, produto).filter((falha) => !antes.includes(falha) && falha.startsWith(clausula));
+ if (!novas.length) {
+ console.error(`MUTAÇÃO PASSOU: ${nomeMutante} (variante ${i + 1}/${variantes.length}) não reprovou ${clausula}`);
+ process.exit(1);
+ }
+ exemplo ??= novas[0];
+ }
+ console.log(`${clausula} mutante ${nomeMutante} reprovado em ${variantes.length} variante(s): ${exemplo}`);
+ process.exit(0);
+ }
+ const falhas = auditar(fontes);
+ for (const falha of falhas) console.error(`✗ ${falha}`);
+ if (falhas.length) process.exit(1);
+ const modulos = [...fontes.keys()].filter((rel) => rel.startsWith('public/js/') && /\.m?js$/.test(rel));
+ const noGrafo = alcancaveis(fontes);
+ const fora = modulos.filter((rel) => !noGrafo.has(rel)).length;
+ console.log(`✓ LP1-LP3 ${modulos.length} módulos em public/js (${fora} fora do grafo de imports, nenhum escreve estado): nenhum laboratório publicado; allowlist ${Object.keys(PRODUTO).length} com motivo`);
+}
diff --git a/tools/eval/lib/browser-routing.mjs b/tools/eval/lib/browser-routing.mjs
new file mode 100644
index 0000000000..0e6f00b1ec
--- /dev/null
+++ b/tools/eval/lib/browser-routing.mjs
@@ -0,0 +1 @@
+export const useEgo = (platform, env) => platform !== 'linux' && Object.hasOwn(env, 'EGO_TASK_SPACE');
diff --git a/tools/eval/lib/gpu-profile.mjs b/tools/eval/lib/gpu-profile.mjs
new file mode 100644
index 0000000000..ae779703a4
--- /dev/null
+++ b/tools/eval/lib/gpu-profile.mjs
@@ -0,0 +1,24 @@
+export const classifyGpuEnvironment = (platform, gpu, webgl2, acceleration, device) => {
+ if (platform !== 'darwin' && platform !== 'linux') return { ok: false, stage: 'platform', reason: 'platform_not_supported' };
+ if (webgl2 !== true) return { ok: false, stage: 'webgl2', reason: 'webgl2_unavailable' };
+ if (typeof gpu !== 'string' || !gpu.trim()) return { ok: false, stage: 'gpu', reason: 'gpu_absent' };
+ if (/swiftshader|software|llvmpipe|softpipe|swrast|lavapipe/i.test(gpu)) return { ok: false, stage: 'gpu', reason: 'gpu_software' };
+ if (platform === 'darwin' && !/Apple M4 Pro|Metal/i.test(gpu)) return { ok: false, stage: 'gpu', reason: 'gpu_not_supported' };
+ if (platform === 'linux' && !/\bAMD\b.*(?:\bRadeon\b|\bRADV\b)/i.test(gpu)) return { ok: false, stage: 'gpu', reason: 'gpu_not_supported' };
+ if (platform === 'linux' && (device?.vendorId !== 4098 || !Number.isSafeInteger(device?.deviceId) || device.deviceId <= 0)) return { ok: false, stage: 'gpu', reason: 'gpu_device_unavailable' };
+ if (platform === 'linux' && acceleration !== 'enabled') return { ok: false, stage: 'gpu', reason: 'gpu_acceleration_unavailable' };
+ return { ok: true, stage: 'profile' };
+};
+
+export async function linuxGpuEvidence(browser, page) {
+ const measured = await page.evaluate(() => {
+ const gl = document.createElement('canvas').getContext('webgl2');
+ const ext = gl?.getExtension('WEBGL_debug_renderer_info');
+ return { webgl2: !!gl, gpu: ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : null };
+ });
+ const session = await browser.newBrowserCDPSession();
+ try {
+ const info = await session.send('SystemInfo.getInfo');
+ return { ...measured, acceleration: info.gpu?.featureStatus?.webgl, device: info.gpu?.devices?.[0] };
+ } finally { await session.detach(); }
+}
diff --git a/tools/eval/lib/node-minimo.mjs b/tools/eval/lib/node-minimo.mjs
new file mode 100644
index 0000000000..2c3c648e09
--- /dev/null
+++ b/tools/eval/lib/node-minimo.mjs
@@ -0,0 +1,22 @@
+/* Importado pelo efeito: aborta o eval antes de medir quando o `node` do PATH não
+ * tem `fetch` global. Falha fechada; pular o passo esconderia a régua. */
+const NODE_MINIMO = 20;
+
+export function problemaDoNode({ versao, temFetch, binario }) {
+ const maior = Number.parseInt(String(versao).split('.')[0], 10);
+ if (maior >= NODE_MINIMO && temFetch) return null;
+ const motivo = maior >= NODE_MINIMO ? 'não tem fetch global' : `é anterior ao ${NODE_MINIMO}`;
+ return `eval abortado: Node ${versao} (${binario}) ${motivo}. `
+ + 'Use o node do Homebrew: /opt/homebrew/bin/node '
+ + '(ponha /opt/homebrew/bin antes de /usr/local/bin no PATH).';
+}
+
+const problema = problemaDoNode({
+ versao: process.versions.node,
+ temFetch: typeof fetch === 'function',
+ binario: process.execPath,
+});
+if (problema) {
+ console.error(problema);
+ process.exit(1);
+}
diff --git a/tools/eval/lib/privacy-indexeddb-fixture.mjs b/tools/eval/lib/privacy-indexeddb-fixture.mjs
new file mode 100644
index 0000000000..8fe97ff6f1
--- /dev/null
+++ b/tools/eval/lib/privacy-indexeddb-fixture.mjs
@@ -0,0 +1,34 @@
+export function privacyIndexedDB(schedule = run => Promise.resolve().then(run)) {
+ return {
+ open() {
+ const request = {
+ result: {
+ close() {},
+ transaction(store, mode) {
+ if (store !== 'lock' || mode !== 'readwrite') throw new Error('Invalid privacy lock');
+ const transaction = {
+ abort() {},
+ objectStore() {
+ return {
+ get() {
+ return {
+ set onsuccess(run) {
+ schedule(run).catch(error => {
+ transaction.error = error;
+ transaction.onabort?.();
+ });
+ },
+ };
+ },
+ };
+ },
+ };
+ return transaction;
+ },
+ },
+ };
+ queueMicrotask(() => request.onsuccess?.());
+ return request;
+ },
+ };
+}
diff --git a/tools/eval/lib/serve-eval.mjs b/tools/eval/lib/serve-eval.mjs
new file mode 100644
index 0000000000..2b9a60f4d7
--- /dev/null
+++ b/tools/eval/lib/serve-eval.mjs
@@ -0,0 +1,98 @@
+/* ============================================================================
+ serve-eval.mjs — SOBE O tools/eval/serve.mjs E ESPERA COM UM PRAZO SÓ
+ ----------------------------------------------------------------------------
+ POR QUE EXISTE (OPS-11): cada régua tinha o próprio teto de boot (30 a 60 s,
+ 60×500 ms no vm-palco) e o serve.mjs (Astro + Vite) levou 51–117 s para
+ responder num Mac com o volume lento. O pre-push reprovava por infraestrutura
+ ("servidor de eval não subiu na porta 9177"), não pelo que a régua mede.
+
+ Agora o prazo é um só, EVAL_BOOT_TIMEOUT_MS (padrão 180000). Porta ocupada
+ reprova antes do spawn, e o filho que morre antes de responder reprova NA HORA
+ com o código de saída e a cauda do stderr, em vez de esperar o prazo inteiro. Cada régua continua escolhendo a
+ URL que prova "pronto" (e, se precisar, o que a resposta tem que conter).
+ ============================================================================ */
+import { spawn } from 'node:child_process';
+import net from 'node:net';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const RAIZ = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
+const CAUDA_STDERR = 2000;
+const ANUNCIO = 'eval server ->';
+
+export const PRAZO_BOOT_MS = (() => {
+ const bruto = process.env.EVAL_BOOT_TIMEOUT_MS;
+ if (bruto === undefined || bruto === '') return 180000;
+ const ms = Number(bruto);
+ if (!Number.isFinite(ms) || ms <= 0) throw new Error(`EVAL_BOOT_TIMEOUT_MS inválido: ${JSON.stringify(bruto)} (ms > 0)`);
+ return ms;
+})();
+
+const segundos = (ms) => (ms / 1000).toFixed(1);
+
+/* Sobe `node