Expand spine model to support several sources per bone

This commit is contained in:
Erimel committed 2026-10-19 22:10:09 -04:00
1 parent 6c25eae4f0
commit efdc1aa4f5
1 file changed
+136 -65
@@ -15,7 +15,8 @@ const val DEFAULT_SPINE_UPPER_LOWER = 0.5f
private data class Reliability(
val forward: Float,
val side: Float? = null, // Use forward if null
val side: Float? = null, // Uses forward if null
val proportion: Float = 1f,
)
private enum class SpineSource(val parts: Array<BodyPart>) {
@@ -29,52 +30,54 @@ private enum class SpineSource(val parts: Array<BodyPart>) {
private val SPINE_SOURCES = enumEntries<SpineSource>().toTypedArray()
// The higher a value is, the more reliable that source is.
// The higher a value is, the that source is considered as reliable.
// If a "To" is 2x the "From", it'll use 100% "To".
// If a "To" is the same as "From", it'll do 50-50.
// A negative value will go towards the opposite rotation.
// A From and To may be taken from different roots.
// Order matters! Missing elements of the inner arrays will be skipped gracefully.
// TODO mess with proportion!
private val SPINE_SOURCE_RELIABILITY = arrayOf(
SpineSource.UPPER_CHEST to mapOf(
SpineSource.UPPER_CHEST to arrayOf(
SpineSource.UPPER_CHEST to Reliability(-6.5f, -24f), // Itself
// To
SpineSource.LOWER_CHEST to Reliability(1f),
SpineSource.UPPER_WAIST to Reliability(1.5f),
SpineSource.LOWER_WAIST to Reliability(2f),
SpineSource.HIP to Reliability(4f),
SpineSource.UPPER_LEGS to Reliability(1.5f, 1.75f),
SpineSource.HIP to Reliability(4f, null, 1f),
SpineSource.UPPER_LEGS to Reliability(3.25f, 3.75f),
),
SpineSource.LOWER_CHEST to mapOf(
SpineSource.LOWER_CHEST to arrayOf(
// From
SpineSource.UPPER_CHEST to Reliability(-10f, -42f),
SpineSource.LOWER_CHEST to Reliability(-11f, -45f), // Itself
// To
SpineSource.UPPER_WAIST to Reliability(1.5f, 10f),
SpineSource.LOWER_WAIST to Reliability(2f, 7f),
SpineSource.HIP to Reliability(4f),
SpineSource.HIP to Reliability(4f, null, 1f),
SpineSource.UPPER_LEGS to Reliability(3.25f, 3.75f),
),
SpineSource.UPPER_WAIST to mapOf(
SpineSource.UPPER_WAIST to arrayOf(
// From
SpineSource.UPPER_CHEST to Reliability(11f),
SpineSource.LOWER_CHEST to Reliability(11.5f),
SpineSource.UPPER_WAIST to Reliability(60f), // Itself
// To
SpineSource.LOWER_WAIST to Reliability(17f, 20f),
SpineSource.HIP to Reliability(5.5f, 8f),
SpineSource.HIP to Reliability(5.5f, 8f, 1f),
SpineSource.UPPER_LEGS to Reliability(0.25f, 4.25f),
),
SpineSource.LOWER_WAIST to mapOf(
SpineSource.LOWER_WAIST to arrayOf(
// From
SpineSource.UPPER_CHEST to Reliability(6f),
SpineSource.LOWER_CHEST to Reliability(6.5f),
SpineSource.UPPER_WAIST to Reliability(15f),
SpineSource.LOWER_WAIST to Reliability(44f), // Itself
// To
SpineSource.HIP to Reliability(10f, 12f),
SpineSource.HIP to Reliability(10f, 12f, 1f),
SpineSource.UPPER_LEGS to Reliability(1.75f, 10f),
),
SpineSource.HIP to mapOf(
SpineSource.HIP to arrayOf(
// From
SpineSource.UPPER_CHEST to Reliability(9.5f, 9f),
SpineSource.LOWER_CHEST to Reliability(9.75f, 9.25f),
@@ -85,31 +88,99 @@ private val SPINE_SOURCE_RELIABILITY = arrayOf(
SpineSource.UPPER_LEGS to Reliability(7f, 22f),
),
)
private val SPINE_SOURCE_RELIABILITY_INDEXED = SPINE_SOURCE_RELIABILITY.withIndex()
private val SPINE_SOURCE_RELIABILITY_SOURCES = SPINE_SOURCE_RELIABILITY.associate { (spineSource, reliabilities) ->
spineSource to reliabilities
}
private val SPINE_SOURCE_RELIABILITY_OWN_INDEX = SPINE_SOURCE_RELIABILITY.associate { (spineSource, reliabilities) ->
spineSource to SPINE_SOURCE_RELIABILITY_SOURCES[spineSource]!!.map { it.first }.indexOf(spineSource)
}
private val SPINE_SOURCE_RELIABILITY_MAP = SPINE_SOURCE_RELIABILITY.map { (spineSource, reliabilities) ->
spineSource to reliabilities.toMap()
}.toTypedArray()
/** The spine bones this processor imputes, top down. Other sources are only read as references. */
val SPINE_IMPUTED_PARTS: List<BodyPart> = SPINE_SOURCE_RELIABILITY.flatMap { (source, _) -> source.parts.toList() }
private fun nearestActive(startIndex: Int, step: Int, sourceActive: Map<SpineSource, Boolean>): Int? {
private fun nearestActive(sources: Array<Pair<SpineSource, Reliability>>, startIndex: Int, step: Int, sourceActive: Map<SpineSource, Boolean>): List<SpineSource> {
var i = startIndex
while (i in SPINE_SOURCES.indices) {
if (sourceActive[SPINE_SOURCES[i]] == true) return i
val result = mutableListOf<SpineSource>()
var proportionSum = 0f
while (i >= 0 && i < sources.count() && proportionSum < 1f) {
val source = sources[i]
if (sourceActive[source.first] == true) {
result.add(source.first)
proportionSum += source.second.proportion
}
i += step
}
return null
return result
}
private fun getFromTo(selfIndex: Int, sourceActive: Map<SpineSource, Boolean>): Pair<Int?, Int?> {
/**
* Builds a map containing the list of From SpineSource and a list of To SpineSource for each of key in SPINE_SOURCE_RELIABILITY.
*/
private fun buildFromTo(sourceActive: Map<SpineSource, Boolean>) = SPINE_SOURCE_RELIABILITY.associate { source ->
val spineSource = source.first
val sources = SPINE_SOURCE_RELIABILITY_SOURCES[spineSource] ?: error("No SPINE_SOURCE_RELIABILITY_SOURCES found for $spineSource")
val selfIndex = SPINE_SOURCE_RELIABILITY_OWN_INDEX[spineSource] ?: error("No SPINE_SOURCE_RELIABILITY_OWN_INDEX found for $spineSource")
// Find From, the first active bone in itself + its parents.
val from = nearestActive(selfIndex, -1, sourceActive)
val from = nearestActive(sources, selfIndex, -1, sourceActive)
// Find To, the next active bone in its children
val to = nearestActive(sources, selfIndex + 1, 1, sourceActive)
// Find To, the next active bone in its children, skipping the immediate next if itself is active except if it's the only one (for hip).
// If To is null, we return null for the whole thing
val isActive = sourceActive[SPINE_SOURCES[selfIndex]] == true
val immediateNext = selfIndex + 1
val takeImmediateNext = (!isActive || selfIndex + 2 == SPINE_SOURCES.count()) && sourceActive[SPINE_SOURCES[immediateNext]] == true
val to = if (takeImmediateNext) immediateNext else nearestActive(selfIndex + 2, 1, sourceActive)
spineSource to (from to to)
}
return from to to
private fun averageRotation(inputSkeleton: InputSkeleton, takeBodyParts: Array<BodyPart> = arrayOf()): Quaternion? {
val bonesToAverage = inputSkeleton.values.filter { it.bodyPart in takeBodyParts }
return bonesToAverage.map { it.rotation }
.reduceIndexedOrNull { index, acc, rotation ->
// Very important that this is interpQ as lerpQ will break on axes/polarity
acc.interpQ(rotation, 1f / (index + 1))
}
}
private fun weightedAverageRotation(sources: List<SpineSource>, reliabilities: Map<SpineSource, Reliability>, boneInputs: InputSkeleton): Quaternion {
var accProportion = 0f
return sources.foldIndexed(Quaternion.IDENTITY) { i, acc, fromSource ->
val rotation = averageRotation(boneInputs, fromSource.parts)
if (rotation != null) {
val proportion = if (i + 1 == sources.count()) {
// Use all the remaining
1 - accProportion
} else {
reliabilities[fromSource]?.proportion ?: error("No proportion found for $fromSource")
}
accProportion += proportion
acc * rotation.pow(proportion)
} else {
acc
}
}
}
private fun weightedAverageReliability(sources: List<SpineSource>, reliabilities: Map<SpineSource, Reliability>): Pair<Float, Float?> {
var accProportion = 0f
var accForward = 0f
var accSide: Float? = null
for ((i, source) in sources.withIndex()) {
val reliability = reliabilities[source] ?: continue
val proportion = if (i + 1 == sources.count()) {
// Use all the remaining
1 - accProportion
} else {
reliabilities[source]?.proportion ?: error("No proportion found for $source")
}
accProportion += proportion
accForward += (reliability.forward * proportion)
if (reliability.side != null) accSide = (accSide ?: 0f) + (reliability.side * proportion)
}
return accForward to accSide
}
/**
@@ -135,15 +206,6 @@ private fun interpolateRatio(fromUpperToLower: Float, curvature: Float, fromReli
}
}
private fun averageRotation(inputSkeleton: InputSkeleton, takeBodyParts: Array<BodyPart> = arrayOf()): Quaternion {
val bonesToAverage = inputSkeleton.values.filter { it.bodyPart in takeBodyParts }
return bonesToAverage.map { it.rotation }
.reduceIndexedOrNull { index, acc, rotation ->
// Very important that this is interpQ as lerpQ will break on axes/polarity
acc.interpQ(rotation, 1f / (index + 1))
} ?: Quaternion.IDENTITY
}
/**
* Interpolates between 2 rotations with a different ratio for forward and the rest/side.
*/
@@ -175,56 +237,65 @@ fun interpolateForwardSide(fromRotation: Quaternion, toRotation: Quaternion, for
class SpineInputProcessor(val settings: Settings) : SkeletonInputProcessor {
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
val ratios = settings.context.state.value.data.skeletonConfig.ratios
val boneInputs = BodyPartMap(mutableInputSkeleton)
val sourceActive = SPINE_SOURCES.associateWith { it.parts.all { part -> boneInputs[part]?.isRotationActive == true } }
val fromTo = SPINE_SOURCE_RELIABILITY.withIndex().associate { (selfIndex, source) ->
source.first to getFromTo(selfIndex, sourceActive)
}
val sourceActive = SPINE_SOURCES.associateWith { it.parts.all { part -> mutableInputSkeleton[part]?.isRotationActive == true } }
val fromTo = buildFromTo(sourceActive)
for ((spineIndex, spineSourceReliability) in SPINE_SOURCE_RELIABILITY.withIndex()) {
val boneInputs = BodyPartMap(mutableInputSkeleton)
for ((spineIndex, spineSourceReliability) in SPINE_SOURCE_RELIABILITY_INDEXED) {
val spineSource = spineSourceReliability.first
// For optimization's sake, assume only one BodyPart per SpineSource we traverse.
val bodyPart = spineSource.parts.first()
val bone = boneInputs[bodyPart] ?: continue
val isActive = bone.isRotationActive
// Get reliabilities mapped to this spine bone
val reliabilities = SPINE_SOURCE_RELIABILITY[spineIndex].second
val reliabilities = SPINE_SOURCE_RELIABILITY_MAP[spineIndex].second
// Get the spine sources for the current spineSource
val (fromIndex, toIndex) = fromTo[spineSource] ?: error("No fromTo for $spineSource found.")
// toIndex will be null if the bone has no active children.
if (toIndex == null) continue
val (fromSpineSource, toSpineSource) = if (fromIndex != null) {
SPINE_SOURCES[fromIndex] to SPINE_SOURCES[toIndex]
} else {
// Fall back to itself to its to's to
val toTo = fromTo[SPINE_SOURCES[toIndex]] ?: continue
spineSource to SPINE_SOURCES[toTo.second ?: continue]
}
val (from, to) = fromTo[spineSource] ?: error("No fromTo for $spineSource found.")
if (to.isEmpty()) continue // Nothing to interpolate with
// We are interpolating as-if we were the To, but using self instead of to
val sourceActive = isActive || fromIndex == null
// Determine the sources used for getting rotation
val fromRotationSources = from.ifEmpty { to }
val fromReliabilitySources = from.ifEmpty { listOf(spineSource) }
val toSources = if (from.isNotEmpty()) to else to.flatMap { fromTo[it]?.second ?: emptyList() }
// Get the interpolation ratios. sideRatio is null if nothing specified for side.
val fromReliability = reliabilities[fromSpineSource] ?: continue
val toReliability = reliabilities[toSpineSource] ?: continue
val forwardRatio = interpolateRatio(ratios.imputeSpineFromUpperToLower, ratios.spineCurvature, fromReliability.forward, toReliability.forward, sourceActive)
val sideRatio = if (fromReliability.side != null || toReliability.side != null) {
interpolateRatio(ratios.imputeSpineFromUpperToLower, ratios.spineCurvature, fromReliability.side ?: fromReliability.forward, toReliability.side ?: toReliability.forward, sourceActive)
// Get From and To's weighted average reliabilities
val (fromForwardReliability, fromSideReliability) = weightedAverageReliability(fromReliabilitySources, reliabilities)
val (toForwardReliability, toSideReliability) = weightedAverageReliability(toSources, reliabilities)
// Get From and To's weighted average rotations
val fromRotation = weightedAverageRotation(fromRotationSources, reliabilities, boneInputs)
val toRotation = weightedAverageRotation(toSources, reliabilities, boneInputs)
// We are interpolating as-if we were the To if From is empty
val sourceActive = bone.isRotationActive || from.isEmpty()
// Calculate ratios from reliabilities
val forwardRatio = interpolateRatio(
ratios.imputeSpineFromUpperToLower,
ratios.spineCurvature,
fromForwardReliability,
toForwardReliability,
sourceActive,
)
val sideRatio = if (fromSideReliability != null || toSideReliability != null) {
interpolateRatio(
ratios.imputeSpineFromUpperToLower,
ratios.spineCurvature,
fromSideReliability ?: fromForwardReliability,
toSideReliability ?: toForwardReliability,
sourceActive,
)
} else {
null
}
// If from is null, use to as from and use to's to as to
val fromParts = if (fromIndex != null) fromSpineSource.parts else SPINE_SOURCES[toIndex].parts
val toParts = toSpineSource.parts
// Interpolate between from and to using our interpolation ratio.
mutableInputSkeleton[bodyPart] = bone.copy(
rotation = interpolateForwardSide(
averageRotation(boneInputs, fromParts),
averageRotation(boneInputs, toParts),
fromRotation,
toRotation,
forwardRatio,
sideRatio,
),