Skip to content

Free Motion Capture for Everyone πŸ’€βœ¨

TypeScript
21.9 KB
Raw Blame
import {createSelector, createSlice, PayloadAction} from '@reduxjs/toolkit';
import {RootState} from '../../types';
import {loadFromStorage} from '@/store/persistence';
import {
    processMocapRecording,
    startMocapRecording,
    stopMocapRecording,
} from "@/store/slices/mocap/mocap-thunks";
import {
    selectActiveRecordingFullPath,
    selectActiveRecordingOrigin,
    selectEffectiveRecordingPath,
} from "@/store/slices/active-recording/active-recording-slice";

// ==================== Types ====================

/**
 * Legacy numeric complexity levels for the old MediaPipe realtime detector config.
 * 0 = LITE (fastest), 1 = FULL (balanced), 2 = HEAVY (most accurate)
 */
export type LegacyMediapipeModelComplexity = 0 | 1 | 2;

/**
 * Mirrors skellytracker MediapipeDetectorConfig.
 * Field names use snake_case to match the backend JSON.
 */
export interface MediapipeDetectorConfig {
    model_complexity: LegacyMediapipeModelComplexity;
    min_detection_confidence: number;
    min_tracking_confidence: number;
    confidence_threshold: number;
    static_image_mode: boolean;
    smooth_landmarks: boolean;
    enable_segmentation: boolean;
    smooth_segmentation: boolean;
    refine_face_landmarks: boolean;
}

/**
 * Mirrors backend EstimatorConfig (bone length estimation tuning).
 */
export interface EstimatorConfig {
    max_samples: number;
    min_samples_for_full_confidence: number;
    iqr_confidence_sensitivity: number;
}

export interface TriangulationConfig {
    use_outlier_rejection: boolean;
    minimum_cameras_for_triangulation: number;
    maximum_cameras_to_drop: number;
    target_reprojection_error: number;
}

export type BlenderModelFormat = "fbx" | "bvh";
export type ArmatureRestPose = "tpose" | "apose";

/**
 * Options forwarded to the freemocap_blender_addon's export.
 * Field names use snake_case to match the backend JSON.
 */
export interface BlenderExportConfig {
    /** Formats to write. May be empty, which skips 3D model export entirely. */
    formats: BlenderModelFormat[];
    /** Rest pose the armature is built in. */
    rest_pose: ArmatureRestPose;
    /** Run the addon's foot-locking motion cleanup before the scene is set up. */
    apply_foot_locking: boolean;
    /** Run the addon's hand/finger marker range-of-motion limit before the scene is set up. */
    limit_hand_markers_range_of_motion: boolean;
}

export interface PosthocFilterConfig {
    method: "butter_low_pass";
    cutoff: number;
    sampling_rate: number;
    order: number;
}

/**
 * Mirrors backend RealtimeFilterConfig (skeleton smoothing + gating).
 * Field names use snake_case to match the backend JSON.
 */
export interface RealtimeFilterConfig {
    // One Euro Filter params
    min_cutoff: number;
    beta: number;
    d_cutoff: number;
    // FABRIK params
    fabrik_tolerance: number;
    fabrik_max_iterations: number;
    // Bone length estimation params
    height_meters: number;
    noise_sigma: number;
    estimator_config: EstimatorConfig;
    // Point gate params
    max_reprojection_error_px: number;
    max_velocity_m_per_s: number;
    max_rejected_streak: number;
    // Prediction params
    max_prediction_frames: number;
    prediction_velocity_decay: number;
}

export type DetectorType = "rtmpose" | "mediapipe";
export type RTMPoseModelName = "rtmw-x-l_256x192" | "rtmw-x-l_384x288" | "rtmw-l-m_256x192";
export type MediapipeModelComplexity = "lite" | "full" | "heavy";

export const RTMPOSE_MODELS: { label: string; value: RTMPoseModelName }[] = [
    { label: "Default", value: "rtmw-x-l_256x192" },
    { label: "High Res", value: "rtmw-x-l_384x288" },
    { label: "Fast", value: "rtmw-l-m_256x192" },
];

