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 | 394x 394x 394x 177x 394x 177x 177x 1x 177x 394x 394x 394x 130x 130x 130x 130x 130x 130x 130x 130x 394x 16x 16x 15x 15x 15x 16x 394x 1x 1x 1x 1x 394x 14x 14x 14x 14x 14x 14x 394x 394x 68x 68x 68x 68x 68x 68x 394x 141x 394x 10x 394x | /**
* usePlayerAnimation - React hook for player animation state
*
* Provides a React interface to the PlayerAnimationStateMachine
* with automatic cleanup and event handling.
*
* @module hooks/usePlayerAnimation
* @category Hooks
* @korean 플레이어애니메이션훅
*/
import { useCallback, useMemo, useRef, useState } from "react";
import {
AnimationEvents,
AnimationState,
DEFAULT_ANIMATION_CONFIGS,
PlayerAnimationStateMachine,
} from "../systems/animation";
import type {
AnimationConfig,
AnimationUpdateResult,
} from "../systems/animation/core/types";
import type { TrigramStance } from "../types/common";
/**
* Options for usePlayerAnimation hook
*
* @korean 플레이어애니메이션훅옵션
*/
export interface UsePlayerAnimationOptions {
/**
* Custom animation configurations
* If not provided, uses DEFAULT_ANIMATION_CONFIGS
*
* @korean 커스텀애니메이션설정
*/
readonly customConfigs?: Map<AnimationState, AnimationConfig>;
/**
* Animation event callbacks
*
* **IMPORTANT**: The events object should be stable (memoized) to prevent
* unnecessary re-initialization of the animation system. Changes to event
* callbacks after the hook is initialized will NOT be reflected in the
* animation system. Use `useMemo` or define events outside the component
* to ensure stability.
*
* @korean 이벤트콜백
*/
readonly events?: AnimationEvents;
/**
* Initial animation state (defaults to "idle")
*
* @korean 초기상태
*/
readonly initialState?: AnimationState;
}
/**
* Return type for usePlayerAnimation hook
*
* @korean 플레이어애니메이션훅반환타입
*/
export interface UsePlayerAnimationReturn {
/**
* Current animation state
*
* @korean 현재상태
*/
readonly currentState: AnimationState;
/**
* Current frame index
*
* @korean 현재프레임
*/
readonly currentFrame: number;
/**
* Update animation state (call in useFrame)
*
* @param deltaTime - Time elapsed since last update in seconds
* @returns Animation update result
*
* @korean 업데이트
*/
readonly update: (deltaTime: number) => AnimationUpdateResult;
/**
* Transition to a new animation state
*
* @param newState - Target animation state
* @returns Whether transition was successful
*
* @korean 상태전환
*/
readonly transitionTo: (newState: AnimationState) => boolean;
/**
* Transition to ATTACK state with technique-specific duration.
*
* The default ATTACK config is 200ms (12 frames), but real techniques
* range from 350ms to 1200ms. This method overrides the duration so
* the state machine stays in ATTACK for the full technique animation.
*
* @param durationSeconds - The skeletal animation duration in seconds
* @returns Whether transition was successful
*
* @korean 공격전환 (기술별 지속시간)
*/
readonly transitionToAttack: (durationSeconds: number) => boolean;
/**
* Transition to stance-specific guard animation
*
* @param stance - Trigram stance
* @returns Whether transition was successful
*
* @korean 자세가드전환
*/
readonly transitionToStanceGuard: (stance: TrigramStance) => boolean;
/**
* Transition to stance_change animation with specific transition data
*
* **Korean**: 자세 전환 애니메이션 시작
*
* Initiates a stance change animation with the specific transition data
* from the 64-transition matrix. This provides stance-specific keyframes
* and blend weights for smooth interpolation.
*
* @param fromStance - Source trigram stance
* @param toStance - Target trigram stance
* @returns Whether transition was successful
*
* @korean 자세전환애니메이션시작
*/
readonly transitionToStanceChange: (
fromStance: TrigramStance,
toStance: TrigramStance,
) => boolean;
/**
* Check if currently in a stance guard animation
*
* @returns True if in any stance guard state
*
* @korean 자세가드확인
*/
readonly isInStanceGuard: () => boolean;
/**
* Get current guard stance (if in guard animation)
*
* @returns Trigram stance or null
*
* @korean 현재가드자세
*/
readonly getCurrentGuardStance: () => TrigramStance | null;
/**
* Reset animation to idle state
*
* @korean 초기화
*/
readonly reset: () => void;
}
/**
* React hook for player animation state management
*
* Provides frame-accurate animation control with priority system
* and event callbacks. Integrates seamlessly with useFrame for
* 60fps updates.
*
* @param options - Animation options
* @returns Animation control interface
*
* @example
* ```typescript
* // Basic usage
* const { currentState, currentFrame, update, transitionTo } = usePlayerAnimation({
* events: {
* onAnimationStart: (state) => console.log(`Started ${state}`),
* onAnimationComplete: (state) => console.log(`Completed ${state}`),
* onFrame: (frame, state) => {
* if (state === "attack" && frame === 6) {
* // Execute attack at midpoint
* executeAttack();
* }
* }
* }
* });
*
* // In useFrame callback
* useFrame((state, delta) => {
* const result = update(delta);
* // Update visuals based on result.state and result.frame
* });
*
* // Trigger animations
* const handleAttackInput = () => {
* transitionTo("attack");
* };
*
* const handleMovement = (isMoving: boolean) => {
* transitionTo(isMoving ? "walk" : "idle");
* };
* ```
*
* @korean 플레이어애니메이션훅
*/
export function usePlayerAnimation(
options: UsePlayerAnimationOptions = {},
): UsePlayerAnimationReturn {
const { customConfigs, events, initialState = "idle" } = options;
// Force re-renders when state changes
const [, forceUpdate] = useState(0);
// Create animation configs (memoized)
const configs = useMemo(
() => customConfigs ?? DEFAULT_ANIMATION_CONFIGS,
[customConfigs],
);
// Create animation state machine (persistent across renders via useMemo)
const stateMachine = useMemo(() => {
const machine = new PlayerAnimationStateMachine(configs, events);
// Set initial state if not "idle"
if (initialState !== "idle") {
machine.transitionTo(initialState);
}
return machine;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // Empty deps - only create once
// Track previous state to only update on actual changes
const prevStateRef = useRef<AnimationState>(stateMachine.getCurrentState());
const prevFrameRef = useRef<number>(stateMachine.getCurrentFrame());
// Memoized callbacks with selective state updates
const update = useCallback(
(deltaTime: number) => {
const result = stateMachine.update(deltaTime);
const currentState = stateMachine.getCurrentState();
const currentFrame = stateMachine.getCurrentFrame();
// Only trigger re-render if state or frame changed
Eif (
currentState !== prevStateRef.current ||
currentFrame !== prevFrameRef.current
) {
prevStateRef.current = currentState;
prevFrameRef.current = currentFrame;
forceUpdate((n) => n + 1);
}
return result;
},
[stateMachine],
);
const transitionTo = useCallback(
(newState: AnimationState) => {
const success = stateMachine.transitionTo(newState);
if (success) {
prevStateRef.current = stateMachine.getCurrentState();
prevFrameRef.current = stateMachine.getCurrentFrame();
forceUpdate((n) => n + 1);
}
return success;
},
[stateMachine],
);
const reset = useCallback(() => {
stateMachine.reset();
prevStateRef.current = stateMachine.getCurrentState();
prevFrameRef.current = stateMachine.getCurrentFrame();
forceUpdate((n) => n + 1);
}, [stateMachine]);
const transitionToStanceGuard = useCallback(
(stance: TrigramStance) => {
const success = stateMachine.transitionToStanceGuard(stance);
Eif (success) {
prevStateRef.current = stateMachine.getCurrentState();
prevFrameRef.current = stateMachine.getCurrentFrame();
forceUpdate((n) => n + 1);
}
return success;
},
[stateMachine],
);
const transitionToAttack = useCallback(
(durationSeconds: number) => {
const success = stateMachine.transitionToAttack(durationSeconds);
if (success) {
prevStateRef.current = stateMachine.getCurrentState();
prevFrameRef.current = stateMachine.getCurrentFrame();
forceUpdate((n) => n + 1);
}
return success;
},
[stateMachine],
);
const transitionToStanceChange = useCallback(
(fromStance: TrigramStance, toStance: TrigramStance) => {
const success = stateMachine.transitionToStanceChange(
fromStance,
toStance,
);
Eif (success) {
prevStateRef.current = stateMachine.getCurrentState();
prevFrameRef.current = stateMachine.getCurrentFrame();
forceUpdate((n) => n + 1);
}
return success;
},
[stateMachine],
);
const isInStanceGuard = useCallback(() => {
return stateMachine.isInStanceGuard();
}, [stateMachine]);
const getCurrentGuardStance = useCallback(() => {
return stateMachine.getCurrentGuardStance();
}, [stateMachine]);
// Memoize the return value to ensure stable reference unless state/frame changes
// Note: Using ref.current as dependencies is intentional here - when state changes,
// forceUpdate triggers a re-render, and the refs have new values which cause
// the useMemo to recalculate
// Return a fresh object each render to ensure currentState/currentFrame are always up-to-date
// Mutable ref values don't trigger re-renders, so we can't rely on memoization here
return {
currentState: prevStateRef.current,
currentFrame: prevFrameRef.current,
update,
transitionTo,
transitionToAttack,
transitionToStanceGuard,
transitionToStanceChange,
isInStanceGuard,
getCurrentGuardStance,
reset,
};
}
|