diff --git a/server/core/src/main/java/dev/slimevr/config/settings.kt b/server/core/src/main/java/dev/slimevr/config/settings.kt index a208e2865..9936c9a0a 100644 --- a/server/core/src/main/java/dev/slimevr/config/settings.kt +++ b/server/core/src/main/java/dev/slimevr/config/settings.kt @@ -29,6 +29,27 @@ data class TrackerConfig( val magEnabled: Boolean? = null, ) +@Serializable +data class TapDetectionConfig ( + var yawResetDelay: Float = 0.2f, + var fullResetDelay: Float = 1.0f, + var mountingResetDelay: Float = 1.0f, + var yawResetEnabled: Boolean = true, + var fullResetEnabled: Boolean = true, + var mountingResetEnabled: Boolean = true, + @Serializable(with = BodyPartSerializer::class) + var yawResetBodyPart: BodyPart? = BodyPart.CHEST, + @Serializable(with = BodyPartSerializer::class) + var mountingResetBodyPart: BodyPart? = BodyPart.RIGHT_UPPER_LEG, + @Serializable(with = BodyPartSerializer::class) + var fullResetBodyPart: BodyPart? = BodyPart.LEFT_UPPER_LEG, + var yawResetTaps: Int = 2, + var fullResetTaps: Int = 3, + var mountingResetTaps: Int = 3, + var numberTrackersOverThreshold: Int = 1 +) { +} + @Serializable data class SettingsConfigState( val trackerPort: Int = 6969, @@ -40,6 +61,7 @@ data class SettingsConfigState( val vrcOscConfig: VRCOSCConfig = defaultVrcOscConfig(), val vmcConfig: VMCConfig = VMCConfig(), val version: Int = SETTINGS_CONFIG_VERSION, + val tapDetectionConfig: TapDetectionConfig = TapDetectionConfig(), ) private fun defaultVrcOscConfig() = VRCOSCConfig() diff --git a/server/core/src/main/java/dev/slimevr/tracker/behaviours.kt b/server/core/src/main/java/dev/slimevr/tracker/behaviours.kt index 4231c0f94..d2358ac3f 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/behaviours.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/behaviours.kt @@ -1,84 +1,172 @@ package dev.slimevr.tracker +import dev.slimevr.AppLogger +import dev.slimevr.VRServerState +import dev.slimevr.config.SettingsState import dev.slimevr.skeleton.SkeletonActions import dev.slimevr.util.safeLaunch import io.github.axisangles.ktmath.Quaternion -import io.github.axisangles.ktmath.Vector3 +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChangedBy import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.isActive +import solarxr_protocol.datatypes.BodyPart +import solarxr_protocol.datatypes.TrackerStatus import kotlin.concurrent.atomics.AtomicInt import kotlin.concurrent.atomics.ExperimentalAtomicApi import kotlin.concurrent.atomics.incrementAndFetch +import kotlin.time.Duration.Companion.milliseconds import kotlin.time.TimeSource private const val NS_CONVERTER = 1.0e9f private const val CLUMP_TIME_NS = 0.06f * NS_CONVERTER -private const val NEEDED_ACCEL_DELTA = 4.0f -private const val ALLOWED_BODY_ACCEL = 2.0f +private const val NEEDED_ACCEL_DELTA = 6.0f +private const val ALLOWED_BODY_ACCEL = 2.25f private const val ALLOWED_BODY_ACCEL_SQUARED = ALLOWED_BODY_ACCEL * ALLOWED_BODY_ACCEL -private const val TAP_WINDOW_PER_TAP_S = 0.3f +private const val TAP_WINDOW_PER_TAP_NS = 0.3f * NS_CONVERTER class TrackerTapDetectionBehaviour : TrackerBehaviour { private val accelList = ArrayDeque>() private val tapTimestamps = ArrayDeque() private var waitForLowAccel = false + data class TapDetectionContext( + val actionToExecute: TrackerActions?, + val tapsNeeded: Int, + val actionDelay: Float, + val numberTrackersOverThreshold: Int + ) + + @OptIn(ExperimentalCoroutinesApi::class) override fun observe(receiver: Tracker) { - // TODO: only enable this on the trackers that have taps assigned to them - receiver.context.state - .distinctUntilChangedBy { it.rawAcceleration } - .onEach { current -> - val now = System.nanoTime() - val magnitude = current.rawAcceleration.len() - - accelList.add(magnitude to now) - while (accelList.isNotEmpty() && now - accelList.first().second > CLUMP_TIME_NS) { - accelList.removeFirst() - } - - val max = accelList.maxOfOrNull { it.first } ?: 0f - val min = accelList.minOfOrNull { it.first } ?: 0f - val accelDelta = max - min - - if (accelDelta > NEEDED_ACCEL_DELTA && !waitForLowAccel) { - val othersOverThreshold = receiver.appContext.server.context.state.value.trackers.values - .count { it.context.state.value.id != current.id && it.context.state.value.rawAcceleration.lenSq() > ALLOWED_BODY_ACCEL_SQUARED } - if (othersOverThreshold <= 1) { - tapTimestamps.add(now) - waitForLowAccel = true + // Outer flow (loading) is refreshed when TapDetection config or a tracker's bodyPart or status changes + combine( + receiver.appContext.config.settings.context.state + .distinctUntilChangedBy { configState -> + configState.data.tapDetectionConfig }, + receiver.appContext.server.context.state + .flatMapLatest { serverState -> + combine(serverState.trackers.values.map { tracker -> tracker.context.state }) + { trackerStates -> + trackerStates.map { it.bodyPart to it.status } } } - - if (max < ALLOWED_BODY_ACCEL) { - waitForLowAccel = false - } - - if (tapTimestamps.isNotEmpty()) { - val totalWindowNs = (TAP_WINDOW_PER_TAP_S * tapTimestamps.size * NS_CONVERTER).toLong() - while (tapTimestamps.isNotEmpty() && now - tapTimestamps.first() > totalWindowNs) { - tapTimestamps.removeFirst() + .distinctUntilChanged() + ) { configState, _ -> + loadTapDetection(receiver, configState, receiver.appContext.server.context.state.value) + } + // Inner flow (process) is refreshed everytime this tracker's acceleration is updated + .flatMapLatest { tapDetectionContext -> + receiver.context.state + .filter { tapDetectionContext.actionToExecute != null } + .distinctUntilChangedBy { it.rawAcceleration } + .onEach { currentTracker -> + processTapDetection(receiver, currentTracker, tapDetectionContext) } + }.launchIn(receiver.context.scope) + } - if (tapTimestamps.isNotEmpty()) { - val lastTapTime = tapTimestamps.last() - if (now - lastTapTime > (TAP_WINDOW_PER_TAP_S * NS_CONVERTER).toLong()) { - val count = tapTimestamps.size - if (count >= 2) { - println("Detected $count taps on ${receiver.context.state.value.id}") - // TODO trigger the tap action - } - tapTimestamps.clear() - } + // Loads TapDetection config + private fun loadTapDetection( + receiver: Tracker, + configState: SettingsState, + serverState: VRServerState + ): TapDetectionContext { + val tapDetectionConfig = configState.data.tapDetectionConfig + val trackersBodyParts = serverState.trackers.values + .map { it.context.state.value.bodyPart } + .toSet() + + val referenceRotation = serverState.trackers.firstNotNullOfOrNull { + val trackerState = it.value.context.state.value + if (trackerState.status == TrackerStatus.OK && trackerState.bodyPart == BodyPart.HEAD) { + trackerState.rotation + } else null + } ?: Quaternion.IDENTITY + + val yawResetBodyPart = listOf(tapDetectionConfig.yawResetBodyPart, BodyPart.UPPER_CHEST, BodyPart.CHEST, BodyPart.HIP, BodyPart.WAIST) + .firstOrNull { it in trackersBodyParts } + val fullResetBodyPart = listOf(tapDetectionConfig.fullResetBodyPart, BodyPart.LEFT_UPPER_LEG, BodyPart.LEFT_LOWER_LEG) + .firstOrNull { it in trackersBodyParts } + val mountingResetBodyPart = listOf(tapDetectionConfig.mountingResetBodyPart, BodyPart.RIGHT_UPPER_LEG, BodyPart.RIGHT_LOWER_LEG) + .firstOrNull { it in trackersBodyParts } + + val (actionToExecute, tapsNeeded, actionDelay) = when (receiver.context.state.value.bodyPart) { + null -> Triple(null, 0, 0f) + yawResetBodyPart if tapDetectionConfig.yawResetEnabled -> + Triple(TrackerActions.YawReset(referenceRotation), tapDetectionConfig.yawResetTaps, tapDetectionConfig.yawResetDelay) + fullResetBodyPart if tapDetectionConfig.fullResetEnabled -> + Triple(TrackerActions.FullReset(referenceRotation), tapDetectionConfig.fullResetTaps, tapDetectionConfig.fullResetDelay) + mountingResetBodyPart if tapDetectionConfig.mountingResetEnabled -> + Triple(TrackerActions.MountingReset(referenceRotation), tapDetectionConfig.mountingResetTaps, tapDetectionConfig.mountingResetDelay) + else -> Triple(null, 0, 0f) + } + + resetTapDetection() + + return TapDetectionContext(actionToExecute, tapsNeeded, actionDelay, tapDetectionConfig.numberTrackersOverThreshold) + } + + // Logic loop for tap detection + private fun processTapDetection( + receiver: Tracker, + currentTracker: TrackerState, + context: TapDetectionContext + ) { + if (context.actionToExecute == null) return + + val now = System.nanoTime() + + accelList.add(currentTracker.rawAcceleration.len() to now) + while (accelList.isNotEmpty() && now - accelList.first().second > CLUMP_TIME_NS) { + accelList.removeFirst() + } + + val max = accelList.maxOfOrNull { it.first } ?: 0f + val min = accelList.minOfOrNull { it.first } ?: 0f + val accelDelta = max - min + + if (accelDelta > NEEDED_ACCEL_DELTA && !waitForLowAccel) { + val othersOverThreshold = receiver.appContext.server.context.state.value.trackers.values + .count { it.context.state.value.id != currentTracker.id && it.context.state.value.rawAcceleration.lenSq() > ALLOWED_BODY_ACCEL_SQUARED } + if (othersOverThreshold < context.numberTrackersOverThreshold) { + tapTimestamps.add(now) + waitForLowAccel = true + } + } + + if (max < ALLOWED_BODY_ACCEL) waitForLowAccel = false + + if (tapTimestamps.isNotEmpty()) { + val totalWindowNs = (TAP_WINDOW_PER_TAP_NS * tapTimestamps.size).toLong() + while (tapTimestamps.isNotEmpty() && now - tapTimestamps.first() > totalWindowNs) { + tapTimestamps.removeFirst() + } + + if (tapTimestamps.isNotEmpty() && now - tapTimestamps.last() > TAP_WINDOW_PER_TAP_NS.toLong()) { + if (tapTimestamps.size >= context.tapsNeeded) { + receiver.context.scope.safeLaunch { + AppLogger.tracker.info("TapDetection triggered ${context.actionToExecute}") + delay((context.actionDelay * 1000).toLong().milliseconds) + receiver.appContext.server.context.state.value.trackers.values.forEach { it.context.dispatch(context.actionToExecute) } } + resetTapDetection() } } - .launchIn(receiver.context.scope) + } + } + + private fun resetTapDetection(){ + accelList.clear() + tapTimestamps.clear() + waitForLowAccel = false } } @@ -203,7 +291,7 @@ class TrackerTPSBehaviour : TrackerBehaviour { var mark = TimeSource.Monotonic.markNow() while (isActive) { try { - delay(1000) + delay(1000.milliseconds) val elapsed = mark.elapsedNow() val tps = count.exchange(0) * 1000L / elapsed.inWholeMilliseconds receiver.context.dispatch(TrackerActions.Update { copy(tps = tps.toUShort()) })