All files / entities/animations AnimationHandler.js

79.82% Statements 91/114
75% Branches 48/64
85.71% Functions 18/21
78.3% Lines 83/106

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        1x         45x 45x 45x 45x 45x 45x 45x       45x 45x     90x                     39x 24x 15x 13x     39x       3x       2x 2x       3x 1x     3x                 3x 3x   2x 2x     2x     2x 2x 1x 1x                             10x 10x 1x 1x                 9x   9x   9x 1x   8x 8x 8x   8x           8x       8x 8x                           4x 4x 1x 1x                 3x   3x 3x   3x       3x 3x   3x           3x       3x   3x 2x         2x 2x       3x                                                           1x 1x                                                       1x 1x                       2x 2x   1x 1x                 2x 2x   1x 1x                 2x 2x   1x 1x                 5x 5x       1x    
import { AnimationMixer, AnimationClip, LoopRepeat, LoopOnce, EventDispatcher } from 'three';
import { ENTITY_EVENTS } from '../constants';
import { ANIMATION_NOT_FOUND } from '../../lib/messages';
 
const DEFAULT_BLEND_DURATION = 0.3;
 
export default class AnimationHandler extends EventDispatcher {
 
    constructor(mesh, animations = []) {
        super();
        this.mixer = new AnimationMixer(mesh);
        this.animations = animations;
        this.isPlaying = false;
        this.currentAction = null;
        this.activeActions = new Map(); // Track multiple active actions for layered blending
        this.addEventsListeners();
    }
 
    addEventsListeners() {
        this.mixer.addEventListener('loop', this.getAnimationEventHandler(ENTITY_EVENTS.ANIMATION.LOOP));
        this.mixer.addEventListener('finished', this.getAnimationEventHandler(ENTITY_EVENTS.ANIMATION.FINISHED));
    }
 
    getAnimationEventHandler = (type) => ({ action, direction }) => {
        this.dispatchEvent({
            type,
            action,
            direction
        })
    }
 
    getAction(id) {
        let action;
 
        if (typeof id === 'number') {
            action = this.animations[id];
        } else if (typeof id === 'string') {
            action = AnimationClip.findByName(this.animations, id);
        }
 
        return action;
    }
 
    getAvailableAnimations() {
        return this.animations.map(({ name }) => name);
    }
 
    stopAll() {
        this.mixer.stopAllAction();
        this.isPlaying = false;
    }
 
    stopCurrentAnimation() {
        if (this.currentAction) {
            this.currentAction.stop();
        }
 
        this.isPlaying = false;
    }
 
    /**
     * Stop a specific animation by name/index with optional fade out
     * @param {string|number} id - Animation name or index
     * @param {number} fadeOutDuration - Duration to fade out (0 for immediate stop)
     */
    stopAnimation(id, fadeOutDuration = 0) {
        const clip = this.getAction(id);
        if (!clip) return;
 
        const action = this.mixer.clipAction(clip);
        Iif (fadeOutDuration > 0) {
            action.fadeOut(fadeOutDuration);
        } else {
            action.stop();
        }
 
        this.activeActions.delete(id);
        if (this.currentAction === action) {
            this.currentAction = null;
            this.isPlaying = false;
        }
    }
 
    /**
     * Play an animation with optional blending from current animation
     * @param {string|number} id - Animation name or index
     * @param {Object} options - Playback options
     * @param {number} options.loop - Loop mode (LoopRepeat, LoopOnce, etc.)
     * @param {number} options.blendDuration - Duration to blend from previous animation
     * @param {number} options.timeScale - Playback speed (1 = normal, 2 = double speed)
     * @param {number} options.weight - Animation weight for layered blending (0-1)
     * @param {boolean} options.clampWhenFinished - Keep last frame when finished (for LoopOnce)
     */
    playAnimation(id, options = {}) {
        const clip = this.getAction(id);
        if (!clip) {
            console.warn(ANIMATION_NOT_FOUND);
            return null;
        }
 
        const {
            loop = LoopRepeat,
            blendDuration = DEFAULT_BLEND_DURATION,
            timeScale = 1,
            weight = 1,
            clampWhenFinished = true
        } = options;
 
        this.isPlaying = true;
 
        if (this.currentAction) {
            return this.crossFadeTo(id, { ...options, blendDuration });
        } else {
            const action = this.mixer.clipAction(clip);
            this.currentAction = action;
            this.activeActions.set(id, action);
 
            action
                .reset()
                .setLoop(loop)
                .setEffectiveTimeScale(timeScale)
                .setEffectiveWeight(weight);
 
            Iif (loop === LoopOnce) {
                action.clampWhenFinished = clampWhenFinished;
            }
 
            action.play();
            return action;
        }
    }
 
