diff --git a/gui/app/src/components/settings/pages/TrackingSettings.tsx b/gui/app/src/components/settings/pages/TrackingSettings.tsx index 80fe01527..747db4bbc 100644 --- a/gui/app/src/components/settings/pages/TrackingSettings.tsx +++ b/gui/app/src/components/settings/pages/TrackingSettings.tsx @@ -377,7 +377,7 @@ export function TrackingSettings() { > @@ -39,186 +30,3 @@ fun centreOfMass( val boneCentre = (bone.headPosition + bone.tailPosition) / 2f return@fold acc + (boneCentre * massEntry.value) } - -fun computeComState(time: ComparableTimeMark, last: COMState?, com: Vector3): COMState = if (last != null) { - val deltaTime = (time - last.time).inFloatingSeconds - val comVelocity = (com - last.position) / deltaTime - val comAcceleration = (comVelocity - last.velocity) / deltaTime - COMState( - time, - com, - comVelocity, - comAcceleration, - ) -} else { - COMState( - time, - com, - Vector3.ZERO, - Vector3.ZERO, - ) -} - -// TODO Gravity can probably be defined somewhere more globally or smth? -const val GRAVITY_MAGNITUDE = 9.81f -val GRAVITY_VECTOR = Vector3(0f, -GRAVITY_MAGNITUDE, 0f) - -const val FLOOR_DISTANCE_CUTOFF = 0.065f -val PRESSURE_FALLBACK = 0.1f to 0.1f - -// TODO This feels wrong to be hardcoded, is there a reason we're doing this? -val FORCE_VECTOR_TO_PRESSURE: Vector3 = Vector3(0.25f, 1f, 0.25f) - -// In m/s^2 -val FORCE_ERROR_TOLERANCE_SQR: Float = 4f * 4f - -// Get the pressure prediction for the feet based of the centre of mass (assume mass is -// 1). This is assuming that the mass is 1 and the force of gravity is 9.8 m/s^2, this -// allows for the force sum to map directly to the acceleration of the centre of mass -// since F = ma, and if m is 1, then F = a. -fun predictFootPressure( - leftFootPosition: Vector3, - rightFootPosition: Vector3, - centerOfMass: Vector3, - centerOfMassAcceleration: Vector3, - floorLevel: Float, -): Pair { - // From the COM to each foot - val leftFootVector: Vector3 = (leftFootPosition - centerOfMass).unit() - val rightFootVector: Vector3 = (rightFootPosition - centerOfMass).unit() - - // Ratio of gravity on each foot to support the COM - val leftFootMagnitude: Float = GRAVITY_MAGNITUDE * leftFootVector.y - val rightFootMagnitude: Float = GRAVITY_MAGNITUDE * rightFootVector.y - - // Get the force vector each foot could apply to the COM - val leftFootForce: Vector3 = leftFootVector * (leftFootMagnitude / 2f) - val rightFootForce: Vector3 = rightFootVector * (rightFootMagnitude / 2f) - - // Based off the acceleration of the COM, get the force each foot is likely applying - // (the expected force sum should be equal to centerOfMassAcceleration since the - // mass is 1) - val (modifiedLeftFootForce, modifiedRightFootForce) = findForceVectors( - leftFootForce, - rightFootForce, - centerOfMassAcceleration, - ) - - // See if the force vectors found a reasonable solution, if they did not, we assume - // there is another force acting on the COM, and fall back to a low pressure - // prediction. - if (detectOutsideForces( - modifiedLeftFootForce, - modifiedRightFootForce, - Vector3.ZERO, - ) - ) { - // Assume user not standing - return PRESSURE_FALLBACK - } - // Assume user standing - - // Set the pressure to the force on each foot times the force to pressure scalar - var leftFootPressure = modifiedLeftFootForce.hadamard(FORCE_VECTOR_TO_PRESSURE).len() - var rightFootPressure = modifiedRightFootForce.hadamard(FORCE_VECTOR_TO_PRESSURE).len() - - // TODO So we calculate all this, but then if the foot is within the cutoff from the - // floor, it just goes to some abstractly enormous value?? Why? - // Distance from the ground is a factor in the pressure using the inverse of the - // distance to the ground scale the pressure - val leftDistance: Float = - if (leftFootPosition.y > (floorLevel + FLOOR_DISTANCE_CUTOFF)) { - leftFootPosition.y - (floorLevel + FLOOR_DISTANCE_CUTOFF) - } else { - // Nearly zero - 0.001f - } - leftFootPressure *= 1f / leftDistance - val rightDistance: Float = - if (rightFootPosition.y > (floorLevel + FLOOR_DISTANCE_CUTOFF)) { - rightFootPosition.y - (floorLevel + FLOOR_DISTANCE_CUTOFF) - } else { - // Nearly zero - 0.001f - } - rightFootPressure *= 1f / rightDistance - - // Normalize the pressure values - val pressureSum = leftFootPressure + rightFootPressure - leftFootPressure /= pressureSum - rightFootPressure /= pressureSum - return leftFootPressure to rightFootPressure -} - -// Perform a gradient descent to scale the force vectors to best match the acceleration -// of the COM -fun findForceVectors( - leftFootForceInit: Vector3, - rightFootForceInit: Vector3, - centerOfMassAcceleration: Vector3, -): Pair { - var leftFootForce: Vector3 = leftFootForceInit - var rightFootForce: Vector3 = rightFootForceInit - val iterations = 100 - val stepSize = 0.01f - // Set up the temporary variables - var tempLeftFootForce1: Vector3 - var tempLeftFootForce2: Vector3 - var tempRightFootForce1: Vector3 - var tempRightFootForce2: Vector3 - var error: Vector3 - var error1: Vector3 - var error2: Vector3 - var error3: Vector3 - var error4: Vector3 - for (i in 0 until iterations) { - tempLeftFootForce1 = leftFootForce - tempLeftFootForce2 = leftFootForce - tempRightFootForce1 = rightFootForce - tempRightFootForce2 = rightFootForce - - // Get the error at the current position - error = getForceVectorError(leftFootForce, rightFootForce, centerOfMassAcceleration) - - // Add and subtract the error to the force vectors - tempLeftFootForce1 *= (1.0f + stepSize) - tempLeftFootForce2 *= (1.0f - stepSize) - tempRightFootForce1 *= (1.0f + stepSize) - tempRightFootForce2 *= (1.0f - stepSize) - - // Get the error at the new position - error1 = getForceVectorError(tempLeftFootForce1, rightFootForce, centerOfMassAcceleration) - error2 = getForceVectorError(tempLeftFootForce2, rightFootForce, centerOfMassAcceleration) - error3 = getForceVectorError(tempRightFootForce1, leftFootForce, centerOfMassAcceleration) - error4 = getForceVectorError(tempRightFootForce2, leftFootForce, centerOfMassAcceleration) - - // Set the new force vectors - if (error1.len() < error.len()) { - leftFootForce = tempLeftFootForce1 - } else if (error2.len() < error.len()) { - leftFootForce = tempLeftFootForce2 - } - if (error3.len() < error.len()) { - rightFootForce = tempRightFootForce1 - } else if (error4.len() < error.len()) { - rightFootForce = tempRightFootForce2 - } - } - - return leftFootForce to rightFootForce -} - -// Detect any outside forces on the body such as a wall or a chair. -// Returns true if there is an outside force. -fun detectOutsideForces( - f1: Vector3, - f2: Vector3, - centerOfMassAcceleration: Vector3, -): Boolean = getForceVectorError(f1, f2, centerOfMassAcceleration).lenSq() > FORCE_ERROR_TOLERANCE_SQR - -// Simple error function for the force vector gradient descent -fun getForceVectorError( - f1: Vector3, - f2: Vector3, - centerOfMassAcceleration: Vector3, -): Vector3 = centerOfMassAcceleration - (GRAVITY_VECTOR + f1 + f2) diff --git a/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/toe-snap.kt b/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/toe-snap.kt index 0b26fdebd..515791c3e 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/toe-snap.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/toe-snap.kt @@ -36,7 +36,7 @@ fun computeToeSnapRatio( // Lessen the ratio as the ankle doesn't point down val ankleDownDirection = abs(ankleLocalPosition.unit().y.coerceAtMost(0f)) - val ankleDownRatio = FastMath.clampedRemap(ankleDownDirection, ANKLE_DOWN_MIN, ANKLE_DOWN_MAX, 0f, 1f) + val ankleDownRatio = FastMath.remapClamped(ankleDownDirection, ANKLE_DOWN_MIN, ANKLE_DOWN_MAX, 0f, 1f) return rangeToFloorRatio * ankleDownRatio } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/targetprocessors/skating-correction.kt b/server/core/src/main/java/dev/slimevr/skeleton/targetprocessors/skating-correction.kt index c1b1d685c..17fd3c177 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/targetprocessors/skating-correction.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/targetprocessors/skating-correction.kt @@ -3,7 +3,6 @@ package dev.slimevr.skeleton.targetprocessors import com.jme3.math.FastMath import dev.slimevr.config.Settings import dev.slimevr.skeleton.BodyPartMap -import dev.slimevr.skeleton.COMState import dev.slimevr.skeleton.ComputedSkeleton import dev.slimevr.skeleton.IKTargets import dev.slimevr.skeleton.InputSkeleton @@ -12,66 +11,47 @@ import dev.slimevr.skeleton.Skeleton import dev.slimevr.skeleton.SkeletonTargetProcessor import dev.slimevr.skeleton.bodyPartMap import dev.slimevr.skeleton.centreOfMass -import dev.slimevr.skeleton.computeComState -import dev.slimevr.skeleton.predictFootPressure import dev.slimevr.util.inFloatingSeconds import dev.slimevr.util.timeSource import io.github.axisangles.ktmath.Vector3 import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.rpc.ResetType -import kotlin.math.abs +import kotlin.collections.set import kotlin.time.ComparableTimeMark -// Minimum strengths for the lock thresholds -const val SCAlAR_STRENGTH_MIN = 0.4f +// Max correction offset length, drags position closer +const val OFFSET_LIMIT_MIN = 0.12f +const val OFFSET_LIMIT_MAX = 0.2f +// Parameters to decide if a foot should be locked // Higher makes it harder to unlock after being locked -const val LOCKED_UNLOCK_MULTIPLIER = 1.15f - -// Max correction offset length -const val OFFSET_LIMIT = 0.12f - -// Main parameters to decide if a foot is locked or not +const val LOCKED_UNLOCK_MULTIPLIER = 1.12f const val FLOOR_DISTANCE_THRESHOLD = 0.065f -const val SKATING_ANGULAR_VELOCITY_THRESHOLD = 6f -const val SKATING_ACCELERATION_THRESHOLD = 1.3f +const val COM_DISTANCE_THRESHOLD = 0.3f +const val ACCELERATION_THRESHOLD_MIN = 0.4f +const val ACCELERATION_THRESHOLD_MAX = 1.3f -// The point at which the scalar is at the max or min depending on accel -const val MAX_SCALAR_ACCEL = 0.2f -const val MIN_SCALAR_ACCEL = 0.9f +// Need to be locked for this long to actually be locked +const val LOCK_WARMUP_MIN = 0.250f +const val LOCK_WARMUP_MAX = 0.150f -// The point at which the scalar is at it max or min in a double locked foot situation -const val MAX_SCALAR_DORMANT = 0.2f -const val MIN_SCALAR_DORMANT = 1.50f - -// The point at which the scalar is at its max or min in a single locked foot situation -const val MAX_SCALAR_ACTIVE = 0.1f -const val MIN_SCALAR_ACTIVE = 1.75f - -// The resulting values from scalar -const val PARAM_SCALAR_MAX = 3.2f -const val PARAM_SCALAR_MID = 1.0f -const val PARAM_SCALAR_MIN = 0.25f - -// Maximum scalars for the pressure on each foot -const val PRESSURE_SCALAR_MIN = 0.1f -const val PRESSURE_SCALAR_MAX = 1.9f - -// The distance correction scales with the linear velocity -const val VELOCITY_MIN = 0.01f -const val VELOCITY_MAX = 0.06f -const val VELOCITY_CORRECTION_MIN = 0.5f -const val VELOCITY_CORRECTION_MAX = 0.7f +// Smoothing +// The distance correction scales with the linear velocity and distance from locked position +const val DISTANCE_MIN = 0.01f +const val DISTANCE_MAX = 0.1f +const val DISTANCE_CORRECTION_MIN = 0.45f +const val DISTANCE_CORRECTION_MAX = 1f // The correction speed accelerates with time -const val DURATION_CORRECTION_SPEED = 0.4f -const val DURATION_CORRECTION_WARMUP = 1.75f +const val DURATION_CORRECTION_SPEED = 2f +const val DURATION_CORRECTION_WARMUP = 0.7f // To not keep smoothing forever, making it so we'd run IK for nothing. const val CORRECTION_EPSILON = 0.001f data class LockState( val locked: Boolean, + val shouldLockTime: ComparableTimeMark? = null, val position: Vector3? = null, ) @@ -80,125 +60,72 @@ data class ReleaseSmoothing( val offset: Vector3, ) -/** - * Returns if a foot is considered as planted and should be locked using: - * - vertical translation from floor - * - angular velocity magnitude - * - acceleration magnitude - */ -fun shouldLock( - position: Vector3, - acceleration: Vector3, - angularVelocity: Vector3?, - floorLevel: Float = 0f, +fun comLocked( wasLocked: Boolean, - thresholdStrength: Float = 1f, - velocitySensitivity: Float = 1f, - accelerationSensitivity: Float = 1f, -): Boolean { - val baseMultiplier = (if (wasLocked) LOCKED_UNLOCK_MULTIPLIER else 1f) + position: Vector3, + centreOfMass: Vector3, +) = (position - centreOfMass).let { Vector3(it.x, 0f, it.z) }.len() <= COM_DISTANCE_THRESHOLD * (if (wasLocked) LOCKED_UNLOCK_MULTIPLIER else 1f) - // Vertical position - val lockedToFloor = position.y - floorLevel <= FLOOR_DISTANCE_THRESHOLD * baseMultiplier +fun floorLocked( + wasLocked: Boolean, + position: Vector3, + floorLevel: Float, +) = position.y - floorLevel <= FLOOR_DISTANCE_THRESHOLD * (if (wasLocked) LOCKED_UNLOCK_MULTIPLIER else 1f) - // Angular velocity + acceleration - val thresholdMultiplier = baseMultiplier * thresholdStrength - val lockedAngular = angularVelocity == null || angularVelocity.len() <= SKATING_ANGULAR_VELOCITY_THRESHOLD * thresholdMultiplier * velocitySensitivity - val lockedAccel = acceleration.len() <= SKATING_ACCELERATION_THRESHOLD * thresholdMultiplier * accelerationSensitivity - - return lockedToFloor && lockedAngular && lockedAccel -} +fun accelLocked( + wasLocked: Boolean, + acceleration: Vector3, + accelerationThreshold: Float, +) = acceleration.len() <= accelerationThreshold * (if (wasLocked) LOCKED_UNLOCK_MULTIPLIER else 1f) fun computeLockState( - wasLocked: Boolean, - isLocked: Boolean, + lastState: LockState, + now: ComparableTimeMark, + lockWarmup: Float, + shouldLock: Boolean, position: Vector3, -): LockState? = if (isLocked && !wasLocked) { - LockState( - true, - position, - ) -} else if (!isLocked && wasLocked) { - // Last locked position could be retained if needed, but I can't think of a use - LockState( - false, - ) -} else { - null -} + offsetLimit: Float, +): LockState { + val adjustedLastState = if (lastState.position != null) { + // Keep locked position within a limit + val unlockedVerticalPosition = Vector3(lastState.position.x, position.y, lastState.position.z) + val positionDelta = position - unlockedVerticalPosition + val limitRatio = (1 - (offsetLimit / positionDelta.len())).coerceAtLeast(0f) + lastState.copy(position = unlockedVerticalPosition.lerp(position, limitRatio)) + } else { + lastState + } -fun computeSensitivity( - isLocked: Boolean, - altIsLocked: Boolean, - accelerationMagnitude: Float, - velocity: Vector3, - altVelocity: Vector3, - pressure: Float, -): Pair { - // Get the first set of scalars that are based on acceleration from the IMUs - val footScalarAccel: Float = getFootScalarAccel( - isLocked, - accelerationMagnitude, - ) - - // Get the second set of scalars that is based off of how close each foot is to a - // lock and dynamically adjusting the scalars (based off the assumption that if you - // are standing one foot is likely planted on the ground unless you are moving - // fast) - val footScalarVel: Float = getFootLockLikelihood( - velocity, - altVelocity, - isLocked && altIsLocked, - ) - - // Combine the scalars to get the final scalars - val footSensitivityVel = ( - ((footScalarAccel + footScalarVel) / 2f) * - (pressure * 2f).coerceIn( - PRESSURE_SCALAR_MIN, - PRESSURE_SCALAR_MAX, - ) - ) - - // Velocity sensitivity to acceleration sensitivity - return footSensitivityVel to footScalarVel -} - -// Calculate a scalar using acceleration to apply to the non acceleration based -// hyperparameters when calculating lock states -fun getFootScalarAccel(isLocked: Boolean, accelerationMagnitude: Float): Float = if (isLocked) { - FastMath.clampedRemap(accelerationMagnitude, MAX_SCALAR_ACCEL, MIN_SCALAR_ACCEL, PARAM_SCALAR_MAX, PARAM_SCALAR_MIN) -} else { - PARAM_SCALAR_MID -} - -// Calculate a scalar using the velocity of the foot trackers and the lock states to -// calculate a scalar to apply to the non acceleration based hyperparameters when -// calculating lock states -fun getFootLockLikelihood(primaryFootVel: Vector3, otherFootVel: Vector3, bothLocked: Boolean): Float = if (bothLocked) { - val velocityDiff = (primaryFootVel - otherFootVel).let { Vector3(it.x, 0f, it.z) }.len() - FastMath.clampedRemap(velocityDiff, MAX_SCALAR_DORMANT, MIN_SCALAR_DORMANT, PARAM_SCALAR_MAX, PARAM_SCALAR_MIN) -} else { - val velocityDiffAbs = abs(primaryFootVel.len() - otherFootVel.len()) - FastMath.clampedRemap(velocityDiffAbs, MAX_SCALAR_ACTIVE, MIN_SCALAR_ACTIVE, PARAM_SCALAR_MAX, PARAM_SCALAR_MIN) + if (shouldLock) { + if (adjustedLastState.locked) return adjustedLastState + if (adjustedLastState.shouldLockTime == null) return LockState(shouldLockTime = now, locked = false) + return if ((now - adjustedLastState.shouldLockTime).inFloatingSeconds > lockWarmup) { + LockState(true, position = position) + } else { + adjustedLastState + } + } else if (adjustedLastState.locked) { + return LockState(locked = false) + } else { + return adjustedLastState + } } fun computeReleaseSmoothing(offset: Vector3, horizontalVelocity: Float, secondsUnlocked: Float, deltaTime: Float): Vector3 { val length = offset.len() if (length <= CORRECTION_EPSILON) return Vector3.ZERO - val velocityCorrection = horizontalVelocity * FastMath.clampedRemap(length, VELOCITY_MIN, VELOCITY_MAX, VELOCITY_CORRECTION_MIN, VELOCITY_CORRECTION_MAX) - val durationCorrection = DURATION_CORRECTION_SPEED * (secondsUnlocked / DURATION_CORRECTION_WARMUP).coerceAtMost(1f) + val distanceMultiplier = FastMath.remapClamped(length, DISTANCE_MIN, DISTANCE_MAX, DISTANCE_CORRECTION_MIN, DISTANCE_CORRECTION_MAX) + val velocityCorrection = horizontalVelocity * distanceMultiplier + val durationCorrection = DURATION_CORRECTION_SPEED * (secondsUnlocked / DURATION_CORRECTION_WARMUP).coerceAtMost(1f) * distanceMultiplier val totalCorrection = (velocityCorrection + durationCorrection) * deltaTime val remaining = (length - totalCorrection).coerceAtLeast(0f) return offset * (remaining / length) } -data class SkatingBodyParts( +private data class SkatingBodyParts( // ex. Left foot val bodyPart: BodyPart, - // Mirror of bodyPart (ex. right foot) - val mirrorBodyPart: BodyPart, // ex. Left lower leg (ankle) val ikTargetBodyPart: BodyPart, ) @@ -206,109 +133,70 @@ data class SkatingBodyParts( class SkatingCorrectionTargetProcessor(val settings: Settings, val skeleton: Skeleton) : SkeletonTargetProcessor, ResettableSkeletonProcessor { - val skatingBodyParts = arrayOf( + private val skatingBodyParts = arrayOf( SkatingBodyParts( BodyPart.LEFT_FOOT, - BodyPart.RIGHT_FOOT, BodyPart.LEFT_LOWER_LEG, ), SkatingBodyParts( BodyPart.RIGHT_FOOT, - BodyPart.LEFT_FOOT, BodyPart.RIGHT_LOWER_LEG, ), ) var lastProcessTime = timeSource.markNow() - var lastComState: COMState? = null - val pressure: BodyPartMap = bodyPartMap() val lockState: BodyPartMap = bodyPartMap() val releaseSmoothing: BodyPartMap = bodyPartMap() override fun process(mutableIkTargets: IKTargets, inputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float) { val skeletonConfig = settings.context.state.value.data.skeletonConfig if (!skeleton.effectiveSkatingCorrection) return - val scalarStrength = FastMath.remap(skeletonConfig.ratios.skatingCorrectionStrength, 0f, 1f, SCAlAR_STRENGTH_MIN, 1f) + val offsetLimit = FastMath.remapClamped(skeletonConfig.ratios.skatingCorrectionStrength, 0f, 1f, OFFSET_LIMIT_MIN, OFFSET_LIMIT_MAX) + val accelerationThreshold = FastMath.remapClamped(skeletonConfig.ratios.skatingCorrectionStrength, 0f, 1f, ACCELERATION_THRESHOLD_MIN, ACCELERATION_THRESHOLD_MAX) + val lockWarmup = FastMath.remapClamped(skeletonConfig.ratios.skatingCorrectionStrength, 0f, 1f, LOCK_WARMUP_MIN, LOCK_WARMUP_MAX) val now = timeSource.markNow() val deltaTime = (now - lastProcessTime).inFloatingSeconds.coerceIn(0f, 1f) lastProcessTime = now - // Update centre of mass - val comState = computeComState(now, lastComState, centreOfMass(fk)) - lastComState = comState - - // Predict the pressure for each foot - predictFootPressure( - fk[BodyPart.LEFT_FOOT]?.headPosition ?: return, - fk[BodyPart.RIGHT_FOOT]?.headPosition ?: return, - comState.position, - comState.acceleration, - floorLevel, - ).let { - pressure[BodyPart.LEFT_FOOT] = it.first - pressure[BodyPart.RIGHT_FOOT] = it.second + // Centre of mass + val com = centreOfMass(fk) + // If no body part is locked due to com, then we can't rely on it. + var noComLocked = true + val comLock: BodyPartMap = bodyPartMap() + for ((bodyPart, ikTargetBodyPart) in skatingBodyParts) { + val isComLocked = comLocked( + lockState[bodyPart]?.locked == true, + mutableIkTargets[ikTargetBodyPart] ?: fk[ikTargetBodyPart]?.tailPosition ?: continue, + com, + ) + comLock[bodyPart] = isComLocked + if (isComLocked) noComLocked = false } - for ((bodyPart, mirrorBodyPart, ikTargetBodyPart) in skatingBodyParts) { - val input = inputSkeleton[bodyPart] ?: continue + for ((bodyPart, ikTargetBodyPart) in skatingBodyParts) { val bone = fk[bodyPart] ?: continue - val mirrorBone = fk[mirrorBodyPart] ?: continue val ikBone = fk[ikTargetBodyPart] ?: continue val curPosition = mutableIkTargets[ikTargetBodyPart] ?: ikBone.tailPosition - val lastState = lockState[bodyPart] - val wasLocked = lastState?.locked == true - val mirrorLocked = lockState[mirrorBodyPart]?.locked == true + val lastState = lockState[bodyPart] ?: LockState(locked = false) - val (velocitySensitivity, accelerationSensitivity) = computeSensitivity( - wasLocked, - mirrorLocked, - bone.acceleration.len(), - bone.velocity.linear, - mirrorBone.velocity.linear, - pressure[bodyPart] ?: 0.5f, - ) - - // Consider locking BodyPart - val isLocked = shouldLock( - curPosition, - bone.acceleration, - if (input.isRotationActive) { - bone.velocity.angular - } else { - null - }, - floorLevel, - wasLocked, - scalarStrength, - velocitySensitivity, - accelerationSensitivity, - ) + // Compute if the body part should be locked + val shouldLock = (noComLocked || comLock[bodyPart] == true) && + floorLocked(lastState.locked, curPosition, floorLevel) && + accelLocked(lastState.locked, bone.acceleration, accelerationThreshold) // Update lock state val activeState = computeLockState( - wasLocked, - isLocked, + lastState, + now, + lockWarmup, + shouldLock, curPosition, - )?.also { - // Track lock state changes - lockState[bodyPart] = it - // Otherwise pull the last state - } ?: lastState?.let { - if (it.position != null) { - // Keep locked position within a limit - val unlockedVerticalPosition = Vector3(it.position.x, curPosition.y, it.position.z) - val positionDelta = curPosition - unlockedVerticalPosition - val limitRatio = (1 - (OFFSET_LIMIT / positionDelta.len())).coerceAtLeast(0f) - LockState(it.locked, unlockedVerticalPosition.lerp(curPosition, limitRatio)).also { newState -> - lockState[bodyPart] = newState - } - } else { - it - } - } ?: continue + offsetLimit, + ) + lockState[bodyPart] = activeState - // Continue smoothing + // Continue smoothing if we were val smoothingOffset = releaseSmoothing[bodyPart]?.let { lastSmoothing -> // Get new smoothing val newSmoothing = computeReleaseSmoothing( @@ -328,8 +216,8 @@ class SkatingCorrectionTargetProcessor(val settings: Settings, val skeleton: Ske null } } - // Start smoothing - val activeSmoothingOffset = if (!isLocked && wasLocked && lastState.position != null) { + // Start smoothing fresh if we just unlocked + val activeSmoothingOffset = if (!activeState.locked && lastState.locked && lastState.position != null) { // If unlocking, start smoothing from the locked position (plus last // smoothing offset if present) to the current position val lastLockPosition = smoothingOffset?.let { offset -> @@ -345,6 +233,7 @@ class SkatingCorrectionTargetProcessor(val settings: Settings, val skeleton: Ske ) } } else { + // Just use smoothing we already computed above smoothingOffset } @@ -364,8 +253,6 @@ class SkatingCorrectionTargetProcessor(val settings: Settings, val skeleton: Ske override fun reset(resetType: ResetType) { if (resetType == ResetType.FULL) { lastProcessTime = timeSource.markNow() - lastComState = null - pressure.clear() lockState.clear() releaseSmoothing.clear() }