/**
 * Mirrors backend MocapPipelineConfig.
 */
export interface MocapConfig {
    detector: MediapipeDetectorConfig;
    skeleton_filter: RealtimeFilterConfig;
    triangulation: TriangulationConfig;
    posthoc_filter: PosthocFilterConfig;
    blender_export: BlenderExportConfig;
    detectorType: DetectorType;
    rtmPoseModelName: RTMPoseModelName;
    rtmPoseConfidenceThreshold: number;
    mediapipeModelComplexity: MediapipeModelComplexity;
    mediapipeDetectionConfidence: number;
    mediapipePresenceConfidence: number;
    mediapipeTrackingConfidence: number;
    mediapipeNumHands: number;
    mediapipeNumFaces: number;
}

/** Realtime preset matching MEDIAPIPE_TRACKER_REALTIME_PRESET on the backend. */
export const MEDIAPIPE_REALTIME_PRESET: MediapipeDetectorConfig = {
    model_complexity: 0,
    min_detection_confidence: 0.5,
    min_tracking_confidence: 0.5,
    confidence_threshold: 0.5,
    static_image_mode: false,
    smooth_landmarks: true,
    enable_segmentation: false,
    smooth_segmentation: false,
    refine_face_landmarks: true,
};

/** Posthoc preset matching MEDIAPIPE_TRACKER_POSTHOC_PRESET on the backend. */
export const MEDIAPIPE_POSTHOC_PRESET: MediapipeDetectorConfig = {
    model_complexity: 2,
    min_detection_confidence: 0.5,
    min_tracking_confidence: 0.5,
    confidence_threshold: 0.5,
    static_image_mode: false,
    smooth_landmarks: true,
    enable_segmentation: true,
    smooth_segmentation: true,
    refine_face_landmarks: true,
};

/** Default EstimatorConfig matching backend defaults. */
export const DEFAULT_ESTIMATOR_CONFIG: EstimatorConfig = {
    max_samples: 500,
    min_samples_for_full_confidence: 100,
    iqr_confidence_sensitivity: 10.0,
};

export type DetectorPreset = "realtime" | "posthoc" | "custom";

/** Detects which preset (if any) the current detector config matches. */
export function detectPreset(
    config: { model_complexity: number; enable_segmentation: boolean; smooth_segmentation: boolean }
): DetectorPreset {
    if (
        config.model_complexity === 0 &&
        !config.enable_segmentation &&
        !config.smooth_segmentation
    ) return "realtime";
    if (
        config.model_complexity === 2 &&
        config.enable_segmentation &&
        config.smooth_segmentation
    ) return "posthoc";
    return "custom";
}

/**
 * Default RealtimeFilterConfig.
 *
 * One Euro Filter tuning (positions are in millimetres):
 *   adaptive cutoff (Hz) = min_cutoff + beta * |velocity_mm_s|
 *
 * min_cutoff (Hz) β€” settling speed when stationary:
 *   1.0 Hz β†’ ~0.4 s at 30 fps (default, snappy settling)
 *   0.5 Hz β†’ ~0.8 s, 2.0 Hz β†’ ~0.2 s
 *
 * beta (1/mm) β€” responsiveness during motion:
 *   0.007 β†’ walking (500 mm/s) adds 3.5 Hz; fast swing (2000 mm/s) β†’ ~15 Hz
 *   Range 0.003–0.02 is appropriate for mm-space data.
 *   NOTE: beta = 0.3 (meter-space convention) is ~1000Γ— too high.
 */

export const DEFAULT_TRIANGULATION_CONFIG: TriangulationConfig = {
    use_outlier_rejection: true,
    minimum_cameras_for_triangulation: 2,
    maximum_cameras_to_drop: 1,
    target_reprojection_error: 0.02,
};


