Compare commits

...
Author SHA1 Message Date
loucass003 05dc3cf31e Better compile time calculation 2026-09-15 18:07:44 +02:00
loucass003 68d678bcf4 Clean up tests. remove redundant ones, regroup stuff 2026-09-15 16:54:09 +02:00
loucass003 cc0f7dd3e8 More cleanup. Handle more edge cases 2026-09-15 16:33:34 +02:00
loucass003 d49877668d More cleanup. move ressouces in the right folder. Simplified override 2026-09-15 15:46:50 +02:00
loucass003 3ee7f00e8d Mimic mc override system / move files around 2026-09-15 14:55:05 +02:00
loucass003 e957ebc977 Migration logic 2026-09-15 14:05:45 +02:00
loucass003 065d2bf71b Re organise and split parser in a way we can add stuff without too much overlap 2026-09-15 13:54:35 +02:00
loucass003 c54ea7f1b9 Splitted and more organised ressource pack parser / compiler 2026-09-15 06:34:01 +02:00
loucass003 309cff3406 Check for duplicates in vchat output addresses 2026-09-15 03:36:47 +02:00
loucass003 3b4df34049 Verify pipline operation order and give errors 2026-09-15 03:36:47 +02:00
loucass003 8e2fb1609b More checks on VMC outputs when compiling the packs 2026-09-15 03:36:47 +02:00
loucass003 49ac85b129 Make sure order of fallacks is correct 2026-09-15 03:36:47 +02:00
loucass003 d962d52631 Better overrides 2026-09-15 03:36:47 +02:00
loucass003 0bb2772cf0 removes in overides 2026-09-15 03:35:59 +02:00
loucass003 b6acf4a98e overrides 2026-09-15 03:35:59 +02:00
loucass003 9526be4841 VRCOSC output from pack 2026-09-15 03:35:59 +02:00
loucass003 55e631b7f0 Battery Source to pack 2026-09-15 03:28:03 +02:00
loucass003 9c29e8880f VRM mappings from pack 2026-09-15 03:23:12 +02:00
loucass003 dcabe69bc8 Bone Routing from pack 2026-09-15 03:21:07 +02:00
loucass003 efeada35fa Constrains and RotationFallback processors 2026-09-15 03:19:30 +02:00
loucass003 4b4aa89f37 Proportions from resource packs 2026-09-15 03:18:11 +02:00
loucass003 5b5a20ff4c Ressource pack base parser 2026-09-15 03:13:08 +02:00
loucass003 4ab1e6c127 Formated jsons + outputs 2026-09-15 03:13:08 +02:00
loucass003 8a149e861f Ressource pack structure example 2026-09-15 03:13:08 +02:00
171 changed files with 6077 additions and 1635 deletions

No files matched your search

