/** * Sistema de excavaciĂłn por celdas para el suelo blando đŸȘ. * * Cada `DigGrid` es una rejilla de celdas de tierra (por defecto 1×1 u) construida con * `InstancedMesh` para el cuerpo y las capas de tierra, y un colisionador sĂłlido por celda * (tag `dig`, material `soft`). Al cavar una celda: * 1. se apaga su colisionador (se abre el hueco), * 2. se oculta su instancia (matriz a escala 0), * 3. se persiste con la bandera `dig...`, * 4. se lanza `onDug` (premios) y, al vaciar la rejilla, `onComplete` (cofres secretos). * * El hĂ©roe emite `hero:dig` con `target` = colisionador de la celda; `wireDig` enruta el evento * a la rejilla correspondiente. Las rejillas se colocan en huecos del terreno (nunca debajo de un * `z.ground` monolĂ­tico) para que al retirar celdas quede un tĂșnel transitable de verdad. */ import * as THREE from 'three'; import type { Game } from '../core/game'; import type { Collider, Hit } from '../core/types'; import { P, kitMat } from './kit/util'; import { tallyAdd } from '../core/tally'; export interface DigCell { readonly i: number; readonly j: number; readonly x: number; readonly y: number; readonly flag: string; readonly col: Collider; done: boolean; } export type DigRewardKind = 'coin' | 'diamond' | 'heart'; export interface DigReward { /** Columna (0 = izquierda). */ i: number; /** Fila (0 = abajo). */ j: number; kind: DigRewardKind; /** Id persistente para diamantes/cofres. */ id?: string; /** Cantidad de monedas (por defecto 1). */ n?: number; } export interface DigGridOpts { game: Game; /** Prefijo de banderas (p. ej. `cave.dig-a`). */ prefix: string; /** Esquina inferior izquierda de la rejilla. */ x0: number; y0: number; cols: number; rows: number; /** Tamaño de celda (1 por defecto). */ cell?: number; /** Premios que aparecen al excavar celdas concretas. */ rewards?: DigReward[]; onDug?: (cell: DigCell, grid: DigGrid) => void; onComplete?: (grid: DigGrid) => void; /** Panel oscuro detrĂĄs (por defecto true) para que el tĂșnel se lea al vaciar celdas. */ back?: boolean; /** Acabado de la fila superior: 'grass' (cĂ©sped, a ras del suelo del bosque), 'cave' (roca) o 'none'. */ top?: 'grass' | 'cave' | 'none'; /** Paleta de la tierra: 'forest' (ocre del bosque, por defecto) o 'cave' (pardo grisĂĄceo). */ soil?: 'forest' | 'cave'; } // Tierra suelta: caja lisa (sin biseles) a ras de la cara del terreno; cada celda con un tono algo distinto // para que se lea como tierra removida y no como cajas. El cĂ©sped solo en la fila de arriba. const soilMat = kitMat('digSoilV', { color: 0xffffff, gloss: 0.1, rim: 0.22 }); const soilCapMat = kitMat('digGrassCap', { color: 0x5bd23c, gloss: 0.35, rim: 0.4 }); const caveCapMat = kitMat('digCaveCap', { color: 0x6b6278, gloss: 0.25, rim: 0.35 }); let cellGeo: THREE.BoxGeometry | null = null; function soilGeo(): THREE.BoxGeometry { if (!cellGeo) { cellGeo = new THREE.BoxGeometry(1, 1, 1); cellGeo.userData.shared = true; } return cellGeo; } const SOIL = { forest: [0x9a5f2e, 0xa86a35, 0x8f5629, 0xb0733c], cave: [0x6e5a4a, 0x7a6352, 0x63503f, 0x846b58], }; // Fondo del tĂșnel: la misma tierra, mĂĄs sombreada (continuidad con el terreno, nunca un hueco negro). const backMat = kitMat('digBackSoil', { color: 0x5a3a20, gloss: 0.04, rim: 0.12 }); const backMatCave = kitMat('digBackCave', { color: 0x43372e, gloss: 0.04, rim: 0.12 }); const _dummy = new THREE.Object3D(); const _tmpC = new THREE.Color(); export class DigGrid { readonly cells: DigCell[][] = []; readonly cols: number; readonly rows: number; readonly x0: number; readonly y0: number; readonly cs: number; total: number; removed = 0; private readonly game: Game; private readonly body: THREE.InstancedMesh; private readonly caps: THREE.InstancedMesh; private readonly rewardMap = new Map(); private readonly onDug?: (cell: DigCell, grid: DigGrid) => void; private topStyle: 'grass' | 'cave' | 'none' = 'grass'; private readonly pal: number[]; private readonly onComplete?: (grid: DigGrid) => void; constructor(o: DigGridOpts) { this.game = o.game; this.x0 = o.x0; this.y0 = o.y0; this.cols = Math.max(1, Math.round(o.cols)); this.rows = Math.max(1, Math.round(o.rows)); this.cs = o.cell ?? 1; this.total = this.cols * this.rows; this.onDug = o.onDug; this.onComplete = o.onComplete; for (const r of o.rewards ?? []) { this.rewardMap.set(`${r.i},${r.j}`, r); if (r.kind === 'coin') tallyAdd(o.game, 'c', Math.max(1, r.n ?? 1)); else if (r.kind === 'diamond') tallyAdd(o.game, 'd', 1); } const count = this.total; this.body = new THREE.InstancedMesh(soilGeo(), soilMat, count); this.caps = new THREE.InstancedMesh(P.rbox(), o.top === 'cave' ? caveCapMat : soilCapMat, count); this.topStyle = o.top ?? 'grass'; const pal = (this.pal = SOIL[o.soil ?? 'forest']); const tmpC = new THREE.Color(); for (let k = 0; k < count; k++) { tmpC.setHex(pal[(k * 7 + (k >> 2) * 3) % pal.length]); this.body.setColorAt(k, tmpC); } if (this.body.instanceColor) this.body.instanceColor.needsUpdate = true; this.body.castShadow = true; this.body.receiveShadow = true; this.caps.castShadow = false; this.caps.receiveShadow = true; this.body.name = 'dig-grid'; this.caps.name = 'dig-caps'; // de la cara frontal del terreno (z 1.4) hacia el fondo, igual que el suelo const depth = 4.2; const w = this.cols * this.cs; const h = this.rows * this.cs; if (o.back !== false) { const back = new THREE.Mesh(new THREE.BoxGeometry(w + 0.1, h + 0.1, 0.12), o.soil === 'cave' ? backMatCave : backMat); back.position.set(this.x0 + w / 2, this.y0 + h / 2, -2.86); back.receiveShadow = true; back.name = 'dig-back'; o.game.zoneGroup?.add(back); } let idx = 0; for (let j = 0; j < this.rows; j++) { const row: DigCell[] = []; for (let i = 0; i < this.cols; i++) { const x = this.x0 + (i + 0.5) * this.cs; const y = this.y0 + (j + 0.5) * this.cs; const flag = `dig.${o.prefix}.${i}.${j}`; const col = this.game.physics.box(x, y, this.cs * 0.995, this.cs * 0.995, { material: 'soft', tag: 'dig', owner: this, }); const cell: DigCell = { i, j, x, y, flag, col, done: false }; row.push(cell); this.place(idx, x, y, depth); if (this.game.state.has(flag)) this.hideCell(cell, idx); idx++; } this.cells.push(row); } this.body.instanceMatrix.needsUpdate = true; this.caps.instanceMatrix.needsUpdate = true; o.game.zoneGroup?.add(this.body, this.caps); } private place(idx: number, x: number, y: number, depth: number): void { const s = this.cs; const zc = 1.4 - depth / 2; _dummy.position.set(x, y, zc); _dummy.rotation.set(0, 0, 0); _dummy.scale.set(s * 1.002, s * 1.002, depth); _dummy.updateMatrix(); this.body.setMatrixAt(idx, _dummy.matrix); // cĂ©sped / roca solo en la fila de arriba const top = Math.floor(idx / this.cols) === this.rows - 1 && this.topStyle !== 'none'; _dummy.position.set(x, y + s * 0.5, zc); _dummy.scale.set(top ? s * 1.02 : 0, top ? 0.16 : 0, top ? depth + 0.06 : 0); _dummy.updateMatrix(); this.caps.setMatrixAt(idx, _dummy.matrix); } private hideCell(cell: DigCell, idx: number): void { if (cell.done) return; cell.done = true; cell.col.enabled = false; // La celda no desaparece: se retira al fondo como pared de tierra en sombra (el tĂșnel conserva // la textura del terreno en vez de dejar un agujero negro). const s = this.cs; _dummy.position.set(cell.x, cell.y, -2.45); _dummy.rotation.set(0, 0, 0); _dummy.scale.set(s * 1.002, s * 1.002, 0.7); _dummy.updateMatrix(); this.body.setMatrixAt(idx, _dummy.matrix); _tmpC.setHex(this.pal[(idx * 7 + (idx >> 2) * 3) % this.pal.length]).multiplyScalar(0.58); this.body.setColorAt(idx, _tmpC); if (this.body.instanceColor) this.body.instanceColor.needsUpdate = true; _dummy.scale.set(0, 0, 0); _dummy.updateMatrix(); this.caps.setMatrixAt(idx, _dummy.matrix); } /** Excava la celda cuyo colisionador es `col`. Devuelve true si habĂ­a algo que cavar. */ dig(col: Collider): boolean { for (let j = 0; j < this.cells.length; j++) { const row = this.cells[j]; for (let i = 0; i < row.length; i++) { const cell = row[i]; if (cell.col !== col || cell.done) continue; const idx = j * this.cols + i; this.hideCell(cell, idx); this.body.instanceMatrix.needsUpdate = true; this.caps.instanceMatrix.needsUpdate = true; this.game.state.set(cell.flag, true); this.removed++; this.giveReward(cell); this.onDug?.(cell, this); if (this.removed >= this.total) this.onComplete?.(this); this.game.state.save(); return true; } } return false; } /** Destruye la rejilla (por si una zona necesita retirarla antes de cambiar). */ dispose(): void { for (const row of this.cells) for (const c of row) this.game.physics.remove(c.col); this.body.removeFromParent(); this.caps.removeFromParent(); } private giveReward(cell: DigCell): void { const r = this.rewardMap.get(`${cell.i},${cell.j}`); if (!r) return; const g = this.game; const n = Math.max(1, r.n ?? 1); if (r.kind === 'diamond') { if (g.hasType('item.diamond')) g.spawn('item.diamond', cell.x, cell.y, { id: r.id, pop: true, tally: true }); } else if (r.kind === 'heart') { if (g.hasType('item.heart')) g.spawn('item.heart', cell.x, cell.y); } else { for (let k = 0; k < n; k++) { if (g.hasType('item.coin')) g.spawn('item.coin', cell.x + (k - (n - 1) / 2) * 0.32, cell.y, { tally: true }); } } } } /** * Conecta el evento `hero:dig` con una lista de rejillas. Devuelve la funciĂłn para desconectar * (la zona la llama en `onExit`). */ export function wireDig(game: Game, grids: readonly DigGrid[]): () => void { return game.events.on('hero:dig', (e) => { const target = (e as { target?: Collider }).target; if (!target) return; for (const grid of grids) if (grid.dig(target)) return; }); } /** ReacciĂłn comĂșn de una celda al golpe (opcional, si alguna zona quiere usar `takeHit`). */ export function isDigHit(hit: Hit): boolean { return hit.damage > 0; }