export const DEFAULT_REALTIME_FILTER_CONFIG: RealtimeFilterConfig = {
    min_cutoff: 1.0,
    beta: 0.007,
    d_cutoff: 1.0,
    fabrik_tolerance: 1e-4,
    fabrik_max_iterations: 20,
    height_meters: 1.75,
    noise_sigma: 0.015,
    estimator_config: { ...DEFAULT_ESTIMATOR_CONFIG },
    max_reprojection_error_px: 60.0,
    max_velocity_m_per_s: 50.0,
    max_rejected_streak: 5,
    max_prediction_frames: 15,
    prediction_velocity_decay: 0.75,
};

export const DEFAULT_POSTHOC_FILTER_CONFIG: PosthocFilterConfig ={
    method: "butter_low_pass",
    cutoff: 6.0,
    sampling_rate: 30.0,
    order: 4,
};

/** Matches the addon defaults: export formats fbx+bvh, armature built in T-pose. */
export const DEFAULT_BLENDER_EXPORT_CONFIG: BlenderExportConfig = {
    formats: ["fbx", "bvh"],
    rest_pose: "tpose",
    apply_foot_locking: false,
    limit_hand_markers_range_of_motion: false,
};

export const BLENDER_MODEL_FORMATS: { label: string; value: BlenderModelFormat }[] = [
    { label: "FBX", value: "fbx" },
    { label: "BVH", value: "bvh" },
];

export const ARMATURE_REST_POSES: { label: string; value: ArmatureRestPose }[] = [
    { label: "TPOSE", value: "tpose" },
    { label: "APOSE", value: "apose" },
];


 
export interface MocapDirectoryInfo {
    exists: boolean;
    canRecord: boolean;
    canCalibrate: boolean;
    cameraMocapTomlPath: string | null;
    lastSuccessfulCalibrationTomlPath: string | null;
    hasSynchronizedVideos: boolean;
    hasVideos: boolean;
    cameraCount: number;
    errorMessage: string | null;
}

export interface MocapState {
    config: MocapConfig;
    isRecording: boolean;
    recordingProgress: number;
    isLoading: boolean;
    error: string | null;
    directoryInfo: MocapDirectoryInfo | null;
    /** User-specified calibration TOML path override. null = use most recent (default). */
    calibrationTomlPath: string | null;
    processingProgress: number;
    processingPhase: string;
}


const DEFAULT_MOCAP_CONFIG: MocapConfig = {
    detector: {...MEDIAPIPE_REALTIME_PRESET},
    triangulation: {...DEFAULT_TRIANGULATION_CONFIG},
    skeleton_filter: {...DEFAULT_REALTIME_FILTER_CONFIG},
    posthoc_filter: {...DEFAULT_POSTHOC_FILTER_CONFIG},
    blender_export: {
        formats: [...DEFAULT_BLENDER_EXPORT_CONFIG.formats],
        rest_pose: DEFAULT_BLENDER_EXPORT_CONFIG.rest_pose,
        apply_foot_locking: DEFAULT_BLENDER_EXPORT_CONFIG.apply_foot_locking,
        limit_hand_markers_range_of_motion: DEFAULT_BLENDER_EXPORT_CONFIG.limit_hand_markers_range_of_motion,
    },

    detectorType: "rtmpose",
    rtmPoseModelName: "rtmw-x-l_256x192",
    rtmPoseConfidenceThreshold: 0.004,
    mediapipeModelComplexity: "heavy",
    mediapipeDetectionConfidence: 0.5,
    mediapipePresenceConfidence: 0.5,
    mediapipeTrackingConfidence: 0.5,
    mediapipeNumHands: 2,
    mediapipeNumFaces: 1,
};

// ==================== Initial State ====================

const _persistedMocapConfig = loadFromStorage<Partial<MocapConfig> | null>( "mocap.config", null, );