@@ -36,6 +36,7 @@ import dev.slimevr.keybind.KeybindManager
import dev.slimevr.networkprofile.NetworkProfileManager
import dev.slimevr.provisioning.ProvisioningManager
import dev.slimevr.resets.ResetsManager
import dev.slimevr.resourcepacks.ResourcePackManager
import dev.slimevr.routing.BoneRoutingManager
import dev.slimevr.skeleton.Skeleton
import dev.slimevr.solarxr.rpc.ServerInfos
@@ -149,9 +150,11 @@ class ForegroundService : Service() {
private suspend fun startServer(scope: CoroutineScope) {
val storage = AndroidConfigStorage(filesDir)
val config = AppConfig.create(scope = scope, storage = storage)
val resourcePacks = ResourcePackManager.loadCompiled(storage, javaClass.classLoader ?: ClassLoader.getSystemClassLoader())
val skeletonDefinition = resourcePacks.skeleton
val server = VRServer.create(scope = scope)
val serialServer = createAndroidSerialServer(context = this, scope = scope)
val bones = BoneRegistryManager.create(scope = scope)
val bones = BoneRegistryManager.create(scope = scope, initial = skeletonDefinition.registry)
// Nothing registers extension bones yet, so this is a no-op today; it exists so the
// tracking stack below never observes a registry that could still change under it.
bones.freeze()
@@ -160,9 +163,9 @@ class ForegroundService : Service() {
val firmwareManager = FirmwareManager.create(ctx = phase1, scope = scope, flasher = AndroidFirmwareFlasher)
val networkProfileManager = NetworkProfileManager.create(scope = scope, isSupported = false)
val skeleton = Skeleton.create(scope = scope, ctx = phase1, waiter = createAndroidWaiter())
val skeleton = Skeleton.create(scope = scope, ctx = phase1, definition = skeletonDefinition, waiter = createAndroidWaiter())
val provisioningManager = ProvisioningManager.create(ctx = phase1, scope = scope)
val heightCalibrationManager = HeightCalibrationManager.create(ctx = phase1, scope = scope)
val heightCalibrationManager = HeightCalibrationManager.create(ctx = phase1, scope = scope, definition = skeletonDefinition)
val trackingChecklist = TrackingChecklist.create(scope = scope)
val udpServer = UdpServer.create(scope = scope, addressResolver = ::resolveAndroidUdpAddress)
val boneRouting = BoneRoutingManager.create(scope = scope)
@@ -1,15 +1,23 @@
package dev.slimevr.android.config
import dev.slimevr.config.ConfigStorage
import dev.slimevr.config.StorageEntry
import dev.slimevr.config.StorageEntryType
import dev.slimevr.config.TextFileHandle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.RandomAccessFile
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.StandardCopyOption
class AndroidConfigStorage(private val root: File) : ConfigStorage {
override suspend fun readBytes(path: String): ByteArray? = withContext(Dispatchers.IO) {
val file = resolve(path)
if (file.exists()) file.readBytes() else null
}
override suspend fun read(path: String): String? = withContext(Dispatchers.IO) {
val file = resolve(path)
if (file.exists()) file.readText() else null
@@ -46,6 +54,22 @@ class AndroidConfigStorage(private val root: File) : ConfigStorage {
directory.isDirectory || directory.mkdirs()
}
override suspend fun list(path: String): List<StorageEntry> = withContext(Dispatchers.IO) {
val directory = resolve(path).toPath()
if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) return@withContext emptyList()
Files.list(directory).use { stream ->
stream.map { child ->
val type = when {
Files.isSymbolicLink(child) -> StorageEntryType.SYMLINK
Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS) -> StorageEntryType.DIRECTORY
Files.isRegularFile(child, LinkOption.NOFOLLOW_LINKS) -> StorageEntryType.FILE
else -> StorageEntryType.OTHER
}
StorageEntry(child.fileName.toString(), type)
}.sorted(compareBy { it.name }).toList()
}
}
override suspend fun openTextFile(path: String): TextFileHandle = withContext(Dispatchers.IO) {
val file = resolve(path)
file.parentFile?.mkdirs()
+27
View File
@@ -15,6 +15,24 @@ tasks.withType<Jar> {
from("../../LICENSE-MIT")
}
val generateCoreResourcePackIndex = tasks.register("generateCoreResourcePackIndex") {
val corePack = layout.projectDirectory.dir("src/main/resources/dev/slimevr/resourcepacks/core")
val index = layout.buildDirectory.file("generated/resources/dev/slimevr/resourcepacks/core/index.txt")
inputs.dir(corePack)
outputs.file(index)
doLast {
val root = corePack.asFile.toPath()
val files = corePack.asFile.walkTopDown()
.filter { it.isFile && !it.relativeTo(corePack.asFile).invariantSeparatorsPath.startsWith("schemas/") }
.map { root.relativize(it.toPath()).toString().replace('\\', '/') }
.sorted()
index.get().asFile.apply {
parentFile.mkdirs()
writeText(files.joinToString("\n", postfix = "\n"))
}
}
}
allprojects {
repositories {
// Use jcenter for resolving dependencies.
@@ -31,10 +49,15 @@ kotlin {
sourceSets {
val commonMain = getByName("commonMain") {
kotlin.srcDir("src/main/java")
resources.srcDir("src/main/resources")
resources.srcDir(layout.buildDirectory.dir("generated/resources"))
dependencies {
api(project(":solarxr-protocol:generated"))
api("com.google.flatbuffers:flatbuffers-java:22.10.26")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.10.0")
implementation("com.github.erosb:json-sKema:0.31.0") {
exclude(group = "org.yaml", module = "snakeyaml")
}
implementation("com.mayakapps.kache:kache:2.1.1")
implementation("io.klogging:klogging:0.11.7")
api("com.appstractive:dns-sd-kt:1.1.0")
@@ -64,6 +87,10 @@ kotlin {
}
}
tasks.matching { it.name.endsWith("ProcessResources") }.configureEach {
dependsOn(generateCoreResourcePackIndex)
}
tasks.withType<JavaCompile> {
options.encoding = "UTF-8"
}
@@ -53,9 +53,6 @@ inline fun <V : Any> BodyPartMap<V>.forEachBone(action: (BodyPart, V) -> Unit) {
}
}
/** Converts a [BodyPartMap] to a plain [BoneId]-keyed [Map]; no registry needed since every key is standard. */
fun <V : Any> BodyPartMap<V>.resolveToBoneIds(): Map<BoneId, V> = mapKeys { it.key.boneId }
/**
* Dense array-backed map keyed by [BoneId], scoped to the [registry] it was built for.
* IDs run `1..registry.maxId`, slot 0 is unused.
@@ -1,4 +1,4 @@
package dev.slimevr.skeleton
package dev.slimevr.bones
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
@@ -2,26 +2,23 @@ package dev.slimevr.bones
import dev.slimevr.context.Context
import kotlinx.coroutines.CoroutineScope
import solarxr_protocol.connection.BoneDefinition
data class BoneRegistryState(val registry: BoneRegistry, val frozen: Boolean)
sealed interface BoneRegistryActions {
data class RegisterBones(val bones: List<BoneDefinition>) : BoneRegistryActions
data object Freeze : BoneRegistryActions
}
typealias BoneRegistryContext = Context<BoneRegistryState, BoneRegistryActions>
/**
* Owns the server's [BoneRegistry]. Bones are contributed via [register] during bootstrap, then
* Owns the server's [BoneRegistry], seeded from the compiled resource-pack skeleton at bootstrap.
* [freeze] closes the window before the tracking stack starts: no tracker or skeleton state is
* ever built against a registry that can still change under it.
*/
class BoneRegistryManager(val context: BoneRegistryContext) {
val current: BoneRegistry get() = context.state.value.registry
fun register(bones: List<BoneDefinition>) = context.dispatch(BoneRegistryActions.RegisterBones(bones))
fun freeze() = context.dispatch(BoneRegistryActions.Freeze)
companion object {
@@ -1,29 +1,5 @@
package dev.slimevr.bones
import solarxr_protocol.connection.BoneDefinition
import solarxr_protocol.connection.BoneRegistry as WireBoneRegistry
/**
* Assigns each of [incoming] a fresh ID above every ID [registry] already has, preserving order.
* A `parent` must reference a bone [registry] already defines
*/
private fun assignIds(registry: BoneRegistry, incoming: List<BoneDefinition>): List<BoneDefinition> {
var nextId = registry.maxId
return incoming.map { definition ->
require(definition.parent == 0.toUShort() || registry[BoneId(definition.parent)] != null) {
"Extension bone \"${definition.key}\" has an unknown parent"
}
nextId++
definition.copy(id = nextId.toUShort())
}
}
fun reduce(state: BoneRegistryState, action: BoneRegistryActions): BoneRegistryState = when (action) {
is BoneRegistryActions.RegisterBones -> {
require(!state.frozen) { "The bone registry is frozen; bones must be registered before the tracking stack starts" }
val merged = WireBoneRegistry(bones = state.registry.value.bones + assignIds(state.registry, action.bones))
state.copy(registry = BoneRegistry.from(merged))
}
is BoneRegistryActions.Freeze -> state.copy(frozen = true)
}
@@ -18,14 +18,25 @@ import kotlinx.serialization.json.Json
interface ConfigStorage {
suspend fun read(path: String): String?
suspend fun readBytes(path: String): ByteArray? = read(path)?.encodeToByteArray()
suspend fun write(path: String, content: String)
suspend fun backup(path: String)
suspend fun exists(path: String): Boolean
suspend fun ensureDirectory(path: String): Boolean
/** Lists direct children only. Implementations must not follow symbolic links. */
suspend fun list(path: String): List<StorageEntry> = emptyList()
suspend fun openTextFile(path: String): TextFileHandle
fun displayPath(path: String): String = path
}
enum class StorageEntryType { FILE, DIRECTORY, SYMLINK, OTHER }
data class StorageEntry(
val name: String,
val type: StorageEntryType,
)
interface TextFileHandle {
suspend fun write(text: String)
suspend fun flush()
@@ -6,7 +6,7 @@ import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.boneId
import dev.slimevr.config.UserConfig
import dev.slimevr.config.UserConfigActions
import dev.slimevr.skeleton.computeDefaultProportionsByBone
import dev.slimevr.resourcepacks.bones.CompiledSkeleton
import dev.slimevr.tracker.TrackerState
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.flow.combine
@@ -97,6 +97,7 @@ class BaseCalibrationBehaviour : HeightCalibrationBehaviourType {
internal suspend fun runCalibrationSession(
context: HeightCalibrationContext,
userConfig: UserConfig,
definition: CompiledSkeleton,
hmdUpdates: kotlinx.coroutines.flow.Flow<TrackerSnapshot>,
controllerUpdates: kotlinx.coroutines.flow.Flow<TrackerSnapshot>,
clock: () -> Long = System::nanoTime,
@@ -216,7 +217,7 @@ internal suspend fun runCalibrationSession(
if (finalStatus == UserHeightCalibrationStatus.DONE) {
userConfig.context.dispatch(
UserConfigActions.Update {
copy(userHeight = relativeY, proportions = computeDefaultProportionsByBone(relativeY))
copy(userHeight = relativeY, proportions = definition.heightScaledProportionValues(relativeY))
},
)
}
@@ -9,6 +9,7 @@ import dev.slimevr.bones.boneId
import dev.slimevr.config.UserConfig
import dev.slimevr.context.Behaviour
import dev.slimevr.context.Context
import dev.slimevr.resourcepacks.bones.CompiledSkeleton
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.CoroutineScope
@@ -48,6 +49,7 @@ class HeightCalibrationManager(
val context: HeightCalibrationContext,
val serverContext: VRServer,
private val userConfig: UserConfig,
private val definition: CompiledSkeleton,
) {
fun startObserving() = context.observeAll(this)
@@ -89,7 +91,7 @@ class HeightCalibrationManager(
fun start() {
sessionJob?.cancel()
sessionJob = context.scope.launch { runCalibrationSession(context, userConfig, hmdUpdates, controllerUpdates) }
sessionJob = context.scope.launch { runCalibrationSession(context, userConfig, definition, hmdUpdates, controllerUpdates) }
}
fun cancel() {
@@ -102,6 +104,7 @@ class HeightCalibrationManager(
fun create(
ctx: Phase1ContextProvider,
scope: CoroutineScope,
definition: CompiledSkeleton,
): HeightCalibrationManager {
val context = Context.create(
initialState = INITIAL_HEIGHT_CALIBRATION_STATE,
@@ -110,7 +113,7 @@ class HeightCalibrationManager(
behaviours = listOf(BaseCalibrationBehaviour()),
name = "HeightCalibration",
)
return HeightCalibrationManager(context = context, serverContext = ctx.server, userConfig = ctx.config.userConfig)
return HeightCalibrationManager(context = context, serverContext = ctx.server, userConfig = ctx.config.userConfig, definition = definition)
}
}
}
@@ -0,0 +1,159 @@
package dev.slimevr.resourcepacks.bones
import dev.slimevr.bones.BoneId
import dev.slimevr.bones.BoneRegistry
import dev.slimevr.bones.Constraint
import dev.slimevr.bones.HingeConstraint
import dev.slimevr.bones.LooseHingeConstraint
import dev.slimevr.bones.TwistSwingConstraint
import dev.slimevr.resourcepacks.Offset
import dev.slimevr.resourcepacks.ParsedResourcePack
import dev.slimevr.resourcepacks.compiler.BoneContribution
import dev.slimevr.resourcepacks.compiler.BoneField
import dev.slimevr.resourcepacks.compiler.ProportionContribution
import dev.slimevr.resourcepacks.compiler.ResourceOrigin
import dev.slimevr.resourcepacks.compiler.ResourcePackCompilationDiagnostic
import dev.slimevr.resourcepacks.compiler.diagnostic
import dev.slimevr.resourcepacks.compiler.reportCycles
import io.github.axisangles.ktmath.Vector3
import com.jme3.math.FastMath.DEG_TO_RAD as degToRad
import dev.slimevr.resourcepacks.Constraint as PackConstraint
import dev.slimevr.resourcepacks.HingeConstraint as PackHingeConstraint
import dev.slimevr.resourcepacks.LooseHingeConstraint as PackLooseHingeConstraint
import dev.slimevr.resourcepacks.TwistSwingConstraint as PackTwistSwingConstraint
/** Get last origin or null */
internal fun BoneContribution.originOrNull(field: BoneField): ResourceOrigin? = originOrNull(field.path)
/** Get last origin or default */
internal fun BoneContribution.origin(field: BoneField): ResourceOrigin = originOrNull(field.path) ?: definitionOrigin
internal fun compileConstraint(constraint: PackConstraint): Constraint = when (constraint) {
is PackTwistSwingConstraint -> TwistSwingConstraint(
twist = constraint.twistDegrees * degToRad,
swing = constraint.swingDegrees * degToRad,
allowedDeviation = (constraint.allowedDeviationDegrees ?: 0f) * degToRad,
)
is PackHingeConstraint -> HingeConstraint(
min = constraint.minDegrees * degToRad,
max = constraint.maxDegrees * degToRad,
hingeAxis = Vector3(constraint.axis.x, constraint.axis.y, constraint.axis.z),
)
is PackLooseHingeConstraint -> LooseHingeConstraint(
min = constraint.minDegrees * degToRad,
max = constraint.maxDegrees * degToRad,
allowedDeviation = constraint.allowedDeviationDegrees * degToRad,
hingeAxis = Vector3(constraint.axis.x, constraint.axis.y, constraint.axis.z),
)
}
/** Resolve bone key and report errors */
internal fun resolveBoneKey(
key: String,
origin: ResourceOrigin,
context: String,
registry: BoneRegistry,
diagnostics: MutableList<ResourcePackCompilationDiagnostic>,
): BoneId {
val boneId = registry[key]
if (boneId != null) return boneId
diagnostics += origin.diagnostic("Unknown bone '$key' in $context")
return BoneId(0u)
}
/** Resolve fallback to BoneId */
internal fun resolveFallbackBone(
key: String,
contribution: BoneContribution,
registry: BoneRegistry,
diagnostics: MutableList<ResourcePackCompilationDiagnostic>,
): BoneId {
val target = if (key == "parent") contribution.resource.value.parent else key
val origin = contribution.origin(BoneField.RotationFallback)
if (target == null) {
diagnostics += origin.diagnostic("Unknown bone '$key' in rotationFallback")
return BoneId(0u)
}
return resolveBoneKey(target, origin, "rotationFallback", registry, diagnostics)
}
internal fun compileOffset(
offset: Offset,
origin: ResourceOrigin,
proportionsByKey: Map<String, ProportionContribution>,
diagnostics: MutableList<ResourcePackCompilationDiagnostic>,
): CompiledOffset {
val base = offset.base?.let { Vector3(it.x, it.y, it.z) } ?: Vector3.ZERO
val terms = (offset.terms ?: emptyList()).map { term ->
if (term.proportion !in proportionsByKey) {
diagnostics += origin.diagnostic("Unknown proportion '${term.proportion}'")
}
CompiledOffsetTerm(
term.proportion,
Vector3(term.direction.x, term.direction.y, term.direction.z),
)
}
return CompiledOffset(base, terms)
}
/**
* Orders an acyclic fallback chain source-before-consumer. A cycle keeps its existing hierarchy
* order
*/
internal fun <T> orderFallbackDependencies(
entries: List<Pair<BoneId, T>>,
dependency: (T) -> BoneId?,
): List<Pair<BoneId, T>> {
val remaining = entries.toMutableList()
val result = mutableListOf<Pair<BoneId, T>>()
while (remaining.isNotEmpty()) {
val pending = remaining.associate { it.first to it.second }
val readyIndex = remaining.indexOfFirst { (_, value) ->
val source = dependency(value)
source == null || source !in pending
}
val cycleIndex = remaining.indexOfFirst { (boneId, _) ->
var source = dependency(pending.getValue(boneId))
val visited = mutableSetOf<BoneId>()
while (source != null && source != boneId && visited.add(source)) source = pending[source]?.let(dependency)
source == boneId
}
val nextIndex = listOf(readyIndex, cycleIndex).filter { it >= 0 }.minOrNull() ?: 0
result += remaining.removeAt(nextIndex)
}
return result
}
internal fun validateHierarchy(
core: ParsedResourcePack,
bonesByKey: Map<String, BoneContribution>,
diagnostics: MutableList<ResourcePackCompilationDiagnostic>,
) {
val roots = bonesByKey.values.filter { it.resource.value.parent == null }
if (roots.isEmpty()) {
val overrideOrigin = bonesByKey.values.mapNotNull { it.originOrNull(BoneField.Parent) }.lastOrNull()
diagnostics += overrideOrigin?.diagnostic("A resource-pack registry must have exactly one root; found none")
?: ResourcePackCompilationDiagnostic(
core.manifest.value.id,
core.manifest.path,
"A resource-pack registry must have exactly one root; found none",
)
} else if (roots.size > 1) {
for (contribution in roots) {
diagnostics += contribution.origin(BoneField.Parent).diagnostic("A resource-pack registry must have exactly one root; found ${roots.size}")
}
}
reportCycles(
bonesByKey.keys,
{ bonesByKey.getValue(it).resource.value.parent },
) { start, _, cycle ->
val overrideOrigin =
cycle.mapNotNull { bonesByKey.getValue(it).originOrNull(BoneField.Parent) }
.lastOrNull()
diagnostics += bonesByKey.getValue(start).origin(overrideOrigin)
.diagnostic("Bone hierarchy contains a cycle: ${cycle.joinToString(" -> ")}")
}
}
@@ -0,0 +1,27 @@
package dev.slimevr.resourcepacks.bones
import dev.slimevr.resourcepacks.BoneInputs
import dev.slimevr.resourcepacks.BoneOutputs
import dev.slimevr.resourcepacks.Constraint
import dev.slimevr.resourcepacks.Offset
import dev.slimevr.resourcepacks.RotationFallback
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class BoneDefinition(
@SerialName("$" + "schema") val schema: String? = null,
val key: String,
val nameKey: String,
val mirror: String? = null,
val batterySources: List<String>? = null,
val candidateSources: List<String>? = null,
val overridable: Boolean? = null,
val parent: String? = null,
val headOffset: Offset? = null,
val tailOffset: Offset? = null,
val rotationFallback: RotationFallback? = null,
val constraint: Constraint? = null,
val outputs: BoneOutputs? = null,
val inputs: BoneInputs? = null,
)
@@ -0,0 +1,198 @@
package dev.slimevr.resourcepacks.bones
import dev.slimevr.bones.BoneId
import dev.slimevr.bones.BoneMap
import dev.slimevr.bones.BoneRegistry
import dev.slimevr.bones.BoneSet
import dev.slimevr.bones.Constraint
import dev.slimevr.resourcepacks.EmitSource
import dev.slimevr.resourcepacks.FixedProportionDefault
import dev.slimevr.resourcepacks.HeightRatioProportionDefault
import dev.slimevr.resourcepacks.PipelineStep
import dev.slimevr.resourcepacks.ProportionDefault
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.rpc.RoutingOutput
import solarxr_protocol.rpc.SkeletonBone
import kotlin.collections.iterator
private fun resolveDefault(default: ProportionDefault, height: Float): Float = when (default) {
is FixedProportionDefault -> default.value
is HeightRatioProportionDefault -> default.value * height
}
/** Height, in meters, that the core pack's `heightRatio` proportion defaults are expressed against. */
const val REFERENCE_HEIGHT = 1.58f
/** The proportion key corresponding to this [SkeletonBone].
* FIXME: Remove SkeletonBone completely. Also from solarxr
*/
val SkeletonBone.proportionKey: String get() = "slimevr:${name.lowercase()}"
/** Inverse of [SkeletonBone.proportionKey]; null for a proportion key no [SkeletonBone] names (an extension pack's). */
fun skeletonBoneOf(proportionKey: String): SkeletonBone? = SkeletonBone.entries.firstOrNull { it.proportionKey == proportionKey }
data class CompiledProportion(
val key: String,
val nameKey: String,
val descriptionKey: String?,
val contributesToHeight: Boolean,
val minimum: Float?,
val maximum: Float?,
val default: ProportionDefault,
)
data class CompiledOffsetTerm(val proportion: String, val direction: Vector3)
/** A bone's resolved offset: a fixed [base] plus a weighted sum of proportion [terms]. */
data class CompiledOffset(val base: Vector3, val terms: List<CompiledOffsetTerm>)
/** Resolved bone geometry mapping tail and head vectors for all bones. */
class BoneOffsets(val tail: BoneMap<Vector3>, val head: BoneMap<Vector3>)
/** A bone's compiled VMC output: its Unity name(s), resolved output/input parent, and rest rotation. */
data class CompiledVmcOutput(
val names: List<String>,
val outputParent: BoneId?,
val inputParent: BoneId?,
val restRotation: Quaternion,
)
/** A compiled VRChat OSC emission, with its optional relative bone resolved to an ID. */
data class CompiledEmitEntry(
val from: EmitSource,
val relativeTo: BoneId?,
val steps: List<PipelineStep>,
)
/** A bone's compiled VRChat output: whether it's forced on, and its OSC emissions by address. */
data class CompiledVrchatOutput(val required: Boolean, val emit: Map<String, CompiledEmitEntry>)
/**
* Everything [dev.slimevr.resourcepacks.compiler.compileResourcePacks] resolves for one bone: its offsets, constraint, routing
* facts, and output/input declarations. A plain bone with none of these has every field null.
*/
data class CompiledBone(
val tailOffset: CompiledOffset? = null,
val headOffset: CompiledOffset? = null,
val constraint: Constraint? = null,
val mirror: BoneId? = null,
/** Null if the bone declares no `candidateSources` at all; distinct from an empty list. */
val candidateSources: List<BoneId>? = null,
val batterySources: List<BoneId>? = null,
val overridable: Boolean = false,
val driverOutput: Boolean = false,
val vmc: CompiledVmcOutput? = null,
val vrchat: CompiledVrchatOutput? = null,
val vrchatInput: String? = null,
)
/**
* The compiled bone registry, proportion catalog, and per-bone data produced by
* [dev.slimevr.resourcepacks.compiler.compileResourcePacks].
*/
class CompiledSkeleton(
val registry: BoneRegistry,
val proportions: Map<String, CompiledProportion>,
private val bones: BoneMap<CompiledBone>,
val copyRotationFallbacks: List<Pair<BoneId, BoneId>>,
val firstActiveRotationFallbacks: List<Pair<BoneId, List<BoneId>>>,
val vmcInputOrder: List<BoneId>,
) {
private val boneEntries = bones.entries
val constraints: BoneMap<Constraint> = BoneMap.of<Constraint>(registry).also { map ->
for ((boneId, bone) in boneEntries) bone.constraint?.let { map[boneId] = it }
}
private val driverOutputs = BoneSet.of(registry, boneEntries.filter { it.value.driverOutput }.map { it.key })
/** Bones with a VMC output declaration. Equal to [acceptedBones] of [RoutingOutput.VMC]. */
val vmcNamedBones: Set<BoneId> = BoneSet.of(registry, boneEntries.filter { it.value.vmc != null }.map { it.key })
/** Bones with a VRChat OSC emission declared. Equal to [acceptedBones] of [RoutingOutput.VRC_OSC]. */
val vrchatEmittingBones: Set<BoneId> = BoneSet.of(registry, boneEntries.filter { it.value.vrchat != null }.map { it.key })
private val vrchatRequired = BoneSet.of(registry, boneEntries.filter { it.value.vrchat?.required == true }.map { it.key })
val overridableBones: BoneSet = BoneSet.of(registry, boneEntries.filter { it.value.overridable }.map { it.key })
/** Bones with a `candidateSources` list, each naming the bones that make it a routing candidate. */
val candidateBones: Set<BoneId> = BoneSet.of(registry, boneEntries.filter { it.value.candidateSources != null }.map { it.key })
val vrchatInputAddresses: Map<String, BoneId> =
boneEntries.mapNotNull { (boneId, bone) -> bone.vrchatInput?.let { it to boneId } }.toMap()
/** Exact VMC/Unity bone name to the bone it names. */
val unityNameToBone: Map<String, BoneId> =
boneEntries.flatMap { (boneId, bone) -> bone.vmc?.names.orEmpty().map { it to boneId } }.toMap()
/** Bones [output] can receive, from each bone's `outputs.driver`/`outputs.vmc`/`outputs.vrchat`. */
fun acceptedBones(output: RoutingOutput): Set<BoneId> = when (output) {
RoutingOutput.DRIVER -> driverOutputs
RoutingOutput.VMC -> vmcNamedBones
RoutingOutput.VRC_OSC -> vrchatEmittingBones
}
/**
* Bones [output] that are required and cannot be disabled
*/
fun requiredBones(output: RoutingOutput): Set<BoneId> = when (output) {
RoutingOutput.DRIVER -> emptySet()
RoutingOutput.VMC -> vmcNamedBones
RoutingOutput.VRC_OSC -> vrchatRequired
}
fun candidateSourcesOf(boneId: BoneId): List<BoneId> = bones[boneId]?.candidateSources ?: emptyList()
/** Ordered bones whose assigned tracker's battery represents [boneId]'s battery. */
fun batterySourcesOf(boneId: BoneId): List<BoneId> = bones[boneId]?.batterySources ?: emptyList()
fun emitEntriesOf(boneId: BoneId): Map<String, CompiledEmitEntry> = bones[boneId]?.vrchat?.emit ?: emptyMap()
fun vmcOutputOf(boneId: BoneId): CompiledVmcOutput? = bones[boneId]?.vmc
/** A bone's VMC mirror-image bone, itself if it has none. */
fun mirrorOf(boneId: BoneId): BoneId = bones[boneId]?.mirror ?: boneId
/** Every proportion's default value at [height], keyed by proportion key. */
fun defaultProportionValues(height: Float = REFERENCE_HEIGHT): Map<String, Float> {
val result = mutableMapOf<String, Float>()
for ((key, proportion) in proportions) result[key] = resolveDefault(proportion.default, height)
return result
}
/** The default value of every height-ratio proportion at [height], keyed by proportion key. */
fun heightScaledProportionValues(height: Float): Map<String, Float> {
val result = mutableMapOf<String, Float>()
for ((key, proportion) in proportions) {
if (proportion.default is HeightRatioProportionDefault) result[key] = resolveDefault(proportion.default, height)
}
return result
}
/** Sums the `contributesToHeight` proportions in [values] to derive standing height. */
fun height(values: Map<String, Float>): Float {
var sum = 0f
for ((key, proportion) in proportions) if (proportion.contributesToHeight) sum += values[key] ?: 0f
return sum
}
private fun resolve(offset: CompiledOffset, values: Map<String, Float>): Vector3 {
var sum = offset.base
for (term in offset.terms) sum += term.direction * (values[term.proportion] ?: 0f)
return sum
}
private fun isResolvable(offset: CompiledOffset, values: Map<String, Float>): Boolean = offset.terms.isEmpty() || offset.terms.any { it.proportion in values }
fun toBoneOffsets(values: Map<String, Float>): BoneOffsets {
val tail = BoneMap.of<Vector3>(registry)
val head = BoneMap.of<Vector3>(registry)
for ((boneId, bone) in boneEntries) {
bone.tailOffset?.let { if (isResolvable(it, values)) tail[boneId] = resolve(it, values) }
bone.headOffset?.let { if (isResolvable(it, values)) head[boneId] = resolve(it, values) }
}
return BoneOffsets(tail, head)
}
}
@@ -0,0 +1,169 @@
package dev.slimevr.resourcepacks.bones.outputs
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.BoneId
import dev.slimevr.bones.BoneMap
import dev.slimevr.bones.BoneRegistry
import dev.slimevr.bones.key
import dev.slimevr.resourcepacks.VmcInputParent
import dev.slimevr.resourcepacks.VmcOutput
import dev.slimevr.resourcepacks.bones.CompiledVmcOutput
import dev.slimevr.resourcepacks.bones.origin
import dev.slimevr.resourcepacks.bones.resolveBoneKey
import dev.slimevr.resourcepacks.compiler.BoneContribution
import dev.slimevr.resourcepacks.compiler.BoneField
import dev.slimevr.resourcepacks.compiler.ResourcePackCompilationDiagnostic
import dev.slimevr.resourcepacks.compiler.diagnostic
import dev.slimevr.resourcepacks.compiler.reportCycles
import dev.slimevr.resourcepacks.compiler.reportDuplicateBoneKey
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import kotlin.collections.iterator
import kotlin.math.cos
import kotlin.math.sin
import com.jme3.math.FastMath.DEG_TO_RAD as degToRad
/** Resolves each bone's VMC output, dynamically re-rooting the hierarchy at the hip if no explicit parents are set. */
internal fun compileVmcOutputs(
registry: BoneRegistry,
contributions: Map<BoneId, Pair<BoneContribution, VmcOutput>>,
diagnostics: MutableList<ResourcePackCompilationDiagnostic>,
): BoneMap<CompiledVmcOutput> {
val result = BoneMap.of<CompiledVmcOutput>(registry)
val hip = registry[BodyPart.HIP.key] ?: return result
val bfsParent = mutableMapOf<BoneId, BoneId?>(hip to null)
val adjacency = mutableMapOf<BoneId, MutableList<BoneId>>()
for (index in 1..registry.maxId) {
val boneId = BoneId(index.toUShort())
val parent = registry.parentOf(boneId) ?: continue
adjacency.getOrPut(boneId) { mutableListOf() }.add(parent)
adjacency.getOrPut(parent) { mutableListOf() }.add(boneId)
}
val queue = ArrayDeque(listOf(hip))
while (queue.isNotEmpty()) {
val current = queue.removeFirst()
for (neighbor in adjacency[current].orEmpty()) {
if (neighbor in bfsParent) continue
bfsParent[neighbor] = current
queue += neighbor
}
}
fun namedAncestor(boneId: BoneId): BoneId? {
var current = bfsParent[boneId]
while (current != null && current !in contributions) current = bfsParent[current]
return current
}
for ((boneId, pair) in contributions) {
val (contribution, vmc) = pair
val origin = contribution.origin(BoneField.OutputsVmc)
val outputParent = vmc.outputParent?.let {
resolveBoneKey(
it,
origin,
"outputs.vmc.outputParent",
registry,
diagnostics,
)
} ?: namedAncestor(boneId)
val inputParent = when (val parent = vmc.inputParent) {
VmcInputParent.Omitted -> outputParent
VmcInputParent.ExplicitNull -> null
is VmcInputParent.Bone -> resolveBoneKey(
parent.key,
origin,
"outputs.vmc.inputParent",
registry,
diagnostics,
)
}
result[boneId] = CompiledVmcOutput(
names = vmc.name.values,
outputParent = outputParent,
inputParent = inputParent,
restRotation = (
vmc.restRotation
?: emptyList()
).fold(Quaternion.IDENTITY) { acc, step ->
axisAngleQuaternion(
Vector3(step.axis.x, step.axis.y, step.axis.z),
step.degrees * degToRad,
) *
acc
},
)
}
validateVmcOutputs(registry, result, contributions, diagnostics)
return result
}
private fun validateVmcOutputs(
registry: BoneRegistry,
outputs: BoneMap<CompiledVmcOutput>,
contributions: Map<BoneId, Pair<BoneContribution, VmcOutput>>,
diagnostics: MutableList<ResourcePackCompilationDiagnostic>,
) {
val names = mutableMapOf<String, BoneId>()
for ((boneId, output) in outputs) {
val contribution = contributions.getValue(boneId).first
val origin = contribution.origin(BoneField.OutputsVmc)
for (name in output.names) {
reportDuplicateBoneKey(
names,
name,
boneId,
"VMC name",
registry,
origin,
diagnostics,
)
}
for ((field, parent) in listOf("outputParent" to output.outputParent, "inputParent" to output.inputParent)) {
if (parent != null && parent !in outputs) {
val parentKey = registry.keyOf(parent) ?: parent.toString()
diagnostics += origin.diagnostic("VMC $field '$parentKey' does not have a VMC output")
}
}
}
fun validateParentGraph(field: String, parentOf: (CompiledVmcOutput) -> BoneId?) {
reportCycles(
outputs.keys,
{ outputs[it]?.let(parentOf) },
) { _, lastVisited, cycle ->
val origin =
contributions.getValue(lastVisited).first.origin(BoneField.OutputsVmc)
val keys = cycle.map { registry.keyOf(it) ?: it.toString() }
diagnostics += origin.diagnostic(
"VMC $field graph contains a cycle: ${
keys.joinToString(
" -> ",
)
}",
)
}
}
validateParentGraph("outputParent", CompiledVmcOutput::outputParent)
validateParentGraph("inputParent", CompiledVmcOutput::inputParent)
}
internal fun compileVmcInputOrder(outputs: BoneMap<CompiledVmcOutput>): List<BoneId> {
val childrenByParent = outputs.entries.groupBy({ it.value.inputParent }, { it.key })
val result = mutableListOf<BoneId>()
val visited = mutableSetOf<BoneId>()
fun visit(boneId: BoneId) {
if (!visited.add(boneId)) return
result += boneId
childrenByParent[boneId]?.forEach(::visit)
}
childrenByParent[null].orEmpty().forEach(::visit)
outputs.keys.forEach(::visit)
return result
}
private fun axisAngleQuaternion(axis: Vector3, radians: Float): Quaternion {
val half = radians / 2f
return Quaternion(cos(half), axis.unit() * sin(half))
}
@@ -0,0 +1,108 @@
package dev.slimevr.resourcepacks.bones.outputs
import dev.slimevr.bones.BoneId
import dev.slimevr.bones.BoneMap
import dev.slimevr.bones.BoneRegistry
import dev.slimevr.resourcepacks.EmitEntry
import dev.slimevr.resourcepacks.EmitSource
import dev.slimevr.resourcepacks.PipelineStep
import dev.slimevr.resourcepacks.ScalarOrVector
import dev.slimevr.resourcepacks.bones.CompiledEmitEntry
import dev.slimevr.resourcepacks.bones.origin
import dev.slimevr.resourcepacks.bones.resolveBoneKey
import dev.slimevr.resourcepacks.compiler.BoneContribution
import dev.slimevr.resourcepacks.compiler.BoneField
import dev.slimevr.resourcepacks.compiler.ResourceOrigin
import dev.slimevr.resourcepacks.compiler.ResourcePackCompilationDiagnostic
import dev.slimevr.resourcepacks.compiler.diagnostic
import dev.slimevr.resourcepacks.compiler.reportDuplicateBoneKey
import kotlin.collections.iterator
internal fun compileEmitEntries(
registry: BoneRegistry,
contributions: Map<BoneId, Pair<BoneContribution, Map<String, EmitEntry>>>,
diagnostics: MutableList<ResourcePackCompilationDiagnostic>,
): BoneMap<Map<String, CompiledEmitEntry>> {
val result = BoneMap.of<Map<String, CompiledEmitEntry>>(registry)
val addresses = mutableMapOf<String, BoneId>()
for ((boneId, pair) in contributions) {
val (contribution, entries) = pair
result[boneId] = entries.mapValues { (address, entry) ->
val origin = contribution.origin(BoneField.OutputsVrchatEmit(address))
reportDuplicateBoneKey(
addresses,
address,
boneId,
"VRChat emit address",
registry,
origin,
diagnostics,
)
validateEmitPipeline(address, entry, origin, diagnostics)
CompiledEmitEntry(
from = entry.from,
relativeTo = entry.relativeTo?.let {
resolveBoneKey(
it,
origin,
"outputs.vrchat.emit.relativeTo",
registry,
diagnostics,
)
},
steps = entry.value ?: emptyList(),
)
}
}
return result
}
private enum class EmitValueType { ROTATION, VECTOR, NUMBER, BOOLEAN }
private fun validateEmitPipeline(
address: String,
entry: EmitEntry,
origin: ResourceOrigin,
diagnostics: MutableList<ResourcePackCompilationDiagnostic>,
) {
var type = when (entry.from) {
EmitSource.POSITION -> EmitValueType.VECTOR
EmitSource.ROTATION -> EmitValueType.ROTATION
}
for ((index, step) in entry.value.orEmpty().withIndex()) {
val (operation, next) = when (step) {
is PipelineStep.Euler -> {
"euler" to if (type != EmitValueType.ROTATION) {
null
} else if (step.spec.axis == null) {
EmitValueType.VECTOR
} else {
EmitValueType.NUMBER
}
}
is PipelineStep.Scale -> "scale" to arithmeticResult(type, step.operand)
is PipelineStep.Divide -> "divide" to arithmeticResult(type, step.operand)
is PipelineStep.Offset -> "offset" to arithmeticResult(type, step.operand)
is PipelineStep.Clamp -> "clamp" to type.takeIf { it == EmitValueType.NUMBER || it == EmitValueType.VECTOR }
is PipelineStep.GreaterThan -> "greaterThan" to EmitValueType.BOOLEAN.takeIf { type == EmitValueType.NUMBER }
is PipelineStep.LessThan -> "lessThan" to EmitValueType.BOOLEAN.takeIf { type == EmitValueType.NUMBER }
}
if (next == null) {
diagnostics += origin.diagnostic("VRChat emit '$address' cannot apply $operation to ${type.name.lowercase()} at pipeline step ${index + 1}")
return
}
type = next
}
}
private fun arithmeticResult(type: EmitValueType, operand: ScalarOrVector): EmitValueType? = when (type) {
EmitValueType.ROTATION, EmitValueType.VECTOR -> type
EmitValueType.NUMBER -> if (operand is ScalarOrVector.Scalar) EmitValueType.NUMBER else null
EmitValueType.BOOLEAN -> null
}
@@ -0,0 +1,25 @@
package dev.slimevr.resourcepacks
import kotlinx.serialization.json.JsonObject
data class SourcedResource<T>(val path: String, val value: T, val raw: JsonObject)
class ParsedResourcePack(
val source: String,
val manifest: SourcedResource<PackManifest>,
val objects: Map<ResourceType<*>, List<Pair<String, JsonObject>>>,
val entries: Map<String, ResourcePackEntry> = emptyMap(),
)
data class ResourcePackDiagnostic(val path: String, val pointer: String = "", val message: String)
class ResourcePackParseException(val diagnostics: List<ResourcePackDiagnostic>) :
IllegalArgumentException(
diagnostics.joinToString("\n") { "${it.path}${it.pointer}: ${it.message}" },
)
data class ResourcePackFailure(val folder: String, val diagnostics: List<ResourcePackDiagnostic>)
data class ResourcePackCatalog(
val core: ParsedResourcePack,
val userPacks: List<ParsedResourcePack>,
val failures: List<ResourcePackFailure>,
)
@@ -0,0 +1,44 @@
package dev.slimevr.resourcepacks.compiler
import dev.slimevr.resourcepacks.ParsedResourcePack
import dev.slimevr.resourcepacks.SourcedResource
import dev.slimevr.resourcepacks.bones.BoneDefinition
import dev.slimevr.resourcepacks.proportions.ProportionDefinition
/** Tracks bone properties by their JSON path to attribute overrides. */
internal sealed class BoneField(val path: List<String>) {
object Mirror : BoneField(listOf("mirror"))
object BatterySources : BoneField(listOf("batterySources"))
object CandidateSources : BoneField(listOf("candidateSources"))
object Parent : BoneField(listOf("parent"))
object HeadOffset : BoneField(listOf("headOffset"))
object TailOffset : BoneField(listOf("tailOffset"))
object RotationFallback : BoneField(listOf("rotationFallback"))
object OutputsVmc : BoneField(listOf("outputs", "vmc"))
object InputsVrchat : BoneField(listOf("inputs", "vrchat"))
class OutputsVrchatEmit(address: String) : BoneField(listOf("outputs", "vrchat", "emit", address))
}
/** One pack's contribution of a [T]-typed resource, with the origin of whichever pack last overrode each JSON path. */
internal data class Contribution<T>(
val pack: ParsedResourcePack,
val resource: SourcedResource<T>,
/** The pack that last set or removed the property at each path, keyed by that property's JSON path. */
val origins: Map<List<String>, ResourceOrigin> = emptyMap(),
val latestOverride: ResourceOrigin? = null,
) {
internal val definitionOrigin get() = ResourceOrigin(pack, resource.path)
internal fun originOrNull(path: List<String>): ResourceOrigin? {
for (length in path.size downTo 0) origins[path.subList(0, length)]?.let { return it }
return null
}
/** An origin already resolved elsewhere (e.g. across several bones), falling back to this resource's own defining pack. */
fun origin(resolved: ResourceOrigin?): ResourceOrigin = resolved ?: validationOrigin()
fun validationOrigin(): ResourceOrigin = latestOverride ?: definitionOrigin
}
internal typealias BoneContribution = Contribution<BoneDefinition>
internal typealias ProportionContribution = Contribution<ProportionDefinition>
@@ -0,0 +1,44 @@
package dev.slimevr.resourcepacks.compiler
import dev.slimevr.bones.BoneId
import dev.slimevr.bones.BoneRegistry
import dev.slimevr.resourcepacks.ParsedResourcePack
data class ResourcePackCompilationDiagnostic(val packId: String, val path: String, val message: String)
class ResourcePackCompilationException(val diagnostics: List<ResourcePackCompilationDiagnostic>) :
IllegalArgumentException(
diagnostics.joinToString("\n") { "${it.packId}:${it.path}: ${it.message}" },
)
internal data class ResourceOrigin(val pack: ParsedResourcePack, val path: String)
internal fun ResourceOrigin.diagnostic(message: String) = ResourcePackCompilationDiagnostic(pack.manifest.value.id, path, message)
/** Finds every cycle reachable by following [parentOf] from each of [nodes]. */
internal fun <T> reportCycles(nodes: Iterable<T>, parentOf: (T) -> T?, report: (start: T, lastVisited: T, cycle: Set<T>) -> Unit) {
val reportedCycles = mutableSetOf<Set<T>>()
for (node in nodes) {
val visited = linkedSetOf<T>()
var current: T? = node
while (current != null && visited.add(current)) current = parentOf(current)
if (current == null) continue
val cycle = visited.dropWhile { it != current }.toSet()
if (reportedCycles.add(cycle)) report(node, visited.last(), cycle)
}
}
/** Registers [key] against [boneId] in [seen], reporting a "first used by" diagnostic through [origin] if another bone already claimed it. */
internal fun reportDuplicateBoneKey(
seen: MutableMap<String, BoneId>,
key: String,
boneId: BoneId,
label: String,
registry: BoneRegistry,
origin: ResourceOrigin,
diagnostics: MutableList<ResourcePackCompilationDiagnostic>,
) {
val existing = seen.putIfAbsent(key, boneId) ?: return
val existingKey = registry.keyOf(existing) ?: existing.toString()
diagnostics += origin.diagnostic("Duplicate $label '$key'; first used by '$existingKey'")
}
@@ -0,0 +1,263 @@
package dev.slimevr.resourcepacks.compiler
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.BoneId
import dev.slimevr.bones.BoneMap
import dev.slimevr.bones.BoneRegistry
import dev.slimevr.bones.key
import dev.slimevr.resourcepacks.CopyRotationFallback
import dev.slimevr.resourcepacks.EmitEntry
import dev.slimevr.resourcepacks.FirstActiveRotationFallback
import dev.slimevr.resourcepacks.NoRotationFallback
import dev.slimevr.resourcepacks.ResourcePackCatalog
import dev.slimevr.resourcepacks.ResourceTypes
import dev.slimevr.resourcepacks.VmcOutput
import dev.slimevr.resourcepacks.bones.CompiledBone
import dev.slimevr.resourcepacks.bones.CompiledProportion
import dev.slimevr.resourcepacks.bones.CompiledSkeleton
import dev.slimevr.resourcepacks.bones.CompiledVrchatOutput
import dev.slimevr.resourcepacks.bones.compileConstraint
import dev.slimevr.resourcepacks.bones.compileOffset
import dev.slimevr.resourcepacks.bones.orderFallbackDependencies
import dev.slimevr.resourcepacks.bones.origin
import dev.slimevr.resourcepacks.bones.outputs.compileEmitEntries
import dev.slimevr.resourcepacks.bones.outputs.compileVmcInputOrder
import dev.slimevr.resourcepacks.bones.outputs.compileVmcOutputs
import dev.slimevr.resourcepacks.bones.resolveBoneKey
import dev.slimevr.resourcepacks.bones.resolveFallbackBone
import dev.slimevr.resourcepacks.bones.validateHierarchy
import kotlin.collections.iterator
import kotlin.collections.plusAssign
import kotlin.collections.set
import solarxr_protocol.connection.BoneDefinition as WireBoneDefinition
import solarxr_protocol.connection.BoneRegistry as WireBoneRegistry
/** Compiles the ordered resource-pack stack into a runtime [CompiledSkeleton]. */
fun compileResourcePacks(catalog: ResourcePackCatalog): CompiledSkeleton = compileSkeleton(resolveResourcePacks(catalog))
internal fun compileSkeleton(resources: ResolvedResourcePacks): CompiledSkeleton {
val catalog = resources.catalog
val diagnostics = mutableListOf<ResourcePackCompilationDiagnostic>()
val packs = listOf(catalog.core) + catalog.userPacks
if (catalog.core.manifest.value.id != "slimevr:core") {
diagnostics += ResourcePackCompilationDiagnostic(
catalog.core.manifest.value.id,
catalog.core.manifest.path,
"Expected bundled core pack ID 'slimevr:core'",
)
}
val bonesByKey = resources.keyed(ResourceTypes.BONE) { it.key }
val proportionsByKey = resources.keyed(ResourceTypes.PROPORTION) { it.key }
val translations = resources.get(ResourceTypes.LANGUAGE).values
.filter { it.resource.path.endsWith("/en.json") }
.flatMap { contribution ->
contribution.resource.value.translations.map { (key, value) ->
val origin = contribution.originOrNull(listOf(key)) ?: contribution.validationOrigin()
Triple(key, value, packs.indexOf(origin.pack))
}
}
.sortedBy { it.third }
.associate { it.first to it.second }
val standardParts = BodyPart.entries.filter { it != BodyPart.NONE }
val standardPartsByKey = standardParts.associateBy(BodyPart::key)
for (part in standardParts) {
if (part.key !in bonesByKey) {
diagnostics += ResourcePackCompilationDiagnostic(
catalog.core.manifest.value.id,
catalog.core.manifest.path,
"Missing standard bone '${part.key}'",
)
}
}
for ((key, contribution) in bonesByKey) {
val part = standardPartsByKey[key]
if (part != null && contribution.pack !== catalog.core) {
diagnostics += ResourcePackCompilationDiagnostic(
contribution.pack.manifest.value.id,
contribution.resource.path,
"Standard bone '$key' belongs to the core pack",
)
}
if (part == null && contribution.pack === catalog.core) {
diagnostics += ResourcePackCompilationDiagnostic(
catalog.core.manifest.value.id,
contribution.resource.path,
"Core pack defines non-standard bone '$key'",
)
}
contribution.resource.value.parent?.let { parent ->
if (parent !in bonesByKey) diagnostics += contribution.origin(BoneField.Parent).diagnostic("Unknown parent bone '$parent'")
}
}
if (diagnostics.isEmpty()) validateHierarchy(catalog.core, bonesByKey, diagnostics)
if (diagnostics.isNotEmpty()) throw ResourcePackCompilationException(diagnostics)
val standardContributions = standardParts.map { part -> bonesByKey.getValue(part.key) }
val extensions = bonesByKey.values.filter { it.resource.value.key !in standardPartsByKey }
val allContributions = standardContributions + extensions
val idByKey = allContributions.mapIndexed { index, contribution -> contribution.resource.value.key to (index + 1).toUShort() }.toMap()
val registry = BoneRegistry.from(
WireBoneRegistry(
bones = allContributions.mapIndexed { index, contribution ->
val definition = contribution.resource.value
WireBoneDefinition(
id = (index + 1).toUShort(),
key = definition.key,
displayName = translations[definition.nameKey] ?: definition.nameKey,
parent = definition.parent?.let(idByKey::getValue) ?: 0.toUShort(),
)
},
),
)
val proportions = proportionsByKey.mapValues { (key, contribution) ->
val definition = contribution.resource.value
CompiledProportion(
key = key,
nameKey = definition.nameKey,
descriptionKey = definition.descriptionKey,
contributesToHeight = definition.contributesToHeight ?: false,
minimum = definition.minimum,
maximum = definition.maximum,
default = definition.default,
)
}
val bones = mutableMapOf<BoneId, CompiledBone>()
val copyFallbacksByBoneId = mutableMapOf<BoneId, Pair<BoneContribution, CopyRotationFallback>>()
val firstActiveFallbacksByBoneId = mutableMapOf<BoneId, Pair<BoneContribution, FirstActiveRotationFallback>>()
val vmcContributions = mutableMapOf<BoneId, Pair<BoneContribution, VmcOutput>>()
val emitContributions = mutableMapOf<BoneId, Pair<BoneContribution, Map<String, EmitEntry>>>()
val vrchatRequired = mutableSetOf<BoneId>()
val vrchatInputAddresses = mutableMapOf<String, BoneId>()
for (contribution in allContributions) {
val definition = contribution.resource.value
val boneId = registry[definition.key] ?: continue
when (val fallback = definition.rotationFallback) {
null, is NoRotationFallback -> {}
is CopyRotationFallback -> copyFallbacksByBoneId[boneId] = contribution to fallback
is FirstActiveRotationFallback -> firstActiveFallbacksByBoneId[boneId] = contribution to fallback
}
definition.outputs?.vmc?.let { vmcContributions[boneId] = contribution to it }
definition.outputs?.vrchat?.let {
if (it.required == true) vrchatRequired += boneId
emitContributions[boneId] = contribution to it.emit
}
definition.inputs?.vrchat?.let { input ->
reportDuplicateBoneKey(
vrchatInputAddresses,
input.address,
boneId,
"VRChat input address",
registry,
contribution.origin(BoneField.InputsVrchat),
diagnostics,
)
}
bones[boneId] = CompiledBone(
tailOffset = definition.tailOffset?.let {
compileOffset(
it,
contribution.origin(BoneField.TailOffset),
proportionsByKey,
diagnostics,
)
},
headOffset = definition.headOffset?.let {
compileOffset(
it,
contribution.origin(BoneField.HeadOffset),
proportionsByKey,
diagnostics,
)
},
constraint = definition.constraint?.let { compileConstraint(it) },
mirror = definition.mirror?.let {
resolveBoneKey(
it,
contribution.origin(BoneField.Mirror),
"mirror",
registry,
diagnostics,
)
},
candidateSources = definition.candidateSources?.map {
resolveBoneKey(
it,
contribution.origin(BoneField.CandidateSources),
"candidateSources",
registry,
diagnostics,
)
},
batterySources = definition.batterySources?.map {
resolveBoneKey(
it,
contribution.origin(BoneField.BatterySources),
"batterySources",
registry,
diagnostics,
)
},
overridable = definition.overridable == true,
driverOutput = definition.outputs?.driver != null,
vrchatInput = definition.inputs?.vrchat?.address,
)
}
val hierarchyOrder = registry.hierarchyFrom(registry.root).map { it.second }
val resolvedCopyRotationFallbacks = hierarchyOrder.mapNotNull { boneId ->
copyFallbacksByBoneId[boneId]?.let { (contribution, fallback) ->
boneId to resolveFallbackBone(
fallback.source,
contribution,
registry,
diagnostics,
)
}
}
val resolvedFirstActiveRotationFallbacks = hierarchyOrder.mapNotNull { boneId ->
firstActiveFallbacksByBoneId[boneId]?.let { (contribution, fallback) ->
boneId to fallback.sources.map {
resolveFallbackBone(
it,
contribution,
registry,
diagnostics,
)
}
}
}
val firstActiveBones = resolvedFirstActiveRotationFallbacks.mapTo(mutableSetOf()) { it.first }
for ((boneId, source) in resolvedCopyRotationFallbacks) {
if (source !in firstActiveBones) continue
val contribution = copyFallbacksByBoneId.getValue(boneId).first
val sourceKey = registry.keyOf(source) ?: source.toString()
diagnostics += contribution.origin(BoneField.RotationFallback).diagnostic(
"A copy rotationFallback cannot use firstActive bone '$sourceKey' as its source because copy fallbacks run first",
)
}
val copyRotationFallbacks =
orderFallbackDependencies(resolvedCopyRotationFallbacks) { it }
val firstActiveRotationFallbacks =
orderFallbackDependencies(resolvedFirstActiveRotationFallbacks) { it.lastOrNull() }
val vmcOutputMetadata = compileVmcOutputs(registry, vmcContributions, diagnostics)
val emitEntries = compileEmitEntries(registry, emitContributions, diagnostics)
val vmcInputOrder = compileVmcInputOrder(vmcOutputMetadata)
if (diagnostics.isNotEmpty()) throw ResourcePackCompilationException(diagnostics)
val boneMap = BoneMap.of<CompiledBone>(registry)
for ((boneId, bone) in bones) {
boneMap[boneId] = bone.copy(
vmc = vmcOutputMetadata[boneId],
vrchat = emitEntries[boneId]?.let { CompiledVrchatOutput(required = boneId in vrchatRequired, emit = it) },
)
}
return CompiledSkeleton(registry, proportions, boneMap, copyRotationFallbacks, firstActiveRotationFallbacks, vmcInputOrder)
}
@@ -0,0 +1,131 @@
package dev.slimevr.resourcepacks.compiler
import dev.slimevr.resourcepacks.ParsedResourcePack
import dev.slimevr.resourcepacks.ResourcePackCatalog
import dev.slimevr.resourcepacks.ResourcePackDiagnostic
import dev.slimevr.resourcepacks.ResourceType
import dev.slimevr.resourcepacks.SourcedResource
import dev.slimevr.resourcepacks.orderResourcePacks
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
internal class ResolvedResourcePacks(
val catalog: ResourcePackCatalog,
private val resources: Map<ResourceType<*>, Map<String, Contribution<*>>>,
) {
val entries = (listOf(catalog.core) + catalog.userPacks).flatMap { it.entries.entries }.associate { it.key to it.value }
@Suppress("UNCHECKED_CAST")
fun <T : Any> get(type: ResourceType<T>): Map<String, Contribution<T>> = resources[type].orEmpty() as Map<String, Contribution<T>>
fun <T : Any> keyed(type: ResourceType<T>, keyOf: (T) -> String): Map<String, Contribution<T>> {
val result = linkedMapOf<String, Contribution<T>>()
val diagnostics = mutableListOf<ResourcePackCompilationDiagnostic>()
for (contribution in get(type).values) {
val key = keyOf(contribution.resource.value)
if (result.putIfAbsent(key, contribution) != null) {
diagnostics += contribution.validationOrigin().diagnostic("Duplicate ${type.id} key '$key'")
}
}
if (diagnostics.isNotEmpty()) throw ResourcePackCompilationException(diagnostics)
return result
}
}
/** Applies path precedence, inheritance and validation once for every registered resource type. */
internal fun resolveResourcePacks(catalog: ResourcePackCatalog): ResolvedResourcePacks {
val ordered = orderResourcePacks(catalog)
val packs = listOf(ordered.core) + ordered.userPacks
val diagnostics = mutableListOf<ResourcePackCompilationDiagnostic>()
val resources = packs.flatMap { it.objects.keys }.distinct().associateWith { type ->
resolveType(packs, type, diagnostics)
}
if (diagnostics.isNotEmpty()) throw ResourcePackCompilationException(diagnostics)
return ResolvedResourcePacks(ordered, resources)
}
private data class Layer(val pack: ParsedResourcePack, val document: JsonObject)
private data class LayerId(val path: String, val index: Int)
private data class ResolvedDocument(val document: JsonObject, val origins: Map<List<String>, ResourceOrigin>)
private fun <T : Any> resolveType(
packs: List<ParsedResourcePack>,
type: ResourceType<T>,
diagnostics: MutableList<ResourcePackCompilationDiagnostic>,
): Map<String, Contribution<T>> {
val layers = linkedMapOf<String, MutableList<Layer>>()
for (pack in packs) {
for ((path, document) in pack.objects[type].orEmpty()) {
layers.getOrPut(path) { mutableListOf() }.add(Layer(pack, document))
}
}
val cache = mutableMapOf<LayerId, ResolvedDocument?>()
val visiting = linkedSetOf<LayerId>()
fun resolve(id: LayerId): ResolvedDocument? {
if (cache.containsKey(id)) return cache[id]
val layer = layers.getValue(id.path)[id.index]
val origin = ResourceOrigin(layer.pack, id.path)
if (!visiting.add(id)) {
diagnostics += origin.diagnostic("Cyclic \$extend detected: ${visiting.joinToString(" -> ") { it.path }} -> ${id.path}")
return null
}
fun resolveDocument(): ResolvedDocument? {
val extend = layer.document["\$extend"]
val parent = if (extend != null) {
val path = (extend as? JsonPrimitive)?.takeIf { it.isString }?.content
if (path == null) {
diagnostics += origin.diagnostic("\$extend must be a resource path string")
return null
}
val parentIndex = if (path == id.path) id.index - 1 else layers[path]?.lastIndex ?: -1
if (parentIndex < 0) {
diagnostics += origin.diagnostic("Unknown \$extend target '$path' (no inherited layer)")
return null
}
resolve(LayerId(path, parentIndex)) ?: return null
} else if (type.mergeLayers && id.index > 0) {
resolve(LayerId(id.path, id.index - 1)) ?: return null
} else {
ResolvedDocument(JsonObject(emptyMap()), emptyMap())
}
val origins = parent.origins.toMutableMap()
fun merge(target: JsonObject, source: JsonObject, prefix: List<String>): JsonObject {
val result = target.toMutableMap()
for ((key, value) in source) {
if (key == "\$extend") continue
val path = prefix + key
val existing = result[key]
if (value is JsonObject) {
if (existing !is JsonObject) origins.keys.removeAll { it.take(path.size) == path }
result[key] = merge(existing as? JsonObject ?: JsonObject(emptyMap()), value, path)
origins[path] = origin
} else {
origins.keys.removeAll { it.take(path.size) == path }
origins[path] = origin
result[key] = value
}
}
return JsonObject(result)
}
val document = merge(parent.document, layer.document, emptyList())
origins[emptyList()] = origin
return ResolvedDocument(document, origins)
}
val resolved = resolveDocument()
visiting.remove(id)
cache[id] = resolved
return resolved
}
val result = linkedMapOf<String, Contribution<T>>()
for ((path, stack) in layers) {
val resolved = resolve(LayerId(path, stack.lastIndex)) ?: continue
val origin = ResourceOrigin(stack.last().pack, path)
val localDiagnostics = mutableListOf<ResourcePackDiagnostic>()
val decoded = type.validateAndDecode(path, resolved.document, localDiagnostics)
diagnostics += localDiagnostics.map { origin.diagnostic(it.message) }
if (decoded != null) {
result[path] = Contribution(stack.first().pack, SourcedResource(path, decoded.value, resolved.document), resolved.origins, origin)
}
}
return result
}
@@ -0,0 +1,17 @@
package dev.slimevr.resourcepacks
import kotlinx.serialization.json.JsonObject
fun deepMerge(target: JsonObject, source: JsonObject): JsonObject {
val result = target.toMutableMap()
for ((k, v) in source) {
if (k == "\$extend") continue
val existing = result[k]
if (existing is JsonObject && v is JsonObject) {
result[k] = deepMerge(existing, v)
} else {
result[k] = v
}
}
return JsonObject(result)
}
@@ -0,0 +1,102 @@
package dev.slimevr.resourcepacks
import dev.slimevr.resourcepacks.languages.LanguageResource
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationException
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.decodeFromJsonElement
import kotlinx.serialization.json.float
import kotlinx.serialization.json.jsonPrimitive
private fun Decoder.requireJson(): JsonDecoder = this as? JsonDecoder ?: throw SerializationException("Resource packs require a JSON decoder")
private fun JsonElement.objectValue(): JsonObject = this as? JsonObject ?: throw SerializationException("Expected a JSON object")
private fun neverEncoded(): Nothing = error("Resource packs are never re-encoded")
object VmcNamesSerializer : KSerializer<VmcNames> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("VmcNames", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder) = decoder.requireJson().decodeJsonElement().let { VmcNames(if (it is JsonArray) it.map { name -> name.jsonPrimitive.content } else listOf(it.jsonPrimitive.content)) }
override fun serialize(encoder: Encoder, value: VmcNames) = neverEncoded()
}
object VmcOutputSerializer : KSerializer<VmcOutput> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("VmcOutput", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): VmcOutput {
val json = decoder.requireJson().json
val objectValue = decoder.requireJson().decodeJsonElement().objectValue()
val parent = when (val raw = objectValue["inputParent"]) {
null -> VmcInputParent.Omitted
JsonNull -> VmcInputParent.ExplicitNull
else -> VmcInputParent.Bone(raw.jsonPrimitive.content)
}
return VmcOutput(json.decodeFromJsonElement(objectValue["name"]!!), objectValue["outputParent"]?.jsonPrimitive?.contentOrNull, parent, objectValue["restRotation"]?.let { json.decodeFromJsonElement(it) })
}
override fun serialize(encoder: Encoder, value: VmcOutput) = neverEncoded()
}
object EulerSpecSerializer : KSerializer<EulerSpec> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("EulerSpec", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): EulerSpec {
val json = decoder.requireJson().json
val value = decoder.requireJson().decodeJsonElement()
if (value is JsonPrimitive) return EulerSpec(axis = json.decodeFromJsonElement(value))
val objectValue = value.objectValue()
return EulerSpec(objectValue["axis"]?.let { json.decodeFromJsonElement(it) }, objectValue["order"]?.let { json.decodeFromJsonElement(it) }, objectValue["unit"]?.let { json.decodeFromJsonElement(it) })
}
override fun serialize(encoder: Encoder, value: EulerSpec) = neverEncoded()
}
object ScalarOrVectorSerializer : KSerializer<ScalarOrVector> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("ScalarOrVector", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): ScalarOrVector {
val json = decoder.requireJson().json
val value = decoder.requireJson().decodeJsonElement()
return if (value is JsonPrimitive) ScalarOrVector.Scalar(value.float) else ScalarOrVector.Vector(json.decodeFromJsonElement(value))
}
override fun serialize(encoder: Encoder, value: ScalarOrVector) = neverEncoded()
}
object PipelineStepSerializer : KSerializer<PipelineStep> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("PipelineStep", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): PipelineStep {
val json = decoder.requireJson().json
val (key, value) = decoder.requireJson().decodeJsonElement().objectValue().entries.singleOrNull()
?: throw SerializationException("A pipeline step must have exactly one operation")
return when (key) {
"euler" -> PipelineStep.Euler(json.decodeFromJsonElement(value))
"scale" -> PipelineStep.Scale(json.decodeFromJsonElement(value))
"divide" -> PipelineStep.Divide(json.decodeFromJsonElement(value))
"offset" -> PipelineStep.Offset(json.decodeFromJsonElement(value))
"clamp" -> PipelineStep.Clamp(json.decodeFromJsonElement(value))
"greaterThan" -> PipelineStep.GreaterThan(json.decodeFromJsonElement(value))
"lessThan" -> PipelineStep.LessThan(json.decodeFromJsonElement(value))
else -> throw SerializationException("Unknown pipeline step operation '$key'")
}
}
override fun serialize(encoder: Encoder, value: PipelineStep) = neverEncoded()
}
/** A language file has `$schema` alongside otherwise flat translation entries. */
object LanguageResourceSerializer : KSerializer<LanguageResource> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LanguageResource", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): LanguageResource {
val document = decoder.requireJson().decodeJsonElement().objectValue()
val schema = document["$" + "schema"]?.jsonPrimitive?.contentOrNull
val translations = document.filterKeys { it != "$" + "schema" }.mapValues { (_, value) ->
(value as? JsonPrimitive)?.content ?: throw SerializationException("Language values must be strings")
}
return LanguageResource(schema, translations)
}
override fun serialize(encoder: Encoder, value: LanguageResource) = neverEncoded()
}
@@ -0,0 +1,7 @@
package dev.slimevr.resourcepacks.languages
import dev.slimevr.resourcepacks.LanguageResourceSerializer
import kotlinx.serialization.Serializable
@Serializable(with = LanguageResourceSerializer::class)
data class LanguageResource(val schema: String?, val translations: Map<String, String>)
@@ -0,0 +1,86 @@
package dev.slimevr.resourcepacks
import dev.slimevr.config.ConfigStorage
import dev.slimevr.config.StorageEntryType
import dev.slimevr.config.configPath
import dev.slimevr.logging.AppLogger
import dev.slimevr.resourcepacks.bones.CompiledSkeleton
import dev.slimevr.resourcepacks.compiler.ResourcePackCompilationException
import dev.slimevr.resourcepacks.compiler.compileResourcePacks
import kotlinx.coroutines.CancellationException
import kotlin.time.measureTimedValue
data class LoadedResourcePacks(val catalog: ResourcePackCatalog, val skeleton: CompiledSkeleton)
object ResourcePackManager {
suspend fun loadCompiled(storage: ConfigStorage, classLoader: ClassLoader): LoadedResourcePacks {
val catalog = load(storage, classLoader)
val coreCatalog = catalog.copy(userPacks = emptyList())
val (core, coreCompileTime) = measureTimedValue { compileResourcePacks(coreCatalog) }
AppLogger.config.info("Compiled core pack in ${coreCompileTime.inWholeMilliseconds}ms.")
if (catalog.userPacks.isEmpty()) return LoadedResourcePacks(catalog, core)
return try {
val ordered = orderResourcePacks(catalog)
val (compiled, compileTime) = measureTimedValue { compileResourcePacks(ordered) }
AppLogger.config.info("Compiled resource pack stack in ${compileTime.inWholeMilliseconds}ms.")
LoadedResourcePacks(ordered, compiled)
} catch (e: ResourcePackCompilationException) {
AppLogger.config.error("Unable to compile resource packs; loading bundled core pack only:\n${e.message}")
val failure = ResourcePackFailure(
"compiled stack",
e.diagnostics.map {
ResourcePackDiagnostic("${it.packId}/${it.path}", message = it.message)
},
)
LoadedResourcePacks(coreCatalog.copy(failures = catalog.failures + failure), core)
}
}
suspend fun load(storage: ConfigStorage, classLoader: ClassLoader): ResourcePackCatalog {
val (core, coreTime) = measureTimedValue { ResourcePackParser.parse(ClasspathResourcePackSource.core(classLoader)) }
AppLogger.config.info("Loaded core pack in ${coreTime.inWholeMilliseconds}ms.")
val root = "resourcepacks"
if (!storage.ensureDirectory(root)) {
AppLogger.config.error("Unable to create ${storage.displayPath(root)}; loading bundled core pack only")
return ResourcePackCatalog(core, emptyList(), emptyList())
}
val folders = try {
storage.list(root).filter { it.type == StorageEntryType.DIRECTORY }.sortedBy { it.name }
} catch (e: Exception) {
if (e is CancellationException) throw e
AppLogger.config.error(e, "Unable to enumerate ${storage.displayPath(root)}; loading bundled core pack only")
return ResourcePackCatalog(core, emptyList(), emptyList())
}
val packs = mutableListOf<ParsedResourcePack>()
val failures = mutableListOf<ResourcePackFailure>()
for (folder in folders) {
val packRoot = configPath(root, folder.name)
val containsManifest = try {
storage.list(packRoot).any { it.name == "manifest.json" && it.type == StorageEntryType.FILE }
} catch (e: Exception) {
if (e is CancellationException) throw e
val diagnostic = ResourcePackDiagnostic("manifest.json", message = "Unable to inspect pack: ${e.message}")
failures += ResourcePackFailure(folder.name, listOf(diagnostic))
AppLogger.config.error("Skipping unreadable resource pack '${folder.name}': ${diagnostic.message}")
continue
}
if (!containsManifest) continue
try {
val (parsed, packTime) = measureTimedValue { ResourcePackParser.parse(StorageResourcePackSource(storage, packRoot)) }
if (parsed.manifest.value.formatVersion < ResourcePackParser.CURRENT_FORMAT_VERSION) {
AppLogger.config.warn("Loaded pack '${folder.name}' in ${packTime.inWholeMilliseconds}ms. Format version ${parsed.manifest.value.formatVersion} was automatically migrated to ${ResourcePackParser.CURRENT_FORMAT_VERSION}. This older format is deprecated and may lose support in future updates.")
} else {
AppLogger.config.info("Loaded pack '${folder.name}' in ${packTime.inWholeMilliseconds}ms.")
}
packs += parsed
} catch (e: ResourcePackParseException) {
failures += ResourcePackFailure(folder.name, e.diagnostics)
AppLogger.config.error("Skipping invalid resource pack '${folder.name}': ${e.message}")
}
}
return ResourcePackCatalog(core, packs.toList(), failures.toList())
}
}
@@ -0,0 +1,17 @@
package dev.slimevr.resourcepacks
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class PackManifest(
@SerialName("$" + "schema") val schema: String? = null,
val formatVersion: Int,
val id: String,
val nameKey: String,
val descriptionKey: String,
val version: List<Int>,
val authors: List<String>,
val before: List<String> = emptyList(),
val after: List<String> = emptyList(),
)
@@ -0,0 +1,52 @@
package dev.slimevr.resourcepacks
import dev.slimevr.resourcepacks.compiler.ResourceOrigin
import dev.slimevr.resourcepacks.compiler.ResourcePackCompilationDiagnostic
import dev.slimevr.resourcepacks.compiler.ResourcePackCompilationException
import dev.slimevr.resourcepacks.compiler.diagnostic
import java.util.PriorityQueue
/** Stable ordering of the packs. core, manifest constraints, then pack ID */
internal fun orderResourcePacks(catalog: ResourcePackCatalog): ResourcePackCatalog {
val packs = listOf(catalog.core) + catalog.userPacks
val byId = packs.associateBy { it.manifest.value.id }
val diagnostics = mutableListOf<ResourcePackCompilationDiagnostic>()
for ((id, duplicates) in packs.groupBy { it.manifest.value.id }) {
if (duplicates.size > 1) {
for (pack in duplicates) diagnostics += ResourceOrigin(pack, pack.manifest.path).diagnostic("Duplicate pack ID '$id'")
}
}
if (diagnostics.isNotEmpty()) throw ResourcePackCompilationException(diagnostics)
val edges = byId.keys.associateWith { mutableSetOf<String>() }
val incoming = byId.keys.associateWith { 0 }.toMutableMap()
fun edge(before: String, after: String) {
if (before !in byId || after !in byId) return
if (edges.getValue(before).add(after)) incoming[after] = incoming.getValue(after) + 1
}
for (pack in catalog.userPacks) edge(catalog.core.manifest.value.id, pack.manifest.value.id)
for (pack in packs) {
val manifest = pack.manifest.value
for (before in manifest.before) edge(manifest.id, before)
for (after in manifest.after) edge(after, manifest.id)
}
val ready = PriorityQueue(incoming.filterValues { it == 0 }.keys)
val ordered = mutableListOf<ParsedResourcePack>()
while (ready.isNotEmpty()) {
val id = ready.remove()
ordered += byId.getValue(id)
for (next in edges.getValue(id)) {
incoming[next] = incoming.getValue(next) - 1
if (incoming[next] == 0) ready.add(next)
}
}
if (ordered.size != packs.size) {
val blocked = incoming.filterValues { it > 0 }.keys.sorted()
throw ResourcePackCompilationException(
blocked.map { id ->
val pack = byId.getValue(id)
ResourceOrigin(pack, pack.manifest.path).diagnostic("Pack ordering cycle blocks: ${blocked.joinToString()}; core must load first")
},
)
}
return catalog.copy(userPacks = ordered.filter { it !== catalog.core })
}
@@ -0,0 +1,77 @@
package dev.slimevr.resourcepacks
import kotlinx.coroutines.CancellationException
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonObject
internal val ResourcePackJson = Json {
ignoreUnknownKeys = false
explicitNulls = true
}
object ResourcePackParser {
const val MIN_SUPPORTED_FORMAT_VERSION = 1
const val CURRENT_FORMAT_VERSION = 1
suspend fun parse(source: ResourcePackSource, types: List<ResourceType<*>> = ResourceTypes.ALL): ParsedResourcePack {
val entries = try {
source.entries()
} catch (e: Exception) {
if (e is CancellationException) throw e
throw ResourcePackParseException(listOf(ResourcePackDiagnostic("", message = "Unable to scan ${source.description}: ${e.message}")))
}
val diagnostics = mutableListOf<ResourcePackDiagnostic>()
entries.groupBy { it.path }.filterValues { it.size > 1 }.keys.sorted().forEach { diagnostics += ResourcePackDiagnostic(it, message = "Duplicate resource path") }
val manifestEntry = entries.firstOrNull { it.path == "manifest.json" }
if (manifestEntry == null) {
diagnostics += ResourcePackDiagnostic("manifest.json", message = "Missing manifest")
throw ResourcePackParseException(diagnostics)
}
val rawManifest = try {
ResourcePackJson.parseToJsonElement(manifestEntry.readText()).jsonObject
} catch (e: Exception) {
if (e is CancellationException) throw e
diagnostics += ResourcePackDiagnostic("manifest.json", message = "Malformed JSON: ${e.message}")
throw ResourcePackParseException(diagnostics)
}
val migratedManifest = ResourceTypes.MANIFEST.migrateJson(rawManifest, CURRENT_FORMAT_VERSION)
val parsedManifest = ResourceTypes.MANIFEST.validateAndDecode(manifestEntry.path, migratedManifest, diagnostics)
if (parsedManifest == null) {
throw ResourcePackParseException(diagnostics)
}
val formatVersion = parsedManifest.value.formatVersion
if (formatVersion < MIN_SUPPORTED_FORMAT_VERSION) {
diagnostics += ResourcePackDiagnostic("manifest.json", message = "Unsupported format version $formatVersion. Minimum supported is $MIN_SUPPORTED_FORMAT_VERSION")
throw ResourcePackParseException(diagnostics)
}
val objects = mutableMapOf<ResourceType<*>, MutableList<Pair<String, JsonObject>>>()
for (entry in entries) {
if (entry.path == "manifest.json") continue
val type = types.firstOrNull { it.matches(entry.path) }
if (type != null) {
try {
val element = ResourcePackJson.parseToJsonElement(entry.readText())
if (element is JsonObject) {
val migrated = type.migrateJson(element, formatVersion)
objects.getOrPut(type) { mutableListOf() }.add(entry.path to migrated)
} else {
diagnostics += ResourcePackDiagnostic(entry.path, message = "Expected JSON object")
}
} catch (e: Exception) {
if (e is CancellationException) throw e
diagnostics += ResourcePackDiagnostic(entry.path, message = "Malformed JSON: ${e.message}")
}
}
}
if (diagnostics.isNotEmpty()) throw ResourcePackParseException(diagnostics.sortedWith(compareBy<ResourcePackDiagnostic> { it.path }.thenBy { it.pointer }))
return ParsedResourcePack(source.description, parsedManifest, objects, entries.associateBy { it.path })
}
}
@@ -0,0 +1,102 @@
package dev.slimevr.resourcepacks
import dev.slimevr.osc.OscArg
import dev.slimevr.resourcepacks.bones.CompiledEmitEntry
import dev.slimevr.skeleton.BoneState
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import kotlin.math.PI
import kotlin.math.max
import kotlin.math.min
private sealed interface PipelineValue {
data class Rotation(val value: Quaternion) : PipelineValue
data class Vector(val value: Vector3) : PipelineValue
data class Number(val value: Float) : PipelineValue
data class Boolean(val value: kotlin.Boolean) : PipelineValue
}
internal fun evaluateEmit(entry: CompiledEmitEntry, bone: BoneState, relativeTo: BoneState?): List<OscArg> {
var value: PipelineValue = when (entry.from) {
EmitSource.POSITION -> PipelineValue.Vector(
relativeTo?.let { it.rotation.inv().sandwich(bone.headPosition - it.headPosition) } ?: bone.headPosition,
)
EmitSource.ROTATION -> PipelineValue.Rotation(
relativeTo?.let { it.rotation.inv() * bone.rotation } ?: bone.rotation,
)
}
for (step in entry.steps) value = applyStep(step, value)
return value.toOscArgs()
}
private fun applyStep(step: PipelineStep, value: PipelineValue): PipelineValue = when (step) {
is PipelineStep.Euler -> euler(value, step.spec)
is PipelineStep.Scale -> arithmetic(value, step.operand, 1f) { left, right -> left * right }
is PipelineStep.Divide -> arithmetic(value, step.operand, 1f) { left, right -> left / right }
is PipelineStep.Offset -> arithmetic(value, step.operand, 0f) { left, right -> left + right }
is PipelineStep.Clamp -> clamp(value, step.bounds)
is PipelineStep.GreaterThan -> PipelineValue.Boolean((value as PipelineValue.Number).value > step.threshold)
is PipelineStep.LessThan -> PipelineValue.Boolean((value as PipelineValue.Number).value < step.threshold)
}
private fun euler(value: PipelineValue, spec: EulerSpec): PipelineValue {
val rotation = (value as PipelineValue.Rotation).value
val order = io.github.axisangles.ktmath.EulerOrder.valueOf((spec.order ?: EulerOrder.XYZ).name)
val angles = rotation.toEulerAngles(order)
val scale = if ((spec.unit ?: EulerUnit.DEGREES) == EulerUnit.DEGREES) 180f / PI.toFloat() else 1f
fun axis(axis: Axis): Float = when (axis) {
Axis.X -> angles.x * scale
Axis.Y -> angles.y * scale
Axis.Z -> angles.z * scale
}
return spec.axis?.let { PipelineValue.Number(axis(it)) }
?: PipelineValue.Vector(Vector3(axis(Axis.X), axis(Axis.Y), axis(Axis.Z)))
}
private fun arithmetic(value: PipelineValue, operand: ScalarOrVector, default: Float, operation: (Float, Float) -> Float): PipelineValue = when (value) {
is PipelineValue.Number -> PipelineValue.Number(operation(value.value, operand.scalar()))
is PipelineValue.Vector -> PipelineValue.Vector(componentWise(value.value, operand, default, operation))
is PipelineValue.Rotation -> {
val q = value.value
val result = componentWise(Vector3(q.x, q.y, q.z), operand, default, operation)
PipelineValue.Rotation(Quaternion(q.w, result.x, result.y, result.z))
}
is PipelineValue.Boolean -> error("Arithmetic cannot apply to boolean")
}
private fun ScalarOrVector.scalar(): Float = when (this) {
is ScalarOrVector.Scalar -> value
is ScalarOrVector.Vector -> error("A vector operand cannot apply to a scalar pipeline value")
}
private fun componentWise(value: Vector3, operand: ScalarOrVector, default: Float, operation: (Float, Float) -> Float): Vector3 = when (operand) {
is ScalarOrVector.Scalar -> Vector3(operation(value.x, operand.value), operation(value.y, operand.value), operation(value.z, operand.value))
is ScalarOrVector.Vector -> Vector3(
operation(value.x, operand.value.x ?: default),
operation(value.y, operand.value.y ?: default),
operation(value.z, operand.value.z ?: default),
)
}
private fun clamp(value: PipelineValue, bounds: List<Float>): PipelineValue {
val minimum = bounds[0]
val maximum = bounds[1]
fun clamped(number: Float) = max(minimum, min(maximum, number))
return when (value) {
is PipelineValue.Number -> PipelineValue.Number(clamped(value.value))
is PipelineValue.Vector -> PipelineValue.Vector(Vector3(clamped(value.value.x), clamped(value.value.y), clamped(value.value.z)))
else -> error("Clamp can only apply to a number or vector")
}
}
private fun PipelineValue.toOscArgs(): List<OscArg> = when (this) {
is PipelineValue.Boolean -> listOf(if (value) OscArg.True else OscArg.False)
is PipelineValue.Number -> listOf(OscArg.Float(value))
is PipelineValue.Vector -> listOf(OscArg.Float(value.x), OscArg.Float(value.y), OscArg.Float(value.z))
is PipelineValue.Rotation -> listOf(OscArg.Float(value.w), OscArg.Float(value.x), OscArg.Float(value.y), OscArg.Float(value.z))
}
@@ -0,0 +1,17 @@
package dev.slimevr.resourcepacks.proportions
import dev.slimevr.resourcepacks.ProportionDefault
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class ProportionDefinition(
@SerialName("$" + "schema") val schema: String? = null,
val key: String,
val nameKey: String,
val descriptionKey: String? = null,
val contributesToHeight: Boolean? = null,
val minimum: Float? = null,
val maximum: Float? = null,
val default: ProportionDefault,
)
@@ -0,0 +1,158 @@
@file:OptIn(kotlinx.serialization.ExperimentalSerializationApi::class)
package dev.slimevr.resourcepacks
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonClassDiscriminator
@Serializable
data class Vector3(val x: Float, val y: Float, val z: Float)
@Serializable
data class OffsetTerm(val proportion: String, val direction: Vector3)
@Serializable
data class Offset(val base: Vector3? = null, val terms: List<OffsetTerm>? = null)
@Serializable
@JsonClassDiscriminator("type")
sealed interface RotationFallback
@Serializable
@SerialName("none")
data object NoRotationFallback : RotationFallback
@Serializable
@SerialName("copy")
data class CopyRotationFallback(val source: String) : RotationFallback
@Serializable
@SerialName("firstActive")
data class FirstActiveRotationFallback(val sources: List<String>) : RotationFallback
@Serializable
@JsonClassDiscriminator("type")
sealed interface Constraint
@Serializable
@SerialName("twistSwing")
data class TwistSwingConstraint(val twistDegrees: Float, val swingDegrees: Float, val allowedDeviationDegrees: Float? = null) : Constraint
@Serializable
@SerialName("hinge")
data class HingeConstraint(val minDegrees: Float, val maxDegrees: Float, val axis: Vector3) : Constraint
@Serializable
@SerialName("looseHinge")
data class LooseHingeConstraint(val minDegrees: Float, val maxDegrees: Float, val allowedDeviationDegrees: Float, val axis: Vector3) : Constraint
@Serializable
@JsonClassDiscriminator("type")
sealed interface ProportionDefault {
val value: Float
}
@Serializable
@SerialName("fixed")
data class FixedProportionDefault(override val value: Float) : ProportionDefault
@Serializable
@SerialName("heightRatio")
data class HeightRatioProportionDefault(override val value: Float) : ProportionDefault
@Serializable
data class DriverOutput(val supported: Boolean)
@Serializable(with = VmcNamesSerializer::class)
data class VmcNames(val values: List<String>) {
init {
require(values.isNotEmpty())
}
}
sealed interface VmcInputParent {
data object Omitted : VmcInputParent
data object ExplicitNull : VmcInputParent
data class Bone(val key: String) : VmcInputParent
}
@Serializable
data class RestRotation(val axis: Vector3, val degrees: Float)
@Serializable(with = VmcOutputSerializer::class)
data class VmcOutput(
val name: VmcNames,
val outputParent: String? = null,
val inputParent: VmcInputParent = VmcInputParent.Omitted,
val restRotation: List<RestRotation>? = null,
)
@Serializable
data class VrchatOutput(val required: Boolean? = null, val emit: Map<String, EmitEntry>)
@Serializable
data class EmitEntry(val from: EmitSource, val relativeTo: String? = null, val value: List<PipelineStep>? = null)
@Serializable
enum class EmitSource {
@SerialName("position")
POSITION,
@SerialName("rotation")
ROTATION,
}
/** One pipeline transform step; the schema requires exactly one operation per step. */
@Serializable(with = PipelineStepSerializer::class)
sealed interface PipelineStep {
data class Euler(val spec: EulerSpec) : PipelineStep
data class Scale(val operand: ScalarOrVector) : PipelineStep
data class Divide(val operand: ScalarOrVector) : PipelineStep
data class Offset(val operand: ScalarOrVector) : PipelineStep
data class Clamp(val bounds: List<Float>) : PipelineStep
data class GreaterThan(val threshold: Float) : PipelineStep
data class LessThan(val threshold: Float) : PipelineStep
}
@Serializable(with = EulerSpecSerializer::class)
data class EulerSpec(val axis: Axis? = null, val order: EulerOrder? = null, val unit: EulerUnit? = null)
@Serializable enum class Axis {
@SerialName("x")
X,
@SerialName("y")
Y,
@SerialName("z")
Z,
}
@Serializable enum class EulerOrder { XYZ, XZY, YXZ, YZX, ZXY, ZYX }
@Serializable enum class EulerUnit {
@SerialName("degrees")
DEGREES,
@SerialName("radians")
RADIANS,
}
@Serializable(with = ScalarOrVectorSerializer::class)
sealed interface ScalarOrVector {
data class Scalar(val value: Float) : ScalarOrVector
data class Vector(val value: PartialVector3) : ScalarOrVector
}
@Serializable
data class PartialVector3(val x: Float? = null, val y: Float? = null, val z: Float? = null)
@Serializable
data class BoneOutputs(val driver: DriverOutput? = null, val vmc: VmcOutput? = null, val vrchat: VrchatOutput? = null)
@Serializable
data class VrchatInput(val address: String)
@Serializable
data class BoneInputs(val vrchat: VrchatInput? = null)
@@ -0,0 +1,88 @@
package dev.slimevr.resourcepacks
import com.github.erosb.jsonsKema.JsonParser
import com.github.erosb.jsonsKema.Schema
import com.github.erosb.jsonsKema.SchemaLoader
import com.github.erosb.jsonsKema.SchemaLoaderConfig
import com.github.erosb.jsonsKema.Validator
import dev.slimevr.resourcepacks.bones.BoneDefinition
import dev.slimevr.resourcepacks.languages.LanguageResource
import dev.slimevr.resourcepacks.proportions.ProportionDefinition
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.decodeFromJsonElement
import java.net.URI
import java.nio.charset.StandardCharsets
abstract class ResourceType<T : Any>(val id: String) {
open val mergeLayers: Boolean = false
open fun migrateJson(document: JsonObject, fromVersion: Int): JsonObject = document
abstract fun matches(path: String): Boolean
abstract fun validateAndDecode(path: String, document: JsonObject, diagnostics: MutableList<in ResourcePackDiagnostic>): SourcedResource<T>?
}
abstract class JsonResourceType<T : Any>(
id: String,
val schemaName: String,
) : ResourceType<T>(id) {
val schema: Schema by lazy {
val base = URI("classpath:/${PackSchemas.ROOT}/")
val document = PackSchemas.documents[schemaName] ?: error("Bundled resource-pack schema is missing: ${PackSchemas.ROOT}/$schemaName")
SchemaLoader(JsonParser(document, base.resolve(schemaName)).parse(), PackSchemas.config.copy(initialBaseURI = base.resolve(schemaName))).load()
}
override fun validateAndDecode(path: String, document: JsonObject, diagnostics: MutableList<in ResourcePackDiagnostic>): SourcedResource<T>? {
val instance = try {
JsonParser(document.toString()).parse()
} catch (e: Exception) {
diagnostics += ResourcePackDiagnostic(path, message = "Invalid JSON: ${e.message}")
return null
}
val failure = Validator.forSchema(schema).validate(instance)
if (failure != null) {
diagnostics += ResourcePackDiagnostic(path, message = "$id schema: $failure")
return null
}
return try {
SourcedResource(path, decode(document), document)
} catch (e: Exception) {
diagnostics += ResourcePackDiagnostic(path, message = "Schema/model drift while decoding: ${e.message}")
null
}
}
abstract fun decode(document: JsonObject): T
}
object ResourceTypes {
val MANIFEST: JsonResourceType<PackManifest> = object : JsonResourceType<PackManifest>("manifest", "manifest.schema.json") {
override fun matches(path: String) = path == "manifest.json"
override fun decode(document: JsonObject) = ResourcePackJson.decodeFromJsonElement<PackManifest>(document)
}
val BONE: JsonResourceType<BoneDefinition> = object : JsonResourceType<BoneDefinition>("bone", "bone.schema.json") {
override fun matches(path: String) = path.startsWith("data/") && path.contains("/bones/") && path.endsWith(".json") && path.count { it == '/' } == 3
override fun decode(document: JsonObject) = ResourcePackJson.decodeFromJsonElement<BoneDefinition>(document)
}
val PROPORTION: JsonResourceType<ProportionDefinition> = object : JsonResourceType<ProportionDefinition>("proportion", "proportion.schema.json") {
override fun matches(path: String) = path.startsWith("data/") && path.contains("/proportions/") && path.endsWith(".json") && path.count { it == '/' } == 3
override fun decode(document: JsonObject) = ResourcePackJson.decodeFromJsonElement<ProportionDefinition>(document)
}
val LANGUAGE: JsonResourceType<LanguageResource> = object : JsonResourceType<LanguageResource>("language", "language.schema.json") {
override val mergeLayers = true
override fun matches(path: String) = path.startsWith("assets/") && path.contains("/lang/") && path.endsWith(".json") && path.count { it == '/' } == 3
override fun decode(document: JsonObject) = ResourcePackJson.decodeFromJsonElement<LanguageResource>(document)
}
val ALL = listOf(MANIFEST, BONE, PROPORTION, LANGUAGE)
}
internal object PackSchemas {
const val ROOT = ClasspathResourcePackSource.CORE_ROOT + "/schemas/v1"
val documents = ResourceTypes.ALL.associate { type ->
type.schemaName to (
PackSchemas::class.java.classLoader.getResourceAsStream("$ROOT/${type.schemaName}")?.bufferedReader(StandardCharsets.UTF_8)?.use { it.readText() }
?: error("Bundled resource-pack schema is missing: $ROOT/${type.schemaName}")
)
}
val config = SchemaLoaderConfig.createDefaultConfig(documents.mapKeys { (name, _) -> URI("classpath:/$ROOT/").resolve(name) })
}
@@ -0,0 +1,99 @@
package dev.slimevr.resourcepacks
import dev.slimevr.config.ConfigStorage
import dev.slimevr.config.StorageEntryType
import dev.slimevr.config.configPath
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
class ResourcePackEntry(val path: String, private val reader: suspend () -> ByteArray) {
constructor(path: String, contents: String) : this(path, { contents.encodeToByteArray() })
suspend fun readBytes(): ByteArray = reader()
suspend fun readText(): String = readBytes().decodeToString(throwOnInvalidSequence = true)
}
interface ResourcePackSource {
val description: String
suspend fun entries(): List<ResourcePackEntry>
}
class StorageResourcePackSource(
private val storage: ConfigStorage,
private val root: String,
override val description: String = storage.displayPath(root),
) : ResourcePackSource {
override suspend fun entries(): List<ResourcePackEntry> {
val result = mutableListOf<ResourcePackEntry>()
suspend fun visit(relative: String) {
val directory = if (relative.isEmpty()) root else configPath(root, relative)
for (entry in storage.list(directory).sortedBy { it.name }) {
if (entry.name.isEmpty() || entry.name.contains('/') || entry.name.contains('\\') || entry.name == "." || entry.name == "..") {
throw IOException("Invalid entry name '${entry.name}' in $directory")
}
val child = if (relative.isEmpty()) entry.name else "$relative/${entry.name}"
when (entry.type) {
StorageEntryType.SYMLINK -> throw IOException("Symbolic links are not permitted in resource packs ($child)")
StorageEntryType.DIRECTORY -> visit(child)
StorageEntryType.FILE -> {
val path = normalizePath(child)
result += ResourcePackEntry(path) {
storage.readBytes(configPath(root, path)) ?: throw IOException("Unable to read $path")
}
}
StorageEntryType.OTHER -> throw IOException("Unsupported filesystem entry in resource pack: $child")
}
}
}
visit("")
return result.sortedBy { it.path }
}
}
class ClasspathResourcePackSource private constructor(
private val classLoader: ClassLoader,
override val description: String,
) : ResourcePackSource {
override suspend fun entries(): List<ResourcePackEntry> = withContext(Dispatchers.IO) {
val indexPath = "$CORE_ROOT/index.txt"
val paths = classLoader.getResourceAsStream(indexPath)?.bufferedReader()?.use { reader ->
reader.lineSequence().filter { it.isNotBlank() }.map(::normalizePath).toList()
} ?: throw IOException("Bundled core resource-pack index is missing ($indexPath)")
paths.sorted().map { path ->
val resource = "$CORE_ROOT/$path"
ResourcePackEntry(path) {
withContext(Dispatchers.IO) {
classLoader.getResourceAsStream(resource)?.use { it.readBytes() }
?: throw IOException("Bundled core resource is missing ($resource)")
}
}
}
}
companion object {
const val CORE_ROOT = "dev/slimevr/resourcepacks/core"
fun core(classLoader: ClassLoader): ClasspathResourcePackSource {
val resource = "$CORE_ROOT/manifest.json"
val urls = classLoader.getResources(resource).toList()
require(urls.size == 1) {
when (urls.size) {
0 -> "Bundled core resource pack is missing ($resource)"
else -> "Bundled core resource pack is duplicated: ${urls.joinToString()}"
}
}
return ClasspathResourcePackSource(classLoader, "bundled core pack (${urls.single()})")
}
}
}
internal fun normalizePath(path: String): String {
val normalized = path.replace('\\', '/')
require(normalized.isNotEmpty() && !normalized.startsWith('/') && normalized.split('/').none { it.isEmpty() || it == "." || it == ".." }) {
"Invalid resource-pack path: $path"
}
return normalized
}
@@ -16,7 +16,7 @@ class BoneRoutingBasicBehaviour(private val appContext: AppContextProvider) : Bo
override fun observe(receiver: BoneRoutingManager) {
val server = appContext.server
val settings = appContext.config.settings
val registry = appContext.bones.current
val definition = appContext.skeleton.definition
combine(
settings.context.state.map { it.data.boneRoutingConfig }.distinctUntilChanged(),
@@ -27,7 +27,7 @@ class BoneRoutingBasicBehaviour(private val appContext: AppContextProvider) : Bo
if (!config.automatic) {
receiver.context.dispatch(
BoneRoutingActions.SetRoutes(
effectiveRoutes(manualRoutesAsBoneIds(config.manualRoutes, registry), outputStates, registry),
effectiveRoutes(manualRoutesAsBoneIds(config.manualRoutes, definition), outputStates, definition),
),
)
}
@@ -47,19 +47,19 @@ class BoneRoutingBasicBehaviour(private val appContext: AppContextProvider) : Bo
trackers.map { tracker ->
tracker.context.state.distinctUntilChanged { a, b -> a.boneId == b.boneId && a.status == b.status }
},
) { states -> trackedBodyParts(states.asList(), registry) }
) { states -> trackedBoneIds(states.asList()) }
.distinctUntilChanged()
}
.map { fineBodyParts -> Triple(config, outputStates, fineBodyParts) }
.map { boneIds -> Triple(config, outputStates, boneIds) }
}
.onEach { (config, outputStates, fineBodyParts) ->
val candidates = determineCandidateBones(fineBodyParts)
.onEach { (config, outputStates, boneIds) ->
val candidates = determineCandidateBones(boneIds, definition)
receiver.context.dispatch(
BoneRoutingActions.SetRoutes(
effectiveRoutes(
computeAutomaticRoutes(candidates, outputStates, registry) + overrideRoutes(config, registry),
computeAutomaticRoutes(candidates, outputStates, definition) + overrideRoutes(config, definition),
outputStates,
registry,
definition,
),
),
)
@@ -1,15 +1,11 @@
package dev.slimevr.routing
import dev.slimevr.AppContextProvider
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.BoneId
import dev.slimevr.bones.BoneRegistry
import dev.slimevr.config.BoneRoutingConfig
import dev.slimevr.solarxr.driver.DRIVER_SUPPORTED_BONES
import dev.slimevr.resourcepacks.bones.CompiledSkeleton
import dev.slimevr.tracker.TrackerState
import dev.slimevr.util.isActive
import dev.slimevr.vmc.VMC_SUPPORTED_BONES
import dev.slimevr.vrcosc.VRC_OSC_SUPPORTED_BONES
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
@@ -30,11 +26,7 @@ private val ALL_ACTIVE: OutputStates = RoutingOutput.entries.associateWith { Rou
private val PRIORITY_CHAIN = listOf(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC)
fun acceptedBones(output: RoutingOutput): Set<BodyPart> = when (output) {
RoutingOutput.DRIVER -> DRIVER_SUPPORTED_BONES
RoutingOutput.VRC_OSC -> VRC_OSC_SUPPORTED_BONES
RoutingOutput.VMC -> VMC_SUPPORTED_BONES
}
fun acceptedBones(output: RoutingOutput, definition: CompiledSkeleton): Set<BoneId> = definition.acceptedBones(output)
fun conflictingOutputs(output: RoutingOutput): Set<RoutingOutput> = when (output) {
in PRIORITY_CHAIN -> PRIORITY_CHAIN.toSet() - output
@@ -42,32 +34,19 @@ fun conflictingOutputs(output: RoutingOutput): Set<RoutingOutput> = when (output
}
/** Bones an output needs to work at all, so the user cannot turn them off. */
fun requiredBones(output: RoutingOutput): Set<BodyPart> = when (output) {
RoutingOutput.DRIVER, RoutingOutput.VRC_OSC -> emptySet()
RoutingOutput.VMC -> VMC_SUPPORTED_BONES
}
fun requiredBones(output: RoutingOutput, definition: CompiledSkeleton): Set<BoneId> = definition.requiredBones(output)
/**
* Bones automatic never routes on its own. Sending a hand to the driver takes over the
* real controllers, so it stays the user's call whatever the mode.
*/
val OVERRIDABLE_BONES: Set<BodyPart> = setOf(BodyPart.LEFT_HAND, BodyPart.RIGHT_HAND)
fun overridableBones(output: RoutingOutput, definition: CompiledSkeleton): Set<BoneId> = definition.overridableBones intersect acceptedBones(output, definition) subtract requiredBones(output, definition)
fun overridableBones(output: RoutingOutput): Set<BodyPart> = OVERRIDABLE_BONES intersect acceptedBones(output) subtract requiredBones(output)
fun manualRoutesAsBoneIds(manualRoutes: Map<String, Set<RoutingOutput>>?, definition: CompiledSkeleton): Routes = manualRoutes.orEmpty().mapNotNull { (key, outputs) -> definition.registry[key]?.let { it to outputs } }.toMap()
/** Resolves a static [BodyPart] set to the [BoneId]s a specific registry gives them. */
private fun BoneRegistry.idsOf(bodyParts: Set<BodyPart>): Set<BoneId> = bodyParts.mapNotNullTo(mutableSetOf()) { this[it] }
fun Routes.toManualRoutesConfig(definition: CompiledSkeleton): Map<String, Set<RoutingOutput>> = mapNotNull { (boneId, outputs) -> definition.registry.keyOf(boneId)?.let { it to outputs } }.toMap()
private fun BoneRegistry.acceptedIds(output: RoutingOutput): Set<BoneId> = idsOf(acceptedBones(output))
private fun BoneRegistry.requiredIds(output: RoutingOutput): Set<BoneId> = idsOf(requiredBones(output))
fun manualRoutesAsBoneIds(manualRoutes: Map<String, Set<RoutingOutput>>?, registry: BoneRegistry): Routes = manualRoutes.orEmpty().mapNotNull { (key, outputs) -> registry[key]?.let { it to outputs } }.toMap()
fun Routes.toManualRoutesConfig(registry: BoneRegistry): Map<String, Set<RoutingOutput>> = mapNotNull { (boneId, outputs) -> registry.keyOf(boneId)?.let { it to outputs } }.toMap()
fun overrideRoutes(config: BoneRoutingConfig, registry: BoneRegistry): Routes {
val overridableIds = registry.idsOf(OVERRIDABLE_BONES)
return manualRoutesAsBoneIds(config.manualRoutes, registry).filterKeys { it in overridableIds }
}
fun overrideRoutes(config: BoneRoutingConfig, definition: CompiledSkeleton): Routes = manualRoutesAsBoneIds(config.manualRoutes, definition).filterKeys { it in definition.overridableBones }
fun isActive(states: OutputStates, output: RoutingOutput): Boolean = states[output] == RoutingOutputState.ACTIVE
@@ -121,24 +100,24 @@ fun intendedRoutesFlow(appContext: AppContextProvider): Flow<Routes> = combine(
appContext.config.settings.context.state.map { it.data.boneRoutingConfig }.distinctUntilChanged(),
appContext.boneRouting.context.state.map { it.routes },
) { config, sent ->
val registry = appContext.bones.current
val requested = if (config.automatic) sent else manualRoutesAsBoneIds(config.manualRoutes, registry)
effectiveRoutes(requested + overrideRoutes(config, registry), ALL_ACTIVE, registry)
val definition = appContext.skeleton.definition
val requested = if (config.automatic) sent else manualRoutesAsBoneIds(config.manualRoutes, definition)
effectiveRoutes(requested + overrideRoutes(config, definition), ALL_ACTIVE, definition)
}.distinctUntilChanged()
/**
* What actually gets sent: the requested routes plus whatever each output requires,
* minus anything an output cannot accept or cannot currently send.
*/
fun effectiveRoutes(routes: Routes, outputStates: OutputStates, registry: BoneRegistry): Routes {
fun effectiveRoutes(routes: Routes, outputStates: OutputStates, definition: CompiledSkeleton): Routes {
val result = mutableMapOf<BoneId, Set<RoutingOutput>>()
for ((bone, outputs) in routes) {
val kept = outputs.filterTo(mutableSetOf()) { isActive(outputStates, it) && bone in registry.acceptedIds(it) }
val kept = outputs.filterTo(mutableSetOf()) { isActive(outputStates, it) && bone in acceptedBones(it, definition) }
if (kept.isNotEmpty()) result[bone] = kept
}
for (output in RoutingOutput.entries) {
if (!isActive(outputStates, output)) continue
for (bone in registry.requiredIds(output)) {
for (bone in requiredBones(output, definition)) {
result[bone] = result[bone].orEmpty() + output
}
}
@@ -149,59 +128,47 @@ fun applyRoutingChange(
config: BoneRoutingConfig,
automatic: Boolean,
routes: Routes,
registry: BoneRegistry,
definition: CompiledSkeleton,
): BoneRoutingConfig {
// Switching modes only flips the switch: each mode keeps the picks left in it.
if (automatic != config.automatic) return config.copy(automatic = automatic)
val requested = routes
.mapValues { (bone, outputs) -> outputs.filterTo(mutableSetOf()) { bone in registry.acceptedIds(it) && bone !in registry.requiredIds(it) } }
.mapValues { (bone, outputs) -> outputs.filterTo(mutableSetOf()) { bone in acceptedBones(it, definition) && bone !in requiredBones(it, definition) } }
.filterValues { it.isNotEmpty() }
val overridableIds = registry.idsOf(OVERRIDABLE_BONES)
val overridableIds = definition.overridableBones
return config.copy(
manualRoutes = if (automatic) {
// Automatic owns every other bone, so only the overrides come from the request.
(
manualRoutesAsBoneIds(config.manualRoutes, registry).filterKeys { it !in overridableIds } +
manualRoutesAsBoneIds(config.manualRoutes, definition).filterKeys { it !in overridableIds } +
requested.filterKeys { it in overridableIds }
).toManualRoutesConfig(registry)
).toManualRoutesConfig(definition)
} else {
requested.toManualRoutesConfig(registry)
requested.toManualRoutesConfig(definition)
},
)
}
private val candidateToFineBodyParts = mapOf(
BodyPart.UPPER_CHEST to setOf(BodyPart.UPPER_CHEST, BodyPart.LOWER_CHEST),
BodyPart.LEFT_UPPER_ARM to setOf(BodyPart.LEFT_UPPER_ARM, BodyPart.LEFT_LOWER_ARM),
BodyPart.RIGHT_UPPER_ARM to setOf(BodyPart.RIGHT_UPPER_ARM, BodyPart.RIGHT_LOWER_ARM),
BodyPart.HIP to setOf(BodyPart.HIP, BodyPart.LOWER_WAIST, BodyPart.UPPER_WAIST, BodyPart.LOWER_CHEST, BodyPart.UPPER_CHEST),
BodyPart.LEFT_UPPER_LEG to setOf(BodyPart.LEFT_UPPER_LEG),
BodyPart.RIGHT_UPPER_LEG to setOf(BodyPart.RIGHT_UPPER_LEG),
BodyPart.LEFT_FOOT to setOf(BodyPart.LEFT_FOOT, BodyPart.LEFT_LOWER_LEG, BodyPart.LEFT_UPPER_LEG),
BodyPart.RIGHT_FOOT to setOf(BodyPart.RIGHT_FOOT, BodyPart.RIGHT_LOWER_LEG, BodyPart.RIGHT_UPPER_LEG),
)
/** Tracker body parts that count as present. Loopback trackers never enable an output. */
fun trackedBodyParts(trackers: Collection<TrackerState>, registry: BoneRegistry): Set<BodyPart?> = trackers
/** Tracker bones that count as present. Loopback trackers never enable an output. */
fun trackedBoneIds(trackers: Collection<TrackerState>): Set<BoneId?> = trackers
.filter {
it.status.isActive() &&
it.origin != DeviceOrigin.DRIVER &&
it.origin != DeviceOrigin.VRC &&
it.origin != DeviceOrigin.VMC
}
.map { it.boneId?.let { id -> registry.bodyPartOf(id) } }
.map { it.boneId }
.toSet()
fun determineCandidateBones(fineBodyParts: Set<BodyPart?>): Set<BodyPart> = candidateToFineBodyParts
.filterValues { it.any { bp -> bp in fineBodyParts } }
.keys
fun determineCandidateBones(trackedBoneIds: Set<BoneId?>, definition: CompiledSkeleton): Set<BoneId> = definition.candidateBones
.filterTo(mutableSetOf()) { candidate -> definition.candidateSourcesOf(candidate).any { it in trackedBoneIds } }
/** Hands each bone to the best output that is on and can take it, so nothing is sent twice. */
fun computeAutomaticRoutes(candidateBones: Set<BodyPart>, outputStates: OutputStates, registry: BoneRegistry): Routes {
fun computeAutomaticRoutes(candidateBones: Set<BoneId>, outputStates: OutputStates, definition: CompiledSkeleton): Routes {
val chain = PRIORITY_CHAIN.filter { isActive(outputStates, it) }
return candidateBones
.mapNotNull { bone -> chain.firstOrNull { bone in acceptedBones(it) }?.let { output -> registry[bone]?.let { it to setOf(output) } } }
.mapNotNull { bone -> chain.firstOrNull { bone in acceptedBones(it, definition) }?.let { output -> bone to setOf(output) } }
.toMap()
}
@@ -2,14 +2,13 @@ package dev.slimevr.skeleton
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.BoneMap
import dev.slimevr.bones.BoneRegistry
import dev.slimevr.bones.BoneSet
import dev.slimevr.bones.boneId
import dev.slimevr.bones.mutateCopy
import dev.slimevr.bones.resolveToBoneIds
import dev.slimevr.config.Settings
import dev.slimevr.config.UserConfig
import dev.slimevr.logging.AppLogger
import dev.slimevr.resourcepacks.bones.CompiledSkeleton
import dev.slimevr.util.MonotonicValueTimeMark
import dev.slimevr.util.PreciseWaiter
import dev.slimevr.util.timeSource
@@ -34,17 +33,15 @@ import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlin.time.measureTime
class ProportionsBehaviour(private val userConfig: UserConfig, private val registry: BoneRegistry) : SkeletonBehaviour {
class ProportionsBehaviour(private val userConfig: UserConfig, private val definition: CompiledSkeleton) : SkeletonBehaviour {
override fun observe(receiver: Skeleton) {
userConfig.context.state
.distinctUntilChangedBy { it.data.proportions }
.map { it.data.proportions }
.onEach { proportions ->
if (proportions.isNotEmpty()) {
val lengths = configToBoneValues(proportions)
receiver.context.dispatch(SkeletonActions.SetProportions(toBoneOffsets(lengths, registry), lengths.height()))
receiver.resetProcessors(ResetType.FULL)
}
val values = definition.defaultProportionValues() + proportions.filterKeys { it in definition.proportions }
receiver.context.dispatch(SkeletonActions.SetProportions(definition.toBoneOffsets(values), definition.height(values), values))
receiver.resetProcessors(ResetType.FULL)
}
.launchIn(receiver.context.scope)
}
@@ -173,6 +170,7 @@ private class TickTimings(private val hz: Int, private val window: Duration, pri
class ComputedSkeletonBehaviour(
val hz: Int,
val definition: CompiledSkeleton,
val inputProcessors: List<SkeletonInputProcessor> = emptyList(),
val fkComputedProcessors: List<SkeletonComputedProcessor> = emptyList(),
val fkProcessors: List<SkeletonFkProcessor> = emptyList(),
@@ -182,7 +180,7 @@ class ComputedSkeletonBehaviour(
) : SkeletonBehaviour {
private val intervalDuration = (1.0 / hz).seconds
private val headId = BodyPart.HEAD.boneId
private val constraints = BODY_PART_CONSTRAINT_MAP.resolveToBoneIds()
private val constraints = definition.constraints
private val ikChains = resolveIkChains()
/** Shortest gap between two tick starts before the later one is pushed to the next slot */
@@ -1,151 +0,0 @@
package dev.slimevr.skeleton
import com.jme3.math.FastMath
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.BodyPartMap
import dev.slimevr.bones.BoneId
import io.github.axisangles.ktmath.Quaternion
// TODO Actually figure out good values for these constraints, maybe a source would be
// good?
val BODY_PART_CONSTRAINT_MAP: BodyPartMap<Constraint> = BodyPartMap(
mapOf(
BodyPart.LEFT_SHOULDER to TwistSwingConstraint(
0f * FastMath.DEG_TO_RAD,
30f * FastMath.DEG_TO_RAD,
),
BodyPart.LEFT_UPPER_ARM to TwistSwingConstraint(
120f * FastMath.DEG_TO_RAD,
180f * FastMath.DEG_TO_RAD,
),
BodyPart.LEFT_LOWER_ARM to LooseHingeConstraint(
-180f * FastMath.DEG_TO_RAD,
0f * FastMath.DEG_TO_RAD,
40f * FastMath.DEG_TO_RAD,
),
BodyPart.LEFT_HAND to TwistSwingConstraint(
120f * FastMath.DEG_TO_RAD,
120f * FastMath.DEG_TO_RAD,
),
BodyPart.RIGHT_SHOULDER to TwistSwingConstraint(
0f * FastMath.DEG_TO_RAD,
30f * FastMath.DEG_TO_RAD,
),
BodyPart.RIGHT_UPPER_ARM to TwistSwingConstraint(
120f * FastMath.DEG_TO_RAD,
180f * FastMath.DEG_TO_RAD,
),
BodyPart.RIGHT_LOWER_ARM to LooseHingeConstraint(
-180f * FastMath.DEG_TO_RAD,
0f * FastMath.DEG_TO_RAD,
40f * FastMath.DEG_TO_RAD,
),
BodyPart.RIGHT_HAND to TwistSwingConstraint(
120f * FastMath.DEG_TO_RAD,
120f * FastMath.DEG_TO_RAD,
),
BodyPart.UPPER_CHEST to TwistSwingConstraint(
90f * FastMath.DEG_TO_RAD,
120f * FastMath.DEG_TO_RAD,
),
BodyPart.LOWER_CHEST to TwistSwingConstraint(
60f * FastMath.DEG_TO_RAD,
120f * FastMath.DEG_TO_RAD,
),
BodyPart.UPPER_WAIST to TwistSwingConstraint(
60f * FastMath.DEG_TO_RAD,
120f * FastMath.DEG_TO_RAD,
),
BodyPart.LOWER_WAIST to TwistSwingConstraint(
60f * FastMath.DEG_TO_RAD,
120f * FastMath.DEG_TO_RAD,
),
BodyPart.HIP to TwistSwingConstraint(
60f * FastMath.DEG_TO_RAD,
120f * FastMath.DEG_TO_RAD,
),
BodyPart.LEFT_UPPER_LEG to TwistSwingConstraint(
120f * FastMath.DEG_TO_RAD,
170f * FastMath.DEG_TO_RAD,
),
BodyPart.LEFT_LOWER_LEG to LooseHingeConstraint(
-5f * FastMath.DEG_TO_RAD,
180f * FastMath.DEG_TO_RAD,
10f * FastMath.DEG_TO_RAD,
),
BodyPart.LEFT_FOOT to LooseHingeConstraint(
-60f * FastMath.DEG_TO_RAD,
90f * FastMath.DEG_TO_RAD,
60f * FastMath.DEG_TO_RAD,
),
BodyPart.RIGHT_UPPER_LEG to TwistSwingConstraint(
120f * FastMath.DEG_TO_RAD,
170f * FastMath.DEG_TO_RAD,
),
BodyPart.RIGHT_LOWER_LEG to LooseHingeConstraint(
-5f * FastMath.DEG_TO_RAD,
180f * FastMath.DEG_TO_RAD,
10f * FastMath.DEG_TO_RAD,
),
BodyPart.RIGHT_FOOT to LooseHingeConstraint(
-60f * FastMath.DEG_TO_RAD,
90f * FastMath.DEG_TO_RAD,
60f * FastMath.DEG_TO_RAD,
),
),
)
fun constrainOffset(
constraint: Constraint,
parent: Quaternion,
bone: Quaternion,
offset: Quaternion,
): Quaternion {
// TODO: Ensure the quaternion multiplication order is correct here
return constraint.apply(parent, offset * bone) * bone.inv()
}
fun constrainOffsetWithSkeleton(
boneId: BoneId,
offset: Quaternion,
bones: ComputedSkeleton,
constraints: Map<BoneId, Constraint>,
): Quaternion {
val registry = bones.registry
val constraint = constraints[boneId] ?: return offset
val boneRot = bones[boneId]?.rotation ?: return offset
val parentRot = registry.parentOf(boneId)?.let { parent ->
bones[parent]?.rotation
} ?: Quaternion.IDENTITY
return constrainOffset(
constraint,
parentRot,
boneRot,
offset,
)
}
fun constrainSkeleton(
bones: InputSkeleton,
constraints: Map<BoneId, Constraint>,
): InputSkeleton {
val registry = bones.registry
// Apply constraints top-down, from the root
for ((parentId, boneId) in registry.hierarchyFrom(registry.root)) {
val bone = bones[boneId] ?: continue
val constraint = constraints[boneId] ?: continue
val parentRotation = parentId?.let { bones[it]?.rotation } ?: Quaternion.IDENTITY
bones[boneId] = bone.copy(
rotation = constraint.apply(
parentRotation,
bone.rotation,
),
)
}
return bones
}
@@ -0,0 +1,56 @@
package dev.slimevr.skeleton
import dev.slimevr.bones.BoneId
import dev.slimevr.bones.Constraint
import io.github.axisangles.ktmath.Quaternion
fun constrainOffset(
constraint: Constraint,
parent: Quaternion,
bone: Quaternion,
offset: Quaternion,
): Quaternion {
// TODO: Ensure the quaternion multiplication order is correct here
return constraint.apply(parent, offset * bone) * bone.inv()
}
fun constrainOffsetWithSkeleton(
boneId: BoneId,
offset: Quaternion,
bones: ComputedSkeleton,
constraints: Map<BoneId, Constraint>,
): Quaternion {
val registry = bones.registry
val constraint = constraints[boneId] ?: return offset
val boneRot = bones[boneId]?.rotation ?: return offset
val parentRot = registry.parentOf(boneId)?.let { parent ->
bones[parent]?.rotation
} ?: Quaternion.IDENTITY
return constrainOffset(
constraint,
parentRot,
boneRot,
offset,
)
}
fun constrainSkeleton(
bones: InputSkeleton,
constraints: Map<BoneId, Constraint>,
): InputSkeleton {
val registry = bones.registry
// Apply constraints top-down, from the root
for ((parentId, boneId) in registry.hierarchyFrom(registry.root)) {
val bone = bones[boneId] ?: continue
val constraint = constraints[boneId] ?: continue
val parentRotation = parentId?.let { bones[it]?.rotation } ?: Quaternion.IDENTITY
bones[boneId] = bone.copy(
rotation = constraint.apply(
parentRotation,
bone.rotation,
),
)
}
return bones
}
@@ -3,6 +3,7 @@ package dev.slimevr.skeleton
import com.jme3.math.FastMath
import dev.slimevr.bones.BoneId
import dev.slimevr.bones.BoneSet
import dev.slimevr.bones.Constraint
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
@@ -1,49 +0,0 @@
package dev.slimevr.skeleton.inputprocessors
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.BoneId
import dev.slimevr.bones.boneId
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.SkeletonInputProcessor
/**
* Handles setting the rotation of an inactive bone with its source bone.
*/
class BoneDirectLinkInputProcessor : SkeletonInputProcessor {
/**
* First element is the linked bone.
*
* Second element is the bone the first element is linked to.
*/
private val linkedToSource: Array<Pair<BoneId, BoneId>> = arrayOf(
BodyPart.HEAD to BodyPart.NECK,
BodyPart.NECK to BodyPart.HEAD,
BodyPart.LEFT_FOOT to BodyPart.LEFT_LOWER_LEG,
BodyPart.RIGHT_FOOT to BodyPart.RIGHT_LOWER_LEG,
BodyPart.LEFT_SHOULDER to BodyPart.UPPER_CHEST,
BodyPart.RIGHT_SHOULDER to BodyPart.UPPER_CHEST,
BodyPart.LEFT_UPPER_ARM to BodyPart.LEFT_SHOULDER,
BodyPart.RIGHT_UPPER_ARM to BodyPart.RIGHT_SHOULDER,
BodyPart.LEFT_LOWER_ARM to BodyPart.LEFT_UPPER_ARM,
BodyPart.RIGHT_LOWER_ARM to BodyPart.RIGHT_UPPER_ARM,
BodyPart.LEFT_HAND to BodyPart.LEFT_LOWER_ARM,
BodyPart.RIGHT_HAND to BodyPart.RIGHT_LOWER_ARM,
).map { (bodyPart, source) -> bodyPart.boneId to source.boneId }.toTypedArray()
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
for ((boneId, sourceId) in linkedToSource) {
val bone = mutableInputSkeleton[boneId] ?: continue
if (bone.isRotationActive) continue
val rotation = mutableInputSkeleton[sourceId]?.rotation ?: continue
if (rotation == bone.rotation) continue
mutableInputSkeleton[boneId] = bone.copy(rotation = rotation)
}
}
}
@@ -1,18 +1,16 @@
package dev.slimevr.skeleton.inputprocessors
import dev.slimevr.bones.BoneId
import dev.slimevr.bones.resolveToBoneIds
import dev.slimevr.config.Settings
import dev.slimevr.skeleton.BODY_PART_CONSTRAINT_MAP
import dev.slimevr.skeleton.Constraint
import dev.slimevr.resourcepacks.bones.CompiledSkeleton
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.SkeletonInputProcessor
import dev.slimevr.skeleton.constrainSkeleton
class ConstraintInputProcessor(
val settings: Settings,
definition: CompiledSkeleton,
) : SkeletonInputProcessor {
private val constraints: Map<BoneId, Constraint> = BODY_PART_CONSTRAINT_MAP.resolveToBoneIds()
private val constraints = definition.constraints
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
val skeletonConfig = settings.context.state.value.data.skeletonConfig
@@ -0,0 +1,23 @@
package dev.slimevr.skeleton.inputprocessors
import dev.slimevr.bones.BoneId
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.SkeletonInputProcessor
/**
* Copies another bone's rotation onto a bone that has no live tracker of its own. [schedule] pairs
* a bone with its source, in ancestor-before-descendant order, so a source that itself needed
* copying this pass is already resolved by the time it's read.
*/
class CopyRotationFallbackInputProcessor(
private val schedule: List<Pair<BoneId, BoneId>>,
) : SkeletonInputProcessor {
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
for ((boneId, source) in schedule) {
val bone = mutableInputSkeleton[boneId] ?: continue
if (bone.isRotationActive) continue
val rotation = mutableInputSkeleton[source]?.rotation ?: continue
mutableInputSkeleton[boneId] = bone.copy(rotation = rotation)
}
}
}
@@ -0,0 +1,23 @@
package dev.slimevr.skeleton.inputprocessors
import dev.slimevr.bones.BoneId
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.SkeletonInputProcessor
/**
* Sets an untracked bone's rotation from the first actively-tracked bone in its source list,
* falling back to the list's last entry regardless of its activity if none are active.
*/
class FirstActiveRotationFallbackInputProcessor(
private val schedule: List<Pair<BoneId, List<BoneId>>>,
) : SkeletonInputProcessor {
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
for ((boneId, sources) in schedule) {
val bone = mutableInputSkeleton[boneId] ?: continue
if (bone.isRotationActive) continue
val active = sources.firstNotNullOfOrNull { mutableInputSkeleton[it]?.takeIf { b -> b.isRotationActive } }
val rotation = (active ?: sources.lastOrNull()?.let { mutableInputSkeleton[it] })?.rotation ?: continue
mutableInputSkeleton[boneId] = bone.copy(rotation = rotation)
}
}
}
@@ -1,48 +0,0 @@
package dev.slimevr.skeleton.inputprocessors
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.BoneId
import dev.slimevr.bones.boneId
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.SkeletonInputProcessor
/**
* Handles setting the rotation of an inactive toe bone with the first active toe bone in its sources, or keeps
* the old rotation if none of them are active.
*/
class ToeActiveLinkInputProcessor : SkeletonInputProcessor {
/**
* First element is the bone whose BoneInput is not actively receiving data.
*
* Second element contains a list of bones whose rotation should be used as a fallback prioritized from first to last.
* First active bone will be prioritized. If none are active, the last bone is used.
*/
private val toeToSources: Array<Pair<BoneId, Array<BoneId>>> = arrayOf(
BodyPart.LEFT_BIG_TOE to arrayOf(BodyPart.LEFT_INDEX_TOE, BodyPart.LEFT_MIDDLE_TOE, BodyPart.LEFT_RING_TOE, BodyPart.LEFT_LITTLE_TOE, BodyPart.LEFT_FOOT),
BodyPart.LEFT_INDEX_TOE to arrayOf(BodyPart.LEFT_MIDDLE_TOE, BodyPart.LEFT_RING_TOE, BodyPart.LEFT_LITTLE_TOE, BodyPart.LEFT_BIG_TOE, BodyPart.LEFT_FOOT),
BodyPart.LEFT_MIDDLE_TOE to arrayOf(BodyPart.LEFT_INDEX_TOE, BodyPart.LEFT_RING_TOE, BodyPart.LEFT_LITTLE_TOE, BodyPart.LEFT_BIG_TOE, BodyPart.LEFT_FOOT),
BodyPart.LEFT_RING_TOE to arrayOf(BodyPart.LEFT_MIDDLE_TOE, BodyPart.LEFT_INDEX_TOE, BodyPart.LEFT_LITTLE_TOE, BodyPart.LEFT_BIG_TOE, BodyPart.LEFT_FOOT),
BodyPart.LEFT_LITTLE_TOE to arrayOf(BodyPart.LEFT_RING_TOE, BodyPart.LEFT_MIDDLE_TOE, BodyPart.LEFT_INDEX_TOE, BodyPart.LEFT_BIG_TOE, BodyPart.LEFT_FOOT),
BodyPart.RIGHT_BIG_TOE to arrayOf(BodyPart.RIGHT_INDEX_TOE, BodyPart.RIGHT_MIDDLE_TOE, BodyPart.RIGHT_RING_TOE, BodyPart.RIGHT_LITTLE_TOE, BodyPart.RIGHT_FOOT),
BodyPart.RIGHT_INDEX_TOE to arrayOf(BodyPart.RIGHT_MIDDLE_TOE, BodyPart.RIGHT_RING_TOE, BodyPart.RIGHT_LITTLE_TOE, BodyPart.RIGHT_BIG_TOE, BodyPart.RIGHT_FOOT),
BodyPart.RIGHT_MIDDLE_TOE to arrayOf(BodyPart.RIGHT_INDEX_TOE, BodyPart.RIGHT_RING_TOE, BodyPart.RIGHT_LITTLE_TOE, BodyPart.RIGHT_BIG_TOE, BodyPart.RIGHT_FOOT),
BodyPart.RIGHT_RING_TOE to arrayOf(BodyPart.RIGHT_MIDDLE_TOE, BodyPart.RIGHT_INDEX_TOE, BodyPart.RIGHT_LITTLE_TOE, BodyPart.RIGHT_BIG_TOE, BodyPart.RIGHT_FOOT),
BodyPart.RIGHT_LITTLE_TOE to arrayOf(BodyPart.RIGHT_RING_TOE, BodyPart.RIGHT_MIDDLE_TOE, BodyPart.RIGHT_INDEX_TOE, BodyPart.RIGHT_BIG_TOE, BodyPart.RIGHT_FOOT),
).map { (bodyPart, sources) ->
bodyPart.boneId to sources.map { it.boneId }.toTypedArray()
}.toTypedArray()
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
for ((boneId, sources) in toeToSources) {
val bone = mutableInputSkeleton[boneId] ?: continue
if (bone.isRotationActive) continue
val closestActiveBoneOrLast = sources.firstNotNullOfOrNull { id ->
mutableInputSkeleton[id]?.takeIf { it.isRotationActive }
} ?: sources.lastOrNull()?.let { mutableInputSkeleton[it] } ?: continue
mutableInputSkeleton[boneId] = bone.copy(rotation = closestActiveBoneOrLast.rotation)
}
}
}
@@ -9,20 +9,22 @@ import dev.slimevr.bones.mapValues
import dev.slimevr.bones.mutateCopy
import dev.slimevr.context.Behaviour
import dev.slimevr.context.Context
import dev.slimevr.resourcepacks.bones.BoneOffsets
import dev.slimevr.resourcepacks.bones.CompiledSkeleton
import dev.slimevr.skeleton.computedprocessors.VelocityComputedProcessor
import dev.slimevr.skeleton.fkprocessors.FootPlantFkProcessor
import dev.slimevr.skeleton.fkprocessors.LocalizerFkProcessor
import dev.slimevr.skeleton.fkprocessors.ToeSnapFkProcessor
import dev.slimevr.skeleton.inputprocessors.BoneDirectLinkInputProcessor
import dev.slimevr.skeleton.inputprocessors.BoneYawFallbackInputProcessor
import dev.slimevr.skeleton.inputprocessors.ConstraintInputProcessor
import dev.slimevr.skeleton.inputprocessors.CopyRotationFallbackInputProcessor
import dev.slimevr.skeleton.inputprocessors.FingerImputeInputProcessor
import dev.slimevr.skeleton.inputprocessors.FirstActiveRotationFallbackInputProcessor
import dev.slimevr.skeleton.inputprocessors.HeadPositionFallbackProcessor
import dev.slimevr.skeleton.inputprocessors.HipYawRollAlignInputProcessor
import dev.slimevr.skeleton.inputprocessors.PredictionInputProcessor
import dev.slimevr.skeleton.inputprocessors.SmoothingInputProcessor
import dev.slimevr.skeleton.inputprocessors.SpineInputProcessor
import dev.slimevr.skeleton.inputprocessors.ToeActiveLinkInputProcessor
import dev.slimevr.skeleton.inputprocessors.UpperLegsRollAlignInputProcessor
import dev.slimevr.skeleton.targetprocessors.FloorClipTargetProcessor
import dev.slimevr.skeleton.targetprocessors.SkatingCorrectionTargetProcessor
@@ -92,6 +94,7 @@ typealias ComputedSkeleton = BoneMap<BoneState>
data class SkeletonState(
val boneInputs: InputSkeleton,
val proportionValues: Map<String, Float>,
val skeletonHeight: Float,
val floorLevel: Float,
val paused: Boolean,
@@ -110,17 +113,21 @@ val DEFAULT_BONE_INPUT = BoneInput(
isPositionActive = false,
)
fun defaultSkeletonState(registry: BoneRegistry): SkeletonState {
val offsets = toBoneOffsets(DEFAULT_PROPORTIONS, registry)
fun defaultSkeletonState(definition: CompiledSkeleton): SkeletonState {
val defaults = definition.defaultProportionValues()
val offsets = definition.toBoneOffsets(defaults)
return SkeletonState(
boneInputs = offsets.tail.mapValues { boneId, tailOffset ->
DEFAULT_BONE_INPUT.copy(
boneId = boneId,
headOffset = offsets.head[boneId] ?: Vector3.ZERO,
offset = tailOffset,
)
boneInputs = BoneMap.of<BoneInput>(definition.registry).also { inputs ->
for ((_, boneId) in definition.registry.hierarchyFrom(definition.registry.root)) {
inputs[boneId] = DEFAULT_BONE_INPUT.copy(
boneId = boneId,
headOffset = offsets.head[boneId] ?: Vector3.ZERO,
offset = offsets.tail[boneId] ?: Vector3.ZERO,
)
}
},
skeletonHeight = DEFAULT_HEIGHT,
proportionValues = defaults,
skeletonHeight = definition.height(defaults),
floorLevel = 0f,
paused = false,
pausedProcessedBoneInputs = null,
@@ -172,7 +179,7 @@ sealed interface SkeletonActions {
data class SetBoneAcceleration(val boneId: BoneId, val acceleration: Vector3, val setActive: Boolean = true) : SkeletonActions
data class SetBonePosition(val boneId: BoneId, val position: Vector3?, val setActive: Boolean = true) : SkeletonActions
data class DisableBone(val boneId: BoneId) : SkeletonActions
data class SetProportions(val boneOffsets: BoneOffsets, val skeletonHeight: Float) : SkeletonActions
data class SetProportions(val boneOffsets: BoneOffsets, val skeletonHeight: Float, val values: Map<String, Float>) : SkeletonActions
data class PauseTracking(val pause: Boolean) : SkeletonActions
data class SetPausedBoneInputs(val pausedBoneInputs: InputSkeleton) : SkeletonActions
data object ResetHeadPosition : SkeletonActions
@@ -201,6 +208,7 @@ interface SkeletonTargetProcessor {
class Skeleton(
val context: SkeletonContext,
val definition: CompiledSkeleton,
val computed: MutableSharedFlow<ComputedSkeleton>,
private val resettableSkeletonProcessors: Set<ResettableSkeletonProcessor>,
) {
@@ -219,18 +227,18 @@ class Skeleton(
companion object {
const val DEFAULT_HZ = 500
fun create(scope: CoroutineScope, ctx: Phase1ContextProvider, waiter: PreciseWaiter, hz: Int = DEFAULT_HZ): Skeleton {
fun create(scope: CoroutineScope, ctx: Phase1ContextProvider, definition: CompiledSkeleton, waiter: PreciseWaiter, hz: Int = DEFAULT_HZ): Skeleton {
val settings = ctx.config.settings
val registry = ctx.bones.current
val resettableSkeletonProcessors = mutableSetOf<ResettableSkeletonProcessor>()
val behaviours = listOf(
ProportionsBehaviour(ctx.config.userConfig, registry),
ProportionsBehaviour(ctx.config.userConfig, definition),
HeightLogBehaviour(),
LocalizerResetBehaviour(settings),
// YouSpinMeRightRoundBehaviour(inputHz = 50f),
ComputedSkeletonBehaviour(
hz = hz,
definition = definition,
waiter = waiter,
inputProcessors = listOf(
PredictionInputProcessor(settings).also { resettableSkeletonProcessors.add(it) },
@@ -240,10 +248,10 @@ class Skeleton(
SpineInputProcessor(settings),
HipYawRollAlignInputProcessor(settings),
UpperLegsRollAlignInputProcessor(settings),
BoneDirectLinkInputProcessor(),
CopyRotationFallbackInputProcessor(definition.copyRotationFallbacks),
FingerImputeInputProcessor(),
ToeActiveLinkInputProcessor(),
ConstraintInputProcessor(settings),
FirstActiveRotationFallbackInputProcessor(definition.firstActiveRotationFallbacks),
ConstraintInputProcessor(settings, definition),
),
fkComputedProcessors = listOf(
VelocityComputedProcessor().also { resettableSkeletonProcessors.add(it) },
@@ -264,7 +272,7 @@ class Skeleton(
)
val context = Context.create(
initialState = defaultSkeletonState(registry),
initialState = defaultSkeletonState(definition),
scope = scope,
reducer = ::reduce,
behaviours = behaviours,
@@ -276,7 +284,7 @@ class Skeleton(
val computed = MutableSharedFlow<ComputedSkeleton>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
computed.tryEmit(buildBones(context.state.value.boneInputs))
return Skeleton(context, computed, resettableSkeletonProcessors)
return Skeleton(context, definition, computed, resettableSkeletonProcessors)
}
}
}
@@ -1,320 +0,0 @@
package dev.slimevr.skeleton
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.BodyPartMap
import dev.slimevr.bones.BoneMap
import dev.slimevr.bones.BoneRegistry
import dev.slimevr.bones.boneId
import io.github.axisangles.ktmath.Vector3
import io.github.axisangles.ktmath.times
import solarxr_protocol.rpc.SkeletonBone
import kotlin.collections.map
import kotlin.collections.plus
// TODO : Placeholder, move this to config defaults somehow
val DEFAULT_PROPORTIONS = mapOf(
SkeletonBone.HEAD to 0.1f,
SkeletonBone.NECK to 0.1f,
SkeletonBone.UPPER_CHEST to 0.16f,
SkeletonBone.LOWER_CHEST to 0.16f,
SkeletonBone.UPPER_WAIST to 0.1f,
SkeletonBone.LOWER_WAIST to 0.1f,
SkeletonBone.HIP to 0.04f,
SkeletonBone.HIPS_WIDTH to 0.26f,
SkeletonBone.UPPER_LEG to 0.42f,
SkeletonBone.LOWER_LEG to 0.5f,
SkeletonBone.FOOT_LENGTH to 0.13f,
SkeletonBone.FOOT_SHIFT to -0.05f,
SkeletonBone.SHOULDERS_DISTANCE to 0.06f,
SkeletonBone.SHOULDERS_WIDTH to 0.35f,
SkeletonBone.UPPER_ARM to 0.26f,
SkeletonBone.LOWER_ARM to 0.26f,
SkeletonBone.HAND_Y to 0.08f,
SkeletonBone.HAND_Z to 0f,
)
// Set of SkeletonBones whose lengths sum to standing height (spine + legs).
// Arms are excluded: they scale with height but are not part of the height measurement.
private val HEIGHT_CONTRIBUTING_BONES: Set<SkeletonBone> = setOf(
SkeletonBone.NECK,
SkeletonBone.UPPER_CHEST,
SkeletonBone.LOWER_CHEST,
SkeletonBone.UPPER_WAIST,
SkeletonBone.LOWER_WAIST,
SkeletonBone.HIP,
SkeletonBone.UPPER_LEG,
SkeletonBone.LOWER_LEG,
)
// Maps each SolarXR SkeletonBone to the BodyPart(s) it controls in the skeleton with vectors for offset directions.
private val BONE_VALUE_TO_OFFSETS: Map<SkeletonBone, BodyPartMap<Vector3>> = mapOf(
SkeletonBone.HEAD to BodyPartMap(mapOf(BodyPart.HEAD to Vector3.POS_Z)),
SkeletonBone.NECK to BodyPartMap(mapOf(BodyPart.NECK to Vector3.NEG_Y)),
SkeletonBone.UPPER_CHEST to BodyPartMap(mapOf(BodyPart.UPPER_CHEST to Vector3.NEG_Y)),
SkeletonBone.LOWER_CHEST to BodyPartMap(mapOf(BodyPart.LOWER_CHEST to Vector3.NEG_Y)),
SkeletonBone.UPPER_WAIST to BodyPartMap(mapOf(BodyPart.UPPER_WAIST to Vector3.NEG_Y)),
SkeletonBone.LOWER_WAIST to BodyPartMap(mapOf(BodyPart.LOWER_WAIST to Vector3.NEG_Y)),
SkeletonBone.HIP to BodyPartMap(mapOf(BodyPart.HIP to Vector3.NEG_Y)),
SkeletonBone.UPPER_LEG to BodyPartMap(mapOf(BodyPart.LEFT_UPPER_LEG to Vector3.NEG_Y, BodyPart.RIGHT_UPPER_LEG to Vector3.NEG_Y)),
SkeletonBone.LOWER_LEG to BodyPartMap(mapOf(BodyPart.LEFT_LOWER_LEG to Vector3.NEG_Y, BodyPart.RIGHT_LOWER_LEG to Vector3.NEG_Y)),
SkeletonBone.FOOT_LENGTH to BodyPartMap(mapOf(BodyPart.LEFT_FOOT to Vector3.NEG_Z, BodyPart.RIGHT_FOOT to Vector3.NEG_Z)),
SkeletonBone.FOOT_SHIFT to BodyPartMap(mapOf(BodyPart.LEFT_LOWER_LEG to Vector3.NEG_Z, BodyPart.RIGHT_LOWER_LEG to Vector3.NEG_Z)),
SkeletonBone.SHOULDERS_DISTANCE to BodyPartMap(mapOf(BodyPart.LEFT_SHOULDER to Vector3.NEG_Y, BodyPart.RIGHT_SHOULDER to Vector3.NEG_Y)),
SkeletonBone.SHOULDERS_WIDTH to BodyPartMap(mapOf(BodyPart.LEFT_SHOULDER to Vector3.NEG_X / 2f, BodyPart.RIGHT_SHOULDER to Vector3.POS_X / 2f)),
SkeletonBone.UPPER_ARM to BodyPartMap(mapOf(BodyPart.LEFT_UPPER_ARM to Vector3.NEG_Y, BodyPart.RIGHT_UPPER_ARM to Vector3.NEG_Y)),
SkeletonBone.LOWER_ARM to BodyPartMap(mapOf(BodyPart.LEFT_LOWER_ARM to Vector3.NEG_Y, BodyPart.RIGHT_LOWER_ARM to Vector3.NEG_Y)),
SkeletonBone.HAND_Y to BodyPartMap(mapOf(BodyPart.LEFT_HAND to Vector3.NEG_Y, BodyPart.RIGHT_HAND to Vector3.NEG_Y)),
SkeletonBone.HAND_Z to BodyPartMap(mapOf(BodyPart.LEFT_HAND to Vector3.NEG_Z, BodyPart.RIGHT_HAND to Vector3.NEG_Z)),
)
private val BONE_VALUE_TO_HEAD_OFFSETS: Map<SkeletonBone, BodyPartMap<Vector3>> = mapOf(
SkeletonBone.HIPS_WIDTH to BodyPartMap(mapOf(BodyPart.LEFT_UPPER_LEG to Vector3.NEG_X / 2f, BodyPart.RIGHT_UPPER_LEG to Vector3.POS_X / 2f)),
)
// Inverts an offset table so a resolved offset vector can be turned back into a SkeletonBone value.
// Each direction is divided by its squared length so a dot product with the resolved offset
// recovers the signed scalar.
private fun invertOffsetTable(table: Map<SkeletonBone, BodyPartMap<Vector3>>): BodyPartMap<Map<SkeletonBone, Vector3>> = BodyPartMap(
table
.flatMap { (cfg, bones) -> bones.map { (bone, vec) -> bone to (cfg to vec / vec.lenSq()) } }
.groupBy({ it.first }, { it.second })
.mapValues { it.value.toMap() },
)
private val BONE_OFFSET_TO_VALUES: BodyPartMap<Map<SkeletonBone, Vector3>> = invertOffsetTable(BONE_VALUE_TO_OFFSETS)
private val BONE_HEAD_OFFSET_TO_VALUES: BodyPartMap<Map<SkeletonBone, Vector3>> = invertOffsetTable(BONE_VALUE_TO_HEAD_OFFSETS)
// Sum of default bone lengths for height-contributing bones
// Used to normalize HEIGHT_SCALED_BONE_RATIOS.
val DEFAULT_HEIGHT = DEFAULT_PROPORTIONS.height()
// Per-bone fraction of total standing height, includes spine, legs, and arms, all bones
// whose length scales with user height.
// Non-height bones (HEAD, HIPS_WIDTH) are absent; they keep fixed defaults from DEFAULT_SKELETON_STATE.
private val HEIGHT_SCALED_BONE_RATIOS: Map<SkeletonBone, Float> = (
HEIGHT_CONTRIBUTING_BONES + setOf(SkeletonBone.UPPER_ARM, SkeletonBone.LOWER_ARM, SkeletonBone.HAND_Y, SkeletonBone.FOOT_LENGTH)
).associateWith { (DEFAULT_PROPORTIONS[it] ?: 0f) / DEFAULT_HEIGHT }
// Sums the HEIGHT_CONTRIBUTING_BONES lengths to derive standing height.
fun Map<SkeletonBone, Float>.height(): Float = HEIGHT_CONTRIBUTING_BONES.sumOf { bone ->
this[bone]?.toDouble() ?: 0.0
}.toFloat()
// Returns proportions keyed by SkeletonBone.name for config storage.
// Only height-scaled bones are included.
fun computeDefaultProportionsByBone(height: Float): Map<String, Float> = HEIGHT_SCALED_BONE_RATIOS
.mapKeys { (bone, _) -> bone.name }
.mapValues { (_, ratio) -> height * ratio }
// Returns proportions for all tracked bones: height-scaled + default lengths for the rest.
fun computeAllDefaultProportionsByBone(height: Float): Map<String, Float> {
val nonScaled = DEFAULT_PROPORTIONS.mapKeys { (bone, _) -> bone.name }
val heightScaled = computeDefaultProportionsByBone(height)
return nonScaled + heightScaled
}
// Resolved bone geometry for a set of proportions. tail is the head->tail vector in the bone's own
// frame; head is the parent-tail->head vector in the parent's frame (Vector3.ZERO for most bones).
data class BoneOffsets(
val tail: BoneMap<Vector3>,
val head: BoneMap<Vector3>,
)
fun toBoneOffsets(lengths: Map<SkeletonBone, Float>, registry: BoneRegistry): BoneOffsets {
val tail = BoneMap.of<Vector3>(registry)
val head = BoneMap.of<Vector3>(registry)
for ((cfg, length) in lengths) {
BONE_VALUE_TO_OFFSETS[cfg]?.let {
for ((bodyPart, vec) in it) {
val id = bodyPart.boneId
tail[id] = (tail[id] ?: Vector3.ZERO) + length * vec
}
}
BONE_VALUE_TO_HEAD_OFFSETS[cfg]?.let {
for ((bodyPart, vec) in it) {
val id = bodyPart.boneId
head[id] = (head[id] ?: Vector3.ZERO) + length * vec
}
}
}
lengths[SkeletonBone.HAND_Y]?.let { handY ->
for ((bodyPart, vec) in getFingerOffsets(handY)) tail[bodyPart.boneId] = vec
for ((bodyPart, vec) in getFingerHeadOffsets(handY)) head[bodyPart.boneId] = vec
}
lengths[SkeletonBone.FOOT_LENGTH]?.let { footLength ->
for ((bodyPart, vec) in getToeOffsets(footLength)) tail[bodyPart.boneId] = vec
for ((bodyPart, vec) in getToeHeadOffsets(footLength)) head[bodyPart.boneId] = vec
}
return BoneOffsets(tail, head)
}
fun toBoneValues(tailOffsets: BodyPartMap<Vector3>, headOffsets: BodyPartMap<Vector3>): Map<SkeletonBone, Float> {
fun invert(offsets: BodyPartMap<Vector3>, table: BodyPartMap<Map<SkeletonBone, Vector3>>) = offsets.flatMap { (bone, vec) ->
table[bone]?.map { (cfg, cfgVec) -> cfg to vec.dot(cfgVec) } ?: emptyList()
}
return (invert(tailOffsets, BONE_OFFSET_TO_VALUES) + invert(headOffsets, BONE_HEAD_OFFSET_TO_VALUES))
.groupBy({ it.first }, { it.second })
.mapValues { it.value.first() }
}
fun configToBoneValues(proportions: Map<String, Float>): Map<SkeletonBone, Float> = proportions.mapKeys {
SkeletonBone.entries.firstOrNull { cfg -> cfg.name == it.key } ?: SkeletonBone.NONE
}
// Fraction of a finger's length taken by each phalanx, hand-ward to tip-ward. Sums to 1.
private val PHALANX_RATIOS = floatArrayOf(0.5f, 0.283f, 0.217f)
/**
* A finger in the hand's rest frame. The hand hangs with the palm toward the thigh, so for the left
* hand +X points to the palm (medial), -Y toward the fingertips, -Z forward; the right hand mirrors X.
* The knuckles fan front-to-back: the index sits forward near the thumb, the little finger back.
*
* @param segments the three bones hand-ward to tip-ward
* @param lengthFraction the whole finger's length as a fraction of handLength
* @param knuckle the first bone's head vs the hand's tail, fractions of handLength
* @param lean how the finger drifts as it extends, per unit of segment length (the -Y fall is on top)
*/
private class Finger(
val segments: List<Pair<BodyPart, BodyPart>>,
val lengthFraction: Float,
val knuckle: Vector3,
val lean: Vector3,
)
private val FINGERS = listOf(
Finger(
listOf(
BodyPart.LEFT_THUMB_METACARPAL to BodyPart.RIGHT_THUMB_METACARPAL,
BodyPart.LEFT_THUMB_PROXIMAL to BodyPart.RIGHT_THUMB_PROXIMAL,
BodyPart.LEFT_THUMB_DISTAL to BodyPart.RIGHT_THUMB_DISTAL,
),
lengthFraction = 0.72f,
knuckle = Vector3(0.16f, 0.3f, -0.28f),
lean = Vector3(0.05f, 0f, -0.7f),
),
Finger(
listOf(
BodyPart.LEFT_INDEX_PROXIMAL to BodyPart.RIGHT_INDEX_PROXIMAL,
BodyPart.LEFT_INDEX_INTERMEDIATE to BodyPart.RIGHT_INDEX_INTERMEDIATE,
BodyPart.LEFT_INDEX_DISTAL to BodyPart.RIGHT_INDEX_DISTAL,
),
lengthFraction = 0.805f,
knuckle = Vector3(0.03f, 0.05f, -0.34f),
lean = Vector3.ZERO,
),
Finger(
listOf(
BodyPart.LEFT_MIDDLE_PROXIMAL to BodyPart.RIGHT_MIDDLE_PROXIMAL,
BodyPart.LEFT_MIDDLE_INTERMEDIATE to BodyPart.RIGHT_MIDDLE_INTERMEDIATE,
BodyPart.LEFT_MIDDLE_DISTAL to BodyPart.RIGHT_MIDDLE_DISTAL,
),
lengthFraction = 0.92f,
knuckle = Vector3(0.04f, 0f, -0.11f),
lean = Vector3.ZERO,
),
Finger(
listOf(
BodyPart.LEFT_RING_PROXIMAL to BodyPart.RIGHT_RING_PROXIMAL,
BodyPart.LEFT_RING_INTERMEDIATE to BodyPart.RIGHT_RING_INTERMEDIATE,
BodyPart.LEFT_RING_DISTAL to BodyPart.RIGHT_RING_DISTAL,
),
lengthFraction = 0.805f,
knuckle = Vector3(0.03f, 0.03f, 0.11f),
lean = Vector3.ZERO,
),
Finger(
listOf(
BodyPart.LEFT_LITTLE_PROXIMAL to BodyPart.RIGHT_LITTLE_PROXIMAL,
BodyPart.LEFT_LITTLE_INTERMEDIATE to BodyPart.RIGHT_LITTLE_INTERMEDIATE,
BodyPart.LEFT_LITTLE_DISTAL to BodyPart.RIGHT_LITTLE_DISTAL,
),
lengthFraction = 0.69f,
knuckle = Vector3(0f, 0.1f, 0.31f),
lean = Vector3.ZERO,
),
)
/**
* head to tail vectors for every finger bone, scaled from handLength. The three phalanges of a finger
* share a direction and split the finger's length by [PHALANX_RATIOS].
*/
private fun getFingerOffsets(handLength: Float): Map<BodyPart, Vector3> = buildMap {
for (finger in FINGERS) {
val fingerLength = handLength * finger.lengthFraction
val dir = Vector3(finger.lean.x, -1f + finger.lean.y, finger.lean.z).unit()
finger.segments.forEachIndexed { i, (left, right) ->
val segment = fingerLength * PHALANX_RATIOS[i]
put(left, dir * segment)
put(right, Vector3(-dir.x, dir.y, dir.z) * segment)
}
}
}
/**
* head offset for each finger's first bone, fanning the knuckles across the palm.
* The other bones chain tail-to-head and are absent here.
*/
private fun getFingerHeadOffsets(handLength: Float): Map<BodyPart, Vector3> = buildMap {
for (finger in FINGERS) {
val (left, right) = finger.segments.first()
val k = finger.knuckle
put(left, Vector3(k.x * handLength, k.y * handLength, k.z * handLength))
put(right, Vector3(-k.x * handLength, k.y * handLength, k.z * handLength))
}
}
private class Toe(
val segments: Pair<BodyPart, BodyPart>,
val lengthFraction: Float,
val headOffset: Vector3,
)
private val TOES = listOf(
Toe(
BodyPart.LEFT_BIG_TOE to BodyPart.RIGHT_BIG_TOE,
lengthFraction = 0.27f,
headOffset = Vector3(0.28f, 0f, 0f),
),
Toe(
BodyPart.LEFT_INDEX_TOE to BodyPart.RIGHT_INDEX_TOE,
lengthFraction = 0.24f,
headOffset = Vector3(0.12f, 0f, 0f),
),
Toe(
BodyPart.LEFT_MIDDLE_TOE to BodyPart.RIGHT_MIDDLE_TOE,
lengthFraction = 0.23f,
headOffset = Vector3(0f, 0f, 0f),
),
Toe(
BodyPart.LEFT_RING_TOE to BodyPart.RIGHT_RING_TOE,
lengthFraction = 0.21f,
headOffset = Vector3(-0.12f, 0f, 0f),
),
Toe(
BodyPart.LEFT_LITTLE_TOE to BodyPart.RIGHT_LITTLE_TOE,
lengthFraction = 0.18f,
headOffset = Vector3(-0.26f, 0f, 0f),
),
)
/**
* Returns the offsets for the toe bones scaled from the footLength.
*/
private fun getToeOffsets(footLength: Float) = buildMap {
for (toe in TOES) {
val toeLength = footLength * toe.lengthFraction
put(toe.segments.first, Vector3(0f, 0f, -toeLength))
put(toe.segments.second, Vector3(0f, 0f, -toeLength))
}
}
// Head offsets spread the toe roots across the forefoot. X is the foot's medial-lateral axis in
// foot-local space, positive toward the big toe of a left foot. Values are fractions of footLength.
private fun getToeHeadOffsets(footLength: Float): Map<BodyPart, Vector3> = buildMap {
for (toe in TOES) {
val k = toe.headOffset
put(toe.segments.first, Vector3(k.x * footLength, k.y * footLength, k.z * footLength))
put(toe.segments.second, Vector3(-k.x * footLength, k.y * footLength, k.z * footLength))
}
}
@@ -46,7 +46,7 @@ fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when
offset = action.boneOffsets.tail[boneId] ?: bone.offset,
)
}
state.copy(boneInputs = newBones, skeletonHeight = action.skeletonHeight)
state.copy(boneInputs = newBones, skeletonHeight = action.skeletonHeight, proportionValues = action.values)
}
is SkeletonActions.PauseTracking -> state.copy(paused = action.pause, pausedProcessedBoneInputs = null)
@@ -1,11 +1,7 @@
package dev.slimevr.solarxr.driver
import dev.slimevr.AppContextProvider
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.BodyPartMap
import dev.slimevr.bones.BoneId
import dev.slimevr.bones.boneId
import dev.slimevr.bones.forEachBone
import dev.slimevr.logging.AppLogger
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.SolarXRBridgeBehaviour
@@ -23,47 +19,9 @@ import solarxr_protocol.datatypes.DeviceOrigin
import solarxr_protocol.driver_protocol.BoneBatteryUpdate
import solarxr_protocol.driver_protocol.SkeletonUpdate
val DRIVER_SUPPORTED_BONES = setOf(
BodyPart.UPPER_CHEST,
BodyPart.LEFT_UPPER_ARM,
BodyPart.RIGHT_UPPER_ARM,
BodyPart.HIP,
BodyPart.LEFT_UPPER_LEG,
BodyPart.RIGHT_UPPER_LEG,
BodyPart.LEFT_FOOT,
BodyPart.RIGHT_FOOT,
BodyPart.LEFT_SHOULDER,
BodyPart.RIGHT_SHOULDER,
BodyPart.LEFT_HAND,
BodyPart.RIGHT_HAND,
)
class DriverOutgoingTrackersBehaviour(
private val appContext: AppContextProvider,
) : SolarXRBridgeBehaviour {
// Fallback chain per bone, used to attribute battery and status to the nearest
// physical tracker. Bones without an entry just report no battery.
val bodyPartToNearest: BodyPartMap<Set<BodyPart>> = BodyPartMap(
mapOf(
BodyPart.UPPER_CHEST to setOf(BodyPart.UPPER_CHEST, BodyPart.LOWER_CHEST),
BodyPart.HIP to setOf(BodyPart.HIP, BodyPart.LOWER_WAIST, BodyPart.UPPER_WAIST, BodyPart.LOWER_CHEST, BodyPart.UPPER_CHEST),
BodyPart.LEFT_UPPER_LEG to setOf(BodyPart.LEFT_UPPER_LEG),
BodyPart.RIGHT_UPPER_LEG to setOf(BodyPart.RIGHT_UPPER_LEG),
BodyPart.LEFT_FOOT to setOf(BodyPart.LEFT_FOOT, BodyPart.LEFT_LOWER_LEG),
BodyPart.RIGHT_FOOT to setOf(BodyPart.RIGHT_FOOT, BodyPart.RIGHT_LOWER_LEG),
BodyPart.LEFT_UPPER_ARM to setOf(BodyPart.LEFT_UPPER_ARM, BodyPart.LEFT_LOWER_ARM),
BodyPart.RIGHT_UPPER_ARM to setOf(BodyPart.RIGHT_UPPER_ARM, BodyPart.RIGHT_LOWER_ARM),
BodyPart.LEFT_HAND to setOf(BodyPart.LEFT_HAND, BodyPart.LEFT_LOWER_ARM),
BodyPart.RIGHT_HAND to setOf(BodyPart.RIGHT_HAND, BodyPart.RIGHT_LOWER_ARM),
),
)
private val nearestBoneIds: Map<BoneId, Set<BoneId>> = buildMap {
bodyPartToNearest.forEachBone { bodyPart, fallbacks ->
put(bodyPart.boneId, fallbacks.mapTo(mutableSetOf()) { it.boneId })
}
}
@OptIn(ExperimentalCoroutinesApi::class)
override fun observe(receiver: SolarXRBridge) {
val server = appContext.server
@@ -96,7 +54,7 @@ class DriverOutgoingTrackersBehaviour(
receiver.sendDriverMessage(SkeletonUpdate(bones = bones))
for (boneId in computedSkeleton.keys) {
val closestTracker = nearestBoneIds[boneId].orEmpty()
val closestTracker = appContext.skeleton.definition.batterySourcesOf(boneId)
.firstNotNullOfOrNull { trackerStateByBoneId[it] }
val closestDevice =
server.context.state.value.devices[closestTracker?.deviceId]?.context?.state?.value
@@ -2,8 +2,8 @@ package dev.slimevr.solarxr.rpc
import dev.slimevr.AppContextProvider
import dev.slimevr.bones.BoneId
import dev.slimevr.bones.BoneRegistry
import dev.slimevr.config.SettingsActions
import dev.slimevr.resourcepacks.bones.CompiledSkeleton
import dev.slimevr.routing.OutputStates
import dev.slimevr.routing.Routes
import dev.slimevr.routing.acceptedBones
@@ -30,26 +30,21 @@ import solarxr_protocol.rpc.RoutingOutput
import solarxr_protocol.rpc.RoutingOutputState
import solarxr_protocol.rpc.RoutingOutputStatus
// Every bone any output can take gets a row, so the GUI can draw the whole table
// from the response alone.
private val ROUTABLE_BONES = RoutingOutput.entries.flatMapTo(mutableSetOf()) { acceptedBones(it) }
private fun buildResponse(
automatic: Boolean,
routes: Routes,
outputStates: OutputStates,
registry: BoneRegistry,
routableBones: Set<BoneId>,
definition: CompiledSkeleton,
) = BoneRoutingSettingsResponse(
automatic = automatic,
routes = ROUTABLE_BONES.mapNotNull { bone -> registry[bone] }.map { boneId ->
BoneRoute(boneId = boneId.value, outputs = routes[boneId].orEmpty().toList())
},
routes = routableBones.map { boneId -> BoneRoute(boneId = boneId.value, outputs = routes[boneId].orEmpty().toList()) },
outputs = RoutingOutput.entries.map { output ->
RoutingOutputStatus(
output = output,
accepts = acceptedBones(output).mapNotNull { registry[it]?.value },
requires = requiredBones(output).mapNotNull { registry[it]?.value },
overridable = overridableBones(output).mapNotNull { registry[it]?.value },
accepts = acceptedBones(output, definition).map { it.value },
requires = requiredBones(output, definition).map { it.value },
overridable = overridableBones(output, definition).map { it.value },
conflicts = conflictingOutputs(output).toList(),
state = outputStates[output] ?: RoutingOutputState.UNSUPPORTED,
)
@@ -62,12 +57,15 @@ class BoneRoutingBehaviour(
private val settings = appContext.config.settings
override fun observe(receiver: SolarXRBridge) {
val registry = appContext.bones.current
val definition = appContext.skeleton.definition
// Every bone any output can take gets a row, so the GUI can draw the whole table
// from the response alone.
val routableBones = RoutingOutput.entries.flatMapTo(mutableSetOf()) { acceptedBones(it, definition) }
val responses = combine(
settings.context.state.map { it.data.boneRoutingConfig.automatic }.distinctUntilChanged(),
intendedRoutesFlow(appContext),
outputStatesFlow(appContext),
) { automatic, routes, outputStates -> buildResponse(automatic, routes, outputStates, registry) }
) { automatic, routes, outputStates -> buildResponse(automatic, routes, outputStates, routableBones, definition) }
.distinctUntilChanged()
receiver.rpcDispatcher.on<BoneRoutingSettingsRequest> {
@@ -95,7 +93,7 @@ class BoneRoutingBehaviour(
config = boneRoutingConfig,
automatic = req.automatic,
routes = requested,
registry = registry,
definition = definition,
),
)
},
@@ -1,23 +1,16 @@
package dev.slimevr.solarxr.rpc
import dev.slimevr.bones.ALL_BODY_PARTS
import dev.slimevr.bones.bodyPartMap
import dev.slimevr.bones.boneId
import dev.slimevr.config.UserConfig
import dev.slimevr.config.UserConfigActions
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.resourcepacks.bones.proportionKey
import dev.slimevr.resourcepacks.bones.skeletonBoneOf
import dev.slimevr.skeleton.Skeleton
import dev.slimevr.skeleton.computeAllDefaultProportionsByBone
import dev.slimevr.skeleton.computeDefaultProportionsByBone
import dev.slimevr.skeleton.height
import dev.slimevr.skeleton.toBoneValues
import dev.slimevr.skeleton.SkeletonState
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.SolarXRBridgeBehaviour
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import solarxr_protocol.rpc.ChangeSkeletonProportionsRequest
import solarxr_protocol.rpc.ChangeUserHeightRequest
@@ -29,45 +22,27 @@ import solarxr_protocol.rpc.SkeletonProportionsResponse
private const val MIN_HEIGHT = 0.9f
// Bones whose value is a signed offset rather than a length, so negatives are valid.
private val SIGNED_BONES = setOf(SkeletonBone.FOOT_SHIFT)
internal fun buildSkeletonProportionsResponse(state: SkeletonState): SkeletonProportionsResponse = SkeletonProportionsResponse(
skeletonParts = state.proportionValues.mapNotNull { (key, value) -> skeletonBoneOf(key)?.let { SkeletonPart(it, value) } },
skeletonHeight = state.skeletonHeight,
)
class SkeletonProportionsBehaviour(
private val userConfig: UserConfig,
private val skeleton: Skeleton,
) : SolarXRBridgeBehaviour {
private fun buildConfigResponse(boneInputs: InputSkeleton): SkeletonProportionsResponse {
val registry = boneInputs.registry
val tailOffsets = bodyPartMap<Vector3>()
val headOffsets = bodyPartMap<Vector3>()
for ((boneId, input) in boneInputs) {
val bodyPart = registry.bodyPartOf(boneId) ?: continue
tailOffsets[bodyPart] = input.offset
headOffsets[bodyPart] = input.headOffset
}
val boneValues = toBoneValues(tailOffsets, headOffsets)
val skeletonParts = boneValues.map { (offset, bone) -> SkeletonPart(offset, bone) }
return SkeletonProportionsResponse(skeletonParts = skeletonParts, skeletonHeight = boneValues.height())
}
override fun observe(receiver: SolarXRBridge) {
skeleton.context.state
.map { it.boneInputs }
.distinctUntilChanged { old, new ->
ALL_BODY_PARTS.all { part ->
val id = part.boneId
old[id]?.offset == new[id]?.offset && old[id]?.headOffset == new[id]?.headOffset
}
}
.distinctUntilChangedBy { it.proportionValues }
.drop(1)
.onEach { boneInputs ->
val configResponse = buildConfigResponse(boneInputs)
.onEach { state ->
val configResponse = buildSkeletonProportionsResponse(state)
receiver.sendRpc(configResponse)
}
.launchIn(receiver.context.scope)
receiver.rpcDispatcher.on<SkeletonProportionsRequest> {
receiver.sendRpc(buildConfigResponse(skeleton.context.state.value.boneInputs))
receiver.sendRpc(buildSkeletonProportionsResponse(skeleton.context.state.value))
}.launchIn(receiver.context.scope)
receiver.rpcDispatcher.on<ChangeUserHeightRequest> { req ->
@@ -77,7 +52,7 @@ class SkeletonProportionsBehaviour(
if (height >= MIN_HEIGHT) {
userConfig.context.dispatch(
UserConfigActions.Update {
copy(userHeight = height, proportions = computeDefaultProportionsByBone(height))
copy(userHeight = height, proportions = skeleton.definition.heightScaledProportionValues(height))
},
)
}
@@ -86,7 +61,7 @@ class SkeletonProportionsBehaviour(
receiver.rpcDispatcher.on<SkeletonProportionsResetAllRequest> {
val height = userConfig.context.state.value.data.userHeight
if (height >= MIN_HEIGHT) {
val defaults = computeAllDefaultProportionsByBone(height)
val defaults = skeleton.definition.defaultProportionValues(height)
userConfig.context.dispatch(UserConfigActions.Update { copy(proportions = defaults) })
}
}.launchIn(receiver.context.scope)
@@ -94,9 +69,11 @@ class SkeletonProportionsBehaviour(
receiver.rpcDispatcher.on<ChangeSkeletonProportionsRequest> { req ->
val bone = req.bone
if (bone == SkeletonBone.NONE) return@on
val value = if (bone in SIGNED_BONES) req.value else req.value.coerceAtLeast(0f)
val key = bone.proportionKey
val proportion = skeleton.definition.proportions[key] ?: return@on
val value = req.value.coerceIn(proportion.minimum ?: Float.NEGATIVE_INFINITY, proportion.maximum ?: Float.POSITIVE_INFINITY)
userConfig.context.dispatch(UserConfigActions.Update { copy(proportions = proportions + (bone.name to value)) })
userConfig.context.dispatch(UserConfigActions.Update { copy(proportions = proportions + (key to value)) })
}.launchIn(receiver.context.scope)
}
}
@@ -1,9 +1,9 @@
package dev.slimevr.vmc
import dev.slimevr.bones.BodyPartMap
import dev.slimevr.bones.bodyPartMap
import dev.slimevr.bones.BoneMap
import dev.slimevr.osc.OscArg
import dev.slimevr.osc.OscMessage
import dev.slimevr.resourcepacks.bones.CompiledSkeleton
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
@@ -21,23 +21,24 @@ data class VmcPoseTracker(
* for the rest.
*/
class VmcInputFrame(
val boneLocalRotations: BodyPartMap<Quaternion> = bodyPartMap(),
val boneLocalPositions: BodyPartMap<Vector3> = bodyPartMap(),
definition: CompiledSkeleton,
val boneLocalRotations: BoneMap<Quaternion> = BoneMap.of(definition.registry),
val boneLocalPositions: BoneMap<Vector3> = BoneMap.of(definition.registry),
val poseTrackers: MutableMap<String, VmcPoseTracker> = mutableMapOf(),
var rootPosition: Vector3 = Vector3.ZERO,
var rootRotation: Quaternion = Quaternion.IDENTITY,
)
fun emptyVmcInputFrame() = VmcInputFrame()
fun emptyVmcInputFrame(definition: CompiledSkeleton) = VmcInputFrame(definition)
internal fun decodeVmcMessage(msg: OscMessage, frame: VmcInputFrame) {
internal fun decodeVmcMessage(msg: OscMessage, frame: VmcInputFrame, definition: CompiledSkeleton) {
when (msg.address) {
"/VMC/Ext/Bone/Pos" -> {
val name = (msg.args.getOrNull(0) as? OscArg.String)?.value ?: return
val bodyPart = UNITY_BONE_TO_BODY_PART[name.lowercase()] ?: return
val boneId = definition.unityNameToBone[name] ?: return
val (pos, rot) = parseVmcTransform(msg.args, startIndex = 1) ?: return
frame.boneLocalPositions[bodyPart] = pos
frame.boneLocalRotations[bodyPart] = rot
frame.boneLocalPositions[boneId] = pos
frame.boneLocalRotations[boneId] = rot
}
"/VMC/Ext/Root/Pos" -> {
@@ -84,40 +85,42 @@ internal fun parseVmcTransform(args: List<OscArg>, startIndex: Int): Pair<Vector
data class VmcBoneTransform(val rotation: Quaternion, val position: Vector3)
/**
* Inverse of vmcLocalRotation/vmcLocalPosition (output-encoder.kt): walks VMC_INPUT_BONE_ORDER
* parent-before-child, accumulating VMC's parent-local bone rotations/positions into world
* Inverse of vmcLocalRotation/vmcLocalPosition (output-encoder.kt): walks the compiled VMC input
* order parent-before-child, accumulating VMC's parent-local bone rotations/positions into world
* rotations and positions.
*/
fun vmcWorldTransforms(
locals: BodyPartMap<Quaternion>,
localPositions: BodyPartMap<Vector3>,
definition: CompiledSkeleton,
locals: BoneMap<Quaternion>,
localPositions: BoneMap<Vector3>,
rootRotation: Quaternion,
rootPosition: Vector3,
scale: Float,
): BodyPartMap<VmcBoneTransform> {
val restAdjusted = bodyPartMap<Quaternion>()
val modelPositions = bodyPartMap<Vector3>()
val result = bodyPartMap<VmcBoneTransform>()
): BoneMap<VmcBoneTransform> {
val registry = definition.registry
val restAdjusted = BoneMap.of<Quaternion>(registry)
val modelPositions = BoneMap.of<Vector3>(registry)
val result = BoneMap.of<VmcBoneTransform>(registry)
for (bone in VMC_INPUT_BONE_ORDER) {
val parent = VMC_INPUT_BONE_PARENTS[bone]
val local = locals[bone] ?: Quaternion.IDENTITY
val localPosition = localPositions[bone] ?: Vector3.ZERO
for (boneId in definition.vmcInputOrder) {
val output = definition.vmcOutputOf(boneId) ?: continue
val parent = output.inputParent
val local = locals[boneId] ?: Quaternion.IDENTITY
val localPosition = localPositions[boneId] ?: Vector3.ZERO
val parentAdjusted = parent?.let { restAdjusted[it] }
val adjusted = if (parentAdjusted != null) parentAdjusted * local else local
restAdjusted[bone] = adjusted
restAdjusted[boneId] = adjusted
val modelPosition = if (parent != null && parentAdjusted != null) {
(modelPositions[parent] ?: Vector3.ZERO) + parentAdjusted.sandwich(localPosition)
} else {
localPosition
}
modelPositions[bone] = modelPosition
modelPositions[boneId] = modelPosition
val rest = VMC_REST_ROTATIONS[bone] ?: Quaternion.IDENTITY
result[bone] = VmcBoneTransform(
rotation = rootRotation * (adjusted * rest),
result[boneId] = VmcBoneTransform(
rotation = rootRotation * (adjusted * output.restRotation),
position = (rootPosition + rootRotation.sandwich(modelPosition)) * scale,
)
}
@@ -2,9 +2,7 @@ package dev.slimevr.vmc
import dev.slimevr.AppContextProvider
import dev.slimevr.VRServerActions
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.BoneId
import dev.slimevr.bones.boneId
import dev.slimevr.config.Settings
import dev.slimevr.device.Device
import dev.slimevr.device.DeviceActions
@@ -12,6 +10,7 @@ import dev.slimevr.logging.AppLogger
import dev.slimevr.osc.OscBundle
import dev.slimevr.osc.OscReceiver
import dev.slimevr.osc.forEachOscMessage
import dev.slimevr.resourcepacks.bones.CompiledSkeleton
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.util.formatExceptionMessage
@@ -32,12 +31,13 @@ internal class VmcTrackerRegistry(
private val boneTrackerIds = mutableMapOf<BoneId, Int>()
private val poseTrackerIds = mutableMapOf<String, Int>()
fun boneTracker(bodyPart: BodyPart, unityName: String): Tracker {
val boneId = bodyPart.boneId
fun boneTracker(boneId: BoneId, unityName: String): Tracker {
boneTrackerIds[boneId]?.let { id -> appContext.server.getTracker(id)?.let { existing -> return existing } }
val device = findOrCreateDevice()
val trackerId = appContext.server.nextHandle()
val registry = appContext.skeleton.definition.registry
val hardwareKey = registry.bodyPartOf(boneId) ?: registry.keyOf(boneId) ?: unityName
val runtimeTracker = Tracker.create(
scope = manager.context.scope,
id = trackerId,
@@ -45,7 +45,7 @@ internal class VmcTrackerRegistry(
boneId = boneId,
intendedBoneId = boneId,
deviceId = device.context.state.value.id,
hardwareId = "vmc:bone:$bodyPart",
hardwareId = "vmc:bone:$hardwareKey",
origin = DeviceOrigin.VMC,
appContext = appContext,
)
@@ -118,13 +118,13 @@ class VMCInputBehaviour(
private val appContext: AppContextProvider,
private val settings: Settings,
) : VMCBehaviour {
internal class InputRuntime {
var lastFrame: VmcInputFrame = emptyVmcInputFrame()
internal class InputRuntime(definition: CompiledSkeleton) {
var lastFrame: VmcInputFrame = emptyVmcInputFrame(definition)
}
override fun observe(receiver: VMCManager) {
val registry = VmcTrackerRegistry(appContext, receiver)
val runtime = InputRuntime()
val runtime = InputRuntime(appContext.skeleton.definition)
var oscReceiver: OscReceiver? = null
settings.context.state
@@ -195,7 +195,8 @@ class VMCInputBehaviour(
receiver: VMCManager,
portIn: Int,
) {
forEachOscMessage(bundle) { msg -> decodeVmcMessage(msg, runtime.lastFrame) }
val definition = appContext.skeleton.definition
forEachOscMessage(bundle) { msg -> decodeVmcMessage(msg, runtime.lastFrame, definition) }
val frame = runtime.lastFrame
val vrmHeight = receiver.context.state.value.vrm?.vrmHeight
@@ -203,6 +204,7 @@ class VMCInputBehaviour(
val scale = if (vrmHeight != null && vrmHeight > 0f) skeletonHeight / vrmHeight else 1f
val worldTransforms = vmcWorldTransforms(
definition = definition,
locals = frame.boneLocalRotations,
localPositions = frame.boneLocalPositions,
rootRotation = frame.rootRotation,
@@ -210,10 +212,10 @@ class VMCInputBehaviour(
scale = scale,
)
for (bodyPart in frame.boneLocalRotations.keys) {
val transform = worldTransforms[bodyPart] ?: continue
val unityName = BODY_PART_TO_UNITY_BONE[bodyPart]?.first() ?: continue
val tracker = registry.boneTracker(bodyPart, unityName)
for (boneId in frame.boneLocalRotations.keys) {
val transform = worldTransforms[boneId] ?: continue
val unityName = definition.vmcOutputOf(boneId)?.names?.first() ?: continue
val tracker = registry.boneTracker(boneId, unityName)
tracker.context.dispatch(TrackerActions.SetStatus(TrackerStatus.OK))
tracker.context.dispatch(TrackerActions.SetRotation(rotation = transform.rotation, position = transform.position))
}
@@ -1,241 +0,0 @@
package dev.slimevr.vmc
import com.jme3.math.FastMath
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.BodyPartMap
import dev.slimevr.resets.ResetBodyParts
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
// TODO how to handle UPPER_WAIST?
val BODY_PART_TO_UNITY_BONE: BodyPartMap<Array<String>> = BodyPartMap(
mapOf(
BodyPart.HEAD to arrayOf("Head"),
BodyPart.NECK to arrayOf("Neck"),
BodyPart.UPPER_CHEST to arrayOf("UpperChest"),
BodyPart.LOWER_CHEST to arrayOf("Chest"),
BodyPart.UPPER_WAIST to arrayOf("Spine"),
BodyPart.HIP to arrayOf("Hips"),
BodyPart.LEFT_SHOULDER to arrayOf("LeftShoulder"),
BodyPart.RIGHT_SHOULDER to arrayOf("RightShoulder"),
BodyPart.LEFT_UPPER_ARM to arrayOf("LeftUpperArm"),
BodyPart.RIGHT_UPPER_ARM to arrayOf("RightUpperArm"),
BodyPart.LEFT_LOWER_ARM to arrayOf("LeftLowerArm"),
BodyPart.RIGHT_LOWER_ARM to arrayOf("RightLowerArm"),
BodyPart.LEFT_HAND to arrayOf("LeftHand"),
BodyPart.RIGHT_HAND to arrayOf("RightHand"),
BodyPart.LEFT_UPPER_LEG to arrayOf("LeftUpperLeg"),
BodyPart.RIGHT_UPPER_LEG to arrayOf("RightUpperLeg"),
BodyPart.LEFT_LOWER_LEG to arrayOf("LeftLowerLeg"),
BodyPart.RIGHT_LOWER_LEG to arrayOf("RightLowerLeg"),
BodyPart.LEFT_FOOT to arrayOf("LeftFoot"),
BodyPart.RIGHT_FOOT to arrayOf("RightFoot"),
BodyPart.LEFT_THUMB_METACARPAL to arrayOf("LeftThumbProximal"),
BodyPart.LEFT_THUMB_PROXIMAL to arrayOf("LeftThumbIntermediate"),
BodyPart.LEFT_THUMB_DISTAL to arrayOf("LeftThumbDistal"),
BodyPart.LEFT_INDEX_PROXIMAL to arrayOf("LeftIndexProximal"),
BodyPart.LEFT_INDEX_INTERMEDIATE to arrayOf("LeftIndexIntermediate"),
BodyPart.LEFT_INDEX_DISTAL to arrayOf("LeftIndexDistal"),
BodyPart.LEFT_MIDDLE_PROXIMAL to arrayOf("LeftMiddleProximal"),
BodyPart.LEFT_MIDDLE_INTERMEDIATE to arrayOf("LeftMiddleIntermediate"),
BodyPart.LEFT_MIDDLE_DISTAL to arrayOf("LeftMiddleDistal"),
BodyPart.LEFT_RING_PROXIMAL to arrayOf("LeftRingProximal"),
BodyPart.LEFT_RING_INTERMEDIATE to arrayOf("LeftRingIntermediate"),
BodyPart.LEFT_RING_DISTAL to arrayOf("LeftRingDistal"),
BodyPart.LEFT_LITTLE_PROXIMAL to arrayOf("LeftLittleProximal"),
BodyPart.LEFT_LITTLE_INTERMEDIATE to arrayOf("LeftLittleIntermediate"),
BodyPart.LEFT_LITTLE_DISTAL to arrayOf("LeftLittleDistal"),
BodyPart.RIGHT_THUMB_METACARPAL to arrayOf("RightThumbProximal"),
BodyPart.RIGHT_THUMB_PROXIMAL to arrayOf("RightThumbIntermediate"),
BodyPart.RIGHT_THUMB_DISTAL to arrayOf("RightThumbDistal"),
BodyPart.RIGHT_INDEX_PROXIMAL to arrayOf("RightIndexProximal"),
BodyPart.RIGHT_INDEX_INTERMEDIATE to arrayOf("RightIndexIntermediate"),
BodyPart.RIGHT_INDEX_DISTAL to arrayOf("RightIndexDistal"),
BodyPart.RIGHT_MIDDLE_PROXIMAL to arrayOf("RightMiddleProximal"),
BodyPart.RIGHT_MIDDLE_INTERMEDIATE to arrayOf("RightMiddleIntermediate"),
BodyPart.RIGHT_MIDDLE_DISTAL to arrayOf("RightMiddleDistal"),
BodyPart.RIGHT_RING_PROXIMAL to arrayOf("RightRingProximal"),
BodyPart.RIGHT_RING_INTERMEDIATE to arrayOf("RightRingIntermediate"),
BodyPart.RIGHT_RING_DISTAL to arrayOf("RightRingDistal"),
BodyPart.RIGHT_LITTLE_PROXIMAL to arrayOf("RightLittleProximal"),
BodyPart.RIGHT_LITTLE_INTERMEDIATE to arrayOf("RightLittleIntermediate"),
BodyPart.RIGHT_LITTLE_DISTAL to arrayOf("RightLittleDistal"),
BodyPart.LEFT_BIG_TOE to arrayOf("LeftToes", "LeftBigToe"),
BodyPart.LEFT_INDEX_TOE to arrayOf("LeftIndexToe"),
BodyPart.LEFT_MIDDLE_TOE to arrayOf("LeftMiddleToe"),
BodyPart.LEFT_RING_TOE to arrayOf("LeftRingToe"),
BodyPart.LEFT_LITTLE_TOE to arrayOf("LeftLittleToe"),
BodyPart.RIGHT_BIG_TOE to arrayOf("RightToes", "RightBigToe"),
BodyPart.RIGHT_INDEX_TOE to arrayOf("RightIndexToe"),
BodyPart.RIGHT_MIDDLE_TOE to arrayOf("RightMiddleToe"),
BodyPart.RIGHT_RING_TOE to arrayOf("RightRingToe"),
BodyPart.RIGHT_LITTLE_TOE to arrayOf("RightLittleToe"),
),
)
// Bones VMC can accept. Used by the routing module.
val VMC_SUPPORTED_BONES: Set<BodyPart> = BODY_PART_TO_UNITY_BONE.keys
// HIP-rooted hierarchy. VMC/Unity expects this; our skeleton is HEAD-rooted.
// TODO Test with a model that has UPPER_CHEST
// and figure out how to deal with it (check if present in VRM?)
val VMC_HIERARCHY_MAP: BodyPartMap<Array<BodyPart>> = BodyPartMap(
mapOf(
BodyPart.HIP to arrayOf(BodyPart.UPPER_WAIST, BodyPart.LEFT_UPPER_LEG, BodyPart.RIGHT_UPPER_LEG),
BodyPart.UPPER_WAIST to arrayOf(BodyPart.LOWER_CHEST),
BodyPart.LOWER_CHEST to arrayOf(BodyPart.UPPER_CHEST, BodyPart.NECK, BodyPart.LEFT_SHOULDER, BodyPart.RIGHT_SHOULDER),
BodyPart.NECK to arrayOf(BodyPart.HEAD),
BodyPart.LEFT_UPPER_LEG to arrayOf(BodyPart.LEFT_LOWER_LEG),
BodyPart.RIGHT_UPPER_LEG to arrayOf(BodyPart.RIGHT_LOWER_LEG),
BodyPart.LEFT_LOWER_LEG to arrayOf(BodyPart.LEFT_FOOT),
BodyPart.RIGHT_LOWER_LEG to arrayOf(BodyPart.RIGHT_FOOT),
BodyPart.LEFT_SHOULDER to arrayOf(BodyPart.LEFT_UPPER_ARM),
BodyPart.RIGHT_SHOULDER to arrayOf(BodyPart.RIGHT_UPPER_ARM),
BodyPart.LEFT_UPPER_ARM to arrayOf(BodyPart.LEFT_LOWER_ARM),
BodyPart.RIGHT_UPPER_ARM to arrayOf(BodyPart.RIGHT_LOWER_ARM),
BodyPart.LEFT_LOWER_ARM to arrayOf(BodyPart.LEFT_HAND),
BodyPart.RIGHT_LOWER_ARM to arrayOf(BodyPart.RIGHT_HAND),
BodyPart.LEFT_HAND to arrayOf(
BodyPart.LEFT_THUMB_METACARPAL,
BodyPart.LEFT_INDEX_PROXIMAL,
BodyPart.LEFT_MIDDLE_PROXIMAL,
BodyPart.LEFT_RING_PROXIMAL,
BodyPart.LEFT_LITTLE_PROXIMAL,
),
BodyPart.LEFT_THUMB_METACARPAL to arrayOf(BodyPart.LEFT_THUMB_PROXIMAL),
BodyPart.LEFT_THUMB_PROXIMAL to arrayOf(BodyPart.LEFT_THUMB_DISTAL),
BodyPart.LEFT_INDEX_PROXIMAL to arrayOf(BodyPart.LEFT_INDEX_INTERMEDIATE),
BodyPart.LEFT_INDEX_INTERMEDIATE to arrayOf(BodyPart.LEFT_INDEX_DISTAL),
BodyPart.LEFT_MIDDLE_PROXIMAL to arrayOf(BodyPart.LEFT_MIDDLE_INTERMEDIATE),
BodyPart.LEFT_MIDDLE_INTERMEDIATE to arrayOf(BodyPart.LEFT_MIDDLE_DISTAL),
BodyPart.LEFT_RING_PROXIMAL to arrayOf(BodyPart.LEFT_RING_INTERMEDIATE),
BodyPart.LEFT_RING_INTERMEDIATE to arrayOf(BodyPart.LEFT_RING_DISTAL),
BodyPart.LEFT_LITTLE_PROXIMAL to arrayOf(BodyPart.LEFT_LITTLE_INTERMEDIATE),
BodyPart.LEFT_LITTLE_INTERMEDIATE to arrayOf(BodyPart.LEFT_LITTLE_DISTAL),
BodyPart.RIGHT_HAND to arrayOf(
BodyPart.RIGHT_THUMB_METACARPAL,
BodyPart.RIGHT_INDEX_PROXIMAL,
BodyPart.RIGHT_MIDDLE_PROXIMAL,
BodyPart.RIGHT_RING_PROXIMAL,
BodyPart.RIGHT_LITTLE_PROXIMAL,
),
BodyPart.RIGHT_THUMB_METACARPAL to arrayOf(BodyPart.RIGHT_THUMB_PROXIMAL),
BodyPart.RIGHT_THUMB_PROXIMAL to arrayOf(BodyPart.RIGHT_THUMB_DISTAL),
BodyPart.RIGHT_INDEX_PROXIMAL to arrayOf(BodyPart.RIGHT_INDEX_INTERMEDIATE),
BodyPart.RIGHT_INDEX_INTERMEDIATE to arrayOf(BodyPart.RIGHT_INDEX_DISTAL),
BodyPart.RIGHT_MIDDLE_PROXIMAL to arrayOf(BodyPart.RIGHT_MIDDLE_INTERMEDIATE),
BodyPart.RIGHT_MIDDLE_INTERMEDIATE to arrayOf(BodyPart.RIGHT_MIDDLE_DISTAL),
BodyPart.RIGHT_RING_PROXIMAL to arrayOf(BodyPart.RIGHT_RING_INTERMEDIATE),
BodyPart.RIGHT_RING_INTERMEDIATE to arrayOf(BodyPart.RIGHT_RING_DISTAL),
BodyPart.RIGHT_LITTLE_PROXIMAL to arrayOf(BodyPart.RIGHT_LITTLE_INTERMEDIATE),
BodyPart.RIGHT_LITTLE_INTERMEDIATE to arrayOf(BodyPart.RIGHT_LITTLE_DISTAL),
BodyPart.LEFT_FOOT to arrayOf(
BodyPart.LEFT_BIG_TOE,
BodyPart.LEFT_INDEX_TOE,
BodyPart.LEFT_MIDDLE_TOE,
BodyPart.LEFT_RING_TOE,
BodyPart.LEFT_LITTLE_TOE,
),
BodyPart.RIGHT_FOOT to arrayOf(
BodyPart.RIGHT_BIG_TOE,
BodyPart.RIGHT_INDEX_TOE,
BodyPart.RIGHT_MIDDLE_TOE,
BodyPart.RIGHT_RING_TOE,
BodyPart.RIGHT_LITTLE_TOE,
),
),
)
private class VmcBoneTree(hierarchy: BodyPartMap<Array<BodyPart>>) {
val order: List<BodyPart>
val parents: BodyPartMap<BodyPart?>
init {
fun visit(parent: BodyPart?, bone: BodyPart, into: MutableList<Pair<BodyPart?, BodyPart>>) {
into.add(parent to bone)
hierarchy[bone]?.forEach { visit(bone, it, into) }
}
val traversal = buildList { visit(null, BodyPart.HIP, this) }
order = traversal.map { (_, bone) -> bone }
parents = BodyPartMap(traversal.associate { (parent, child) -> child to parent })
}
}
val VMC_OUTPUT_BONE_PARENTS: BodyPartMap<BodyPart?> = VmcBoneTree(VMC_HIERARCHY_MAP).parents
val VMC_INPUT_HIERARCHY_MAP: BodyPartMap<Array<BodyPart>> = BodyPartMap(
VMC_HIERARCHY_MAP +
mapOf(
BodyPart.LOWER_CHEST to arrayOf(BodyPart.UPPER_CHEST),
BodyPart.UPPER_CHEST to arrayOf(BodyPart.NECK, BodyPart.LEFT_SHOULDER, BodyPart.RIGHT_SHOULDER),
),
)
private val vmcInputTree = VmcBoneTree(VMC_INPUT_HIERARCHY_MAP)
val VMC_INPUT_BONE_ORDER: List<BodyPart> = vmcInputTree.order
val VMC_INPUT_BONE_PARENTS: BodyPartMap<BodyPart?> = vmcInputTree.parents
val UNITY_BONE_TO_BODY_PART: Map<String, BodyPart> = BODY_PART_TO_UNITY_BONE.entries
.flatMap { (bodyPart, names) -> names.map { name -> name.lowercase() to bodyPart } }
.toMap()
val VMC_MIRROR_BONE_PAIRS: List<Pair<BodyPart, BodyPart>> = listOf(
BodyPart.LEFT_SHOULDER to BodyPart.RIGHT_SHOULDER,
BodyPart.LEFT_UPPER_ARM to BodyPart.RIGHT_UPPER_ARM,
BodyPart.LEFT_LOWER_ARM to BodyPart.RIGHT_LOWER_ARM,
BodyPart.LEFT_HAND to BodyPart.RIGHT_HAND,
BodyPart.LEFT_UPPER_LEG to BodyPart.RIGHT_UPPER_LEG,
BodyPart.LEFT_LOWER_LEG to BodyPart.RIGHT_LOWER_LEG,
BodyPart.LEFT_FOOT to BodyPart.RIGHT_FOOT,
BodyPart.LEFT_THUMB_METACARPAL to BodyPart.RIGHT_THUMB_METACARPAL,
BodyPart.LEFT_THUMB_PROXIMAL to BodyPart.RIGHT_THUMB_PROXIMAL,
BodyPart.LEFT_THUMB_DISTAL to BodyPart.RIGHT_THUMB_DISTAL,
BodyPart.LEFT_INDEX_PROXIMAL to BodyPart.RIGHT_INDEX_PROXIMAL,
BodyPart.LEFT_INDEX_INTERMEDIATE to BodyPart.RIGHT_INDEX_INTERMEDIATE,
BodyPart.LEFT_INDEX_DISTAL to BodyPart.RIGHT_INDEX_DISTAL,
BodyPart.LEFT_MIDDLE_PROXIMAL to BodyPart.RIGHT_MIDDLE_PROXIMAL,
BodyPart.LEFT_MIDDLE_INTERMEDIATE to BodyPart.RIGHT_MIDDLE_INTERMEDIATE,
BodyPart.LEFT_MIDDLE_DISTAL to BodyPart.RIGHT_MIDDLE_DISTAL,
BodyPart.LEFT_RING_PROXIMAL to BodyPart.RIGHT_RING_PROXIMAL,
BodyPart.LEFT_RING_INTERMEDIATE to BodyPart.RIGHT_RING_INTERMEDIATE,
BodyPart.LEFT_RING_DISTAL to BodyPart.RIGHT_RING_DISTAL,
BodyPart.LEFT_LITTLE_PROXIMAL to BodyPart.RIGHT_LITTLE_PROXIMAL,
BodyPart.LEFT_LITTLE_INTERMEDIATE to BodyPart.RIGHT_LITTLE_INTERMEDIATE,
BodyPart.LEFT_LITTLE_DISTAL to BodyPart.RIGHT_LITTLE_DISTAL,
BodyPart.LEFT_BIG_TOE to BodyPart.RIGHT_BIG_TOE,
BodyPart.LEFT_BIG_TOE to BodyPart.RIGHT_BIG_TOE,
BodyPart.LEFT_INDEX_TOE to BodyPart.RIGHT_INDEX_TOE,
BodyPart.LEFT_MIDDLE_TOE to BodyPart.RIGHT_MIDDLE_TOE,
BodyPart.LEFT_RING_TOE to BodyPart.RIGHT_RING_TOE,
BodyPart.LEFT_LITTLE_TOE to BodyPart.RIGHT_LITTLE_TOE,
)
val VMC_MIRROR_BONES: BodyPartMap<BodyPart> = BodyPartMap(
VMC_MIRROR_BONE_PAIRS
.flatMap { (left, right) -> listOf(left to right, right to left) }
.toMap(),
)
fun vmcMirrorSource(bodyPart: BodyPart): BodyPart = VMC_MIRROR_BONES[bodyPart] ?: bodyPart
// Per-bone rest offset, subtracted from the live world rotation before computing the VMC local.
// Arms remap our hanging rest (NEG_Y) to the VRM rig's T-pose rest direction so the avatar isn't stuck at T regardless of our pose.
val VMC_REST_ROTATIONS: BodyPartMap<Quaternion> = run {
val leftArm = Quaternion.rotationAroundZAxis(-FastMath.HALF_PI)
val rightArm = Quaternion.rotationAroundZAxis(FastMath.HALF_PI)
BodyPartMap(
mapOf(
BodyPart.LEFT_UPPER_ARM to leftArm,
BodyPart.LEFT_LOWER_ARM to leftArm,
BodyPart.LEFT_HAND to leftArm,
BodyPart.RIGHT_UPPER_ARM to rightArm,
BodyPart.RIGHT_LOWER_ARM to rightArm,
BodyPart.RIGHT_HAND to rightArm,
) +
ResetBodyParts.LEFT_FINGERS.associateWith { leftArm } +
ResetBodyParts.RIGHT_FINGERS.associateWith { rightArm },
)
}
fun vmcMirrorPosition(pos: Vector3): Vector3 = Vector3(-pos.x, pos.y, pos.z)
fun vmcMirrorRotation(rot: Quaternion): Quaternion = Quaternion(rot.w, rot.x, -rot.y, -rot.z)
@@ -59,8 +59,8 @@ class VMCManager(val context: VMCContext) {
fun startObserving(appContext: AppContextProvider) {
val settings = appContext.config.settings
val behaviours = listOf(
VMCVrmBehaviour(settings),
VMCOutputBehaviour(appContext.skeleton, appContext.bones.current, settings, appContext.boneRouting),
VMCVrmBehaviour(appContext.skeleton, settings),
VMCOutputBehaviour(appContext.skeleton, settings, appContext.boneRouting),
VMCInputBehaviour(appContext, settings),
)
@@ -1,12 +1,12 @@
package dev.slimevr.vmc
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.boneId
import dev.slimevr.bones.BoneId
import dev.slimevr.config.VMCConfig
import dev.slimevr.osc.OscArg
import dev.slimevr.osc.OscBundle
import dev.slimevr.osc.OscContent
import dev.slimevr.osc.OscMessage
import dev.slimevr.resourcepacks.bones.CompiledSkeleton
import dev.slimevr.skeleton.BoneState
import dev.slimevr.skeleton.ComputedSkeleton
import io.github.axisangles.ktmath.Quaternion
@@ -14,8 +14,9 @@ import io.github.axisangles.ktmath.Vector3
import kotlin.time.Duration
internal fun buildOutgoingBundle(
definition: CompiledSkeleton,
bones: ComputedSkeleton,
routedBones: Set<BodyPart>,
routedBones: Set<BoneId>,
config: VMCConfig,
vrm: VrmGeometry?,
elapsed: Duration,
@@ -27,41 +28,39 @@ internal fun buildOutgoingBundle(
// Send the origin (0, 0, 0) as root
add(OscContent.Message(transformMessage("/VMC/Ext/Root/Pos", "root", Vector3.ZERO, Quaternion.IDENTITY)))
for ((targetBodyPart, unityNames) in BODY_PART_TO_UNITY_BONE) {
if (targetBodyPart !in routedBones) continue
for (targetBoneId in definition.vmcNamedBones) {
if (targetBoneId !in routedBones) continue
val output = definition.vmcOutputOf(targetBoneId) ?: continue
val targetParentBodyPart = VMC_OUTPUT_BONE_PARENTS[targetBodyPart]
val trackingBodyPart = if (config.mirrorTracking) vmcMirrorSource(targetBodyPart) else targetBodyPart
val trackingBone = bones[trackingBodyPart.boneId] ?: continue
val targetParentBoneId = output.outputParent
val trackingBoneId = if (config.mirrorTracking) definition.mirrorOf(targetBoneId) else targetBoneId
val trackingBone = bones[trackingBoneId] ?: continue
if (targetParentBodyPart == null) {
if (targetParentBoneId == null) {
// TODO anchorHip https://github.com/SlimeVR/SlimeVR-Server/blob/main/server/core/src/main/java/dev/slimevr/osc/VMCHandler.kt#L371
val pos = vrm?.hipLocalPosition ?: Vector3.ZERO
val rot = vmcLocalRotation(trackingBone, null, targetBodyPart, null, config.mirrorTracking)
add(OscContent.Message(transformMessage("/VMC/Ext/Bone/Pos", unityNames.first(), pos, rot)))
val rot = vmcLocalRotation(trackingBone, output.restRotation, null, Quaternion.IDENTITY, config.mirrorTracking)
add(OscContent.Message(transformMessage("/VMC/Ext/Bone/Pos", output.names.first(), pos, rot)))
continue
}
val trackingParentBodyPart = if (config.mirrorTracking) {
vmcMirrorSource(targetParentBodyPart)
} else {
targetParentBodyPart
}
val trackingParent = bones[trackingParentBodyPart.boneId] ?: continue
val targetParentRest = definition.vmcOutputOf(targetParentBoneId)?.restRotation ?: Quaternion.IDENTITY
val trackingParentBoneId = if (config.mirrorTracking) definition.mirrorOf(targetParentBoneId) else targetParentBoneId
val trackingParent = bones[trackingParentBoneId] ?: continue
val pos = if (vrm != null) {
vrm.bindOffsets[targetBodyPart] ?: Vector3.ZERO
vrm.bindOffsets[targetBoneId] ?: Vector3.ZERO
} else {
vmcLocalPosition(trackingBone, trackingParent, targetParentBodyPart, config.mirrorTracking)
vmcLocalPosition(trackingBone, trackingParent, targetParentRest, config.mirrorTracking)
}
val rot = vmcLocalRotation(
trackingBone,
output.restRotation,
trackingParent,
targetBodyPart,
targetParentBodyPart,
targetParentRest,
config.mirrorTracking,
)
for (outputName in unityNames) {
for (outputName in output.names) {
add(OscContent.Message(transformMessage("/VMC/Ext/Bone/Pos", outputName, pos, rot)))
}
}
@@ -74,33 +73,32 @@ internal fun buildInitRequestMessage(): OscMessage = OscMessage("/VMC/Ext/Req",
private fun restAdjustedWorld(
bone: BoneState,
restBodyPart: BodyPart,
rest: Quaternion,
mirror: Boolean = false,
): Quaternion {
val world = if (mirror) vmcMirrorRotation(bone.rotation) else bone.rotation
val rest = VMC_REST_ROTATIONS[restBodyPart] ?: return world
return world * rest.inv()
}
internal fun vmcLocalRotation(
bone: BoneState,
rest: Quaternion,
parent: BoneState?,
restBodyPart: BodyPart,
restParentBodyPart: BodyPart?,
parentRest: Quaternion,
mirror: Boolean,
): Quaternion {
val adjusted = restAdjustedWorld(bone, restBodyPart, mirror)
if (parent == null || restParentBodyPart == null) return adjusted
return restAdjustedWorld(parent, restParentBodyPart, mirror).inv() * adjusted
val adjusted = restAdjustedWorld(bone, rest, mirror)
if (parent == null) return adjusted
return restAdjustedWorld(parent, parentRest, mirror).inv() * adjusted
}
internal fun vmcLocalPosition(
bone: BoneState,
parent: BoneState,
restParentBodyPart: BodyPart,
parentRest: Quaternion,
mirror: Boolean,
): Vector3 {
val parentAdjusted = restAdjustedWorld(parent, restParentBodyPart, mirror)
val parentAdjusted = restAdjustedWorld(parent, parentRest, mirror)
val localPosition = bone.headPosition - parent.headPosition
return parentAdjusted.inv().sandwich(if (mirror) vmcMirrorPosition(localPosition) else localPosition)
}
@@ -118,3 +116,7 @@ private fun transformMessage(address: String, name: String, pos: Vector3, rot: Q
OscArg.Float(-rot.w),
),
)
internal fun vmcMirrorPosition(pos: Vector3): Vector3 = Vector3(-pos.x, pos.y, pos.z)
internal fun vmcMirrorRotation(rot: Quaternion): Quaternion = Quaternion(rot.w, rot.x, -rot.y, -rot.z)
@@ -1,7 +1,6 @@
package dev.slimevr.vmc
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.BoneRegistry
import dev.slimevr.bones.BoneId
import dev.slimevr.config.Settings
import dev.slimevr.config.VMCConfig
import dev.slimevr.logging.AppLogger
@@ -28,7 +27,6 @@ private val RECOVERY_CONFIRM_DELAY = 2.seconds
class VMCOutputBehaviour(
private val skeleton: Skeleton,
private val registry: BoneRegistry,
private val settings: Settings,
private val boneRouting: BoneRoutingManager,
) : VMCBehaviour {
@@ -62,7 +60,6 @@ class VMCOutputBehaviour(
val routedBones = boneRouting.context.state
.map { state -> state.routes.filterValues { RoutingOutput.VMC in it }.keys }
.distinctUntilChanged()
.map { boneIds -> boneIds.mapNotNullTo(mutableSetOf(), registry::bodyPartOf) }
val config = settings.context.state
.map { it.data.vmcConfig }
@@ -134,7 +131,7 @@ class VMCOutputBehaviour(
receiver: VMCManager,
runtime: OutputRuntime,
bones: ComputedSkeleton,
routedBones: Set<BodyPart>,
routedBones: Set<BoneId>,
config: VMCConfig,
startedAt: MonotonicValueTimeMark,
) {
@@ -142,7 +139,7 @@ class VMCOutputBehaviour(
val status = receiver.context.state.value.status
if (runtime.sendFailing && runtime.nextFrameRetryAt?.hasPassedNow() == false) return
val bundle = buildOutgoingBundle(bones, routedBones, config, receiver.context.state.value.vrm, startedAt.elapsedNow())
val bundle = buildOutgoingBundle(skeleton.definition, bones, routedBones, config, receiver.context.state.value.vrm, startedAt.elapsedNow())
try {
sender.send(bundle)
@@ -1,9 +1,13 @@
package dev.slimevr.vmc
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.BodyPartMap
import dev.slimevr.bones.BoneId
import dev.slimevr.bones.BoneMap
import dev.slimevr.bones.key
import dev.slimevr.config.Settings
import dev.slimevr.logging.AppLogger
import dev.slimevr.resourcepacks.bones.CompiledSkeleton
import dev.slimevr.skeleton.Skeleton
import dev.slimevr.util.formatExceptionMessage
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.flow.distinctUntilChanged
@@ -93,27 +97,35 @@ data class Node(
// VRM bind-pose geometry derived from a parsed VRM JSON. Used to keep the avatar's
// local bone offsets aligned with the model's own proportions.
data class VrmGeometry(
val bindOffsets: BodyPartMap<Vector3>,
val bindOffsets: BoneMap<Vector3>,
val hipLocalPosition: Vector3,
/** Floor-to-neck height, on the same basis as Skeleton.skeletonHeight. Used to scale VMC input positions. */
val vrmHeight: Float,
)
fun buildVrmGeometry(reader: VrmReader): VrmGeometry {
val bindOffsets = BodyPartMap(
BODY_PART_TO_UNITY_BONE.mapValues { (_, unityNames) -> reader.offsetForBone(unityNames.first()) ?: Vector3.ZERO },
)
fun offset(bodyPart: BodyPart) = bindOffsets[bodyPart] ?: Vector3.ZERO
fun buildVrmGeometry(definition: CompiledSkeleton, reader: VrmReader): VrmGeometry {
val registry = definition.registry
val bindOffsets = BoneMap.of<Vector3>(registry)
for (boneId in definition.vmcNamedBones) {
val name = definition.vmcOutputOf(boneId)?.names?.first() ?: continue
bindOffsets[boneId] = reader.offsetForBone(name) ?: Vector3.ZERO
}
val hipLocalPosition = offset(BodyPart.HIP)
val hip = registry[BodyPart.HIP.key]!!
val neck = registry[BodyPart.NECK.key]!!
val hipLocalPosition = bindOffsets[hip] ?: Vector3.ZERO
val vrmHeight = (
offset(BodyPart.HIP) +
offset(BodyPart.UPPER_WAIST) +
offset(BodyPart.LOWER_CHEST) +
offset(BodyPart.UPPER_CHEST) +
offset(BodyPart.NECK)
).y
// Floor-to-neck height, summed by walking the pack's own real parent chain from hip up to
// neck, rather than a fixed anatomy list, so it still works if a pack changes what's between
// them (e.g. no upper_waist, or an extra bone). Any bone on that chain missing a VRM offset
// (lower_waist has no VMC output at all) simply contributes 0.
var vrmHeight = 0f
var current: BoneId? = hip
while (current != null) {
vrmHeight += (bindOffsets[current] ?: Vector3.ZERO).y
if (current == neck) break
current = registry.parentOf(current)
}
return VrmGeometry(
bindOffsets = bindOffsets,
@@ -122,7 +134,7 @@ fun buildVrmGeometry(reader: VrmReader): VrmGeometry {
)
}
class VMCVrmBehaviour(private val settings: Settings) : VMCBehaviour {
class VMCVrmBehaviour(private val skeleton: Skeleton, private val settings: Settings) : VMCBehaviour {
override fun observe(receiver: VMCManager) {
settings.context.state
.map { it.data.vmcConfig.vrmJson }
@@ -135,7 +147,7 @@ class VMCVrmBehaviour(private val settings: Settings) : VMCBehaviour {
}
try {
val vrm = buildVrmGeometry(VrmReader(json))
val vrm = buildVrmGeometry(skeleton.definition, VrmReader(json))
receiver.context.dispatch(VMCActions.SetVrm(state = VMCOSCVrmState.LOADED, vrm = vrm))
} catch (e: Exception) {
val message = "Failed to parse VRM JSON"
@@ -181,13 +181,8 @@ class VRCOSCInputBehaviour(
receiver: VRCOSCManager,
portIn: Int,
) {
if (!message.address.startsWith("$TRACKING_VRSYSTEM_PATH/")) return
val tracker = when (message.address) {
"$TRACKING_VRSYSTEM_PATH/head/pose" -> VRSystemTracker.HEAD
"$TRACKING_VRSYSTEM_PATH/leftwrist/pose" -> VRSystemTracker.LEFT_WRIST
"$TRACKING_VRSYSTEM_PATH/rightwrist/pose" -> VRSystemTracker.RIGHT_WRIST
else -> return
}
val boneId = appContext.skeleton.definition.vrchatInputAddresses[message.address] ?: return
val tracker = trackerByBoneId[boneId] ?: return
val position = parsePosition(message.args) ?: return
val rotation = parseVrcEulerRotation(message.args, startIndex = 3) ?: return
@@ -207,3 +202,9 @@ class VRCOSCInputBehaviour(
)
}
}
private val trackerByBoneId = mapOf(
BodyPart.HEAD.boneId to VRSystemTracker.HEAD,
BodyPart.LEFT_HAND.boneId to VRSystemTracker.LEFT_WRIST,
BodyPart.RIGHT_HAND.boneId to VRSystemTracker.RIGHT_WRIST,
)
@@ -103,7 +103,7 @@ class VRCOSCManager(
fun startObserving(appContext: AppContextProvider) {
val settings = appContext.config.settings
val behaviours = listOf(
VRCOSCOutputBehaviour(appContext.skeleton, appContext.bones.current, settings, appContext.boneRouting),
VRCOSCOutputBehaviour(appContext.skeleton, settings, appContext.boneRouting),
VRCOSCInputBehaviour(appContext, settings),
VRCOSCOscQueryBehaviour(
settings,
@@ -1,61 +1,32 @@
package dev.slimevr.vrcosc
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.boneId
import dev.slimevr.bones.BoneId
import dev.slimevr.osc.OscArg
import dev.slimevr.osc.OscBundle
import dev.slimevr.osc.OscContent
import dev.slimevr.osc.OscMessage
import dev.slimevr.resourcepacks.bones.CompiledSkeleton
import dev.slimevr.resourcepacks.evaluateEmit
import dev.slimevr.skeleton.ComputedSkeleton
import io.github.axisangles.ktmath.EulerOrder
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import kotlin.math.PI
private val trackerIdsByBodyPart = mapOf(
BodyPart.HIP to 1,
BodyPart.LEFT_FOOT to 2,
BodyPart.RIGHT_FOOT to 3,
BodyPart.LEFT_UPPER_LEG to 4,
BodyPart.RIGHT_UPPER_LEG to 5,
BodyPart.UPPER_CHEST to 6,
BodyPart.LEFT_UPPER_ARM to 7,
BodyPart.RIGHT_UPPER_ARM to 8,
)
/** Bones VRChat OSC can accept. Used by the routing module. */
val VRC_OSC_SUPPORTED_BONES: Set<BodyPart> = trackerIdsByBodyPart.keys
internal fun buildOutgoingBundle(
definition: CompiledSkeleton,
bones: ComputedSkeleton,
routedBones: Set<BodyPart>,
routedBones: Set<BoneId>,
): OscBundle? {
val messages = buildList<OscContent> {
for ((bodyPart, trackerId) in trackerIdsByBodyPart) {
if (bodyPart !in routedBones) continue
val bone = bones[bodyPart.boneId] ?: continue
add(
OscContent.Message(
positionMessage("/tracking/trackers/$trackerId/position", bone.headPosition),
),
)
add(
OscContent.Message(
rotationMessage("/tracking/trackers/$trackerId/rotation", bone.rotation),
),
)
for (boneId in definition.vrchatEmittingBones) {
if (boneId !in routedBones) continue
val bone = bones[boneId] ?: continue
for ((address, entry) in definition.emitEntriesOf(boneId)) {
val relativeTo = entry.relativeTo?.let(bones::get)
if (entry.relativeTo != null && relativeTo == null) continue
add(OscContent.Message(OscMessage(address, evaluateEmit(entry, bone, relativeTo))))
}
}
bones[BodyPart.HEAD.boneId]?.let { head ->
add(
OscContent.Message(
positionMessage("/tracking/trackers/head/position", head.headPosition),
),
)
}
addAll(buildToeMessages(bones))
}
return messages.takeIf { it.isNotEmpty() }?.let { OscBundle(1L, it) }
@@ -72,25 +43,3 @@ internal fun buildYawAlignMessage(headRotation: Quaternion): OscMessage {
),
)
}
private fun positionMessage(address: String, position: Vector3) = OscMessage(
address,
listOf(
OscArg.Float(position.x),
OscArg.Float(position.y),
OscArg.Float(-position.z),
),
)
private fun rotationMessage(address: String, rotation: Quaternion): OscMessage {
val (_, x, y, z) = Quaternion(rotation.w, -rotation.x, -rotation.y, rotation.z)
.toEulerAngles(EulerOrder.YXZ)
return OscMessage(
address,
listOf(
OscArg.Float(x * 180f / PI.toFloat()),
OscArg.Float(y * 180f / PI.toFloat()),
OscArg.Float(z * 180f / PI.toFloat()),
),
)
}
@@ -1,13 +1,11 @@
package dev.slimevr.vrcosc
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.BoneRegistry
import dev.slimevr.bones.BoneId
import dev.slimevr.config.Settings
import dev.slimevr.config.VRCOSCConfig
import dev.slimevr.logging.AppLogger
import dev.slimevr.osc.OscSender
import dev.slimevr.routing.BoneRoutingManager
import dev.slimevr.skeleton.BoneState
import dev.slimevr.skeleton.ComputedSkeleton
import dev.slimevr.skeleton.Skeleton
import dev.slimevr.util.MonotonicValueTimeMark
@@ -23,7 +21,6 @@ import solarxr_protocol.rpc.RoutingOutput
import solarxr_protocol.rpc.VRCOSCOutputState
import solarxr_protocol.rpc.VRCOSCTargetSource
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TimeSource
private val FRAME_RETRY_DELAY = 2.seconds
@@ -34,7 +31,6 @@ private val RECOVERY_CONFIRM_DELAY = 2.seconds
class VRCOSCOutputBehaviour(
private val skeleton: Skeleton,
private val registry: BoneRegistry,
private val settings: Settings,
private val boneRouting: BoneRoutingManager,
) : VRCOSCBehaviour {
@@ -72,7 +68,6 @@ class VRCOSCOutputBehaviour(
val routedBones = boneRouting.context.state
.map { state -> state.routes.filterValues { RoutingOutput.VRC_OSC in it }.keys }
.distinctUntilChanged()
.map { boneIds -> boneIds.mapNotNullTo(mutableSetOf(), registry::bodyPartOf) }
combine(skeleton.computed, routedBones, ::Pair)
.onEach { (computedSkeleton, bones) -> sendFrame(receiver, runtime, computedSkeleton, bones) }
@@ -143,7 +138,7 @@ class VRCOSCOutputBehaviour(
receiver: VRCOSCManager,
runtime: OutputRuntime,
bones: ComputedSkeleton,
routedBones: Set<BodyPart>,
routedBones: Set<BoneId>,
) {
val sender = runtime.sender ?: return
val state = receiver.context.state.value
@@ -151,7 +146,7 @@ class VRCOSCOutputBehaviour(
if (runtime.sendFailing && runtime.nextFrameRetryAt?.hasPassedNow() == false) return
val bundle = buildOutgoingBundle(bones, routedBones) ?: return
val bundle = buildOutgoingBundle(skeleton.definition, bones, routedBones) ?: return
try {
sender.send(bundle)
@@ -1,113 +0,0 @@
package dev.slimevr.vrcosc
import dev.slimevr.bones.BodyPart
import dev.slimevr.bones.boneId
import dev.slimevr.osc.OscArg
import dev.slimevr.osc.OscContent
import dev.slimevr.osc.OscMessage
import dev.slimevr.skeleton.BoneState
import dev.slimevr.skeleton.ComputedSkeleton
import dev.slimevr.util.Side
import dev.slimevr.util.opposite
import io.github.axisangles.ktmath.EulerOrder
private const val ABSOLUTE_SPLAY_THRESHOLD_ANGLE = 7
private const val MINIMUM_TIP_TOE_PITCH = -14
private const val MINIMUM_BENDING_PITCH = 15
private const val MAXIMUM_ABSOLUTE_TOE_RANGE = 90
internal fun buildToeMessages(bones: ComputedSkeleton): List<OscContent> {
val messages = mutableListOf<OscContent>()
fun bone(bodyPart: BodyPart): BoneState? = bones[bodyPart.boneId]
// LEFT FOOT + TOES
val leftFoot = bone(BodyPart.LEFT_FOOT)
if (leftFoot != null) {
val leftToes = listOf(
bone(BodyPart.LEFT_BIG_TOE),
bone(BodyPart.LEFT_INDEX_TOE),
bone(BodyPart.LEFT_MIDDLE_TOE),
bone(BodyPart.LEFT_RING_TOE),
bone(BodyPart.LEFT_LITTLE_TOE),
)
processToesForFoot(leftFoot, leftToes, Side.LEFT, messages)
}
// RIGHT FOOT + TOES
val rightFoot = bone(BodyPart.RIGHT_FOOT)
if (rightFoot != null) {
val rightToes = listOf(
bone(BodyPart.RIGHT_BIG_TOE),
bone(BodyPart.RIGHT_INDEX_TOE),
bone(BodyPart.RIGHT_MIDDLE_TOE),
bone(BodyPart.RIGHT_RING_TOE),
bone(BodyPart.RIGHT_LITTLE_TOE),
)
processToesForFoot(rightFoot, rightToes, Side.RIGHT, messages)
}
return messages
}
private fun processToesForFoot(
foot: BoneState,
toeBones: List<BoneState?>,
side: Side,
messages: MutableList<OscContent>,
) {
var lastAssigned: BoneState? = null
for ((segmentIndex, toe) in toeBones.withIndex()) {
if (toe != null) {
lastAssigned = toe
}
if (lastAssigned == null) continue
val splayDirection = if (segmentIndex > 0) side else side.opposite
processToe(foot, lastAssigned, side, segmentIndex, splayDirection, messages)
}
}
private val Side.oscName: String
get() = when (this) {
Side.LEFT -> "Left"
Side.RIGHT -> "Right"
}
private fun processToe(
foot: BoneState,
toe: BoneState,
side: Side,
toeNumber: Int,
splayDirection: Side,
messages: MutableList<OscContent>,
) {
val oscToeNumber = toeNumber + 1
val footRot = foot.rotation
val toeRot = toe.rotation
val currentRelative = footRot.inv() * toeRot
val euler = currentRelative.toEulerAngles(EulerOrder.XYZ)
val pitch = Math.toDegrees(euler.x.toDouble()).toFloat()
val yaw = Math.toDegrees(euler.z.toDouble()).toFloat()
val tipToe = pitch < MINIMUM_TIP_TOE_PITCH
val bending = pitch > MINIMUM_BENDING_PITCH
val splayed = when (splayDirection) {
Side.LEFT -> yaw < -ABSOLUTE_SPLAY_THRESHOLD_ANGLE
Side.RIGHT -> yaw > ABSOLUTE_SPLAY_THRESHOLD_ANGLE
}
val toeCurlValue = (pitch / MAXIMUM_ABSOLUTE_TOE_RANGE).coerceIn(-1f, 1f)
val toeSplayValue = (yaw / MAXIMUM_ABSOLUTE_TOE_RANGE).coerceIn(-1f, 1f)
messages.addAll(
listOf(
OscContent.Message(OscMessage("/avatar/parameters/TipToes${side.oscName}", listOf(if (tipToe) OscArg.True else OscArg.False))),
OscContent.Message(OscMessage("/avatar/parameters/ToeBent${side.oscName}${oscToeNumber}Bool", listOf(if (bending) OscArg.True else OscArg.False))),
OscContent.Message(OscMessage("/avatar/parameters/ToeSplay${side.oscName}$oscToeNumber", listOf(if (splayed) OscArg.True else OscArg.False))),
OscContent.Message(OscMessage("/avatar/parameters/Toe${side.oscName}${oscToeNumber}Float", listOf(OscArg.Float(toeCurlValue)))),
OscContent.Message(OscMessage("/avatar/parameters/ToeSplay${side.oscName}${oscToeNumber}Float", listOf(OscArg.Float(toeSplayValue)))),
),
)
}
@@ -0,0 +1,102 @@
{
"$schema": "../../schemas/v1/language.schema.json",
"slimevr:pack.core.name": "SlimeVR Core Skeleton",
"slimevr:pack.core.description": "The built-in humanoid skeleton resources.",
"slimevr:bone.head": "Head",
"slimevr:bone.neck": "Neck",
"slimevr:bone.upper_chest": "Upper chest",
"slimevr:bone.lower_chest": "Lower chest",
"slimevr:bone.upper_waist": "Upper waist",
"slimevr:bone.lower_waist": "Lower waist",
"slimevr:bone.hip": "Hip",
"slimevr:bone.left_upper_leg": "Left thigh",
"slimevr:bone.right_upper_leg": "Right thigh",
"slimevr:bone.left_lower_leg": "Left ankle",
"slimevr:bone.right_lower_leg": "Right ankle",
"slimevr:bone.left_foot": "Left foot",
"slimevr:bone.right_foot": "Right foot",
"slimevr:bone.left_upper_arm": "Left upper arm",
"slimevr:bone.right_upper_arm": "Right upper arm",
"slimevr:bone.left_lower_arm": "Left lower arm",
"slimevr:bone.right_lower_arm": "Right lower arm",
"slimevr:bone.left_hand": "Left hand",
"slimevr:bone.right_hand": "Right hand",
"slimevr:bone.left_shoulder": "Left shoulder",
"slimevr:bone.right_shoulder": "Right shoulder",
"slimevr:bone.left_thumb_metacarpal": "Left thumb metacarpal",
"slimevr:bone.left_thumb_proximal": "Left thumb proximal",
"slimevr:bone.left_thumb_distal": "Left thumb distal",
"slimevr:bone.left_index_proximal": "Left index proximal",
"slimevr:bone.left_index_intermediate": "Left index intermediate",
"slimevr:bone.left_index_distal": "Left index distal",
"slimevr:bone.left_middle_proximal": "Left middle proximal",
"slimevr:bone.left_middle_intermediate": "Left middle intermediate",
"slimevr:bone.left_middle_distal": "Left middle distal",
"slimevr:bone.left_ring_proximal": "Left ring proximal",
"slimevr:bone.left_ring_intermediate": "Left ring intermediate",
"slimevr:bone.left_ring_distal": "Left ring distal",
"slimevr:bone.left_little_proximal": "Left little proximal",
"slimevr:bone.left_little_intermediate": "Left little intermediate",
"slimevr:bone.left_little_distal": "Left little distal",
"slimevr:bone.right_thumb_metacarpal": "Right thumb metacarpal",
"slimevr:bone.right_thumb_proximal": "Right thumb proximal",
"slimevr:bone.right_thumb_distal": "Right thumb distal",
"slimevr:bone.right_index_proximal": "Right index proximal",
"slimevr:bone.right_index_intermediate": "Right index intermediate",
"slimevr:bone.right_index_distal": "Right index distal",
"slimevr:bone.right_middle_proximal": "Right middle proximal",
"slimevr:bone.right_middle_intermediate": "Right middle intermediate",
"slimevr:bone.right_middle_distal": "Right middle distal",
"slimevr:bone.right_ring_proximal": "Right ring proximal",
"slimevr:bone.right_ring_intermediate": "Right ring intermediate",
"slimevr:bone.right_ring_distal": "Right ring distal",
"slimevr:bone.right_little_proximal": "Right little proximal",
"slimevr:bone.right_little_intermediate": "Right little intermediate",
"slimevr:bone.right_little_distal": "Right little distal",
"slimevr:bone.left_big_toe": "Left Big Toe",
"slimevr:bone.left_index_toe": "Left Index Toe",
"slimevr:bone.left_middle_toe": "Left Middle Toe",
"slimevr:bone.left_ring_toe": "Left Ring Toe",
"slimevr:bone.left_little_toe": "Left Little Toe",
"slimevr:bone.right_big_toe": "Right Big Toe",
"slimevr:bone.right_index_toe": "Right Index Toe",
"slimevr:bone.right_middle_toe": "Right Middle Toe",
"slimevr:bone.right_ring_toe": "Right Ring Toe",
"slimevr:bone.right_little_toe": "Right Little Toe",
"slimevr:proportion.head": "Head Shift",
"slimevr:proportion.head.description": "This is the distance from your headset to the middle of your head. To adjust it, shake your head left to right as if you're disagreeing and modify it until any movement in other trackers is negligible.",
"slimevr:proportion.neck": "Neck Length",
"slimevr:proportion.neck.description": "This is the distance from the middle of your head to the base of your neck. To adjust it, move your head up and down as if you're nodding or tilt your head to the left and right and modify it until any movement in other trackers is negligible.",
"slimevr:proportion.upper_chest": "Upper Chest Length",
"slimevr:proportion.upper_chest.description": "This is the distance from the base of your neck to the middle of your chest. To adjust it, adjust your Torso Length properly and modify it in various positions (sitting down, bending over, lying down, etc.) until your virtual spine matches with your real one.",
"slimevr:proportion.lower_chest": "Lower Chest Length",
"slimevr:proportion.lower_chest.description": "This is the distance from the middle of your chest to the middle of your spine. To adjust it, adjust your Torso Length properly and modify it in various positions (sitting down, bending over, lying down, etc.) until your virtual spine matches with your real one.",
"slimevr:proportion.upper_waist": "Upper Waist Length",
"slimevr:proportion.upper_waist.description": "This is the distance from the middle of your spine to a bit above your belly button. To adjust it, adjust your Torso Length properly and modify it in various positions (sitting down, bending over, lying down, etc.) until your virtual spine matches with your real one.",
"slimevr:proportion.lower_waist": "Lower Waist Length",
"slimevr:proportion.lower_waist.description": "This is the distance from a bit above your belly button to a bit below it. To adjust it, adjust your Torso Length properly and modify it in various positions (sitting down, bending over, lying down, etc.) until your virtual spine matches with your real one.",
"slimevr:proportion.hip": "Hip Length",
"slimevr:proportion.hip.description": "This is the distance from a bit bellow your belly button to your hips. To adjust it, set your Torso Length properly and modify it in various positions (sitting down, bending over, lying down, etc.) until your virtual spine matches your real one.",
"slimevr:proportion.hips_width": "Hips Width",
"slimevr:proportion.hips_width.description": "This is the distance between the start of your legs. To adjust it, perform a full reset with your legs straight and modify it until your virtual legs match up with your real ones horizontally.",
"slimevr:proportion.upper_leg": "Upper Leg Length",
"slimevr:proportion.upper_leg.description": "This is the distance from your hips to your knees. To adjust it, adjust your Leg Length properly and modify it until your virtual knees are at the same level as your real ones.",
"slimevr:proportion.lower_leg": "Lower Leg Length",
"slimevr:proportion.lower_leg.description": "This is the distance from your knees to your ankles. To adjust it, adjust your Leg Length properly and modify it until your virtual knees are at the same level as your real ones.",
"slimevr:proportion.foot_length": "Foot Length",
"slimevr:proportion.foot_length.description": "This is the distance from your ankles to your toes. To adjust it, tiptoe and modify it until your virtual feet stay in place.",
"slimevr:proportion.foot_shift": "Foot Shift",
"slimevr:proportion.foot_shift.description": "This value is the horizontal distance from your knee to your ankle. It accounts for your lower legs going backwards when standing up straight. To adjust it, set Foot Length to 0, perform a full reset and modify it until your virtual feet line up with the middle of your ankles.",
"slimevr:proportion.shoulders_distance": "Shoulders Distance",
"slimevr:proportion.shoulders_distance.description": "This is the vertical distance from the base of your neck to your shoulders. To adjust it, set Upper Arm Length to 0 and modify it until your virtual elbow trackers line up vertically with your real shoulders.",
"slimevr:proportion.shoulders_width": "Shoulders Width",
"slimevr:proportion.shoulders_width.description": "This is the horizontal distance from the base of your neck to your shoulders. To adjust it, set Upper Arm Length to 0 and modify it until your virtual elbow trackers line up horizontally with your real shoulders.",
"slimevr:proportion.upper_arm": "Upper Arm Length",
"slimevr:proportion.upper_arm.description": "This is the distance from your shoulders to your elbows. To adjust it, adjust Arm Length properly and modify it until your elbow trackers line up with your real elbows.",
"slimevr:proportion.lower_arm": "Lower Arm Length",
"slimevr:proportion.lower_arm.description": "This is the distance from your elbows to your wrists. To adjust it, adjust Arm Length properly and modify it until your elbow trackers line up with your real elbows.",
"slimevr:proportion.hand_y": "Hand Distance Y",
"slimevr:proportion.hand_y.description": "This is the vertical distance from your wrists to the middle of your hand. To adjust it for motion capture, adjust Arm Length properly and modify it until your hand trackers line up vertically with the middle of your hands. To adjust it for elbow tracking from your controllers, set Arm Length to 0 and modify it until your elbow trackers line up vertically with your wrists.",
"slimevr:proportion.hand_z": "Hand Distance Z",
"slimevr:proportion.hand_z.description": "This is the horizontal distance from your wrists to the middle of your hand. To adjust it for motion capture, set it to 0. To adjust it for elbow tracking from your controllers, set Arm Length to 0 and modify it until your elbow trackers line up horizontally with your wrists."
}
@@ -0,0 +1,17 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:head",
"nameKey": "slimevr:bone.head",
"tailOffset": {"terms": [{"proportion": "slimevr:head", "direction": {"x": 0, "y": 0, "z": 1}}]},
"rotationFallback": {"type": "copy", "source": "slimevr:neck"},
"outputs": {
"vmc": {"name": "Head"},
"vrchat": {
"required": true,
"emit": {
"/tracking/trackers/head/position": {"from": "position", "value": [{"scale": {"z": -1}}]}
}
}
},
"inputs": {"vrchat": {"address": "/tracking/vrsystem/head/pose"}}
}
@@ -0,0 +1,36 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:hip",
"nameKey": "slimevr:bone.hip",
"batterySources": [
"slimevr:hip",
"slimevr:lower_waist",
"slimevr:upper_waist",
"slimevr:lower_chest",
"slimevr:upper_chest"
],
"candidateSources": [
"slimevr:hip",
"slimevr:lower_waist",
"slimevr:upper_waist",
"slimevr:lower_chest",
"slimevr:upper_chest"
],
"parent": "slimevr:lower_waist",
"tailOffset": {"terms": [{"proportion": "slimevr:hip", "direction": {"x": 0, "y": -1, "z": 0}}]},
"rotationFallback": {"type": "none"},
"constraint": {"type": "twistSwing", "twistDegrees": 60, "swingDegrees": 120},
"outputs": {
"driver": {"supported": true},
"vmc": {"name": "Hips"},
"vrchat": {
"emit": {
"/tracking/trackers/1/position": {"from": "position", "value": [{"scale": {"z": -1}}]},
"/tracking/trackers/1/rotation": {
"from": "rotation",
"value": [{"scale": {"x": -1, "y": -1}}, {"euler": {"order": "YXZ"}}]
}
}
}
}
}
@@ -0,0 +1,51 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_big_toe",
"nameKey": "slimevr:bone.left_big_toe",
"mirror": "slimevr:right_big_toe",
"candidateSources": ["slimevr:left_big_toe"],
"parent": "slimevr:left_foot",
"headOffset": {
"terms": [{"proportion": "slimevr:foot_length", "direction": {"x": 0.28, "y": 0, "z": 0}}]
},
"tailOffset": {
"terms": [{"proportion": "slimevr:foot_length", "direction": {"x": 0, "y": 0, "z": -0.27}}]
},
"rotationFallback": {
"type": "firstActive",
"sources": [
"slimevr:left_index_toe",
"slimevr:left_middle_toe",
"slimevr:left_ring_toe",
"slimevr:left_little_toe",
"slimevr:left_foot"
]
},
"outputs": {
"vmc": {"name": ["LeftToes", "LeftBigToe"]},
"vrchat": {
"emit": {
"/avatar/parameters/ToeBentLeft1Bool": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "x"}, {"greaterThan": 15}]
},
"/avatar/parameters/ToeSplayLeft1": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "z"}, {"greaterThan": 7}]
},
"/avatar/parameters/ToeLeft1Float": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "x"}, {"divide": 90}, {"clamp": [-1, 1]}]
},
"/avatar/parameters/ToeSplayLeft1Float": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "z"}, {"divide": 90}, {"clamp": [-1, 1]}]
}
}
}
}
}
@@ -0,0 +1,33 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_foot",
"nameKey": "slimevr:bone.left_foot",
"mirror": "slimevr:right_foot",
"batterySources": ["slimevr:left_foot", "slimevr:left_lower_leg"],
"candidateSources": ["slimevr:left_foot", "slimevr:left_lower_leg", "slimevr:left_upper_leg"],
"parent": "slimevr:left_lower_leg",
"tailOffset": {
"terms": [{"proportion": "slimevr:foot_length", "direction": {"x": 0, "y": 0, "z": -1}}]
},
"rotationFallback": {"type": "copy", "source": "slimevr:left_lower_leg"},
"constraint": {
"type": "looseHinge",
"minDegrees": -60,
"maxDegrees": 90,
"allowedDeviationDegrees": 60,
"axis": {"x": -1, "y": 0, "z": 0}
},
"outputs": {
"driver": {"supported": true},
"vmc": {"name": "LeftFoot"},
"vrchat": {
"emit": {
"/tracking/trackers/2/position": {"from": "position", "value": [{"scale": {"z": -1}}]},
"/tracking/trackers/2/rotation": {
"from": "rotation",
"value": [{"scale": {"x": -1, "y": -1}}, {"euler": {"order": "YXZ"}}]
}
}
}
}
}
@@ -0,0 +1,25 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_hand",
"nameKey": "slimevr:bone.left_hand",
"mirror": "slimevr:right_hand",
"batterySources": ["slimevr:left_hand", "slimevr:left_lower_arm"],
"overridable": true,
"parent": "slimevr:left_lower_arm",
"tailOffset": {
"terms": [
{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -1, "z": 0}},
{"proportion": "slimevr:hand_z", "direction": {"x": 0, "y": 0, "z": -1}}
]
},
"rotationFallback": {"type": "copy", "source": "slimevr:left_lower_arm"},
"constraint": {"type": "twistSwing", "twistDegrees": 120, "swingDegrees": 120},
"outputs": {
"driver": {"supported": true},
"vmc": {
"name": "LeftHand",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
},
"inputs": {"vrchat": {"address": "/tracking/vrsystem/leftwrist/pose"}}
}
@@ -0,0 +1,17 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_index_distal",
"nameKey": "slimevr:bone.left_index_distal",
"mirror": "slimevr:right_index_distal",
"parent": "slimevr:left_index_intermediate",
"tailOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -0.174685, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "LeftIndexDistal",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
}
}
@@ -0,0 +1,17 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_index_intermediate",
"nameKey": "slimevr:bone.left_index_intermediate",
"mirror": "slimevr:right_index_intermediate",
"parent": "slimevr:left_index_proximal",
"tailOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -0.227815, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "LeftIndexIntermediate",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
}
}
@@ -0,0 +1,20 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_index_proximal",
"nameKey": "slimevr:bone.left_index_proximal",
"mirror": "slimevr:right_index_proximal",
"parent": "slimevr:left_hand",
"headOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0.03, "y": 0.05, "z": -0.34}}]
},
"tailOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -0.4025, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "LeftIndexProximal",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
}
}
@@ -0,0 +1,51 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_index_toe",
"nameKey": "slimevr:bone.left_index_toe",
"mirror": "slimevr:right_index_toe",
"candidateSources": ["slimevr:left_index_toe"],
"parent": "slimevr:left_foot",
"headOffset": {
"terms": [{"proportion": "slimevr:foot_length", "direction": {"x": 0.12, "y": 0, "z": 0}}]
},
"tailOffset": {
"terms": [{"proportion": "slimevr:foot_length", "direction": {"x": 0, "y": 0, "z": -0.24}}]
},
"rotationFallback": {
"type": "firstActive",
"sources": [
"slimevr:left_middle_toe",
"slimevr:left_ring_toe",
"slimevr:left_little_toe",
"slimevr:left_big_toe",
"slimevr:left_foot"
]
},
"outputs": {
"vmc": {"name": "LeftIndexToe"},
"vrchat": {
"emit": {
"/avatar/parameters/ToeBentLeft2Bool": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "x"}, {"greaterThan": 15}]
},
"/avatar/parameters/ToeSplayLeft2": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "z"}, {"lessThan": -7}]
},
"/avatar/parameters/ToeLeft2Float": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "x"}, {"divide": 90}, {"clamp": [-1, 1]}]
},
"/avatar/parameters/ToeSplayLeft2Float": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "z"}, {"divide": 90}, {"clamp": [-1, 1]}]
}
}
}
}
}
@@ -0,0 +1,17 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_little_distal",
"nameKey": "slimevr:bone.left_little_distal",
"mirror": "slimevr:right_little_distal",
"parent": "slimevr:left_little_intermediate",
"tailOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -0.14973, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "LeftLittleDistal",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
}
}
@@ -0,0 +1,17 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_little_intermediate",
"nameKey": "slimevr:bone.left_little_intermediate",
"mirror": "slimevr:right_little_intermediate",
"parent": "slimevr:left_little_proximal",
"tailOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -0.19527, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "LeftLittleIntermediate",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
}
}
@@ -0,0 +1,20 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_little_proximal",
"nameKey": "slimevr:bone.left_little_proximal",
"mirror": "slimevr:right_little_proximal",
"parent": "slimevr:left_hand",
"headOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": 0.1, "z": 0.31}}]
},
"tailOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -0.345, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "LeftLittleProximal",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
}
}
@@ -0,0 +1,56 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_little_toe",
"nameKey": "slimevr:bone.left_little_toe",
"mirror": "slimevr:right_little_toe",
"candidateSources": ["slimevr:left_little_toe"],
"parent": "slimevr:left_foot",
"headOffset": {
"terms": [{"proportion": "slimevr:foot_length", "direction": {"x": -0.26, "y": 0, "z": 0}}]
},
"tailOffset": {
"terms": [{"proportion": "slimevr:foot_length", "direction": {"x": 0, "y": 0, "z": -0.18}}]
},
"rotationFallback": {
"type": "firstActive",
"sources": [
"slimevr:left_ring_toe",
"slimevr:left_middle_toe",
"slimevr:left_index_toe",
"slimevr:left_big_toe",
"slimevr:left_foot"
]
},
"outputs": {
"vmc": {"name": "LeftLittleToe"},
"vrchat": {
"emit": {
"/avatar/parameters/ToeBentLeft5Bool": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "x"}, {"greaterThan": 15}]
},
"/avatar/parameters/ToeSplayLeft5": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "z"}, {"lessThan": -7}]
},
"/avatar/parameters/ToeLeft5Float": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "x"}, {"divide": 90}, {"clamp": [-1, 1]}]
},
"/avatar/parameters/ToeSplayLeft5Float": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "z"}, {"divide": 90}, {"clamp": [-1, 1]}]
},
"/avatar/parameters/TipToesLeft": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "x"}, {"lessThan": -14}]
}
}
}
}
}
@@ -0,0 +1,24 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_lower_arm",
"nameKey": "slimevr:bone.left_lower_arm",
"mirror": "slimevr:right_lower_arm",
"parent": "slimevr:left_upper_arm",
"tailOffset": {
"terms": [{"proportion": "slimevr:lower_arm", "direction": {"x": 0, "y": -1, "z": 0}}]
},
"rotationFallback": {"type": "copy", "source": "slimevr:left_upper_arm"},
"constraint": {
"type": "looseHinge",
"minDegrees": -180,
"maxDegrees": 0,
"allowedDeviationDegrees": 40,
"axis": {"x": -1, "y": 0, "z": 0}
},
"outputs": {
"vmc": {
"name": "LeftLowerArm",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
}
}
@@ -0,0 +1,22 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_lower_leg",
"nameKey": "slimevr:bone.left_lower_leg",
"mirror": "slimevr:right_lower_leg",
"parent": "slimevr:left_upper_leg",
"tailOffset": {
"terms": [
{"proportion": "slimevr:lower_leg", "direction": {"x": 0, "y": -1, "z": 0}},
{"proportion": "slimevr:foot_shift", "direction": {"x": 0, "y": 0, "z": -1}}
]
},
"rotationFallback": {"type": "none"},
"constraint": {
"type": "looseHinge",
"minDegrees": -5,
"maxDegrees": 180,
"allowedDeviationDegrees": 10,
"axis": {"x": -1, "y": 0, "z": 0}
},
"outputs": {"vmc": {"name": "LeftLowerLeg"}}
}
@@ -0,0 +1,17 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_middle_distal",
"nameKey": "slimevr:bone.left_middle_distal",
"mirror": "slimevr:right_middle_distal",
"parent": "slimevr:left_middle_intermediate",
"tailOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -0.19964, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "LeftMiddleDistal",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
}
}
@@ -0,0 +1,17 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_middle_intermediate",
"nameKey": "slimevr:bone.left_middle_intermediate",
"mirror": "slimevr:right_middle_intermediate",
"parent": "slimevr:left_middle_proximal",
"tailOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -0.26036, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "LeftMiddleIntermediate",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
}
}
@@ -0,0 +1,20 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_middle_proximal",
"nameKey": "slimevr:bone.left_middle_proximal",
"mirror": "slimevr:right_middle_proximal",
"parent": "slimevr:left_hand",
"headOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0.04, "y": 0, "z": -0.11}}]
},
"tailOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -0.46, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "LeftMiddleProximal",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
}
}
@@ -0,0 +1,51 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_middle_toe",
"nameKey": "slimevr:bone.left_middle_toe",
"mirror": "slimevr:right_middle_toe",
"candidateSources": ["slimevr:left_middle_toe"],
"parent": "slimevr:left_foot",
"headOffset": {
"terms": [{"proportion": "slimevr:foot_length", "direction": {"x": 0, "y": 0, "z": 0}}]
},
"tailOffset": {
"terms": [{"proportion": "slimevr:foot_length", "direction": {"x": 0, "y": 0, "z": -0.23}}]
},
"rotationFallback": {
"type": "firstActive",
"sources": [
"slimevr:left_index_toe",
"slimevr:left_ring_toe",
"slimevr:left_little_toe",
"slimevr:left_big_toe",
"slimevr:left_foot"
]
},
"outputs": {
"vmc": {"name": "LeftMiddleToe"},
"vrchat": {
"emit": {
"/avatar/parameters/ToeBentLeft3Bool": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "x"}, {"greaterThan": 15}]
},
"/avatar/parameters/ToeSplayLeft3": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "z"}, {"lessThan": -7}]
},
"/avatar/parameters/ToeLeft3Float": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "x"}, {"divide": 90}, {"clamp": [-1, 1]}]
},
"/avatar/parameters/ToeSplayLeft3Float": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "z"}, {"divide": 90}, {"clamp": [-1, 1]}]
}
}
}
}
}
@@ -0,0 +1,17 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_ring_distal",
"nameKey": "slimevr:bone.left_ring_distal",
"mirror": "slimevr:right_ring_distal",
"parent": "slimevr:left_ring_intermediate",
"tailOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -0.174685, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "LeftRingDistal",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
}
}
@@ -0,0 +1,17 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_ring_intermediate",
"nameKey": "slimevr:bone.left_ring_intermediate",
"mirror": "slimevr:right_ring_intermediate",
"parent": "slimevr:left_ring_proximal",
"tailOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -0.227815, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "LeftRingIntermediate",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
}
}
@@ -0,0 +1,20 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_ring_proximal",
"nameKey": "slimevr:bone.left_ring_proximal",
"mirror": "slimevr:right_ring_proximal",
"parent": "slimevr:left_hand",
"headOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0.03, "y": 0.03, "z": 0.11}}]
},
"tailOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -0.4025, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "LeftRingProximal",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
}
}
@@ -0,0 +1,51 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_ring_toe",
"nameKey": "slimevr:bone.left_ring_toe",
"mirror": "slimevr:right_ring_toe",
"candidateSources": ["slimevr:left_ring_toe"],
"parent": "slimevr:left_foot",
"headOffset": {
"terms": [{"proportion": "slimevr:foot_length", "direction": {"x": -0.12, "y": 0, "z": 0}}]
},
"tailOffset": {
"terms": [{"proportion": "slimevr:foot_length", "direction": {"x": 0, "y": 0, "z": -0.21}}]
},
"rotationFallback": {
"type": "firstActive",
"sources": [
"slimevr:left_middle_toe",
"slimevr:left_index_toe",
"slimevr:left_little_toe",
"slimevr:left_big_toe",
"slimevr:left_foot"
]
},
"outputs": {
"vmc": {"name": "LeftRingToe"},
"vrchat": {
"emit": {
"/avatar/parameters/ToeBentLeft4Bool": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "x"}, {"greaterThan": 15}]
},
"/avatar/parameters/ToeSplayLeft4": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "z"}, {"lessThan": -7}]
},
"/avatar/parameters/ToeLeft4Float": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "x"}, {"divide": 90}, {"clamp": [-1, 1]}]
},
"/avatar/parameters/ToeSplayLeft4Float": {
"from": "rotation",
"relativeTo": "slimevr:left_foot",
"value": [{"euler": "z"}, {"divide": 90}, {"clamp": [-1, 1]}]
}
}
}
}
}
@@ -0,0 +1,23 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_shoulder",
"nameKey": "slimevr:bone.left_shoulder",
"mirror": "slimevr:right_shoulder",
"parent": "slimevr:neck",
"tailOffset": {
"terms": [
{"proportion": "slimevr:shoulders_distance", "direction": {"x": 0, "y": -1, "z": 0}},
{"proportion": "slimevr:shoulders_width", "direction": {"x": -0.5, "y": 0, "z": 0}}
]
},
"rotationFallback": {"type": "copy", "source": "slimevr:upper_chest"},
"constraint": {"type": "twistSwing", "twistDegrees": 0, "swingDegrees": 30},
"outputs": {
"driver": {"supported": true},
"vmc": {
"name": "LeftShoulder",
"outputParent": "slimevr:lower_chest",
"inputParent": "slimevr:upper_chest"
}
}
}
@@ -0,0 +1,22 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_thumb_distal",
"nameKey": "slimevr:bone.left_thumb_distal",
"mirror": "slimevr:right_thumb_distal",
"parent": "slimevr:left_thumb_proximal",
"tailOffset": {
"terms": [
{
"proportion": "slimevr:hand_y",
"direction": {"x": 0.00639448, "y": -0.12788955, "z": -0.08952269}
}
]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "LeftThumbDistal",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
}
}
@@ -0,0 +1,25 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_thumb_metacarpal",
"nameKey": "slimevr:bone.left_thumb_metacarpal",
"mirror": "slimevr:right_thumb_metacarpal",
"parent": "slimevr:left_hand",
"headOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0.16, "y": 0.3, "z": -0.28}}]
},
"tailOffset": {
"terms": [
{
"proportion": "slimevr:hand_y",
"direction": {"x": 0.01473382, "y": -0.29467638, "z": -0.20627347}
}
]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "LeftThumbProximal",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
}
}
@@ -0,0 +1,22 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_thumb_proximal",
"nameKey": "slimevr:bone.left_thumb_proximal",
"mirror": "slimevr:right_thumb_proximal",
"parent": "slimevr:left_thumb_metacarpal",
"tailOffset": {
"terms": [
{
"proportion": "slimevr:hand_y",
"direction": {"x": 0.00833934, "y": -0.16678683, "z": -0.11675078}
}
]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "LeftThumbIntermediate",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
}
}
}
@@ -0,0 +1,30 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_upper_arm",
"nameKey": "slimevr:bone.left_upper_arm",
"mirror": "slimevr:right_upper_arm",
"batterySources": ["slimevr:left_upper_arm", "slimevr:left_lower_arm"],
"candidateSources": ["slimevr:left_upper_arm", "slimevr:left_lower_arm"],
"parent": "slimevr:left_shoulder",
"tailOffset": {
"terms": [{"proportion": "slimevr:upper_arm", "direction": {"x": 0, "y": -1, "z": 0}}]
},
"rotationFallback": {"type": "copy", "source": "slimevr:left_shoulder"},
"constraint": {"type": "twistSwing", "twistDegrees": 120, "swingDegrees": 180},
"outputs": {
"driver": {"supported": true},
"vmc": {
"name": "LeftUpperArm",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": -90}]
},
"vrchat": {
"emit": {
"/tracking/trackers/7/position": {"from": "position", "value": [{"scale": {"z": -1}}]},
"/tracking/trackers/7/rotation": {
"from": "rotation",
"value": [{"scale": {"x": -1, "y": -1}}, {"euler": {"order": "YXZ"}}]
}
}
}
}
}
@@ -0,0 +1,30 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:left_upper_leg",
"nameKey": "slimevr:bone.left_upper_leg",
"mirror": "slimevr:right_upper_leg",
"batterySources": ["slimevr:left_upper_leg"],
"candidateSources": ["slimevr:left_upper_leg"],
"parent": "slimevr:hip",
"headOffset": {
"terms": [{"proportion": "slimevr:hips_width", "direction": {"x": -0.5, "y": 0, "z": 0}}]
},
"tailOffset": {
"terms": [{"proportion": "slimevr:upper_leg", "direction": {"x": 0, "y": -1, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"constraint": {"type": "twistSwing", "twistDegrees": 120, "swingDegrees": 170},
"outputs": {
"driver": {"supported": true},
"vmc": {"name": "LeftUpperLeg"},
"vrchat": {
"emit": {
"/tracking/trackers/4/position": {"from": "position", "value": [{"scale": {"z": -1}}]},
"/tracking/trackers/4/rotation": {
"from": "rotation",
"value": [{"scale": {"x": -1, "y": -1}}, {"euler": {"order": "YXZ"}}]
}
}
}
}
}
@@ -0,0 +1,12 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:lower_chest",
"nameKey": "slimevr:bone.lower_chest",
"parent": "slimevr:upper_chest",
"tailOffset": {
"terms": [{"proportion": "slimevr:lower_chest", "direction": {"x": 0, "y": -1, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"constraint": {"type": "twistSwing", "twistDegrees": 60, "swingDegrees": 120},
"outputs": {"vmc": {"name": "Chest"}}
}
@@ -0,0 +1,11 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:lower_waist",
"nameKey": "slimevr:bone.lower_waist",
"parent": "slimevr:upper_waist",
"tailOffset": {
"terms": [{"proportion": "slimevr:lower_waist", "direction": {"x": 0, "y": -1, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"constraint": {"type": "twistSwing", "twistDegrees": 60, "swingDegrees": 120}
}
@@ -0,0 +1,15 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:neck",
"nameKey": "slimevr:bone.neck",
"parent": "slimevr:head",
"tailOffset": {"terms": [{"proportion": "slimevr:neck", "direction": {"x": 0, "y": -1, "z": 0}}]},
"rotationFallback": {"type": "copy", "source": "slimevr:head"},
"outputs": {
"vmc": {
"name": "Neck",
"outputParent": "slimevr:lower_chest",
"inputParent": "slimevr:upper_chest"
}
}
}
@@ -0,0 +1,51 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:right_big_toe",
"nameKey": "slimevr:bone.right_big_toe",
"mirror": "slimevr:left_big_toe",
"candidateSources": ["slimevr:right_big_toe"],
"parent": "slimevr:right_foot",
"headOffset": {
"terms": [{"proportion": "slimevr:foot_length", "direction": {"x": -0.28, "y": 0, "z": 0}}]
},
"tailOffset": {
"terms": [{"proportion": "slimevr:foot_length", "direction": {"x": 0, "y": 0, "z": -0.27}}]
},
"rotationFallback": {
"type": "firstActive",
"sources": [
"slimevr:right_index_toe",
"slimevr:right_middle_toe",
"slimevr:right_ring_toe",
"slimevr:right_little_toe",
"slimevr:right_foot"
]
},
"outputs": {
"vmc": {"name": ["RightToes", "RightBigToe"]},
"vrchat": {
"emit": {
"/avatar/parameters/ToeBentRight1Bool": {
"from": "rotation",
"relativeTo": "slimevr:right_foot",
"value": [{"euler": "x"}, {"greaterThan": 15}]
},
"/avatar/parameters/ToeSplayRight1": {
"from": "rotation",
"relativeTo": "slimevr:right_foot",
"value": [{"euler": "z"}, {"lessThan": -7}]
},
"/avatar/parameters/ToeRight1Float": {
"from": "rotation",
"relativeTo": "slimevr:right_foot",
"value": [{"euler": "x"}, {"divide": 90}, {"clamp": [-1, 1]}]
},
"/avatar/parameters/ToeSplayRight1Float": {
"from": "rotation",
"relativeTo": "slimevr:right_foot",
"value": [{"euler": "z"}, {"divide": 90}, {"clamp": [-1, 1]}]
}
}
}
}
}
@@ -0,0 +1,33 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:right_foot",
"nameKey": "slimevr:bone.right_foot",
"mirror": "slimevr:left_foot",
"batterySources": ["slimevr:right_foot", "slimevr:right_lower_leg"],
"candidateSources": ["slimevr:right_foot", "slimevr:right_lower_leg", "slimevr:right_upper_leg"],
"parent": "slimevr:right_lower_leg",
"tailOffset": {
"terms": [{"proportion": "slimevr:foot_length", "direction": {"x": 0, "y": 0, "z": -1}}]
},
"rotationFallback": {"type": "copy", "source": "slimevr:right_lower_leg"},
"constraint": {
"type": "looseHinge",
"minDegrees": -60,
"maxDegrees": 90,
"allowedDeviationDegrees": 60,
"axis": {"x": -1, "y": 0, "z": 0}
},
"outputs": {
"driver": {"supported": true},
"vmc": {"name": "RightFoot"},
"vrchat": {
"emit": {
"/tracking/trackers/3/position": {"from": "position", "value": [{"scale": {"z": -1}}]},
"/tracking/trackers/3/rotation": {
"from": "rotation",
"value": [{"scale": {"x": -1, "y": -1}}, {"euler": {"order": "YXZ"}}]
}
}
}
}
}
@@ -0,0 +1,25 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:right_hand",
"nameKey": "slimevr:bone.right_hand",
"mirror": "slimevr:left_hand",
"batterySources": ["slimevr:right_hand", "slimevr:right_lower_arm"],
"overridable": true,
"parent": "slimevr:right_lower_arm",
"tailOffset": {
"terms": [
{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -1, "z": 0}},
{"proportion": "slimevr:hand_z", "direction": {"x": 0, "y": 0, "z": -1}}
]
},
"rotationFallback": {"type": "copy", "source": "slimevr:right_lower_arm"},
"constraint": {"type": "twistSwing", "twistDegrees": 120, "swingDegrees": 120},
"outputs": {
"driver": {"supported": true},
"vmc": {
"name": "RightHand",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": 90}]
}
},
"inputs": {"vrchat": {"address": "/tracking/vrsystem/rightwrist/pose"}}
}
@@ -0,0 +1,17 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:right_index_distal",
"nameKey": "slimevr:bone.right_index_distal",
"mirror": "slimevr:left_index_distal",
"parent": "slimevr:right_index_intermediate",
"tailOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -0.174685, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "RightIndexDistal",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": 90}]
}
}
}
@@ -0,0 +1,17 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:right_index_intermediate",
"nameKey": "slimevr:bone.right_index_intermediate",
"mirror": "slimevr:left_index_intermediate",
"parent": "slimevr:right_index_proximal",
"tailOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -0.227815, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "RightIndexIntermediate",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": 90}]
}
}
}
@@ -0,0 +1,20 @@
{
"$schema": "../../schemas/v1/bone.schema.json",
"key": "slimevr:right_index_proximal",
"nameKey": "slimevr:bone.right_index_proximal",
"mirror": "slimevr:left_index_proximal",
"parent": "slimevr:right_hand",
"headOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": -0.03, "y": 0.05, "z": -0.34}}]
},
"tailOffset": {
"terms": [{"proportion": "slimevr:hand_y", "direction": {"x": 0, "y": -0.4025, "z": 0}}]
},
"rotationFallback": {"type": "none"},
"outputs": {
"vmc": {
"name": "RightIndexProximal",
"restRotation": [{"axis": {"x": 0, "y": 0, "z": 1}, "degrees": 90}]
}
}
}
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff. Show more