LINE1 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150123456import * as THREE from 'three';7import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';8import { HERO_MODEL_DIR, HERO_MODEL_FILES, MODEL_DIR, MODEL_FILES, VILLAGE_WATER_TEXTURE } from './assets.js';9import * as hex from './hex.js';1011const STATUS_COLORS = {12 ward: 0x7fd7ff,13 poison: 0x8ade6c,14 marked: 0xffb15c,15 rooted: 0xb98a5c,16};1718const ATTACK_COLORS = {19 attack: 0xffd27f,20 retaliate: 0xff9a6b,21 cast: 0xa98bff,22 damage: 0xff4d5e,23};242526function flatDirection(from, to) {27 const dx = to.x - from.x;28 const dz = to.z - from.z;29 const length = Math.hypot(dx, dz) || 1;30 return new THREE.Vector3(dx / length, 0, dz / length);31}323334function shadeTexture(size = 128, reach = 1) {35 const canvas = document.createElement('canvas');36 canvas.width = size;37 canvas.height = size;38 const context = canvas.getContext('2d');39 const gradient = context.createLinearGradient(0, 0, size, 0);40 41 42 gradient.addColorStop(0, 'rgba(10, 7, 16, 0)');43 gradient.addColorStop(reach * 0.32, 'rgba(10, 7, 16, 0.4)');44 gradient.addColorStop(reach * 0.62, 'rgba(10, 7, 16, 0.78)');45 gradient.addColorStop(reach, 'rgba(10, 7, 16, 1)');46 gradient.addColorStop(1, 'rgba(10, 7, 16, 1)');47 context.fillStyle = gradient;48 context.fillRect(0, 0, size, size);49 const texture = new THREE.CanvasTexture(canvas);50 texture.colorSpace = THREE.SRGBColorSpace;51 return texture;52}535455function radialTexture(size = 128) {56 const canvas = document.createElement('canvas');57 canvas.width = size;58 canvas.height = size;59 const context = canvas.getContext('2d');60 const gradient = context.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);61 gradient.addColorStop(0, 'rgba(255, 255, 255, 0.95)');62 gradient.addColorStop(0.4, 'rgba(255, 255, 255, 0.4)');63 gradient.addColorStop(1, 'rgba(255, 255, 255, 0)');64 context.fillStyle = gradient;65 context.fillRect(0, 0, size, size);66 const texture = new THREE.CanvasTexture(canvas);67 texture.colorSpace = THREE.SRGBColorSpace;68 return texture;69}707172function environmentTexture() {73 const canvas = document.createElement('canvas');74 canvas.width = 512;75 canvas.height = 256;76 const context = canvas.getContext('2d');7778 const sky = context.createLinearGradient(0, 0, 0, 256);79 sky.addColorStop(0, '#121022');80 sky.addColorStop(0.42, '#3a2a4a');81 sky.addColorStop(0.56, '#6b4630');82 sky.addColorStop(1, '#120d12');83 context.fillStyle = sky;84 context.fillRect(0, 0, 512, 256);8586 for (const [x, y, radius, color] of [87 [96, 118, 74, 'rgba(255, 148, 70, 0.85)'],88 [408, 104, 96, 'rgba(172, 112, 255, 0.55)'],89 [256, 54, 128, 'rgba(118, 96, 196, 0.28)'],90 ]) {91 const glow = context.createRadialGradient(x, y, 0, x, y, radius);92 glow.addColorStop(0, color);93 glow.addColorStop(1, 'rgba(0, 0, 0, 0)');94 context.fillStyle = glow;95 context.beginPath();96 context.arc(x, y, radius, 0, Math.PI * 2);97 context.fill();98 }99100 const texture = new THREE.CanvasTexture(canvas);101 texture.mapping = THREE.EquirectangularReflectionMapping;102 texture.colorSpace = THREE.SRGBColorSpace;103 return texture;104}105106107function fabricTexture(size = 128) {108 const canvas = document.createElement('canvas');109 canvas.width = size;110 canvas.height = size;111 const context = canvas.getContext('2d');112 const image = context.createImageData(size, size);113 let seed = 977;114 const random = () => {115 seed = (seed * 16807) % 2147483647;116 return seed / 2147483647;117 };118 for (let index = 0; index < size * size; index += 1) {119 const value = 226 + random() * 29;120 image.data[index * 4] = value;121 image.data[index * 4 + 1] = value;122 image.data[index * 4 + 2] = value;123 image.data[index * 4 + 3] = 255;124 }125 context.putImageData(image, 0, 0);126 const texture = new THREE.CanvasTexture(canvas);127 texture.wrapS = THREE.RepeatWrapping;128 texture.wrapT = THREE.RepeatWrapping;129 texture.repeat.set(3, 3);130 texture.colorSpace = THREE.SRGBColorSpace;131 return texture;132}133134135function seeded(seed) {136 let state = seed;137 return () => {138 state = (state * 16807) % 2147483647;139 return state / 2147483647;140 };141}142143144function surfaceTexture(size = 128) {145 const canvas = document.createElement('canvas');146 canvas.width = size;147 canvas.height = size;148 const context = canvas.getContext('2d');149 const image = context.createImageData(size, size);150 let seed = 431;151 const random = () => {152 seed = (seed * 16807) % 2147483647;153 return seed / 2147483647;154 };155 for (let index = 0; index < size * size; index += 1) {156 const value = 180 + random() * 75;157 image.data[index * 4] = value;158 image.data[index * 4 + 1] = value;159 image.data[index * 4 + 2] = value;160 image.data[index * 4 + 3] = 255;161 }162 context.putImageData(image, 0, 0);163 const texture = new THREE.CanvasTexture(canvas);164 texture.wrapS = THREE.RepeatWrapping;165 texture.wrapT = THREE.RepeatWrapping;166 texture.repeat.set(2, 2);167 texture.colorSpace = THREE.NoColorSpace;168 return texture;169}170171172function runeTexture(size = 512) {173 const canvas = document.createElement('canvas');174 canvas.width = size;175 canvas.height = size;176 const context = canvas.getContext('2d');177 context.translate(size / 2, size / 2);178 context.strokeStyle = 'rgba(255, 214, 150, 0.9)';179 context.lineCap = 'round';180181 let seed = 19;182 const random = () => {183 seed = (seed * 16807) % 2147483647;184 return seed / 2147483647;185 };186187 for (const [radius, width] of [[204, 3], [192, 1.4], [150, 1.2], [96, 1]]) {188 context.beginPath();189 context.arc(0, 0, radius, 0, Math.PI * 2);190 context.lineWidth = width;191 context.stroke();192 }193194 for (let index = 0; index < 48; index += 1) {195 const angle = (index / 48) * Math.PI * 2;196 const inner = 192;197 const outer = index % 4 === 0 ? 210 : 201;198 context.beginPath();199 context.moveTo(Math.cos(angle) * inner, Math.sin(angle) * inner);200 context.lineTo(Math.cos(angle) * outer, Math.sin(angle) * outer);201 context.lineWidth = index % 4 === 0 ? 2.2 : 1;202 context.stroke();203 }204205 for (let index = 0; index < 16; index += 1) {206 const angle = (index / 16) * Math.PI * 2 + 0.07;207 context.save();208 context.translate(Math.cos(angle) * 170, Math.sin(angle) * 170);209 context.rotate(angle + Math.PI / 2);210 context.lineWidth = 1.6;211 context.beginPath();212 const strokes = 2 + Math.floor(random() * 3);213 for (let stroke = 0; stroke < strokes; stroke += 1) {214 context.moveTo((random() - 0.5) * 18, (random() - 0.5) * 22);215 context.lineTo((random() - 0.5) * 18, (random() - 0.5) * 22);216 }217 context.stroke();218 context.restore();219 }220221 context.beginPath();222 for (let index = 0; index < 6; index += 1) {223 const angle = (index / 6) * Math.PI * 2 - Math.PI / 2;224 const x = Math.cos(angle) * 74;225 const y = Math.sin(angle) * 74;226 if (index === 0) context.moveTo(x, y);227 else context.lineTo(x, y);228 }229 context.closePath();230 context.lineWidth = 2;231 context.stroke();232233 const texture = new THREE.CanvasTexture(canvas);234 texture.colorSpace = THREE.SRGBColorSpace;235 return texture;236}237238239240241242243function valueNoiseField(size, seed, cells = [6, 12, 24, 48]) {244 const random = seeded(seed);245 const octaves = cells.map((count, index) => ({246 cells: count,247 amplitude: 0.55 / (index + 1),248 grid: Array.from({ length: count * count }, () => random()),249 }));250 const wrap = (value, cells) => ((value % cells) + cells) % cells;251 const sample = (layer, u, v) => {252 const fx = u * layer.cells;253 const fy = v * layer.cells;254 const x0 = Math.floor(fx);255 const y0 = Math.floor(fy);256 const tx = fx - x0;257 const ty = fy - y0;258 const sx = tx * tx * (3 - 2 * tx);259 const sy = ty * ty * (3 - 2 * ty);260 const row0 = wrap(y0, layer.cells) * layer.cells;261 const row1 = wrap(y0 + 1, layer.cells) * layer.cells;262 const left = wrap(x0, layer.cells);263 const right = wrap(x0 + 1, layer.cells);264 const a = layer.grid[row0 + left];265 const b = layer.grid[row0 + right];266 const c = layer.grid[row1 + left];267 const d = layer.grid[row1 + right];268 return (a * (1 - sx) + b * sx) * (1 - sy) + (c * (1 - sx) + d * sx) * sy;269 };270271 const field = new Float32Array(size * size);272 for (let y = 0; y < size; y += 1) {273 for (let x = 0; x < size; x += 1) {274 let value = 0;275 for (const layer of octaves) value += sample(layer, x / size, y / size) * layer.amplitude;276 field[y * size + x] = value;277 }278 }279 return { field, random };280}281282283284285286function tileDrawable(size, draw) {287 for (let dy = -1; dy <= 1; dy += 1) {288 for (let dx = -1; dx <= 1; dx += 1) {289 draw(dx * size, dy * size);290 }291 }292}293294295function dirtNormalTexture(size = 512) {296 const { field, random } = valueNoiseField(size, 9182);297 for (let index = 0; index < field.length; index += 1) {298 299 field[index] += (random() - 0.5) * 0.06;300 }301302 const canvas = document.createElement('canvas');303 canvas.width = size;304 canvas.height = size;305 const context = canvas.getContext('2d');306 const image = context.createImageData(size, size);307 const at = (x, y) => field[(((y % size) + size) % size) * size + (((x % size) + size) % size)];308 const strength = 3.2;309 for (let y = 0; y < size; y += 1) {310 for (let x = 0; x < size; x += 1) {311 const dx = (at(x + 1, y) - at(x - 1, y)) * strength;312 const dy = (at(x, y + 1) - at(x, y - 1)) * strength;313 const length = Math.hypot(-dx, -dy, 1);314 const index = (y * size + x) * 4;315 image.data[index] = ((-dx / length) * 0.5 + 0.5) * 255;316 image.data[index + 1] = ((-dy / length) * 0.5 + 0.5) * 255;317 image.data[index + 2] = ((1 / length) * 0.5 + 0.5) * 255;318 image.data[index + 3] = 255;319 }320 }321 context.putImageData(image, 0, 0);322 const texture = new THREE.CanvasTexture(canvas);323 texture.wrapS = THREE.RepeatWrapping;324 texture.wrapT = THREE.RepeatWrapping;325 texture.repeat.set(8, 6.4);326 texture.colorSpace = THREE.NoColorSpace;327 return texture;328}329330331function dirtGrainTexture(size = 256) {332 const canvas = document.createElement('canvas');333 canvas.width = size;334 canvas.height = size;335 const context = canvas.getContext('2d');336 const random = seeded(8144);337 for (let index = 0; index < 1500; index += 1) {338 const x = random() * size;339 const y = random() * size;340 const radius = 0.5 + random() * 1.9;341 const light = random() < 0.45;342 context.fillStyle = light343 ? `rgba(232, 208, 172, ${0.16 + random() * 0.28})`344 : `rgba(36, 25, 16, ${0.18 + random() * 0.34})`;345 for (const [dx, dy] of [346 [0, 0],347 [-size, 0],348 [size, 0],349 [0, -size],350 [0, size],351 ]) {352 context.beginPath();353 context.arc(x + dx, y + dy, radius, 0, Math.PI * 2);354 context.fill();355 }356 }357 const texture = new THREE.CanvasTexture(canvas);358 texture.wrapS = THREE.RepeatWrapping;359 texture.wrapT = THREE.RepeatWrapping;360 texture.repeat.set(14, 10);361 texture.anisotropy = 4;362 texture.colorSpace = THREE.SRGBColorSpace;363 return texture;364}365366367368369370371372function paintedDirtTexture(size = 512) {373 const canvas = document.createElement('canvas');374 canvas.width = size;375 canvas.height = size;376 const context = canvas.getContext('2d');377 378 379 const { field, random } = valueNoiseField(size, 6131, [12, 24, 48, 96]);380381 382 383 384 const dark = [78, 62, 48];385 const light = [118, 98, 79];386 const image = context.createImageData(size, size);387 for (let index = 0; index < size * size; index += 1) {388 const wash = Math.min(1, Math.max(0, (field[index] - 0.4) * 1.9));389 const grit = 0.93 + random() * 0.14;390 for (let channel = 0; channel < 3; channel += 1) {391 image.data[index * 4 + channel] = Math.min(392 255,393 (dark[channel] + (light[channel] - dark[channel]) * wash) * grit,394 );395 }396 image.data[index * 4 + 3] = 255;397 }398 context.putImageData(image, 0, 0);399400 401 402 const speck = (x, y, draw) => {403 tileDrawable(size, (dx, dy) => draw(x + dx, y + dy));404 };405406 407 for (let index = 0; index < 1400; index += 1) {408 const x = random() * size;409 const y = random() * size;410 const radius = 0.4 + random() * 1.1;411 const pale = 128 + random() * 64;412 speck(x, y, (px, py) => {413 context.fillStyle = `rgba(${pale | 0}, ${(pale * 0.92) | 0}, ${(pale * 0.78) | 0}, ${414 0.3 + random() * 0.4415 })`;416 context.beginPath();417 context.arc(px, py, radius, 0, Math.PI * 2);418 context.fill();419 });420 }421422 423 424 for (let index = 0; index < 340; index += 1) {425 const x = random() * size;426 const y = random() * size;427 const radius = 1.4 + random() * 2.6;428 const angle = random() * Math.PI * 2;429 const pale = 132 + random() * 62;430 speck(x, y, (px, py) => {431 context.save();432 context.translate(px, py);433 context.rotate(angle);434 context.fillStyle = 'rgba(32, 22, 15, 0.5)';435 context.beginPath();436 context.ellipse(0.7, 0.9, radius, radius * 0.74, 0, 0, Math.PI * 2);437 context.fill();438 context.fillStyle = `rgb(${pale | 0}, ${(pale * 0.94) | 0}, ${(pale * 0.82) | 0})`;439 context.beginPath();440 context.ellipse(0, 0, radius, radius * 0.74, 0, 0, Math.PI * 2);441 context.fill();442 context.restore();443 });444 }445446 447 for (let index = 0; index < 700; index += 1) {448 const x = random() * size;449 const y = random() * size;450 const radius = 0.8 + random() * 2.4;451 speck(x, y, (px, py) => {452 context.fillStyle = `rgba(38, 27, 19, ${0.16 + random() * 0.24})`;453 context.beginPath();454 context.arc(px, py, radius, 0, Math.PI * 2);455 context.fill();456 });457 }458459 460 461 context.lineCap = 'round';462 for (let index = 0; index < 14; index += 1) {463 const x = random() * size;464 const y = random() * size;465 const steps = [];466 let cx = x;467 let cy = y;468 const count = 2 + Math.floor(random() * 4);469 for (let step = 0; step < count; step += 1) {470 cx += (random() - 0.5) * 26;471 cy += (random() - 0.5) * 26;472 steps.push([cx, cy]);473 }474 const alpha = 0.12 + random() * 0.14;475 const width = 0.6 + random() * 0.9;476 speck(x, y, (dx, dy) => {477 context.strokeStyle = `rgba(34, 24, 16, ${alpha})`;478 context.lineWidth = width;479 context.beginPath();480 context.moveTo(x + dx, y + dy);481 for (const [px, py] of steps) context.lineTo(px + dx, py + dy);482 context.stroke();483 });484 }485486 const texture = new THREE.CanvasTexture(canvas);487 texture.wrapS = THREE.RepeatWrapping;488 texture.wrapT = THREE.RepeatWrapping;489 texture.colorSpace = THREE.SRGBColorSpace;490 return texture;491}492493494495496497498function paintedGrassTexture(size = 512) {499 const canvas = document.createElement('canvas');500 canvas.width = size;501 canvas.height = size;502 const context = canvas.getContext('2d');503 const { field, random } = valueNoiseField(size, 4207, [16, 32, 64, 128]);504505 506 507 508 const dark = [34, 58, 46];509 const light = [82, 116, 76];510 const image = context.createImageData(size, size);511 for (let index = 0; index < size * size; index += 1) {512 const wash = Math.min(1, Math.max(0, (field[index] - 0.4) * 2));513 const grit = 0.94 + random() * 0.12;514 for (let channel = 0; channel < 3; channel += 1) {515 image.data[index * 4 + channel] = Math.min(516 255,517 (dark[channel] + (light[channel] - dark[channel]) * wash) * grit,518 );519 }520 image.data[index * 4 + 3] = 255;521 }522 context.putImageData(image, 0, 0);523524 const speck = (x, y, draw) => {525 tileDrawable(size, (dx, dy) => draw(x + dx, y + dy));526 };527528 529 for (let index = 0; index < 60; index += 1) {530 const x = random() * size;531 const y = random() * size;532 const radius = 10 + random() * 34;533 const dry = random() < 0.45;534 const [r, g, b] = dry ? [126, 112, 64] : [24, 38, 26];535 const alpha = dry ? 0.14 + random() * 0.14 : 0.16 + random() * 0.16;536 speck(x, y, (px, py) => {537 const gradient = context.createRadialGradient(px, py, 0, px, py, radius);538 gradient.addColorStop(0, `rgba(${r}, ${g}, ${b}, ${alpha})`);539 gradient.addColorStop(1, `rgba(${r}, ${g}, ${b}, 0)`);540 context.fillStyle = gradient;541 context.beginPath();542 context.arc(px, py, radius, 0, Math.PI * 2);543 context.fill();544 });545 }546547 548 549 const greens = ['#33482c', '#3c5232', '#455b38', '#4e643d', '#586d43', '#62774a', '#738554', '#7f905c'];550 const blade = (x, y, length, lean, width, color, alpha) => {551 context.globalAlpha = alpha;552 context.strokeStyle = color;553 context.lineWidth = width;554 context.beginPath();555 context.moveTo(x, y);556 context.quadraticCurveTo(x + lean * 0.3, y - length * 0.62, x + lean, y - length);557 context.stroke();558 };559 context.lineCap = 'round';560 for (let index = 0; index < 3400; index += 1) {561 const x = random() * size;562 const y = random() * size;563 const length = 5 + random() * 12;564 const lean = (random() - 0.5) * 9;565 const width = 0.7 + random() * 0.9;566 const color = greens[Math.floor(random() * greens.length)];567 const alpha = 0.45 + random() * 0.45;568 speck(x, y, (px, py) => blade(px, py, length, lean, width, color, alpha));569 }570571 572 for (let index = 0; index < 40; index += 1) {573 const x = random() * size;574 const y = random() * size;575 const spread = 3 + random() * 7;576 const count = 10 + Math.floor(random() * 9);577 const stems = Array.from({ length: count }, () => ({578 dx: (random() - 0.5) * spread * 2,579 dy: (random() - 0.5) * spread,580 length: 7 + random() * 12,581 lean: (random() - 0.5) * 11,582 width: 0.8 + random() * 0.9,583 color: greens[Math.floor(random() * greens.length)],584 alpha: 0.5 + random() * 0.45,585 }));586 speck(x, y, (px, py) => {587 for (const stem of stems) {588 blade(px + stem.dx, py + stem.dy, stem.length, stem.lean, stem.width, stem.color, stem.alpha);589 }590 });591 }592593 594 context.globalAlpha = 1;595 for (let index = 0; index < 90; index += 1) {596 const x = random() * size;597 const y = random() * size;598 const radius = 0.5 + random() * 0.8;599 const pale = 190 + random() * 45;600 speck(x, y, (px, py) => {601 context.fillStyle = `rgba(${pale | 0}, ${(pale * 0.97) | 0}, ${(pale * 0.82) | 0}, 0.55)`;602 context.beginPath();603 context.arc(px, py, radius, 0, Math.PI * 2);604 context.fill();605 });606 }607608 const texture = new THREE.CanvasTexture(canvas);609 texture.wrapS = THREE.RepeatWrapping;610 texture.wrapT = THREE.RepeatWrapping;611 texture.colorSpace = THREE.SRGBColorSpace;612 return texture;613}614615616function dirtStainTexture(width = 1024, height = 768) {617 const canvas = document.createElement('canvas');618 canvas.width = width;619 canvas.height = height;620 const context = canvas.getContext('2d');621 const random = seeded(7013);622623 const blotch = (x, y, radius, color) => {624 const gradient = context.createRadialGradient(x, y, 0, x, y, radius);625 gradient.addColorStop(0, color);626 gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');627 context.fillStyle = gradient;628 context.beginPath();629 context.arc(x, y, radius, 0, Math.PI * 2);630 context.fill();631 };632633 634 635 const edge = (gradient) => {636 context.fillStyle = gradient;637 context.fillRect(0, 0, width, height);638 };639 const top = context.createLinearGradient(0, 0, 0, 140);640 top.addColorStop(0, 'rgba(34, 22, 15, 0.3)');641 top.addColorStop(1, 'rgba(34, 22, 15, 0)');642 edge(top);643 const bottom = context.createLinearGradient(0, height, 0, height - 140);644 bottom.addColorStop(0, 'rgba(34, 22, 15, 0.24)');645 bottom.addColorStop(1, 'rgba(34, 22, 15, 0)');646 edge(bottom);647 const left = context.createLinearGradient(0, 0, 150, 0);648 left.addColorStop(0, 'rgba(34, 22, 15, 0.26)');649 left.addColorStop(1, 'rgba(34, 22, 15, 0)');650 edge(left);651 const right = context.createLinearGradient(width, 0, width - 150, 0);652 right.addColorStop(0, 'rgba(34, 22, 15, 0.26)');653 right.addColorStop(1, 'rgba(34, 22, 15, 0)');654 edge(right);655656 for (let index = 0; index < 80; index += 1) {657 const dark = random() < 0.55;658 blotch(659 random() * width,660 random() * height,661 28 + random() * 160,662 dark663 ? `rgba(50, 33, 21, ${0.05 + random() * 0.11})`664 : `rgba(224, 196, 158, ${0.04 + random() * 0.08})`,665 );666 }667668 669 context.lineCap = 'round';670 for (let index = 0; index < 24; index += 1) {671 let x = random() * width;672 let y = random() * height;673 context.beginPath();674 context.moveTo(x, y);675 const steps = 3 + Math.floor(random() * 5);676 for (let step = 0; step < steps; step += 1) {677 x += (random() - 0.5) * 52;678 y += (random() - 0.5) * 52;679 context.lineTo(x, y);680 }681 context.strokeStyle = `rgba(38, 26, 18, ${0.08 + random() * 0.1})`;682 context.lineWidth = 0.8 + random() * 1.6;683 context.stroke();684 }685686 687 const trail = (startX, drift, steps) => {688 for (let step = 0; step < steps; step += 1) {689 const t = step / steps;690 const x = startX + drift * Math.sin(t * Math.PI * 1.4) + (random() - 0.5) * 9;691 const y = 44 + t * (height - 180);692 const side = step % 2 === 0 ? -5 : 5;693 context.save();694 context.translate(x + side, y);695 context.rotate((random() - 0.5) * 0.4);696 context.beginPath();697 context.ellipse(0, 0, 2.4, 5.2, 0, 0, Math.PI * 2);698 context.fillStyle = 'rgba(42, 29, 20, 0.16)';699 context.fill();700 context.restore();701 }702 };703 trail(width * 0.36, 34, 30);704 trail(width * 0.42, 26, 24);705 trail(width * 0.63, -36, 26);706707 708 const rut = (startX, drift) => {709 const path = new Path2D();710 for (let step = 0; step <= 40; step += 1) {711 const t = step / 40;712 const x = startX + drift * Math.sin(t * Math.PI * 0.8);713 const y = t * height;714 if (step === 0) path.moveTo(x, y);715 else path.lineTo(x, y);716 }717 context.lineWidth = 7;718 context.strokeStyle = 'rgba(30, 20, 13, 0.16)';719 context.stroke(path);720 context.save();721 context.translate(2.4, 0);722 context.lineWidth = 2.4;723 context.strokeStyle = 'rgba(214, 184, 146, 0.09)';724 context.stroke(path);725 context.restore();726 };727 rut(width * 0.47, 24);728 rut(width * 0.53, 24);729730 731 for (let index = 0; index < 900; index += 1) {732 context.fillStyle =733 random() < 0.4 ? 'rgba(228, 204, 168, 0.16)' : 'rgba(44, 30, 21, 0.16)';734 context.beginPath();735 context.arc(random() * width, random() * height, 0.6 + random() * 1.7, 0, Math.PI * 2);736 context.fill();737 }738739 740 741 const pixels = context.getImageData(0, 0, width, height);742 for (let y = 0; y < height; y += 1) {743 const fy = Math.min(1, Math.min(y, height - 1 - y) / (height * 0.1));744 for (let x = 0; x < width; x += 1) {745 const fx = Math.min(1, Math.min(x, width - 1 - x) / (width * 0.1));746 const t = Math.min(fx, fy);747 pixels.data[(y * width + x) * 4 + 3] *= t * t * (3 - 2 * t);748 }749 }750 context.putImageData(pixels, 0, 0);751752 const texture = new THREE.CanvasTexture(canvas);753 texture.colorSpace = THREE.SRGBColorSpace;754 return texture;755}756757758function grassTuftTexture(size = 128) {759 const canvas = document.createElement('canvas');760 canvas.width = size;761 canvas.height = size;762 const context = canvas.getContext('2d');763 const random = seeded(5501);764 const blades = ['#5d6b32', '#6f7a3c', '#4d5a2a', '#83904b', '#7a6a3c', '#a08b52', '#56622e'];765766 767 const root = context.createRadialGradient(size / 2, size, 1, size / 2, size, size * 0.42);768 root.addColorStop(0, 'rgba(28, 25, 12, 0.55)');769 root.addColorStop(1, 'rgba(28, 25, 12, 0)');770 context.fillStyle = root;771 context.fillRect(0, size * 0.5, size, size * 0.5);772773 context.lineCap = 'round';774 for (let index = 0; index < 52; index += 1) {775 const baseX = size * 0.5 + (random() - 0.5) * size * 0.6;776 const height = size * (0.26 + random() * 0.68);777 const lean = (random() - 0.5) * size * 0.75;778 context.globalAlpha = 0.45 + random() * 0.55;779 context.strokeStyle = blades[Math.floor(random() * blades.length)];780 context.lineWidth = 1.1 + random() * 2.4;781 context.beginPath();782 context.moveTo(baseX, size);783 context.quadraticCurveTo(784 baseX + lean * 0.35,785 size - height * 0.6,786 baseX + lean,787 size - height,788 );789 context.stroke();790 }791 context.globalAlpha = 1;792 const texture = new THREE.CanvasTexture(canvas);793 texture.colorSpace = THREE.SRGBColorSpace;794 return texture;795}796797798function crossedPlaneGeometry(size = 1) {799 const half = size / 2;800 const geometry = new THREE.BufferGeometry();801 geometry.setAttribute(802 'position',803 new THREE.Float32BufferAttribute(804 [805 -half, 0, 0, half, 0, 0, half, size, 0, -half, size, 0,806 0, 0, -half, 0, 0, half, 0, size, half, 0, size, -half,807 ],808 3,809 ),810 );811 geometry.setAttribute(812 'uv',813 new THREE.Float32BufferAttribute(814 [0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1],815 2,816 ),817 );818 geometry.setIndex([0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7]);819 geometry.computeVertexNormals();820 return geometry;821}822823824function hexTileTexture(size = 128) {825 const canvas = document.createElement('canvas');826 canvas.width = size;827 canvas.height = size;828 const context = canvas.getContext('2d');829 const centerX = size / 2;830 const centerY = size / 2;831 const radius = size * 0.46;832 context.beginPath();833 for (let index = 0; index < 6; index += 1) {834 const angle = Math.PI / 6 + (index / 6) * Math.PI * 2;835 const x = centerX + Math.cos(angle) * radius;836 const y = centerY + Math.sin(angle) * radius;837 if (index === 0) context.moveTo(x, y);838 else context.lineTo(x, y);839 }840 context.closePath();841 const fill = context.createRadialGradient(centerX, centerY, radius * 0.15, centerX, centerY, radius);842 fill.addColorStop(0, 'rgba(255, 255, 255, 0.58)');843 fill.addColorStop(1, 'rgba(255, 255, 255, 0.32)');844 context.fillStyle = fill;845 context.fill();846 context.lineWidth = size * 0.035;847 context.strokeStyle = 'rgba(255, 255, 255, 0.95)';848 context.stroke();849 850 context.lineWidth = size * 0.012;851 context.strokeStyle = 'rgba(255, 255, 255, 0.28)';852 context.beginPath();853 for (let index = 0; index < 6; index += 1) {854 const angle = Math.PI / 6 + (index / 6) * Math.PI * 2;855 const x = centerX + Math.cos(angle) * radius * 0.78;856 const y = centerY + Math.sin(angle) * radius * 0.78;857 if (index === 0) context.moveTo(x, y);858 else context.lineTo(x, y);859 }860 context.closePath();861 context.stroke();862 const texture = new THREE.CanvasTexture(canvas);863 texture.colorSpace = THREE.SRGBColorSpace;864 return texture;865}866867868869870871872const CASTLE_SCALE = 0.5;873const WALL_COURSES = 4; 874const WALLS_ACROSS = 33; 875const WALLS_DEEP = 24; 876const TOWER_SCALE = 1; 877const TOWER_COURSES = 2; 878const GATE_SCALE = 1.5; 879const GATE_TOWER_OFFSET = 2; 880const BUTTRESS_SCALE = 1.4; 881882883884const DIRT_TILE = 1.1;885const VILLAGE_GROUND_TILE = 1.25;886const VILLAGE_GROUND_SIZE = 400; 887const VILLAGE_ROAD_WIDTH = 4.8;888const VILLAGE_ROAD_LENGTH = 34;889890891892893const VILLAGE_WALL_Z = -13;894const VILLAGE_WALL_SCALE = 1.3; 895const VILLAGE_WALL_COURSES = 2; 896897const VILLAGE_WALL_ACROSS = 92; 898const VILLAGE_GATE_SCALE = VILLAGE_WALL_SCALE * 2; 899const VILLAGE_TOWER_SCALE = 1.5;900const VILLAGE_TOWER_COURSES = 2;901const VILLAGE_TINT = 0xd9b696; 902903904const HOUSE_CELL = 0.5;905906const VILLAGE_SCREENS = new Set(['title', 'village']);907908export class BattleView {909 constructor(canvas) {910 this.canvas = canvas;911 this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' });912 this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));913 this.renderer.setSize(window.innerWidth, window.innerHeight);914 this.renderer.shadowMap.enabled = true;915 this.renderer.shadowMap.type = THREE.PCFShadowMap; 916 this.renderer.toneMapping = THREE.ACESFilmicToneMapping;917 this.renderer.toneMappingExposure = 1.12;918919 this.scene = new THREE.Scene();920 this.scene.background = new THREE.Color(0x0a0710);921 this.scene.fog = new THREE.Fog(0x0a0710, 20, 42);922923 this.camera = new THREE.PerspectiveCamera(924 50,925 window.innerWidth / window.innerHeight,926 0.1,927 100,928 );929 this.camera.position.set(0, 11.6, 12.8);930 this.camera.lookAt(0, -0.7, 0.5);931932 this.time = 0;933 this.cardAt = -Infinity;934 this.serial = -1;935 this.screen = 'title';936 this.models = {};937 this.heroModels = {};938 this.heroAnimations = {};939 this.unitVisuals = new Map();940 this.highlights = new Map();941 this.effects = [];942 this.projectiles = [];943 this.timers = [];944 this.attackChain = null;945 this.suppressCast = false;946 this.fixtures = [];947 this.dust = null;948 this.embers = null;949 this.rune = null;950 this.dirtTexture = null;951 this.dirtBumpTexture = null;952 this.glowTexture = radialTexture();953 this.runeTexture = runeTexture();954 this.hexTileTexture = hexTileTexture();955 this.dirtStainTexture = dirtStainTexture();956 this.dirtNormalTexture = dirtNormalTexture();957 this.dirtGrainTexture = dirtGrainTexture();958 this.grassTuftTexture = grassTuftTexture();959 this.surfaceTexture = surfaceTexture();960 this.fabricTexture = fabricTexture();961 this.environment = null;962 this.targets = [];963 this.hover = null;964 this.marker = null;965 this.villageScene = null;966 this.villageCamera = null;967 this.villageAnchors = {};968 this.villageLanterns = [];969 this.villageTime = 0;970 this.villageGroundTexture = null;971 this.villagePathTexture = null;972 this.villageWaterTexture = null;973 this.villageWater = null;974 this.raycaster = new THREE.Raycaster();975 this.groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.06);976977 this.bindResize();978 }979980 bindResize() {981 window.addEventListener('resize', () => {982 this.camera.aspect = window.innerWidth / window.innerHeight;983 this.camera.updateProjectionMatrix();984 if (this.villageCamera) {985 this.villageCamera.aspect = window.innerWidth / window.innerHeight;986 this.villageCamera.updateProjectionMatrix();987 }988 this.renderer.setSize(window.innerWidth, window.innerHeight);989 });990 }991992 async load() {993 const loader = new GLTFLoader();994 const loaded = await Promise.all(995 Object.entries(MODEL_FILES).map(async ([name, file]) => {996 try {997 const gltf = await loader.loadAsync(encodeURI(MODEL_DIR + file));998 return [name, gltf.scene];999 } catch (error) {1000 console.warn(`Could not load model ${file}`, error);1001 return [name, null];1002 }1003 }),1004 );1005 this.models = Object.fromEntries(loaded);10061007 const heroes = await Promise.all(1008 Object.entries(HERO_MODEL_FILES).map(async ([name, file]) => {1009 try {1010 const gltf = await loader.loadAsync(encodeURI(HERO_MODEL_DIR + file));1011 return [name, gltf.scene, gltf.animations ?? []];1012 } catch (error) {1013 console.warn(`Could not load heroine model ${file}`, error);1014 return [name, null, []];1015 }1016 }),1017 );1018 this.heroModels = Object.fromEntries(1019 heroes.filter(([, scene]) => scene).map(([name, scene]) => [name, scene]),1020 );1021 this.heroAnimations = Object.fromEntries(heroes.map(([name, , animations]) => [name, animations]));10221023 1024 1025 1026 this.dirtTexture = this.tileGround(paintedDirtTexture(), 1, 1);1027 1028 1029 this.dirtBumpTexture = this.dirtTexture.clone();1030 this.dirtBumpTexture.colorSpace = THREE.NoColorSpace;1031 this.dirtBumpTexture.needsUpdate = true;10321033 this.villageGroundTexture = this.tileGround(1034 paintedGrassTexture(),1035 VILLAGE_GROUND_SIZE / VILLAGE_GROUND_TILE,1036 VILLAGE_GROUND_SIZE / VILLAGE_GROUND_TILE,1037 );1038 1039 1040 this.villagePathTexture = this.tileGround(1041 this.dirtTexture.clone(),1042 Math.round(VILLAGE_ROAD_WIDTH / VILLAGE_GROUND_TILE),1043 Math.round(VILLAGE_ROAD_LENGTH / VILLAGE_GROUND_TILE),1044 );1045 this.villageWaterTexture = await this.loadOptionalTexture(VILLAGE_WATER_TEXTURE, 5, 5);10461047 this.environment = this.buildEnvironment();1048 this.buildLighting();1049 this.buildArena();1050 this.buildVillage();1051 }10521053 async loadOptionalTexture(path, repeatX, repeatY) {1054 try {1055 return await this.loadTexture(path, repeatX, repeatY);1056 } catch (error) {1057 console.warn(`Could not load texture ${path}`, error);1058 return null;1059 }1060 }10611062 buildEnvironment() {1063 if (!THREE.PMREMGenerator) return null;1064 const generator = new THREE.PMREMGenerator(this.renderer);1065 const source = environmentTexture();1066 const target = generator.fromEquirectangular(source);1067 source.dispose();1068 generator.dispose();1069 return target.texture;1070 }10711072 async loadTexture(path, repeatX, repeatY) {1073 const texture = await new THREE.TextureLoader().loadAsync(path);1074 this.tileGround(texture, repeatX, repeatY);1075 texture.colorSpace = THREE.SRGBColorSpace;1076 return texture;1077 }10781079 108010811082108310841085 tileGround(texture, repeatX, repeatY) {1086 texture.wrapS = THREE.RepeatWrapping;1087 texture.wrapT = THREE.RepeatWrapping;1088 texture.repeat.set(repeatX, repeatY);1089 texture.anisotropy = 4;1090 return texture;1091 }10921093 buildLighting() {1094 this.scene.add(new THREE.HemisphereLight(0x9182c4, 0x1b1119, 1.2));10951096 const sun = new THREE.DirectionalLight(0xffdcb6, 3.4);1097 sun.position.set(5.5, 13, 7.5);1098 sun.castShadow = true;1099 sun.shadow.mapSize.set(2048, 2048);1100 sun.shadow.camera.left = -14;1101 sun.shadow.camera.right = 14;1102 sun.shadow.camera.top = 14;1103 sun.shadow.camera.bottom = -14;1104 sun.shadow.camera.near = 1;1105 sun.shadow.camera.far = 40;1106 sun.shadow.bias = -0.0006;1107 this.scene.add(sun);11081109 const rim = new THREE.PointLight(0x8a4dff, 55, 26, 2);1110 rim.position.set(-7, 5, -4);1111 this.scene.add(rim);11121113 const fill = new THREE.DirectionalLight(0x7e74d8, 0.85);1114 fill.position.set(-9, 7, -7);1115 this.scene.add(fill);11161117 1118 const moon = new THREE.DirectionalLight(0x9fb8ff, 0.5);1119 moon.position.set(9, 8, -7);1120 this.scene.add(moon);11211122 1123 const characterRim = new THREE.DirectionalLight(0xa9c4ff, 1.15);1124 characterRim.position.set(-8, 6, -6);1125 this.scene.add(characterRim);1126 }11271128 placeModel(name, x, y, z, rotationY = 0, scale = 1) {1129 const model = this.models[name];1130 if (!model) return null;1131 const clone = model.clone(true);1132 clone.position.set(x, y, z);1133 clone.rotation.y = rotationY;1134 clone.scale.setScalar(scale);1135 clone.traverse((object) => {1136 if (object.isMesh) {1137 object.castShadow = true;1138 object.receiveShadow = true;1139 }1140 });1141 this.scene.add(clone);1142 return clone;1143 }11441145 11461147114811491150 placeBatch(name, placements, target = this.scene) {1151 const model = this.models[name];1152 if (!model || placements.length === 0) return;1153 model.updateMatrixWorld(true);11541155 const meshes = [];1156 model.traverse((object) => {1157 if (object.isMesh) meshes.push(object);1158 });11591160 const position = new THREE.Vector3();1161 const rotation = new THREE.Quaternion();1162 const euler = new THREE.Euler();1163 const scale = new THREE.Vector3();1164 const matrix = new THREE.Matrix4();1165 const tone = new THREE.Color();1166 for (const mesh of meshes) {1167 const batch = new THREE.InstancedMesh(mesh.geometry, mesh.material, placements.length);1168 placements.forEach((place, index) => {1169 position.set(place.x, place.y, place.z);1170 1171 euler.set(place.tiltX ?? 0, place.rotationY ?? 0, place.tiltZ ?? 0, 'YXZ');1172 rotation.setFromEuler(euler);1173 const size = place.scale ?? 1;1174 if (Array.isArray(size)) scale.set(size[0], size[1] ?? size[0], size[2] ?? size[0]);1175 else scale.setScalar(size);1176 matrix.compose(position, rotation, scale).multiply(mesh.matrixWorld);1177 batch.setMatrixAt(index, matrix);1178 1179 1180 const seed = Math.abs(Math.sin(place.x * 12.9898 + place.z * 78.233)) % 1;1181 batch.setColorAt(index, tone.setScalar(0.93 + seed * 0.07));1182 });1183 batch.instanceMatrix.needsUpdate = true;1184 batch.instanceColor.needsUpdate = true;1185 batch.castShadow = true;1186 batch.receiveShadow = true;1187 batch.computeBoundingSphere();1188 target.add(batch);1189 }1190 }11911192 buildArena() {1193 1194 1195 1196 1197 const segment = CASTLE_SCALE;1198 const halfWidth = (WALLS_ACROSS * segment) / 2;1199 const halfDepth = (WALLS_DEEP * segment) / 2;1200 const wallTop = WALL_COURSES * segment;1201 const gateHalf = GATE_SCALE / 2;1202 1203 1204 const gateZ = segment / 2;1205 1206 1207 const wallReach = halfDepth + 18;1208 const wallSegments = Math.round((wallReach * 2) / segment);12091210 1211 1212 1213 1214 const fieldExtent = 220;1215 const dirtRepeat = Math.round(fieldExtent / DIRT_TILE);1216 for (const texture of [this.dirtTexture, this.dirtBumpTexture, this.dirtNormalTexture]) {1217 if (texture) this.tileGround(texture, dirtRepeat, dirtRepeat);1218 }1219 const ground = new THREE.Mesh(1220 new THREE.PlaneGeometry(fieldExtent, fieldExtent),1221 new THREE.MeshStandardMaterial({1222 color: 0xb39a7b,1223 map: this.dirtTexture,1224 bumpMap: this.dirtBumpTexture,1225 bumpScale: 0.035,1226 normalMap: this.dirtNormalTexture,1227 normalScale: new THREE.Vector2(1.3, 1.3),1228 roughness: 1,1229 metalness: 0,1230 }),1231 );1232 ground.rotation.x = -Math.PI / 2;1233 ground.position.y = 0.02;1234 ground.receiveShadow = true;1235 this.scene.add(ground);12361237 const batches = new Map();1238 const add = (name, place) => {1239 const placements = batches.get(name);1240 if (placements) placements.push(place);1241 else batches.set(name, [place]);1242 };12431244 for (let course = 0; course < WALL_COURSES; course += 1) {1245 const y = course * segment;1246 1247 1248 const topCourse = course === WALL_COURSES - 1;1249 const loopZs = [3.25, 9.25, 15.25, 21.25];1250 for (let j = 0; j < wallSegments; j += 1) {1251 const z = -wallReach + segment / 2 + j * segment;1252 1253 1254 if (y < GATE_SCALE && Math.abs(z - gateZ) < gateHalf - 1e-6) continue;1255 const windowed = topCourse && loopZs.some((loop) => Math.abs(Math.abs(z) - loop) < 1e-6);1256 add(windowed ? 'window' : 'wall', {1257 x: -halfWidth,1258 y,1259 z,1260 rotationY: windowed ? -Math.PI / 2 : Math.PI / 2,1261 scale: CASTLE_SCALE,1262 });1263 }1264 }12651266 1267 1268 1269 1270 1271 const parapet = CASTLE_SCALE * 2;1272 const parapetInset = 0.6 * parapet - segment / 2; 1273 const westGaps = new Set([3, 10, 17, 24, 31, 38, 44]);1274 for (let j = 0; j < wallSegments / 2; j += 1) {1275 const z = -wallReach + parapet / 2 + j * parapet;1276 if (!westGaps.has(j)) {1277 add('battlement', { x: -halfWidth + parapetInset, y: wallTop, z, rotationY: Math.PI / 2, scale: parapet });1278 }1279 }12801281 add('gate', { x: -halfWidth, y: 0, z: gateZ, rotationY: Math.PI / 2, scale: GATE_SCALE });12821283 1284 1285 1286 const towers = [1287 [-wallReach, 0.92, TOWER_COURSES],1288 [-18, 1.04, TOWER_COURSES + 1],1289 [-12, 0.94, TOWER_COURSES],1290 [-halfDepth, TOWER_SCALE, TOWER_COURSES],1291 [gateZ - GATE_TOWER_OFFSET, TOWER_SCALE, TOWER_COURSES],1292 [gateZ + GATE_TOWER_OFFSET, TOWER_SCALE, TOWER_COURSES],1293 [halfDepth, TOWER_SCALE, TOWER_COURSES],1294 [12, 0.9, TOWER_COURSES - 1],1295 [18, 1.06, TOWER_COURSES + 1],1296 [wallReach, 0.95, TOWER_COURSES],1297 ];1298 for (const [z, scale, courses] of towers) {1299 let y = 0;1300 add('towerBase', { x: -halfWidth, y, z, rotationY: 0, scale });1301 y += scale;1302 for (let course = 0; course < courses; course += 1) {1303 add('tower', {1304 x: -halfWidth,1305 y,1306 z,1307 rotationY: (course % 2) * (Math.PI / 4) + z * 0.004,1308 scale,1309 });1310 y += scale;1311 }1312 add('towerEdge', { x: -halfWidth, y, z, rotationY: Math.PI / 8, scale });1313 y += 0.4 * scale;1314 add('towerTop', { x: -halfWidth, y, z, rotationY: Math.PI / 8, scale });1315 }13161317 1318 1319 1320 for (const z of [-22.4, -16.4, -10.4, -4.4, 4.4, 10.4, 16.4, 22.4]) {1321 add('buttress', { x: -halfWidth + segment / 2, y: 0, z, rotationY: Math.PI, scale: BUTTRESS_SCALE });1322 }13231324 1325 1326 1327 1328 const shadeReach = 80;1329 const shade = new THREE.Mesh(1330 new THREE.PlaneGeometry(shadeReach, fieldExtent),1331 new THREE.MeshBasicMaterial({1332 map: shadeTexture(128, halfWidth / shadeReach),1333 transparent: true,1334 depthWrite: false,1335 }),1336 );1337 shade.rotation.x = -Math.PI / 2;1338 shade.position.set(shadeReach / 2, 0.055, 0);1339 shade.renderOrder = 1;1340 this.scene.add(shade);13411342 1343 1344 1345 const grain = new THREE.Mesh(1346 new THREE.PlaneGeometry(halfWidth * 2 - 0.1, halfDepth * 2 - 0.1),1347 new THREE.MeshStandardMaterial({1348 map: this.dirtGrainTexture,1349 transparent: true,1350 opacity: 0.34,1351 roughness: 1,1352 metalness: 0,1353 depthWrite: false,1354 }),1355 );1356 grain.rotation.x = -Math.PI / 2;1357 grain.position.y = 0.028;1358 grain.renderOrder = 0.5;1359 this.scene.add(grain);13601361 1362 const stains = new THREE.Mesh(1363 new THREE.PlaneGeometry(halfWidth * 2 - 0.1, halfDepth * 2 - 0.1),1364 new THREE.MeshStandardMaterial({1365 map: this.dirtStainTexture,1366 transparent: true,1367 opacity: 0.9,1368 roughness: 1,1369 metalness: 0,1370 depthWrite: false,1371 }),1372 );1373 stains.rotation.x = -Math.PI / 2;1374 stains.position.y = 0.032;1375 stains.receiveShadow = true;1376 this.scene.add(stains);13771378 1379 1380 const pebbleRandom = seeded(2459);1381 const pebbles = [];1382 const pebbleColors = [0x7d6a58, 0x94806a, 0x6b5a4a, 0xa08c72, 0x5e5044, 0xb9a98f];1383 const reachX = halfWidth - 0.9;1384 const reachZ = halfDepth - 0.9;1385 for (let index = 0; index < 320; index += 1) {1386 const x = (pebbleRandom() * 2 - 1) * reachX;1387 const z = (pebbleRandom() * 2 - 1) * reachZ;1388 const edge = Math.max(Math.abs(x) / reachX, Math.abs(z) / reachZ);1389 if (pebbleRandom() > 0.1 + edge ** 3 * 1.2) continue;1390 pebbles.push({1391 x,1392 z,1393 size: 0.022 + pebbleRandom() ** 2 * 0.11,1394 spin: pebbleRandom() * Math.PI * 2,1395 tiltX: (pebbleRandom() - 0.5) * 0.6,1396 tiltZ: (pebbleRandom() - 0.5) * 0.6,1397 squash: 0.45 + pebbleRandom() * 0.35,1398 color: pebbleColors[Math.floor(pebbleRandom() * pebbleColors.length)],1399 });1400 }14011402 1403 for (let index = 0; index < 40; index += 1) {1404 const x = (pebbleRandom() * 2 - 1) * reachX;1405 const z = (pebbleRandom() * 2 - 1) * reachZ;1406 const edge = Math.max(Math.abs(x) / reachX, Math.abs(z) / reachZ);1407 if (edge < 0.7) continue;1408 pebbles.push({1409 x,1410 z,1411 size: 0.13 + pebbleRandom() * 0.18,1412 spin: pebbleRandom() * Math.PI * 2,1413 tiltX: (pebbleRandom() - 0.5) * 0.5,1414 tiltZ: (pebbleRandom() - 0.5) * 0.5,1415 squash: 0.5 + pebbleRandom() * 0.35,1416 color: pebbleColors[Math.floor(pebbleRandom() * pebbleColors.length)],1417 });1418 }14191420 if (pebbles.length > 0) {1421 const pebbleMesh = new THREE.InstancedMesh(1422 new THREE.DodecahedronGeometry(1, 0),1423 new THREE.MeshStandardMaterial({ roughness: 1, metalness: 0, flatShading: true }),1424 pebbles.length,1425 );1426 const position = new THREE.Vector3();1427 const rotation = new THREE.Quaternion();1428 const euler = new THREE.Euler();1429 const scale = new THREE.Vector3();1430 const matrix = new THREE.Matrix4();1431 const color = new THREE.Color();1432 pebbles.forEach((pebble, index) => {1433 position.set(pebble.x, 0.02 + pebble.size * 0.5, pebble.z);1434 euler.set(pebble.tiltX, pebble.spin, pebble.tiltZ, 'YXZ');1435 rotation.setFromEuler(euler);1436 scale.set(pebble.size, pebble.size * pebble.squash, pebble.size);1437 matrix.compose(position, rotation, scale);1438 pebbleMesh.setMatrixAt(index, matrix);1439 pebbleMesh.setColorAt(index, color.setHex(pebble.color));1440 });1441 pebbleMesh.instanceMatrix.needsUpdate = true;1442 pebbleMesh.instanceColor.needsUpdate = true;1443 pebbleMesh.castShadow = true;1444 pebbleMesh.receiveShadow = true;1445 pebbleMesh.computeBoundingSphere();1446 this.scene.add(pebbleMesh);1447 }14481449 1450 1451 const tuftRandom = seeded(6607);1452 const tufts = [];1453 for (let index = 0; index < 180; index += 1) {1454 const x = (tuftRandom() * 2 - 1) * 24;1455 const z = (tuftRandom() * 2 - 1) * 20;1456 1457 1458 const inField = Math.abs(x) < halfWidth - 1.5 && Math.abs(z) < halfDepth - 1.2;1459 if (inField && tuftRandom() > 0.1) continue;1460 if (x > halfWidth - 1) continue;1461 const height = 0.2 + tuftRandom() * 0.36;1462 tufts.push({1463 x,1464 z,1465 height,1466 width: height * (0.75 + tuftRandom() * 0.4),1467 yaw: tuftRandom() * Math.PI * 2,1468 });1469 }1470 if (tufts.length > 0) {1471 const tuftMesh = new THREE.InstancedMesh(1472 crossedPlaneGeometry(1),1473 new THREE.MeshStandardMaterial({1474 map: this.grassTuftTexture,1475 alphaTest: 0.35,1476 side: THREE.DoubleSide,1477 roughness: 1,1478 metalness: 0,1479 }),1480 tufts.length,1481 );1482 const position = new THREE.Vector3();1483 const rotation = new THREE.Quaternion();1484 const euler = new THREE.Euler();1485 const scale = new THREE.Vector3();1486 const matrix = new THREE.Matrix4();1487 tufts.forEach((tuft, index) => {1488 position.set(tuft.x, 0.02, tuft.z);1489 euler.set(0, tuft.yaw, 0);1490 rotation.setFromEuler(euler);1491 scale.set(tuft.width, tuft.height, tuft.width);1492 matrix.compose(position, rotation, scale);1493 tuftMesh.setMatrixAt(index, matrix);1494 });1495 tuftMesh.instanceMatrix.needsUpdate = true;1496 tuftMesh.receiveShadow = true;1497 tuftMesh.computeBoundingSphere();1498 this.scene.add(tuftMesh);1499 }15001501 1502 const twigRandom = seeded(3313);1503 const twigColors = [0x6b563c, 0x8a7551, 0x5a4630, 0x9c8760];1504 const twigs = [];1505 for (let index = 0; index < 160; index += 1) {1506 const x = (twigRandom() * 2 - 1) * (halfWidth - 1);1507 const z = (twigRandom() * 2 - 1) * (halfDepth - 1);1508 const edge = Math.max(Math.abs(x) / (halfWidth - 1), Math.abs(z) / (halfDepth - 1));1509 if (twigRandom() > 0.18 + edge * edge * 0.9) continue;1510 twigs.push({1511 x,1512 z,1513 length: 0.1 + twigRandom() ** 2 * 0.32,1514 yaw: twigRandom() * Math.PI * 2,1515 color: twigColors[Math.floor(twigRandom() * twigColors.length)],1516 });1517 }1518 if (twigs.length > 0) {1519 const twigMesh = new THREE.InstancedMesh(1520 new THREE.CylinderGeometry(0.012, 0.018, 1, 5),1521 new THREE.MeshStandardMaterial({ roughness: 1, metalness: 0 }),1522 twigs.length,1523 );1524 const position = new THREE.Vector3();1525 const rotation = new THREE.Quaternion();1526 const euler = new THREE.Euler();1527 const scale = new THREE.Vector3();1528 const matrix = new THREE.Matrix4();1529 const color = new THREE.Color();1530 twigs.forEach((twig, index) => {1531 position.set(twig.x, 0.036, twig.z);1532 euler.set(0, twig.yaw, Math.PI / 2, 'YXZ');1533 rotation.setFromEuler(euler);1534 scale.set(1, twig.length, 1);1535 matrix.compose(position, rotation, scale);1536 twigMesh.setMatrixAt(index, matrix);1537 twigMesh.setColorAt(index, color.setHex(twig.color));1538 });1539 twigMesh.instanceMatrix.needsUpdate = true;1540 twigMesh.instanceColor.needsUpdate = true;1541 twigMesh.receiveShadow = true;1542 twigMesh.computeBoundingSphere();1543 this.scene.add(twigMesh);1544 }15451546 const tileRadius = hex.TILE_RADIUS - 0.02;1547 1548 1549 const tileSize = (tileRadius * 2) / 0.92;1550 const highlightGeometry = new THREE.PlaneGeometry(tileSize, tileSize);15511552 for (const cell of hex.allHexes()) {1553 const point = hex.center(cell);1554 const highlight = new THREE.Mesh(1555 highlightGeometry,1556 new THREE.MeshBasicMaterial({1557 color: 0xffffff,1558 map: this.hexTileTexture,1559 transparent: true,1560 opacity: 0.55,1561 depthWrite: false,1562 }),1563 );1564 highlight.position.set(point.x, 0.08, point.z);1565 highlight.rotation.x = -Math.PI / 2;1566 highlight.visible = false;1567 highlight.renderOrder = 2;1568 this.scene.add(highlight);1569 this.highlights.set(hex.key(cell), highlight);1570 }15711572 1573 const wardMaterial = new THREE.MeshBasicMaterial({1574 color: 0xbf9860,1575 transparent: true,1576 opacity: 0.22,1577 depthWrite: false,1578 });1579 for (const [x, z, width, depth] of [1580 [0, -4.62, 13.9, 0.05],1581 [0, 4.62, 13.9, 0.05],1582 [-6.95, 0, 0.05, 9.3],1583 [6.95, 0, 0.05, 9.3],1584 ]) {1585 const ward = new THREE.Mesh(new THREE.BoxGeometry(width, 0.012, depth), wardMaterial);1586 ward.position.set(x, 0.045, z);1587 this.scene.add(ward);1588 }15891590 if (this.runeTexture) {1591 const runeMaterial = new THREE.MeshBasicMaterial({1592 map: this.runeTexture,1593 transparent: true,1594 opacity: 0.15,1595 blending: THREE.AdditiveBlending,1596 depthWrite: false,1597 side: THREE.DoubleSide,1598 });1599 this.rune = new THREE.Mesh(new THREE.PlaneGeometry(8.6, 8.6), runeMaterial);1600 this.rune.rotation.x = -Math.PI / 2;1601 this.rune.position.set(0, 0.064, 0);1602 this.rune.renderOrder = 1;1603 this.scene.add(this.rune);1604 }16051606 1607 1608 for (const [x, z] of [1609 [-halfWidth - 2.4, -halfDepth + 0.6],1610 [-halfWidth - 2.6, 2.4],1611 ]) {1612 this.placeModel('tree', x, 0, z, 0, 0.9);1613 }1614 1615 for (const [x, z, scale] of [1616 [-7.45, 2.65, 0.72],1617 [7.5, -2.9, 0.75],1618 [-7.5, -2.95, 0.68],1619 [7.45, 1.95, 0.66],1620 [-6.5, -5.45, 0.55],1621 [6.4, -5.5, 0.58],1622 ]) {1623 this.placeModel('shrub', x, 0, z, 0, scale);1624 }16251626 1627 1628 1629 for (const [name, x, z, yaw, scale, tiltX = 0] of [1630 1631 ['columnDamaged', 7.62, -2.35, 0.35, 1.6],1632 ['columnDamaged', 7.7, 0.4, -0.45, 1.15],1633 ['columnDamaged', 7.5, 1.5, 0.9, 0.6],1634 ['column', 7.5, 2.9, 0.1, 1.25, Math.PI / 2],1635 ['column', 7.42, -3.4, 1.2, 0.85, Math.PI / 2],1636 ['rubble', 7.35, -1.4, 0.4, 1.6],1637 ['rubble', 7.7, 0.95, -0.8, 1.1],1638 ['rubble', 7.55, -2.95, 0.9, 0.8],1639 1640 ['columnDamaged', -7.62, 2.2, -0.3, 1.45],1641 ['columnDamaged', -7.7, 0.5, 0.5, 0.85],1642 ['column', -7.6, -2.4, 0.15, 1.35],1643 ['column', -7.5, -0.6, -0.15, 1.2, Math.PI / 2],1644 ['column', -7.45, 3.3, -1.1, 0.8, Math.PI / 2],1645 ['rubble', -7.4, -1.6, -0.5, 1.4],1646 ['rubble', -7.7, 1.4, 0.7, 1],1647 1648 ['columnDamaged', -6.05, -5.4, 0.6, 0.55],1649 ['column', 6.15, -5.4, 1.35, 0.8, Math.PI / 2],1650 ['rubble', -3.75, -5.45, 0.35, 1.15],1651 ['rubble', 6.8, -5.4, -0.25, 0.9],1652 ]) {1653 1654 add(name, { x, y: tiltX ? 0.1 * scale : 0, z, rotationY: yaw, tiltX, scale });1655 }16561657 for (const [name, placements] of batches) this.placeBatch(name, placements);16581659 1660 1661 1662 const brazierSources = [];1663 for (const [x, z] of [1664 [-7.2, -4.8],1665 [-7.2, 4.8],1666 ]) {1667 this.buildBrazier(x, z);1668 brazierSources.push({ x, z, y: 0.82 });1669 }1670 this.buildEmbers(brazierSources);1671 this.buildDust();16721673 this.placeModel('crate', -5.6, 0, -5.05, 0.4, 0.72);1674 this.placeModel('crate', -4.85, 0, -5.12, -0.2, 0.62);1675 this.placeModel('barrel', 5.6, 0, -5.05, 0, 0.72);1676 this.placeModel('barrel', 4.85, 0, -5.12, 0, 0.62);16771678 this.marker = new THREE.Mesh(1679 new THREE.TorusGeometry(0.42, 0.035, 8, 32),1680 new THREE.MeshBasicMaterial({ color: 0xe8c477 }),1681 );1682 this.marker.rotation.x = -Math.PI / 2;1683 this.marker.position.y = 0.15;1684 this.marker.visible = false;1685 this.scene.add(this.marker);16861687 this.buildArenaVillage();1688 }16891690 16911692169316941695 buildArenaVillage() {1696 const batches = new Map();1697 let houseTint = null;1698 const add = (name, place) => {1699 const entry = houseTint === null ? place : { ...place, tint: houseTint };1700 const placements = batches.get(name);1701 if (placements) placements.push(entry);1702 else batches.set(name, [entry]);1703 };17041705 1706 1707 const houses = [1708 { x: -12.0, z: -9.6, width: 3, depth: 3, storeys: 3, yaw: Math.PI / 2 + 0.06, painted: true, doorAt: 1, roofPitch: 1.14, tint: 0xf2e0cc },1709 { x: -11.7, z: -2.8, width: 4, depth: 3, storeys: 2, yaw: Math.PI / 2 - 0.05, painted: false, doorAt: 2, roofPitch: 0.98, tint: 0xc9a88b },1710 { x: -11.5, z: 4.2, width: 3, depth: 3, storeys: 1, yaw: Math.PI / 2 - 0.08, painted: false, doorAt: 1, leanTo: true, roofPitch: 0.9, tint: 0xd8c6b4 },1711 { x: -16.9, z: -8.2, width: 3, depth: 4, storeys: 2, yaw: Math.PI / 2 + 0.14, painted: true, doorAt: 2, roofPitch: 1.18, tint: 0xe6c9ad },1712 { x: -17.0, z: -1.0, width: 3, depth: 2, storeys: 1, yaw: 0.03, painted: true, doorAt: 1, leanTo: true, roofPitch: 1.05, tint: 0xb99a80 },1713 { x: -17.2, z: 5.4, width: 2, depth: 4, storeys: 2, yaw: Math.PI / 2 + 0.18, painted: false, doorAt: 0, roofPitch: 1.1, tint: 0xead6c2 },1714 ];1715 for (const house of houses) {1716 houseTint = house.tint;1717 this.addVillageHouse(add, house);1718 }1719 houseTint = null;17201721 1722 for (const [x, z, scale, yaw] of [1723 [-21.8, -14.6, 1.9, 0.4],1724 [-14.8, -15.8, 1.5, 1.2],1725 [-9.8, -15.4, 1.35, 2.1],1726 [-13.6, -5.9, 1.25, 0.8],1727 [-22.2, -5.2, 1.7, 1.8],1728 [-21.4, 5.8, 1.55, 0.9],1729 [-13.6, 9.2, 1.3, 2.4],1730 [-20.4, 11.2, 1.6, 0.3],1731 ]) {1732 add('tree', { x, y: 0, z, rotationY: yaw, scale });1733 }1734 for (const [x, z, scale] of [1735 [-10.1, -8.6, 0.75],1736 [-9.9, -3.8, 0.65],1737 [-13.9, -13.6, 0.8],1738 [-14.2, 5.1, 0.7],1739 [-9.6, 6.6, 0.72],1740 ]) {1741 add('shrub', { x, y: 0, z, rotationY: x, scale });1742 }17431744 1745 add('barrel', { x: -9.9, y: 0, z: -5.4, rotationY: 0.3, scale: 0.85 });1746 add('barrel', { x: -10.1, y: 0, z: 1.1, rotationY: -0.2, scale: 0.7 });1747 add('crate', { x: -9.7, y: 0, z: -9.8, rotationY: 0.5, scale: 1 });1748 add('fenceWood', { x: -14.6, y: 0, z: -13.2, rotationY: 0.1, scale: 1.2 });1749 add('ladder', { x: -14.4, y: 0, z: -6.7, rotationY: Math.PI / 2, scale: 1.2 });17501751 1752 add('columnWood', { x: -13.6, y: 0, z: 1.3, rotationY: 0, scale: 0.95 });1753 add('columnWood', { x: -14.8, y: 0, z: 1.3, rotationY: 0, scale: 0.95 });1754 add('columnWood', { x: -13.6, y: 0, z: 2.5, rotationY: 0, scale: 0.95 });1755 add('columnWood', { x: -14.8, y: 0, z: 2.5, rotationY: 0, scale: 0.95 });1756 add('roofHighSide', { x: -14.2, y: 1.02, z: 1.9, rotationY: 0, scale: [1.7, 0.6, 1.7] });1757 add('barrel', { x: -13.9, y: 0, z: 1.7, rotationY: 0.6, scale: 0.7 });1758 add('crate', { x: -14.5, y: 0, z: 2.2, rotationY: -0.3, scale: 0.8 });17591760 for (const [name, placements] of batches) this.placeVillageBatch(name, placements, this.scene);17611762 1763 for (const [x, y, z] of [1764 [-10.2, 2.5, -9.4],1765 [-10.1, 2.4, -2.6],1766 [-10.0, 2.4, 4.4],1767 ]) {1768 const glow = new THREE.Sprite(1769 new THREE.SpriteMaterial({1770 map: this.glowTexture,1771 color: 0xffa050,1772 transparent: true,1773 opacity: 0.55,1774 blending: THREE.AdditiveBlending,1775 depthWrite: false,1776 }),1777 );1778 glow.position.set(x, y, z);1779 glow.scale.set(2.2, 2.2, 1);1780 this.scene.add(glow);17811782 const light = new THREE.PointLight(0xffa050, 8, 8, 2);1783 light.position.set(x, y, z);1784 this.scene.add(light);1785 }1786 }17871788 17891790 17911792179317941795 buildVillage() {1796 const scene = new THREE.Scene();1797 scene.background = new THREE.Color(0x1a1016);1798 scene.fog = new THREE.Fog(0x2b1a1d, 40, 104);1799 this.villageScene = scene;18001801 const camera = new THREE.PerspectiveCamera(1802 40,1803 window.innerWidth / window.innerHeight,1804 0.1,1805 220,1806 );1807 camera.position.set(2.5, 9, 22);1808 camera.lookAt(-0.5, 2.2, -6);1809 this.villageCamera = camera;18101811 const root = new THREE.Group();1812 scene.add(root);18131814 this.buildVillageGround(root);1815 this.buildVillageLighting(scene);18161817 const batches = new Map();1818 const add = (name, place) => {1819 const placements = batches.get(name);1820 if (placements) placements.push(place);1821 else batches.set(name, [place]);1822 };18231824 this.buildVillageWall(add);1825 this.buildVillageHouses(add);1826 this.buildVillageProps(add);18271828 for (const [name, placements] of batches) this.placeVillageBatch(name, placements, root);1829 this.buildVillageAnchors(root);1830 }18311832 1833 placeVillageBatch(name, placements, target) {1834 const model = this.models[name];1835 if (!model || placements.length === 0) return;1836 model.updateMatrixWorld(true);18371838 const tint = new THREE.Color(VILLAGE_TINT);1839 const perInstance = placements.some((place) => place.tint !== undefined);1840 const instanceTint = new THREE.Color();1841 const meshes = [];1842 model.traverse((object) => {1843 if (object.isMesh) meshes.push(object);1844 });18451846 const position = new THREE.Vector3();1847 const rotation = new THREE.Quaternion();1848 const euler = new THREE.Euler();1849 const scale = new THREE.Vector3();1850 const matrix = new THREE.Matrix4();1851 for (const mesh of meshes) {1852 const material = mesh.material.clone();1853 material.side = THREE.DoubleSide;1854 if (material.color) material.color.multiply(tint);1855 const batch = new THREE.InstancedMesh(mesh.geometry, material, placements.length);1856 placements.forEach((place, index) => {1857 position.set(place.x, place.y, place.z);1858 euler.set(place.tiltX ?? 0, place.rotationY ?? 0, place.tiltZ ?? 0, 'YXZ');1859 rotation.setFromEuler(euler);1860 const size = place.scale ?? 1;1861 if (Array.isArray(size)) scale.set(size[0], size[1] ?? size[0], size[2] ?? size[0]);1862 else scale.setScalar(size);1863 matrix.compose(position, rotation, scale).multiply(mesh.matrixWorld);1864 batch.setMatrixAt(index, matrix);1865 if (perInstance) batch.setColorAt(index, instanceTint.setHex(place.tint ?? 0xffffff));1866 });1867 batch.instanceMatrix.needsUpdate = true;1868 if (perInstance) batch.instanceColor.needsUpdate = true;1869 batch.castShadow = true;1870 batch.receiveShadow = true;1871 batch.computeBoundingSphere();1872 target.add(batch);1873 }1874 }18751876 buildVillageGround(root) {1877 const groundMaterial = new THREE.MeshStandardMaterial({1878 color: 0xbfa87c,1879 map: this.villageGroundTexture,1880 roughness: 1,1881 metalness: 0,1882 });1883 const ground = new THREE.Mesh(1884 new THREE.PlaneGeometry(VILLAGE_GROUND_SIZE, VILLAGE_GROUND_SIZE),1885 groundMaterial,1886 );1887 ground.rotation.x = -Math.PI / 2;1888 ground.position.y = -0.06;1889 ground.receiveShadow = true;1890 root.add(ground);18911892 1893 const pathMaterial = new THREE.MeshStandardMaterial({1894 color: 0x9f937c,1895 map: this.villagePathTexture,1896 roughness: 1,1897 metalness: 0,1898 transparent: true,1899 opacity: 0.82,1900 });1901 const path = new THREE.Mesh(new THREE.PlaneGeometry(VILLAGE_ROAD_WIDTH, VILLAGE_ROAD_LENGTH), pathMaterial);1902 path.rotation.x = -Math.PI / 2;1903 path.position.set(0, 0.004, -1);1904 path.receiveShadow = true;1905 root.add(path);19061907 if (this.villageWaterTexture) {1908 const waterMaterial = new THREE.MeshStandardMaterial({1909 color: 0x5c7a78,1910 map: this.villageWaterTexture,1911 roughness: 0.32,1912 metalness: 0.12,1913 transparent: true,1914 opacity: 0.96,1915 });1916 const pond = new THREE.Mesh(new THREE.CircleGeometry(3.4, 40), waterMaterial);1917 pond.rotation.x = -Math.PI / 2;1918 pond.position.set(-14.2, 0.012, 5.4);1919 pond.receiveShadow = true;1920 root.add(pond);1921 this.villageWater = waterMaterial;1922 }1923 }19241925 buildVillageLighting(scene) {1926 scene.add(new THREE.HemisphereLight(0xffb98a, 0x2a1820, 1.5));1927 scene.add(new THREE.AmbientLight(0x593b3a, 0.6));19281929 const sun = new THREE.DirectionalLight(0xffc58d, 3.2);1930 sun.position.set(-16, 20, 14);1931 sun.castShadow = true;1932 sun.shadow.mapSize.set(2048, 2048);1933 sun.shadow.camera.left = -30;1934 sun.shadow.camera.right = 30;1935 sun.shadow.camera.top = 30;1936 sun.shadow.camera.bottom = -24;1937 sun.shadow.camera.near = 1;1938 sun.shadow.camera.far = 80;1939 sun.shadow.bias = -0.0008;1940 scene.add(sun);19411942 1943 const moon = new THREE.DirectionalLight(0x8f9bd8, 0.7);1944 moon.position.set(12, 9, -18);1945 scene.add(moon);19461947 1948 1949 const fill = new THREE.DirectionalLight(0xffb27a, 1.15);1950 fill.position.set(7, 12, 20);1951 scene.add(fill);19521953 for (const [x, z, height] of [1954 [-2.6, -10.6, 2.9],1955 [2.6, -10.6, 2.9],1956 [-5.2, -3.4, 2.6],1957 [5.4, 0.6, 2.6],1958 [-5.4, 6.2, 2.5],1959 ]) {1960 this.buildVillageLantern(x, z, height);1961 }1962 }19631964 buildVillageLantern(x, z, height) {1965 const group = new THREE.Group();1966 group.position.set(x, 0, z);19671968 const wood = new THREE.MeshStandardMaterial({ color: 0x543a2a, roughness: 0.9 });1969 const post = new THREE.Mesh(new THREE.CylinderGeometry(0.07, 0.1, height, 6), wood);1970 post.position.y = height / 2;1971 post.castShadow = true;1972 group.add(post);19731974 const arm = new THREE.Mesh(new THREE.BoxGeometry(0.46, 0.08, 0.08), wood);1975 arm.position.set(0.23, height - 0.12, 0);1976 group.add(arm);19771978 const glass = new THREE.Mesh(1979 new THREE.SphereGeometry(0.15, 10, 8),1980 new THREE.MeshBasicMaterial({ color: 0xffd58a }),1981 );1982 glass.position.set(0.46, height - 0.3, 0);1983 group.add(glass);19841985 const glow = new THREE.Sprite(1986 new THREE.SpriteMaterial({1987 map: this.glowTexture,1988 color: 0xff9a48,1989 transparent: true,1990 opacity: 0.6,1991 blending: THREE.AdditiveBlending,1992 depthWrite: false,1993 }),1994 );1995 glow.position.copy(glass.position);1996 glow.scale.set(1.8, 1.8, 1);1997 group.add(glow);19981999 const light = new THREE.PointLight(0xffa050, 16, 10, 2);2000 light.position.copy(glass.position);2001 group.add(light);20022003 this.villageScene.add(group);2004 this.villageLanterns.push({2005 light,2006 glow,2007 base: 16,2008 phase: Math.random() * Math.PI * 2,2009 });2010 }20112012 buildVillageWall(add) {2013 const segment = VILLAGE_WALL_SCALE;2014 const half = (VILLAGE_WALL_ACROSS * segment) / 2;2015 const gateHalf = VILLAGE_GATE_SCALE / 2;2016 const wallTop = VILLAGE_WALL_COURSES * segment;20172018 for (let course = 0; course < VILLAGE_WALL_COURSES; course += 1) {2019 const y = course * segment;2020 for (let i = 0; i < VILLAGE_WALL_ACROSS; i += 1) {2021 const x = -half + segment / 2 + i * segment;2022 2023 if (y < VILLAGE_GATE_SCALE && Math.abs(x) < gateHalf - 1e-6) continue;2024 add('wall', { x, y, z: VILLAGE_WALL_Z, rotationY: 0, scale: segment });2025 }2026 }20272028 2029 2030 const parapet = segment * 2;2031 const parapetInset = 0.6 * parapet - segment / 2;2032 const weathered = new Set([5, 9, 14, 19, 31, 38, 43]);2033 for (let i = 0; i < VILLAGE_WALL_ACROSS / 2; i += 1) {2034 if (weathered.has(i)) continue;2035 const x = -half + parapet / 2 + i * parapet;2036 add('battlement', {2037 x,2038 y: wallTop,2039 z: VILLAGE_WALL_Z + parapetInset,2040 rotationY: 0,2041 scale: parapet,2042 });2043 }20442045 add('gate', { x: 0, y: 0, z: VILLAGE_WALL_Z, rotationY: 0, scale: VILLAGE_GATE_SCALE });20462047 2048 2049 for (const [x, scale] of [2050 [-half, VILLAGE_TOWER_SCALE],2051 [half, VILLAGE_TOWER_SCALE],2052 [-3.4, VILLAGE_TOWER_SCALE * 0.92],2053 [3.4, VILLAGE_TOWER_SCALE * 0.92],2054 ]) {2055 let y = 0;2056 add('towerBase', { x, y, z: VILLAGE_WALL_Z, rotationY: 0, scale });2057 y += scale;2058 for (let course = 0; course < VILLAGE_TOWER_COURSES; course += 1) {2059 add('tower', {2060 x,2061 y,2062 z: VILLAGE_WALL_Z,2063 rotationY: (course % 2) * (Math.PI / 4),2064 scale,2065 });2066 y += scale;2067 }2068 add('towerEdge', { x, y, z: VILLAGE_WALL_Z, rotationY: Math.PI / 8, scale });2069 y += 0.4 * scale;2070 add('towerTop', { x, y, z: VILLAGE_WALL_Z, rotationY: Math.PI / 8, scale });2071 }2072 }20732074 buildVillageHouses(add) {2075 2076 2077 const houses = [2078 { x: -8.6, z: -9.2, width: 4, depth: 3, storeys: 2, yaw: 0.05, painted: false, doorAt: 2 },2079 { x: 8.4, z: -9.0, width: 3, depth: 3, storeys: 2, yaw: -0.07, painted: true, doorAt: 0 },2080 { x: -10.2, z: -2.0, width: 3, depth: 4, storeys: 2, yaw: -0.04, painted: true, doorAt: 1, leanTo: true },2081 { x: 9.4, z: -3.0, width: 4, depth: 3, storeys: 2, yaw: 0.06, painted: false, doorAt: 3 },2082 { x: -6.9, z: 4.4, width: 3, depth: 3, storeys: 1, yaw: 0.1, painted: false, doorAt: 1 },2083 { x: 8.2, z: 3.6, width: 3, depth: 4, storeys: 2, yaw: -0.09, painted: true, doorAt: 2, leanTo: true },2084 ];2085 for (const house of houses) this.addVillageHouse(add, house);2086 }20872088 208920902091209220932094 addVillageHouse(add, { x, z, width, depth, storeys, yaw = 0, painted = false, doorAt = 0, leanTo = false, roofPitch = 1.05 }) {2095 const cell = HOUSE_CELL;2096 const cos = Math.cos(yaw);2097 const sin = Math.sin(yaw);2098 const place = (name, lx, lz, ly, rotationY = 0, scale = 1) => {2099 add(name, {2100 x: x + lx * cos + lz * sin,2101 y: ly,2102 z: z - lx * sin + lz * cos,2103 rotationY: yaw + rotationY,2104 scale,2105 });2106 };21072108 const columns = Math.round(width / cell);2109 const rows = Math.round(depth / cell);2110 const courses = Math.round(1 / cell); 2111 2112 const doorColumn = Math.min(columns - 2, doorAt * 2 + 1);2113 const windowFront = (column) => column % 4 === 2;2114 const windowBack = (column) => column % 4 === 0;21152116 for (let column = 0; column < columns; column += 1) {2117 const lx = -width / 2 + cell / 2 + column * cell;2118 for (let row = 0; row < rows; row += 1) {2119 const lz = -depth / 2 + cell / 2 + row * cell;2120 place(row === rows - 1 ? 'woodFloor' : 'stoneFloor', lx, lz, 0.02, 0, cell);2121 }2122 }21232124 const wall = painted ? 'paneWallPainted' : 'paneWall';2125 const door = painted ? 'paneWallPaintedDoor' : 'paneWallDoor';2126 const windowPane = painted ? 'paneWindowPainted' : 'paneWindow';21272128 for (let storey = 0; storey < storeys; storey += 1) {2129 for (let course = 0; course < courses; course += 1) {2130 const ly = storey + course * cell;2131 for (let column = 0; column < columns; column += 1) {2132 const lx = -width / 2 + cell / 2 + column * cell;2133 const ground = storey === 0;2134 2135 if (ground && column === doorColumn) {2136 if (course === 0) place(door, lx, depth / 2, 0, 0, [cell, 1, cell]);2137 continue;2138 }2139 const front = !ground && windowFront(column) ? windowPane : wall;2140 place(front, lx, depth / 2, ly, 0, cell);2141 const back = !ground && windowBack(column) ? windowPane : wall;2142 place(back, lx, -depth / 2, ly, Math.PI, cell);2143 }2144 for (let row = 0; row < rows; row += 1) {2145 const lz = -depth / 2 + cell / 2 + row * cell;2146 const side = storey > 0 && row === 0 ? windowPane : wall;2147 place(side, width / 2, lz, ly, Math.PI / 2, cell);2148 place(wall, -width / 2, lz, ly, -Math.PI / 2, cell);2149 }2150 }2151 }21522153 2154 for (const sx of [-1, 1]) {2155 for (const sz of [-1, 1]) {2156 for (let storey = 0; storey < storeys; storey += 1) {2157 place('columnWood', (sx * width) / 2, (sz * depth) / 2, storey);2158 }2159 }2160 }21612162 2163 for (let row = 0; row < rows; row += 1) {2164 const lz = -depth / 2 + cell / 2 + row * cell;2165 place('roof', 0, lz, storeys, 0, [width + 0.9, roofPitch, cell]);2166 }21672168 2169 2170 if (leanTo) {2171 for (let row = 0; row < rows; row += 1) {2172 const lz = -depth / 2 + cell / 2 + row * cell;2173 place('roofSide', width / 2 + 0.55, lz, storeys - 0.65, Math.PI, [1, 0.9, cell]);2174 }2175 for (const lz of [-depth / 2 + 0.4, depth / 2 - 0.4]) {2176 place('columnWood', width / 2 + 1.0, lz, 0, 0, [1, Math.max(0.5, storeys - 0.55), 1]);2177 }2178 }21792180 2181 const porchX = -width / 2 + cell / 2 + doorColumn * cell;2182 for (let across = -1; across <= 1; across += 1) {2183 for (let out = 0; out < 2; out += 1) {2184 place('woodFloor', porchX + across * cell, depth / 2 + cell / 2 + out * cell, 0.01, 0, cell);2185 }2186 }2187 place('barrel', width / 2 + 0.7, depth / 2 + 0.1, 0, 0, 0.8);2188 place('crate', -width / 2 - 0.5, depth / 2 + 0.5, 0, 0, 0.9);2189 }21902191 buildVillageProps(add) {2192 2193 for (const [x, z, scale, yaw] of [2194 [-20.5, -15.5, 1.9, 0.4],2195 [-13.5, -16.6, 1.5, 1.2],2196 [-4.4, -16.2, 1.7, 2.1],2197 [5.4, -16.4, 1.4, 0.8],2198 [13.8, -16.2, 1.8, 2.6],2199 [20.6, -14.8, 1.6, 1.7],2200 [-12.6, -7.4, 1.2, 0.3],2201 [12.8, -6.8, 1.35, 1.9],2202 [-13.4, -1.8, 1.1, 2.2],2203 [12.4, 1.1, 1.15, 0.9],2204 [-17.6, 7.2, 1.5, 1.4],2205 [16.8, 7.8, 1.45, 2.4],2206 [-24, -24, 3.0, 0.6],2207 [-11, -26, 2.7, 1.8],2208 [0, -28, 3.3, 2.4],2209 [12, -25, 2.8, 0.9],2210 [23, -23, 2.9, 1.5],2211 ]) {2212 add('tree', { x, y: 0, z, rotationY: yaw, scale });2213 }2214 for (const [x, z, scale] of [2215 [-12.4, -11.8, 0.9],2216 [-4.6, -8.2, 0.8],2217 [12.3, -11.4, 0.85],2218 [4.4, -5.2, 0.7],2219 [-12.2, 4.4, 0.75],2220 [12.6, 5.2, 0.9],2221 [-3.4, 7.6, 0.7],2222 [4.8, 8.4, 0.75],2223 ]) {2224 add('shrub', { x, y: 0, z, rotationY: x, scale });2225 }22262227 2228 add('columnWood', { x: 3.0, y: 0, z: -7.8, rotationY: 0, scale: 1.15 });2229 add('columnWood', { x: 5.0, y: 0, z: -7.8, rotationY: 0, scale: 1.15 });2230 add('columnWood', { x: 3.0, y: 0, z: -5.9, rotationY: 0, scale: 1.15 });2231 add('columnWood', { x: 5.0, y: 0, z: -5.9, rotationY: 0, scale: 1.15 });2232 add('roofHighSide', { x: 4.0, y: 1.18, z: -6.85, rotationY: 0, scale: [2.9, 0.75, 2.5] });2233 add('barrel', { x: 3.35, y: 0, z: -6.4, rotationY: 0.3, scale: 0.85 });2234 add('barrel', { x: 4.75, y: 0, z: -6.3, rotationY: -0.2, scale: 0.7 });2235 add('crate', { x: 4.1, y: 0, z: -7.2, rotationY: 0.5, scale: 1.1 });22362237 2238 add('barrel', { x: -3.4, y: 0, z: 2.6, rotationY: 0.4, scale: 0.9 });2239 add('barrel', { x: -3.75, y: 0, z: 3.5, rotationY: -0.3, scale: 0.7 });2240 add('crate', { x: 3.3, y: 0, z: 4.6, rotationY: -0.4, scale: 0.95 });2241 add('fenceWood', { x: -3.2, y: 0, z: 8.0, rotationY: 0.1, scale: 1.2 });22422243 2244 for (const [x, z, yaw] of [2245 [-12.4, 4.6, 0],2246 [13.6, 4.4, Math.PI],2247 ]) {2248 for (let i = 0; i < 4; i += 1) {2249 const offset = -1.8 + i * 1.2;2250 add('fence', {2251 x: x + offset * Math.cos(yaw),2252 y: 0.02,2253 z: z + offset * Math.sin(yaw),2254 rotationY: yaw,2255 scale: 1.2,2256 });2257 }2258 }22592260 2261 if (this.villageWater) {2262 add('dockSide', { x: -14.2, y: 0, z: 2.9, rotationY: 0, scale: 1.1 });2263 add('dockSide', { x: -14.2, y: 0, z: 1.8, rotationY: 0, scale: 1.1 });2264 add('dockCorner', { x: -14.2, y: 0, z: 0.7, rotationY: 0, scale: 1.1 });2265 add('overhangFence', { x: -13.6, y: 0.55, z: 2.3, rotationY: Math.PI / 2, scale: 1.6 });2266 }22672268 2269 add('ladder', { x: -11.7, y: 0, z: -7.4, rotationY: Math.PI / 2, scale: 1.3 });2270 add('fenceWood', { x: 11.0, y: 0, z: -8.9, rotationY: 0.2, scale: 1.3 });2271 }22722273 buildVillageAnchors(root) {2274 2275 2276 this.villageAnchors = {2277 gate: new THREE.Vector3(0, VILLAGE_GATE_SCALE + 1.0, VILLAGE_WALL_Z + 0.3),2278 market: new THREE.Vector3(4.0, 2.6, -6.6),2279 hall: new THREE.Vector3(8.4, 3.9, -9.0),2280 };22812282 for (const point of Object.values(this.villageAnchors)) {2283 const glow = new THREE.Sprite(2284 new THREE.SpriteMaterial({2285 map: this.glowTexture,2286 color: 0xffcf7d,2287 transparent: true,2288 opacity: 0.75,2289 blending: THREE.AdditiveBlending,2290 depthWrite: false,2291 }),2292 );2293 glow.position.copy(point);2294 glow.scale.set(1.1, 1.1, 1);2295 root.add(glow);2296 }2297 }22982299 updateVillage(dt) {2300 this.villageTime += dt;2301 for (const lantern of this.villageLanterns) {2302 const flicker =2303 0.84 +2304 Math.sin(this.villageTime * 7.3 + lantern.phase) * 0.1 +2305 Math.sin(this.villageTime * 19.1 + lantern.phase * 2.7) * 0.05;2306 lantern.light.intensity = lantern.base * flicker;2307 lantern.glow.material.opacity = 0.34 + flicker * 0.3;2308 const scale = 1.5 + flicker * 0.4;2309 lantern.glow.scale.set(scale, scale, 1);2310 }2311 if (this.villageWater?.map) {2312 this.villageWater.map.offset.x = this.villageTime * 0.008;2313 this.villageWater.map.offset.y = this.villageTime * 0.005;2314 }2315 }23162317 2318 menuAnchors() {2319 if (!this.villageCamera) return {};2320 const width = window.innerWidth;2321 const height = window.innerHeight;2322 return Object.fromEntries(2323 Object.entries(this.villageAnchors).map(([key, anchor]) => {2324 const projection = anchor.clone().project(this.villageCamera);2325 return [2326 key,2327 {2328 x: (projection.x * 0.5 + 0.5) * width,2329 y: (-projection.y * 0.5 + 0.5) * height,2330 visible: projection.z < 1,2331 },2332 ];2333 }),2334 );2335 }23362337 buildBrazier(x, z) {2338 const group = new THREE.Group();2339 group.position.set(x, 0, z);23402341 const stone = new THREE.MeshStandardMaterial({ color: 0x453b4a, roughness: 0.92 });2342 const iron = new THREE.MeshStandardMaterial({ color: 0x211c26, roughness: 0.52, metalness: 0.55 });23432344 const base = new THREE.Mesh(new THREE.CylinderGeometry(0.24, 0.34, 0.4, 8), stone);2345 base.position.y = 0.2;2346 base.castShadow = true;2347 base.receiveShadow = true;2348 group.add(base);23492350 const bowl = new THREE.Mesh(new THREE.CylinderGeometry(0.34, 0.2, 0.26, 12), iron);2351 bowl.position.y = 0.52;2352 bowl.castShadow = true;2353 group.add(bowl);23542355 const coals = new THREE.Mesh(2356 new THREE.CircleGeometry(0.27, 14),2357 new THREE.MeshBasicMaterial({2358 color: 0xff6a2a,2359 transparent: true,2360 opacity: 0.85,2361 blending: THREE.AdditiveBlending,2362 depthWrite: false,2363 }),2364 );2365 coals.rotation.x = -Math.PI / 2;2366 coals.position.y = 0.66;2367 group.add(coals);23682369 const flame = new THREE.Group();2370 const outer = new THREE.Mesh(2371 new THREE.ConeGeometry(0.2, 0.72, 8),2372 new THREE.MeshBasicMaterial({2373 color: 0xff7a30,2374 transparent: true,2375 opacity: 0.5,2376 blending: THREE.AdditiveBlending,2377 depthWrite: false,2378 }),2379 );2380 outer.position.y = 0.36;2381 const inner = new THREE.Mesh(2382 new THREE.ConeGeometry(0.1, 0.44, 8),2383 new THREE.MeshBasicMaterial({2384 color: 0xffe3a0,2385 transparent: true,2386 opacity: 0.72,2387 blending: THREE.AdditiveBlending,2388 depthWrite: false,2389 }),2390 );2391 inner.position.y = 0.3;2392 flame.add(outer, inner);2393 flame.position.y = 0.64;2394 group.add(flame);23952396 const glow = new THREE.Sprite(2397 new THREE.SpriteMaterial({2398 map: this.glowTexture,2399 color: 0xff8b3d,2400 transparent: true,2401 opacity: 0.55,2402 blending: THREE.AdditiveBlending,2403 depthWrite: false,2404 }),2405 );2406 glow.position.y = 1.0;2407 glow.scale.set(1.6, 1.6, 1);2408 group.add(glow);24092410 const light = new THREE.PointLight(0xff8a3a, 24, 8.5, 2);2411 light.position.y = 1.15;2412 group.add(light);24132414 this.scene.add(group);2415 this.fixtures.push({2416 light,2417 flame,2418 glow,2419 baseIntensity: 24,2420 phase: Math.random() * Math.PI * 2,2421 });2422 }24232424 buildEmbers(sources) {2425 const perSource = 14;2426 const count = sources.length * perSource;2427 const positions = new Float32Array(count * 3);2428 const data = [];2429 for (let source = 0; source < sources.length; source += 1) {2430 for (let index = 0; index < perSource; index += 1) {2431 const offset = source * perSource + index;2432 data.push({2433 baseX: sources[source].x,2434 baseZ: sources[source].z,2435 baseY: sources[source].y + Math.random() * 0.22,2436 angle: Math.random() * Math.PI * 2,2437 radius: 0.04 + Math.random() * 0.16,2438 speed: 0.18 + Math.random() * 0.26,2439 phase: Math.random(),2440 });2441 positions[offset * 3] = sources[source].x;2442 positions[offset * 3 + 1] = sources[source].y;2443 positions[offset * 3 + 2] = sources[source].z;2444 }2445 }24462447 const geometry = new THREE.BufferGeometry();2448 geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));2449 const material = new THREE.PointsMaterial({2450 color: 0xffa45a,2451 size: 0.055,2452 map: this.glowTexture,2453 transparent: true,2454 opacity: 0.85,2455 blending: THREE.AdditiveBlending,2456 depthWrite: false,2457 sizeAttenuation: true,2458 });2459 const points = new THREE.Points(geometry, material);2460 points.frustumCulled = false;2461 this.scene.add(points);2462 this.embers = { points, positions, data };2463 }24642465 buildDust() {2466 const count = 160;2467 const positions = new Float32Array(count * 3);2468 const data = [];2469 for (let index = 0; index < count; index += 1) {2470 const mote = {2471 baseX: (Math.random() - 0.5) * 19,2472 baseZ: (Math.random() - 0.5) * 13,2473 phase: Math.random(),2474 speed: 0.018 + Math.random() * 0.04,2475 sway: 0.12 + Math.random() * 0.32,2476 };2477 data.push(mote);2478 positions[index * 3] = mote.baseX;2479 positions[index * 3 + 1] = 0.25 + Math.random() * 4.8;2480 positions[index * 3 + 2] = mote.baseZ;2481 }24822483 const geometry = new THREE.BufferGeometry();2484 geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));2485 const material = new THREE.PointsMaterial({2486 color: 0xd6c8ff,2487 size: 0.05,2488 map: this.glowTexture,2489 transparent: true,2490 opacity: 0.38,2491 blending: THREE.AdditiveBlending,2492 depthWrite: false,2493 sizeAttenuation: true,2494 });2495 const points = new THREE.Points(geometry, material);2496 points.frustumCulled = false;2497 this.scene.add(points);2498 this.dust = { points, positions, data };2499 }25002501 updateAmbient(dt) {2502 for (const fixture of this.fixtures) {2503 const flicker =2504 0.82 +2505 Math.sin(this.time * 9.3 + fixture.phase) * 0.12 +2506 Math.sin(this.time * 21.7 + fixture.phase * 2.3) * 0.06;2507 fixture.light.intensity = fixture.baseIntensity * flicker;2508 fixture.flame.scale.set(1 + flicker * 0.12, 1 + flicker * 0.2, 1 + flicker * 0.12);2509 fixture.flame.rotation.y += dt * 1.8;2510 fixture.glow.material.opacity = 0.24 + flicker * 0.22;2511 const glowScale = 1.4 + flicker * 0.35;2512 fixture.glow.scale.set(glowScale, glowScale, 1);2513 }25142515 if (this.rune) this.rune.rotation.z = this.time * 0.06;25162517 if (this.dust) {2518 const { positions, data } = this.dust;2519 for (let index = 0; index < data.length; index += 1) {2520 const mote = data[index];2521 const age = (this.time * mote.speed + mote.phase) % 1;2522 positions[index * 3] = mote.baseX + Math.sin(this.time * 0.25 + mote.phase * 8) * mote.sway;2523 positions[index * 3 + 1] = 0.25 + age * 4.8;2524 positions[index * 3 + 2] = mote.baseZ + Math.cos(this.time * 0.21 + mote.phase * 6) * mote.sway;2525 }2526 this.dust.points.geometry.attributes.position.needsUpdate = true;2527 }25282529 if (this.embers) {2530 const { positions, data } = this.embers;2531 for (let index = 0; index < data.length; index += 1) {2532 const ember = data[index];2533 const age = (this.time * ember.speed + ember.phase) % 1;2534 const spread = ember.radius * (1 - age * 0.7);2535 positions[index * 3] = ember.baseX + Math.cos(ember.angle + age * 5) * spread;2536 positions[index * 3 + 1] = ember.baseY + age * 1.5;2537 positions[index * 3 + 2] = ember.baseZ + Math.sin(ember.angle + age * 5) * spread;2538 }2539 this.embers.points.geometry.attributes.position.needsUpdate = true;2540 }2541 }25422543 resetBattle(serial) {2544 if (serial === this.serial) return;2545 this.serial = serial;2546 for (const visual of this.unitVisuals.values()) {2547 this.disposeObject(visual.group);2548 }2549 this.unitVisuals.clear();2550 for (const effect of this.effects) {2551 this.disposeObject(effect.mesh);2552 }2553 this.effects = [];2554 for (const projectile of this.projectiles) {2555 this.disposeObject(projectile.group);2556 }2557 this.projectiles = [];2558 this.timers = [];2559 this.attackChain = null;2560 this.suppressCast = false;2561 this.hover = null;2562 this.targets = [];2563 }25642565 disposeObject(object) {2566 this.scene.remove(object);2567 object.traverse((child) => {2568 if (child.geometry) child.geometry.dispose();2569 if (child.material) {2570 const materials = Array.isArray(child.material) ? child.material : [child.material];2571 for (const material of materials) {2572 if (material.map) material.map.dispose();2573 material.dispose();2574 }2575 }2576 });2577 }25782579 addUnitHud(group, unit, barY) {2580 const bar = new THREE.Group();2581 const back = new THREE.Mesh(2582 new THREE.PlaneGeometry(0.88, 0.11),2583 new THREE.MeshBasicMaterial({ color: 0x0d0912, transparent: true, opacity: 0.85, depthWrite: false }),2584 );2585 const fill = new THREE.Mesh(2586 new THREE.PlaneGeometry(0.82, 0.06),2587 new THREE.MeshBasicMaterial({2588 color: unit.team === 'allies' ? 0x74e39b : 0xff5f74,2589 transparent: true,2590 depthWrite: false,2591 }),2592 );2593 fill.position.z = 0.002;2594 bar.add(back, fill);2595 bar.position.y = barY;2596 bar.renderOrder = 3;2597 group.add(bar);25982599 const statusDots = [];2600 Object.entries(STATUS_COLORS).forEach(([status, dotColor], index) => {2601 const dot = new THREE.Mesh(2602 new THREE.SphereGeometry(0.045, 8, 8),2603 new THREE.MeshBasicMaterial({ color: dotColor }),2604 );2605 dot.position.set(-0.21 + index * 0.14, barY + 0.13, 0);2606 dot.visible = false;2607 group.add(dot);2608 statusDots.push({ status, dot });2609 });26102611 const bodyHeight = Math.max(0.8, barY - 0.35);2612 const ward = new THREE.Mesh(2613 new THREE.SphereGeometry(bodyHeight * 0.52, 16, 12),2614 new THREE.MeshBasicMaterial({2615 color: 0x7fd7ff,2616 transparent: true,2617 opacity: 0.09,2618 blending: THREE.AdditiveBlending,2619 depthWrite: false,2620 side: THREE.DoubleSide,2621 }),2622 );2623 ward.position.y = bodyHeight * 0.52;2624 ward.visible = false;2625 group.add(ward);26262627 const wardWire = new THREE.Mesh(2628 new THREE.SphereGeometry(bodyHeight * 0.53, 12, 8),2629 new THREE.MeshBasicMaterial({2630 color: 0x9fe8ff,2631 wireframe: true,2632 transparent: true,2633 opacity: 0.08,2634 blending: THREE.AdditiveBlending,2635 depthWrite: false,2636 }),2637 );2638 wardWire.position.y = ward.position.y;2639 wardWire.visible = false;2640 group.add(wardWire);26412642 const rooted = new THREE.Group();2643 for (let index = 0; index < 6; index += 1) {2644 const angle = (index / 6) * Math.PI * 2;2645 const root = new THREE.Mesh(2646 new THREE.ConeGeometry(0.03, 0.3, 4),2647 new THREE.MeshBasicMaterial({ color: 0xb98a5c, transparent: true, opacity: 0.8 }),2648 );2649 root.position.set(Math.cos(angle) * 0.32, 0.13, Math.sin(angle) * 0.32);2650 root.rotation.z = Math.cos(angle) * 0.55;2651 root.rotation.x = Math.sin(angle) * 0.55;2652 rooted.add(root);2653 }2654 rooted.visible = false;2655 group.add(rooted);26562657 const poison = new THREE.Mesh(2658 new THREE.TorusGeometry(0.38, 0.02, 6, 24),2659 new THREE.MeshBasicMaterial({2660 color: 0x8ade6c,2661 transparent: true,2662 opacity: 0.7,2663 blending: THREE.AdditiveBlending,2664 depthWrite: false,2665 }),2666 );2667 poison.rotation.x = -Math.PI / 2;2668 poison.position.y = 0.1;2669 poison.visible = false;2670 group.add(poison);26712672 const marked = new THREE.Mesh(2673 new THREE.OctahedronGeometry(0.09, 0),2674 new THREE.MeshBasicMaterial({ color: 0xffb15c }),2675 );2676 marked.position.y = barY + 0.22;2677 marked.visible = false;2678 group.add(marked);26792680 const statusFX = { ward, wardWire, rooted, poison, marked, markedBaseY: barY + 0.22 };2681 return { bar, fill, statusDots, statusFX };2682 }26832684 buildHeroUnit(unit, source) {2685 const group = new THREE.Group();2686 const color = new THREE.Color(unit.color);2687 2688 2689 group.rotation.y = Math.PI / 2;26902691 2692 const shadow = new THREE.Mesh(2693 new THREE.PlaneGeometry(0.95, 0.95),2694 new THREE.MeshBasicMaterial({2695 map: this.glowTexture,2696 color: 0x000000,2697 transparent: true,2698 opacity: 0.2,2699 depthWrite: false,2700 }),2701 );2702 shadow.rotation.x = -Math.PI / 2;2703 shadow.position.y = 0.058;2704 group.add(shadow);27052706 2707 2708 const body = new THREE.Group();2709 const model = source.clone(true);2710 const flashMaterials = [];2711 model.traverse((object) => {2712 if (!object.isMesh) return;2713 object.castShadow = true;2714 object.receiveShadow = true;2715 const materials = Array.isArray(object.material) ? object.material : [object.material];2716 const clones = materials.map((material) => {2717 const clone = material.clone();2718 const name = (material.name ?? '').toLowerCase();2719 const metal = /steel|gold|bronze|buckle|clasp|band|guard|pommel|chain|mail|metal/.test(name);2720 const soft = /skin|hair|robe|cloth|leather|cloak|cowl|tunic|bodice|dress|belt|boot|bracer|feather|sash|wrap/.test(name);2721 clone.envMap = this.environment;2722 clone.envMapIntensity = (clone.metalness ?? 0) > 0.45 ? 1.5 : 1;2723 if (soft || metal) {2724 clone.bumpMap = this.surfaceTexture;2725 clone.bumpScale = metal ? 0.0015 : 0.006;2726 if (soft) {2727 clone.roughnessMap = this.surfaceTexture;2728 clone.roughness = Math.min(1, (clone.roughness ?? 0.6) * 1.1);2729 if (!clone.map) clone.map = this.fabricTexture;2730 }2731 }27322733 let result = clone;2734 if (clone.isMeshStandardMaterial && (soft || metal)) {2735 const physical = new THREE.MeshPhysicalMaterial({2736 color: clone.color,2737 map: clone.map,2738 normalMap: clone.normalMap,2739 normalScale: clone.normalScale,2740 bumpMap: clone.bumpMap,2741 bumpScale: clone.bumpScale,2742 roughness: clone.roughness,2743 roughnessMap: clone.roughnessMap,2744 metalness: clone.metalness,2745 metalnessMap: clone.metalnessMap,2746 emissive: clone.emissive,2747 emissiveMap: clone.emissiveMap,2748 emissiveIntensity: clone.emissiveIntensity,2749 transparent: clone.transparent,2750 opacity: clone.opacity,2751 alphaTest: clone.alphaTest,2752 alphaMap: clone.alphaMap,2753 side: clone.side,2754 depthWrite: clone.depthWrite,2755 flatShading: clone.flatShading,2756 vertexColors: clone.vertexColors,2757 envMap: clone.envMap,2758 envMapIntensity: clone.envMapIntensity,2759 });2760 physical.name = clone.name;2761 if (soft) {2762 physical.sheen = /skin/.test(name) ? 0.25 : 0.7;2763 physical.sheenRoughness = 0.72;2764 physical.sheenColor = physical.color.clone().lerp(new THREE.Color(0xffffff), 0.4);2765 }2766 if (metal) {2767 physical.clearcoat = 0.16;2768 physical.clearcoatRoughness = 0.26;2769 }2770 result = physical;2771 }2772 if (result.isMeshStandardMaterial && !result.transparent && !/(eye|iris|sclera|lip)/.test(name)) {2773 result.onBeforeCompile = (shader) => {2774 shader.fragmentShader = shader.fragmentShader.replace(2775 '#include <emissivemap_fragment>',2776 `#include <emissivemap_fragment>2777 float rim = pow(1.0 - max(dot(normalize(vNormal), normalize(vViewPosition)), 0.0), 2.6);2778 totalEmissiveRadiance += vec3(0.18, 0.26, 0.45) * rim * 0.65;`,2779 );2780 };2781 }2782 result.needsUpdate = true;2783 if (result.emissive) {2784 flashMaterials.push({2785 material: result,2786 baseEmissive: result.emissive.clone(),2787 baseIntensity: result.emissiveIntensity,2788 });2789 }2790 return result;2791 });2792 object.material = Array.isArray(object.material) ? clones : clones[0];2793 });2794 const clips = this.heroAnimations[unit.character] ?? [];2795 const animated = clips.length > 0;2796 if (!animated) this.refineHeroProportions(unit.character, model);2797 model.scale.set(0.78, 0.87, 0.78);2798 const weapon = animated ? null : this.buildWeaponRig(unit.character, model);2799 body.add(model);2800 group.add(body);28012802 let mixer = null;2803 const actions = {};2804 if (animated) {2805 mixer = new THREE.AnimationMixer(model);2806 for (const clip of clips) actions[clip.name] = mixer.clipAction(clip);2807 actions.Idle?.play();2808 }28092810 const ring = new THREE.Mesh(2811 new THREE.TorusGeometry(0.37, 0.02, 6, 24),2812 new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.6 }),2813 );2814 ring.rotation.x = -Math.PI / 2;2815 ring.position.y = 0.06;2816 group.add(ring);28172818 const height = new THREE.Box3().setFromObject(body).max.y;2819 const { bar, fill, statusDots, statusFX } = this.addUnitHud(group, unit, height + 0.2);28202821 const point = hex.center(unit.hex);2822 group.position.set(point.x, 0, point.z);2823 this.scene.add(group);28242825 const visual = {2826 group,2827 body,2828 bodyBaseY: 0,2829 material: null,2830 flashMaterials,2831 fill,2832 bar,2833 statusDots,2834 statusFX,2835 baseY: height,2836 base: new THREE.Vector3(point.x, 0, point.z),2837 target: new THREE.Vector3(point.x, 0, point.z),2838 dash: null,2839 weapon,2840 mixer,2841 actions,2842 flashUntil: 0,2843 flashColor: new THREE.Color(0xffffff),2844 deathAt: 0,2845 };2846 this.unitVisuals.set(unit.id, visual);2847 return visual;2848 }28492850 2851 refineHeroProportions(character, model) {2852 const nodes = new Map();2853 model.traverse((object) => {2854 if (object.name) nodes.set(object.name, object);2855 });28562857 const neckName = `${character[0].toUpperCase()}${character.slice(1)}_Neck`;2858 const neck = nodes.get(neckName);2859 const pivotY = neck ? neck.position.y : 1.35;2860 const headParts = [];2861 model.traverse((object) => {2862 if (!object.name) return;2863 const name = object.name;2864 if (/Neck|Mantle|Quiver|Arrow|Hand|Shoulder|Collar/.test(name)) return;2865 if (/(Head|Hair|Brow|Eye|Iris|Sclera|Lip|Chin|Ear|Nose|Bang|Braid|Crown|Antler|Face)/i.test(name)) {2866 headParts.push(object);2867 }2868 });2869 if (headParts.length === 0) return;28702871 model.updateMatrixWorld(true);2872 const pivot = new THREE.Group();2873 pivot.position.set(0, pivotY, 0);2874 model.add(pivot);2875 pivot.updateMatrixWorld(true);2876 for (const part of headParts) pivot.attach(part);2877 pivot.scale.setScalar(0.8);2878 pivot.updateMatrixWorld(true);2879 }28802881 2882 buildWeaponRig(character, model) {2883 const nodes = new Map();2884 model.traverse((object) => {2885 if (object.name) nodes.set(object.name, object);2886 });28872888 const rig = (prefixes, pivotName, axis, amplitude) => {2889 const pivotNode = nodes.get(pivotName);2890 if (!pivotNode) return null;2891 const parts = [];2892 model.traverse((object) => {2893 if (!object.name) return;2894 if (prefixes.some((prefix) => object.name.startsWith(prefix))) parts.push(object);2895 });2896 if (parts.length === 0) return null;28972898 const pivot = new THREE.Group();2899 pivot.position.copy(pivotNode.position);2900 model.add(pivot);2901 for (const part of parts) {2902 part.position.sub(pivot.position);2903 pivot.add(part);2904 }2905 return { pivot, rest: pivot.rotation.clone(), axis, amplitude };2906 };29072908 if (character === 'finella') {2909 const pivots = [2910 rig(['Finella_Leading_Dagger'], 'Finella_Leading_Dagger_Grip', 'y', 0.95),2911 rig(['Finella_Reverse_Dagger'], 'Finella_Reverse_Dagger_Grip', 'y', -0.75),2912 ].filter(Boolean);2913 return pivots.length > 0 ? { pivots, swingAt: -1e9, swingDuration: 0.36 } : null;2914 }2915 if (character === 'atlanta') {2916 const bow = rig(['Atlanta_Bow', 'Atlanta_Recurve_Bow'], 'Atlanta_Bow_Grip', 'z', 0.32);2917 return bow ? { pivots: [bow], swingAt: -1e9, swingDuration: 0.45 } : null;2918 }2919 return null;2920 }29212922 buildUnit(unit) {2923 const heroModel = unit.team === 'allies' ? this.heroModels[unit.character] : null;2924 if (heroModel) return this.buildHeroUnit(unit, heroModel);29252926 const group = new THREE.Group();2927 const color = new THREE.Color(unit.color);2928 group.rotation.y = unit.team === 'allies' ? Math.PI / 2 : -Math.PI / 2;29292930 2931 const shadow = new THREE.Mesh(2932 new THREE.PlaneGeometry(0.95, 0.95),2933 new THREE.MeshBasicMaterial({2934 map: this.glowTexture,2935 color: 0x000000,2936 transparent: true,2937 opacity: 0.2,2938 depthWrite: false,2939 }),2940 );2941 shadow.rotation.x = -Math.PI / 2;2942 shadow.position.y = 0.058;2943 group.add(shadow);2944 const material = unit.team === 'allies'2945 ? new THREE.MeshStandardMaterial({2946 color,2947 roughness: 0.55,2948 metalness: 0.12,2949 emissive: color.clone().multiplyScalar(0.35),2950 emissiveIntensity: 0.35,2951 })2952 : null;29532954 let baseY = 0.65;2955 let body = null;2956 let flashMaterials = null;2957 if (unit.team === 'allies') {2958 body = new THREE.Mesh(new THREE.CapsuleGeometry(0.21, 0.55, 6, 14), material);2959 body.position.y = 0.62;2960 body.castShadow = true;2961 group.add(body);29622963 const hat = new THREE.Mesh(2964 new THREE.ConeGeometry(0.27, 0.44, 10),2965 new THREE.MeshStandardMaterial({2966 color: color.clone().multiplyScalar(0.55),2967 roughness: 0.8,2968 }),2969 );2970 hat.position.y = 1.13;2971 hat.rotation.z = 0.12;2972 hat.castShadow = true;2973 group.add(hat);29742975 const orb = new THREE.Mesh(2976 new THREE.SphereGeometry(0.07, 10, 10),2977 new THREE.MeshBasicMaterial({ color: 0xfff2c4 }),2978 );2979 orb.position.set(0.28, 0.92, 0.12);2980 group.add(orb);29812982 const ring = new THREE.Mesh(2983 new THREE.TorusGeometry(0.32, 0.02, 6, 24),2984 new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.6 }),2985 );2986 ring.rotation.x = -Math.PI / 2;2987 ring.position.y = 0.06;2988 group.add(ring);2989 baseY = 0.9;2990 } else {2991 const figure = this.buildTormentFigure(unit);2992 body = figure.group;2993 baseY = figure.height;2994 flashMaterials = figure.flashMaterials;2995 group.add(body);2996 }29972998 const { bar, fill, statusDots, statusFX } = this.addUnitHud(group, unit, baseY + 0.36);29993000 const point = hex.center(unit.hex);3001 group.position.set(point.x, 0, point.z);3002 this.scene.add(group);30033004 const visual = {3005 group,3006 body,3007 bodyBaseY: body ? body.position.y : 0,3008 material,3009 flashMaterials,3010 baseEmissive: material ? material.emissive.clone() : new THREE.Color(0x000000),3011 fill,3012 bar,3013 statusDots,3014 statusFX,3015 baseY,3016 base: new THREE.Vector3(point.x, 0, point.z),3017 target: new THREE.Vector3(point.x, 0, point.z),3018 dash: null,3019 flashUntil: 0,3020 flashColor: new THREE.Color(0xffffff),3021 deathAt: 0,3022 };3023 this.unitVisuals.set(unit.id, visual);3024 return visual;3025 }30263027 3028 buildTormentFigure(unit) {3029 const group = new THREE.Group();3030 const color = new THREE.Color(unit.color);3031 const armor = new THREE.MeshStandardMaterial({3032 color: color.clone().lerp(new THREE.Color(0xffffff), 0.14),3033 roughness: 0.46,3034 metalness: 0.4,3035 emissive: color.clone().multiplyScalar(0.3),3036 emissiveIntensity: 0.45,3037 });3038 const dark = new THREE.MeshStandardMaterial({3039 color: 0x17121c,3040 roughness: 0.62,3041 metalness: 0.34,3042 });3043 const trim = new THREE.MeshStandardMaterial({3044 color: color.clone().lerp(new THREE.Color(0xffffff), 0.3),3045 roughness: 0.34,3046 metalness: 0.62,3047 emissive: color.clone().multiplyScalar(0.4),3048 emissiveIntensity: 0.45,3049 });3050 const cloth = new THREE.MeshStandardMaterial({3051 color: color.clone().multiplyScalar(0.32),3052 roughness: 0.8,3053 metalness: 0.04,3054 });3055 armor.envMap = this.environment;3056 armor.envMapIntensity = 1.2;3057 trim.envMap = this.environment;3058 trim.envMapIntensity = 1.5;3059 dark.envMap = this.environment;3060 dark.envMapIntensity = 0.7;3061 cloth.envMap = this.environment;3062 cloth.envMapIntensity = 0.5;3063 const eye = new THREE.MeshBasicMaterial({ color: 0xff5a6a });30643065 const add = (geometry, material, x, y, z, { rot, scale } = {}) => {3066 const mesh = new THREE.Mesh(geometry, material);3067 mesh.position.set(x, y, z);3068 if (rot) mesh.rotation.set(...rot);3069 if (scale) mesh.scale.set(...scale);3070 mesh.castShadow = true;3071 mesh.receiveShadow = true;3072 group.add(mesh);3073 return mesh;3074 };3075 const ball = (radius, material, x, y, z, scale) =>3076 add(new THREE.SphereGeometry(radius, 12, 9), material, x, y, z, { scale });30773078 let height = 1.2;3079 if (unit.shape === 'brute') {3080 for (const side of [-1, 1]) {3081 add(new THREE.CapsuleGeometry(0.12, 0.42, 4, 10), cloth, side * 0.2, 0.5, 0);3082 add(new THREE.CylinderGeometry(0.13, 0.12, 0.36, 10), armor, side * 0.2, 0.4, 0.02);3083 add(new THREE.BoxGeometry(0.26, 0.2, 0.36), dark, side * 0.2, 0.1, 0.05);3084 }3085 ball(0.27, dark, 0, 0.82, 0, [1.05, 0.6, 0.85]);3086 ball(0.36, armor, 0, 1.16, 0, [1.0, 1.08, 0.78]);3087 for (const y of [1.05, 1.17, 1.29]) add(new THREE.BoxGeometry(0.42, 0.05, 0.06), trim, 0, y, 0.27);3088 for (const side of [-1, 1]) {3089 ball(0.2, armor, side * 0.44, 1.4, 0, [0.9, 0.75, 1.0]);3090 add(new THREE.ConeGeometry(0.05, 0.2, 6), trim, side * 0.44, 1.56, 0, { rot: [0, 0, -side * 0.35] });3091 add(new THREE.CapsuleGeometry(0.1, 0.42, 4, 10), dark, side * 0.46, 1.02, 0.02);3092 add(new THREE.CylinderGeometry(0.11, 0.1, 0.3, 10), armor, side * 0.47, 0.9, 0.03);3093 ball(0.12, dark, side * 0.48, 0.66, 0.06);3094 }3095 add(new THREE.CylinderGeometry(0.15, 0.17, 0.16, 10), dark, 0, 1.56, 0);3096 ball(0.19, armor, 0, 1.66, 0, [1.0, 1.08, 1.05]);3097 add(new THREE.BoxGeometry(0.24, 0.2, 0.07), dark, 0, 1.6, 0.17);3098 for (const side of [-1, 1]) {3099 add(new THREE.SphereGeometry(0.03, 6, 6), eye, side * 0.07, 1.7, 0.19);3100 add(new THREE.ConeGeometry(0.06, 0.36, 6), trim, side * 0.17, 1.84, 0, { rot: [0, 0, -side * 0.5] });3101 }3102 add(new THREE.CylinderGeometry(0.035, 0.035, 1.7, 6), dark, 0.5, 0.9, 0.08);3103 add(new THREE.BoxGeometry(0.06, 0.42, 0.34), trim, 0.5, 1.6, 0.25);3104 height = 1.86;3105 } else if (unit.shape === 'spire') {3106 for (const side of [-1, 1]) {3107 add(new THREE.CapsuleGeometry(0.06, 0.5, 4, 8), cloth, side * 0.1, 0.44, 0);3108 add(new THREE.BoxGeometry(0.14, 0.13, 0.28), dark, side * 0.1, 0.07, 0.04);3109 }3110 add(new THREE.BoxGeometry(0.34, 0.07, 0.24), dark, 0, 0.8, 0);3111 add(new THREE.BoxGeometry(0.06, 0.08, 0.03), trim, 0, 0.8, 0.13);3112 ball(0.16, dark, 0, 1.0, 0, [0.92, 1.18, 0.7]);3113 add(new THREE.BoxGeometry(0.2, 0.22, 0.04), armor, 0, 1.04, 0.12);3114 add(new THREE.BoxGeometry(0.05, 0.44, 0.03), trim, 0.06, 0.98, 0.13, { rot: [0, 0, -0.45] });3115 for (const side of [-1, 1]) {3116 ball(0.075, dark, side * 0.19, 1.15, 0, [1, 0.9, 1]);3117 add(new THREE.CylinderGeometry(0.05, 0.045, 0.12, 8), armor, side * 0.24, 0.8, 0.02);3118 }3119 add(new THREE.CapsuleGeometry(0.045, 0.3, 4, 8), dark, -0.23, 0.94, 0);3120 add(new THREE.CapsuleGeometry(0.045, 0.26, 4, 8), dark, 0.26, 1.0, 0.08, { rot: [-0.7, 0, 0] });3121 ball(0.05, dark, 0.34, 1.0, 0.16);3122 add(new THREE.TorusGeometry(0.42, 0.018, 5, 18, Math.PI), trim, 0.36, 1.0, 0.18, {3123 rot: [0, Math.PI / 2, Math.PI / 2],3124 });3125 add(new THREE.CylinderGeometry(0.004, 0.004, 0.84, 4), dark, 0.36, 1.0, 0.18);3126 add(new THREE.CylinderGeometry(0.008, 0.008, 0.6, 4), dark, 0.36, 1.0, 0.5, { rot: [Math.PI / 2, 0, 0] });3127 add(new THREE.ConeGeometry(0.02, 0.08, 4), trim, 0.36, 1.0, 0.82, { rot: [Math.PI / 2, 0, 0] });3128 add(new THREE.CylinderGeometry(0.05, 0.045, 0.42, 8), dark, -0.12, 1.1, -0.14, { rot: [0, 0, 0.25] });3129 add(new THREE.ConeGeometry(0.02, 0.04, 4), trim, -0.11, 1.36, -0.13);3130 add(new THREE.ConeGeometry(0.16, 0.36, 10), armor, 0, 1.4, 0);3131 ball(0.11, dark, 0, 1.3, 0);3132 add(new THREE.BoxGeometry(0.2, 0.14, 0.05), dark, 0, 1.27, 0.13);3133 for (const side of [-1, 1]) {3134 add(new THREE.SphereGeometry(0.02, 6, 6), eye, side * 0.05, 1.31, 0.165);3135 }3136 height = 1.6;3137 } else {3138 for (const side of [-1, 1]) {3139 add(new THREE.CapsuleGeometry(0.07, 0.4, 4, 8), cloth, side * 0.11, 0.42, 0);3140 add(new THREE.CylinderGeometry(0.085, 0.075, 0.36, 8), armor, side * 0.11, 0.38, 0);3141 add(new THREE.BoxGeometry(0.16, 0.16, 0.3), dark, side * 0.11, 0.08, 0.05);3142 }3143 ball(0.17, dark, 0, 0.8, 0, [1.1, 0.6, 0.85]);3144 for (const side of [-1, 1]) {3145 add(new THREE.BoxGeometry(0.13, 0.22, 0.04), armor, side * 0.1, 0.66, 0.14, { rot: [0, 0, -side * 0.08] });3146 }3147 ball(0.19, armor, 0, 1.0, 0, [1.05, 1.1, 0.8]);3148 add(new THREE.BoxGeometry(0.06, 0.3, 0.03), trim, 0, 1.0, 0.16);3149 add(new THREE.BoxGeometry(0.3, 0.05, 0.04), trim, 0, 0.84, 0.14);3150 for (const side of [-1, 1]) {3151 ball(0.1, armor, side * 0.22, 1.16, 0, [1, 0.8, 1]);3152 add(new THREE.ConeGeometry(0.035, 0.12, 5), trim, side * 0.22, 1.27, 0, { rot: [0, 0, -side * 0.25] });3153 add(new THREE.CapsuleGeometry(0.05, 0.3, 4, 8), dark, side * 0.26, 0.92, 0, { rot: [0, 0, -side * 0.1] });3154 ball(0.06, armor, side * 0.28, 0.7, 0.03);3155 }3156 add(new THREE.CylinderGeometry(0.06, 0.07, 0.1, 8), dark, 0, 1.23, 0);3157 ball(0.13, armor, 0, 1.33, 0, [0.95, 1.08, 1.05]);3158 add(new THREE.BoxGeometry(0.16, 0.09, 0.07), dark, 0, 1.3, 0.1);3159 add(new THREE.BoxGeometry(0.14, 0.016, 0.02), eye, 0, 1.33, 0.14);3160 add(new THREE.ConeGeometry(0.03, 0.2, 5), trim, 0, 1.52, -0.02);3161 add(new THREE.BoxGeometry(0.3, 0.4, 0.04), armor, -0.2, 0.9, 0.2);3162 ball(0.05, trim, -0.2, 0.9, 0.23);3163 add(new THREE.BoxGeometry(0.035, 0.52, 0.06), trim, 0.32, 1.0, 0.1, { rot: [0.25, 0, 0] });3164 add(new THREE.BoxGeometry(0.14, 0.03, 0.05), dark, 0.32, 0.74, 0.1);3165 add(new THREE.CylinderGeometry(0.018, 0.018, 0.12, 6), dark, 0.32, 0.68, 0.1);3166 height = 1.5;3167 }31683169 const flashMaterials = [3170 { material: armor, baseEmissive: armor.emissive.clone(), baseIntensity: 0.35 },3171 { material: dark, baseEmissive: dark.emissive.clone(), baseIntensity: 0.35 },3172 { material: trim, baseEmissive: trim.emissive.clone(), baseIntensity: 0.45 },3173 { material: cloth, baseEmissive: cloth.emissive.clone(), baseIntensity: 0 },3174 ];3175 return { group, flashMaterials, height };3176 }31773178 setHover(cell) {3179 this.hover = cell;3180 }31813182 setTargets(cells) {3183 this.targets = cells;3184 }31853186 handleEvent(event) {3187 if (event.type === 'round') {3188 this.spawnShadowPulse();3189 return;3190 }3191 if (event.type === 'line' && event.cells?.length) {3192 for (const cell of event.cells) this.spawnBeam(event.from, cell, event.color ?? 0x9fe8ff);3193 this.suppressCast = true;3194 return;3195 }3196 if (event.type === 'burst') {3197 this.spawnBurst(event.hex, event.radius ?? 1);3198 this.suppressCast = true;3199 return;3200 }3201 if (event.type === 'attack' || event.type === 'retaliate') {3202 this.suppressCast = false;3203 this.animateAttack(event);3204 return;3205 }3206 if (event.type === 'damage') {3207 this.handleDamage(event);3208 return;3209 }3210 if (event.type === 'move') {3211 this.suppressCast = false;3212 if (event.from) this.spawnDustPuff(event.from);3213 const visual = this.unitVisuals.get(event.unit);3214 if (visual?.actions?.Walk && this.time !== this.cardAt) {3215 visual.actions.Idle?.fadeOut(0.06);3216 const walk = visual.actions.Walk;3217 visual.actionSerial = (visual.actionSerial ?? 0) + 1;3218 const serial = visual.actionSerial;3219 walk.reset();3220 walk.setLoop(THREE.LoopRepeat, Infinity);3221 walk.fadeIn(0.06).play();3222 this.after(0.5, () => {3223 if (visual.actionSerial !== serial) return;3224 walk.fadeOut(0.18);3225 visual.actions.Idle?.reset().fadeIn(0.18).play();3226 });3227 }3228 return;3229 }3230 if (event.type === 'death') {3231 this.spawnDeath(event.unit);3232 }3233 this.suppressCast = false;3234 const colorByType = {3235 heal: 0x7cf0a8,3236 death: 0xffffff,3237 card: 0xa98bff,3238 status: 0x7fd7ff,3239 };3240 const color = colorByType[event.type];3241 if (!color) return;3242 const id = event.unit ?? event.target ?? event.attacker;3243 this.flashUnit(id, color);3244 if (event.type === 'card') {3245 this.cardAt = this.time;3246 this.playModelAction(this.unitVisuals.get(event.unit), 'Attack');3247 }3248 }32493250 flashUnit(id, color, duration = 0.28) {3251 const visual = this.unitVisuals.get(id);3252 if (!visual) return;3253 visual.flashColor.setHex(color);3254 visual.flashUntil = this.time + duration;3255 }32563257 3258 after(delay, action) {3259 this.timers.push({ at: this.time + delay, action });3260 }32613262 playModelAction(visual, name, hold = 0.85) {3263 if (!visual?.actions?.[name]) return;3264 const action = visual.actions[name];3265 visual.actionSerial = (visual.actionSerial ?? 0) + 1;3266 const serial = visual.actionSerial;3267 for (const [key, other] of Object.entries(visual.actions)) {3268 if (key !== name) other.fadeOut(0.08);3269 }3270 action.reset();3271 action.setLoop(THREE.LoopOnce, 1);3272 action.clampWhenFinished = true;3273 action.fadeIn(0.08).play();3274 this.after(action.getClip().duration * hold, () => {3275 if (visual.actionSerial !== serial) return;3276 action.fadeOut(0.14);3277 visual.actions.Idle?.reset().fadeIn(0.14).play();3278 });3279 }32803281 animateAttack(event) {3282 const attacker = this.unitVisuals.get(event.attacker);3283 const target = this.unitVisuals.get(event.target);3284 if (!attacker || !target) return;3285 this.attackChain = { attacker: event.attacker, target: event.target };32863287 const color = event.type === 'retaliate' ? ATTACK_COLORS.retaliate : ATTACK_COLORS.attack;3288 const from = new THREE.Vector3(attacker.target.x, 0.72, attacker.target.z);3289 const to = new THREE.Vector3(target.target.x, 0.72, target.target.z);3290 const direction = flatDirection(from, to);3291 const ranged = (event.range ?? 1) > 1;32923293 if (attacker.weapon) {3294 attacker.weapon.swingAt = this.time;3295 attacker.weapon.swingDuration = ranged ? 0.5 : 0.36;3296 }32973298 this.playModelAction(attacker, 'Attack');32993300 if (ranged) {3301 3302 attacker.dash = {3303 dir: direction.clone().negate(),3304 distance: 0.12,3305 startedAt: this.time,3306 duration: 0.2,3307 };3308 this.flashUnit(event.attacker, color, 0.2);3309 this.spawnProjectile(from, to, color, 0.22, () => {3310 this.hitUnit(event.target, from, to, color);3311 });3312 return;3313 }33143315 3316 attacker.dash = {3317 dir: direction,3318 distance: 0.55,3319 startedAt: this.time,3320 duration: 0.32,3321 };3322 this.after(0.15, () => this.hitUnit(event.target, from, to, color, { slash: true }));3323 }33243325 handleDamage(event) {3326 const chain = this.attackChain;3327 this.attackChain = null;3328 if (chain && chain.attacker === event.source && chain.target === event.unit) {3329 3330 return;3331 }3332 if (3333 !this.suppressCast &&3334 event.source &&3335 this.unitVisuals.has(event.source) &&3336 this.unitVisuals.has(event.unit)3337 ) {3338 3339 const caster = this.unitVisuals.get(event.source);3340 const target = this.unitVisuals.get(event.unit);3341 const from = new THREE.Vector3(caster.target.x, 0.72, caster.target.z);3342 const to = new THREE.Vector3(target.target.x, 0.72, target.target.z);3343 this.flashUnit(event.source, ATTACK_COLORS.cast, 0.24);3344 this.spawnProjectile(from, to, ATTACK_COLORS.cast, 0.24, () => {3345 this.hitUnit(event.unit, from, to, ATTACK_COLORS.cast);3346 });3347 return;3348 }3349 this.flashUnit(event.unit, ATTACK_COLORS.damage);3350 }33513352 hitUnit(id, from, to, color, { slash = false } = {}) {3353 const visual = this.unitVisuals.get(id);3354 if (!visual) return;3355 this.flashUnit(id, color, 0.3);3356 this.spawnImpact(new THREE.Vector3(to.x, 0.75, to.z), color);3357 if (slash) this.spawnSlash(new THREE.Vector3(to.x, 0.8, to.z), color);3358 this.playModelAction(visual, 'Hit', 0.8);3359 visual.dash = {3360 dir: flatDirection(from, to),3361 distance: 0.16,3362 startedAt: this.time,3363 duration: 0.24,3364 };3365 }33663367 spawnProjectile(from, to, color, duration, onArrive) {3368 const material = new THREE.MeshBasicMaterial({3369 color,3370 transparent: true,3371 opacity: 0.95,3372 blending: THREE.AdditiveBlending,3373 depthWrite: false,3374 });3375 const group = new THREE.Group();3376 const direction = new THREE.Vector3().subVectors(to, from);3377 const distance = direction.length();3378 if (distance < 0.01) return;3379 direction.normalize();33803381 const head = new THREE.Mesh(new THREE.SphereGeometry(0.075, 8, 8), material);3382 const trail = new THREE.Mesh(new THREE.CylinderGeometry(0.022, 0.01, 0.5, 5), material);3383 trail.position.y = -0.28;3384 group.add(head, trail);3385 group.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction);3386 group.position.copy(from);3387 this.scene.add(group);33883389 this.projectiles.push({3390 group,3391 material,3392 from: from.clone(),3393 to: to.clone(),3394 startedAt: this.time,3395 duration,3396 arc: Math.min(0.45, distance * 0.08),3397 onArrive,3398 });3399 }34003401 spawnImpact(point, color) {3402 const ringMaterial = new THREE.MeshBasicMaterial({3403 color,3404 transparent: true,3405 opacity: 0.9,3406 side: THREE.DoubleSide,3407 blending: THREE.AdditiveBlending,3408 depthWrite: false,3409 });3410 const ring = new THREE.Mesh(new THREE.RingGeometry(0.07, 0.14, 24), ringMaterial);3411 ring.position.copy(point);3412 ring.quaternion.copy(this.camera.quaternion);3413 this.scene.add(ring);3414 this.effects.push({ mesh: ring, material: ringMaterial, life: 0.3, maxLife: 0.3, grow: 2.6 });34153416 const sparkPositions = new Float32Array(7 * 3);3417 for (let index = 0; index < 7; index += 1) {3418 const angle = (index / 7) * Math.PI * 2 + Math.random() * 0.4;3419 const spread = 0.14 + Math.random() * 0.1;3420 sparkPositions[index * 3] = Math.cos(angle) * spread;3421 sparkPositions[index * 3 + 1] = (Math.random() - 0.35) * spread;3422 sparkPositions[index * 3 + 2] = Math.sin(angle) * spread;3423 }3424 const sparkGeometry = new THREE.BufferGeometry();3425 sparkGeometry.setAttribute('position', new THREE.BufferAttribute(sparkPositions, 3));3426 const sparkMaterial = new THREE.PointsMaterial({3427 color,3428 size: 0.075,3429 transparent: true,3430 opacity: 0.95,3431 blending: THREE.AdditiveBlending,3432 depthWrite: false,3433 });3434 const sparks = new THREE.Points(sparkGeometry, sparkMaterial);3435 sparks.position.copy(point);3436 this.scene.add(sparks);3437 this.effects.push({ mesh: sparks, material: sparkMaterial, life: 0.32, maxLife: 0.32, grow: 1.8 });3438 }34393440 spawnSlash(point, color) {3441 const material = new THREE.MeshBasicMaterial({3442 color,3443 transparent: true,3444 opacity: 0.95,3445 side: THREE.DoubleSide,3446 blending: THREE.AdditiveBlending,3447 depthWrite: false,3448 });3449 const geometry = new THREE.RingGeometry(0.24, 0.38, 20, 1, Math.PI * 0.18, Math.PI * 0.72);3450 const mesh = new THREE.Mesh(geometry, material);3451 mesh.position.copy(point);3452 mesh.quaternion.copy(this.camera.quaternion);3453 mesh.rotateZ(-0.45);3454 this.scene.add(mesh);3455 this.effects.push({ mesh, material, life: 0.22, maxLife: 0.22, grow: 1.5, opacity: 0.95 });3456 }34573458 spawnParticles(point, color, {3459 count = 8,3460 spread = 0.4,3461 size = 0.07,3462 life = 0.5,3463 rise = 0,3464 grow = 1.4,3465 opacity = 0.85,3466 } = {}) {3467 const positions = new Float32Array(count * 3);3468 for (let index = 0; index < count; index += 1) {3469 const angle = Math.random() * Math.PI * 2;3470 const radius = Math.random() * spread;3471 positions[index * 3] = Math.cos(angle) * radius;3472 positions[index * 3 + 1] = (Math.random() - 0.3) * spread * 0.6;3473 positions[index * 3 + 2] = Math.sin(angle) * radius;3474 }34753476 const geometry = new THREE.BufferGeometry();3477 geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));3478 const material = new THREE.PointsMaterial({3479 color,3480 size,3481 map: this.glowTexture,3482 transparent: true,3483 opacity,3484 blending: THREE.AdditiveBlending,3485 depthWrite: false,3486 sizeAttenuation: true,3487 });3488 const points = new THREE.Points(geometry, material);3489 points.position.copy(point);3490 points.frustumCulled = false;3491 this.scene.add(points);3492 this.effects.push({ mesh: points, material, life, maxLife: life, grow, rise, opacity });3493 }34943495 spawnDustPuff(cell) {3496 const point = hex.center(cell);3497 this.spawnParticles(new THREE.Vector3(point.x, 0.12, point.z), 0x9b8d9f, {3498 count: 7,3499 spread: 0.5,3500 size: 0.09,3501 life: 0.55,3502 rise: 0.12,3503 grow: 1.1,3504 opacity: 0.5,3505 });3506 }35073508 spawnDeath(id) {3509 const visual = this.unitVisuals.get(id);3510 if (!visual) return;3511 const point = new THREE.Vector3(visual.target.x, 0.85, visual.target.z);3512 this.spawnImpact(point, 0xc9b6ff);3513 this.spawnParticles(point, 0xbfa9ff, {3514 count: 12,3515 spread: 0.55,3516 size: 0.07,3517 life: 0.9,3518 rise: 0.7,3519 grow: 1.6,3520 opacity: 0.8,3521 });35223523 const wispMaterial = new THREE.SpriteMaterial({3524 map: this.glowTexture,3525 color: 0xcdbbff,3526 transparent: true,3527 opacity: 0.8,3528 blending: THREE.AdditiveBlending,3529 depthWrite: false,3530 });3531 const wisp = new THREE.Sprite(wispMaterial);3532 wisp.position.copy(point);3533 wisp.scale.set(0.7, 0.7, 1);3534 this.scene.add(wisp);3535 this.effects.push({3536 mesh: wisp,3537 material: wispMaterial,3538 life: 0.9,3539 maxLife: 0.9,3540 grow: 1.2,3541 rise: 0.9,3542 opacity: 0.8,3543 });3544 }35453546 spawnBeam(from, to, color) {3547 if (!from || !to) return;3548 const start = hex.center(from);3549 const end = hex.center(to);3550 const a = new THREE.Vector3(start.x, 0.7, start.z);3551 const b = new THREE.Vector3(end.x, 0.7, end.z);3552 const direction = b.clone().sub(a);3553 const length = direction.length();3554 if (length < 0.01) return;3555 const material = new THREE.MeshBasicMaterial({3556 color,3557 transparent: true,3558 opacity: 0.9,3559 blending: THREE.AdditiveBlending,3560 depthWrite: false,3561 });3562 const mesh = new THREE.Mesh(new THREE.CylinderGeometry(0.035, 0.035, length, 6), material);3563 mesh.position.copy(a).add(b).multiplyScalar(0.5);3564 mesh.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction.normalize());3565 this.scene.add(mesh);3566 this.effects.push({ mesh, material, life: 0.4, maxLife: 0.4 });3567 }35683569 spawnBurst(centerHex, radius) {3570 const point = hex.center(centerHex);3571 const material = new THREE.MeshBasicMaterial({3572 color: 0xc7a1ff,3573 transparent: true,3574 opacity: 0.8,3575 side: THREE.DoubleSide,3576 depthWrite: false,3577 });3578 const mesh = new THREE.Mesh(new THREE.RingGeometry(0.4, 0.58, 40), material);3579 mesh.rotation.x = -Math.PI / 2;3580 mesh.position.set(point.x, 0.12, point.z);3581 this.scene.add(mesh);3582 this.effects.push({ mesh, material, life: 0.5, maxLife: 0.5, grow: 1 + radius * 1.6 });3583 }35843585 35863587358835893590 spawnShadowPulse() {3591 const material = new THREE.MeshBasicMaterial({3592 map: this.glowTexture,3593 color: 0x05030a,3594 transparent: true,3595 opacity: 0.62,3596 depthWrite: false,3597 });3598 const mesh = new THREE.Mesh(new THREE.PlaneGeometry(9, 7), material);3599 mesh.rotation.x = -Math.PI / 2;3600 mesh.position.set(9.2, 0.058, 0);3601 mesh.renderOrder = 1;3602 this.scene.add(mesh);3603 this.effects.push({ mesh, material, life: 1.5, maxLife: 1.5, opacity: 0.62, driftX: -2.4 });3604 }36053606 update(dt, snapshot, { hover = null } = {}) {3607 this.time += dt;3608 this.screen = snapshot?.screen ?? 'battle';3609 for (let index = this.timers.length - 1; index >= 0; index -= 1) {3610 const timer = this.timers[index];3611 if (this.time < timer.at) continue;3612 this.timers.splice(index, 1);3613 timer.action();3614 }3615 this.updateAmbient(dt);3616 if (VILLAGE_SCREENS.has(this.screen)) {3617 this.updateVillage(dt);3618 this.marker.visible = false;3619 for (const visual of this.unitVisuals.values()) visual.group.visible = false;3620 return;3621 }3622 if (!snapshot?.battle) {3623 this.marker.visible = false;3624 for (const mesh of this.highlights.values()) mesh.visible = false;3625 for (const visual of this.unitVisuals.values()) visual.group.visible = false;3626 return;3627 }3628 const battle = snapshot.battle;3629 const alive = new Set();36303631 for (const unit of battle.units) {3632 alive.add(unit.id);3633 const visual = this.unitVisuals.get(unit.id) ?? this.buildUnit(unit);3634 visual.mixer?.update(dt);3635 const point = hex.center(unit.hex);3636 visual.target.set(point.x, 0, point.z);3637 const factor = Math.min(1, dt * 14);3638 visual.base.x += (visual.target.x - visual.base.x) * factor;3639 visual.base.z += (visual.target.z - visual.base.z) * factor;36403641 let dashX = 0;3642 let dashZ = 0;3643 if (visual.dash) {3644 const progress = (this.time - visual.dash.startedAt) / visual.dash.duration;3645 if (progress >= 1) {3646 visual.dash = null;3647 } else {3648 const offset = Math.sin(progress * Math.PI) * visual.dash.distance;3649 dashX = visual.dash.dir.x * offset;3650 dashZ = visual.dash.dir.z * offset;3651 }3652 }3653 visual.group.position.x = visual.base.x + dashX;3654 visual.group.position.z = visual.base.z + dashZ;36553656 if (unit.health <= 0) {3657 if (!visual.deathAt) visual.deathAt = this.time;3658 const progress = Math.min(1, (this.time - visual.deathAt) / 0.45);3659 visual.group.scale.setScalar(1 - progress * 0.9);3660 visual.group.position.y = -progress * 0.6;3661 if (progress >= 1) visual.group.visible = false;3662 } else {3663 visual.deathAt = 0;3664 visual.group.visible = true;3665 visual.group.scale.setScalar(1);3666 visual.group.position.y = 0;3667 if (visual.body) {3668 const breath = Math.sin(this.time * 1.7 + unit.id * 1.3);3669 visual.body.position.y = visual.bodyBaseY + breath * 0.025;3670 visual.body.rotation.z = Math.sin(this.time * 1.05 + unit.id) * 0.012;3671 }3672 if (visual.weapon) {3673 const weapon = visual.weapon;3674 const elapsed = (this.time - weapon.swingAt) / weapon.swingDuration;3675 const active = elapsed >= 0 && elapsed <= 1;3676 const swing = active ? Math.sin(elapsed * Math.PI) : 0;3677 weapon.pivots.forEach((entry, index) => {3678 const idle = Math.sin(this.time * 1.5 + index * 1.7 + unit.id) * 0.018;3679 entry.pivot.rotation.set(entry.rest.x, entry.rest.y, entry.rest.z);3680 if (entry.axis === 'y') entry.pivot.rotation.y += swing * entry.amplitude + idle;3681 else entry.pivot.rotation.z += swing * entry.amplitude + idle;3682 });3683 }3684 }36853686 const ratio = Math.max(0, unit.health / unit.maxHealth);3687 visual.fill.scale.x = Math.max(0.001, ratio);3688 visual.fill.position.x = -0.41 * (1 - ratio);3689 visual.bar.quaternion3690 .copy(visual.group.quaternion)3691 .invert()3692 .multiply(this.camera.quaternion);36933694 for (const { status, dot } of visual.statusDots) {3695 if (status === 'ward') dot.visible = unit.wardRounds > 0;3696 else if (status === 'poison') dot.visible = unit.poisonRounds > 0;3697 else if (status === 'marked') dot.visible = unit.markedRounds > 0;3698 else if (status === 'rooted') dot.visible = unit.rooted > 0;3699 }37003701 if (visual.statusFX) {3702 const fx = visual.statusFX;3703 const warded = unit.wardRounds > 0;3704 fx.ward.visible = warded;3705 fx.wardWire.visible = warded;3706 if (warded) {3707 const pulse = 1 + Math.sin(this.time * 2.2 + unit.id) * 0.015;3708 fx.ward.scale.setScalar(pulse);3709 fx.wardWire.scale.setScalar(pulse);3710 fx.ward.material.opacity = 0.07 + Math.sin(this.time * 2 + unit.id) * 0.02;3711 }3712 fx.rooted.visible = unit.rooted > 0;3713 if (unit.rooted > 0) fx.rooted.rotation.y += dt * 0.6;3714 fx.poison.visible = unit.poisonRounds > 0;3715 if (unit.poisonRounds > 0) {3716 fx.poison.rotation.z += dt * 1.2;3717 fx.poison.scale.setScalar(1 + Math.sin(this.time * 3 + unit.id) * 0.08);3718 }3719 fx.marked.visible = unit.markedRounds > 0;3720 if (unit.markedRounds > 0) {3721 fx.marked.rotation.y += dt * 2.4;3722 fx.marked.position.y = fx.markedBaseY + Math.sin(this.time * 2.6 + unit.id) * 0.05;3723 }3724 }37253726 if (visual.flashMaterials) {3727 const flashing = visual.flashUntil > this.time;3728 for (const entry of visual.flashMaterials) {3729 if (flashing) {3730 entry.material.emissive.copy(visual.flashColor);3731 entry.material.emissiveIntensity = 1.5;3732 } else {3733 entry.material.emissive.copy(entry.baseEmissive);3734 entry.material.emissiveIntensity = entry.baseIntensity;3735 }3736 }3737 } else if (visual.flashUntil > this.time) {3738 visual.material.emissive.copy(visual.flashColor);3739 visual.material.emissiveIntensity = 1.6;3740 } else {3741 visual.material.emissive.copy(visual.baseEmissive);3742 visual.material.emissiveIntensity = 0.35;3743 }3744 }37453746 for (const [id, visual] of this.unitVisuals) {3747 if (!alive.has(id)) {3748 this.scene.remove(visual.group);3749 if (visual.flashMaterials) {3750 for (const entry of visual.flashMaterials) entry.material.dispose();3751 } else {3752 visual.material.dispose();3753 }3754 this.unitVisuals.delete(id);3755 }3756 }37573758 const currentUnit = battle.units.find((unit) => unit.id === battle.current);3759 if (currentUnit) {3760 const point = hex.center(currentUnit.hex);3761 this.marker.position.x = point.x;3762 this.marker.position.z = point.z;3763 this.marker.rotation.z = this.time * 0.8;3764 this.marker.visible = true;3765 } else {3766 this.marker.visible = false;3767 }37683769 const reachable = new Set(battle.reachable.map(hex.key));3770 const attackableHexes = new Set(3771 battle.units3772 .filter((unit) => battle.attackable.includes(unit.id))3773 .map((unit) => hex.key(unit.hex)),3774 );3775 const targetSet = new Set(this.targets.map(hex.key));3776 const currentKey = currentUnit ? hex.key(currentUnit.hex) : null;3777 const hoverKey = hover ? hex.key(hover) : null;3778 3779 3780 const selecting = snapshot.screen === 'battle' && Boolean(battle.isPlayerTurn);37813782 for (const [key, mesh] of this.highlights) {3783 let color = null;3784 let opacity = 0.6;3785 if (selecting && key === hoverKey) {3786 color = 0xffe7a3;3787 opacity = 0.9;3788 } else if (selecting && targetSet.has(key)) {3789 color = 0x8fe0ff;3790 opacity = 0.85;3791 } else if (selecting && reachable.has(key)) {3792 color = 0x6fe08f;3793 opacity = 0.7;3794 } else if (selecting && attackableHexes.has(key)) {3795 color = 0xff6b7a;3796 opacity = 0.85;3797 } else if (selecting && key === currentKey) {3798 color = 0xd9b566;3799 opacity = 0.6;3800 }3801 mesh.visible = color !== null;3802 if (color !== null) {3803 mesh.material.color.setHex(color);3804 mesh.material.opacity = opacity;3805 }3806 }38073808 for (let index = this.effects.length - 1; index >= 0; index -= 1) {3809 const effect = this.effects[index];3810 effect.life -= dt;3811 if (effect.life <= 0) {3812 this.scene.remove(effect.mesh);3813 if (effect.mesh.geometry) effect.mesh.geometry.dispose();3814 effect.material.dispose();3815 this.effects.splice(index, 1);3816 continue;3817 }3818 const progress = 1 - effect.life / effect.maxLife;3819 effect.material.opacity = (effect.opacity ?? 0.9) * (1 - progress);3820 if (effect.rise) effect.mesh.position.y += effect.rise * dt;3821 if (effect.driftX) effect.mesh.position.x += effect.driftX * dt;3822 if (effect.grow) effect.mesh.scale.setScalar(1 + progress * effect.grow);3823 }38243825 for (let index = this.projectiles.length - 1; index >= 0; index -= 1) {3826 const projectile = this.projectiles[index];3827 const progress = Math.min(1, (this.time - projectile.startedAt) / projectile.duration);3828 projectile.group.position.lerpVectors(projectile.from, projectile.to, progress);3829 projectile.group.position.y += Math.sin(progress * Math.PI) * projectile.arc;3830 if (progress < 1) continue;3831 this.scene.remove(projectile.group);3832 projectile.group.traverse((child) => {3833 if (child.geometry) child.geometry.dispose();3834 });3835 projectile.material.dispose();3836 this.projectiles.splice(index, 1);3837 projectile.onArrive?.();3838 }3839 }38403841 project(cell, height = 1.15) {3842 const point = hex.center(cell);3843 const vector = new THREE.Vector3(point.x, height, point.z).project(this.camera);3844 return {3845 x: (vector.x * 0.5 + 0.5) * window.innerWidth,3846 y: (-vector.y * 0.5 + 0.5) * window.innerHeight,3847 visible: vector.z < 1,3848 };3849 }38503851 pickHex(clientX, clientY) {3852 const rect = this.canvas.getBoundingClientRect();3853 const ndc = new THREE.Vector2(3854 ((clientX - rect.left) / rect.width) * 2 - 1,3855 -((clientY - rect.top) / rect.height) * 2 + 1,3856 );3857 this.raycaster.setFromCamera(ndc, this.camera);3858 const point = new THREE.Vector3();3859 if (!this.raycaster.ray.intersectPlane(this.groundPlane, point)) return null;3860 return hex.hexFromPoint(point.x, point.z);3861 }38623863 render() {3864 if (VILLAGE_SCREENS.has(this.screen) && this.villageScene) {3865 this.renderer.render(this.villageScene, this.villageCamera);3866 return;3867 }3868 this.renderer.render(this.scene, this.camera);3869 }3870}38713872export function createView(canvas) {3873 return new BattleView(canvas);3874}