const initialMocapConfig: MocapConfig = {
    ...DEFAULT_MOCAP_CONFIG,
    ...(_persistedMocapConfig ?? {}),

    detector: {
        ...DEFAULT_MOCAP_CONFIG.detector,
        ...(_persistedMocapConfig?.detector ?? {}),
    },

    triangulation: {
        ...DEFAULT_MOCAP_CONFIG.triangulation,
        ...(_persistedMocapConfig?.triangulation ?? {}),
    },

    skeleton_filter: {
        ...DEFAULT_MOCAP_CONFIG.skeleton_filter,
        ...(_persistedMocapConfig?.skeleton_filter ?? {}),
    },

    posthoc_filter: {
        ...DEFAULT_MOCAP_CONFIG.posthoc_filter,
        ...(_persistedMocapConfig?.posthoc_filter ?? {}),
    },

    blender_export: {
        ...DEFAULT_MOCAP_CONFIG.blender_export,
        ...(_persistedMocapConfig?.blender_export ?? {}),
    },
};

const initialState: MocapState = {
    config: initialMocapConfig,
    isRecording: false,
    recordingProgress: 0,
    isLoading: false,
    error: null,
    directoryInfo: null,
    calibrationTomlPath: null,
    processingProgress: 0,
    processingPhase: "",
};

// ==================== Slice ====================

export const mocapSlice = createSlice({
    name: 'mocap',
    initialState,
    reducers: {
        /** Switch between rtmpose and mediapipe detector backends. */
        mocapDetectorTypeChanged: (state, action: PayloadAction<DetectorType>) => {
            state.config.detectorType = action.payload;
        },

        /** Change the RTMPose model variant. */
        mocapRtmPoseModelNameChanged: (state, action: PayloadAction<RTMPoseModelName>) => {
            state.config.rtmPoseModelName = action.payload;
        },

        /** Change the RTMPose keypoint confidence threshold. */
        mocapRtmPoseConfidenceThresholdChanged: (state, action: PayloadAction<number>) => {
            state.config.rtmPoseConfidenceThreshold = action.payload;
        },

        /** Change the MediaPipe model complexity (lite/full/heavy). */
        mocapMediapipeComplexityChanged: (state, action: PayloadAction<MediapipeModelComplexity>) => {
            state.config.mediapipeModelComplexity = action.payload;
        },

        /** Update a shared MediaPipe confidence value (applies to pose, hands, and face). */
        mocapMediapipeDetectionConfidenceChanged: (state, action: PayloadAction<number>) => {
            state.config.mediapipeDetectionConfidence = action.payload;
        },
        mocapMediapipePresenceConfidenceChanged: (state, action: PayloadAction<number>) => {
            state.config.mediapipePresenceConfidence = action.payload;
        },
        mocapMediapipeTrackingConfidenceChanged: (state, action: PayloadAction<number>) => {
            state.config.mediapipeTrackingConfidence = action.payload;
        },

        mocapMediapipeNumHandsChanged: (state, action: PayloadAction<number>) => {
            state.config.mediapipeNumHands = action.payload;
        },
        mocapMediapipeNumFacesChanged: (state, action: PayloadAction<number>) => {
            state.config.mediapipeNumFaces = action.payload;
        },

        /** Replace the entire detector config (e.g. applying a preset). */
        mocapDetectorConfigReplaced: (state, action: PayloadAction<MediapipeDetectorConfig>) => {
            state.config.detector = action.payload;
        },

        /** Partially update individual detector fields. */
        mocapDetectorConfigUpdated: (state, action: PayloadAction<Partial<MediapipeDetectorConfig>>) => {
            state.config.detector = { ...state.config.detector, ...action.payload };
        },

        /** Replace the entire skeleton filter config. */
        skeletonFilterConfigReplaced: (state, action: PayloadAction<RealtimeFilterConfig>) => {
            state.config.skeleton_filter = action.payload;
        },

        /** Partially update individual skeleton filter fields. */
        skeletonFilterConfigUpdated: (state, action: PayloadAction<Partial<RealtimeFilterConfig>>) => {
            state.config.skeleton_filter = { ...state.config.skeleton_filter, ...action.payload };
        },

        triangulationConfigUpdated: (state, action: PayloadAction<Partial<TriangulationConfig>>) => {
            state.config.triangulation = { ...state.config.triangulation, ...action.payload };
        },

        posthocFilterConfigUpdated: (state, action: PayloadAction<Partial<PosthocFilterConfig>>) => {
            state.config.posthoc_filter = {...state.config.posthoc_filter, ...action.payload};
        },

        blenderExportConfigUpdated: (state, action: PayloadAction<Partial<BlenderExportConfig>>) => {
            state.config.blender_export = { ...state.config.blender_export, ...action.payload };
        },

        mocapProgressUpdated: (state, action: PayloadAction<number>) => {
            state.recordingProgress = action.payload;
        },

        mocapErrorCleared: (state) => {
            state.error = null;
        },

        mocapDirectoryInfoUpdated: (state, action: PayloadAction<MocapDirectoryInfo>) => {
            state.directoryInfo = action.payload;
        },

        calibrationTomlPathChanged: (state, action: PayloadAction<string>) => {
            state.calibrationTomlPath = action.payload;
        },

        calibrationTomlPathCleared: (state) => {
            state.calibrationTomlPath = null;
        },

        posthocProgressReceived: (state, action: PayloadAction<{phase: string; progress_fraction: number; detail: string}>) => {
            state.processingPhase = action.payload.phase;
            state.processingProgress = Math.round(action.payload.progress_fraction * 100);
            if (action.payload.phase === 'complete' || action.payload.phase === 'failed') {
                state.isLoading = false;
            }
        },

        resetMocapState: () => initialState,
    },

    extraReducers: (builder) => {
        builder
            .addCase(startMocapRecording.pending, (state) => {
                state.isLoading = true;
                state.error = null;
            })
            .addCase(startMocapRecording.fulfilled, (state) => {
                state.isLoading = false;
                state.isRecording = true;
                state.recordingProgress = 0;
            })
            .addCase(startMocapRecording.rejected, (state, action) => {
                state.isLoading = false;
                state.error = action.payload || 'Failed to start recording';
            });

        builder
            .addCase(stopMocapRecording.pending, (state) => {
                state.isLoading = true;
                state.error = null;
            })
            .addCase(stopMocapRecording.fulfilled, (state) => {
                state.isLoading = false;
                state.isRecording = false;
                state.recordingProgress = 0;
            })
            .addCase(stopMocapRecording.rejected, (state, action) => {
                state.isLoading = false;
                state.error = action.payload || 'Failed to stop recording';
            });

        builder
            .addCase(processMocapRecording.pending, (state) => {
                state.isLoading = true;
                state.error = null;
                state.processingProgress = 0;
                state.processingPhase = '';
            })
            .addCase(processMocapRecording.fulfilled, (state) => {
                // isLoading stays true β€” it will be reset by posthocProgressReceived
                // when the pipeline emits 'complete' or 'failed' over WebSocket
            })
            .addCase(processMocapRecording.rejected, (state, action) => {
                state.isLoading = false;
                state.error = action.payload || 'Failed to process recording';
            });

    },
});