    /**
     * Crossfade from current animation to a new animation
     * @param {string|number} id - Target animation name or index
     * @param {Object} options - Blend options
     * @param {number} options.blendDuration - Duration of the crossfade
     * @param {number} options.loop - Loop mode for the new animation
     * @param {number} options.timeScale - Playback speed
     * @param {boolean} options.warp - Whether to warp time scales during blend
     */
    crossFadeTo(id, options = {}) {
        const clip = this.getAction(id);
        if (!clip) {
            console.warn(ANIMATION_NOT_FOUND);
            return null;
        }
 
        const {
            blendDuration = DEFAULT_BLEND_DURATION,
            loop = LoopRepeat,
            timeScale = 1,
            warp = false,
            clampWhenFinished = true
        } = options;
 
        const previousAction = this.currentAction;
        const newAction = this.mixer.clipAction(clip);
 
        Iif (previousAction === newAction) {
            return newAction; // Already playing this animation
        }
 
        this.currentAction = newAction;
        this.activeActions.set(id, newAction);
 
        newAction
            .reset()
            .setLoop(loop)
            .setEffectiveTimeScale(timeScale)
            .setEffectiveWeight(1);
 
        Iif (loop === LoopOnce) {
            newAction.clampWhenFinished = clampWhenFinished;
        }
 
        newAction.play();
 
        if (previousAction) {
            Iif (warp) {
                // Synchronize time scales during crossfade
                previousAction.crossFadeTo(newAction, blendDuration, true);
            } else {
                // Standard crossfade
                previousAction.fadeOut(blendDuration);
                newAction.fadeIn(blendDuration);
            }
        }
 
        return newAction;
    }
 
    /**
     * Legacy method - kept for backwards compatibility
     */
    fadeToAnimation(action, { duration = DEFAULT_BLEND_DURATION, loop = LoopRepeat } = {}) {
        const previousAction = this.currentAction;
        this.currentAction = this.mixer.clipAction(action);
 
        if (previousAction && previousAction !== this.currentAction) {
            previousAction.fadeOut(duration);
        }
 
        this.currentAction
            .reset()
            .setEffectiveTimeScale(1)
            .setEffectiveWeight(1)
            .fadeIn(duration)
            .setLoop(loop)
            .play();
    }
 
    /**
     * Set the weight of an animation for layered blending
     * @param {string|number} id - Animation name or index
     * @param {number} weight - Weight value (0-1)
     * @param {number} fadeDuration - Optional fade duration to reach target weight
     */
    setAnimationWeight(id, weight, fadeDuration = 0) {
        const clip = this.getAction(id);
        Eif (!clip) return;
 
        const action = this.mixer.clipAction(clip);
 
        if (fadeDuration > 0) {
            // Gradually change weight
            const startWeight = action.getEffectiveWeight();
            const startTime = this.mixer.time;
 
            const updateWeight = () => {
                const elapsed = this.mixer.time - startTime;
                const t = Math.min(elapsed / fadeDuration, 1);
                action.setEffectiveWeight(startWeight + (weight - startWeight) * t);
            };
 
            // This will be called in the update loop
            action._weightUpdateFn = updateWeight;
        } else {
            action.setEffectiveWeight(weight);
        }
    }
 
    /**
     * Set the time scale (speed) of an animation
     * @param {string|number} id - Animation name or index
     * @param {number} timeScale - Speed multiplier (1 = normal)
     */
    setAnimationTimeScale(id, timeScale) {
        const clip = this.getAction(id);
        Eif (!clip) return;
 
        const action = this.mixer.clipAction(clip);
        action.setEffectiveTimeScale(timeScale);
    }
 
    /**
     * Get the current time of an animation
     * @param {string|number} id - Animation name or index
     * @returns {number} Current time in seconds
     */
    getAnimationTime(id) {
        const clip = this.getAction(id);
        if (!clip) return 0;
 
        const action = this.mixer.clipAction(clip);
        return action.time;
    }
 
    /**
     * Set the current time of an animation
     * @param {string|number} id - Animation name or index
     * @param {number} time - Time in seconds
     */
    setAnimationTime(id, time) {
        const clip = this.getAction(id);
        if (!clip) return;
 
        const action = this.mixer.clipAction(clip);
        action.time = time;
    }
 
    /**
     * Check if a specific animation is currently playing
     * @param {string|number} id - Animation name or index
     * @returns {boolean}
     */
    isAnimationPlaying(id) {
        const clip = this.getAction(id);
        if (!clip) return false;
 
        const action = this.mixer.clipAction(clip);
        return action.isRunning();
    }
 
    /**
     * Get the duration of an animation clip
     * @param {string|number} id - Animation name or index
     * @returns {number} Duration in seconds
     */
    getAnimationDuration(id) {
        const clip = this.getAction(id);
        return clip ? clip.duration : 0;
    }
 
    update(dt) {
        this.mixer.update(dt);
    }
}