@greenborn/mapa-voxel-back 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,447 @@
1
+ // construirMapa.js - Genera un mapa completo: alturas, estructuras, chunks,
2
+ // luces e índice de salas.
3
+ //
4
+ // No tiene efectos al importarse. Pensado para correrse en un worker (el
5
+ // host decide dónde): ver `buffersTransferibles` para pasar el resultado sin
6
+ // copiar los buffers grandes.
7
+ //
8
+ // Opciones de `construirMapa(opciones)`:
9
+ // - modo: 'zombies' | 'equipos' | otro (sin bases especiales).
10
+ // Configuración del mundo (tamaño, minimapas): ver `configurarMundo` en
11
+ // mapConfig.js. Datos de juego (autos, árboles, etc.): ver plugins/datos.js.
12
+ import { generateMapType3, generateVolumeType3 } from './mapType3.js';
13
+ import { WORLD_CONFIG, BLOCK_TYPES, isTintableMinimap, tintBlockMinimap } from './mapConfig.js';
14
+ import { idPaleta, claveTinte, compactarMapaAlturas } from '../formato/chunk_compacto.js';
15
+ import { CONFIG } from '../plugins/datos.js';
16
+ import { pluginsFaltantes } from '../plugins/registro.js';
17
+ import { COLORES_EQUIPO } from '../plugins/datos.js';
18
+ import { generarNidos } from './genera_nidos.js';
19
+ import { generarRefugios } from './genera_refugios.js';
20
+ import { elegirTiendas } from './genera_tiendas.js';
21
+ import { ID_LUZ_INTERIOR } from '../plugins/datos.js';
22
+
23
+ /**
24
+ * Elige, para cada bando del modo zombies, una casa YA generada por el
25
+ * algoritmo normal (nunca se construye nada nuevo) para que haga de base. Se
26
+ * agrupan las estructuras por `parcelId` (cada parcela es una casa completa,
27
+ * con todos sus ambientes y pisos) y se calcula la caja que la contiene.
28
+ *
29
+ * Las dos bases quedan en cuadras opuestas del mapa: una casa del cuadrante
30
+ * noroeste para los humanos y otra del cuadrante sudeste para los zombies,
31
+ * sorteada al azar entre las candidatas de cada cuadrante. Si algún
32
+ * cuadrante no tiene casas (mapa chico o mala suerte), se cae a la candidata
33
+ * más cercana a esa esquina entre todas las que hay.
34
+ *
35
+ * Devuelve `[zonaHumana, zonaZombie]`, cada una `{ x, z, radio }` en el mismo
36
+ * formato que antes usaba `ZONAS_ESPECIALES`: centro de la casa elegida y un
37
+ * radio que cubre su huella (con margen), para que `buscarSpawn` sortee
38
+ * puntos de aparición dentro de ella.
39
+ */
40
+ function elegirBasesEnEdificios(structures, width, depth) {
41
+ const porParcela = new Map();
42
+ for (const s of structures) {
43
+ if (!s || !s.parcelId || s.type === 'spawn') continue;
44
+ // `techo`: altura real del punto más alto de la casa (y + alto de la
45
+ // sala). `maxHeightMap` sólo guarda el nivel del suelo, no los edificios.
46
+ const tope = (s.y || 0) + (s.height || 0);
47
+ let caja = porParcela.get(s.parcelId);
48
+ if (!caja) {
49
+ caja = { minX: s.x, minZ: s.z, maxX: s.x + s.width, maxZ: s.z + s.depth, techo: tope };
50
+ porParcela.set(s.parcelId, caja);
51
+ } else {
52
+ caja.minX = Math.min(caja.minX, s.x);
53
+ caja.minZ = Math.min(caja.minZ, s.z);
54
+ caja.maxX = Math.max(caja.maxX, s.x + s.width);
55
+ caja.maxZ = Math.max(caja.maxZ, s.z + s.depth);
56
+ caja.techo = Math.max(caja.techo, tope);
57
+ }
58
+ }
59
+
60
+ // sólo casas de un tamaño razonable: descarta restos de parcelas que no
61
+ // llegaron a construirse (hueco demasiado chico para una casa real).
62
+ // También se descartan las pegadas al borde del mapa: `buscarSpawn`
63
+ // fuerza los puntos de aparición a quedar a `MARGEN_BORDE` del límite
64
+ // (ver `multijugador.js`), así que una base ahí terminaría generando
65
+ // jugadores fuera de su propia parcela, pisando el límite del mundo.
66
+ const TAMANO_MIN = 20;
67
+ const MARGEN_BASE = 40;
68
+ const candidatas = [...porParcela.values()]
69
+ .filter(c => (c.maxX - c.minX) >= TAMANO_MIN && (c.maxZ - c.minZ) >= TAMANO_MIN)
70
+ .filter(c => c.minX >= MARGEN_BASE && c.maxX <= width - MARGEN_BASE &&
71
+ c.minZ >= MARGEN_BASE && c.maxZ <= depth - MARGEN_BASE)
72
+ .map(c => ({
73
+ cx: (c.minX + c.maxX) / 2,
74
+ cz: (c.minZ + c.maxZ) / 2,
75
+ radio: Math.max(c.maxX - c.minX, c.maxZ - c.minZ) / 2 + 6,
76
+ caja: { minX: c.minX, minZ: c.minZ, maxX: c.maxX, maxZ: c.maxZ, techo: c.techo }
77
+ }));
78
+
79
+ const medioX = width / 2, medioZ = depth / 2;
80
+ const poolHumano = candidatas.filter(c => c.cx < medioX && c.cz < medioZ);
81
+ const poolZombie = candidatas.filter(c => c.cx >= medioX && c.cz >= medioZ);
82
+
83
+ const alAzar = (arr) => arr[Math.floor(Math.random() * arr.length)];
84
+ // fallback: sin candidatas en el cuadrante propio, la más cercana a esa
85
+ // esquina entre todas las casas del mapa (mejor eso que no tener base).
86
+ const masCercanaA = (ex, ez) => candidatas.reduce((mejor, c) => {
87
+ const d = Math.hypot(c.cx - ex, c.cz - ez);
88
+ return (!mejor || d < mejor.d) ? { c, d } : mejor;
89
+ }, null)?.c;
90
+
91
+ const zonaHumana = poolHumano.length ? alAzar(poolHumano) : masCercanaA(0, 0);
92
+ const zonaZombie = poolZombie.length ? alAzar(poolZombie) : masCercanaA(width, depth);
93
+
94
+ return [
95
+ zonaHumana && { x: zonaHumana.cx, z: zonaHumana.cz, radio: zonaHumana.radio, caja: zonaHumana.caja },
96
+ zonaZombie && { x: zonaZombie.cx, z: zonaZombie.cz, radio: zonaZombie.radio, caja: zonaZombie.caja }
97
+ ];
98
+ }
99
+
100
+ /** Luces del mapa: ambiente, sol y una point light en la sala inicial. */
101
+ function construirLuces(room) {
102
+ const lights = [];
103
+
104
+ // AmbientLight aumentada para iluminar escenas oscuras fuera de las fuentes directas
105
+ lights.push({
106
+ type: 'ambient',
107
+ color: 0xFFFFFF,
108
+ intensity: .5
109
+ });
110
+
111
+ // DirectionalLight para amanecer
112
+ lights.push({
113
+ type: 'directional',
114
+ position: [0, 50, 0],
115
+ color: 0xffffff,
116
+ intensity: 5,
117
+ castShadow: true
118
+ });
119
+
120
+ // Sólo se considera el comportamiento de tipo3. añadimos una PointLight
121
+ // si la sala inicial (`room`) está definida.
122
+ if (room) {
123
+ const centerX = room.x + Math.floor(room.width / 2);
124
+ const centerZ = room.z + Math.floor(room.depth / 2);
125
+ const lightY = room.y + Math.floor(room.height / 2); // Centro vertical de la sala para mejor iluminación
126
+ lights.push({
127
+ type: 'point',
128
+ position: [centerX, lightY, centerZ],
129
+ color: 0xffffff,
130
+ intensity: 10.0,
131
+ distance: CONFIG.lighting.point.distance,
132
+ castShadow: true
133
+ });
134
+ }
135
+
136
+ return lights;
137
+ }
138
+
139
+ // Parte el volumen en chunks con el formato compacto de
140
+ // `cliente/chunks/chunk_compacto.js` (leer ahí el detalle): de cada chunk sólo
141
+ // se guardan las capas que no son subsuelo macizo ni cielo, y los tintes van
142
+ // en arrays tipados + paleta en lugar de un objeto por celda.
143
+ function dividirEnChunks(volume, chunkSize) {
144
+ const chunks = {};
145
+ const numChunksX = Math.ceil(volume.width / chunkSize);
146
+ const numChunksZ = Math.ceil(volume.depth / chunkSize);
147
+ const volH = volume.height;
148
+ const volD = volume.depth;
149
+ const RELLENO = BLOCK_TYPES.BROWN; // subsuelo (ver generateVolumeType3)
150
+
151
+ // Celdas escritas por encima de lo previsto para su columna (ver
152
+ // `overflow` en volumeBuffer.js): casi nunca hay, pero si hay tienen que
153
+ // entrar en el rango de capas de su chunk.
154
+ const topeOverflow = new Map(); // chunkKey -> y máxima + 1
155
+ for (const idx of volume.overflow.keys()) {
156
+ const x = Math.floor(idx / (volH * volD));
157
+ const resto = idx - x * volH * volD;
158
+ const y = Math.floor(resto / volD);
159
+ const z = resto - y * volD;
160
+ const key = `${Math.floor(x / chunkSize)}_${Math.floor(z / chunkSize)}`;
161
+ if ((topeOverflow.get(key) || 0) < y + 1) topeOverflow.set(key, y + 1);
162
+ }
163
+
164
+ for (let chunkX = 0; chunkX < numChunksX; chunkX++) {
165
+ for (let chunkZ = 0; chunkZ < numChunksZ; chunkZ++) {
166
+ const chunkKey = `${chunkX}_${chunkZ}`;
167
+ const startX = chunkX * chunkSize;
168
+ const endX = Math.min(startX + chunkSize, volume.width);
169
+ const startZ = chunkZ * chunkSize;
170
+ const endZ = Math.min(startZ + chunkSize, volume.depth);
171
+
172
+ const cw = endX - startX;
173
+ const cd = endZ - startZ;
174
+
175
+ // Rango vertical que hace falta guardar: desde la primera capa
176
+ // donde alguna columna deja de ser subsuelo hasta la última con
177
+ // algún bloque.
178
+ let yBase = volH;
179
+ let yTope = topeOverflow.get(chunkKey) || 0;
180
+ for (let lx = 0; lx < cw; lx++) {
181
+ const gx = startX + lx;
182
+ for (let lz = 0; lz < cd; lz++) {
183
+ const gz = startZ + lz;
184
+ let tope = volume.colHeights[gx * volD + gz];
185
+ while (tope > 0 && volume.getType(gx, tope - 1, gz) === 0) tope--;
186
+ if (tope > yTope) yTope = tope;
187
+ let piso = 0;
188
+ while (piso < yBase && volume.getType(gx, piso, gz) === RELLENO) piso++;
189
+ if (piso < yBase) yBase = piso;
190
+ }
191
+ }
192
+ if (yTope <= yBase) {
193
+ // chunk sin nada más que subsuelo: una capa (de aire) alcanza
194
+ yBase = Math.min(yBase, volH - 1);
195
+ yTope = yBase + 1;
196
+ }
197
+ const capas = yTope - yBase;
198
+
199
+ // Uint8Array empaquetado: 4 bits/celda (2 celdas por byte), ya que
200
+ // los tipos de bloque actuales van de 0 a 13 y entran en un nibble.
201
+ // El nibble alto/bajo dentro del byte se elige con `idx & 1` (ver
202
+ // leerVoxel/escribirVoxel en chunk_compacto.js).
203
+ const chunkTypes = new Uint8Array(Math.ceil((cw * capas * cd) / 2));
204
+ for (let lx = 0; lx < cw; lx++) {
205
+ const gx = startX + lx;
206
+ for (let yl = 0; yl < capas; yl++) {
207
+ const fila = (lx * capas + yl) * cd;
208
+ for (let lz = 0; lz < cd; lz++) {
209
+ const val = volume.getType(gx, yBase + yl, startZ + lz) & 0x0F;
210
+ if (val === 0) continue;
211
+ const dstIdx = fila + lz;
212
+ chunkTypes[dstIdx >> 1] |= val << ((dstIdx & 1) << 2);
213
+ }
214
+ }
215
+ }
216
+
217
+ chunks[chunkKey] = {
218
+ types: chunkTypes,
219
+ yBase,
220
+ capas,
221
+ relleno: RELLENO,
222
+ volumeWidth: cw,
223
+ volumeHeight: volH,
224
+ volumeDepth: cd,
225
+ tintClaves: null,
226
+ tintIds: null,
227
+ tintN: 0,
228
+ tintPaleta: [null],
229
+ startX,
230
+ startZ,
231
+ entities: []
232
+ };
233
+ }
234
+ }
235
+
236
+ // Tintes: UNA pasada por las celdas tintadas (antes se consultaba el Map
237
+ // por cada una de las ~38 millones de celdas del mapa), repartiéndolas al
238
+ // chunk que les toca. Clave y id de paleta van juntos en un solo número
239
+ // (clave * 65536 + id) para poder ordenar por clave con un sort nativo.
240
+ const porChunk = new Map(); // chunkKey -> number[]
241
+ const idLocal = new Map(); // chunkKey -> Map<id global, id del chunk>
242
+ for (const [idx, idGlobal] of volume.tints) {
243
+ const x = Math.floor(idx / (volH * volD));
244
+ const resto = idx - x * volH * volD;
245
+ const y = Math.floor(resto / volD);
246
+ const z = resto - y * volD;
247
+ const chunkKey = `${Math.floor(x / chunkSize)}_${Math.floor(z / chunkSize)}`;
248
+ const c = chunks[chunkKey];
249
+ if (!c) continue;
250
+ let ids = idLocal.get(chunkKey);
251
+ if (!ids) { ids = new Map(); idLocal.set(chunkKey, ids); porChunk.set(chunkKey, []); }
252
+ let id = ids.get(idGlobal);
253
+ if (id === undefined) {
254
+ const t = volume.paleta[idGlobal];
255
+ id = idPaleta(c, t.tintMinimap || null, t.tintRender || null);
256
+ ids.set(idGlobal, id);
257
+ }
258
+ if (id === 0) continue;
259
+ porChunk.get(chunkKey).push(claveTinte(c, x - c.startX, y, z - c.startZ) * 65536 + id);
260
+ }
261
+ for (const [chunkKey, lista] of porChunk) {
262
+ const c = chunks[chunkKey];
263
+ const ordenado = Float64Array.from(lista).sort();
264
+ const n = ordenado.length;
265
+ c.tintClaves = new Uint32Array(n);
266
+ c.tintIds = new Uint16Array(n);
267
+ for (let i = 0; i < n; i++) {
268
+ const v = ordenado[i];
269
+ const clave = Math.floor(v / 65536);
270
+ c.tintClaves[i] = clave;
271
+ c.tintIds[i] = v - clave * 65536;
272
+ }
273
+ c.tintN = n;
274
+ }
275
+
276
+ return chunks;
277
+ }
278
+
279
+ // -----------------------------------------------------------------------------
280
+ // índice de salas para búsquedas rápidas por posición
281
+ // cada sala recibe un id numérico y se guarda en un diccionario `byId`.
282
+ // también generamos dos listas ordenadas (minX y minZ) para filtrar por ejes
283
+
284
+ function buildRoomIndex(structures) {
285
+ const byId = Object.create(null);
286
+ const sortedByMinX = [];
287
+ const sortedByMinZ = [];
288
+ let counter = 1;
289
+
290
+ for (const s of structures) {
291
+ if (s == null) continue;
292
+ // consideramos únicamente elementos con caja delimitadora válida
293
+ if (typeof s.x === 'number' && typeof s.z === 'number' &&
294
+ typeof s.width === 'number' && typeof s.depth === 'number') {
295
+ const id = counter++;
296
+ s.roomId = id; // opcional, útil para depuración
297
+ const minX = s.x;
298
+ const minZ = s.z;
299
+ const maxX = s.x + s.width - 1;
300
+ const maxZ = s.z + s.depth - 1;
301
+ const meta = { id, type: s.type || 'unknown', minX, minZ, maxX, maxZ };
302
+ byId[id] = meta;
303
+ sortedByMinX.push(meta);
304
+ sortedByMinZ.push(meta);
305
+ }
306
+ }
307
+
308
+ sortedByMinX.sort((a, b) => a.minX - b.minX);
309
+ sortedByMinZ.sort((a, b) => a.minZ - b.minZ);
310
+
311
+ return { byId, sortedByMinX, sortedByMinZ };
312
+ }
313
+
314
+ /**
315
+ * Genera un mapa nuevo. Devuelve sólo datos (clonables con structuredClone,
316
+ * así se puede pasar desde un worker): sin funciones ni instancias de clase.
317
+ */
318
+ export function construirMapa(opciones = {}) {
319
+ const faltan = pluginsFaltantes();
320
+ if (faltan.length) {
321
+ throw new Error(`construirMapa: faltan plugins de datos: ${faltan.join(', ')} (ver registrarPlugins)`);
322
+ }
323
+ const modo = opciones.modo ?? null;
324
+ const { heightMap, maxHeightMap, structures, startPosition, room, surfaceTypeMap, entities, zonas } =
325
+ generateMapType3(WORLD_CONFIG.width, WORLD_CONFIG.height, WORLD_CONFIG.volumeHeight);
326
+
327
+ // modo zombies: las bases de cada bando son casas ya generadas por el
328
+ // algoritmo normal (ver `elegirBasesEnEdificios`), nunca construcciones
329
+ // nuevas. Se eligen ACÁ, antes de pintar el minimapa, para que éste
330
+ // pueda marcar la base zombie (ver generateMapPNGs/generateVolumeType3).
331
+ // modo equipos: una base por equipo (la base i es del equipo i, ver
332
+ // EQUIPOS en cliente/equipos_config.js), con el color de cada equipo.
333
+ let zonasEspeciales = null;
334
+ if (modo === 'zombies' || modo === 'equipos') {
335
+ const bases = elegirBasesEnEdificios(structures, WORLD_CONFIG.width, WORLD_CONFIG.height);
336
+ const colores = modo === 'equipos'
337
+ ? [COLORES_EQUIPO.azul, COLORES_EQUIPO.rojo]
338
+ : [0x2f9dff, 0xff00ff];
339
+ zonasEspeciales = bases.map((b, i) => b && { ...b, color: colores[i] });
340
+ console.log('[mapa] bases elegidas entre las casas del mapa:', zonasEspeciales);
341
+ }
342
+
343
+ // nidos de zombies (supervivencia, §5): se deciden acá, con las alturas
344
+ // todavía como arrays; el modo sólo decide si el servidor los usa.
345
+ const diag = {};
346
+ const nidos = generarNidos(zonas, {
347
+ structures, entities, heightMap, surfaceTypeMap,
348
+ width: WORLD_CONFIG.width, depth: WORLD_CONFIG.height,
349
+ bases: [startPosition, zonasEspeciales && zonasEspeciales[0]], diag
350
+ });
351
+ console.log(`[mapa] ${nidos.length} nido(s) de zombies; puntos rechazados: ${JSON.stringify(diag)}`);
352
+
353
+ // refugios subterráneos (§13): se deciden junto a los nidos (los esquivan) y
354
+ // existen en todos los modos; el volumen ya sale excavado, sin excavación en
355
+ // runtime. Cada uno aporta su luz fija de sala como entidad de chunk.
356
+ const diagRef = {};
357
+ const refugios = generarRefugios(zonas, {
358
+ structures, entities, heightMap, surfaceTypeMap,
359
+ width: WORLD_CONFIG.width, depth: WORLD_CONFIG.height, nidos, startPosition, diag: diagRef
360
+ });
361
+ for (const r of refugios) {
362
+ entities.push({ type: 'entidad_objeto', model: ID_LUZ_INTERIOR, x: r.luz.x, y: r.luz.y, z: r.luz.z, siempre: true, refugio: true });
363
+ }
364
+ console.log(`[mapa] ${refugios.length} refugio(s) subterráneo(s) (${refugios.filter(r => r.salida === 'casa').length} con salida en una casa); descartes: ${JSON.stringify(diagRef)}`);
365
+
366
+ // tiendas de supervivencia (mostrador + NPC, ver genera_tiendas.js): van en salas de
367
+ // planta baja con puerta a la calle y sin botín; el servidor sólo las usa en supervivencia.
368
+ const { tiendas } = elegirTiendas(structures, { width: WORLD_CONFIG.width, depth: WORLD_CONFIG.height });
369
+
370
+ const volume = generateVolumeType3(WORLD_CONFIG.width, WORLD_CONFIG.height, WORLD_CONFIG.volumeHeight, heightMap, startPosition, room, surfaceTypeMap, structures, zonasEspeciales, refugios);
371
+
372
+ const lights = construirLuces(room);
373
+ console.log('Mapa generado exitosamente');
374
+
375
+ // teñir un bloque debajo de la posición inicial para verlo fácilmente.
376
+ // pintar únicamente en el minimapa (renderDefault se queda sin tintado)
377
+ if (startPosition) {
378
+ const sx = startPosition.x;
379
+ const sy = Math.max(0, startPosition.y - 1);
380
+ const sz = startPosition.z;
381
+ const blockType = volume.getType(sx, sy, sz);
382
+ if (blockType != null && isTintableMinimap(blockType)) {
383
+ tintBlockMinimap(volume, sx, sy, sz, 0xff00ff, 0.5);
384
+ }
385
+ }
386
+
387
+ let roomIndex = null;
388
+ if (structures && Array.isArray(structures)) {
389
+ roomIndex = buildRoomIndex(structures);
390
+ console.log('Room index built:', Object.keys(roomIndex.byId).length, 'entries');
391
+ }
392
+
393
+ // partir el volumen en chunks (los datos viven en ellos desde acá)
394
+ const chunks = dividirEnChunks(volume, WORLD_CONFIG.chunkSize);
395
+
396
+ // Distribuir entidades globales a los chunks correspondientes (si existen)
397
+ // Los autos NO van en los chunks: se mueven, así que los lleva `autos.js`
398
+ // como estado propio (ver `mapa.autos`).
399
+ const autos = [];
400
+ if (entities && Array.isArray(entities)) {
401
+ for (const ent of entities) {
402
+ if (ent.type === 'vehiculo') { autos.push(ent); continue; }
403
+ const cx = Math.floor(ent.x / WORLD_CONFIG.chunkSize);
404
+ const cz = Math.floor(ent.z / WORLD_CONFIG.chunkSize);
405
+ const key = `${cx}_${cz}`;
406
+ if (!chunks[key]) continue;
407
+ chunks[key].entities = chunks[key].entities || [];
408
+ chunks[key].entities.push(ent);
409
+ }
410
+ }
411
+
412
+ // Los mapas de altura salen del generador como arrays de arrays de
413
+ // números; el mapa terminado los lleva como un byte por celda (ver
414
+ // chunk_compacto.js). `maxHeightMap` casi siempre es idéntico a
415
+ // `heightMap`: en ese caso va null y el que lo lee usa `heightMap`.
416
+ const alturas = compactarMapaAlturas(heightMap) || heightMap;
417
+ let alturasMax = compactarMapaAlturas(maxHeightMap) || maxHeightMap;
418
+ if (alturas.datos && alturasMax && alturasMax.datos &&
419
+ alturas.datos.length === alturasMax.datos.length &&
420
+ alturas.datos.every((v, i) => v === alturasMax.datos[i])) {
421
+ alturasMax = null;
422
+ }
423
+
424
+ return {
425
+ heightMap: alturas, maxHeightMap: alturasMax, structures, startPosition, lights, chunks, roomIndex, autos,
426
+ minimapFile: volume.minimapFile, zonasEspeciales, zonas, nidos, refugios, tiendas,
427
+ modo
428
+ };
429
+ }
430
+
431
+ /**
432
+ * Buffers grandes de un mapa (voxels, tintes, mapas de altura), para pasarlos
433
+ * en la lista de transferencia de `postMessage`: cambian de hilo sin copiarse.
434
+ */
435
+ export function buffersTransferibles(mapa) {
436
+ const vistos = new Set();
437
+ const agregar = (v) => { if (v && ArrayBuffer.isView(v)) vistos.add(v.buffer); };
438
+ for (const clave in mapa.chunks) {
439
+ const c = mapa.chunks[clave];
440
+ agregar(c.types);
441
+ agregar(c.tintClaves);
442
+ agregar(c.tintIds);
443
+ }
444
+ if (mapa.heightMap) agregar(mapa.heightMap.datos);
445
+ if (mapa.maxHeightMap) agregar(mapa.maxHeightMap.datos);
446
+ return [...vistos];
447
+ }
@@ -0,0 +1,32 @@
1
+ // excavar_refugios.js - Pasa al volumen lo que decidió genera_refugios.js
2
+ // (plan_supervivencia.md §13): primero se revoca la sala (ladrillo, piso y
3
+ // techo) y después se excava el aire de la sala, la puerta, el descanso, la
4
+ // escalera y el hueco de la trampilla. La hoja de la puerta y la tapa NO son
5
+ // bloques: son entidades con estado (server/refugios.js) y el hueco queda
6
+ // vacío en el volumen.
7
+ //
8
+ // Se corre AL FINAL de generateVolumeType3, después de pintar el minimapa, así
9
+ // el hueco de la trampilla no se marca en él (los refugios son secretos).
10
+
11
+ import { BLOCK_TYPES } from './mapConfig.js';
12
+
13
+ function llenar(volume, caja, tipo, ancho, alto, profundo) {
14
+ for (let x = Math.max(0, caja.x0); x < Math.min(ancho, caja.x1); x++) {
15
+ for (let z = Math.max(0, caja.z0); z < Math.min(profundo, caja.z1); z++) {
16
+ for (let y = Math.max(0, caja.y0); y < Math.min(alto, caja.y1); y++) volume.set(x, y, z, tipo);
17
+ }
18
+ }
19
+ }
20
+
21
+ /** Devuelve la cantidad de celdas excavadas. */
22
+ export function excavarRefugios(volume, refugios, ancho, profundo, alto) {
23
+ let excavadas = 0;
24
+ for (const r of refugios || []) {
25
+ for (const c of r.acabado || []) llenar(volume, c, BLOCK_TYPES[c.bloque], ancho, alto, profundo);
26
+ for (const c of r.excavar) {
27
+ llenar(volume, c, BLOCK_TYPES.AIR, ancho, alto, profundo);
28
+ excavadas += (c.x1 - c.x0) * (c.y1 - c.y0) * (c.z1 - c.z0);
29
+ }
30
+ }
31
+ return excavadas;
32
+ }
@@ -0,0 +1,87 @@
1
+ export function connectBathrooms(structures) {
2
+ const len = structures.length;
3
+ for (let i = 0; i < len; i++) {
4
+ const s = structures[i];
5
+ if (s.type !== 'banio' || !s.parcelId) continue;
6
+ if (s.openNorth || s.openSouth || s.openEast || s.openWest) continue;
7
+
8
+ const tryLink = (t) => {
9
+ const sx0 = s.x, sx1 = s.x + s.width;
10
+ const sz0 = s.z, sz1 = s.z + s.depth;
11
+ const tx0 = t.x, tx1 = t.x + t.width;
12
+ const tz0 = t.z, tz1 = t.z + t.depth;
13
+ // vertical wall
14
+ if (sx1 === tx0 || tx1 === sx0) {
15
+ const overlapZ0 = Math.max(sz0, tz0);
16
+ const overlapZ1 = Math.min(sz1, tz1);
17
+ const overlapLen = overlapZ1 - overlapZ0;
18
+ if (overlapLen > 2) {
19
+ const doorWidth = Math.min(4, overlapLen - 2);
20
+ const doorZStart = overlapZ0 + Math.floor((overlapLen - doorWidth) / 2);
21
+ if (sx1 === tx0) {
22
+ s.openEast = true;
23
+ s.openEastRange = { start: doorZStart, end: doorZStart + doorWidth };
24
+ t.openWest = true;
25
+ t.openWestRange = { start: doorZStart, end: doorZStart + doorWidth };
26
+ } else {
27
+ s.openWest = true;
28
+ s.openWestRange = { start: doorZStart, end: doorZStart + doorWidth };
29
+ t.openEast = true;
30
+ t.openEastRange = { start: doorZStart, end: doorZStart + doorWidth };
31
+ }
32
+ return true;
33
+ }
34
+ }
35
+ // horizontal wall
36
+ if (sz1 === tz0 || tz1 === sz0) {
37
+ const overlapX0 = Math.max(sx0, tx0);
38
+ const overlapX1 = Math.min(sx1, tx1);
39
+ const overlapLen = overlapX1 - overlapX0;
40
+ if (overlapLen > 2) {
41
+ const doorWidth = Math.min(4, overlapLen - 2);
42
+ const doorXStart = overlapX0 + Math.floor((overlapLen - doorWidth) / 2);
43
+ if (sz1 === tz0) {
44
+ s.openSouth = true;
45
+ s.openSouthRange = { start: doorXStart, end: doorXStart + doorWidth };
46
+ t.openNorth = true;
47
+ t.openNorthRange = { start: doorXStart, end: doorXStart + doorWidth };
48
+ } else {
49
+ s.openNorth = true;
50
+ s.openNorthRange = { start: doorXStart, end: doorXStart + doorWidth };
51
+ t.openSouth = true;
52
+ t.openSouthRange = { start: doorXStart, end: doorXStart + doorWidth };
53
+ }
54
+ return true;
55
+ }
56
+ }
57
+ return false;
58
+ };
59
+
60
+ // classify structures by priority
61
+ const halls = [];
62
+ let mainRoom = null;
63
+ const others = [];
64
+ for (let j = 0; j < len; j++) {
65
+ const t = structures[j];
66
+ if (t.parcelId !== s.parcelId || t === s) continue;
67
+ if (t.type === 'hallway') halls.push(t);
68
+ else if (t.frontNorth || t.frontSouth || t.frontEast || t.frontWest) {
69
+ if (!mainRoom) mainRoom = t;
70
+ } else if (t.type !== 'banio') {
71
+ others.push(t);
72
+ }
73
+ }
74
+
75
+ const tryList = (list) => {
76
+ for (const t of list) {
77
+ if (tryLink(t)) return true;
78
+ }
79
+ return false;
80
+ };
81
+
82
+ // attempt each priority in turn
83
+ if (tryList(halls)) continue;
84
+ if (mainRoom && tryLink(mainRoom)) continue;
85
+ tryList(others);
86
+ }
87
+ }
@@ -0,0 +1,104 @@
1
+ // -------------------------------------------------------------------------
2
+ // conexiones de baños
3
+ // -------------------------------------------------------------------------
4
+
5
+ /**
6
+ * Cada baño puede generar **una única** abertura.
7
+ * Prioridad de conexión:
8
+ * 1. cualquier pasillo adyacente
9
+ * 2. la sala principal (la que tenga bandera front*)
10
+ * 3. cualquier otra habitación no-baño dentro de la misma parcela
11
+ *
12
+ * La puerta se centra en el segmento de solapamiento para evitar partirla.
13
+ */
14
+ export function connectBathrooms(structures) {
15
+ const len = structures.length;
16
+ for (let i = 0; i < len; i++) {
17
+ const s = structures[i];
18
+ if (s.type !== 'banio' || !s.parcelId) continue;
19
+ if (s.openNorth || s.openSouth || s.openEast || s.openWest) continue;
20
+
21
+ const tryLink = (t) => {
22
+ const sx0 = s.x, sx1 = s.x + s.width;
23
+ const sz0 = s.z, sz1 = s.z + s.depth;
24
+ const tx0 = t.x, tx1 = t.x + t.width;
25
+ const tz0 = t.z, tz1 = t.z + t.depth;
26
+ // vertical wall
27
+ if (sx1 === tx0 || tx1 === sx0) {
28
+ const overlapZ0 = Math.max(sz0, tz0);
29
+ const overlapZ1 = Math.min(sz1, tz1);
30
+ const overlapLen = overlapZ1 - overlapZ0;
31
+ if (overlapLen > 2) {
32
+ const doorWidth = Math.min(4, overlapLen - 2);
33
+ const doorZStart = overlapZ0 + Math.floor((overlapLen - doorWidth) / 2);
34
+ if (sx1 === tx0) {
35
+ s.openEast = true;
36
+ s.openEastRange = { start: doorZStart, end: doorZStart + doorWidth };
37
+ t.openWest = true;
38
+ t.openWestRange = { start: doorZStart, end: doorZStart + doorWidth };
39
+ } else {
40
+ s.openWest = true;
41
+ s.openWestRange = { start: doorZStart, end: doorZStart + doorWidth };
42
+ t.openEast = true;
43
+ t.openEastRange = { start: doorZStart, end: doorZStart + doorWidth };
44
+ }
45
+ return true;
46
+ }
47
+ }
48
+ // horizontal wall
49
+ if (sz1 === tz0 || tz1 === sz0) {
50
+ const overlapX0 = Math.max(sx0, tx0);
51
+ const overlapX1 = Math.min(sx1, tx1);
52
+ const overlapLen = overlapX1 - overlapX0;
53
+ if (overlapLen > 2) {
54
+ const doorWidth = Math.min(4, overlapLen - 2);
55
+ const doorXStart = overlapX0 + Math.floor((overlapLen - doorWidth) / 2);
56
+ if (sz1 === tz0) {
57
+ s.openSouth = true;
58
+ s.openSouthRange = { start: doorXStart, end: doorXStart + doorWidth };
59
+ t.openNorth = true;
60
+ t.openNorthRange = { start: doorXStart, end: doorXStart + doorWidth };
61
+ } else {
62
+ s.openNorth = true;
63
+ s.openNorthRange = { start: doorXStart, end: doorXStart + doorWidth };
64
+ t.openSouth = true;
65
+ t.openSouthRange = { start: doorXStart, end: doorXStart + doorWidth };
66
+ }
67
+ return true;
68
+ }
69
+ }
70
+ return false;
71
+ };
72
+
73
+ // build candidate lists
74
+ let candidates = [];
75
+ // 1. hallways
76
+ for (let j = 0; j < len; j++) {
77
+ const t = structures[j];
78
+ if (t.parcelId === s.parcelId && t.type === 'hallway') candidates.push(t);
79
+ }
80
+ // 2. main room
81
+ if (candidates.length === 0) {
82
+ for (let j = 0; j < len; j++) {
83
+ const t = structures[j];
84
+ if (t.parcelId === s.parcelId && (t.frontNorth || t.frontSouth || t.frontEast || t.frontWest)) {
85
+ candidates.push(t);
86
+ break;
87
+ }
88
+ }
89
+ }
90
+ // 3. other rooms
91
+ if (candidates.length === 0) {
92
+ for (let j = 0; j < len; j++) {
93
+ const t = structures[j];
94
+ if (t.parcelId === s.parcelId && t.type !== 'hallway' && t.type !== 'banio') {
95
+ candidates.push(t);
96
+ }
97
+ }
98
+ }
99
+
100
+ for (const t of candidates) {
101
+ if (tryLink(t)) break;
102
+ }
103
+ }
104
+ }