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 | 4x 4x 13x 13x 13x 13x 13x 13x 13x 13x 13x 85x 85x 85x 24x 24x 85x 85x 85x 85x 85x 13x 13x 4x 4x 13x 13x 13x 13x 13x 13x 13x 13x 9x 13x 12x 12x 12x 1x 85x | /**
* useTrainingActions Hook - Training Action Handlers
*
* Custom hook for managing training action handlers.
* Mirrors useCombatActions pattern for consistency.
*
* @korean 훈련액션훅 - 훈련 액션 핸들러 관리
*/
import { useCallback, useRef } from "react";
import {
AudioBodyRegion,
ImpactIntensity,
} from "../../../../audio/types";
import type { AttackIntensity } from "../../../screens/combat/hooks/useCombatAudio";
import { getArchetypePhysicalAttributes } from "../../../../data/archetypePhysicalAttributes";
import {
AnimationState,
AnimationType,
getAnimationDurationOrFallback,
getAnimationForTechnique,
} from "../../../../systems/animation";
import { physicalReachCalculator } from "../../../../systems/physics";
import { getTechniquesByStance } from "../../../../systems/trigram/techniques";
import { KoreanTechniquesSystem } from "../../../../systems/trigram/KoreanTechniques";
import { TRIGRAM_STANCES_ORDER } from "../../../../systems/trigram/types";
import type { KoreanTechnique } from "../../../../systems/vitalpoint/types";
import {
CombatAttackType,
DamageType,
PlayerArchetype,
Position,
TrigramStance,
} from "../../../../types/common";
import {
DEFAULT_BODY_RADIUS_METERS,
METERS_TO_TRAINING_UNITS,
} from "../../../../types/physicsConstants";
import { calculateDistance3D } from "../../../../utils/math";
import { TrainingActions, TrainingScreenState } from "./useTrainingState";
export interface UseTrainingActionsConfig {
readonly state: TrainingScreenState;
readonly actions: TrainingActions;
readonly playerPosition: Position;
readonly player3DPosition: [number, number, number];
readonly dummyPosition: [number, number, number];
readonly playerArchetype: import("../../../../types/common").PlayerArchetype;
readonly playerStance: TrigramStance;
/** Ref to current selected technique's animation type for distance-based hit detection */
readonly currentTechniqueAnimationTypeRef: React.MutableRefObject<AnimationType>;
readonly audio: {
readonly playSFX: (sound: string, volume?: number) => Promise<void>;
};
/** Attack sound function from useCombatAudio for playing attack whoosh sounds */
readonly playAttackSound?: (intensity: AttackIntensity) => Promise<void>;
/** Bone impact audio function from useCombatAudio or similar hook */
readonly playBoneImpactSound?: (options: {
region?: AudioBodyRegion;
intensity?: ImpactIntensity;
damage?: number;
remainingHealth?: number;
vitalPoint?: boolean;
hitPosition?: { x: number; y: number; z?: number };
}) => Promise<void>;
readonly onPlayerUpdate: (updates: {
currentStance?: TrigramStance;
lastActionTime?: number;
position?: Position;
}) => void;
readonly playerAnimation: {
readonly transitionTo: (state: AnimationState) => boolean;
readonly transitionToAttack: (durationSeconds: number) => boolean;
readonly transitionToStanceGuard: (stance: TrigramStance) => boolean;
readonly currentState: string;
};
/** External ref to store pending attack data - shared with animation events */
readonly pendingAttackRef: React.MutableRefObject<{
accuracy: number;
vitalPoint: string;
animationType?: AnimationType;
startTime?: number;
techniqueId?: string;
} | null>;
/** Currently selected technique ID (from technique bar) */
readonly selectedTechniqueId?: string;
/** Callback to set the visual attack animation */
readonly setAttackAnimation?: (animationName: string | undefined) => void;
}
export interface UseTrainingActionsReturn {
readonly handleStartTraining: () => void;
readonly handleStopTraining: () => void;
readonly handleDummyHit: (
vitalPointId: string,
attackContext?: {
animationType?: AnimationType;
techniqueId?: string;
},
) => boolean;
readonly handleDummyDefeated: () => void;
readonly handleStanceChange: (stanceIndex: number) => void;
readonly handleAttack: () => void;
}
/**
* Get the best default technique for an archetype based on current stance.
*
* Each archetype has preferred combat styles:
* - MUSA: Direct strikes, joint techniques (BLUNT/JOINT damage)
* - AMSALJA: Nerve strikes, pressure points (NERVE/PRESSURE damage)
* - HACKER: Precise calculated strikes (high accuracy)
* - JEONGBO_YOWON: Psychological pressure, submissions (PRESSURE/JOINT)
* - JOJIK_POKRYEOKBAE: High damage brutal strikes
*
* @korean 원형별 기본 기술 선택 - 8개 자세에 따른 최적 기술
*/
function getDefaultTechniqueForArchetype(
archetype: PlayerArchetype,
stance: TrigramStance,
): KoreanTechnique | undefined {
const techniques = getTechniquesByStance(stance);
Eif (techniques.length === 0) return undefined;
const scoredTechniques = techniques.map((tech) => {
let score = 0;
const damageType = tech.damageType;
const attackType = tech.type;
const isAdvanced =
(tech.kiCost || 0) >= 10 || (tech.staminaCost || 0) >= 15;
switch (archetype) {
case PlayerArchetype.MUSA:
if (damageType === DamageType.JOINT) score += 30;
if (damageType === DamageType.CRUSHING) score += 25;
if (damageType === DamageType.BLUNT) score += 20;
if (attackType === CombatAttackType.STRIKE) score += 15;
if (attackType === CombatAttackType.PUNCH) score += 10;
if (isAdvanced) score += 10;
break;
case PlayerArchetype.AMSALJA:
if (damageType === DamageType.NERVE) score += 35;
if (damageType === DamageType.PRESSURE) score += 30;
if (attackType === CombatAttackType.NERVE_STRIKE) score += 25;
if (attackType === CombatAttackType.PRESSURE_POINT) score += 25;
if (attackType === CombatAttackType.THRUST) score += 15;
if ((tech.accuracy || 0) >= 0.9) score += 10;
break;
case PlayerArchetype.HACKER:
if ((tech.accuracy || 0) >= 0.9) score += 30;
if ((tech.accuracy || 0) >= 0.8) score += 15;
if (damageType === DamageType.NERVE) score += 20;
if (damageType === DamageType.INTERNAL) score += 20;
if (attackType === CombatAttackType.PRESSURE_POINT) score += 15;
break;
case PlayerArchetype.JEONGBO_YOWON:
if (damageType === DamageType.PRESSURE) score += 30;
if (damageType === DamageType.JOINT) score += 25;
if (attackType === CombatAttackType.GRAPPLE) score += 20;
if (attackType === CombatAttackType.PRESSURE_POINT) score += 15;
break;
case PlayerArchetype.JOJIK_POKRYEOKBAE:
if ((tech.damage || 0) >= 35) score += 35;
if ((tech.damage || 0) >= 30) score += 20;
if (damageType === DamageType.SLASHING) score += 20;
if (damageType === DamageType.PIERCING) score += 15;
if (damageType === DamageType.CRUSHING) score += 15;
if (attackType === CombatAttackType.KICK) score += 10;
break;
}
return { technique: tech, score };
});
scoredTechniques.sort((a, b) => b.score - a.score);
return scoredTechniques[0]?.technique;
}
/**
* Calculate hit accuracy based on distance and effective reach.
* Uses PhysicalReachCalculator for animation-aware reach calculation.
*
* Distance logic matches CombatSystem: if out of reach, guaranteed miss (accuracy 0).
* Training scene coordinates are in meters, using METERS_TO_TRAINING_UNITS = 1.0.
*
* **IMPORTANT**: Distance calculation accounts for body radius.
* Center-to-center distance is adjusted by subtracting target body radius
* because attacks hit the body surface, not the center point.
* The target body radius is calculated from physical attributes for archetypes,
* or uses DEFAULT_BODY_RADIUS_METERS for training dummies.
*
* Example: If player center is 1.5m from dummy center, but dummy body
* extends 0.23m from center, the effective distance to hit is 1.27m.
*
* @korean 거리 기반 명중률 계산 - 사정거리 밖이면 빗나감
*/
function calculateHitAccuracy(
playerPos: [number, number, number],
dummyPos: [number, number, number],
archetype: import("../../../../types/common").PlayerArchetype,
stance: TrigramStance,
animationType?: AnimationType,
reachConfig?: import("../../../../types/physics").PhysicalReachConfig,
): number {
const centerToCenterDistance = calculateDistance3D(playerPos, dummyPos);
const playerPhysicalAttributes = getArchetypePhysicalAttributes(archetype);
const targetBodyRadius = DEFAULT_BODY_RADIUS_METERS;
const effectiveDistance = Math.max(
0,
centerToCenterDistance - targetBodyRadius,
);
Eif (animationType !== undefined) {
const maxReachMeters = physicalReachCalculator.calculateMaxReach(
playerPhysicalAttributes,
animationType,
stance,
reachConfig, // Use technique's designed reach if provided
);
const reachInUnits = maxReachMeters * METERS_TO_TRAINING_UNITS;
Eif (effectiveDistance > reachInUnits) {
return 0;
}
return Math.max(0.7, 1.0 - (effectiveDistance / reachInUnits) * 0.3);
}
const defaultReach = 0.7 * METERS_TO_TRAINING_UNITS;
if (effectiveDistance > defaultReach) {
return 0; // Out of reach = miss
}
return Math.max(0.5, 1.0 - (effectiveDistance / defaultReach) * 0.5);
}
/**
* useTrainingActions hook
* Provides training action handlers with proper memoization
*/
export function useTrainingActions(
config: UseTrainingActionsConfig,
): UseTrainingActionsReturn {
const {
state,
actions,
player3DPosition,
dummyPosition,
playerArchetype,
playerStance,
currentTechniqueAnimationTypeRef,
audio,
playBoneImpactSound,
playAttackSound,
onPlayerUpdate,
playerAnimation,
pendingAttackRef,
selectedTechniqueId,
setAttackAnimation,
} = config;
const dummyResetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const handleStartTraining = useCallback(() => {
actions.startTraining();
audio.playSFX("menu_select");
}, [actions, audio]);
const handleStopTraining = useCallback(() => {
if (dummyResetTimeoutRef.current) {
clearTimeout(dummyResetTimeoutRef.current);
dummyResetTimeoutRef.current = null;
}
actions.stopTraining();
audio.playSFX("menu_back");
}, [actions, audio]);
const handleDummyDefeated = useCallback(() => {
actions.setFeedback("훈련 더미 무력화! | Dummy Defeated!");
audio.playSFX("ki_release");
if (dummyResetTimeoutRef.current) {
clearTimeout(dummyResetTimeoutRef.current);
}
dummyResetTimeoutRef.current = setTimeout(() => {
actions.resetDummy();
}, 2000);
}, [actions, audio]);
const handleDummyHit = useCallback(
(
_vitalPointId: string,
attackContext?: {
animationType?: AnimationType;
techniqueId?: string;
},
): boolean => {
const animationType = attackContext?.animationType;
let reachConfig: import("../../../../types/physics").PhysicalReachConfig | undefined;
const resolvedTechniqueId =
attackContext?.techniqueId ?? selectedTechniqueId;
if (resolvedTechniqueId) {
const technique = KoreanTechniquesSystem.getTechniqueById(resolvedTechniqueId);
reachConfig = technique?.reachConfig;
}
const accuracy = calculateHitAccuracy(
player3DPosition,
dummyPosition,
playerArchetype,
playerStance,
animationType,
reachConfig,
);
const hitPosition: [number, number, number] = [
dummyPosition[0],
1.5,
dummyPosition[2],
];
if (accuracy > 0.5) {
const points = Math.round(accuracy * 100);
const damage = Math.round(accuracy * 15); // 0-15 damage based on accuracy
const isPerfect = accuracy > 0.9;
if (state.isTraining) {
actions.registerHit(points, damage, isPerfect);
}
if (playBoneImpactSound) {
void playBoneImpactSound({
damage,
remainingHealth: 100, // Dummy has 100 health
vitalPoint: false,
hitPosition: { x: hitPosition[0], y: hitPosition[1], z: hitPosition[2] },
});
}
let effectType: "success" | "perfect";
if (isPerfect) {
actions.setFeedback("완벽한 타격! | Perfect Strike!");
audio.playSFX("ki_release");
effectType = "perfect";
} else if (accuracy > 0.7) {
actions.setFeedback("좋은 타격! | Good Strike!");
audio.playSFX("ki_charge");
effectType = "success";
} else {
actions.setFeedback("타격 성공 | Strike Success");
audio.playSFX("menu_click");
effectType = "success";
}
actions.addHitEffect({
position: hitPosition,
type: effectType,
visible: true,
damage,
});
return true;
} else {
if (state.isTraining) {
actions.registerMiss();
}
actions.setFeedback("빗나감 | Miss - Out of reach!");
audio.playSFX("menu_navigate");
actions.addHitEffect({
position: hitPosition,
type: "miss",
visible: true,
});
return false;
}
},
[
state.isTraining,
player3DPosition,
dummyPosition,
playerArchetype,
playerStance,
actions,
audio,
playBoneImpactSound,
selectedTechniqueId,
],
);
const handleStanceChange = useCallback(
(stanceIndex: number) => {
actions.setStanceIndex(stanceIndex);
const stance = TRIGRAM_STANCES_ORDER[stanceIndex];
if (stance) {
playerAnimation.transitionToStanceGuard(stance);
onPlayerUpdate({ currentStance: stance });
audio.playSFX("stance_change");
}
},
[actions, onPlayerUpdate, audio, playerAnimation],
);
const handleAttack = useCallback(() => {
let techniqueToUse: KoreanTechnique | undefined;
let techniqueId = selectedTechniqueId;
if (!techniqueId) {
const defaultTechnique = getDefaultTechniqueForArchetype(
playerArchetype,
playerStance,
);
Iif (defaultTechnique) {
techniqueToUse = defaultTechnique;
techniqueId = defaultTechnique.id;
}
}
let animationType = currentTechniqueAnimationTypeRef.current;
Iif (techniqueToUse?.animationType) {
animationType = techniqueToUse.animationType;
currentTechniqueAnimationTypeRef.current = animationType;
}
const startTime = performance.now() / 1000; // Current time in seconds
const accuracy = calculateHitAccuracy(
player3DPosition,
dummyPosition,
playerArchetype,
playerStance,
animationType,
techniqueToUse?.reachConfig, // Pass technique's reachConfig for accurate reach
);
pendingAttackRef.current = {
accuracy,
vitalPoint: state.selectedVitalPoint ?? "generic",
animationType,
startTime,
techniqueId, // Store resolved technique ID for handleDummyHit
};
Iif (setAttackAnimation && techniqueId) {
const animationName = getAnimationForTechnique(techniqueId);
setAttackAnimation(animationName);
playerAnimation.transitionToAttack(
getAnimationDurationOrFallback(animationName),
);
} else {
playerAnimation.transitionToAttack(getAnimationDurationOrFallback());
}
if (!techniqueToUse && selectedTechniqueId) {
techniqueToUse = KoreanTechniquesSystem.getTechniqueById(selectedTechniqueId);
}
if (playAttackSound) {
const damage = techniqueToUse?.damage ?? 10;
const intensity: AttackIntensity =
damage >= 40
? "critical"
: damage >= 25
? "heavy"
: damage >= 10
? "medium"
: "light";
void playAttackSound(intensity);
} else {
audio.playSFX("whoosh");
}
}, [
state.selectedVitalPoint,
player3DPosition,
dummyPosition,
playerArchetype,
playerStance,
currentTechniqueAnimationTypeRef,
playerAnimation,
audio,
playAttackSound,
pendingAttackRef,
selectedTechniqueId,
setAttackAnimation,
]);
return {
handleStartTraining,
handleStopTraining,
handleDummyHit,
handleDummyDefeated,
handleStanceChange,
handleAttack,
};
}
export default useTrainingActions;
|