Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 | 198x 198x 198x 198x 198x 198x 198x 198x 8x 25x 8x 273x 273x 273x 273x 241x 32x 32x 32x 32x 32x 32x 32x 273x 273x 273x 273x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 990x 198x 198x 594x 273x 273x 273x 273x 32x 32x 32x 32x 273x 273x 198x 198x 198x 198x 198x 198x 990x 990x 990x 198x 198x 13860x 396x 13464x 1980x 11484x 4752x 6732x 3366x 3366x 3366x 13860x 13860x 13860x 198x 15x 10x | /**
* Collision Detection System for Black Trigram combat physics.
*
* **Korean**: 충돌 감지 시스템
*
* Implements precise collision detection for the 70 vital points combat system using:
* - Broad-phase AABB (Axis-Aligned Bounding Box) checks for performance
* - Narrow-phase raycasting for precise vital point detection
* - Attack reach validation based on technique and stance
* - Bounding boxes for 5 anatomical regions
*
* ## Architecture
*
* The system uses a two-phase collision detection approach:
*
* 1. **Broad-phase**: Fast AABB checks to eliminate impossible collisions
* 2. **Narrow-phase**: Precise raycasting to identify specific vital points
*
* This ensures 60fps performance even with complex collision queries.
*
* ## Performance
*
* - Broad-phase: O(1) per check (simple distance comparison)
* - Narrow-phase: O(n) where n = vital points in region (typically 8-20)
* - Target: <100 collision checks per frame for 60fps
*
* @example
* ```typescript
* const collision = new CollisionDetection();
*
* const result = collision.checkAttackHit(
* { x: 0, y: 0, z: 5 }, // Attacker position
* { x: 0, y: 0, z: 6.5 }, // Defender position
* { id: "kick", type: "kick" }, // Technique
* TrigramStance.LI, // Attacker stance
* "torso" // Target region
* );
*
* if (result.hit) {
* console.log(`Hit ${result.vitalPoint?.names.english}!`);
* console.log(`Accuracy: ${(result.accuracy * 100).toFixed(1)}%`);
* }
* ```
*
* @module systems/physics/CollisionDetection
* @category Combat Systems
* @korean 충돌감지시스템
*/
import * as THREE from "three";
import { TrigramStance } from "../../types/common";
import type {
AnatomicalRegionPhysics,
BoundingBox,
CollisionResult,
Position3D,
RaycastQuery,
TechniqueType,
} from "../../types/physics";
import {
BASE_REACH,
STANCE_REACH_MODIFIERS,
ANATOMICAL_DIMENSIONS
} from "../../types/physics";
import type { VitalPoint } from "../vitalpoint/types";
import { VITAL_POINTS_DATA } from "../vitalpoint/VitalPointsData";
import { CoordinateMapper } from "./CoordinateMapper";
/**
* Collision Detection Engine for combat physics.
*
* **Korean**: 충돌 감지 엔진
*
* Provides efficient collision detection for combat using bounding boxes and raycasting.
* Optimized for 60fps performance with multiple simultaneous collision checks.
*
* @public
* @category Combat Systems
* @korean 충돌감지엔진
*/
export class CollisionDetection {
private readonly boundingBoxes: Map<AnatomicalRegionPhysics, BoundingBox> = new Map();
private readonly raycaster: THREE.Raycaster = new THREE.Raycaster();
private vitalPointsByRegion: Map<AnatomicalRegionPhysics, VitalPoint[]> = new Map();
// Geometry cache for object pooling to avoid repeated allocations during combat
private readonly geometryCache: Map<string, THREE.BufferGeometry> = new Map();
// Coordinate mapper for 2D→3D conversion
private readonly coordinateMapper: CoordinateMapper;
/**
* Creates a new CollisionDetection instance.
*
* Initializes bounding boxes for all anatomical regions and organizes
* vital points by region for efficient lookup.
*/
constructor() {
this.coordinateMapper = new CoordinateMapper();
this.initializeBoundingBoxes();
this.organizeVitalPointsByRegion();
this.initializeGeometryCache();
}
/**
* Cleans up Three.js resources.
*
* **Korean**: 자원 정리
*
* Disposes of cached geometries and releases memory to prevent leaks.
* Should be called when the CollisionDetection instance is no longer needed.
*
* @public
* @korean 자원정리
*/
public dispose(): void {
// Dispose all cached geometries
for (const geometry of this.geometryCache.values()) {
geometry.dispose();
}
this.geometryCache.clear();
}
/**
* Checks if an attack hits the defender.
*
* **Korean**: 공격 타격 확인
*
* Performs two-phase collision detection:
* 1. Calculate effective attack reach based on technique and stance
* 2. Broad-phase: Check if defender is within reach
* 3. Broad-phase: Check if target region's AABB is within reach
* 4. Narrow-phase: Raycast to find precise vital point hit
*
* @param attackerPosition - 3D position of the attacker
* @param defenderPosition - 3D position of the defender
* @param technique - Technique being used with type information
* @param attackerStance - Attacker's current trigram stance
* @param targetRegion - Anatomical region being targeted
* @returns Collision result with hit status, vital point, distance, and accuracy
*
* @example
* ```typescript
* const result = collision.checkAttackHit(
* { x: 0, y: 0, z: 5 },
* { x: 0, y: 0, z: 6 },
* { type: "punch" },
* TrigramStance.GEON,
* "head"
* );
* ```
*
* @public
* @korean 공격타격확인
*/
checkAttackHit(
attackerPosition: Position3D,
defenderPosition: Position3D,
technique: { type?: string; [key: string]: any },
attackerStance: TrigramStance,
targetRegion: AnatomicalRegionPhysics
): CollisionResult {
// Calculate effective attack reach
const techniqueType = this.parseTechniqueType(technique.type);
const attackReach = this.calculateAttackReach(techniqueType, attackerStance);
// Calculate distance between attacker and defender
const distance = this.calculateDistance3D(attackerPosition, defenderPosition);
// Broad-phase: Check if defender is within reach
if (distance > attackReach.effectiveReach) {
return {
hit: false,
distance,
accuracy: 0,
};
}
// Get target region bounding box
const targetBox = this.boundingBoxes.get(targetRegion);
Iif (!targetBox) {
return {
hit: false,
distance,
accuracy: 0,
};
}
// Narrow-phase: Raycast from attacker to target region
const attackDirection = this.normalizeVector3D(
this.subtractVectors3D(defenderPosition, attackerPosition)
);
const raycastQuery: RaycastQuery = {
origin: attackerPosition,
direction: attackDirection,
maxDistance: attackReach.effectiveReach,
targetRegion,
};
// Check intersection with target bounding box
const intersection = this.raycastBoundingBox(raycastQuery, targetBox, defenderPosition);
Eif (!intersection) {
return {
hit: false,
distance,
accuracy: 0,
};
}
// Determine specific vital point within region
const vitalPoint = this.identifyVitalPoint(
targetRegion,
intersection.point,
defenderPosition
);
if (!vitalPoint) {
return {
hit: false,
distance,
accuracy: 0,
};
}
// Calculate accuracy (how close to vital point center)
const accuracy = this.calculateHitAccuracy(intersection.point, vitalPoint, defenderPosition);
return {
hit: true,
region: targetRegion,
vitalPoint,
distance,
accuracy,
hitPoint: intersection.point,
};
}
/**
* Calculates effective attack reach for a technique.
*
* **Korean**: 공격 범위 계산
*
* Applies stance modifiers to base technique reach.
*
* @param techniqueType - Type of technique
* @param stance - Current trigram stance
* @returns Attack reach with all modifiers applied
*
* @private
* @korean 공격범위계산
*/
private calculateAttackReach(
techniqueType: TechniqueType,
stance: TrigramStance
): {
technique: TechniqueType;
baseReach: number;
stance: TrigramStance;
stanceModifier: number;
effectiveReach: number;
} {
// Use BASE_REACH constant from physics types
const baseReach = BASE_REACH[techniqueType];
// Use STANCE_REACH_MODIFIERS constant from physics types
const stanceModifier = STANCE_REACH_MODIFIERS[stance];
const effectiveReach = baseReach * stanceModifier;
return {
technique: techniqueType,
baseReach,
stance,
stanceModifier,
effectiveReach,
};
}
/**
* Performs raycasting against a bounding box.
*
* **Korean**: 경계 상자 광선 투사
*
* Uses cached geometries from object pool to avoid repeated allocations
* during combat. Creates a Three.js mesh for the bounding box and performs
* raycasting to detect intersection points.
*
* @param query - Raycast query parameters
* @param box - Bounding box to test
* @param defenderPosition - Position of the defender
* @returns Intersection point or null if no hit
*
* @private
* @korean 경계상자광선투사
*/
private raycastBoundingBox(
query: RaycastQuery,
box: BoundingBox,
defenderPosition: Position3D
): { point: Position3D } | null {
// Get cached geometry from pool to avoid repeated allocations
const cacheKey = `${box.type}-${box.region}`;
let geometry = this.geometryCache.get(cacheKey);
// If not cached (shouldn't happen after initialization), create it
Iif (!geometry) {
geometry = this.createGeometryForBox(box);
this.geometryCache.set(cacheKey, geometry);
}
// Create temporary mesh for raycasting (mesh is lightweight, geometry is cached)
const mesh = new THREE.Mesh(geometry);
mesh.position.set(
defenderPosition.x + box.center.x,
defenderPosition.y + box.center.y,
defenderPosition.z + box.center.z
);
// Setup raycaster
this.raycaster.set(
new THREE.Vector3(query.origin.x, query.origin.y, query.origin.z),
new THREE.Vector3(query.direction.x, query.direction.y, query.direction.z)
);
this.raycaster.far = query.maxDistance;
// Perform raycast
const intersections = this.raycaster.intersectObject(mesh);
// Clean up temporary mesh (geometry remains cached)
// Note: mesh.material is undefined, no need to dispose
Iif (intersections.length > 0) {
const point = intersections[0].point;
return {
point: { x: point.x, y: point.y, z: point.z },
};
}
return null;
}
/**
* Creates Three.js geometry for a bounding box.
*
* Helper method for geometry cache initialization.
*
* @param box - Bounding box specification
* @returns Three.js geometry
*
* @private
* @korean 경계상자지오메트리생성
*/
private createGeometryForBox(box: BoundingBox): THREE.BufferGeometry {
switch (box.type) {
case "sphere":
return new THREE.SphereGeometry(box.dimensions.x, 8, 8);
case "box":
return new THREE.BoxGeometry(
box.dimensions.x,
box.dimensions.y,
box.dimensions.z
);
case "capsule":
return new THREE.CapsuleGeometry(
box.dimensions.x,
box.dimensions.y,
4,
8
);
}
}
/**
* Identifies the specific vital point hit within a region.
*
* **Korean**: 급소 식별
*
* Finds the closest vital point to the hit location within the targeted region.
*
* @param region - Anatomical region hit
* @param hitPoint - 3D point where attack intersected
* @param defenderPosition - Position of the defender
* @returns Closest vital point or null if none found
*
* @private
* @korean 급소식별
*/
private identifyVitalPoint(
region: AnatomicalRegionPhysics,
hitPoint: Position3D,
_defenderPosition: Position3D // Prefixed with _ to indicate intentionally unused
): VitalPoint | null {
// Get all vital points for this region
const vitalPoints = this.vitalPointsByRegion.get(region);
if (!vitalPoints || vitalPoints.length === 0) {
return null;
}
// Use CoordinateMapper to find the closest vital point in 3D space
const result = this.coordinateMapper.findClosestVitalPoint(
hitPoint,
vitalPoints,
region
);
// For collision detection, we accept any vital point in the region
// even if it's not very close, as long as the region was hit
// This provides more forgiving collision detection while still
// using accurate 3D positioning for scoring/accuracy
return result ? result.vitalPoint : (vitalPoints.length > 0 ? vitalPoints[0] : null);
}
/**
* Calculates hit accuracy based on distance to vital point center.
*
* **Korean**: 타격 정확도 계산
*
* Accuracy decreases linearly with distance from vital point center.
* Perfect accuracy (1.0) at center, decreasing to 0 at 5cm radius.
*
* @param hitPoint - Point where attack landed
* @param vitalPoint - Target vital point
* @param defenderPosition - Position of the defender
* @returns Accuracy value from 0 to 1
*
* @private
* @korean 타격정확도계산
*/
private calculateHitAccuracy(
hitPoint: Position3D,
vitalPoint: VitalPoint,
_defenderPosition: Position3D // Prefixed with _ to indicate intentionally unused
): number {
// Use CoordinateMapper to convert vital point to 3D and calculate distance
const distance = this.coordinateMapper.distanceToVitalPoint(hitPoint, vitalPoint);
// Accuracy calculation: Perfect (1.0) at center, decreasing to 0 at 5cm radius
const maxDistance = 0.05; // 5cm radius for vital points
const accuracy = Math.max(0, 1 - (distance / maxDistance));
return accuracy;
}
/**
* Calculates Euclidean distance between two 3D points.
*
* @param pos1 - First position
* @param pos2 - Second position
* @returns Distance in meters
*
* @private
* @korean 3D거리계산
*/
private calculateDistance3D(pos1: Position3D, pos2: Position3D): number {
const dx = pos1.x - pos2.x;
const dy = pos1.y - pos2.y;
const dz = pos1.z - pos2.z;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
/**
* Subtracts one 3D vector from another.
*
* @param v1 - First vector
* @param v2 - Second vector
* @returns Resulting vector
*
* @private
* @korean 벡터빼기
*/
private subtractVectors3D(v1: Position3D, v2: Position3D): Position3D {
return {
x: v1.x - v2.x,
y: v1.y - v2.y,
z: v1.z - v2.z,
};
}
/**
* Normalizes a 3D vector to unit length.
*
* @param vec - Vector to normalize
* @returns Normalized vector
*
* @private
* @korean 벡터정규화
*/
private normalizeVector3D(vec: Position3D): Position3D {
const length = Math.sqrt(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z);
Iif (length === 0) {
return { x: 0, y: 0, z: 1 }; // Default forward direction
}
return {
x: vec.x / length,
y: vec.y / length,
z: vec.z / length,
};
}
/**
* Parses technique type from string.
*
* @param techniqueTypeStr - Technique type as string
* @returns Parsed technique type
*
* @private
* @korean 기술유형파싱
*/
private parseTechniqueType(techniqueTypeStr?: string): TechniqueType {
const typeMap: Record<string, TechniqueType> = {
punch: "punch",
kick: "kick",
elbow: "elbow",
knee: "knee",
pressure_point: "pressure_point",
strike: "punch", // Default strike to punch
};
return typeMap[techniqueTypeStr || "punch"] || "punch";
}
/**
* Initializes bounding boxes for all anatomical regions.
*
* Creates collision volumes for the 5 anatomical regions using the
* ANATOMICAL_DIMENSIONS constants from the physics types module.
*
* @private
* @korean 경계상자초기화
*/
private initializeBoundingBoxes(): void {
// Head: Sphere (from ANATOMICAL_DIMENSIONS)
this.boundingBoxes.set("head", {
type: ANATOMICAL_DIMENSIONS.head.type,
center: ANATOMICAL_DIMENSIONS.head.center,
dimensions: {
x: ANATOMICAL_DIMENSIONS.head.radius,
y: 0,
z: 0
}, // radius only
region: "head",
});
// Neck: Capsule (from ANATOMICAL_DIMENSIONS)
this.boundingBoxes.set("neck", {
type: ANATOMICAL_DIMENSIONS.neck.type,
center: ANATOMICAL_DIMENSIONS.neck.center,
dimensions: {
x: ANATOMICAL_DIMENSIONS.neck.radius,
y: ANATOMICAL_DIMENSIONS.neck.height,
z: 0
}, // radius and height
region: "neck",
});
// Torso: Box (from ANATOMICAL_DIMENSIONS)
this.boundingBoxes.set("torso", {
type: ANATOMICAL_DIMENSIONS.torso.type,
center: ANATOMICAL_DIMENSIONS.torso.center,
dimensions: {
x: ANATOMICAL_DIMENSIONS.torso.width,
y: ANATOMICAL_DIMENSIONS.torso.height,
z: ANATOMICAL_DIMENSIONS.torso.depth
}, // width, height, depth
region: "torso",
});
// Arms: Capsules (from ANATOMICAL_DIMENSIONS)
this.boundingBoxes.set("arms", {
type: ANATOMICAL_DIMENSIONS.arms.type,
center: ANATOMICAL_DIMENSIONS.arms.center,
dimensions: {
x: ANATOMICAL_DIMENSIONS.arms.radius,
y: ANATOMICAL_DIMENSIONS.arms.height,
z: 0
}, // radius and length
region: "arms",
});
// Legs: Capsules (from ANATOMICAL_DIMENSIONS)
this.boundingBoxes.set("legs", {
type: ANATOMICAL_DIMENSIONS.legs.type,
center: ANATOMICAL_DIMENSIONS.legs.center,
dimensions: {
x: ANATOMICAL_DIMENSIONS.legs.radius,
y: ANATOMICAL_DIMENSIONS.legs.height,
z: 0
}, // radius and length
region: "legs",
});
}
/**
* Initializes geometry cache for object pooling.
*
* Pre-creates all geometries needed for raycasting to avoid repeated
* allocations during combat. Critical for maintaining 60fps with up to
* 100 collision checks per frame.
*
* @private
* @korean 지오메트리캐시초기화
*/
private initializeGeometryCache(): void {
// Pre-create and cache geometries for all bounding boxes
for (const [_region, box] of this.boundingBoxes.entries()) {
const cacheKey = `${box.type}-${box.region}`;
const geometry = this.createGeometryForBox(box);
this.geometryCache.set(cacheKey, geometry);
}
}
/**
* Organizes vital points by anatomical region for efficient lookup.
*
* NOTE: This categorization currently uses y-coordinate thresholds that assume
* positions are in meters. However, VITAL_POINTS_DATA uses pixel coordinates
* (e.g., y: 50), which will cause incorrect categorization. Most vital points
* will end up in the "legs" region since pixel y-coordinates are typically less
* than 0.8.
*
* TODO: After implementing 2D→3D coordinate mapping, update this method to use
* the converted 3D positions, or use the anatomical region data that may already
* exist in the vital points data structure.
*
* Categorizes the 70 vital points into their respective regions:
* - Head: 10 vital points
* - Neck: 8 vital points
* - Torso: 20 vital points
* - Arms: 16 vital points
* - Legs: 16 vital points
*
* @private
* @korean 급소영역별정리
*/
private organizeVitalPointsByRegion(): void {
const regionMap: Map<AnatomicalRegionPhysics, VitalPoint[]> = new Map([
["head", []],
["neck", []],
["torso", []],
["arms", []],
["legs", []],
]);
// Use existing VitalPointsData categorization by ID prefix
// This is more reliable than coordinate-based heuristics
for (const vp of VITAL_POINTS_DATA) {
let region: AnatomicalRegionPhysics;
// Categorize by ID prefix (existing VitalPointsData convention)
// Check neck-related patterns first (more specific) before head (broader)
if (
vp.id.includes("_neck") ||
vp.id.includes("_throat") ||
vp.id === "head_side_neck" ||
vp.id === "head_throat"
) {
region = "neck";
} else if (vp.id.startsWith("head_")) {
region = "head";
} else if (vp.id.startsWith("torso_")) {
region = "torso";
} else if (vp.id.startsWith("arm_left_") || vp.id.startsWith("arm_right_")) {
region = "arms";
} else if (vp.id.startsWith("leg_left_") || vp.id.startsWith("leg_right_")) {
region = "legs";
} else E{
// Default to torso for uncategorized points (core region)
region = "torso";
}
const list = regionMap.get(region);
Eif (list) {
list.push(vp);
}
}
this.vitalPointsByRegion = regionMap;
}
/**
* Gets the bounding box for an anatomical region.
*
* @param region - Anatomical region
* @returns Bounding box or undefined if not found
*
* @public
* @korean 경계상자조회
*/
getBoundingBox(region: AnatomicalRegionPhysics): BoundingBox | undefined {
return this.boundingBoxes.get(region);
}
/**
* Gets all bounding boxes.
*
* @returns Map of all bounding boxes by region
*
* @public
* @korean 모든경계상자조회
*/
getAllBoundingBoxes(): ReadonlyMap<AnatomicalRegionPhysics, BoundingBox> {
return this.boundingBoxes;
}
/**
* Gets vital points for a specific region.
*
* @param region - Anatomical region
* @returns Array of vital points in that region
*
* @public
* @korean 영역별급소조회
*/
getVitalPointsInRegion(region: AnatomicalRegionPhysics): readonly VitalPoint[] {
return this.vitalPointsByRegion.get(region) || [];
}
}
export default CollisionDetection;
|