mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-12-04 07:42:31 -08:00
Calculate frametimes for skeleton and make smoothing truly independant
This commit is contained in:
1 parent
5d7cd5dfaf
commit
6562d41721
16 files changed
+85
-60
No files matched your search
@@ -47,7 +47,7 @@ class BVHRecordingBehaviour(
|
||||
try {
|
||||
AppLogger.bvh.info("Opening BVH recording at ${storage.displayPath(resolvedPath)}")
|
||||
stream = BvhStream(storage.openTextFile(resolvedPath)).also {
|
||||
it.writeHeader(skeleton.computed.value)
|
||||
it.writeHeader(skeleton.computed.value.bones)
|
||||
// TODO: we could write the initial T-Pose or whatever here
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
@@ -66,9 +66,9 @@ class BVHRecordingBehaviour(
|
||||
}
|
||||
}.launchIn(receiver.context.scope)
|
||||
|
||||
skeleton.computed.onEach { bones ->
|
||||
skeleton.computed.onEach { computedSkeleton ->
|
||||
try {
|
||||
stream?.writeFrame(bones)
|
||||
stream?.writeFrame(computedSkeleton.bones)
|
||||
} catch (e: Exception) {
|
||||
AppLogger.bvh.error("Failed to write BVH frame", e)
|
||||
receiver.context.dispatch(BVHActions.StopRecording)
|
||||
|
||||
@@ -49,7 +49,7 @@ class DriverOutgoingTrackersBehaviour : DriverBridgeBehaviour {
|
||||
::Pair,
|
||||
)
|
||||
.distinctUntilChanged()
|
||||
.onEach { (computedBones, enabledBodyParts) ->
|
||||
.onEach { (computedSkeleton, enabledBodyParts) ->
|
||||
val serverState = receiver.appContext.server.context.state.value
|
||||
|
||||
// Map the nearest trackers to their body parts
|
||||
@@ -61,7 +61,7 @@ class DriverOutgoingTrackersBehaviour : DriverBridgeBehaviour {
|
||||
trackerStateByBodyPart.putIfAbsent(bodyPart, trackerState)
|
||||
}
|
||||
|
||||
computedBones.forEach { (part, state) ->
|
||||
computedSkeleton.bones.forEach { (part, state) ->
|
||||
if (enabledBodyParts.contains(part)) {
|
||||
val closestTracker = bodyPartToNearest[part].orEmpty()
|
||||
.firstNotNullOfOrNull { fallbackPart -> trackerStateByBodyPart[fallbackPart] }
|
||||
|
||||
@@ -15,8 +15,10 @@ import kotlinx.coroutines.launch
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.nanoseconds
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.measureTime
|
||||
|
||||
class BoneTransformBehaviour : SkeletonBehaviour {
|
||||
override fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when (action) {
|
||||
@@ -125,55 +127,64 @@ class ComputedSkeletonBehaviour(
|
||||
val hz: Int,
|
||||
val processors: List<SkeletonProcessor> = emptyList(),
|
||||
) : SkeletonBehaviour {
|
||||
val logSpamWaitDuration = 10.seconds
|
||||
val minimumDelay = 1.nanoseconds
|
||||
private val intervalDuration = (1.0 / hz).seconds
|
||||
private val logSpamWaitDuration = 15.seconds
|
||||
private val minimumDelay = 1.nanoseconds
|
||||
|
||||
override fun observe(receiver: Skeleton) {
|
||||
val intervalDuration = (1.0 / hz).seconds
|
||||
var nextLogTime = timeSource.markNow()
|
||||
var frameStartTime = timeSource.markNow()
|
||||
var lastFrameTime = Duration.ZERO
|
||||
|
||||
receiver.context.scope.launch {
|
||||
while (true) {
|
||||
try {
|
||||
val startTime = timeSource.markNow()
|
||||
// Process starts
|
||||
val processTime = measureTime {
|
||||
|
||||
val targetState = receiver.context.state.value
|
||||
val targetState = receiver.context.state.value
|
||||
|
||||
// Run processors
|
||||
val processed = processors
|
||||
.fold(targetState) { state, processor -> processor.process(state) } // TODO: Add a constrain processor (maybe not needed)
|
||||
// Run processors
|
||||
val processed = processors
|
||||
.fold(targetState) { state, processor -> processor.process(state, lastFrameTime) } // TODO: Add a constrain processor (maybe not needed)
|
||||
|
||||
// Get head position
|
||||
val rootHead = processed.boneInputs[BodyPart.HEAD]
|
||||
?.let { Vector3(it.rawPosition.x, it.rawPosition.y, it.rawPosition.z) }
|
||||
?: Vector3(0f, targetState.skeletonHeight, 0f)
|
||||
// Get head position
|
||||
val rootHead = processed.boneInputs[BodyPart.HEAD]
|
||||
?.let { Vector3(it.rawPosition.x, it.rawPosition.y, it.rawPosition.z) }
|
||||
?: Vector3(0f, targetState.skeletonHeight, 0f)
|
||||
|
||||
// Run FK
|
||||
val fk = buildBones(processed, rootHead = rootHead)
|
||||
// Run FK
|
||||
val fk = buildBones(processed, rootHead = rootHead)
|
||||
|
||||
// val targetProcessors = [FloorClip, FloorSkating, ToePlant, FootPlant]
|
||||
// val targetProcessors = [FloorClip, FloorSkating, ToePlant, FootPlant]
|
||||
//
|
||||
// val targets = targetProcessors
|
||||
// .filter { targetProcessors -> targetProcessors.enabled }
|
||||
// .fold(emptyList<Target>()) { targets, processor -> processor.process(fk, targets) }
|
||||
// val targets = targetProcessors
|
||||
// .filter { targetProcessors -> targetProcessors.enabled }
|
||||
// .fold(emptyList<Target>()) { targets, processor -> processor.process(fk, targets) }
|
||||
//
|
||||
// val ikOutput = solver.solve(fk, targets)
|
||||
// val ikOutput = solver.solve(fk, targets)
|
||||
|
||||
// FIXME bones should still follow the head when paused
|
||||
if (!targetState.paused) {
|
||||
receiver.computed.value = fk
|
||||
// receiver.computed.value = ikOutput
|
||||
// Frame ends
|
||||
lastFrameTime = frameStartTime.elapsedNow()
|
||||
|
||||
// Updated the computed skeleton with the result
|
||||
if (!targetState.paused) { // FIXME : bones should still follow the head when paused
|
||||
receiver.computed.value = ComputedSkeleton(fk, lastFrameTime)
|
||||
// receiver.computed.value = ComputedSkeleton(ikOutput, lastFrameTime)
|
||||
}
|
||||
}
|
||||
// Process ends
|
||||
|
||||
val processTime = startTime.elapsedNow()
|
||||
// Frame starts
|
||||
frameStartTime = timeSource.markNow()
|
||||
|
||||
// Wait the remainder of last process
|
||||
val delayDuration = (intervalDuration - processTime).coerceAtLeast(minimumDelay)
|
||||
|
||||
// Warn if the process took too long to reach the target hz.
|
||||
if (delayDuration <= minimumDelay && nextLogTime.hasPassedNow()) {
|
||||
// Warn if the frame took too long to reach the target hz.
|
||||
AppLogger.skeleton.warn("Can't reach target hz ($hz), process time = $processTime")
|
||||
nextLogTime = timeSource.markNow() + logSpamWaitDuration
|
||||
}
|
||||
|
||||
delay(delayDuration)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
|
||||
@@ -17,6 +17,7 @@ import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import solarxr_protocol.rpc.SkeletonBone
|
||||
import kotlin.time.Duration
|
||||
|
||||
data class BoneInput(
|
||||
val bodyPart: BodyPart,
|
||||
@@ -116,26 +117,32 @@ sealed interface SkeletonActions {
|
||||
typealias SkeletonContext = Context<SkeletonState, SkeletonActions>
|
||||
typealias SkeletonBehaviour = Behaviour<SkeletonState, SkeletonActions, Skeleton>
|
||||
interface SkeletonProcessor {
|
||||
fun process(state: SkeletonState): SkeletonState
|
||||
fun process(state: SkeletonState, lastFrameTime: Duration): SkeletonState
|
||||
}
|
||||
|
||||
data class ComputedSkeleton(
|
||||
val bones: BodyPartMap<BoneState>,
|
||||
val frameTime: Duration,
|
||||
)
|
||||
|
||||
class Skeleton(
|
||||
val context: SkeletonContext,
|
||||
val computed: MutableStateFlow<BodyPartMap<BoneState>>,
|
||||
val computed: MutableStateFlow<ComputedSkeleton>,
|
||||
) {
|
||||
fun startObserving() = context.observeAll(this)
|
||||
|
||||
companion object {
|
||||
fun create(scope: CoroutineScope, ctx: Phase1ContextProvider): Skeleton {
|
||||
val skeletonRefreshRate = 300
|
||||
const val DEFAULT_HZ = 300
|
||||
|
||||
fun create(scope: CoroutineScope, ctx: Phase1ContextProvider, hz: Int = DEFAULT_HZ): Skeleton {
|
||||
val behaviours = listOf(
|
||||
PauseTrackingBehaviour(),
|
||||
BoneTransformBehaviour(),
|
||||
ProportionsBehaviour(ctx.config.userConfig),
|
||||
HeightLogBehaviour(),
|
||||
// YouSpinMeRightRoundBehaviour(inputHz = 50f),
|
||||
// YouSpinMeRightRoundBehaviour(inputHz = 50f),
|
||||
ComputedSkeletonBehaviour(
|
||||
hz = skeletonRefreshRate,
|
||||
hz = hz,
|
||||
processors = listOf(
|
||||
BoneYawFallbackProcessor(),
|
||||
BoneActiveLinkProcessor(),
|
||||
@@ -144,7 +151,7 @@ class Skeleton(
|
||||
BoneDirectLinkProcessor(),
|
||||
FingerImputeProcessor(),
|
||||
BonePredictionProcessor(ctx.config.settings),
|
||||
BoneSmoothingProcessor(ctx.config.settings, skeletonRefreshRate),
|
||||
BoneSmoothingProcessor(ctx.config.settings),
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -156,7 +163,7 @@ class Skeleton(
|
||||
name = "Skeleton",
|
||||
)
|
||||
|
||||
return Skeleton(context, MutableStateFlow(buildBones(context.state.value)))
|
||||
return Skeleton(context, MutableStateFlow(ComputedSkeleton(buildBones(context.state.value), Duration.ZERO)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import dev.slimevr.skeleton.SkeletonProcessor
|
||||
import dev.slimevr.skeleton.SkeletonState
|
||||
import dev.slimevr.skeleton.mutate
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import kotlin.time.Duration
|
||||
|
||||
/**
|
||||
* Handles setting the rotation of an inactive bone with the first active bone in its sources, or keeps
|
||||
@@ -23,7 +24,7 @@ class BoneActiveLinkProcessor : SkeletonProcessor {
|
||||
BodyPart.HIP to arrayOf(BodyPart.WAIST, BodyPart.CHEST, BodyPart.UPPER_CHEST),
|
||||
)
|
||||
|
||||
override fun process(state: SkeletonState): SkeletonState {
|
||||
override fun process(state: SkeletonState, lastFrameTime: Duration): SkeletonState {
|
||||
val boneInputs = state.boneInputs
|
||||
|
||||
val updatedLinkedBones = boneInputs.mutate { updated ->
|
||||
|
||||
@@ -4,6 +4,7 @@ import dev.slimevr.skeleton.BodyPartMap
|
||||
import dev.slimevr.skeleton.SkeletonProcessor
|
||||
import dev.slimevr.skeleton.SkeletonState
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import kotlin.time.Duration
|
||||
|
||||
/**
|
||||
* Handles setting the rotation of an inactive bone with its source bone.
|
||||
@@ -37,7 +38,7 @@ class BoneDirectLinkProcessor : SkeletonProcessor {
|
||||
BodyPart.RIGHT_HAND to BodyPart.RIGHT_LOWER_ARM,
|
||||
)
|
||||
|
||||
override fun process(state: SkeletonState): SkeletonState {
|
||||
override fun process(state: SkeletonState, lastFrameTime: Duration): SkeletonState {
|
||||
val updatedBoneInputs = BodyPartMap(state.boneInputs)
|
||||
|
||||
for ((bodyPart, source) in linkedToSource) {
|
||||
|
||||
@@ -9,6 +9,7 @@ import dev.slimevr.skeleton.mapValues
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import solarxr_protocol.rpc.FilteringType
|
||||
import kotlin.time.Duration
|
||||
|
||||
/**
|
||||
* Tries to predict future rotations of bones.
|
||||
@@ -23,7 +24,7 @@ class BonePredictionProcessor(val settings: Settings) : SkeletonProcessor {
|
||||
|
||||
private var velocities: BodyPartMap<BoneVelocity> = bodyPartMap()
|
||||
|
||||
override fun process(state: SkeletonState): SkeletonState {
|
||||
override fun process(state: SkeletonState, lastFrameTime: Duration): SkeletonState {
|
||||
val config = settings.context.state.value.data.skeletonConfig.filtering
|
||||
if (config.type != FilteringType.PREDICTION) return state
|
||||
val predictionAmount = config.amount
|
||||
|
||||
@@ -9,23 +9,22 @@ import dev.slimevr.skeleton.mapValues
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import solarxr_protocol.rpc.FilteringType
|
||||
import kotlin.time.Duration
|
||||
|
||||
/**
|
||||
* Running average of bones to smooth them out.
|
||||
*/
|
||||
// TODO checking skeletonRefreshRate is not good enough
|
||||
// since we're never gonna get that in practice. Need something more robust.
|
||||
class BoneSmoothingProcessor(val settings: Settings, val skeletonRefreshRate: Int) : SkeletonProcessor {
|
||||
class BoneSmoothingProcessor(val settings: Settings) : SkeletonProcessor {
|
||||
private var smoothedRotations: BodyPartMap<Quaternion> = bodyPartMap()
|
||||
private var smoothedLengths: BodyPartMap<Vector3> = bodyPartMap()
|
||||
|
||||
// TODO this isn't linear. Do we want linear smoothing like in main?
|
||||
override fun process(state: SkeletonState): SkeletonState {
|
||||
override fun process(state: SkeletonState, lastFrameTime: Duration): SkeletonState {
|
||||
val config = settings.context.state.value.data.skeletonConfig.filtering
|
||||
if (config.type != FilteringType.SMOOTHING) return state
|
||||
|
||||
val smoothingAmount = SMOOTH_MIN + config.amount.coerceIn(0f, 1f) * (SMOOTH_MAX - SMOOTH_MIN)
|
||||
val alpha = (1 - smoothingAmount) / (skeletonRefreshRate / 100f)
|
||||
val alpha = (1 - smoothingAmount) * (lastFrameTime.inWholeMicroseconds / 10_000f)
|
||||
|
||||
smoothedRotations = state.boneInputs.mapValues { bodyPart, bone ->
|
||||
(smoothedRotations[bodyPart] ?: bone.rawRotation).lerpR(bone.rawRotation, alpha).unit()
|
||||
@@ -45,7 +44,7 @@ class BoneSmoothingProcessor(val settings: Settings, val skeletonRefreshRate: In
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val SMOOTH_MIN = 0.62f
|
||||
private const val SMOOTH_MAX = 0.9f
|
||||
private const val SMOOTH_MIN = 0.6f
|
||||
private const val SMOOTH_MAX = 0.93f
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,14 @@ import dev.slimevr.skeleton.SkeletonState
|
||||
import dev.slimevr.skeleton.mutate
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import kotlin.collections.set
|
||||
import kotlin.time.Duration
|
||||
|
||||
/**
|
||||
* Handles replacing rotations of boneInputs that are not actively receiving data by
|
||||
* falling back to their parent's yaw.
|
||||
*/
|
||||
class BoneYawFallbackProcessor : SkeletonProcessor {
|
||||
override fun process(state: SkeletonState): SkeletonState {
|
||||
override fun process(state: SkeletonState, lastFrameTime: Duration): SkeletonState {
|
||||
val boneInputs = state.boneInputs
|
||||
|
||||
val updatedFallbackBones = boneInputs.mutate { updated ->
|
||||
|
||||
@@ -7,6 +7,7 @@ import dev.slimevr.skeleton.mutate
|
||||
import dev.slimevr.skeleton.resolveRotationFor
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import kotlin.time.Duration
|
||||
|
||||
/**
|
||||
* Handles rotating bones' yaw and roll to match other bones' yaw and roll.
|
||||
@@ -26,7 +27,7 @@ class BoneYawRollAlignProcessor(val settings: Settings) : SkeletonProcessor {
|
||||
SourceLink(BodyPart.RIGHT_UPPER_LEG, arrayOf(BodyPart.RIGHT_LOWER_LEG), mustBeActive = true),
|
||||
)
|
||||
|
||||
override fun process(state: SkeletonState): SkeletonState {
|
||||
override fun process(state: SkeletonState, lastFrameTime: Duration): SkeletonState {
|
||||
val boneInputs = state.boneInputs
|
||||
val ratios = settings.context.state.value.data.skeletonConfig.ratios
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import dev.slimevr.skeleton.SkeletonState
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import kotlin.collections.get
|
||||
import kotlin.collections.iterator
|
||||
import kotlin.time.Duration
|
||||
|
||||
/**
|
||||
* Handles rotations of inactive finger bones.
|
||||
@@ -50,7 +51,7 @@ class FingerImputeProcessor : SkeletonProcessor {
|
||||
)
|
||||
|
||||
// TODO : There's more math to do here. Reference the original code.
|
||||
override fun process(state: SkeletonState): SkeletonState {
|
||||
override fun process(state: SkeletonState, lastFrameTime: Duration): SkeletonState {
|
||||
val updatedBoneInputs = BodyPartMap(state.boneInputs)
|
||||
|
||||
for ((bodyPart, source) in fingerToSource) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import dev.slimevr.skeleton.SkeletonState
|
||||
import dev.slimevr.skeleton.mutate
|
||||
import dev.slimevr.skeleton.resolveRotationFor
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import kotlin.time.Duration
|
||||
|
||||
/**
|
||||
* Handles imputing the rotation of spine bones that are not actively receiving data from the rotations
|
||||
@@ -37,7 +38,7 @@ class SpineImputeProcessor(val settings: Settings) : SkeletonProcessor {
|
||||
else -> error("Invalid missing spine body part $bodyPart")
|
||||
}
|
||||
|
||||
override fun process(state: SkeletonState): SkeletonState {
|
||||
override fun process(state: SkeletonState, lastFrameTime: Duration): SkeletonState {
|
||||
val boneInputs = state.boneInputs
|
||||
val ratios = settings.context.state.value.data.skeletonConfig.ratios
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import io.github.axisangles.ktmath.Quaternion
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import kotlin.time.ComparableTimeMark
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.DurationUnit
|
||||
|
||||
// TODO We should probably just have globally available velocity on the whole skeleton,
|
||||
@@ -86,7 +87,7 @@ class SkatingCorrectionProcessor : SkeletonProcessor {
|
||||
|
||||
var comState: COMState? = null
|
||||
|
||||
override fun process(state: SkeletonState): SkeletonState {
|
||||
override fun process(state: SkeletonState, lastFrameTime: Duration): SkeletonState {
|
||||
val curTime = timeSource.markNow()
|
||||
|
||||
val lastComState = comState
|
||||
@@ -160,7 +161,7 @@ class SkatingCorrectionProcessor : SkeletonProcessor {
|
||||
class FloorClipProcessor : SkeletonProcessor {
|
||||
fun getDisplacement(footPos: Vector3): Vector3 = Vector3(0f, footPos.y.coerceAtMost(0f), 0f)
|
||||
|
||||
override fun process(state: SkeletonState): SkeletonState {
|
||||
override fun process(state: SkeletonState, lastFrameTime: Duration): SkeletonState {
|
||||
val newBones = state.boneInputs.mapValues { (bodyPart, bone) -> }
|
||||
state.boneInputs[BodyPart.LEFT_FOOT]?.let {
|
||||
val correction = getDisplacement(it.offset)
|
||||
|
||||
@@ -139,7 +139,7 @@ fun createDatafeedFrame(
|
||||
null
|
||||
}
|
||||
val bones = datafeedConfig.boneMask?.let { mask ->
|
||||
skeleton.computed.value.values.map { createBone(it, mask) }
|
||||
skeleton.computed.value.bones.values.map { createBone(it, mask) }
|
||||
}
|
||||
val serverGuards = if (datafeedConfig.serverGuardsMask == true) {
|
||||
createServerGuards(resetsManager, heightCalibrationManager)
|
||||
|
||||
@@ -65,14 +65,14 @@ class VMCOutputBehaviour(
|
||||
}.launchIn(receiver.context.scope)
|
||||
|
||||
skeleton.computed
|
||||
.onEach { bones ->
|
||||
.onEach { computedSkeleton ->
|
||||
val s = sender ?: return@onEach
|
||||
val config = settings.context.state.value.data.vmcConfig
|
||||
val currentTime = System.currentTimeMillis()
|
||||
val vrm = vrmGeometry
|
||||
receiver.context.scope.launch {
|
||||
try {
|
||||
s.send(buildBundle(bones, config, currentTime, vrm))
|
||||
s.send(buildBundle(computedSkeleton.bones, config, currentTime, vrm))
|
||||
} catch (e: Exception) {
|
||||
AppLogger.vmc.error("Failed to send VMC frame", e)
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ class VRCOSCOutputBehaviour(
|
||||
|
||||
private fun observeFrames(receiver: VRCOSCManager, runtime: OutputRuntime) {
|
||||
skeleton.computed
|
||||
.onEach { bones -> sendFrame(receiver, runtime, bones) }
|
||||
.onEach { computedSkeleton -> sendFrame(receiver, runtime, computedSkeleton.bones) }
|
||||
.launchIn(receiver.context.scope)
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user