// ==================== Selectors ====================

export const selectMocap = (state: RootState) => state.mocap;
export const selectMocapConfig = (state: RootState) => state.mocap.config;
export const selectMocapDetectorConfig = (state: RootState) => state.mocap.config.detector;
export const selectMocapTriangulationConfig = (state: RootState) => state.mocap.config.triangulation;
export const selectSkeletonFilterConfig = (state: RootState) => state.mocap.config.skeleton_filter;
export const selectPosthocFilterConfig = (state: RootState) => state.mocap.config.posthoc_filter;
export const selectMocapBlenderExportConfig = (state: RootState) => state.mocap.config.blender_export;
export const selectMocapDetectorType = (state: RootState) => state.mocap.config.detectorType;
export const selectMocapRtmPoseModelName = (state: RootState) => state.mocap.config.rtmPoseModelName;
export const selectMocapRtmPoseConfidenceThreshold = (state: RootState) => state.mocap.config.rtmPoseConfidenceThreshold;
export const selectMocapMediapipeComplexity = (state: RootState) => state.mocap.config.mediapipeModelComplexity;
export const selectMocapMediapipeDetectionConfidence = (state: RootState) => state.mocap.config.mediapipeDetectionConfidence;
export const selectMocapMediapipePresenceConfidence = (state: RootState) => state.mocap.config.mediapipePresenceConfidence;
export const selectMocapMediapipeTrackingConfidence = (state: RootState) => state.mocap.config.mediapipeTrackingConfidence;
export const selectMocapMediapipeNumHands = (state: RootState) => state.mocap.config.mediapipeNumHands;
export const selectMocapMediapipeNumFaces = (state: RootState) => state.mocap.config.mediapipeNumFaces;
export const selectMocapIsLoading = (state: RootState) => state.mocap.isLoading;
export const selectMocapIsRecording = (state: RootState) => state.mocap.isRecording;
export const selectMocapProgress = (state: RootState) => state.mocap.recordingProgress;
export const selectMocapError = (state: RootState) => state.mocap.error;
export const selectMocapDirectoryInfo = (state: RootState) => state.mocap.directoryInfo;
export const selectCalibrationTomlPath = (state: RootState) => state.mocap.calibrationTomlPath;
export const selectProcessingProgress = (state: RootState) => state.mocap.processingProgress;
export const selectProcessingPhase = (state: RootState) => state.mocap.processingPhase;

