/** * Utilidades del kit de mundo: azar con semilla, ruido, cachés de materiales, geometrías y * texturas compartidas (todas con userData.shared = true), y normalización/fusión de geometría. */ import * as THREE from 'three'; import { mergeGeometries, toCreasedNormals } from 'three/examples/jsm/utils/BufferGeometryUtils.js'; import { RoundedBoxGeometry } from 'three/examples/jsm/geometries/RoundedBoxGeometry.js'; import { toonMaterial, type ToonOpts } from '../../render/materials'; // ───────────── Azar y ruido ───────────── /** Generador determinista 0..1 (mulberry32). */ export function rng(seed: number): () => number { let a = (Math.floor(seed) ^ 0x9e3779b9) >>> 0; return () => { a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } export function seedOf(...n: number[]): number { let h = 2166136261; for (const v of n) { h ^= Math.round(v * 977) | 0; h = Math.imul(h, 16777619); } return h >>> 0; } function hash1(i: number, seed: number): number { let h = Math.imul((i | 0) ^ seed, 0x27d4eb2d); h ^= h >>> 15; h = Math.imul(h, 0x85ebca6b); h ^= h >>> 13; return ((h >>> 0) % 10000) / 10000; } /** Ruido de valor 1D suave en 0..1. */ export function noise1(x: number, seed = 0): number { const i = Math.floor(x); const f = x - i; const u = f * f * (3 - 2 * f); return hash1(i, seed) * (1 - u) + hash1(i + 1, seed) * u; } export const smooth = (a: number, b: number, x: number): number => { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); }; // ───────────── Colores ───────────── const tmpA = new THREE.Color(); const tmpB = new THREE.Color(); export function mixHex(a: number, b: number, t: number): number { return tmpA.setHex(a).lerp(tmpB.setHex(b), t).getHex(); } export function shade(hex: number, k: number): number { k = Math.round(k * 20) / 20; return k >= 1 ? mixHex(hex, 0xffffff, k - 1) : mixHex(0x000000, hex, k); } // ───────────── Cachés compartidas ───────────── export function markShared(o: T): T { o.userData.shared = true; return o; } const matCache = new Map(); export interface KitMatOpts extends ToonOpts { vertexColors?: boolean; emissiveMap?: THREE.Texture | null; } /** Material toon cacheado y compartido por clave. */ export function kitMat(key: string, opts: KitMatOpts): THREE.Material { let m = matCache.get(key); if (m) return m; const { vertexColors, emissiveMap, ...toon } = opts; m = toonMaterial(toon); if (vertexColors) m.vertexColors = true; if (emissiveMap && 'emissiveMap' in m) (m as THREE.MeshStandardMaterial).emissiveMap = emissiveMap; m.needsUpdate = true; markShared(m); matCache.set(key, m); return m; } /** Material de color liso (props). */ export function solid(hex: number, gloss = 0.45, extra: Partial = {}): THREE.Material { const key = `solid:${hex}:${gloss}:${extra.emissive ?? ''}:${extra.emissiveIntensity ?? ''}:${extra.opacity ?? ''}`; const m = kitMat(key, { color: hex, gloss, ...extra, transparent: extra.opacity !== undefined && extra.opacity < 1 }); // color liso sin extras: al fusionar props se convierte en color por vértice de un material común if (!Object.keys(extra).length) m.userData.kitSolid = { hex, gloss }; return m; } const geoCache = new Map(); export function sharedGeo(key: string, make: () => THREE.BufferGeometry): THREE.BufferGeometry { let g = geoCache.get(key); if (!g) { g = markShared(make()); geoCache.set(key, g); } return g; } /** Primitivas unitarias compartidas. */ export const P = { sphere: () => sharedGeo('sphere', () => new THREE.SphereGeometry(1, 18, 14)), sphereLo: () => sharedGeo('sphereLo', () => new THREE.SphereGeometry(1, 10, 8)), hemi: () => sharedGeo('hemi', () => new THREE.SphereGeometry(1, 18, 9, 0, Math.PI * 2, 0, Math.PI / 2)), cyl: () => sharedGeo('cyl', () => new THREE.CylinderGeometry(1, 1, 1, 14)), trunk: () => sharedGeo('trunk', () => new THREE.CylinderGeometry(0.72, 1, 1, 10)), cone: () => sharedGeo('cone', () => new THREE.ConeGeometry(1, 1, 14)), coneLo: () => sharedGeo('coneLo', () => new THREE.ConeGeometry(1, 1, 6)), rbox: () => sharedGeo('rbox', () => new RoundedBoxGeometry(1, 1, 1, 3, 0.14)), rboxSoft: () => sharedGeo('rboxSoft', () => new RoundedBoxGeometry(1, 1, 1, 4, 0.3)), octa: () => sharedGeo('octa', () => new THREE.OctahedronGeometry(1, 0)), capsule: () => sharedGeo('capsule', () => new THREE.CapsuleGeometry(0.5, 1, 4, 10)), lily: () => sharedGeo('lily', () => new THREE.CylinderGeometry(1, 1, 1, 22, 1, false, 0.35, Math.PI * 2 - 0.7)), roof: () => sharedGeo('roof', () => { const s = new THREE.Shape([new THREE.Vector2(-0.5, 0), new THREE.Vector2(0.5, 0), new THREE.Vector2(0, 1)]); const g = new THREE.ExtrudeGeometry(s, { depth: 1, bevelEnabled: true, bevelThickness: 0.03, bevelSize: 0.03, bevelSegments: 2 }); g.translate(0, 0, -0.5); return g; }), rock: (i: number) => sharedGeo(`rock${i % 4}`, () => { const g = new THREE.IcosahedronGeometry(1, 2); const r = rng(1234 + (i % 4) * 77); const p = g.attributes.position as THREE.BufferAttribute; const v = new THREE.Vector3(); const offs = [r(), r(), r(), r(), r(), r()]; for (let k = 0; k < p.count; k++) { v.fromBufferAttribute(p, k); const n = v.clone().normalize(); const d = 1 + 0.16 * Math.sin(n.x * 3 + offs[0] * 6) * Math.cos(n.y * 2.5 + offs[1] * 6) + 0.1 * Math.sin(n.z * 4 + offs[2] * 6); v.copy(n).multiplyScalar(d); if (v.y < -0.3) v.y = -0.3 - (v.y + 0.3) * 0.25; p.setXYZ(k, v.x, v.y, v.z); } return toCreasedNormals(g, Math.PI); }), }; // ───────────── Texturas de canvas ───────────── const texCache = new Map(); /** Textura de canvas cacheada (≤1024), sRGB y repetible. */ export function canvasTex(key: string, size: number, draw: (g: CanvasRenderingContext2D, s: number) => void, srgb = true): THREE.CanvasTexture { let t = texCache.get(key); if (t) return t; const c = document.createElement('canvas'); c.width = c.height = Math.min(1024, size); const g = c.getContext('2d')!; draw(g, c.width); t = new THREE.CanvasTexture(c); t.wrapS = t.wrapT = THREE.RepeatWrapping; if (srgb) t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 4; markShared(t); texCache.set(key, t); return t; } // ───────────── Geometría ───────────── export type Painter = (p: THREE.Vector3, n: THREE.Vector3, out: THREE.Color) => void; /** Escribe el atributo color recorriendo vértices. */ export function paint(g: THREE.BufferGeometry, fn: Painter): THREE.BufferGeometry { const pos = g.attributes.position as THREE.BufferAttribute; const nor = g.attributes.normal as THREE.BufferAttribute | undefined; const col = new Float32Array(pos.count * 3); const p = new THREE.Vector3(); const n = new THREE.Vector3(0, 0, 1); const c = new THREE.Color(); for (let i = 0; i < pos.count; i++) { p.fromBufferAttribute(pos, i); if (nor) n.fromBufferAttribute(nor, i); c.setRGB(1, 1, 1); fn(p, n, c); col[i * 3] = c.r; col[i * 3 + 1] = c.g; col[i * 3 + 2] = c.b; } g.setAttribute('color', new THREE.BufferAttribute(col, 3)); return g; } /** Color plano en lineal a partir de hex sRGB (para atributos de color). */ export function flatPaint(hex: number, k = 1): Painter { const base = new THREE.Color(hex); return (_p, _n, out) => out.copy(base).multiplyScalar(k); } /** Deja la geometría no indexada con position/normal/uv/color (para fusionar lotes de terreno). */ export function normalizeFull(g: THREE.BufferGeometry): THREE.BufferGeometry { let r = g.index ? g.toNonIndexed() : g; if (r === g && g.userData.shared) r = g.clone(); const n = r.attributes.position.count; if (!r.attributes.normal) r.computeVertexNormals(); if (!r.attributes.uv) r.setAttribute('uv', new THREE.BufferAttribute(new Float32Array(n * 2), 2)); if (!r.attributes.color) r.setAttribute('color', new THREE.BufferAttribute(new Float32Array(n * 3).fill(1), 3)); for (const k of Object.keys(r.attributes)) if (!['position', 'normal', 'uv', 'color'].includes(k)) r.deleteAttribute(k); r.morphAttributes = {}; r.clearGroups(); return r; } /** Extruye una forma XY entre zBack y zFront con biselado redondo (la forma ya viene encogida `bevel`). */ export function extrude(shape: THREE.Shape, zBack: number, zFront: number, bevel: number, curveSegments = 6, bevelSegments = 3): THREE.BufferGeometry { const depth = Math.max(0.01, zFront - zBack - 2 * bevel); const g = new THREE.ExtrudeGeometry(shape, { depth, steps: 1, curveSegments, bevelEnabled: bevel > 0, bevelThickness: bevel, bevelSize: bevel, bevelSegments, }); g.translate(0, 0, zBack + bevel); const s = toCreasedNormals(g, Math.PI / 3.2); if (s !== g) g.dispose(); return s; } /** Instancia una primitiva compartida transformada (copia no compartida). */ export function placed(src: THREE.BufferGeometry, x: number, y: number, z: number, sx: number, sy: number, sz: number, rx = 0, ry = 0, rz = 0): THREE.BufferGeometry { const g = src.clone(); g.userData = {}; const m = new THREE.Matrix4().compose(new THREE.Vector3(x, y, z), new THREE.Quaternion().setFromEuler(new THREE.Euler(rx, ry, rz)), new THREE.Vector3(sx, sy, sz)); g.applyMatrix4(m); return g; } export interface GeoSink { add(mat: THREE.Material, g: THREE.BufferGeometry, castShadow?: boolean): void } /** Recolector de geometrías por material; al vaciarse fusiona en mallas. */ export class GeoBatch implements GeoSink { private lists = new Map(); private flags = new Map(); add(mat: THREE.Material, g: THREE.BufferGeometry, castShadow = true): void { let l = this.lists.get(mat); if (!l) { l = []; this.lists.set(mat, l); this.flags.set(mat, { cast: castShadow }); } l.push(normalizeFull(g)); } get empty(): boolean { return this.lists.size === 0; } /** Crea una malla por material y vacía el lote. */ flush(parent: THREE.Object3D, name = 'terrain'): THREE.Mesh[] { const out: THREE.Mesh[] = []; for (const [mat, list] of this.lists) { if (!list.length) continue; const merged = list.length === 1 ? list[0] : mergeGeometries(list, false); if (list.length > 1) for (const g of list) g.dispose(); if (!merged) continue; merged.computeBoundingSphere(); const m = new THREE.Mesh(merged, mat); m.name = name; m.castShadow = this.flags.get(mat)?.cast ?? true; m.receiveShadow = true; parent.add(m); out.push(m); } this.lists.clear(); this.flags.clear(); return out; } } export { mergeGeometries };