User height calibration (Non tested)

This commit is contained in:
loucass003 committed 2026-03-29 05:35:48 +02:00
1 parent df4569fe17
commit f65f41ad17
6 files changed
+683 -1

No files matched your search

@@ -0,0 +1,186 @@
@file:OptIn(kotlinx.coroutines.FlowPreview::class)
package dev.slimevr.heightcalibration
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.flow.sample
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.withTimeoutOrNull
import solarxr_protocol.rpc.UserHeightCalibrationStatus
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sqrt
internal const val SAMPLE_INTERVAL_MS = 16L
private const val FLOOR_ALPHA = 0.1f
private const val HMD_ALPHA = 0.1f
private const val CONTROLLER_STABILITY_THRESHOLD = 0.005f
internal const val CONTROLLER_STABILITY_DURATION = 300_000_000L
private const val HMD_STABILITY_THRESHOLD = 0.003f
internal const val HEAD_STABILITY_DURATION = 600_000_000L
internal const val MAX_FLOOR_Y = 0.10f
internal const val HMD_RISE_THRESHOLD = 1.2f
internal const val HEIGHT_MIN = 1.4f
internal const val HEIGHT_MAX = 1.936f
private val HEAD_ANGLE_THRESHOLD = cos((PI / 180.0) * 15.0)
private val CONTROLLER_ANGLE_THRESHOLD = cos((PI / 180.0) * 45.0)
internal const val TIMEOUT_MS = 30_000L
private fun UserHeightCalibrationStatus.isTerminal() = when (this) {
UserHeightCalibrationStatus.DONE,
UserHeightCalibrationStatus.ERROR_TOO_HIGH,
UserHeightCalibrationStatus.ERROR_TOO_SMALL,
-> true
else -> false
}
private fun isControllerPointingDown(snapshot: TrackerSnapshot): Boolean {
val forward = snapshot.rotation.sandwich(Vector3.NEG_Z)
return (forward dot Vector3.NEG_Y) >= CONTROLLER_ANGLE_THRESHOLD
}
private fun isHmdLeveled(snapshot: TrackerSnapshot): Boolean {
val up = snapshot.rotation.sandwich(Vector3.POS_Y)
return (up dot Vector3.POS_Y) >= HEAD_ANGLE_THRESHOLD
}
object CalibrationBehaviour : HeightCalibrationBehaviourType {
override fun reduce(state: HeightCalibrationState, action: HeightCalibrationActions) =
when (action) {
is HeightCalibrationActions.Update -> state.copy(
status = action.status,
currentHeight = action.currentHeight,
)
}
}
internal suspend fun runCalibrationSession(
context: HeightCalibrationContext,
hmdUpdates: kotlinx.coroutines.flow.Flow<TrackerSnapshot>,
controllerUpdates: kotlinx.coroutines.flow.Flow<TrackerSnapshot>,
clock: () -> Long = System::nanoTime,
) {
var currentFloorLevel = Float.MAX_VALUE
var currentHeight = 0f
var floorStableStart: Long? = null
var heightStableStart: Long? = null
var floorFiltered: Vector3? = null
var floorEnergyEma = 0f
var hmdFiltered: Vector3? = null
var hmdEnergyEma = 0f
fun dispatch(status: UserHeightCalibrationStatus, height: Float = currentHeight) {
currentHeight = height
context.dispatch(HeightCalibrationActions.Update(status, height))
}
dispatch(UserHeightCalibrationStatus.RECORDING_FLOOR)
withTimeoutOrNull(TIMEOUT_MS) {
// Floor phase: collect controller updates until the floor level is locked in
controllerUpdates
.sample(SAMPLE_INTERVAL_MS)
.takeWhile { context.state.value.status != UserHeightCalibrationStatus.WAITING_FOR_RISE }
.collect { snapshot ->
val now = clock()
if (snapshot.position.y > MAX_FLOOR_Y) {
floorStableStart = null
floorFiltered = null
floorEnergyEma = 0f
return@collect
}
if (!isControllerPointingDown(snapshot)) {
dispatch(UserHeightCalibrationStatus.WAITING_FOR_CONTROLLER_PITCH)
floorStableStart = null
floorFiltered = null
floorEnergyEma = 0f
return@collect
}
val pos = snapshot.position
val prev = floorFiltered ?: pos
val newFiltered = prev * (1f - FLOOR_ALPHA) + pos * FLOOR_ALPHA
floorFiltered = newFiltered
currentFloorLevel = minOf(currentFloorLevel, pos.y)
val dev = pos - newFiltered
floorEnergyEma = floorEnergyEma * (1f - FLOOR_ALPHA) + (dev dot dev) * FLOOR_ALPHA
if (sqrt(floorEnergyEma) > CONTROLLER_STABILITY_THRESHOLD) {
floorStableStart = null
floorFiltered = null
floorEnergyEma = 0f
return@collect
}
val stableStart = floorStableStart ?: now.also { floorStableStart = it }
if (now - stableStart >= CONTROLLER_STABILITY_DURATION) {
dispatch(UserHeightCalibrationStatus.WAITING_FOR_RISE)
}
}
// Height phase: collect HMD updates until a terminal status is reached
hmdUpdates
.sample(SAMPLE_INTERVAL_MS)
.takeWhile { !context.state.value.status.isTerminal() }
.collect { snapshot ->
val now = clock()
val relativeY = snapshot.position.y - currentFloorLevel
if (relativeY <= HMD_RISE_THRESHOLD) {
dispatch(UserHeightCalibrationStatus.WAITING_FOR_RISE, relativeY)
heightStableStart = null
hmdFiltered = null
hmdEnergyEma = 0f
return@collect
}
if (!isHmdLeveled(snapshot)) {
dispatch(UserHeightCalibrationStatus.WAITING_FOR_FW_LOOK, relativeY)
heightStableStart = null
hmdFiltered = null
hmdEnergyEma = 0f
return@collect
}
dispatch(UserHeightCalibrationStatus.RECORDING_HEIGHT, relativeY)
val pos = snapshot.position
val prev = hmdFiltered ?: pos
val newFiltered = prev * (1f - HMD_ALPHA) + pos * HMD_ALPHA
hmdFiltered = newFiltered
val dev = pos - newFiltered
hmdEnergyEma = hmdEnergyEma * (1f - HMD_ALPHA) + (dev dot dev) * HMD_ALPHA
if (sqrt(hmdEnergyEma) > HMD_STABILITY_THRESHOLD) {
heightStableStart = null
hmdFiltered = null
hmdEnergyEma = 0f
return@collect
}
val stableStart = heightStableStart ?: now.also { heightStableStart = it }
if (now - stableStart >= HEAD_STABILITY_DURATION) {
val finalStatus = when {
relativeY < HEIGHT_MIN -> UserHeightCalibrationStatus.ERROR_TOO_SMALL
relativeY > HEIGHT_MAX -> UserHeightCalibrationStatus.ERROR_TOO_HIGH
else -> UserHeightCalibrationStatus.DONE
}
dispatch(finalStatus, relativeY)
// TODO (when DONE): persist height to config, update user proportions, clear mounting reset flags
}
}
} ?: dispatch(UserHeightCalibrationStatus.ERROR_TIMEOUT)
}
@@ -0,0 +1,102 @@
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
package dev.slimevr.heightcalibration
import dev.slimevr.VRServer
import dev.slimevr.context.Behaviour
import dev.slimevr.context.Context
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.rpc.UserHeightCalibrationStatus
data class TrackerSnapshot(val position: Vector3, val rotation: Quaternion)
data class HeightCalibrationState(
val status: UserHeightCalibrationStatus,
val currentHeight: Float,
)
sealed interface HeightCalibrationActions {
data class Update(val status: UserHeightCalibrationStatus, val currentHeight: Float) : HeightCalibrationActions
}
typealias HeightCalibrationContext = Context<HeightCalibrationState, HeightCalibrationActions>
typealias HeightCalibrationBehaviourType = Behaviour<HeightCalibrationState, HeightCalibrationActions, HeightCalibrationManager>
val INITIAL_HEIGHT_CALIBRATION_STATE = HeightCalibrationState(
status = UserHeightCalibrationStatus.NONE,
currentHeight = 0f,
)
class HeightCalibrationManager(
val context: HeightCalibrationContext,
val serverContext: VRServer,
) {
private var sessionJob: Job? = null
// These Flows do nothing until the calibration use collect on it
val hmdUpdates: Flow<TrackerSnapshot> = serverContext.context.state
.flatMapLatest { state ->
val hmd = state.trackers.values
.find { it.context.state.value.bodyPart == BodyPart.HEAD } // TODO: Need to check for a head with position support
?: return@flatMapLatest emptyFlow()
hmd.context.state.map { s ->
TrackerSnapshot(
// TODO: get HMD position from VR system once position is set in the tracker
position = Vector3.NULL,
rotation = s.rawRotation,
)
}
}
val controllerUpdates: Flow<TrackerSnapshot> = serverContext.context.state
.flatMapLatest { state ->
val controllers = state.trackers.values.filter {
val bodyPart = it.context.state.value.bodyPart
bodyPart == BodyPart.LEFT_HAND || bodyPart == BodyPart.RIGHT_HAND
}
if (controllers.isEmpty()) return@flatMapLatest emptyFlow()
combine(controllers.map { controller ->
controller.context.state.map { s ->
// TODO: get controller position from tracker once position is set in the tracker
val position = Vector3.NULL
TrackerSnapshot(position = position, rotation = s.rawRotation)
}
}) { snapshots -> snapshots.minByOrNull { it.position.y }!! }
}
fun start() {
sessionJob?.cancel()
sessionJob = context.scope.launch { runCalibrationSession(context, hmdUpdates, controllerUpdates) }
}
fun cancel() {
sessionJob?.cancel()
sessionJob = null
context.dispatch(HeightCalibrationActions.Update(UserHeightCalibrationStatus.NONE, 0f))
}
companion object {
fun create(
serverContext: VRServer,
scope: CoroutineScope,
): HeightCalibrationManager {
val behaviours = listOf(CalibrationBehaviour)
val context = Context.create(
initialState = INITIAL_HEIGHT_CALIBRATION_STATE,
scope = scope,
behaviours = behaviours,
)
return HeightCalibrationManager(context = context, serverContext = serverContext)
}
}
}
@@ -0,0 +1,32 @@
package dev.slimevr.solarxr
import dev.slimevr.heightcalibration.HeightCalibrationManager
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import solarxr_protocol.rpc.CancelUserHeightCalibration
import solarxr_protocol.rpc.StartUserHeightCalibration
import solarxr_protocol.rpc.UserHeightRecordingStatusResponse
class HeightCalibrationBehaviour(
private val heightCalibrationManager: HeightCalibrationManager,
) : SolarXRConnectionBehaviour {
override fun observe(receiver: SolarXRConnection) {
receiver.rpcDispatcher.on<StartUserHeightCalibration> {
heightCalibrationManager.start()
}
receiver.rpcDispatcher.on<CancelUserHeightCalibration> {
heightCalibrationManager.cancel()
}
heightCalibrationManager.context.state.drop(1).onEach { state ->
receiver.sendRpc(
UserHeightRecordingStatusResponse(
status = state.status,
hmdheight = state.currentHeight,
),
)
}.launchIn(receiver.context.scope)
}
}
@@ -30,7 +30,7 @@ class VrcBehaviour(
)
}
// Drop the initial value — we only want to push updates when the config changes
// Drop the initial value, we only want to push updates when the config changes
vrcManager.context.state.drop(1).onEach {
receiver.sendRpc(buildCurrentResponse())
}.launchIn(receiver.context.scope)