export const selectMocapRecordingPath = selectActiveRecordingFullPath;

export const selectIsUsingManualMocapPath = createSelector(
    [selectActiveRecordingOrigin],
    (origin) => origin === 'browsed',
);

export const selectCanStartMocapRecording = createSelector(
    [
        selectMocapIsRecording,
        selectMocapIsLoading,
        selectEffectiveRecordingPath,
        selectMocapDirectoryInfo
    ],
    (isRecording, isLoading, effectivePath, directoryInfo) => {
        return !isRecording && !isLoading && !!effectivePath && (directoryInfo?.canRecord ?? true);
    }
);

export const selectCanProcessMocapRecording = createSelector(
    [
        selectMocapRecordingPath,
        selectMocapIsLoading,
        selectMocapIsRecording,
        selectMocapDirectoryInfo,
        selectCalibrationTomlPath,
    ],
    (mocapPath, isLoading, isRecording, directoryInfo, manualCalibrationTomlPath) => {
        const hasVideos = directoryInfo?.hasVideos ?? false;
        // Single-camera recordings use a planar-projection fallback and never need
        // a calibration TOML; multi-camera recordings still require one for triangulation.
        const isSingleCamera = directoryInfo?.cameraCount === 1;
        const hasAnyCalibrationToml =
            !!manualCalibrationTomlPath ||
            !!directoryInfo?.cameraMocapTomlPath ||
            !!directoryInfo?.lastSuccessfulCalibrationTomlPath;
        return !!mocapPath && !isLoading && !isRecording && hasVideos && (isSingleCamera || hasAnyCalibrationToml);
    }
);

// ==================== Actions Export ====================

export const {
    mocapDetectorTypeChanged,
    mocapRtmPoseModelNameChanged,
    mocapRtmPoseConfidenceThresholdChanged,
    mocapMediapipeComplexityChanged,
    mocapMediapipeDetectionConfidenceChanged,
    mocapMediapipePresenceConfidenceChanged,
    mocapMediapipeTrackingConfidenceChanged,
    mocapMediapipeNumHandsChanged,
    mocapMediapipeNumFacesChanged,
    mocapDetectorConfigReplaced,
    mocapDetectorConfigUpdated,
    skeletonFilterConfigReplaced,
    skeletonFilterConfigUpdated,
    triangulationConfigUpdated,
    posthocFilterConfigUpdated,
    blenderExportConfigUpdated,
    mocapProgressUpdated,
    mocapErrorCleared,
    mocapDirectoryInfoUpdated,
    calibrationTomlPathChanged,
    calibrationTomlPathCleared,
    posthocProgressReceived,
    resetMocapState
} = mocapSlice.actions;

export default mocapSlice.reducer;