diff --git a/server/core/src/main/java/dev/slimevr/hid/manager.kt b/server/core/src/main/java/dev/slimevr/hid/manager.kt index 8aa01a1ab..993b25a3f 100644 --- a/server/core/src/main/java/dev/slimevr/hid/manager.kt +++ b/server/core/src/main/java/dev/slimevr/hid/manager.kt @@ -132,8 +132,11 @@ private suspend fun readDevice(connection: HidConnection, receiver: HIDReceiver, -1 } when { - // read error, device gone - read < 0 -> return + // The transport gave up on the device, so let the manager reopen it + read < 0 -> { + AppLogger.hid.info("HID read failed for ${receiver.context.state.value.serialNumber}, reopening") + return + } read > 0 -> { emptyReads = 0 diff --git a/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt b/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt index 548d8f6c1..89434a9ce 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt @@ -7,17 +7,20 @@ import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 import io.ktor.utils.io.CancellationException import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.distinctUntilChangedBy import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import solarxr_protocol.datatypes.BodyPart +import java.util.EnumMap +import java.util.concurrent.locks.LockSupport import kotlin.math.cos import kotlin.math.sin import kotlin.time.Duration +import kotlin.time.TimeSource import kotlin.time.Duration.Companion.minutes -import kotlin.time.Duration.Companion.nanoseconds import kotlin.time.Duration.Companion.seconds import kotlin.time.measureTime @@ -95,6 +98,78 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Float = 1f) : SkeletonBehaviour } } +/** + * Runs [processors] over a copy of [boneInputs]. + * + * The processors share one buffer and write into it, so the copy here is what keeps the caller's + * map, and the state it came from, untouched. + */ +private fun runInputProcessors(processors: List, boneInputs: InputSkeleton, skeletonHeight: Float): InputSkeleton { + val bones = EnumMap(boneInputs) + for (processor in processors) processor.process(bones, skeletonHeight) + return bones +} + +private class TickTimings(private val hz: Int, private val window: Duration, private val target: Duration) { + private val capacity = (hz * window.inWholeSeconds + hz).toInt() + private val computeNanos = LongArray(capacity) + private val intervalNanos = LongArray(capacity) + private var count = 0 + private var lastStart = timeSource.markNow() + private var sinceLastStart = Duration.ZERO + private var nextReport = timeSource.markNow() + window + private var overruns = 0 + private var nextOverrunReport = timeSource.markNow() + OVERRUN_WINDOW + + /** Called with the start of a tick, so the gap between two starts is what gets measured */ + fun started(at: TimeSource.Monotonic.ValueTimeMark) { + sinceLastStart = at - lastStart + lastStart = at + } + + fun finished(compute: Duration) { + if (count == capacity) return + computeNanos[count] = compute.inWholeNanoseconds + intervalNanos[count] = sinceLastStart.inWholeNanoseconds + count++ + } + + /** The line to log once a window has passed, or null while one is still filling */ + fun report(): String? { + if (!nextReport.hasPassedNow()) return null + val compute = computeNanos.copyOf(count).also { it.sort() } + val interval = intervalNanos.copyOf(count).also { it.sort() } + count = 0 + nextReport = timeSource.markNow() + window + return "Skeleton tick over ${compute.size} frames: " + + "compute p50 %.0fus p99 %.0fus max %.0fus | interval p50 %.0fus p99 %.0fus min %.0fus max %.0fus, target ${target.inWholeMicroseconds}us".format( + micros(compute, 0.5), + micros(compute, 0.99), + micros(compute, 1.0), + micros(interval, 0.5), + micros(interval, 0.99), + micros(interval, 0.0), + micros(interval, 1.0), + ) + } + + fun missedDeadline(): String? { + overruns++ + if (!nextOverrunReport.hasPassedNow()) return null + val line = "Couldn't reach ${hz}Hz $overruns times in the last $OVERRUN_WINDOW".takeIf { overruns >= MINIMUM_OVERRUNS_TO_LOG } + overruns = 0 + nextOverrunReport = timeSource.markNow() + OVERRUN_WINDOW + return line + } + + private fun micros(sortedNanos: LongArray, percentile: Double): Double = sortedNanos[((sortedNanos.size - 1) * percentile).toInt()] / 1000.0 + + companion object { + private val OVERRUN_WINDOW = 1.minutes + private const val MINIMUM_OVERRUNS_TO_LOG = 10 + } +} + class ComputedSkeletonBehaviour( val hz: Int, val inputProcessors: List = emptyList(), @@ -102,17 +177,35 @@ class ComputedSkeletonBehaviour( val targetProcessors: List = emptyList(), ) : SkeletonBehaviour { private val intervalDuration = (1.0 / hz).seconds - private val minimumDelay = 1.nanoseconds - private val logSpamWait = 1.minutes - private val minimumFramesToLog = 10 + + /** Shortest gap between two tick starts before the later one is pushed to the next slot */ + private val minimumGap = intervalDuration * 0.75 + + /** + * The first slot on the tick grid falling at least [minimumGap] after [tickStart]. + * + * Ticks stay on the grid they started on so the rate doesn't drift, and a tick that ran late + * gives up its own slot rather than letting the next one fire early to catch up. The gap is + * measured from when the tick actually ran, which always trails its deadline by the wake + * latency, so only a materially short gap costs a slot. + */ + private fun slotAfter(slot: TimeSource.Monotonic.ValueTimeMark, tickStart: TimeSource.Monotonic.ValueTimeMark): TimeSource.Monotonic.ValueTimeMark { + var next = slot + while (next - tickStart < minimumGap) next += intervalDuration + return next + } override fun observe(receiver: Skeleton) { - var nextLogTime = timeSource.markNow() + logSpamWait - var processTooLongCount = 0 + var nextTick = timeSource.markNow() + val fkChangedParts = mutableSetOf() + val timings = TickTimings(hz, 10.seconds, intervalDuration) receiver.context.scope.launch { while (true) { try { + val tickStart = timeSource.markNow() + timings.started(tickStart) + val processTime = measureTime { val targetState = receiver.context.state.value @@ -123,10 +216,11 @@ class ComputedSkeletonBehaviour( } else { // Run pre-FK processors // TODO: Add a constrain processor (maybe not needed) - val processedInputs = inputProcessors.fold(targetState.boneInputs) { boneInputs, processor -> processor.process(boneInputs, targetState.skeletonHeight) } + val processedInputs = runInputProcessors(inputProcessors, targetState.boneInputs, targetState.skeletonHeight) if (targetState.paused) { // We just paused tracking and this is the last frame before we rely on paused bone inputs - receiver.context.dispatch(SkeletonActions.SetPausedBoneInputs(processedInputs)) + // The buffer keeps being written after this, so state gets a copy + receiver.context.dispatch(SkeletonActions.SetPausedBoneInputs(EnumMap(processedInputs))) } processedInputs } @@ -134,22 +228,28 @@ class ComputedSkeletonBehaviour( // Run initial FK var fk = buildBones(boneInputs) - // Run FK processors - fkProcessors.fold((boneInputs)) { inputs, processor -> - // Process new inputs from - val newInputs = processor.process(inputs, fk, targetState.floorLevel) - if (newInputs != inputs) { - // Inputs changed; re-run FK - val changedInputs = newInputs.filter { (part, boneInput) -> boneInput != inputs[part] } - fk = buildBones(newInputs, changedInputs.keys, fk) + // Run FK processors. They write into boneInputs, and this snapshot is what says + // which bones each one moved, so a processor only has to write + val beforeFk = EnumMap(boneInputs) + for (processor in fkProcessors) { + processor.process(boneInputs, fk, targetState.floorLevel) + + // Comparing and filtering the maps allocates an entry per bone each time, so + // the changed set is collected in one walk instead + fkChangedParts.clear() + boneInputs.forEachBone { bodyPart, boneInput -> + val previous = beforeFk[bodyPart] + if (boneInput == previous) return@forEachBone + fkChangedParts.add(bodyPart) + beforeFk[bodyPart] = boneInput // For changed bones with inactive positions, update their input's position in state (needed for Localizer) - val changedPositionInputs = changedInputs.filter { (part, boneInput) -> !boneInput.isPositionActive && boneInput.position != inputs[part]?.position } - for (input in changedPositionInputs) { - receiver.context.dispatch(SkeletonActions.SetBonePosition(input.key, input.value.position, false)) + if (!boneInput.isPositionActive && boneInput.position != previous?.position) { + receiver.context.dispatch(SkeletonActions.SetBonePosition(bodyPart, boneInput.position, false)) } } - newInputs + // Inputs changed; re-run FK + if (fkChangedParts.isNotEmpty()) fk = buildBones(boneInputs, fkChangedParts, fk) } // Run IK processors @@ -174,20 +274,23 @@ class ComputedSkeletonBehaviour( receiver.computed.tryEmit(ikOutput.bones) } - // Wait the remainder of last process - val delayDuration = intervalDuration - processTime - if (delayDuration <= Duration.ZERO) { - // Skeleton took to long to compute this frame - processTooLongCount++ - if (nextLogTime.hasPassedNow()) { - if (processTooLongCount >= minimumFramesToLog) { - AppLogger.skeleton.warn("Couldn't reach ${hz}Hz $processTooLongCount times in the last $logSpamWait") - } - processTooLongCount = 0 - nextLogTime = timeSource.markNow() + logSpamWait - } + timings.finished(processTime) + timings.report()?.let { AppLogger.skeleton.info(it) } + + // Sleep to an absolute deadline, so timer granularity and dispatch latency come out + // of the interval rather than being added on top of it + nextTick += intervalDuration + // Skeleton took to long to compute this frame + if (nextTick.elapsedNow() >= Duration.ZERO) { + timings.missedDeadline()?.let { AppLogger.skeleton.warn(it) } + } + nextTick = slotAfter(nextTick, tickStart) + var remaining = -nextTick.elapsedNow() + while (remaining > Duration.ZERO) { + LockSupport.parkNanos(remaining.inWholeNanoseconds) + coroutineContext.ensureActive() + remaining = -nextTick.elapsedNow() } - delay(delayDuration.coerceAtLeast(minimumDelay)) } catch (e: CancellationException) { throw e } catch (e: Exception) { diff --git a/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/foot-plant.kt b/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/foot-plant.kt index cd616c30c..2066a5ca8 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/foot-plant.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/foot-plant.kt @@ -4,7 +4,6 @@ import dev.slimevr.config.Settings import dev.slimevr.skeleton.ComputedSkeleton import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonFkProcessor -import dev.slimevr.skeleton.mutateCopy import dev.slimevr.tracker.eulerHeading import io.github.axisangles.ktmath.Quaternion import solarxr_protocol.datatypes.BodyPart @@ -31,23 +30,21 @@ fun correctFootAttitude( class FootPlantFkProcessor(val settings: Settings) : SkeletonFkProcessor { val bodyParts: Array = arrayOf(BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT) - override fun process(inputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float): InputSkeleton { - if (!settings.context.state.value.data.skeletonConfig.toggles.footPlant) return inputSkeleton + override fun process(inputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float) { + if (!settings.context.state.value.data.skeletonConfig.toggles.footPlant) return - return inputSkeleton.mutateCopy { - for (bodyPart in bodyParts) { - val input = it[bodyPart] ?: continue - val output = fk[bodyPart] ?: continue - it[bodyPart] = input.copy( - rotation = correctFootAttitude( - input.rotation, - computeFootPlantRatio( - output.headPosition.y, - floorLevel, - ), + for (bodyPart in bodyParts) { + val input = inputSkeleton[bodyPart] ?: continue + val output = fk[bodyPart] ?: continue + inputSkeleton[bodyPart] = input.copy( + rotation = correctFootAttitude( + input.rotation, + computeFootPlantRatio( + output.headPosition.y, + floorLevel, ), - ) - } + ), + ) } } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/localizer.kt b/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/localizer.kt index 7d84bd57e..c2deced92 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/localizer.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/fkprocessors/localizer.kt @@ -5,7 +5,6 @@ import dev.slimevr.skeleton.BoneState import dev.slimevr.skeleton.ComputedSkeleton import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonFkProcessor -import dev.slimevr.skeleton.mutateCopy import io.github.axisangles.ktmath.Vector3 import solarxr_protocol.datatypes.BodyPart @@ -100,10 +99,10 @@ private fun isUserSitting(fk: ComputedSkeleton): Boolean { } class LocalizerFkProcessor(val settings: Settings) : SkeletonFkProcessor { - override fun process(inputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float): InputSkeleton { - val headInput = inputSkeleton[BodyPart.HEAD] ?: return inputSkeleton + override fun process(inputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float) { + val headInput = inputSkeleton[BodyPart.HEAD] ?: return if (headInput.isPositionActive || !settings.context.state.value.data.skeletonConfig.toggles.mocapMode) { - return inputSkeleton + return } val travel = when (getWorldReference(fk)) { @@ -117,6 +116,6 @@ class LocalizerFkProcessor(val settings: Settings) : SkeletonFkProcessor { } val newHeadPosition = (headInput.position ?: Vector3.NULL) - travel - return inputSkeleton.mutateCopy { updated -> updated[BodyPart.HEAD] = headInput.copy(position = newHeadPosition) } + inputSkeleton[BodyPart.HEAD] = headInput.copy(position = newHeadPosition) } } 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 3f78905cb..b3e4a3fe6 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 @@ -4,7 +4,6 @@ import dev.slimevr.config.Settings import dev.slimevr.skeleton.ComputedSkeleton import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonFkProcessor -import dev.slimevr.skeleton.mutateCopy import dev.slimevr.tracker.eulerHeading import io.github.axisangles.ktmath.Quaternion import solarxr_protocol.datatypes.BodyPart @@ -50,25 +49,23 @@ fun snapToes( class ToeSnapFkProcessor(val settings: Settings) : SkeletonFkProcessor { val bodyParts: Array = arrayOf(BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT) - override fun process(inputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float): InputSkeleton { - if (!settings.context.state.value.data.skeletonConfig.toggles.toeSnap) return inputSkeleton + override fun process(inputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float) { + if (!settings.context.state.value.data.skeletonConfig.toggles.toeSnap) return - return inputSkeleton.mutateCopy { - // TODO This loop format should be turned into a function - for (bodyPart in bodyParts) { - val input = it[bodyPart] ?: continue - val output = fk[bodyPart] ?: continue - it[bodyPart] = input.copy( - rotation = snapToes( - input.rotation, - computeToeSnapRatio( - output.headPosition.y, - input.offset.len(), - floorLevel, - ), + // TODO This loop format should be turned into a function + for (bodyPart in bodyParts) { + val input = inputSkeleton[bodyPart] ?: continue + val output = fk[bodyPart] ?: continue + inputSkeleton[bodyPart] = input.copy( + rotation = snapToes( + input.rotation, + computeToeSnapRatio( + output.headPosition.y, + input.offset.len(), + floorLevel, ), - ) - } + ), + ) } } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/ik.kt b/server/core/src/main/java/dev/slimevr/skeleton/ik.kt index 233d5df16..104714215 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/ik.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/ik.kt @@ -144,6 +144,9 @@ fun ccdIk( threshold: Float, maxIterations: Int, ): IKOutput { + // No goals leaves every bone as the FK pass built it, so nothing below needs to run + if (goals.isEmpty()) return IKOutput(bones, emptyMap()) + val workingBoneInputs = EnumMap(boneInputs) var boneOutputs = bones diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-active-link.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-active-link.kt index 023a3b8c4..8cb8fbfa5 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-active-link.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-active-link.kt @@ -2,7 +2,6 @@ package dev.slimevr.skeleton.inputprocessors import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor -import dev.slimevr.skeleton.mutateCopy import solarxr_protocol.datatypes.BodyPart /** @@ -23,15 +22,19 @@ class BoneActiveLinkInputProcessor : SkeletonInputProcessor { BodyPart.HIP to arrayOf(BodyPart.WAIST, BodyPart.CHEST, BodyPart.UPPER_CHEST), ) - override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float): InputSkeleton = inputSkeleton.mutateCopy { updated -> + override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float) { for ((bodyPart, sources) in linkedToSources) { val bone = inputSkeleton[bodyPart] ?: continue if (bone.isRotationActive) continue + // Only inactive inputSkeleton are written, so one written here can never become a source below val closestActiveBone = sources.firstNotNullOfOrNull { part -> inputSkeleton[part]?.takeIf { it.isRotationActive } } ?: continue - updated[bodyPart] = bone.copy(rotation = closestActiveBone.rotation) + // Writing back the rotation the bone already carries would only allocate a new BoneInput + if (closestActiveBone.rotation == bone.rotation) continue + + inputSkeleton[bodyPart] = bone.copy(rotation = closestActiveBone.rotation) } } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-direct-link.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-direct-link.kt index 542f1847c..5f982dce2 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-direct-link.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-direct-link.kt @@ -2,7 +2,6 @@ package dev.slimevr.skeleton.inputprocessors import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor -import dev.slimevr.skeleton.mutateCopy import solarxr_protocol.datatypes.BodyPart /** @@ -37,13 +36,16 @@ class BoneDirectLinkInputProcessor : SkeletonInputProcessor { BodyPart.RIGHT_HAND to BodyPart.RIGHT_LOWER_ARM, ) - override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float): InputSkeleton = inputSkeleton.mutateCopy { updated -> + override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float) { for ((bodyPart, source) in linkedToSource) { - val bone = updated[bodyPart] ?: continue + val bone = inputSkeleton[bodyPart] ?: continue if (bone.isRotationActive) continue - val sourceBone = updated[source] - updated[bodyPart] = bone.copy(rotation = sourceBone?.rotation ?: bone.rotation) + val rotation = inputSkeleton[source]?.rotation ?: continue + // Writing back the rotation the bone already carries would only allocate a new BoneInput + if (rotation == bone.rotation) continue + + inputSkeleton[bodyPart] = bone.copy(rotation = rotation) } } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-prediction.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-prediction.kt index 3bf653bdc..76407032c 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-prediction.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-prediction.kt @@ -5,10 +5,16 @@ import dev.slimevr.skeleton.BodyPartMap import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor import dev.slimevr.skeleton.bodyPartMap -import dev.slimevr.skeleton.mapValues +import dev.slimevr.skeleton.forEachBone +import dev.slimevr.util.timeSource import io.github.axisangles.ktmath.Quaternion import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.rpc.FilteringType +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.TimeSource + +/** How far ahead the prediction reaches at amount 1, scaled down by the configured amount */ +val PREDICTION_LEAD = 10.milliseconds /** * Tries to predict future rotations of bones. @@ -17,6 +23,7 @@ class BonePredictionInputProcessor(val settings: Settings) : SkeletonInputProces private data class BoneVelocity( val lastRotation: Quaternion, val rotationDelta: Quaternion, + val lastChange: TimeSource.Monotonic.ValueTimeMark, ) private var velocities: BodyPartMap = bodyPartMap() @@ -33,36 +40,39 @@ class BonePredictionInputProcessor(val settings: Settings) : SkeletonInputProces else -> 1f } - override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float): InputSkeleton { + override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float) { val config = settings.context.state.value.data.skeletonConfig.filtering if (config.type != FilteringType.PREDICTION) { // Drop stale velocities so re-enabling doesn't diff against a long outdated pose if (velocities.isNotEmpty()) velocities.clear() - return inputSkeleton + return } val predictionAmount = config.amount + val now = timeSource.markNow() val newVelocities = bodyPartMap() - val newBones = inputSkeleton.mapValues { bodyPart, bone -> + inputSkeleton.forEachBone { bodyPart, bone -> val prev = velocities[bodyPart] if (prev == null) { - newVelocities[bodyPart] = BoneVelocity(bone.rotation, Quaternion.IDENTITY) - return@mapValues bone + newVelocities[bodyPart] = BoneVelocity(bone.rotation, Quaternion.IDENTITY, now) + return@forEachBone } val bonePredictionAmount = predictionAmount * getMultiplier(bodyPart) - val rotationDelta = if (bone.rotation !== prev.lastRotation) { - bone.rotation * prev.lastRotation.inv() + val changed = bone.rotation !== prev.lastRotation + val rotationDelta = if (changed) { + val leadScale = (PREDICTION_LEAD / (now - prev.lastChange)).toFloat() + Quaternion.IDENTITY.lerpR(bone.rotation * prev.lastRotation.inv(), leadScale).unit() } else { prev.rotationDelta } - newVelocities[bodyPart] = BoneVelocity(bone.rotation, rotationDelta) + newVelocities[bodyPart] = BoneVelocity(bone.rotation, rotationDelta, if (changed) now else prev.lastChange) val scaledDelta = Quaternion.IDENTITY.lerpR(rotationDelta, bonePredictionAmount).unit() - bone.copy(rotation = (scaledDelta * bone.rotation).unit()) + val predicted = (scaledDelta * bone.rotation).unit() + if (predicted != bone.rotation) inputSkeleton[bodyPart] = bone.copy(rotation = predicted) } velocities = newVelocities - return newBones } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-smoothing.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-smoothing.kt index 10082119b..ef3c61cfd 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-smoothing.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-smoothing.kt @@ -5,7 +5,7 @@ import dev.slimevr.skeleton.BodyPartMap import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor import dev.slimevr.skeleton.bodyPartMap -import dev.slimevr.skeleton.mapValues +import dev.slimevr.skeleton.forEachBone import dev.slimevr.util.inFloatingSeconds import dev.slimevr.util.timeSource import io.github.axisangles.ktmath.Quaternion @@ -19,13 +19,13 @@ class BoneSmoothingInputProcessor(val settings: Settings) : SkeletonInputProcess private var lastProcessTime = timeSource.markNow() // TODO this isn't linear. Do we want linear smoothing like in main? - override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float): InputSkeleton { + override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float) { val config = settings.context.state.value.data.skeletonConfig.filtering if (config.type != FilteringType.SMOOTHING) { // Drop stale poses so re-enabling doesn't blend out of an outdated frame if (smoothed.isNotEmpty()) smoothed.clear() lastProcessTime = timeSource.markNow() - return inputSkeleton + return } // Normalize with frame time @@ -36,14 +36,13 @@ class BoneSmoothingInputProcessor(val settings: Settings) : SkeletonInputProcess val alpha = ((1 - smoothingAmount) * lastFrameTimeSeconds * SMOOTHING_MULTIPLIER).coerceIn(0f, 1f) val newSmoothed = bodyPartMap() - val newBones = inputSkeleton.mapValues { bodyPart, bone -> + inputSkeleton.forEachBone { bodyPart, bone -> val prev = smoothed[bodyPart] ?: bone.rotation val rotation = prev.lerpR(bone.rotation, alpha).unit() newSmoothed[bodyPart] = rotation - bone.copy(rotation = rotation) + if (rotation != bone.rotation) inputSkeleton[bodyPart] = bone.copy(rotation = rotation) } smoothed = newSmoothed - return newBones } companion object { diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-yaw-fallback.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-yaw-fallback.kt index 67d432c16..d23830d6d 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-yaw-fallback.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/bone-yaw-fallback.kt @@ -4,7 +4,6 @@ import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor import dev.slimevr.skeleton.forEachBone import dev.slimevr.skeleton.iterateBodyPartHierarchy -import dev.slimevr.skeleton.mutateCopy import io.github.axisangles.ktmath.Vector3 import kotlin.collections.set @@ -13,16 +12,20 @@ import kotlin.collections.set * falling back to their parent's yaw. */ class BoneYawFallbackInputProcessor : SkeletonInputProcessor { - override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float): InputSkeleton = inputSkeleton.mutateCopy { updated -> + override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float) { inputSkeleton.forEachBone { parentPart, parentBone -> if (!parentBone.isRotationActive) return@forEachBone // Parent needs to be active val children = iterateBodyPartHierarchy(parentPart, true) + // Depends only on the parent, so every child below reuses it + val yaw = parentBone.rotation.project(Vector3.POS_Y).unit() for (childPart in children) { val childBone = inputSkeleton[childPart.second] ?: continue if (childBone.isRotationActive) continue // Child needs to be inactive + // Writing back the rotation the bone already carries would only allocate a new BoneInput + if (yaw == childBone.rotation) continue - updated[childPart.second] = childBone.copy(rotation = parentBone.rotation.project(Vector3.POS_Y).unit()) + inputSkeleton[childPart.second] = childBone.copy(rotation = yaw) } } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/finger-impute.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/finger-impute.kt index eae82d834..f7f0d9dd1 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/finger-impute.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/finger-impute.kt @@ -2,7 +2,6 @@ package dev.slimevr.skeleton.inputprocessors import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor -import dev.slimevr.skeleton.mutateCopy import solarxr_protocol.datatypes.BodyPart /** @@ -48,13 +47,16 @@ class FingerImputeInputProcessor : SkeletonInputProcessor { ) // TODO : There's more math to do here. Reference the original code. - override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float): InputSkeleton = inputSkeleton.mutateCopy { updated -> + override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float) { for ((bodyPart, source) in fingerToSource) { - val bone = updated[bodyPart] ?: continue + val bone = inputSkeleton[bodyPart] ?: continue if (bone.isRotationActive) continue - val sourceBone = updated[source] - updated[bodyPart] = bone.copy(rotation = sourceBone?.rotation ?: bone.rotation) + val rotation = inputSkeleton[source]?.rotation ?: continue + // Writing back the rotation the bone already carries would only allocate a new BoneInput + if (rotation == bone.rotation) continue + + inputSkeleton[bodyPart] = bone.copy(rotation = rotation) } } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/head-position-fallback.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/head-position-fallback.kt index d4f94417d..44521b24d 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/head-position-fallback.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/head-position-fallback.kt @@ -3,7 +3,6 @@ package dev.slimevr.skeleton.inputprocessors import dev.slimevr.config.Settings import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor -import dev.slimevr.skeleton.mutateCopy import io.github.axisangles.ktmath.Vector3 import solarxr_protocol.datatypes.BodyPart @@ -11,11 +10,11 @@ import solarxr_protocol.datatypes.BodyPart * Moves the head input to the skeleton height. Else, it would default to (0, 0, 0). */ class HeadPositionFallbackProcessor(val settings: Settings) : SkeletonInputProcessor { - override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float): InputSkeleton { - val headBone = inputSkeleton[BodyPart.HEAD] ?: return inputSkeleton - if (headBone.position != null) return inputSkeleton + override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float) { + val headBone = inputSkeleton[BodyPart.HEAD] ?: return + if (headBone.position != null) return // Set the head position to the be standing up at the origin - return inputSkeleton.mutateCopy { it[BodyPart.HEAD] = headBone.copy(position = Vector3(0f, skeletonHeight, 0f)) } + inputSkeleton[BodyPart.HEAD] = headBone.copy(position = Vector3(0f, skeletonHeight, 0f)) } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/hip-yaw-roll-align.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/hip-yaw-roll-align.kt index efc7105d2..b9a833ce0 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/hip-yaw-roll-align.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/hip-yaw-roll-align.kt @@ -3,7 +3,6 @@ package dev.slimevr.skeleton.inputprocessors import dev.slimevr.config.Settings import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor -import dev.slimevr.skeleton.mutateCopy import io.github.axisangles.ktmath.Quaternion import solarxr_protocol.datatypes.BodyPart @@ -11,18 +10,16 @@ import solarxr_protocol.datatypes.BodyPart * Handles rotating the hip' yaw and roll to match the upper legs' yaw and roll. */ class HipYawRollAlignInputProcessor(val settings: Settings) : SkeletonInputProcessor { - override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float): InputSkeleton { - val hipBone = inputSkeleton[BodyPart.HIP] ?: return inputSkeleton - if (hipBone.isRotationActive) return inputSkeleton - val leftUpperLegBone = inputSkeleton[BodyPart.LEFT_UPPER_LEG] ?: return inputSkeleton - val rightUpperLegBone = inputSkeleton[BodyPart.RIGHT_UPPER_LEG] ?: return inputSkeleton + override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float) { + val hipBone = inputSkeleton[BodyPart.HIP] ?: return + if (hipBone.isRotationActive) return + val leftUpperLegBone = inputSkeleton[BodyPart.LEFT_UPPER_LEG] ?: return + val rightUpperLegBone = inputSkeleton[BodyPart.RIGHT_UPPER_LEG] ?: return - return inputSkeleton.mutateCopy { updated -> - val ratio = settings.context.state.value.data.skeletonConfig.ratios.interpolateHipWithUpperLegs - val sourceRotation = leftUpperLegBone.rotation.lerpQ(rightUpperLegBone.rotation, 0.5f) - val alignedRotation = alignYawRoll(hipBone.rotation, sourceRotation) - updated[BodyPart.HIP] = hipBone.copy(rotation = hipBone.rotation.interpQ(alignedRotation, ratio)) - } + val ratio = settings.context.state.value.data.skeletonConfig.ratios.interpolateHipWithUpperLegs + val sourceRotation = leftUpperLegBone.rotation.lerpQ(rightUpperLegBone.rotation, 0.5f) + val alignedRotation = alignYawRoll(hipBone.rotation, sourceRotation) + inputSkeleton[BodyPart.HIP] = hipBone.copy(rotation = hipBone.rotation.interpQ(alignedRotation, ratio)) } /** diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/spine-impute.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/spine-impute.kt index ec448758b..96e3b38b5 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/spine-impute.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/spine-impute.kt @@ -1,10 +1,8 @@ package dev.slimevr.skeleton.inputprocessors import dev.slimevr.config.Settings -import dev.slimevr.skeleton.BoneInput import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor -import dev.slimevr.skeleton.mutateCopy import io.github.axisangles.ktmath.Quaternion import solarxr_protocol.datatypes.BodyPart @@ -38,7 +36,7 @@ class SpineImputeInputProcessor(val settings: Settings) : SkeletonInputProcessor else -> error("Invalid missing spine body part $bodyPart") } - override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float): InputSkeleton { + override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float) { val ratios = settings.context.state.value.data.skeletonConfig.ratios val hasChest = inputSkeleton[BodyPart.UPPER_CHEST]?.isRotationActive == true || inputSkeleton[BodyPart.CHEST]?.isRotationActive == true @@ -50,49 +48,47 @@ class SpineImputeInputProcessor(val settings: Settings) : SkeletonInputProcessor if (!hasHip) add(BodyPart.HIP) } - return inputSkeleton.mutateCopy { updated -> - for ((chainIndex, bodyPart) in missingSpineParts.withIndex()) { - val bone = inputSkeleton[bodyPart] ?: continue + for ((chainIndex, bodyPart) in missingSpineParts.withIndex()) { + val bone = inputSkeleton[bodyPart] ?: continue - // Get the first active bones above and below this one in the chain - val (fromSource, toSource) = when (bodyPart) { - BodyPart.WAIST -> { - val from = SpineSource.CHEST.takeIf { hasChest } ?: continue - val to = when { - hasHip -> SpineSource.HIP - hasUpperLegs -> SpineSource.UPPER_LEGS - else -> continue - } - from to to + // Get the first active inputSkeleton above and below this one in the chain + val (fromSource, toSource) = when (bodyPart) { + BodyPart.WAIST -> { + val from = SpineSource.CHEST.takeIf { hasChest } ?: continue + val to = when { + hasHip -> SpineSource.HIP + hasUpperLegs -> SpineSource.UPPER_LEGS + else -> continue } - - BodyPart.HIP -> { - val from = when { - hasWaist -> SpineSource.WAIST - hasChest -> SpineSource.CHEST - else -> continue - } - val to = SpineSource.UPPER_LEGS.takeIf { hasUpperLegs } ?: continue - from to to - } - - else -> error("Invalid missing spine body part $bodyPart") + from to to } - val interpolateRatio = interpolateRatio( - chainIndex, - missingSpineParts.size, - ratios.imputeSpineFromUpperToLower, - ratios.imputeSpineCurvature, - reliabilityOf(bodyPart, fromSource), - reliabilityOf(bodyPart, toSource), - ) + BodyPart.HIP -> { + val from = when { + hasWaist -> SpineSource.WAIST + hasChest -> SpineSource.CHEST + else -> continue + } + val to = SpineSource.UPPER_LEGS.takeIf { hasUpperLegs } ?: continue + from to to + } - val fromRotation = averageRotation(inputSkeleton, fromSource.parts) - val toRotation = averageRotation(inputSkeleton, toSource.parts) - - updated[bodyPart] = bone.copy(rotation = fromRotation.interpQ(toRotation, interpolateRatio)) + else -> error("Invalid missing spine body part $bodyPart") } + + val interpolateRatio = interpolateRatio( + chainIndex, + missingSpineParts.size, + ratios.imputeSpineFromUpperToLower, + ratios.imputeSpineCurvature, + reliabilityOf(bodyPart, fromSource), + reliabilityOf(bodyPart, toSource), + ) + + val fromRotation = averageRotation(inputSkeleton, fromSource.parts) + val toRotation = averageRotation(inputSkeleton, toSource.parts) + + inputSkeleton[bodyPart] = bone.copy(rotation = fromRotation.interpQ(toRotation, interpolateRatio)) } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/toe-direct-link-input-processor.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/toe-direct-link-input-processor.kt index 3222271dd..c07453953 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/toe-direct-link-input-processor.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/toe-direct-link-input-processor.kt @@ -2,7 +2,6 @@ package dev.slimevr.skeleton.inputprocessors import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor -import dev.slimevr.skeleton.mutateCopy import solarxr_protocol.datatypes.BodyPart /** @@ -28,13 +27,16 @@ class ToeDirectLinkInputProcessor : SkeletonInputProcessor { BodyPart.RIGHT_LITTLE_TOE to BodyPart.RIGHT_RING_TOE, ) - override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float): InputSkeleton = inputSkeleton.mutateCopy { updated -> + override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float) { for ((bodyPart, source) in toesToSource) { - val bone = updated[bodyPart] ?: continue + val bone = inputSkeleton[bodyPart] ?: continue if (bone.isRotationActive) continue - val sourceBone = updated[source] - updated[bodyPart] = - bone.copy(rotation = sourceBone?.rotation ?: bone.rotation) + + val rotation = inputSkeleton[source]?.rotation ?: continue + // Writing back the rotation the bone already carries would only allocate a new BoneInput + if (rotation == bone.rotation) continue + + inputSkeleton[bodyPart] = bone.copy(rotation = rotation) } } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/upper-legs-roll-align.kt b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/upper-legs-roll-align.kt index d97990f99..6d86f542c 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/upper-legs-roll-align.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/inputprocessors/upper-legs-roll-align.kt @@ -3,7 +3,6 @@ package dev.slimevr.skeleton.inputprocessors import dev.slimevr.config.Settings import dev.slimevr.skeleton.InputSkeleton import dev.slimevr.skeleton.SkeletonInputProcessor -import dev.slimevr.skeleton.mutateCopy import io.github.axisangles.ktmath.Quaternion import solarxr_protocol.datatypes.BodyPart @@ -21,19 +20,18 @@ class UpperLegsRollAlignInputProcessor(val settings: Settings) : SkeletonInputPr BodyPart.RIGHT_UPPER_LEG to BodyPart.RIGHT_LOWER_LEG, ) - override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float): InputSkeleton { + override fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float) { val ratio = settings.context.state.value.data.skeletonConfig.ratios.interpolateUpperLegsTwistWithLowerLegs - if (ratio == 0f) return inputSkeleton + if (ratio == 0f) return - return inputSkeleton.mutateCopy { updated -> - for (bodyPartToSource in bodyPartToSources) { - val bone = inputSkeleton[bodyPartToSource.first] ?: continue - if (!bone.isRotationActive) continue + // Upper legs are written, lower legs are read, so the two never overlap + for (bodyPartToSource in bodyPartToSources) { + val bone = inputSkeleton[bodyPartToSource.first] ?: continue + if (!bone.isRotationActive) continue - val sourceRotation = inputSkeleton[bodyPartToSource.second]?.rotation ?: continue - val alignedRotation = alignRoll(bone.rotation, sourceRotation) - updated[bodyPartToSource.first] = bone.copy(rotation = bone.rotation.interpQ(alignedRotation, ratio)) - } + val sourceRotation = inputSkeleton[bodyPartToSource.second]?.rotation ?: continue + val alignedRotation = alignRoll(bone.rotation, sourceRotation) + inputSkeleton[bodyPartToSource.first] = bone.copy(rotation = bone.rotation.interpQ(alignedRotation, ratio)) } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/module.kt b/server/core/src/main/java/dev/slimevr/skeleton/module.kt index 8c6d99382..680535c65 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/module.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/module.kt @@ -20,9 +20,12 @@ import dev.slimevr.skeleton.inputprocessors.UpperLegsRollAlignInputProcessor import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.MutableSharedFlow import solarxr_protocol.datatypes.BodyPart +import java.util.concurrent.Executors import solarxr_protocol.rpc.SkeletonBone data class BoneInput( @@ -48,18 +51,23 @@ data class BoneState( val angularVelocity: Vector3, val linearVelocity: Vector3, ) { - private val orientationOffset = when { - offset.len() == 0f -> Quaternion.IDENTITY - offset.unit().y == 1f -> Quaternion.I - else -> Quaternion.fromTo(Vector3.NEG_Y, offset) - } - val orientation: Quaternion = rotation * orientationOffset + // FK rebuilds most of the skeleton every frame, so anything read less often than that is + // computed on demand rather than per bone + private val orientationOffset: Quaternion + get() = when { + offset.len() == 0f -> Quaternion.IDENTITY + offset.unit().y == 1f -> Quaternion.I + else -> Quaternion.fromTo(Vector3.NEG_Y, offset) + } + val orientation: Quaternion + get() = rotation * orientationOffset val localRotation: Quaternion get() = parentBone?.let { it.rotation.inv() * rotation } ?: rotation val localHeadPosition: Vector3 get() = parentBone?.let { headPosition - it.tailPosition } ?: headPosition - val localTailPosition = tailPosition - headPosition + val localTailPosition: Vector3 + get() = tailPosition - headPosition } typealias InputSkeleton = BodyPartMap @@ -141,10 +149,10 @@ sealed interface SkeletonActions { typealias SkeletonContext = Context typealias SkeletonBehaviour = Behaviour interface SkeletonInputProcessor { - fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float): InputSkeleton + fun process(inputSkeleton: InputSkeleton, skeletonHeight: Float) } interface SkeletonFkProcessor { - fun process(inputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float): InputSkeleton + fun process(inputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float) } typealias IKTargets = BodyPartMap interface SkeletonTargetProcessor { @@ -164,6 +172,14 @@ class Skeleton( const val DEFAULT_HZ = 500 fun create(scope: CoroutineScope, ctx: Phase1ContextProvider, hz: Int = DEFAULT_HZ): Skeleton { + // The tick loop parks its thread to hit its interval, so the module gets a thread of its + // own rather than holding up whatever else shares the caller's dispatcher + val dispatcher = Executors.newSingleThreadExecutor { runnable -> + Thread(runnable, "Skeleton").apply { isDaemon = true } + }.asCoroutineDispatcher() + scope.coroutineContext[Job]?.invokeOnCompletion { dispatcher.close() } + val moduleScope = CoroutineScope(scope.coroutineContext + dispatcher) + val settings = ctx.config.settings val behaviours = listOf( ProportionsBehaviour(ctx.config.userConfig), @@ -199,7 +215,7 @@ class Skeleton( val context = Context.create( initialState = DEFAULT_SKELETON_STATE, - scope = scope, + scope = moduleScope, reducer = ::reduce, behaviours = behaviours, name = "Skeleton", diff --git a/server/core/src/test/java/dev/slimevr/skeleton/ToeDirectLinkProcessorTest.kt b/server/core/src/test/java/dev/slimevr/skeleton/ToeDirectLinkProcessorTest.kt index 47acbd09d..5909f3ef0 100644 --- a/server/core/src/test/java/dev/slimevr/skeleton/ToeDirectLinkProcessorTest.kt +++ b/server/core/src/test/java/dev/slimevr/skeleton/ToeDirectLinkProcessorTest.kt @@ -29,29 +29,29 @@ class ToeDirectLinkProcessorTest { pausedProcessedBoneInputs = inputs, ) - val newInputs = processor.process(state.boneInputs, state.skeletonHeight) + processor.process(inputs, state.skeletonHeight) val leftBigToeIsSameRotationAsLeftFoot = - newInputs[BodyPart.LEFT_BIG_TOE]?.rotation == newInputs[BodyPart.LEFT_FOOT]?.rotation + inputs[BodyPart.LEFT_BIG_TOE]?.rotation == inputs[BodyPart.LEFT_FOOT]?.rotation val leftIndexToeIsSameRotationAsLeftBigToe = - newInputs[BodyPart.LEFT_INDEX_TOE]?.rotation == newInputs[BodyPart.LEFT_BIG_TOE]?.rotation + inputs[BodyPart.LEFT_INDEX_TOE]?.rotation == inputs[BodyPart.LEFT_BIG_TOE]?.rotation val leftMiddleToeIsSameRotationAsLeftIndexToe = - newInputs[BodyPart.LEFT_MIDDLE_TOE]?.rotation == newInputs[BodyPart.LEFT_INDEX_TOE]?.rotation + inputs[BodyPart.LEFT_MIDDLE_TOE]?.rotation == inputs[BodyPart.LEFT_INDEX_TOE]?.rotation val leftRingToeIsSameRotationAsLeftMiddleToe = - newInputs[BodyPart.LEFT_RING_TOE]?.rotation == newInputs[BodyPart.LEFT_MIDDLE_TOE]?.rotation + inputs[BodyPart.LEFT_RING_TOE]?.rotation == inputs[BodyPart.LEFT_MIDDLE_TOE]?.rotation val leftLittleToeIsSameRotationAsLeftRingToe = - newInputs[BodyPart.LEFT_LITTLE_TOE]?.rotation == newInputs[BodyPart.LEFT_RING_TOE]?.rotation + inputs[BodyPart.LEFT_LITTLE_TOE]?.rotation == inputs[BodyPart.LEFT_RING_TOE]?.rotation val rightBigToeIsSameRotationAsRightFoot = - newInputs[BodyPart.RIGHT_BIG_TOE]?.rotation == newInputs[BodyPart.RIGHT_FOOT]?.rotation + inputs[BodyPart.RIGHT_BIG_TOE]?.rotation == inputs[BodyPart.RIGHT_FOOT]?.rotation val rightIndexToeIsSameRotationAsRightBigToe = - newInputs[BodyPart.RIGHT_INDEX_TOE]?.rotation == newInputs[BodyPart.RIGHT_BIG_TOE]?.rotation + inputs[BodyPart.RIGHT_INDEX_TOE]?.rotation == inputs[BodyPart.RIGHT_BIG_TOE]?.rotation val rightMiddleToeIsSameRotationAsRightIndexToe = - newInputs[BodyPart.RIGHT_MIDDLE_TOE]?.rotation == newInputs[BodyPart.RIGHT_INDEX_TOE]?.rotation + inputs[BodyPart.RIGHT_MIDDLE_TOE]?.rotation == inputs[BodyPart.RIGHT_INDEX_TOE]?.rotation val rightRingToeIsSameRotationAsRightMiddleToe = - newInputs[BodyPart.RIGHT_RING_TOE]?.rotation == newInputs[BodyPart.RIGHT_MIDDLE_TOE]?.rotation + inputs[BodyPart.RIGHT_RING_TOE]?.rotation == inputs[BodyPart.RIGHT_MIDDLE_TOE]?.rotation val rightLittleToeIsSameRotationAsRightRingToe = - newInputs[BodyPart.RIGHT_LITTLE_TOE]?.rotation == newInputs[BodyPart.RIGHT_RING_TOE]?.rotation + inputs[BodyPart.RIGHT_LITTLE_TOE]?.rotation == inputs[BodyPart.RIGHT_RING_TOE]?.rotation assertTrue( leftBigToeIsSameRotationAsLeftFoot && @@ -99,25 +99,25 @@ class ToeDirectLinkProcessorTest { pausedProcessedBoneInputs = inputs, ) - val newInputs = processor.process(state.boneInputs, state.skeletonHeight) + processor.process(inputs, state.skeletonHeight) val leftIndexToeIsSameRotationAsLeftBigToe = - newInputs[BodyPart.LEFT_INDEX_TOE]?.rotation == newInputs[BodyPart.LEFT_BIG_TOE]?.rotation + inputs[BodyPart.LEFT_INDEX_TOE]?.rotation == inputs[BodyPart.LEFT_BIG_TOE]?.rotation val leftMiddleToeIsSameRotationAsLeftIndexToe = - newInputs[BodyPart.LEFT_MIDDLE_TOE]?.rotation == newInputs[BodyPart.LEFT_INDEX_TOE]?.rotation + inputs[BodyPart.LEFT_MIDDLE_TOE]?.rotation == inputs[BodyPart.LEFT_INDEX_TOE]?.rotation val leftRingToeIsSameRotationAsLeftMiddleToe = - newInputs[BodyPart.LEFT_RING_TOE]?.rotation == newInputs[BodyPart.LEFT_MIDDLE_TOE]?.rotation + inputs[BodyPart.LEFT_RING_TOE]?.rotation == inputs[BodyPart.LEFT_MIDDLE_TOE]?.rotation val leftLittleToeIsSameRotationAsLeftRingToe = - newInputs[BodyPart.LEFT_LITTLE_TOE]?.rotation == newInputs[BodyPart.LEFT_RING_TOE]?.rotation + inputs[BodyPart.LEFT_LITTLE_TOE]?.rotation == inputs[BodyPart.LEFT_RING_TOE]?.rotation val rightIndexToeIsSameRotationAsRightBigToe = - newInputs[BodyPart.RIGHT_INDEX_TOE]?.rotation == newInputs[BodyPart.RIGHT_BIG_TOE]?.rotation + inputs[BodyPart.RIGHT_INDEX_TOE]?.rotation == inputs[BodyPart.RIGHT_BIG_TOE]?.rotation val rightMiddleToeIsSameRotationAsRightIndexToe = - newInputs[BodyPart.RIGHT_MIDDLE_TOE]?.rotation == newInputs[BodyPart.RIGHT_INDEX_TOE]?.rotation + inputs[BodyPart.RIGHT_MIDDLE_TOE]?.rotation == inputs[BodyPart.RIGHT_INDEX_TOE]?.rotation val rightRingToeIsSameRotationAsRightMiddleToe = - newInputs[BodyPart.RIGHT_RING_TOE]?.rotation == newInputs[BodyPart.RIGHT_MIDDLE_TOE]?.rotation + inputs[BodyPart.RIGHT_RING_TOE]?.rotation == inputs[BodyPart.RIGHT_MIDDLE_TOE]?.rotation val rightLittleToeIsSameRotationAsRightRingToe = - newInputs[BodyPart.RIGHT_LITTLE_TOE]?.rotation == newInputs[BodyPart.RIGHT_RING_TOE]?.rotation + inputs[BodyPart.RIGHT_LITTLE_TOE]?.rotation == inputs[BodyPart.RIGHT_RING_TOE]?.rotation assertTrue( leftIndexToeIsSameRotationAsLeftBigToe && @@ -172,21 +172,21 @@ class ToeDirectLinkProcessorTest { pausedProcessedBoneInputs = inputs, ) - val newInputs = processor.process(state.boneInputs, state.skeletonHeight) + processor.process(inputs, state.skeletonHeight) val leftMiddleToeIsSameRotationAsLeftIndexToe = - newInputs[BodyPart.LEFT_MIDDLE_TOE]?.rotation == newInputs[BodyPart.LEFT_INDEX_TOE]?.rotation + inputs[BodyPart.LEFT_MIDDLE_TOE]?.rotation == inputs[BodyPart.LEFT_INDEX_TOE]?.rotation val leftRingToeIsSameRotationAsLeftMiddleToe = - newInputs[BodyPart.LEFT_RING_TOE]?.rotation == newInputs[BodyPart.LEFT_MIDDLE_TOE]?.rotation + inputs[BodyPart.LEFT_RING_TOE]?.rotation == inputs[BodyPart.LEFT_MIDDLE_TOE]?.rotation val leftLittleToeIsSameRotationAsLeftRingToe = - newInputs[BodyPart.LEFT_LITTLE_TOE]?.rotation == newInputs[BodyPart.LEFT_RING_TOE]?.rotation + inputs[BodyPart.LEFT_LITTLE_TOE]?.rotation == inputs[BodyPart.LEFT_RING_TOE]?.rotation val rightMiddleToeIsSameRotationAsRightIndexToe = - newInputs[BodyPart.RIGHT_MIDDLE_TOE]?.rotation == newInputs[BodyPart.RIGHT_INDEX_TOE]?.rotation + inputs[BodyPart.RIGHT_MIDDLE_TOE]?.rotation == inputs[BodyPart.RIGHT_INDEX_TOE]?.rotation val rightRingToeIsSameRotationAsRightMiddleToe = - newInputs[BodyPart.RIGHT_RING_TOE]?.rotation == newInputs[BodyPart.RIGHT_MIDDLE_TOE]?.rotation + inputs[BodyPart.RIGHT_RING_TOE]?.rotation == inputs[BodyPart.RIGHT_MIDDLE_TOE]?.rotation val rightLittleToeIsSameRotationAsRightRingToe = - newInputs[BodyPart.RIGHT_LITTLE_TOE]?.rotation == newInputs[BodyPart.RIGHT_RING_TOE]?.rotation + inputs[BodyPart.RIGHT_LITTLE_TOE]?.rotation == inputs[BodyPart.RIGHT_RING_TOE]?.rotation assertTrue( leftMiddleToeIsSameRotationAsLeftIndexToe && @@ -247,17 +247,17 @@ class ToeDirectLinkProcessorTest { pausedProcessedBoneInputs = inputs, ) - val newInputs = processor.process(state.boneInputs, state.skeletonHeight) + processor.process(inputs, state.skeletonHeight) val leftRingToeIsSameRotationAsLeftMiddleToe = - newInputs[BodyPart.LEFT_RING_TOE]?.rotation == newInputs[BodyPart.LEFT_MIDDLE_TOE]?.rotation + inputs[BodyPart.LEFT_RING_TOE]?.rotation == inputs[BodyPart.LEFT_MIDDLE_TOE]?.rotation val leftLittleToeIsSameRotationAsLeftRingToe = - newInputs[BodyPart.LEFT_LITTLE_TOE]?.rotation == newInputs[BodyPart.LEFT_RING_TOE]?.rotation + inputs[BodyPart.LEFT_LITTLE_TOE]?.rotation == inputs[BodyPart.LEFT_RING_TOE]?.rotation val rightRingToeIsSameRotationAsRightMiddleToe = - newInputs[BodyPart.RIGHT_RING_TOE]?.rotation == newInputs[BodyPart.RIGHT_MIDDLE_TOE]?.rotation + inputs[BodyPart.RIGHT_RING_TOE]?.rotation == inputs[BodyPart.RIGHT_MIDDLE_TOE]?.rotation val rightLittleToeIsSameRotationAsRightRingToe = - newInputs[BodyPart.RIGHT_LITTLE_TOE]?.rotation == newInputs[BodyPart.RIGHT_RING_TOE]?.rotation + inputs[BodyPart.RIGHT_LITTLE_TOE]?.rotation == inputs[BodyPart.RIGHT_RING_TOE]?.rotation assertTrue(leftRingToeIsSameRotationAsLeftMiddleToe && leftLittleToeIsSameRotationAsLeftRingToe) assertTrue(rightRingToeIsSameRotationAsRightMiddleToe && rightLittleToeIsSameRotationAsRightRingToe) @@ -318,12 +318,12 @@ class ToeDirectLinkProcessorTest { pausedProcessedBoneInputs = inputs, ) - val newInputs = processor.process(state.boneInputs, state.skeletonHeight) + processor.process(inputs, state.skeletonHeight) val leftLittleToeIsSameRotationAsLeftRingToe = - newInputs[BodyPart.LEFT_LITTLE_TOE]?.rotation == newInputs[BodyPart.LEFT_RING_TOE]?.rotation + inputs[BodyPart.LEFT_LITTLE_TOE]?.rotation == inputs[BodyPart.LEFT_RING_TOE]?.rotation val rightLittleToeIsSameRotationAsRightRingToe = - newInputs[BodyPart.RIGHT_LITTLE_TOE]?.rotation == newInputs[BodyPart.RIGHT_RING_TOE]?.rotation + inputs[BodyPart.RIGHT_LITTLE_TOE]?.rotation == inputs[BodyPart.RIGHT_RING_TOE]?.rotation assertTrue(leftLittleToeIsSameRotationAsLeftRingToe && rightLittleToeIsSameRotationAsRightRingToe) } diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/hid/hid.kt b/server/desktop/src/main/java/dev/slimevr/desktop/hid/hid.kt index 069da415a..bf7452b1b 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/hid/hid.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/hid/hid.kt @@ -8,6 +8,8 @@ import dev.slimevr.hid.hidVendorIds import dev.slimevr.hid.isCompatibleHidReceiver import dev.slimevr.hid.isCompatibleHidTracker import dev.slimevr.hid.runHidManager +import dev.slimevr.logging.AppLogger +import dev.slimevr.util.timeSource import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -18,6 +20,9 @@ import kotlinx.coroutines.withContext import org.hid4java.jna.HidApi import org.hid4java.jna.HidDeviceInfoStructure import org.hid4java.jna.HidDeviceStructure +import org.hid4java.jna.HidrawHidApiLibrary +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds private val hidLibLock = Any() private var hidLibInitialized = false @@ -67,6 +72,16 @@ private fun enumerateHidDevices(directTrackersEnabled: Boolean): Map= 0 || !wasInterrupted(struct)) break + + // hidapi's poll() has no EINTR retry, so any signal delivered to this thread, like a + // sampling profiler's, surfaces as a device error. Spend what is left of the + // caller's timeout instead, so only a real fault is reported as one + val left = -deadline.elapsedNow() + if (left <= Duration.ZERO) { + result = 0 + break + } + budgetMs = left.inWholeMilliseconds.toInt().coerceAtLeast(1) + } + if (result < 0 && !closed) AppLogger.hid.warn("HID read error: ${lastError(struct)}") + result } override suspend fun write(data: ByteArray): Int = writeLock.withLock { diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/trackingchecklist/behaviours.kt b/server/desktop/src/main/java/dev/slimevr/desktop/trackingchecklist/behaviours.kt index 269ec1d9a..a54ac6d9b 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/trackingchecklist/behaviours.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/trackingchecklist/behaviours.kt @@ -40,58 +40,54 @@ import kotlin.time.Duration.Companion.seconds data class Process(val pid: ULong, val name: String) -private suspend fun getRunningProcesses(): List = when (CURRENT_PLATFORM) { - Platform.LINUX -> buildList { - val psProc = try { - ProcessBuilder("ps", "-eo", "pid,comm").redirectErrorStream(true).start() - } catch (_: IOException) { - return@buildList - } - - val lines = withContext(Dispatchers.IO) { psProc.inputStream.bufferedReader().readLines() } - // skip the header - for (line in lines.slice(1 until lines.size)) { - val data = line.trimStart().split(' ') - add(Process(data[0].toULong(), data[1])) - } - } - - Platform.WINDOWS -> buildList { - val k32 = Kernel32.INSTANCE - val snapshot = k32.CreateToolhelp32Snapshot( - Tlhelp32.TH32CS_SNAPPROCESS, - WinDef.DWORD(0), - ) - if (WinBase.INVALID_HANDLE_VALUE.equals(snapshot)) { - return@buildList - } - - try { - val entry = Tlhelp32.PROCESSENTRY32() - if (!k32.Process32First(snapshot, entry)) { - val err = k32.GetLastError() - AppLogger.checklist.warn("Failed to retrieve process information: ${Kernel32Util.formatMessage(err)} (code $err)") +private suspend fun getRunningProcesses(): List = withContext(Dispatchers.IO) { + when (CURRENT_PLATFORM) { + Platform.LINUX -> buildList { + val psProc = try { + ProcessBuilder("ps", "-eo", "pid,comm").redirectErrorStream(true).start() + } catch (_: IOException) { return@buildList } - do { - add(Process(entry.th32ProcessID.toLong().toULong(), Native.toString(entry.szExeFile))) - } while (k32.Process32Next(snapshot, entry)) - } finally { - k32.CloseHandle(snapshot) + val lines = psProc.inputStream.bufferedReader().readLines() + // skip the header + for (line in lines.slice(1 until lines.size)) { + val data = line.trimStart().split(' ') + add(Process(data[0].toULong(), data[1])) + } } - } - else -> emptyList() + Platform.WINDOWS -> buildList { + val k32 = Kernel32.INSTANCE + val snapshot = k32.CreateToolhelp32Snapshot( + Tlhelp32.TH32CS_SNAPPROCESS, + WinDef.DWORD(0), + ) + if (WinBase.INVALID_HANDLE_VALUE.equals(snapshot)) { + return@buildList + } + + try { + val entry = Tlhelp32.PROCESSENTRY32() + if (!k32.Process32First(snapshot, entry)) { + val err = k32.GetLastError() + AppLogger.checklist.warn("Failed to retrieve process information: ${Kernel32Util.formatMessage(err)} (code $err)") + return@buildList + } + + do { + add(Process(entry.th32ProcessID.toLong().toULong(), Native.toString(entry.szExeFile))) + } while (k32.Process32Next(snapshot, entry)) + } finally { + k32.CloseHandle(snapshot) + } + } + + else -> emptyList() + } } -// Enumerating every process is orders of magnitude costlier than the loopback request it guards, so it -// only runs to disambiguate a refused connection, and only this often. -private val PROCESS_SCAN_INTERVAL = 10.seconds - -private fun Throwable.isConnectionRefused(): Boolean = generateSequence(this, Throwable::cause).any { it is ConnectException } - -private inline fun buildSteamVRDriverStep(driverEnabled: Boolean = true, connected: Boolean = false, installed: Boolean = true, blocked: Boolean = false, enabledInSteamVR: Boolean = true) = TrackingChecklistStep( +private fun buildSteamVRDriverStep(driverEnabled: Boolean = true, connected: Boolean = false, installed: Boolean = true, blocked: Boolean = false, enabledInSteamVR: Boolean = true) = TrackingChecklistStep( valid = connected, enabled = driverEnabled, ignorable = true, @@ -105,7 +101,7 @@ private inline fun buildSteamVRDriverStep(driverEnabled: Boolean = true, connect null }, ) -private inline fun buildStandableStep(supported: Boolean = true, installed: Boolean = false) = TrackingChecklistStep(valid = !installed, enabled = supported, visibility = TrackingChecklistStepVisibility.WHEN_INVALID) +private fun buildStandableStep(supported: Boolean = true, installed: Boolean = false) = TrackingChecklistStep(valid = !installed, enabled = supported, visibility = TrackingChecklistStepVisibility.WHEN_INVALID) class SteamVRCheckBehaviour(private val server: VRServer, private val settings: Settings) : TrackingChecklistBehaviourType { private val client = HttpClient(CIO)