Unify prediction, smoothing, and upsampling

This commit is contained in:
Erimel committed 2026-10-28 18:30:25 -04:00
1 parent aa29c48983
commit 9b4274847b
12 files changed
+113 -280

No files matched your search

@@ -13,7 +13,6 @@ import kotlinx.serialization.json.jsonPrimitive
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.datatypes.MountingMethod
import solarxr_protocol.rpc.ArmsMountingResetMode
import solarxr_protocol.rpc.FilteringType
import solarxr_protocol.rpc.KeybindId
import solarxr_protocol.rpc.RoutingOutput
@@ -117,24 +116,18 @@ data class SkeletonTogglesConfig(
// Used in SkeletonConfig
@Serializable
data class SkeletonRatiosConfig(
val smoothingStrength: Float = 0.1f,
val predictionStrength: Float = 0.2f,
val spineCurvature: Float = 0.75f,
val imputeSpineFromUpperToLower: Float = DEFAULT_SPINE_UPPER_LOWER,
val interpolateUpperLegsTwistWithLowerLegs: Float = 0.85f,
val skatingCorrectionStrength: Float = 0.5f,
)
// Used in SkeletonConfig
@Serializable
data class SkeletonFilteringConfig(
val type: FilteringType = FilteringType.NONE,
val amount: Float = 0.25f,
)
@Serializable
data class SkeletonConfig(
val toggles: SkeletonTogglesConfig = SkeletonTogglesConfig(),
val ratios: SkeletonRatiosConfig = SkeletonRatiosConfig(),
val filtering: SkeletonFilteringConfig = SkeletonFilteringConfig(),
)
const val DEFAULT_VRC_OSC_PORT_OUT: Int = 9000
@@ -44,8 +44,7 @@ private fun smoothVelocity(currentVelocity: Velocity, lastVelocity: Velocity, de
class VelocityComputedProcessor :
SkeletonComputedProcessor,
ResettableSkeletonProcessor {
private val lastVelocities: BodyPartMap<Velocity> = bodyPartMap()
private val lastVelocityData: BodyPartMap<VelocityData> = bodyPartMap()
private val lastVelocities: BodyPartMap<Pair<Velocity, VelocityData>> = bodyPartMap()
private var lastProcessTime = timeSource.markNow()
override fun process(mutableComputedSkeleton: ComputedSkeleton, inputSkeleton: InputSkeleton) {
@@ -57,18 +56,17 @@ class VelocityComputedProcessor :
for ((bodyPart, bone) in mutableComputedSkeleton) {
// Compute current velocity
val currentVelocityData = VelocityData(bone.rotation, bone.tailPosition)
val currentVelocity = lastVelocityData[bodyPart]?.let { computeVelocity(currentVelocityData, it, deltaTime) } ?: ZERO_VELOCITY
val currentVelocity = lastVelocities[bodyPart]?.second?.let { computeVelocity(currentVelocityData, it, deltaTime) } ?: ZERO_VELOCITY
val smoothedVelocity = smoothVelocity(currentVelocity, lastVelocities[bodyPart] ?: ZERO_VELOCITY, deltaTime)
val smoothedVelocity = smoothVelocity(currentVelocity, lastVelocities[bodyPart]?.first ?: ZERO_VELOCITY, deltaTime)
mutableComputedSkeleton[bodyPart] = bone.copy(velocity = smoothedVelocity)
lastVelocityData[bodyPart] = currentVelocityData
lastVelocities[bodyPart] = smoothedVelocity
lastVelocities[bodyPart] = smoothedVelocity to currentVelocityData
}
}
override fun reset(resetType: ResetType) {
lastVelocities.clear()
lastVelocityData.clear()
lastProcessTime = timeSource.markNow()
}
}
@@ -1,5 +1,7 @@
package dev.slimevr.skeleton.inputprocessors
import com.jme3.math.FastMath
import dev.slimevr.config.Settings
import dev.slimevr.skeleton.BodyPartMap
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.ResettableSkeletonProcessor
@@ -25,17 +27,40 @@ private data class BoneSamples(
val runningSample: BoneSample?,
val targetSample: BoneSample?,
val timeBetweenPoses: Duration?,
val predictionRotation: Quaternion?,
val timeLeftForLastPose: Duration = Duration.ZERO,
)
// TODO fine tune these values
// Smoothing
private const val TIME_CARRYOVER_DECAY = 0.9 // Carries over 90% of the last pose's remaining time
private const val TIME_CARRYOVER_DECAY_MIN = 0.8f
private const val TIME_CARRYOVER_DECAY_MAX = 0.1f
// Smaller = more smoother
private const val ROTATION_SMOOTHING_MIN = 0.3f
private const val ROTATION_SMOOTHING_MAX = 0.04f
// Prediction
private const val EXTRAPOLATION_LOG_BASE = 5.0 // Higher = less extrapolation
private const val EXTRAPOLATION_MAX = 1.0 // Allows 5 seconds
private const val EXTRAPOLATION_MAX_SECONDS = 4.5
// Higher = less extrapolation
private const val EXTRAPOLATION_LOG_BASE_MIN = 8.0f
private const val EXTRAPOLATION_LOG_BASE_MAX = 4.0f
// Higher = more prediction
private const val ROTATION_PREDICTION_MIN = 0f
private const val ROTATION_PREDICTION_MAX = 0.95f
// Lower = more biased towards recent rotations
private const val PREVIOUS_PREDICTION_DECAY = 0.2f
// TODO this could use 'some' (A LOT OF) refactoring
// pls don't judge the code quality, I was just trying to make it work for now!
/**
* This processor handles upsampling, smoothing and prediction, all in one processor for optimization's sake.
*
* ----- Upsampling -----
* Since the skeleton runs at a different rate than trackers (e.g: 500hz vs 100hz),
* this processor handles interpolating data received from trackers across skeleton frames up
* until the next tracker data (e.g: interpolating the 100hz data across 5 frames to reach 500hz).
@@ -48,14 +73,28 @@ private const val EXTRAPOLATION_MAX = 1.0 // Allows 5 seconds
*
* With this, processors don't have to care that trackers only send at 100hz and can know that the data from one skeleton
* frame to another will have reliably changed according to the IRL movements.
*
* ----- Smoothing -----
* Smoothing decides how fast to get to the target rotation by just scaling down the interpolation ratio.
*
* ----- Prediction -----
* Prediction decides how far away the target rotation is using an average of past rotation deltas.
*/
class UpsamplingInputProcessor :
class FilteringInputProcessor(val settings: Settings) :
SkeletonInputProcessor,
ResettableSkeletonProcessor {
private val boneSamples: BodyPartMap<BoneSamples> = bodyPartMap()
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
val now = timeSource.markNow()
val skeletonRatios = settings.context.state.value.data.skeletonConfig.ratios
val smoothingStrength = skeletonRatios.smoothingStrength
val predictionStrength = skeletonRatios.predictionStrength
val timeCarryoverDecay = FastMath.remapClamped(smoothingStrength, 0f, 1f, TIME_CARRYOVER_DECAY_MIN, TIME_CARRYOVER_DECAY_MAX).toDouble()
val rotationSmoothingMultiplier = FastMath.remapClamped(smoothingStrength, 0f, 1f, ROTATION_SMOOTHING_MIN, ROTATION_SMOOTHING_MAX)
val extrapolationLogBase = FastMath.remapClamped(predictionStrength, 0f, 1f, EXTRAPOLATION_LOG_BASE_MIN, EXTRAPOLATION_LOG_BASE_MAX).toDouble()
val rotationPredictionMultiplier = FastMath.remapClamped(predictionStrength, 0f, 1f, ROTATION_PREDICTION_MIN, ROTATION_PREDICTION_MAX)
for ((bodyPart, bone) in mutableInputSkeleton) {
if (bone.expectedTps == null || bone.poseTime == null) continue
@@ -71,13 +110,22 @@ class UpsamplingInputProcessor :
val timeBetweenLastPoses = bone.poseTime - targetPoseTime
oldSamples.runningSample?.poseTime?.let { runningPoseTime ->
// Add some of last pose's remaining time
val lastPoseCarryoverTime = oldSamples.timeLeftForLastPose * TIME_CARRYOVER_DECAY
val lastPoseCarryoverTime = oldSamples.timeLeftForLastPose * timeCarryoverDecay
val timeSinceRunningPose = now - runningPoseTime
(timeBetweenLastPoses + lastPoseCarryoverTime - timeSinceRunningPose).coerceAtLeast(Duration.ZERO)
} ?: timeBetweenLastPoses
}
val predictionRotation = oldSamples?.targetSample?.rotation?.let { previousRotation ->
if (predictionStrength > 0f) {
val previousPrediction = oldSamples.predictionRotation?.pow(PREVIOUS_PREDICTION_DECAY) ?: Quaternion.IDENTITY
val currentDelta = (previousRotation.inv() * targetSample.rotation).pow(rotationPredictionMultiplier)
previousPrediction * currentDelta
} else {
null
}
}
BoneSamples(fromSample, null, targetSample, timeBetweenPoses)
BoneSamples(fromSample, null, targetSample, timeBetweenPoses, predictionRotation)
} else {
oldSamples
}
@@ -89,16 +137,23 @@ class UpsamplingInputProcessor :
// Time between now and tracker data.
val timeSinceLastPose = now - bone.poseTime
// Ratio of how close we should be to the next pose.
// 0 = we just got started, 1 = we should have the next one, >1 = we didn't get it yet, packet loss?
// 0 = we just got started, 1 = we should have the next one, >1 = we didn't get it yet; packet lost or late
val rawRatio = timeSinceLastPose / timeBetweenPoses
// In case the rawRatio is >1, we extrapolate using log to keep some smooth perceived movement.
val extrapolationAmount = log((rawRatio).coerceAtLeast(1.0), EXTRAPOLATION_LOG_BASE).coerceAtMost(EXTRAPOLATION_MAX)
val extrapolationAmount = log((rawRatio).coerceIn(1.0, EXTRAPOLATION_MAX_SECONDS), extrapolationLogBase)
// Resulting ratio to use for interpolation, with extrapolation if any.
val interpolationRatio = (rawRatio.coerceAtMost(1.0) + extrapolationAmount).toFloat()
// Upsample rotation, acceleration and position.
val rotation = if (bone.isRotationActive) {
fromSample.rotation.interpQ(targetSample.rotation, interpolationRatio)
val rotationInterpolationRatio = if (smoothingStrength > 0f) {
val extrapolationAmount = log((rawRatio * rotationSmoothingMultiplier).coerceIn(1.0, EXTRAPOLATION_MAX_SECONDS), extrapolationLogBase)
((rawRatio * rotationSmoothingMultiplier).coerceAtMost(1.0) + extrapolationAmount).toFloat()
} else {
interpolationRatio
}
val targetRotation = samples.predictionRotation?.let { targetSample.rotation * it } ?: targetSample.rotation
fromSample.rotation.interpQ(targetRotation, rotationInterpolationRatio)
} else {
targetSample.rotation
}
@@ -1,79 +0,0 @@
package dev.slimevr.skeleton.inputprocessors
import dev.slimevr.config.Settings
import dev.slimevr.skeleton.BodyPartMap
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.ResettableSkeletonProcessor
import dev.slimevr.skeleton.SkeletonInputProcessor
import dev.slimevr.skeleton.bodyPartMap
import dev.slimevr.util.timeSource
import io.github.axisangles.ktmath.Quaternion
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.rpc.FilteringType
import solarxr_protocol.rpc.ResetType
import kotlin.time.ComparableTimeMark
import kotlin.time.Duration.Companion.milliseconds
/** How far ahead the prediction reaches at amount 1, scaled down by the configured amount */
val PREDICTION_LEAD = 12.milliseconds
/**
* Tries to predict future rotations of bones.
*/
class RotationPredictionInputProcessor(val settings: Settings) :
SkeletonInputProcessor,
ResettableSkeletonProcessor {
private data class BoneDelta(
val lastRotation: Quaternion,
val rotationDelta: Quaternion,
val lastChange: ComparableTimeMark,
)
// Used to minimize latency even more for arm tracking where it is more noticeable in VR.
private val PART_MULTIPLIER = BodyPartMap(
mapOf(
BodyPart.LEFT_SHOULDER to 1.4f,
BodyPart.RIGHT_SHOULDER to 1.4f,
BodyPart.LEFT_UPPER_ARM to 1.4f,
BodyPart.RIGHT_UPPER_ARM to 1.4f,
BodyPart.LEFT_LOWER_ARM to 1.4f,
BodyPart.RIGHT_LOWER_ARM to 1.4f,
),
)
private val deltas: BodyPartMap<BoneDelta> = bodyPartMap()
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
val config = settings.context.state.value.data.skeletonConfig.filtering
val filteringAmount = config.amount
if (config.type != FilteringType.PREDICTION || filteringAmount <= 0f) {
// Drop stale velocities so re-enabling doesn't diff against a long outdated pose
if (deltas.isNotEmpty()) deltas.clear()
return
}
val now = timeSource.markNow()
for ((bodyPart, bone) in mutableInputSkeleton) {
if (!bone.isRotationActive) continue
val prev = deltas[bodyPart]
if (prev == null) {
deltas[bodyPart] = BoneDelta(bone.rotation, Quaternion.IDENTITY, now)
continue
}
val leadScale = (PREDICTION_LEAD / (now - prev.lastChange)).toFloat()
val rotationDelta = (bone.rotation / prev.lastRotation).pow(leadScale)
deltas[bodyPart] = BoneDelta(bone.rotation, rotationDelta, now)
val bonePredictionAmount = filteringAmount * (PART_MULTIPLIER[bodyPart] ?: 1f)
val scaledDelta = rotationDelta.pow(bonePredictionAmount)
val predicted = scaledDelta * bone.rotation
if (predicted != bone.rotation) mutableInputSkeleton[bodyPart] = bone.copy(rotation = predicted)
}
}
override fun reset(resetType: ResetType) {
deltas.clear()
}
}
@@ -1,59 +0,0 @@
package dev.slimevr.skeleton.inputprocessors
import dev.slimevr.config.Settings
import dev.slimevr.skeleton.BodyPartMap
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.ResettableSkeletonProcessor
import dev.slimevr.skeleton.SkeletonInputProcessor
import dev.slimevr.skeleton.bodyPartMap
import dev.slimevr.util.inFloatingSeconds
import dev.slimevr.util.timeSource
import io.github.axisangles.ktmath.Quaternion
import solarxr_protocol.rpc.FilteringType
import solarxr_protocol.rpc.ResetType
private const val SMOOTHING_MULTIPLIER = 100f
private const val SMOOTH_MIN = 0.46f
private const val SMOOTH_MAX = 0.92f
/**
* Running average of bone rotations to smooth them out.
*/
class RotationSmoothingInputProcessor(val settings: Settings) :
SkeletonInputProcessor,
ResettableSkeletonProcessor {
private val smoothed: BodyPartMap<Quaternion> = bodyPartMap()
private var lastProcessTime = timeSource.markNow()
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
val config = settings.context.state.value.data.skeletonConfig.filtering
val filteringAmount = config.amount
if (config.type != FilteringType.SMOOTHING || filteringAmount <= 0f) {
// Drop stale poses so re-enabling doesn't blend out of an outdated frame
if (smoothed.isNotEmpty()) smoothed.clear()
lastProcessTime = timeSource.markNow()
return
}
// Normalize with frame time
val lastFrameTimeSeconds = lastProcessTime.elapsedNow().inFloatingSeconds
lastProcessTime = timeSource.markNow()
val smoothingAmount = SMOOTH_MIN + filteringAmount * (SMOOTH_MAX - SMOOTH_MIN)
val alpha = ((1 - smoothingAmount) * lastFrameTimeSeconds * SMOOTHING_MULTIPLIER).coerceIn(0f, 1f)
for ((bodyPart, bone) in mutableInputSkeleton) {
if (!bone.isRotationActive) continue
val prev = smoothed[bodyPart] ?: bone.rotation
val rotation = prev.lerpQ(bone.rotation, alpha).unit()
smoothed[bodyPart] = rotation
if (rotation != bone.rotation) mutableInputSkeleton[bodyPart] = bone.copy(rotation = rotation)
}
}
override fun reset(resetType: ResetType) {
lastProcessTime = timeSource.markNow()
smoothed.clear()
}
}
@@ -12,15 +12,13 @@ import dev.slimevr.skeleton.inputprocessors.BoneOffsetInputProcessor
import dev.slimevr.skeleton.inputprocessors.ConstraintInputProcessor
import dev.slimevr.skeleton.inputprocessors.DirectLinkInputProcessor
import dev.slimevr.skeleton.inputprocessors.FallbackInputProcessor
import dev.slimevr.skeleton.inputprocessors.FilteringInputProcessor
import dev.slimevr.skeleton.inputprocessors.FingersInputProcessor
import dev.slimevr.skeleton.inputprocessors.HeadPositionFallbackInputProcessor
import dev.slimevr.skeleton.inputprocessors.NeckInputProcessor
import dev.slimevr.skeleton.inputprocessors.RotationPredictionInputProcessor
import dev.slimevr.skeleton.inputprocessors.RotationSmoothingInputProcessor
import dev.slimevr.skeleton.inputprocessors.SpineInputProcessor
import dev.slimevr.skeleton.inputprocessors.ToesInputProcessor
import dev.slimevr.skeleton.inputprocessors.UpperLegsRollAlignInputProcessor
import dev.slimevr.skeleton.inputprocessors.UpsamplingInputProcessor
import dev.slimevr.skeleton.targetprocessors.FloorClipTargetProcessor
import dev.slimevr.skeleton.targetprocessors.PositionalTargetProcessor
import dev.slimevr.skeleton.targetprocessors.SkatingCorrectionTargetProcessor
@@ -277,15 +275,13 @@ class Skeleton(
waiter = waiter,
// Run before FK on the inputs
inputProcessors = listOf(
UpsamplingInputProcessor(),
RotationPredictionInputProcessor(settings),
RotationSmoothingInputProcessor(settings),
FilteringInputProcessor(settings),
BoneOffsetInputProcessor(),
HeadPositionFallbackInputProcessor(),
FallbackInputProcessor(),
SpineInputProcessor(settings),
UpperLegsRollAlignInputProcessor(settings),
NeckInputProcessor(),
UpperLegsRollAlignInputProcessor(settings),
DirectLinkInputProcessor(),
FingersInputProcessor(),
ToesInputProcessor(),
@@ -3,7 +3,6 @@ package dev.slimevr.solarxr.rpc
import dev.slimevr.config.Settings
import dev.slimevr.config.SettingsActions
import dev.slimevr.config.SkeletonConfig
import dev.slimevr.config.SkeletonFilteringConfig
import dev.slimevr.config.SkeletonRatiosConfig
import dev.slimevr.config.SkeletonTogglesConfig
import dev.slimevr.skeleton.SkeletonActions
@@ -18,7 +17,6 @@ import solarxr_protocol.rpc.ChangeSkeletonSettingsRequest
import solarxr_protocol.rpc.LegTweaksTmpChange
import solarxr_protocol.rpc.LegTweaksTmpClear
import solarxr_protocol.rpc.SetPauseTrackingRequest
import solarxr_protocol.rpc.SkeletonFiltering
import solarxr_protocol.rpc.SkeletonRatios
import solarxr_protocol.rpc.SkeletonSettingsRequest
import solarxr_protocol.rpc.SkeletonSettingsResponse
@@ -37,15 +35,13 @@ internal fun buildSkeletonSettingsResponse(config: SkeletonConfig) = SkeletonSet
enforceConstraints = config.toggles.enforceConstraints,
),
ratios = SkeletonRatios(
smoothingStrength = config.ratios.smoothingStrength,
predictionStrength = config.ratios.predictionStrength,
spineCurvature = config.ratios.spineCurvature,
imputeSpineFromUpperToLower = config.ratios.imputeSpineFromUpperToLower,
interpolateUpperLegsTwistWithLowerLegs = config.ratios.interpolateUpperLegsTwistWithLowerLegs,
skatingCorrectionStrength = config.ratios.skatingCorrectionStrength,
),
filtering = SkeletonFiltering(
type = config.filtering.type,
amount = config.filtering.amount,
),
)
class SkeletonSettingsBehaviour(
@@ -84,18 +80,14 @@ class SkeletonSettingsBehaviour(
} ?: skeletonConfig.toggles,
ratios = req.ratios?.let {
SkeletonRatiosConfig(
smoothingStrength = it.smoothingStrength ?: 0f,
predictionStrength = it.predictionStrength ?: 0f,
spineCurvature = it.spineCurvature ?: 0f,
imputeSpineFromUpperToLower = it.imputeSpineFromUpperToLower ?: 0f,
interpolateUpperLegsTwistWithLowerLegs = it.interpolateUpperLegsTwistWithLowerLegs ?: 0f,
skatingCorrectionStrength = it.skatingCorrectionStrength ?: 0f,
)
} ?: skeletonConfig.ratios,
filtering = req.filtering?.let {
SkeletonFilteringConfig(
type = it.type,
amount = it.amount,
)
} ?: skeletonConfig.filtering,
),
)
},