Linear upsampling

This commit is contained in:
Erimel committed 2026-10-27 22:49:24 -04:00
1 parent dbbcf677e1
commit 5ddad57851
15 files changed
+151 -95

No files matched your search

@@ -67,6 +67,7 @@ internal fun ensureHidTracker(receiver: HIDReceiver, hidId: Int, deviceId: Int,
hardwareId = deviceState.address,
origin = DeviceOrigin.HID,
appContext = receiver.appContext,
expectedTps = 100u, // TODO: receive from firmware
)
receiver.appContext.server.context.dispatch(VRServerActions.NewTracker(trackerId, newTracker))
newTracker.context.dispatch(TrackerActions.SetStatus(TrackerStatus.OK))
@@ -26,6 +26,7 @@ import java.util.EnumMap
import java.util.concurrent.Executors
import kotlin.math.cos
import kotlin.math.sin
import kotlin.random.Random
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
@@ -67,14 +68,22 @@ class LocalizerResetBehaviour(val settings: Settings) : SkeletonBehaviour {
}
}
class YouSpinMeRightRoundBehaviour(val inputHz: Int = 1) : SkeletonBehaviour {
/**
* packetLoss is random and from 0 to 1.
* sendPosition is for the head data.
*/
class YouSpinMeRightRoundBehaviour(val inputHz: Int = 100, val speed: Float = 1f, val packetLoss: Float = 0f, val sendPosition: Boolean = false) : SkeletonBehaviour {
override fun observe(receiver: Skeleton) {
receiver.context.scope.launch {
val intervalMs = (millisecondsInSecond / inputHz.toFloat()).toLong()
val startTime = timeSource.markNow()
while (true) {
delay(intervalMs)
val elapsed = startTime.elapsedNow().inWholeMilliseconds / millisecondsInSecond
// Simulate packet loss
if (Random.nextFloat() < packetLoss) continue
val elapsed = startTime.elapsedNow().inWholeMilliseconds / millisecondsInSecond * speed
val state = receiver.context.state.value
receiver.context.dispatch(
@@ -98,20 +107,22 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Int = 1) : SkeletonBehaviour {
),
)
val circleRadius = 0.5f
val circleX = cos(elapsed * 2f) * circleRadius
val circleZ = sin(elapsed * 2f) * circleRadius
val jumpHeight = maxOf(0f, sin(elapsed * 3f) * 0.3f)
receiver.context.dispatch(
SkeletonActions.SetBonePose(
BodyPart.HEAD,
Vector3.ZERO,
inputHz.toUShort(),
Quaternion.IDENTITY,
Vector3.ZERO,
Vector3(circleX, state.skeletonHeight + jumpHeight, circleZ),
),
)
if (sendPosition) {
val circleRadius = 0.5f
val circleX = cos(elapsed * 2f) * circleRadius
val circleZ = sin(elapsed * 2f) * circleRadius
val jumpHeight = maxOf(0f, sin(elapsed * 3f) * 0.3f)
receiver.context.dispatch(
SkeletonActions.SetBonePose(
BodyPart.HEAD,
Vector3.ZERO,
inputHz.toUShort(),
Quaternion.IDENTITY,
Vector3.ZERO,
Vector3(circleX, state.skeletonHeight + jumpHeight, circleZ),
),
)
}
}
}
}
@@ -29,7 +29,6 @@ private fun computeVelocity(currentVelocityData: VelocityData, lastVelocityData:
)
}
// Optional smoothing of velocity, to make it smoother for the output (SteamVR/Monado prediction).
private const val SMOOTHING_MS = 25f
private fun smoothVelocity(currentVelocity: Velocity, lastVelocity: Velocity, deltaTime: Float): Velocity {
val t = (deltaTime * (millisecondsInSecond / SMOOTHING_MS)).coerceAtMost(1f)
@@ -42,9 +41,8 @@ private fun smoothVelocity(currentVelocity: Velocity, lastVelocity: Velocity, de
/**
* Computes linear (m/s) and angular (rad/s) velocity for the bones.
*/
class VelocityComputedProcessor(
private val smooth: Boolean = false,
) : SkeletonComputedProcessor,
class VelocityComputedProcessor :
SkeletonComputedProcessor,
ResettableSkeletonProcessor {
private val lastVelocities: BodyPartMap<Velocity> = bodyPartMap()
private val lastVelocityData: BodyPartMap<VelocityData> = bodyPartMap()
@@ -61,15 +59,11 @@ class VelocityComputedProcessor(
val currentVelocityData = VelocityData(bone.rotation, bone.tailPosition)
val currentVelocity = lastVelocityData[bodyPart]?.let { computeVelocity(currentVelocityData, it, deltaTime) } ?: ZERO_VELOCITY
val newVelocity = if (smooth) {
smoothVelocity(currentVelocity, lastVelocities[bodyPart] ?: ZERO_VELOCITY, deltaTime)
} else {
currentVelocity
}
mutableComputedSkeleton[bodyPart] = bone.copy(velocity = newVelocity)
val smoothedVelocity = smoothVelocity(currentVelocity, lastVelocities[bodyPart] ?: ZERO_VELOCITY, deltaTime)
mutableComputedSkeleton[bodyPart] = bone.copy(velocity = smoothedVelocity)
lastVelocityData[bodyPart] = currentVelocityData
lastVelocities[bodyPart] = newVelocity
lastVelocities[bodyPart] = smoothedVelocity
}
}
@@ -38,7 +38,7 @@ class RotationPredictionInputProcessor(val settings: Settings) :
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()
@@ -135,6 +135,7 @@ private fun buildFromTo(sourceActive: Map<SpineSource, Boolean>) = SPINE_SOURCE_
// Higher value makes it so attitude is less prioritized
const val ATTITUDE_MIN = 0.3f
/**
* Prioritize the rotation with the lowest attitude to prevent one thigh driving the whole spine by itself.
* TODO to improve this even more for cases like crossing legs while sitting down, we need to use the rotation delta
@@ -10,82 +10,100 @@ import dev.slimevr.util.timeSource
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.rpc.ResetType
import kotlin.time.ComparableTimeMark
private data class BoneInterpolation(
private data class BoneSample(
val rotation: Quaternion,
val acceleration: Vector3,
val position: Vector3?,
)
private data class BoneSamples(
val fromSample: BoneSample?,
val targetSample: BoneSample?,
val latestPoseTime: ComparableTimeMark,
)
// Allow a little extrapolation to ease into the next pose
private const val MAX_EXTRAPOLATION = 0.25f
private const val EXTRAPOLATION_MULTIPLIER = 0.05f
/**
* 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).
*
* This has the side effect of smoothing data a bit but that is **not** its primary goal as it will run whether
* smoothing filtering is enabled or not.
* Its main goal is to make the data more reliable and easier to work with by avoiding spikes over frames as the skeleton
* receives new data from trackers. We trade off a little bit of latency (~4 ms) for this.
* Its goal is to make the data more reliable and easier to work with by avoiding spikes over frames as the skeleton
* receives new data from trackers. We trade off a little bit of latency (1 tracker tick, or ~10 ms) for this.
*
* It will also extrapolate a little if we haven't received new tracker data in the time we were supposed to,
* to mitigate packet loss and late packets.
*
* 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 is reliable.
* For example, since rotation is interpolated here, the velocity processor doesn't have to do its own interpolation.
* frame to another will have reliably changed according to the IRL movements.
*/
class UpsamplingInputProcessor :
SkeletonInputProcessor,
ResettableSkeletonProcessor {
private var interpolationData: BodyPartMap<BoneInterpolation> = bodyPartMap()
private var lastProcessTime = timeSource.markNow()
private val boneSamples: BodyPartMap<BoneSamples> = bodyPartMap()
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
val deltaTime = lastProcessTime.elapsedNow().inFloatingSeconds
lastProcessTime = timeSource.markNow()
val now = timeSource.markNow()
for ((bodyPart, bone) in mutableInputSkeleton) {
if (bone.tps == null) continue
if (bone.expectedTps == null || bone.poseTime == null) continue
// For a 100hz tracker on 500hz skeleton, this will be 0.2f (interpolating 1/5 every frame)
val interpolationRatio = (deltaTime * bone.tps.toFloat()).coerceAtMost(1f)
val newBone = interpolationData[bodyPart]?.let { interpolation ->
// Interpolate rotation, acceleration and position.
val rotation = if (bone.isRotationActive) {
interpolation.rotation.interpQ(bone.rotation, interpolationRatio)
} else {
bone.rotation
val oldSamples = boneSamples[bodyPart]
val samples = if (bone.poseTime != oldSamples?.latestPoseTime) {
// New pose data
val fromSample = oldSamples?.targetSample
val targetSample = BoneSample(bone.rotation, bone.acceleration, bone.position)
BoneSamples(
fromSample,
targetSample,
bone.poseTime,
).also {
boneSamples[bodyPart] = it
}
val acceleration = if (bone.isAccelerationActive) {
interpolation.acceleration.lerp(bone.acceleration, interpolationRatio)
} else {
bone.acceleration
} else {
oldSamples
}
samples.fromSample?.let { fromSample ->
samples.targetSample?.let { targetSample ->
val timeSinceLastPose = now - bone.poseTime
val rawRatio = (timeSinceLastPose * bone.expectedTps.toInt()).inFloatingSeconds
val extrapolationRatio = ((rawRatio - 1f).coerceAtLeast(0f) * EXTRAPOLATION_MULTIPLIER).coerceAtMost(MAX_EXTRAPOLATION)
val interpolationRatio = rawRatio.coerceAtMost(1f) + extrapolationRatio
// Upsample rotation, acceleration and position.
val rotation = if (bone.isRotationActive) {
fromSample.rotation.interpQ(targetSample.rotation, interpolationRatio)
} else {
targetSample.rotation
}
val acceleration = if (bone.isAccelerationActive) {
fromSample.acceleration.lerp(targetSample.acceleration, interpolationRatio)
} else {
targetSample.acceleration
}
val position = if (bone.isPositionActive && fromSample.position != null && targetSample.position != null) {
fromSample.position.lerp(targetSample.position, interpolationRatio)
} else {
targetSample.position
}
// Update bone data in skeleton and return the bone
mutableInputSkeleton[bodyPart] = bone.copy(
rotation = rotation,
acceleration = acceleration,
position = position,
)
}
val position = if (bone.isPositionActive && bone.position != null && interpolation.position != null) {
interpolation.position.lerp(bone.position, interpolationRatio)
} else {
bone.position
}
// Return modified bone with interpolated data
bone.copy(
rotation = rotation,
acceleration = acceleration,
position = position,
)
} ?: bone
// Set new interpolated bone data
if (bone != newBone) mutableInputSkeleton[bodyPart] = newBone
// Set running interpolation data
interpolationData[bodyPart] = BoneInterpolation(
newBone.rotation,
newBone.acceleration,
newBone.position,
)
}
}
}
override fun reset(resetType: ResetType) {
interpolationData.clear()
lastProcessTime = timeSource.markNow()
boneSamples.clear()
}
}
@@ -8,6 +8,7 @@ import dev.slimevr.skeleton.computedprocessors.VelocityComputedProcessor
import dev.slimevr.skeleton.fkprocessors.FootPlantFkProcessor
import dev.slimevr.skeleton.fkprocessors.LocalizerFkProcessor
import dev.slimevr.skeleton.fkprocessors.ToeSnapFkProcessor
import dev.slimevr.skeleton.inputprocessors.BoneOffsetInputProcessor
import dev.slimevr.skeleton.inputprocessors.ConstraintInputProcessor
import dev.slimevr.skeleton.inputprocessors.DirectLinkInputProcessor
import dev.slimevr.skeleton.inputprocessors.FallbackInputProcessor
@@ -18,7 +19,6 @@ 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.BoneOffsetInputProcessor
import dev.slimevr.skeleton.inputprocessors.UpperLegsRollAlignInputProcessor
import dev.slimevr.skeleton.inputprocessors.UpsamplingInputProcessor
import dev.slimevr.skeleton.targetprocessors.FloorClipTargetProcessor
@@ -33,6 +33,7 @@ import kotlinx.coroutines.flow.MutableSharedFlow
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.rpc.ResetType
import solarxr_protocol.rpc.SkeletonBone
import kotlin.time.ComparableTimeMark
data class Velocity(
/** In meters/s */
@@ -49,7 +50,8 @@ data class BoneInput(
val headOffset: Vector3,
val offset: Vector3,
val boneOffset: Vector3,
val tps: UShort?,
val expectedTps: UShort?,
val poseTime: ComparableTimeMark?,
val rotation: Quaternion,
val acceleration: Vector3,
val position: Vector3?,
@@ -115,7 +117,8 @@ val DEFAULT_BONE_INPUT = BoneInput(
headOffset = Vector3.ZERO,
offset = Vector3.ZERO,
boneOffset = Vector3.ZERO,
tps = null,
expectedTps = null,
poseTime = null,
rotation = Quaternion.IDENTITY,
acceleration = Vector3.ZERO,
position = null,
@@ -182,7 +185,7 @@ sealed interface SkeletonActions {
data class SetBonePose(
val bodyPart: BodyPart,
val boneOffset: Vector3?,
val tps: UShort?,
val expectedTps: UShort?,
val rotation: Quaternion?,
val acceleration: Vector3?,
val position: Vector3?,
@@ -268,7 +271,7 @@ class Skeleton(
ProportionsBehaviour(ctx.config.userConfig),
HeightLogBehaviour(),
LocalizerResetBehaviour(settings),
// YouSpinMeRightRoundBehaviour(inputHz = 50),
// YouSpinMeRightRoundBehaviour(inputHz = 15, speed = 1f, packetLoss = 0f, sendPosition = true),
ComputedSkeletonBehaviour(
hz = hz,
waiter = waiter,
@@ -290,7 +293,7 @@ class Skeleton(
),
// Run on the result of FK and persist
fkComputedProcessors = listOf(
VelocityComputedProcessor(false),
VelocityComputedProcessor(),
),
// Run on the inputs with the result of FK and run FK
fkProcessors = listOf(
@@ -306,7 +309,7 @@ class Skeleton(
),
// Run on the result of IK and persist.
ikComputedProcessors = listOf(
VelocityComputedProcessor(true),
VelocityComputedProcessor(),
),
),
)
@@ -1,5 +1,6 @@
package dev.slimevr.skeleton
import dev.slimevr.util.timeSource
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.datatypes.BodyPart
@@ -11,7 +12,8 @@ fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when
boneInputs = state.boneInputs.mutateCopy {
it[action.bodyPart] = bone.copy(
boneOffset = action.boneOffset ?: bone.boneOffset,
tps = action.tps ?: bone.tps,
expectedTps = action.expectedTps ?: bone.expectedTps,
poseTime = timeSource.markNow(),
rotation = action.rotation ?: bone.rotation,
acceleration = action.acceleration ?: bone.acceleration,
position = action.position ?: bone.position,
@@ -29,7 +31,8 @@ fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when
boneInputs = state.boneInputs.mutateCopy {
it[action.bodyPart] = bone.copy(
boneOffset = Vector3.ZERO,
tps = null,
expectedTps = null,
poseTime = null,
rotation = Quaternion.IDENTITY,
acceleration = Vector3.ZERO,
position = null,
@@ -153,6 +153,7 @@ class DriverIncomingTrackersBehaviour(
origin = DeviceOrigin.DRIVER,
driverName = driverName,
appContext = appContext,
expectedTps = 500u,
)
server.context.dispatch(VRServerActions.NewTracker(trackerId, tracker))
@@ -40,14 +40,14 @@ class TrackerToSkeletonBehaviour : TrackerBehaviour {
.filter { it.bodyPart != null && it.status.isActive() }
activeState
.distinctUntilChanged { old, new -> old.rotation == new.rotation && old.position == new.position && old.pendingSkeletonResets == new.pendingSkeletonResets }
.distinctUntilChanged { old, new -> old.rotation == new.rotation && old.acceleration == new.acceleration && old.position == new.position && old.pendingSkeletonResets == new.pendingSkeletonResets }
.onEach { trackerState ->
trackerState.bodyPart?.let { bodyPart ->
val pendingResets = trackerState.pendingSkeletonResets
val bonePoseActions = SkeletonActions.SetBonePose(
bodyPart,
trackerState.boneOffsets[bodyPart],
trackerState.tps,
trackerState.expectedTps ?: trackerState.tps,
trackerState.rotation,
trackerState.acceleration,
trackerState.position,
@@ -80,6 +80,7 @@ data class TrackerState(
val position: Vector3?,
val imuTemp: Float?,
val accumulatedTicks: UShort,
val expectedTps: UShort?,
val tps: UShort,
val status: TrackerStatus,
val completedRestCalibration: Boolean?,
@@ -147,6 +148,7 @@ class Tracker(
hardwareId: String,
origin: DeviceOrigin,
driverName: String? = null,
expectedTps: UShort? = null,
appContext: AppContextProvider,
): Tracker {
val settings = appContext.config.settings
@@ -165,6 +167,7 @@ class Tracker(
intendedBodyPart = intendedBodyPart,
boneOffsets = intendedBodyPart?.let { part -> intendedBoneOffset?.let { offset -> mapOf(part to offset) } } ?: emptyMap(),
stayAlignedData = DEFAULT_STATE.stayAlignedData.copy(enabled = settings.context.state.value.data.stayAlignedConfig.enabled),
expectedTps = expectedTps,
)
val trackerState = if (savedConfig != null) {
TrackerConfigBehaviour.restoreFromConfig(baseState, savedConfig, settings.context.state.value.data.resetsConfig.saveMountingReset)
@@ -223,6 +226,7 @@ class Tracker(
position = null,
imuTemp = null,
accumulatedTicks = 0u,
expectedTps = null,
tps = 0u,
status = TrackerStatus.DISCONNECTED,
completedRestCalibration = null,
@@ -66,6 +66,7 @@ internal fun assignTracker(receiver: UDPConnection, device: Device, info: Sensor
origin = DeviceOrigin.UDP,
scope = receiver.appContext.server.context.scope,
appContext = receiver.appContext,
expectedTps = 100u,
)
receiver.appContext.server.context.dispatch(VRServerActions.NewTracker(trackerId = trackerId, context = newTracker))
receiver.context.dispatch(
@@ -541,6 +541,7 @@ fun writePacket(dst: Sink, packet: UDPPacket) {
when (type) {
PacketType.HANDSHAKE -> Unit
PacketType.SENSOR_INFO -> dst.writeInt(type.id)
else -> {
@@ -14,8 +14,8 @@ import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.launchIn