Snapshot of the Umamo working tree as it is

Uploaded as-is from /home/litruv/dev/vtsmaker/umamo on 2026-11-03. 1347 files.
Includes the uncommitted work in progress in :edit, :runtime, and :ui, and the
untracked files under module/edit/src/jvmAndroidMain/.

History is not carried over. The source repo is https://github.com/umamoorg/umamo.
This commit is contained in:
litruv
2026-11-03 18:20:25 +11:00
commit 8bd8fa7a0b
1347 changed files with 246161 additions and 0 deletions
+39
View File
@@ -0,0 +1,39 @@
// :runtime — the pure puppet runtime: the immutable PuppetModel and its typed ids, the keyform grid
// algebra, and the sampling eval. Zero format knowledge — CMO3/MOC3 conversion lives in :interop,
// which depends on this module and :format. (Deformation eval and the renderer live in :render,
// which depends on :runtime — not the reverse.)
plugins {
alias(libs.plugins.kotlinMultiplatform)
alias(libs.plugins.androidKmpLibrary)
// Wires the iosArm64 compiles into `check` (a device target has no runnable test task of its own).
id("umamo.kmp-ios-gate")
}
kotlin {
jvmToolchain(21)
jvm()
// The iPadOS ship target, mirroring :format (see its docblock for the full rationale). Two jobs:
// it makes commonMain purity a COMPILER GUARANTEE rather than the root regex gate's convention, and
// it is what lets :render declare the same target — :render/commonMain does api(:runtime), so the
// renderer the Metal engineer builds against could not compile for iOS until this module did.
// Compiles on Linux/CI (klib only, no Xcode linker); a device target has no runnable test task, so
// `umamo.kmp-ios-gate` wires `check` to the compiles.
iosArm64()
android {
namespace = "org.umamo.runtime"
compileSdk = libs.versions.android.compileSdk.get().toInt()
minSdk = libs.versions.android.minSdk.get().toInt()
}
sourceSets {
commonTest {
dependencies {
implementation(kotlin("test"))
}
}
}
}
@@ -0,0 +1,148 @@
package org.umamo.runtime.eval
import org.umamo.runtime.model.ChannelGrids
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.ColorRgb
import org.umamo.runtime.model.FormChannel
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.ParameterId
/*
* Pose sampling for the per-channel keyform tracks, over the same multilinear corner selection the
* geometry blend uses.
*
* Each channel resolves its OWN corners from its OWN grid rather than borrowing geometry's. That is not
* an optimization left on the table - after import compaction a channel track keeps only the axes it
* actually varies along, so its cell linear indices no longer line up with geometry's and a borrowed
* corner set would read the wrong cells. Before compaction the two share axes, so the corners come out
* identical in identical order and the sums are bit-for-bit what the bundled blend produced.
*
* The static fallback applies when the owner has NO track for a channel, or when the track's pose is out
* of range. Out of range NEVER hides: hiding is the geometry grid's decision alone, so keying opacity on
* a narrow parameter cannot make the art vanish at the ends of an unrelated slider.
*
* Every read takes an optional OVERRIDE, which wins over both the track and the static. That is how a
* value the user has typed but not yet keyed reaches the viewport: the pending edit is not in the document
* (it is transient session state), so it arrives beside the pose rather than inside the model.
*/
/**
* The blended value of a SCALAR channel at the given pose, or [staticValue] when it is untracked or the
* pose falls outside the track's key range.
*
* A cell missing from a sparse track contributes nothing rather than falling back, matching how the
* bundled blend has always treated an unresolvable cell.
*
* @param FormChannel channel The scalar channel to sample.
* @param Float staticValue The owner's static value for this channel.
* @param Function paramValue Current value for a given parameter id.
* @return Float The blended value, or [staticValue].
*/
fun ChannelGrids.scalarAt(
channel: FormChannel,
staticValue: Float,
paramValue: (ParameterId) -> Float,
override: ChannelValue? = null,
): Float =
// One body with scalarOrNull, so the renderer's opacity read and the sparse draw-order read can never
// disagree about the blend arithmetic - two separately maintained copies would drift as one gets
// tuned and the other forgotten.
scalarOrNull(channel, paramValue, override) ?: staticValue
/**
* The blended value of a COLOR channel at the given pose, or [staticValue] when untracked or out of range.
*
* @param FormChannel channel The color channel to sample.
* @param ColorRgb staticValue The owner's static color for this channel.
* @param Function paramValue Current value for a given parameter id.
* @return ColorRgb The blended color, or [staticValue].
*/
fun ChannelGrids.colorAt(
channel: FormChannel,
staticValue: ColorRgb,
paramValue: (ParameterId) -> Float,
override: ChannelValue? = null,
): ColorRgb {
(override as? ChannelValue.Color)?.let { pending -> return pending.color }
val grid = this[channel] ?: return staticValue
val corners = gridCorners(grid, paramValue) ?: return staticValue
val cells = cellsByLinearIndex(grid)
var red = 0f
var green = 0f
var blue = 0f
for (corner in corners) {
val color = (cells[corner.linearIndex]?.form as? ChannelValue.Color)?.color ?: continue
red += corner.weight * color.red
green += corner.weight * color.green
blue += corner.weight * color.blue
}
return ColorRgb(red, green, blue)
}
/**
* The value of a FLAG channel at the given pose, or [staticValue] when untracked or out of range.
*
* A flag snaps to the FLOOR cell instead of blending - [gridCorners] builds its first corner by taking the
* lower key on every axis, so corner 0 is the floor cell, which is the same cell the bundled rotation
* blend has always read its reflection flags from.
*
* @param FormChannel channel The flag channel to sample.
* @param Boolean staticValue The owner's static flag for this channel.
* @param Function paramValue Current value for a given parameter id.
* @return Boolean The floor cell's flag, or [staticValue].
*/
fun ChannelGrids.flagAt(
channel: FormChannel,
staticValue: Boolean,
paramValue: (ParameterId) -> Float,
override: ChannelValue? = null,
): Boolean {
(override as? ChannelValue.Flag)?.let { pending -> return pending.flag }
val grid = this[channel] ?: return staticValue
val corners = gridCorners(grid, paramValue) ?: return staticValue
val floorCorner = corners.firstOrNull() ?: return staticValue
val cells = cellsByLinearIndex(grid)
return (cells[floorCorner.linearIndex]?.form as? ChannelValue.Flag)?.flag ?: staticValue
}
/**
* The blended value of a SCALAR channel, or null when the owner does not track it or the pose is out of
* the track's range.
*
* The distinction from [scalarAt] matters where absence is itself information - the per-pose part
* draw-order map is sparse on purpose, so a part with no animated order stays out of it and the renderer
* keeps its static slot rather than being handed a value that merely equals the static.
*
* @param FormChannel channel The scalar channel to sample.
* @param Function paramValue Current value for a given parameter id.
* @param ChannelValue? override A pending unkeyed edit that wins over the track and the static.
* @return Float? The blended value, or null when untracked or out of range.
*/
fun ChannelGrids.scalarOrNull(
channel: FormChannel,
paramValue: (ParameterId) -> Float,
override: ChannelValue? = null,
): Float? {
(override as? ChannelValue.Scalar)?.let { pending -> return pending.value }
val grid = this[channel] ?: return null
val corners = gridCorners(grid, paramValue) ?: return null
val cells = cellsByLinearIndex(grid)
var total = 0f
for (corner in corners) {
val value = (cells[corner.linearIndex]?.form as? ChannelValue.Scalar)?.value ?: continue
total += corner.weight * value
}
return total
}
/**
* Every axis of every channel track, in channel order.
*
* The panel's effective-parameter walk and key-mark scan must union geometry's axes with every channel
* track's, or an opacity-only track becomes invisible to the parameter list. This is the one flatten
* every walk shares; a walk that inlined its own copy instead would silently drift out of sync the
* moment a channel-only axis (e.g. a glue intensity track) is added.
*
* @return List<KeyformAxis> The axes of every track.
*/
fun ChannelGrids.allAxes(): List<KeyformAxis> = gridsByChannel.values.flatMap { grid -> grid.axes }
@@ -0,0 +1,244 @@
package org.umamo.runtime.eval
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.RotationPivotForm
import org.umamo.runtime.model.WarpLatticeForm
/*
* Pure keyform-grid sampling: the multilinear corner selection and the pose-sampling helpers that
* both the renderer's evaluator (:render) and the MOC3 import (Moc3Import) must agree on. Hoisted
* from :render's eval so the import can compute the blend-shape delta reference (the grid form at
* the DEFAULT pose) with the EXACT same arithmetic the evaluator later subtracts - any divergence
* between the two would leak into every MOC3-imported blend shape as a residual offset.
*/
// Bracket tolerances match the Umamo C++ Runtime, needed for ULP-parity with the differential-oracle test.
// A value within EPS_KEY of a key snaps to it; a key span below EPS_SPAN contributes no fraction.
// runtime.keyform's grid algebra shares them: authoring a key closer than EPS_KEY to an existing one, or a
// span below EPS_SPAN, produces a grid this evaluator cannot resolve, so the algebra refuses both - and it
// must refuse against these exact values, not a second copy of them.
/**
* The key-coincidence tolerance. Public because :interop's keyform export refinement merges union
* axes against the same snap distance the sampling here and the grid algebra use; every consumer
* must bracket against this exact value, never a copy of it.
*/
public const val EPS_KEY: Float = 0.001f
internal const val EPS_SPAN = 0.0015f
// The Umamo C++ Runtime caps the multilinear corner set at 16 (kbCorners `maxc`); past that an axis snaps to its
// lower key instead of splitting. Replicated for fidelity (matters only for >4 fractional axes).
private const val MAX_CORNERS = 16
/**
* One axis's bracket of a parameter value: the lower key [index] and the [fraction] toward `index+1`
* (0 when snapped exactly onto a key).
*/
public data class AxisBracket(val index: Int, val fraction: Float)
/**
* A grid cell selected by the current parameters, addressed by its stride-folded [linearIndex], with
* its multilinear [weight].
*/
public data class WeightedCell(val linearIndex: Int, val weight: Float)
/**
* Brackets [value] against an axis's sorted [keys]. Returns null when the value is out of range
* (the entity auto-hides / freezes), otherwise the lower key index and the blend fraction toward
* the next key (0 when snapped onto a key).
*
* @param FloatArray keys The axis's key positions (ascending parameter values).
* @param Float value The current parameter value on this axis.
* @return AxisBracket? The bracket, or null when out of range.
*/
public fun bindBracket(keys: FloatArray, value: Float): AxisBracket? {
val keyCount = keys.size
if (keyCount <= 1) {
if (keyCount == 0) {
return AxisBracket(0, 0f)
}
return if (value > keys[0] - EPS_KEY && value < keys[0] + EPS_KEY) AxisBracket(0, 0f) else null
}
if (value < keys[0] - EPS_KEY || value >= keys[keyCount - 1] + EPS_KEY) {
return null
}
if (value < keys[0] + EPS_KEY) {
return AxisBracket(0, 0f)
}
var hi = 1
while (hi < keyCount && keys[hi] + EPS_KEY <= value) {
hi++
}
if (value <= keys[hi] - EPS_KEY) {
val span = keys[hi] - keys[hi - 1]
val fraction = if (span >= EPS_SPAN) (value - keys[hi - 1]) / span else 0f
return AxisBracket(hi - 1, fraction)
}
return AxisBracket(hi, 0f)
}
/**
* [gridCorners] with each axis's pose clamped into that axis's first..last key (constant hold past the
* ends). Authoring uses this when inserting a key beyond the current span: the new slice should copy the
* nearest end keyform, not fall back to the first cell or the owner's static. Render sampling stays on
* plain [gridCorners], which returns null out of range so geometry can freeze / hide.
*
* @param KeyformGrid grid The entity's keyform grid.
* @param Function paramValue Current value for a given parameter id.
* @return List<WeightedCell>? The weighted corners at the held pose, or null when an axis has no keys.
*/
public fun gridCornersHolding(grid: KeyformGrid<*>, paramValue: (ParameterId) -> Float): List<WeightedCell>? =
gridCorners(grid) { parameterId ->
val keys = grid.axes.firstOrNull { axis -> axis.parameterId == parameterId }?.keys
val value = paramValue(parameterId)
if (keys == null || keys.isEmpty()) {
value
} else {
value.coerceIn(keys.first(), keys.last())
}
}
/**
* The multilinear corner set for [grid] at the current parameters, or null when any controlling axis
* is out of range (the entity is frozen). Each fractional axis doubles the corner
* list (weights ×= frac / 1−frac) and folds a stride-based linear cell index, matching how
* [cellsByLinearIndex] folds each [KeyformCell.coordinate].
*
* @param KeyformGrid grid The entity's keyform grid (only its axes are read).
* @param Function paramValue Current value for a given parameter id.
* @return List<WeightedCell>? The weighted corner cells, or null when hidden.
*/
public fun gridCorners(grid: KeyformGrid<*>, paramValue: (ParameterId) -> Float): List<WeightedCell>? {
var corners = mutableListOf(WeightedCell(0, 1f))
var stride = 1
for (axis in grid.axes) {
val bracket = bindBracket(axis.keys, paramValue(axis.parameterId)) ?: return null
val split = bracket.fraction > 0f && corners.size * 2 <= MAX_CORNERS
if (split) {
val next = ArrayList<WeightedCell>(corners.size * 2)
for (corner in corners) {
next.add(
WeightedCell(
corner.linearIndex + bracket.index * stride,
corner.weight * (1f - bracket.fraction),
),
)
next.add(
WeightedCell(
corner.linearIndex + (bracket.index + 1) * stride,
corner.weight * bracket.fraction,
),
)
}
corners = next
} else {
// Snap (on a key, or over the corner budget): every corner takes the lower key, weight kept.
for (cornerIndex in corners.indices) {
val corner = corners[cornerIndex]
corners[cornerIndex] = WeightedCell(corner.linearIndex + bracket.index * stride, corner.weight)
}
}
stride *= axis.keys.size
}
return corners
}
/**
* Indexes a grid's cells by their stride-folded linear index (axis `a`'s stride = Π key counts of the
* earlier axes), so a [WeightedCell.linearIndex] from [gridCorners] resolves to the matching cell.
*
* A delegate to the grid's own CACHED index: the grid is immutable, and building the map per call put
* hundreds of transient HashMaps on every scrub frame.
*
* @param KeyformGrid grid The grid to index.
* @return Map<Int, KeyformCell> linear index → cell.
*/
public fun <TForm> cellsByLinearIndex(grid: KeyformGrid<TForm>): Map<Int, KeyformCell<TForm>> = grid.cellsByLinearIndex
/**
* The drawable's grid form at the DEFAULT pose as position deltas vs the rest mesh - the shared
* blend-shape delta reference (E5). Null when the drawable is ungridded or the default pose is out
* of the grid's range (the reference is then zero). Static per drawable: the CPU pose prep, the
* GPU delta-texture bake, and the MOC3 import all call this and must agree.
*
* @param Drawable drawable The drawable.
* @param Function defaultValue Default value per parameter id.
* @return FloatArray? The interleaved reference deltas, or null.
*/
public fun meshGridDefaultDeltas(drawable: Drawable, defaultValue: (ParameterId) -> Float): FloatArray? {
val grid = drawable.geometryGrid ?: return null
val defaultCorners = gridCorners(grid, defaultValue) ?: return null
val deltas = FloatArray(grid.cells.firstOrNull()?.form?.positionDeltas?.size ?: 0)
val byLinearIndex = cellsByLinearIndex(grid)
for (corner in defaultCorners) {
val form = byLinearIndex[corner.linearIndex]?.form ?: continue
for (componentIndex in deltas.indices) {
deltas[componentIndex] += corner.weight * form.positionDeltas[componentIndex]
}
}
return deltas
}
/**
* The lattice control points grid-blended at the given pose, or null when the warp is unkeyed or
* the pose is out of the grid's range.
*
* @param KeyformGrid? grid The warp's keyform grid.
* @param Function paramValue Value per parameter id defining the pose.
* @return FloatArray? The interleaved blended control points, or null.
*/
public fun warpControlPointsAt(grid: KeyformGrid<WarpLatticeForm>?, paramValue: (ParameterId) -> Float): FloatArray? {
if (grid == null) {
return null
}
val corners = gridCorners(grid, paramValue) ?: return null
val byLinearIndex = cellsByLinearIndex(grid)
var blended: FloatArray? = null
for (corner in corners) {
val form = byLinearIndex[corner.linearIndex]?.form ?: continue
val target = blended ?: FloatArray(form.controlPoints.size).also { blended = it }
for (componentIndex in target.indices) {
target[componentIndex] += corner.weight * form.controlPoints[componentIndex]
}
}
return blended
}
/**
* The rotation pivot transform grid-blended at the given pose, or null when unkeyed or out of range.
*
* The reflection flags are NOT here: they snap to the floor cell rather than blending, so they live as
* FLAG channels on the deformer's ChannelGrids and are read through flagAt.
*
* @param KeyformGrid? grid The rotation's geometry grid.
* @param Function paramValue Value per parameter id defining the pose.
* @return RotationPivotForm? The blended transform, or null.
*/
public fun rotationFormAt(grid: KeyformGrid<RotationPivotForm>?, paramValue: (ParameterId) -> Float): RotationPivotForm? {
if (grid == null) {
return null
}
val corners = gridCorners(grid, paramValue) ?: return null
val byLinearIndex = cellsByLinearIndex(grid)
var originX = 0f
var originY = 0f
var angle = 0f
var scale = 0f
var resolvedAnyCell = false
for (corner in corners) {
val form = byLinearIndex[corner.linearIndex]?.form ?: continue
resolvedAnyCell = true
originX += corner.weight * form.originX
originY += corner.weight * form.originY
angle += corner.weight * form.angle
scale += corner.weight * form.scale
}
if (!resolvedAnyCell) {
return null
}
return RotationPivotForm(originX, originY, angle, scale)
}
@@ -0,0 +1,462 @@
package org.umamo.runtime.eval
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.sqrt
/*
* Pure warp-lattice point mapping shared by the renderer and structure edits (deformer unwrap bake).
* Bit-identical to the historical :render DeformTransforms implementation.
*/
/**
* In-grid warp transform: maps a child point `(u, v)` inside the lattice `[0,1)²` to world via the
* deformed control points [cp] - `(cols+1)×(rows+1)` points, interleaved x,y. [bilinear] true does the
* quad (bilinear) blend of the 4 surrounding control points, false the triangle split. Writes the
* result to `out[outIndex]`,`out[outIndex+1]`; returns false (and writes nothing) when `(u, v)` is
* outside the grid.
*
* @param FloatArray cp Control points, `(cols+1)*(rows+1)` interleaved x,y.
* @param Int cols Grid columns.
* @param Int rows Grid rows.
* @param Boolean bilinear Quad blend (true) vs triangle split (false).
* @param Float u Normalized horizontal coordinate.
* @param Float v Normalized vertical coordinate.
* @param FloatArray out Destination for the transformed point.
* @param Int outIndex Index of the x slot in [out] (y is `outIndex+1`).
* @return Boolean true when in grid (and written), false when outside.
*/
fun warpInGrid(
cp: FloatArray,
cols: Int,
rows: Int,
bilinear: Boolean,
u: Float,
v: Float,
out: FloatArray,
outIndex: Int,
): Boolean {
if (u < 0f || v < 0f || u >= 1f || v >= 1f) {
return false
}
val pointsPerRow = cols + 1
val gridU = cols * u
val gridV = rows * v
val cellU = gridU - gridU.toInt()
val cellV = gridV - gridV.toInt()
val cellIndex = gridV.toInt() * pointsPerRow + gridU.toInt()
val p00 = cellIndex * 2
val p10 = (cellIndex + 1) * 2
val p01 = (cellIndex + pointsPerRow) * 2
val p11 = (cellIndex + pointsPerRow + 1) * 2
if (!bilinear) {
if (cellU + cellV <= 1f) {
out[outIndex] = cp[p10] * cellU + cp[p00] * (1 - cellU - cellV) + cp[p01] * cellV
out[outIndex + 1] = (1 - cellU - cellV) * cp[p00 + 1] + cp[p10 + 1] * cellU + cp[p01 + 1] * cellV
} else {
val weight = (cellU - 1) + cellV
out[outIndex] = cp[p01] * (1 - cellU) + cp[p11] * weight + cp[p10] * (1 - cellV)
out[outIndex + 1] = weight * cp[p11 + 1] + (1 - cellU) * cp[p01 + 1] + (1 - cellV) * cp[p10 + 1]
}
} else {
val invCellV = 1 - cellV
out[outIndex] =
cp[p10] * cellU * invCellV + cp[p00] * (1 - cellU) * invCellV + cp[p01] * (1 - cellU) * cellV + cp[p11] * cellU * cellV
out[outIndex + 1] =
invCellV * cp[p10 + 1] * cellU + cp[p00 + 1] * (1 - cellU) * invCellV + (1 - cellU) * cp[p01 + 1] * cellV + cellU * cp[p11 + 1] * cellV
}
return true
}
/**
* Out-of-grid warp extrapolation: a pure affine far outside the lattice, edge-blended near the border
* (mode-independent). Assumes `(u, v)` is outside `[0,1)²` (call only after [warpInGrid] returned
* false).
*
* @param FloatArray cp Control points, `(cols+1)*(rows+1)` interleaved x,y.
* @param Int cols Grid columns.
* @param Int rows Grid rows.
* @param Float u Normalized horizontal coordinate (outside `[0,1)`).
* @param Float v Normalized vertical coordinate (outside `[0,1)`).
* @param FloatArray out Destination for the transformed point.
* @param Int outIndex Index of the x slot in [out] (y is `outIndex+1`).
*/
fun warpExtrap(cp: FloatArray, cols: Int, rows: Int, u: Float, v: Float, out: FloatArray, outIndex: Int) {
val pointsPerRow = cols + 1
val lastRowBase = rows * pointsPerRow
val topLeftX = cp[0]
val topLeftY = cp[1]
val topRightX = cp[cols * 2]
val topRightY = cp[cols * 2 + 1]
val botLeftX = cp[lastRowBase * 2]
val botLeftY = cp[lastRowBase * 2 + 1]
val botRightX = cp[(cols + lastRowBase) * 2]
val botRightY = cp[(cols + lastRowBase) * 2 + 1]
val gridU = cols * u
val gridV = rows * v
val dUx = ((botRightX - topLeftX) + (topRightX - botLeftX)) * 0.5f
val dVx = ((botRightX - topLeftX) - (topRightX - botLeftX)) * 0.5f
val dUy = ((botRightY - topLeftY) + (topRightY - botLeftY)) * 0.5f
val dVy = ((botRightY - topLeftY) - (topRightY - botLeftY)) * 0.5f
val originX = (topLeftX + topRightX + botLeftX + botRightX) * 0.25f - (botRightX - topLeftX) * 0.5f
val originY = (topLeftY + topRightY + botLeftY + botRightY) * 0.25f - (botRightY - topLeftY) * 0.5f
if (u <= -2f || u >= 3f || v <= -2f || v >= 3f) {
out[outIndex] = dUx * u + originX + dVx * v
out[outIndex + 1] = dVy * v + dUy * u + originY
return
}
var blendU = 0f
var blendV = 0f
var corner0x = 0f
var corner0y = 0f
var corner1x = 0f
var corner1y = 0f
var corner2x = 0f
var corner2y = 0f
var corner3x = 0f
var corner3y = 0f
if (u <= 0f) {
blendU = (u + 2f) * 0.5f
corner3x = originX - 2f * dUx
corner3y = originY - 2f * dUy
if (v <= 0f) {
corner2x = topLeftX
corner2y = topLeftY
blendV = (v + 2f) * 0.5f
corner1x = originX - 2f * dVx
corner0x = corner3x - 2f * dVx
corner1y = originY - 2f * dVy
corner0y = corner3y - 2f * dVy
} else if (v < 1f) {
var loIdx = gridV.toInt()
val edgeHi: Float
val hiIdx: Int
if (rows == loIdx) {
loIdx = rows - 1
hiIdx = rows
edgeHi = rows.toFloat()
} else {
hiIdx = loIdx + 1
edgeHi = (loIdx + 1).toFloat()
}
blendV = gridV - loIdx
val edgeLo = loIdx.toFloat() / rows
corner1x = cp[loIdx * pointsPerRow * 2]
corner1y = cp[loIdx * pointsPerRow * 2 + 1]
corner2x = cp[hiIdx * pointsPerRow * 2]
corner2y = cp[hiIdx * pointsPerRow * 2 + 1]
corner0x = edgeLo * dVx + corner3x
corner0y = edgeLo * dVy + corner3y
corner3x = (edgeHi / rows) * dVx + corner3x
corner3y = (edgeHi / rows) * dVy + corner3y
} else {
corner1x = botLeftX
corner1y = botLeftY
blendV = (v - 1f) * 0.5f
corner0x = corner3x + dVx
corner0y = corner3y + dVy
corner3x = 3f * dVx + corner3x
corner2x = 3f * dVx + originX
corner3y = 3f * dVy + corner3y
corner2y = 3f * dVy + originY
}
} else if (u < 1f) {
if (v <= 0f) {
var loIdx = gridU.toInt()
val edgeX: Float
val edgeY: Float
val edgeHi: Float
if (cols == loIdx) {
loIdx = cols - 1
edgeX = topRightX
edgeY = topRightY
edgeHi = cols.toFloat()
} else {
edgeX = cp[(loIdx + 1) * 2]
edgeY = cp[(loIdx + 1) * 2 + 1]
edgeHi = (loIdx + 1).toFloat()
}
corner2y = edgeY
blendV = (v + 2f) * 0.5f
blendU = gridU - loIdx
val edgeLo = loIdx.toFloat() / cols
corner3x = cp[loIdx * 2]
corner3y = cp[loIdx * 2 + 1]
corner2x = edgeX
corner0x = (edgeLo * dUx + originX) - 2f * dVx
corner0y = (edgeLo * dUy + originY) - 2f * dVy
corner1x = ((edgeHi / cols) * dUx + originX) - 2f * dVx
corner1y = ((edgeHi / cols) * dUy + originY) - 2f * dVy
} else if (v >= 1f) {
var loIdx = gridU.toInt()
val edgeHi: Float
val hiIdx: Int
if (cols == loIdx) {
loIdx = cols - 1
hiIdx = cols
edgeHi = cols.toFloat()
} else {
hiIdx = loIdx + 1
edgeHi = (loIdx + 1).toFloat()
}
blendV = (v - 1f) * 0.5f
blendU = gridU - loIdx
val edgeLo = loIdx.toFloat() / cols
corner0x = cp[(loIdx + lastRowBase) * 2]
corner0y = cp[(loIdx + lastRowBase) * 2 + 1]
corner1x = cp[(lastRowBase + hiIdx) * 2]
corner1y = cp[(lastRowBase + hiIdx) * 2 + 1]
corner2x = (edgeHi / cols) * dUx + originX + 3f * dVx
corner3x = edgeLo * dUx + originX + 3f * dVx
corner3y = edgeLo * dUy + originY + 3f * dVy
corner2y = (edgeHi / cols) * dUy + originY + 3f * dVy
} else {
out[outIndex] = originX + dUx * u + dVx * v
out[outIndex + 1] = originY + dVy * v + dUy * u
return
}
} else {
blendU = (u - 1f) * 0.5f
corner2x = 3f * dUx + originX
corner2y = 3f * dUy + originY
if (v <= 0f) {
corner3x = topRightX
corner3y = topRightY
blendV = (v + 2f) * 0.5f
corner0x = (originX + dUx) - 2f * dVx
corner1x = corner2x - 2f * dVx
corner1y = corner2y - 2f * dVy
corner0y = (originY + dUy) - 2f * dVy
} else if (v < 1f) {
var loIdx = gridV.toInt()
val edgeHi: Float
val hiIdx: Int
if (rows == loIdx) {
loIdx = rows - 1
hiIdx = rows
edgeHi = rows.toFloat()
} else {
hiIdx = loIdx + 1
edgeHi = (loIdx + 1).toFloat()
}
blendV = gridV - loIdx
corner0x = cp[(loIdx * pointsPerRow + cols) * 2]
corner0y = cp[(loIdx * pointsPerRow + cols) * 2 + 1]
corner3x = cp[(hiIdx * pointsPerRow + cols) * 2]
corner3y = cp[(hiIdx * pointsPerRow + cols) * 2 + 1]
val edgeLo = loIdx.toFloat() / rows
corner1x = edgeLo * dVx + corner2x
corner1y = edgeLo * dVy + corner2y
corner2x = (edgeHi / rows) * dVx + corner2x
corner2y = (edgeHi / rows) * dVy + corner2y
} else {
corner0x = botRightX
corner0y = botRightY
blendV = (v - 1f) * 0.5f
corner1x = corner2x + dVx
corner1y = corner2y + dVy
corner3x = originX + dUx + 3f * dVx
corner2x = 3f * dVx + corner2x
corner3y = originY + dUy + 3f * dVy
corner2y = 3f * dVy + corner2y
}
}
if (blendU + blendV <= 1f) {
out[outIndex] = (corner1x - corner0x) * blendU + corner0x + (corner3x - corner0x) * blendV
out[outIndex + 1] = (corner1y - corner0y) * blendU + corner0y + (corner3y - corner0y) * blendV
} else {
out[outIndex] = (corner3x - corner2x) * (1f - blendU) + corner2x + (corner1x - corner2x) * (1f - blendV)
out[outIndex + 1] = (1f - blendU) * (corner3y - corner2y) + corner2y + (1f - blendV) * (corner1y - corner2y)
}
}
/**
* Warp-transforms `(u, v)` through [cp]: the in-grid fast path, falling back to extrapolation outside.
*
* @param FloatArray cp Control points, `(cols+1)*(rows+1)` interleaved x,y.
* @param Int cols Grid columns.
* @param Int rows Grid rows.
* @param Boolean bilinear Quad blend (true) vs triangle split (false).
* @param Float u Normalized horizontal coordinate.
* @param Float v Normalized vertical coordinate.
* @param FloatArray out Destination for the transformed point.
* @param Int outIndex Index of the x slot in [out] (y is `outIndex+1`).
*/
fun warpApply(
cp: FloatArray,
cols: Int,
rows: Int,
bilinear: Boolean,
u: Float,
v: Float,
out: FloatArray,
outIndex: Int,
) {
if (!warpInGrid(cp, cols, rows, bilinear, u, v, out, outIndex)) {
warpExtrap(cp, cols, rows, u, v, out, outIndex)
}
}
private const val WARP_INVERSE_MAX_ITERATIONS = 20
private const val WARP_INVERSE_JACOBIAN_STEP = 1e-4f
private const val WARP_INVERSE_MAX_STEP = 0.5f
/**
* Solves `warpApply(u, v) ≈ (targetX, targetY)` by damped Newton, writing the best `(u, v)` into
* [outU]/[outV]. Seeds from the values already in those holders (typically a bbox-normalized guess).
*
* @param FloatArray cp Lattice control points.
* @param Int cols Columns.
* @param Int rows Rows.
* @param Boolean bilinear Quad vs triangle.
* @param Float targetX Parent-local target x.
* @param Float targetY Parent-local target y.
* @param FloatArray outUOutV Length-2 holder: seed in, solved UV out.
*/
fun invertWarpApply(
cp: FloatArray,
cols: Int,
rows: Int,
bilinear: Boolean,
targetX: Float,
targetY: Float,
outUOutV: FloatArray,
) {
val toleranceSquared = warpInverseToleranceSquared(cp)
var currentU = outUOutV[0]
var currentV = outUOutV[1]
var bestU = currentU
var bestV = currentV
var bestErrorSquared = Float.MAX_VALUE
val scratch = FloatArray(2)
for (iteration in 0 until WARP_INVERSE_MAX_ITERATIONS) {
warpApply(cp, cols, rows, bilinear, currentU, currentV, scratch, 0)
val residualX = scratch[0] - targetX
val residualY = scratch[1] - targetY
val errorSquared = residualX * residualX + residualY * residualY
if (errorSquared < bestErrorSquared) {
bestErrorSquared = errorSquared
bestU = currentU
bestV = currentV
}
if (errorSquared <= toleranceSquared) {
break
}
warpApply(cp, cols, rows, bilinear, currentU + WARP_INVERSE_JACOBIAN_STEP, currentV, scratch, 0)
val dxDu = (scratch[0] - (residualX + targetX)) / WARP_INVERSE_JACOBIAN_STEP
val dyDu = (scratch[1] - (residualY + targetY)) / WARP_INVERSE_JACOBIAN_STEP
warpApply(cp, cols, rows, bilinear, currentU, currentV + WARP_INVERSE_JACOBIAN_STEP, scratch, 0)
val dxDv = (scratch[0] - (residualX + targetX)) / WARP_INVERSE_JACOBIAN_STEP
val dyDv = (scratch[1] - (residualY + targetY)) / WARP_INVERSE_JACOBIAN_STEP
val determinant = dxDu * dyDv - dxDv * dyDu
if (abs(determinant) < 1e-12f) {
break
}
var stepU = (-residualX * dyDv + dxDv * residualY) / determinant
var stepV = (-residualY * dxDu + dyDu * residualX) / determinant
val stepLength = sqrt(stepU * stepU + stepV * stepV)
if (stepLength > WARP_INVERSE_MAX_STEP) {
val damping = WARP_INVERSE_MAX_STEP / stepLength
stepU *= damping
stepV *= damping
}
currentU += stepU
currentV += stepV
}
outUOutV[0] = bestU
outUOutV[1] = bestV
}
private fun warpInverseToleranceSquared(cp: FloatArray): Float {
var minX = Float.MAX_VALUE
var maxX = -Float.MAX_VALUE
var minY = Float.MAX_VALUE
var maxY = -Float.MAX_VALUE
val pointCount = cp.size / 2
for (pointIndex in 0 until pointCount) {
val x = cp[pointIndex * 2]
val y = cp[pointIndex * 2 + 1]
minX = minOf(minX, x)
maxX = maxOf(maxX, x)
minY = minOf(minY, y)
maxY = maxOf(maxY, y)
}
val span = max(maxX - minX, maxY - minY)
val tolerance = max(1e-5f * span, 1e-6f)
return tolerance * tolerance
}
/**
* Maps interleaved points through a warp lattice (forward).
*
* @param FloatArray points Interleaved child-local positions.
* @param FloatArray cp Control points.
* @param Int cols Columns.
* @param Int rows Rows.
* @param Boolean bilinear Blend mode.
* @return FloatArray Fresh parent-local positions.
*/
fun mapPointsThroughWarpLattice(
points: FloatArray,
cp: FloatArray,
cols: Int,
rows: Int,
bilinear: Boolean,
): FloatArray {
val out = FloatArray(points.size)
val scratch = FloatArray(2)
var index = 0
while (index + 1 < points.size) {
warpApply(cp, cols, rows, bilinear, points[index], points[index + 1], scratch, 0)
out[index] = scratch[0]
out[index + 1] = scratch[1]
index += 2
}
return out
}
/**
* Inverse-maps interleaved parent-local points into a warp's UV, seeding each point from a normalized
* guess against the lattice control-point AABB.
*
* @param FloatArray points Interleaved parent-local positions.
* @param FloatArray cp Control points.
* @param Int cols Columns.
* @param Int rows Rows.
* @param Boolean bilinear Blend mode.
* @return FloatArray Fresh child-local UV positions.
*/
fun invertPointsThroughWarpLattice(
points: FloatArray,
cp: FloatArray,
cols: Int,
rows: Int,
bilinear: Boolean,
): FloatArray {
var minX = Float.POSITIVE_INFINITY
var minY = Float.POSITIVE_INFINITY
var maxX = Float.NEGATIVE_INFINITY
var maxY = Float.NEGATIVE_INFINITY
var index = 0
while (index + 1 < cp.size) {
minX = minOf(minX, cp[index])
maxX = maxOf(maxX, cp[index])
minY = minOf(minY, cp[index + 1])
maxY = maxOf(maxY, cp[index + 1])
index += 2
}
val width = max(maxX - minX, 1e-6f)
val height = max(maxY - minY, 1e-6f)
val out = FloatArray(points.size)
val uv = FloatArray(2)
index = 0
while (index + 1 < points.size) {
uv[0] = (points[index] - minX) / width
uv[1] = (points[index + 1] - minY) / height
invertWarpApply(cp, cols, rows, bilinear, points[index], points[index + 1], uv)
out[index] = uv[0]
out[index + 1] = uv[1]
index += 2
}
return out
}
@@ -0,0 +1,247 @@
package org.umamo.runtime.keyform
import org.umamo.runtime.eval.EPS_KEY
import org.umamo.runtime.model.ChannelGrids
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.Deformer
import org.umamo.runtime.model.FormChannel
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.Part
import org.umamo.runtime.model.PuppetModel
import org.umamo.runtime.model.RenderGroup
/*
* The post-import compaction pass: reduce every channel track to the axes and keys it actually needs, and
* lift a track that never varies into its owner's static field.
*
* Cubism keys every channel on every cell of one bundled grid, so straight after the fan-out a typical
* drawable's opacity track is the same value repeated across the whole grid. Compacting retires those
* tracks entirely, which is what turns an imported Cubism rig into a sparse Umamo one - and it is where
* the split pays for itself: the per-frame scalar blends collapse into field reads.
*
* Two rules keep this safe:
*
* - GEOMETRY IS NEVER COMPACTED. A toggle-part drawable can carry bit-identical geometry across an axis
* whose keys deliberately do not bracket the parameter's default; dropping that axis would make the
* drawable permanently visible, which is a change to someone's rig, not a change in precision. It
* would also move the delta texture's column layout for no benefit.
* - EXACT ONLY. A key is dropped only when the stored value is bit-equal to the blend of its
* neighbours; see KeyformGridCompaction. A near-miss is a value the rigger chose.
*
* Run as a separate model pass rather than inside the importers so it is independently testable and can be
* switched off wholesale when a result needs bisecting against the un-compacted import.
*
* DEFERRED: three importer special cases are now redundant in principle - Cmo3Import's
* `takeIf { it.axes.isNotEmpty() }` on part tracks, its PartComposite seed from the first form, and
* Moc3Import's deliberate zero-axis single-cell grid. They are left in place because removing them is a
* BEHAVIOUR change, not a cleanup: each decides whether a static part's authored composite or its baked
* keyform wins, and the compaction-on/off equivalence test cannot see the difference (both sides carry the
* special case). Only the corpus parity and C-core oracles would catch a mistake, so they should come out
* one at a time under those gates rather than as a batch.
*/
/**
* One owner's channel tracks after compaction: the tracks that still vary, and the constants lifted out.
*
* @property ChannelGrids channelGrids The surviving tracks.
* @property Map constants The channels that collapsed, and the value each holds everywhere.
*/
private class CompactedChannels(
val channelGrids: ChannelGrids,
val constants: Map<FormChannel, ChannelValue>,
)
/**
* Compacts every track, separating the ones that collapsed to a constant from the ones that still vary.
*
* @param Function axisSpansRange Whether an axis's keys bracket its parameter's whole range - the
* out-of-span gate compaction must preserve (see KeyformGridCompaction's file note).
* @return CompactedChannels The surviving tracks plus the lifted constants.
*/
private fun ChannelGrids.compactedTracks(axisSpansRange: (KeyformAxis) -> Boolean): CompactedChannels {
if (isEmpty) {
return CompactedChannels(this, emptyMap())
}
val surviving = LinkedHashMap<FormChannel, KeyformGrid<ChannelValue>>(gridsByChannel.size)
val constants = LinkedHashMap<FormChannel, ChannelValue>()
for ((channel, grid) in gridsByChannel) {
when (val result = grid.compacted(ChannelValueInterpolator, channel.valueKind, axisSpansRange)) {
is CompactionResult.Constant -> constants[channel] = result.form
is CompactionResult.Reduced -> surviving[channel] = result.grid
}
}
val newGrids = if (surviving.isEmpty()) ChannelGrids.Empty else ChannelGrids(surviving)
return CompactedChannels(newGrids, constants)
}
/**
* A lifted DRAW_ORDER constant resolved against an Int draw-order slot: the integral static to write (or
* null to keep the owner's), and the channel grids to keep.
*
* @property Int? staticDrawOrder The exactly-integral lifted draw order, or null.
* @property ChannelGrids channelGrids The grids to keep - the compacted set, or the compacted set with
* [originalGrids]' DRAW_ORDER track restored when the constant was fractional.
*/
private class LiftedDrawOrder(
val staticDrawOrder: Int?,
val channelGrids: ChannelGrids,
)
/**
* Resolves a lifted DRAW_ORDER constant against an Int draw-order slot.
*
* A part-like owner's static slot is an Int, so a fractional constant would have to round, and rounding
* could reorder two siblings the track kept distinct. Such a track goes back into the kept grids from
* [originalGrids] instead - correct, just not free.
*
* @param Map constants The lifted constants.
* @param ChannelGrids compactedGrids The surviving tracks after compaction.
* @param ChannelGrids originalGrids The owner's pre-compaction tracks (the fractional track's source).
* @return LiftedDrawOrder The static to write (or null) and the grids to keep.
*/
private fun liftedDrawOrder(
constants: Map<FormChannel, ChannelValue>,
compactedGrids: ChannelGrids,
originalGrids: ChannelGrids,
): LiftedDrawOrder {
if (constants.hasFractionalDrawOrder()) {
val restored = compactedGrids.gridsByChannel + (FormChannel.DRAW_ORDER to (originalGrids[FormChannel.DRAW_ORDER]!!))
return LiftedDrawOrder(staticDrawOrder = null, channelGrids = ChannelGrids(restored))
}
return LiftedDrawOrder(constants.integralDrawOrderOrNull(), compactedGrids)
}
/**
* This model with every channel track compacted and every collapsed track lifted into its owner's static.
*
* Geometry grids are untouched (see the file note). Evaluation is unchanged to within the tolerance the
* fidelity contract already allows for geometry, and is EXACT wherever a track collapsed to a constant -
* a field read cannot drift the way a weighted sum over corners can. An axis whose keys do not bracket
* its parameter's range is left alone entirely: out-of-span poses fall back to the owner's static, and a
* lift would overwrite exactly the static they fall back to.
*
* @return PuppetModel The compacted model.
*/
fun PuppetModel.withChannelsCompacted(): PuppetModel {
val rangeByParameterId =
parameters.associate { parameter ->
parameter.id to (minOf(parameter.min, parameter.max) to maxOf(parameter.min, parameter.max))
}
// EPS_KEY on both ends: a key the evaluator cannot tell apart from the range end brackets it. An axis
// on a parameter the model does not list is never spanning - a dangling id must stay conservative.
val axisSpansRange: (KeyformAxis) -> Boolean = { axis ->
val range = rangeByParameterId[axis.parameterId]
range != null &&
axis.keys.isNotEmpty() &&
axis.keys.first() <= range.first + EPS_KEY &&
axis.keys.last() >= range.second - EPS_KEY
}
return copy(
drawables =
drawables.map { drawable ->
val compacted = drawable.channelGrids.compactedTracks(axisSpansRange)
if (compacted.constants.isEmpty() && compacted.channelGrids === drawable.channelGrids) {
drawable
} else {
drawable.copy(
channelGrids = compacted.channelGrids,
drawOrder = compacted.constants.scalarOr(FormChannel.DRAW_ORDER, drawable.drawOrder),
opacity = compacted.constants.scalarOr(FormChannel.OPACITY, drawable.opacity),
multiplyColor = compacted.constants.colorOr(FormChannel.MULTIPLY_COLOR, drawable.multiplyColor),
screenColor = compacted.constants.colorOr(FormChannel.SCREEN_COLOR, drawable.screenColor),
)
}
},
deformers = deformers.map { deformer -> deformer.withChannelsCompacted(axisSpansRange) },
parts = parts.map { part -> part.withChannelsCompacted(axisSpansRange) },
glues =
glues.map { glue ->
val compacted = glue.channelGrids.compactedTracks(axisSpansRange)
if (compacted.constants.isEmpty() && compacted.channelGrids === glue.channelGrids) {
glue
} else {
glue.copy(
channelGrids = compacted.channelGrids,
intensity = compacted.constants.scalarOr(FormChannel.GLUE_INTENSITY, glue.intensity),
)
}
},
renderRoot = renderRoot.withChannelsCompacted(axisSpansRange),
)
}
/** This deformer with its channel tracks compacted and any constants lifted into its statics. */
private fun Deformer.withChannelsCompacted(axisSpansRange: (KeyformAxis) -> Boolean): Deformer {
val compacted = channelGrids.compactedTracks(axisSpansRange)
if (compacted.constants.isEmpty() && compacted.channelGrids === channelGrids) {
return this
}
return when (this) {
is Deformer.Warp ->
copy(
channelGrids = compacted.channelGrids,
opacity = compacted.constants.scalarOr(FormChannel.OPACITY, opacity),
multiplyColor = compacted.constants.colorOr(FormChannel.MULTIPLY_COLOR, multiplyColor),
screenColor = compacted.constants.colorOr(FormChannel.SCREEN_COLOR, screenColor),
)
is Deformer.Rotation ->
copy(
channelGrids = compacted.channelGrids,
opacity = compacted.constants.scalarOr(FormChannel.OPACITY, opacity),
multiplyColor = compacted.constants.colorOr(FormChannel.MULTIPLY_COLOR, multiplyColor),
screenColor = compacted.constants.colorOr(FormChannel.SCREEN_COLOR, screenColor),
flipX = compacted.constants.flagOr(FormChannel.FLIP_X, flipX),
flipY = compacted.constants.flagOr(FormChannel.FLIP_Y, flipY),
)
}
}
/**
* This part with its channel tracks compacted, constants lifted into [Part.drawOrder] and the composite.
*
* A collapsed DRAW_ORDER is lifted only when its value is exactly an integer: the part's static slot is an
* Int, so a fractional constant would have to round, and rounding could reorder two parts that the track
* kept distinct. Such a track keeps its (reduced) grid instead - correct, just not free.
*/
private fun Part.withChannelsCompacted(axisSpansRange: (KeyformAxis) -> Boolean): Part {
val compacted = channelGrids.compactedTracks(axisSpansRange)
if (compacted.constants.isEmpty() && compacted.channelGrids === channelGrids) {
return this
}
val lifted = liftedDrawOrder(compacted.constants, compacted.channelGrids, channelGrids)
return copy(
channelGrids = lifted.channelGrids,
drawOrder = lifted.staticDrawOrder ?: drawOrder,
composite =
composite.copy(
opacity = compacted.constants.scalarOr(FormChannel.OPACITY, composite.opacity),
multiplyColor = compacted.constants.colorOr(FormChannel.MULTIPLY_COLOR, composite.multiplyColor),
screenColor = compacted.constants.colorOr(FormChannel.SCREEN_COLOR, composite.screenColor),
),
)
}
/**
* This render group (and its subtree) with its channel tracks compacted.
*
* The render tree carries its own copy of each part's tracks, and for a MOC3 import it is the baked
* authority rather than something derived from the parts - so it is compacted in place instead of being
* re-derived, which would discard the baked order.
*/
private fun RenderGroup.withChannelsCompacted(axisSpansRange: (KeyformAxis) -> Boolean): RenderGroup {
val compacted = channelGrids.compactedTracks(axisSpansRange)
val lifted = liftedDrawOrder(compacted.constants, compacted.channelGrids, channelGrids)
return copy(
drawOrder = lifted.staticDrawOrder ?: drawOrder,
children = children.map { child -> if (child is RenderGroup) child.withChannelsCompacted(axisSpansRange) else child },
channelGrids = lifted.channelGrids,
composite =
composite?.copy(
opacity = compacted.constants.scalarOr(FormChannel.OPACITY, composite.opacity),
multiplyColor = compacted.constants.colorOr(FormChannel.MULTIPLY_COLOR, composite.multiplyColor),
screenColor = compacted.constants.colorOr(FormChannel.SCREEN_COLOR, composite.screenColor),
),
)
}
@@ -0,0 +1,65 @@
package org.umamo.runtime.keyform
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.ColorRgb
import org.umamo.runtime.model.FormChannel
/*
* Readers over a map of lifted channel constants - the values that channel tracks collapsed to, waiting
* to be written into their owner's static fields. Shared by the post-import compaction pass
* (ChannelCompaction) and the parameter-delete collapse (ParameterCrudEdits in :edit), so the two paths
* that lift a track into a static cannot drift apart.
*/
/**
* The lifted constant for [channel] as a float, or [fallback] when the channel did not collapse.
*
* @param FormChannel channel The channel to read.
* @param Float fallback The owner's current static value.
* @return Float The lifted scalar, or [fallback].
*/
fun Map<FormChannel, ChannelValue>.scalarOr(channel: FormChannel, fallback: Float): Float =
(this[channel] as? ChannelValue.Scalar)?.value ?: fallback
/**
* The lifted constant for [channel] as a color, or [fallback] when the channel did not collapse.
*
* @param FormChannel channel The channel to read.
* @param ColorRgb fallback The owner's current static value.
* @return ColorRgb The lifted color, or [fallback].
*/
fun Map<FormChannel, ChannelValue>.colorOr(channel: FormChannel, fallback: ColorRgb): ColorRgb =
(this[channel] as? ChannelValue.Color)?.color ?: fallback
/**
* The lifted constant for [channel] as a flag, or [fallback] when the channel did not collapse.
*
* @param FormChannel channel The channel to read.
* @param Boolean fallback The owner's current static value.
* @return Boolean The lifted flag, or [fallback].
*/
fun Map<FormChannel, ChannelValue>.flagOr(channel: FormChannel, fallback: Boolean): Boolean =
(this[channel] as? ChannelValue.Flag)?.flag ?: fallback
/**
* The lifted DRAW_ORDER constant as an exact Int, or null when absent or fractional.
*
* A part-like owner stores its draw order in an Int slot, so a fractional constant cannot lift - rounding
* it could reorder two siblings the track kept distinct. Callers pair this with [hasFractionalDrawOrder]
* to keep such a value as a track instead.
*
* @return Int? The exactly-integral lifted draw order, or null.
*/
fun Map<FormChannel, ChannelValue>.integralDrawOrderOrNull(): Int? {
val lifted = (this[FormChannel.DRAW_ORDER] as? ChannelValue.Scalar) ?: return null
return lifted.value.toInt().takeIf { candidate -> candidate.toFloat() == lifted.value }
}
/**
* Whether a DRAW_ORDER constant was lifted but is fractional and so must stay a track rather than round
* into an Int static slot.
*
* @return Boolean True when DRAW_ORDER collapsed to a non-integral value.
*/
fun Map<FormChannel, ChannelValue>.hasFractionalDrawOrder(): Boolean =
this[FormChannel.DRAW_ORDER] is ChannelValue.Scalar && integralDrawOrderOrNull() == null
@@ -0,0 +1,136 @@
package org.umamo.runtime.keyform
import org.umamo.runtime.model.ChannelGrids
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.FormChannel
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.MeshDeltaForm
import org.umamo.runtime.model.MeshForm
import org.umamo.runtime.model.RotationForm
import org.umamo.runtime.model.RotationPivotForm
import org.umamo.runtime.model.WarpForm
import org.umamo.runtime.model.WarpLatticeForm
/*
* The import fan-out: splitting one bundled keyform grid into a geometry grid plus per-channel tracks.
*
* CMO3 and MOC3 both store an entity's keyforms as a single grid of all-or-nothing cells, so both
* importers keep building exactly that, and the split happens here afterwards. Every fanned track SHARES
* the source grid's axes list by reference and holds one cell per source cell, which makes the split a
* pure re-shape: gridCorners over a fanned track returns the same corners in the same order as over the
* source, and each channel's weighted sum accumulates in the same order the bundled blend used. The
* evaluated result is therefore bit-identical, which is what lets the whole migration be gated on a
* zero-diff oracle run rather than a tolerance.
*
* Compaction is deliberately NOT part of this - it runs as a separate model pass so the split can land
* with the oracle green by construction and compaction can be turned on (and off) independently.
*/
/**
* This grid re-shaped into a channel track, each cell's form mapped through [valueOf].
*
* The axes list is shared by reference, not copied - that identity is what guarantees the track brackets
* every pose exactly as the source grid does.
*
* @param Function valueOf Maps one source form to the channel value it carries.
* @return KeyformGrid The same shape, carrying channel values.
*/
fun <TForm> KeyformGrid<TForm>.asChannelTrack(valueOf: (TForm) -> ChannelValue): KeyformGrid<ChannelValue> =
KeyformGrid(axes, cells.map { cell -> KeyformCell(cell.coordinate, valueOf(cell.form)) })
/**
* This grid re-shaped into a geometry grid, each cell's form mapped through [geometryOf].
*
* @param Function geometryOf Maps one source form to its geometry payload.
* @return KeyformGrid The same shape, carrying geometry forms.
*/
fun <TForm, TGeometry> KeyformGrid<TForm>.asGeometryGrid(geometryOf: (TForm) -> TGeometry): KeyformGrid<TGeometry> =
KeyformGrid(axes, cells.map { cell -> KeyformCell(cell.coordinate, geometryOf(cell.form)) })
/**
* A [ChannelGrids] holding the given tracks, dropping any that is null.
*
* A null track means the owner does not key that channel and reads its static value instead, so an
* all-null call yields the shared empty instance and allocates nothing.
*
* @param Pair tracks The channel-to-track pairs; null tracks are omitted.
* @return ChannelGrids The tracks, or ChannelGrids.Empty when none survive.
*/
fun channelGridsOf(vararg tracks: Pair<FormChannel, KeyformGrid<ChannelValue>?>): ChannelGrids {
val present = LinkedHashMap<FormChannel, KeyformGrid<ChannelValue>>(tracks.size)
for ((channel, grid) in tracks) {
if (grid != null) {
present[channel] = grid
}
}
return if (present.isEmpty()) ChannelGrids.Empty else ChannelGrids(present)
}
/**
* One deformer's bundled keyform grid, split into its geometry grid and its channel tracks.
*
* @property KeyformGrid geometry The lattice / pivot geometry.
* @property ChannelGrids channels The render (and, for a rotation, reflection) tracks.
*/
class FannedDeformer<TGeometry>(
val geometry: KeyformGrid<TGeometry>,
val channels: ChannelGrids,
)
/**
* Splits a bundled warp grid into its lattice geometry and its render channels.
*
* Shared by both importers rather than written twice, so the two paths cannot drift in which channel a
* value lands on - the failure mode a per-importer copy invites.
*
* @return FannedDeformer The lattice grid plus the opacity / multiply / screen tracks.
*/
fun KeyformGrid<WarpForm>.fanOutWarp(): FannedDeformer<WarpLatticeForm> =
FannedDeformer(
asGeometryGrid { form -> WarpLatticeForm(form.controlPoints) },
channelGridsOf(
FormChannel.OPACITY to asChannelTrack { form -> ChannelValue.Scalar(form.opacity) },
FormChannel.MULTIPLY_COLOR to asChannelTrack { form -> ChannelValue.Color(form.multiplyColor) },
FormChannel.SCREEN_COLOR to asChannelTrack { form -> ChannelValue.Color(form.screenColor) },
),
)
/**
* Splits a bundled rotation grid into its pivot geometry and its channels.
*
* The reflection flags become FLAG tracks here: they snap to the floor cell rather than blending, so they
* cannot ride the pivot form beside values that interpolate.
*
* @return FannedDeformer The pivot grid plus the render and reflection tracks.
*/
fun KeyformGrid<RotationForm>.fanOutRotation(): FannedDeformer<RotationPivotForm> =
FannedDeformer(
asGeometryGrid { form -> RotationPivotForm(form.originX, form.originY, form.angle, form.scale) },
channelGridsOf(
FormChannel.OPACITY to asChannelTrack { form -> ChannelValue.Scalar(form.opacity) },
FormChannel.MULTIPLY_COLOR to asChannelTrack { form -> ChannelValue.Color(form.multiplyColor) },
FormChannel.SCREEN_COLOR to asChannelTrack { form -> ChannelValue.Color(form.screenColor) },
FormChannel.FLIP_X to asChannelTrack { form -> ChannelValue.Flag(form.flipX) },
FormChannel.FLIP_Y to asChannelTrack { form -> ChannelValue.Flag(form.flipY) },
),
)
/**
* Splits a bundled art-mesh grid into its per-vertex deltas and its render channels.
*
* The geometry half is the only channel the GPU consumes, and its cell linear indices are the delta
* texture's column layout - which is why it stays a separate typed grid rather than another map entry.
*
* @return FannedDeformer The delta grid plus the draw-order / opacity / multiply / screen tracks.
*/
fun KeyformGrid<MeshForm>.fanOutMesh(): FannedDeformer<MeshDeltaForm> =
FannedDeformer(
asGeometryGrid { form -> MeshDeltaForm(form.positionDeltas) },
channelGridsOf(
FormChannel.DRAW_ORDER to asChannelTrack { form -> ChannelValue.Scalar(form.drawOrder) },
FormChannel.OPACITY to asChannelTrack { form -> ChannelValue.Scalar(form.opacity) },
FormChannel.MULTIPLY_COLOR to asChannelTrack { form -> ChannelValue.Color(form.multiplyColor) },
FormChannel.SCREEN_COLOR to asChannelTrack { form -> ChannelValue.Color(form.screenColor) },
),
)
@@ -0,0 +1,160 @@
package org.umamo.runtime.keyform
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.ColorRgb
import org.umamo.runtime.model.MeshDeltaForm
import org.umamo.runtime.model.RotationPivotForm
import org.umamo.runtime.model.WarpLatticeForm
/*
* The one interpolation primitive the grid algebra is allowed to use: a 1-D blend between two ADJACENT
* slices of a single axis. The algebra deliberately never performs an N-D blend - that is the evaluator's
* job in runtime.eval, and duplicating it here would put a second, drifting copy of the deformation math
* next to the one the differential oracle checks.
*
* Key insertion, export refinement, and compaction all reduce to this one operation, which is what makes
* the losslessness argument one-dimensional and therefore checkable.
*/
/**
* Blends a form between two adjacent slices of one axis, and tests two stored forms for exact equality.
*
* The [interpolate] contract is strict: it MUST compute `(1 - fraction) * lower + fraction * upper`, the
* same expression `gridCorners` builds its corner weights from - NOT the numerically tidier
* `lower + (upper - lower) * fraction`. Compaction drops a key only when the stored form is bit-equal to
* this function's output, and refinement re-inserts that key by evaluating this same function on the same
* inputs; IEEE-754 is deterministic, so sharing one expression is exactly what makes the two mutual
* inverses. Switching to an algebraically equal formula silently breaks that.
*
* @param TForm The cell payload type this interpolator handles.
*/
interface FormInterpolator<TForm> {
/**
* The form [fraction] of the way from [lower] to [upper].
*
* @param TForm lower The form at the lower key.
* @param TForm upper The form at the next key up.
* @param Float fraction The blend position in 0..1 (0 yields [lower], 1 yields [upper]).
* @return TForm The blended form.
*/
fun interpolate(lower: TForm, upper: TForm, fraction: Float): TForm
/**
* Whether two stored forms are EXACTLY equal - bit-equal floats, never an epsilon compare.
*
* Compaction gates on this. An epsilon here would silently alter a rigger's authored values, which
* the fidelity contract forbids; a value that is merely close is a value someone chose.
*
* @param TForm left The first form.
* @param TForm right The second form.
* @return Boolean True when the two forms are exactly equal.
*/
fun isExactlyEqual(left: TForm, right: TForm): Boolean
}
/**
* Blends two floats with the evaluator's own corner-weight expression.
*
* @param Float lower The lower key's value.
* @param Float upper The upper key's value.
* @param Float fraction The blend position in 0..1.
* @return Float The blended value.
*/
internal fun blendScalar(lower: Float, upper: Float, fraction: Float): Float = (1f - fraction) * lower + fraction * upper
/**
* Blends two interleaved float arrays component-wise.
*
* A length mismatch is a malformed grid rather than something to paper over, so the result takes the
* shorter length and the caller's own vertex-count guards catch it - matching how the evaluator's blend
* sites already tolerate a short delta array.
*
* @param FloatArray lower The lower key's components.
* @param FloatArray upper The upper key's components.
* @param Float fraction The blend position in 0..1.
* @return FloatArray The blended components.
*/
internal fun blendComponents(lower: FloatArray, upper: FloatArray, fraction: Float): FloatArray {
val length = minOf(lower.size, upper.size)
val blended = FloatArray(length)
for (componentIndex in 0 until length) {
blended[componentIndex] = blendScalar(lower[componentIndex], upper[componentIndex], fraction)
}
return blended
}
/** Interpolates a drawable's per-vertex position deltas. */
object MeshDeltaInterpolator : FormInterpolator<MeshDeltaForm> {
override fun interpolate(lower: MeshDeltaForm, upper: MeshDeltaForm, fraction: Float): MeshDeltaForm =
MeshDeltaForm(blendComponents(lower.positionDeltas, upper.positionDeltas, fraction))
override fun isExactlyEqual(left: MeshDeltaForm, right: MeshDeltaForm): Boolean =
left.positionDeltas.contentEquals(right.positionDeltas)
}
/** Interpolates a warp deformer's absolute lattice control points. */
object WarpLatticeInterpolator : FormInterpolator<WarpLatticeForm> {
override fun interpolate(lower: WarpLatticeForm, upper: WarpLatticeForm, fraction: Float): WarpLatticeForm =
WarpLatticeForm(blendComponents(lower.controlPoints, upper.controlPoints, fraction))
override fun isExactlyEqual(left: WarpLatticeForm, right: WarpLatticeForm): Boolean =
left.controlPoints.contentEquals(right.controlPoints)
}
/** Interpolates a rotation deformer's absolute pivot transform (its flags are FLAG channels, not geometry). */
object RotationPivotInterpolator : FormInterpolator<RotationPivotForm> {
override fun interpolate(lower: RotationPivotForm, upper: RotationPivotForm, fraction: Float): RotationPivotForm =
RotationPivotForm(
originX = blendScalar(lower.originX, upper.originX, fraction),
originY = blendScalar(lower.originY, upper.originY, fraction),
angle = blendScalar(lower.angle, upper.angle, fraction),
scale = blendScalar(lower.scale, upper.scale, fraction),
)
override fun isExactlyEqual(left: RotationPivotForm, right: RotationPivotForm): Boolean =
left.originX == right.originX &&
left.originY == right.originY &&
left.angle == right.angle &&
left.scale == right.scale
}
/**
* Interpolates a channel track's value.
*
* Scalars and colors blend; a FLAG snaps to [lower], which is the floor cell. That matches the evaluator
* exactly: `gridCorners` seeds a single corner and appends the lower-key split before the upper-key one,
* so `corners[0]` is always the all-lower-key corner - and that is the corner the rotation flags already
* read today. A mismatched pair (two different kinds in one track) is a malformed track; [lower] wins,
* so the track keeps its own kind rather than silently changing type mid-axis.
*/
object ChannelValueInterpolator : FormInterpolator<ChannelValue> {
override fun interpolate(lower: ChannelValue, upper: ChannelValue, fraction: Float): ChannelValue =
when (lower) {
is ChannelValue.Scalar -> {
if (upper is ChannelValue.Scalar) {
ChannelValue.Scalar(blendScalar(lower.value, upper.value, fraction))
} else {
lower
}
}
is ChannelValue.Color -> {
if (upper is ChannelValue.Color) {
ChannelValue.Color(
ColorRgb(
blendScalar(lower.color.red, upper.color.red, fraction),
blendScalar(lower.color.green, upper.color.green, fraction),
blendScalar(lower.color.blue, upper.color.blue, fraction),
),
)
} else {
lower
}
}
// A boolean has no midpoint: the floor cell wins for the whole span, matching the evaluator.
is ChannelValue.Flag -> lower
}
override fun isExactlyEqual(left: ChannelValue, right: ChannelValue): Boolean = left == right
}
@@ -0,0 +1,658 @@
package org.umamo.runtime.keyform
import org.umamo.runtime.eval.EPS_KEY
import org.umamo.runtime.eval.EPS_SPAN
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import kotlin.math.abs
/*
* The keyform-grid authoring algebra: bind an entity to a parameter, insert / remove a key, write a cell,
* capture a form at the current pose, and refine a grid onto a wider key set for export.
*
* Two invariants run through all of it, both forced by how the evaluator brackets a pose (see
* runtime.eval.bindBracket):
*
* 1. An axis must SPAN its parameter's range. A pose outside an axis's keys makes bindBracket return
* null, which hides the entity outright for a geometry grid and drops a channel to its static value.
* So seeding always reaches min and max, and "arbitrary key positions" means arbitrary INTERIOR keys.
* 2. An axis must keep at least TWO keys. A single-key axis resolves only within EPS_KEY of that key
* and is null everywhere else, so removing down to one key is a vanishing trap - removal collapses
* the axis instead.
*
* A new axis is always APPENDED, never spliced in parameter order: the cell linear index folds axis 0 as
* the fastest-varying, so appending leaves every existing cell's index (and therefore the GPU delta
* texture's column layout) untouched, while an insert in the middle renumbers all of them.
*
* Sparse grids - which Cmo3Import can produce when a cell's form guid does not resolve - are refused
* rather than repaired: every op below returns its receiver unchanged instead of inventing cells.
*/
/** What [withKeyInserted] does with a key that falls outside the axis's existing key span. */
enum class OutOfSpanKeyPolicy {
/**
* Widen the axis, replicating the nearest end slice into the new one. Constant extrapolation, never
* linear: extending a trend past its last authored key would invent motion the rigger never made.
*/
Extend,
/** Leave the grid alone. */
Reject,
}
/**
* This grid with a new axis for [parameter] appended, every existing cell replicated across its keys.
*
* Binding an entity to a parameter for the first time. A null receiver seeds a brand new grid holding
* [currentForm] at every key; an existing grid is replicated once per new key, so the entity looks exactly
* as it did before at every pose - binding alone never changes the render, only the capture that follows
* does.
*
* Returns the receiver unchanged when the grid already keys [parameter] (the bind is already true), and
* NULL on a refusal - a sparse receiver, or a parameter whose range cannot support two distinct keys (a
* min == max parameter is not animatable, and a one-key axis would hide the entity). Null rather than
* the receiver, so a caller's `?: return` refusal guard fires for a non-null receiver too - returning the
* receiver here once let a capture proceed and write onto the channel's OTHER axes.
*
* The seeded keys are the parameter's minimum, default, and maximum, deduplicated - what Cubism seeds, and
* the only layout that both spans the range and puts a key at the neutral pose. A fourth key at the
* current scrub was tried and dropped: the capture that follows a bind lands at the scrub anyway, so the
* extra key changed nothing except to author one the rigger never asked for.
*
* @param Parameter parameter The parameter to bind to; its min / default / max define the seeded keys.
* @param TForm currentForm The form to hold at every seeded key (the entity's present look).
* @return KeyformGrid The grid with the axis appended, the receiver when it already keys [parameter], or
* null when nothing could be seeded.
*/
fun <TForm> KeyformGrid<TForm>?.withAxisSeeded(parameter: Parameter, currentForm: TForm): KeyformGrid<TForm>? {
if (this != null && axisIndexOf(parameter.id) >= 0) {
return this
}
if (this != null && !isDense) {
return null
}
val seedKeys = distinctSortedKeys(floatArrayOf(parameter.min, parameter.default, parameter.max))
if (seedKeys.size < 2) {
return null
}
val newAxis = KeyformAxis(parameter.id, seedKeys)
if (this == null) {
val cells = seedKeys.indices.map { keyIndex -> KeyformCell(intArrayOf(keyIndex), currentForm) }
return KeyformGrid(listOf(newAxis), cells)
}
// Appended, so every existing coordinate keeps its meaning and simply gains a trailing component.
val replicated =
buildList {
for (keyIndex in seedKeys.indices) {
for (cell in cells) {
add(KeyformCell(cell.coordinate + keyIndex, cell.form))
}
}
}
return KeyformGrid(axes + newAxis, replicated)
}
/**
* This grid with a new key at [keyValue] on [parameterId]'s axis, filling the whole new slice.
*
* Inserting a key adds an entire hyperplane of cells, not one cell: on a grid keyed over two parameters,
* a new key on the first axis needs one new cell for every key of the second. Only the interior cells can
* be derived, by blending the two neighbouring slices with [interpolator] - which is exactly the operation
* the export refinement performs, so the two share this code rather than growing a second copy.
*
* Returns the receiver unchanged when the axis is absent, the grid is sparse, [keyValue] is within EPS_KEY
* of an existing key, the insertion would leave a span below EPS_SPAN (a span that narrow evaluates as a
* step rather than a blend), or the key falls outside the span under [OutOfSpanKeyPolicy.Reject].
*
* @param ParameterId parameterId The axis to insert into.
* @param Float keyValue The parameter value of the new key.
* @param FormInterpolator interpolator Blends the neighbouring slices into the new one.
* @param OutOfSpanKeyPolicy outOfSpan How to treat a key beyond the axis's current ends.
* @return KeyformGrid The grid with the key inserted, or the receiver when the insert was refused.
*/
fun <TForm> KeyformGrid<TForm>.withKeyInserted(
parameterId: ParameterId,
keyValue: Float,
interpolator: FormInterpolator<TForm>,
outOfSpan: OutOfSpanKeyPolicy = OutOfSpanKeyPolicy.Extend,
): KeyformGrid<TForm> {
val axisIndex = axisIndexOf(parameterId)
if (axisIndex < 0 || !isDense) {
return this
}
val oldKeys = axes[axisIndex].keys
if (oldKeys.isEmpty()) {
return this
}
// Through keyIndexAt, the one definition of the evaluator's on-a-key snap tolerance.
if (keyIndexAt(parameterId, keyValue) >= 0) {
return this
}
// The insert position in the NEW key array: the count of existing keys below the new value.
val insertPosition = oldKeys.count { existing -> existing < keyValue }
val isBelowSpan = insertPosition == 0
val isAboveSpan = insertPosition == oldKeys.size
if ((isBelowSpan || isAboveSpan) && outOfSpan == OutOfSpanKeyPolicy.Reject) {
return this
}
if (!spansStayResolvable(oldKeys, keyValue, insertPosition)) {
return this
}
val newKeys = FloatArray(oldKeys.size + 1)
oldKeys.copyInto(newKeys, destinationOffset = 0, startIndex = 0, endIndex = insertPosition)
newKeys[insertPosition] = keyValue
oldKeys.copyInto(newKeys, destinationOffset = insertPosition + 1, startIndex = insertPosition, endIndex = oldKeys.size)
val formByOldIndex = cells.associate { cell -> linearIndexOf(cell.coordinate) to cell.form }
val newAxes = axes.toMutableList()
newAxes[axisIndex] = KeyformAxis(parameterId, newKeys)
// The source slices for the new one: the two it sits between, or the single nearest end when extending.
val lowerSourceKeyIndex = if (isBelowSpan) 0 else insertPosition - 1
val upperSourceKeyIndex = if (isAboveSpan) oldKeys.size - 1 else insertPosition
val blendFraction =
if (isBelowSpan || isAboveSpan) {
// Constant extrapolation - both source indices are the same slice, so the fraction is inert.
0f
} else {
val span = oldKeys[upperSourceKeyIndex] - oldKeys[lowerSourceKeyIndex]
if (span >= EPS_SPAN) (keyValue - oldKeys[lowerSourceKeyIndex]) / span else 0f
}
val newCells = ArrayList<KeyformCell<TForm>>(cells.size + cells.size / maxOf(1, oldKeys.size) + 1)
// Existing cells keep their forms; those at or past the insert shift one key index up.
for (cell in cells) {
val shifted = cell.coordinate.copyOf()
if (shifted[axisIndex] >= insertPosition) {
shifted[axisIndex] = shifted[axisIndex] + 1
}
newCells.add(KeyformCell(shifted, cell.form))
}
// One new cell per combination of the OTHER axes, enumerated from any single existing slice.
for (cell in cells) {
if (cell.coordinate[axisIndex] != 0) {
continue
}
val lowerCoordinate = cell.coordinate.copyOf().also { it[axisIndex] = lowerSourceKeyIndex }
val upperCoordinate = cell.coordinate.copyOf().also { it[axisIndex] = upperSourceKeyIndex }
val lowerForm = formByOldIndex[linearIndexOf(lowerCoordinate)] ?: continue
val upperForm = formByOldIndex[linearIndexOf(upperCoordinate)] ?: continue
val insertedForm =
if (lowerSourceKeyIndex == upperSourceKeyIndex) {
lowerForm
} else {
interpolator.interpolate(lowerForm, upperForm, blendFraction)
}
val insertedCoordinate = cell.coordinate.copyOf().also { it[axisIndex] = insertPosition }
newCells.add(KeyformCell(insertedCoordinate, insertedForm))
}
return KeyformGrid(newAxes.toList(), newCells)
}
/**
* The position key [keyIndex] would actually land on if moved toward [newValue] on [parameterId]'s axis.
*
* Almost always [newValue] itself. It is nudged only to keep every span RESOLVABLE: two keys closer than
* EPS_SPAN make the evaluator read fraction 0 across the gap, so the nearer one becomes unreachable and
* the blend degenerates into a step. That is a correctness floor, not a spacing preference - keys may sit
* as close as the evaluator can still tell apart, and no closer.
*
* Returns null when the axis is absent, the grid is sparse, or the index is out of range.
*
* @param ParameterId parameterId The axis the key sits on.
* @param Int keyIndex The key being moved.
* @param Float newValue The requested destination.
* @return Float? The destination it will take, or null when the move cannot apply.
*/
fun KeyformGrid<*>.keyDestinationFor(parameterId: ParameterId, keyIndex: Int, newValue: Float): Float? {
val axisIndex = axisIndexOf(parameterId)
if (axisIndex < 0 || !isDense) {
return null
}
val keys = axes[axisIndex].keys
if (keyIndex < 0 || keyIndex >= keys.size) {
return null
}
var nearestIndex = -1
var nearestDistance = Float.MAX_VALUE
for (index in keys.indices) {
if (index == keyIndex) {
continue
}
val distance = abs(keys[index] - newValue)
if (distance < nearestDistance) {
nearestDistance = distance
nearestIndex = index
}
}
if (nearestDistance >= EPS_SPAN || nearestIndex < 0) {
return newValue
}
val nearestOther = keys[nearestIndex]
// Pushed to the side it was already approaching from, so the nudge never reverses the drag.
//
// A dead-on collision has no approach side, and resolving it by direction of travel would push a key
// dropped onto the LAST key out past it - and therefore out of the parameter's range, where the
// evaluator brackets nothing and every entity keyed on it disappears. So an exact tie nudges INWARD,
// toward the middle of the axis, which is always somewhere the axis already reaches.
val approachingFromBelow =
if (newValue == nearestOther) {
nearestOther >= axisMidpointExcluding(keys, keyIndex)
} else {
newValue < nearestOther
}
val nudged = if (approachingFromBelow) nearestOther - EPS_SPAN else nearestOther + EPS_SPAN
// The nudge is measured against the NEAREST key only, so on a crowded axis it can land right on top of
// the next one along - and two axis keys closer than EPS_SPAN is precisely the unresolvable span this
// function exists to prevent (bindBracket gives such a span fraction 0, making the upper key
// unreachable). Rather than hunt for a gap that may not exist, refuse: a move that cannot be made
// resolvable is better left undone than made silently wrong.
return if (collidesBeyond(keys, keyIndex, nearestIndex, nudged)) null else nudged
}
/**
* Whether [value] lands unresolvably close to a key OTHER than [keyIndex] and [nudgedOffIndex].
*
* Both exclusions are necessary and neither is slack. A key cannot collide with itself, and the key the
* nudge was measured off is EPS_SPAN away BY CONSTRUCTION - but `nearest ± EPS_SPAN` is computed in float32
* and rounds, so testing it would reject the very destination just derived. Every other key is a real
* collision: the nudge only ever consults the NEAREST key, so on a crowded axis it can land right on top of
* the next one along, and two keys closer than EPS_SPAN is the unresolvable span this all exists to
* prevent (bindBracket gives such a span fraction 0, making the upper key unreachable).
*
* @param FloatArray keys The axis's keys.
* @param Int keyIndex The key being moved.
* @param Int nudgedOffIndex The key the destination was pushed away from.
* @param Float value The candidate destination.
* @return Boolean True when the destination would be unresolvably close to some third key.
*/
private fun collidesBeyond(keys: FloatArray, keyIndex: Int, nudgedOffIndex: Int, value: Float): Boolean {
for (index in keys.indices) {
if (index != keyIndex && index != nudgedOffIndex && abs(keys[index] - value) < EPS_SPAN) {
return true
}
}
return false
}
/**
* The midpoint of every key except [keyIndex] - which half of the axis a colliding destination is in.
*
* @param FloatArray keys The axis's keys.
* @param Int keyIndex The key being moved, excluded from the span.
* @return Float The midpoint, or the moved key's own value when it is the only one.
*/
private fun axisMidpointExcluding(keys: FloatArray, keyIndex: Int): Float {
var lowest = Float.MAX_VALUE
var highest = -Float.MAX_VALUE
for (index in keys.indices) {
if (index == keyIndex) {
continue
}
lowest = minOf(lowest, keys[index])
highest = maxOf(highest, keys[index])
}
return if (lowest > highest) keys[keyIndex] else (lowest + highest) / 2f
}
/**
* The ordinal a key inserted at [keyValue] would take on [parameterId]'s axis, or -1 when no key is added.
*
* The [keyIndexAfterMove] counterpart, and public for the same reason: an insert renumbers every key at or
* above it, so a caller holding ordinals - the keyform sheet's key selection - has to correct them, and it
* has to do so BEFORE the insert records its step. Counting the keys below the new value is exactly how
* [withKeyInserted] places it, so the two cannot disagree about where it lands.
*
* -1 covers every case that adds nothing: a missing axis, a sparse or empty grid, and a value already
* within the snap tolerance of an existing key. An insert refused for a reason only [withKeyInserted]
* knows (a span below EPS_SPAN, or an out-of-span key under [OutOfSpanKeyPolicy.Reject]) still reports the
* position it would have taken, so a caller that acts on this must confirm against the edit's own outcome.
*
* @param ParameterId parameterId The axis to insert into.
* @param Float keyValue The parameter value of the new key.
* @return Int The new key's ordinal, or -1 when the insert would add none.
*/
fun KeyformGrid<*>.keyIndexAfterInsert(parameterId: ParameterId, keyValue: Float): Int {
val axisIndex = axisIndexOf(parameterId)
if (axisIndex < 0 || !isDense) {
return -1
}
val keys = axes[axisIndex].keys
// Through keyIndexAt, the one definition of the evaluator's on-a-key snap tolerance - the same gate
// withKeyInserted applies before it decides it has anything to add.
if (keys.isEmpty() || keyIndexAt(parameterId, keyValue) >= 0) {
return -1
}
return keys.count { existing -> existing < keyValue }
}
/**
* The ordinal key [keyIndex] would hold after being moved toward [newValue] - its position in the re-sorted
* axis.
*
* A move can REORDER the axis, so the key a caller is holding changes ordinal underneath it. Anything
* tracking that key (the sheet's selection) has to be told where it went.
*
* @param ParameterId parameterId The axis the key sits on.
* @param Int keyIndex The key being moved.
* @param Float newValue The requested destination.
* @return Int The ordinal after the move, or [keyIndex] when the move cannot apply.
*/
fun KeyformGrid<*>.keyIndexAfterMove(parameterId: ParameterId, keyIndex: Int, newValue: Float): Int {
val axisIndex = axisIndexOf(parameterId)
val destination = keyDestinationFor(parameterId, keyIndex, newValue) ?: return keyIndex
val keys = axes[axisIndex].keys
// Its ordinal is simply how many keys end up below it. Ties break toward the mover's old side, which
// is what sortedBy's stability gives the rebuild in withKeyMoved.
var below = 0
for (index in keys.indices) {
if (index == keyIndex) {
continue
}
if (keys[index] < destination || (keys[index] == destination && index < keyIndex)) {
below++
}
}
return below
}
/**
* This grid with key [keyIndex] on [parameterId]'s axis moved to [newValue], carrying its cells with it.
*
* A move changes only WHERE a key sits, never what it holds - which is what makes it a distinct operation
* rather than a remove plus an insert. Re-inserting would rebuild the moved slice by interpolating its
* neighbours, silently discarding whatever the rigger authored there.
*
* A key MAY cross its neighbours, and doing so re-sorts the axis and PERMUTES the cells to match. That
* permutation is the whole cost of allowing it: a cell's coordinate on an axis is a key ORDINAL, and the
* evaluator requires an axis to be ascending - `bindBracket` reads keys[0] / keys[last] as the span ends,
* scans monotonically, and assumes keys[hi] - keys[hi - 1] is positive, while `gridCorners` assumes ordinal
* i + 1 is the next key by VALUE. Re-sorting the keys without moving the cells to match would satisfy
* `isDense` and corrupt silently: forms would apply at the wrong positions and poses inside the real span
* would resolve to nothing, which for a geometry grid hides its entity outright.
*
* The destination is nudged only to keep spans resolvable - see [keyDestinationFor].
*
* Returns the receiver unchanged when the axis is absent, the index is out of range, the grid is sparse, or
* the destination is where the key already sits.
*
* @param ParameterId parameterId The axis the key sits on.
* @param Int keyIndex The key to move.
* @param Float newValue The requested new position.
* @return KeyformGrid The grid with the key moved, or the receiver when nothing moved.
*/
fun <TForm> KeyformGrid<TForm>.withKeyMoved(parameterId: ParameterId, keyIndex: Int, newValue: Float): KeyformGrid<TForm> {
val axisIndex = axisIndexOf(parameterId)
val destination = keyDestinationFor(parameterId, keyIndex, newValue) ?: return this
val keys = axes[axisIndex].keys
if (destination == keys[keyIndex]) {
return this
}
// Re-sort by the value each ordinal ends up holding. sortedBy is stable, so equal values keep their
// old relative order - which cannot happen anyway after the EPS_SPAN nudge, but keeps the mapping total.
val movedValues = FloatArray(keys.size) { index -> if (index == keyIndex) destination else keys[index] }
val oldOrdinalsInNewOrder = keys.indices.sortedBy { index -> movedValues[index] }
val newKeys = FloatArray(keys.size) { newIndex -> movedValues[oldOrdinalsInNewOrder[newIndex]] }
// The inverse mapping is what the cells travel through: a cell sitting at old ordinal o now sits at the
// position o ended up in.
val newOrdinalByOld = IntArray(keys.size)
for (newIndex in oldOrdinalsInNewOrder.indices) {
newOrdinalByOld[oldOrdinalsInNewOrder[newIndex]] = newIndex
}
val newAxes = axes.toMutableList()
newAxes[axisIndex] = KeyformAxis(parameterId, newKeys)
val reordered = oldOrdinalsInNewOrder.withIndex().any { (newIndex, oldIndex) -> newIndex != oldIndex }
if (!reordered) {
// Nothing crossed, so every coordinate still addresses the same cell and the cells can be shared.
return KeyformGrid(newAxes.toList(), cells)
}
val movedCells =
cells.map { cell ->
val coordinate = cell.coordinate.copyOf()
coordinate[axisIndex] = newOrdinalByOld[coordinate[axisIndex]]
KeyformCell(coordinate, cell.form)
}
return KeyformGrid(newAxes.toList(), movedCells)
}
/**
* This grid with key [keyIndex] removed from [parameterId]'s axis, or the axis collapsed entirely when
* too few keys would remain.
*
* Dropping below [collapseBelowKeyCount] keys collapses the axis (via [withAxisCollapsed]) rather than
* leaving a stub: a single-key axis resolves only within EPS_KEY of its key and hides the entity
* everywhere else, so "remove the second-to-last key" would otherwise make the entity vanish. Collapsing
* the last remaining axis returns null - the entity becomes unkeyed.
*
* @param ParameterId parameterId The axis to remove a key from.
* @param Int keyIndex The key's index on that axis.
* @param Int collapseBelowKeyCount The key count below which the axis collapses instead; two by default,
* which the exporter can lower when it deliberately wants a degenerate axis.
* @return KeyformGrid The reduced grid, the receiver when the removal was refused, or null when the entity
* is left with no axes at all.
*/
fun <TForm> KeyformGrid<TForm>.withKeyRemoved(
parameterId: ParameterId,
keyIndex: Int,
collapseBelowKeyCount: Int = 2,
): KeyformGrid<TForm>? {
val axisIndex = axisIndexOf(parameterId)
if (axisIndex < 0 || !isDense) {
return this
}
val oldKeys = axes[axisIndex].keys
if (keyIndex < 0 || keyIndex >= oldKeys.size) {
return this
}
if (oldKeys.size - 1 < collapseBelowKeyCount) {
// Keep whichever key survives the removal, so the collapsed slice is the one the rigger kept.
val survivingKeyIndex = if (keyIndex == 0) minOf(1, oldKeys.size - 1) else keyIndex - 1
return withAxisCollapsed(parameterId, oldKeys[survivingKeyIndex])
}
val newKeys = FloatArray(oldKeys.size - 1)
oldKeys.copyInto(newKeys, destinationOffset = 0, startIndex = 0, endIndex = keyIndex)
oldKeys.copyInto(newKeys, destinationOffset = keyIndex, startIndex = keyIndex + 1, endIndex = oldKeys.size)
val newAxes = axes.toMutableList()
newAxes[axisIndex] = KeyformAxis(parameterId, newKeys)
val newCells =
cells.mapNotNull { cell ->
val keyOnAxis = cell.coordinate[axisIndex]
when {
keyOnAxis == keyIndex -> null
keyOnAxis > keyIndex -> KeyformCell(cell.coordinate.copyOf().also { it[axisIndex] = keyOnAxis - 1 }, cell.form)
else -> cell
}
}
return KeyformGrid(newAxes.toList(), newCells)
}
/**
* This grid with the cell at [coordinate] holding [form], appending the cell when it is absent.
*
* The write half of a capture: the shape work is already done by the time this runs, so it never changes
* the axes. A coordinate whose length does not match the axis count is refused.
*
* @param IntArray coordinate The target cell's key index per axis.
* @param TForm form The form to store there.
* @return KeyformGrid The grid with the cell written, or the receiver when the coordinate does not fit.
*/
fun <TForm> KeyformGrid<TForm>.withCellWritten(coordinate: IntArray, form: TForm): KeyformGrid<TForm> {
if (coordinate.size != axes.size) {
return this
}
val targetIndex = linearIndexOf(coordinate)
var replaced = false
val newCells =
cells.map { cell ->
if (!replaced && linearIndexOf(cell.coordinate) == targetIndex) {
replaced = true
KeyformCell(coordinate.copyOf(), form)
} else {
cell
}
}
return if (replaced) {
KeyformGrid(axes, newCells)
} else {
KeyformGrid(axes, newCells + KeyformCell(coordinate.copyOf(), form))
}
}
/**
* This grid with [form] captured at [pose] - the keyform-insertion operation behind Blender-style `I`.
*
* Inserts a key on every axis whose pose value does not already land on one (each insert filling its whole
* slice by interpolation, so the entity's look is unchanged everywhere else), then writes [form] into the
* single cell the pose now sits exactly on. Because the capture always lands on a key, the write is a
* plain assignment - there is never a blend to invert.
*
* Returns the receiver when the grid is sparse, or when an axis's pose value cannot be turned into a key
* (out of span under a rejecting policy, or too close to an existing key to be distinguishable).
*
* @param Function pose The current value per parameter id.
* @param TForm form The form to capture.
* @param FormInterpolator interpolator Fills each newly inserted slice.
* @return KeyformGrid The grid with the capture written.
*/
fun <TForm> KeyformGrid<TForm>.withFormCaptured(
pose: (ParameterId) -> Float,
form: TForm,
interpolator: FormInterpolator<TForm>,
): KeyformGrid<TForm> {
if (!isDense || axes.isEmpty()) {
return this
}
var working = this
for (axis in axes) {
val poseValue = pose(axis.parameterId)
// keyIndexAt is the one definition of the on-a-key snap; inlining the epsilon here once let the
// capture and the sheet UI disagree about whether the pose sits on a key.
if (working.keyIndexAt(axis.parameterId, poseValue) >= 0) {
continue
}
working = working.withKeyInserted(axis.parameterId, poseValue, interpolator)
}
val coordinate = IntArray(working.axes.size)
for (axisIndex in working.axes.indices) {
val axis = working.axes[axisIndex]
val poseValue = pose(axis.parameterId)
val keyIndex = working.keyIndexAt(axis.parameterId, poseValue)
if (keyIndex < 0) {
// An axis refused its key (a degenerate span, say); writing a neighbouring cell would silently
// retarget the capture, so leave the grid untouched instead.
return this
}
coordinate[axisIndex] = keyIndex
}
return working.withCellWritten(coordinate, form)
}
/**
* This grid refined onto a wider key set, for lowering a rig to a format that shares key positions.
*
* SPAN-CLAMPED on purpose. For an axis this grid already has, only union keys strictly inside its own
* first..last span are inserted; the span itself is never widened. Widening it would resurrect a drawable
* that its author deliberately keyed to vanish outside a narrow range - the toggle-part pattern - which is
* a rig-altering change, not a rounding one. For a parameter this grid does NOT key, a new axis is
* appended spanning the union plus the parameter's own min and max, with the whole grid replicated across
* it: the channel is constant along that axis, so the widening carries no motion and cannot mislead.
*
* Refining is the exact inverse of compaction: both go through [interpolator], so a key dropped because it
* was bit-equal to its interpolated neighbours is restored bit-equal here.
*
* @param Map unionKeysByParameter The key positions to refine onto, per parameter.
* @param Map parameterRanges Each parameter's min..max, used only when appending an axis this grid lacks.
* @param FormInterpolator interpolator Blends each inserted slice.
* @return KeyformGrid The refined grid, or the receiver when it is sparse.
*/
fun <TForm> KeyformGrid<TForm>.refinedToUnion(
unionKeysByParameter: Map<ParameterId, FloatArray>,
parameterRanges: Map<ParameterId, ClosedFloatingPointRange<Float>>,
interpolator: FormInterpolator<TForm>,
): KeyformGrid<TForm> {
if (!isDense) {
return this
}
var working = this
for ((parameterId, unionKeys) in unionKeysByParameter) {
val axisIndex = working.axisIndexOf(parameterId)
if (axisIndex >= 0) {
val ownKeys = working.axes[axisIndex].keys
if (ownKeys.isEmpty()) {
continue
}
val spanStart = ownKeys.first()
val spanEnd = ownKeys.last()
for (unionKey in unionKeys.sortedArray()) {
if (unionKey > spanStart && unionKey < spanEnd) {
working = working.withKeyInserted(parameterId, unionKey, interpolator, OutOfSpanKeyPolicy.Reject)
}
}
} else {
val range = parameterRanges[parameterId] ?: continue
val appendedKeys = distinctSortedKeys(unionKeys + range.start + range.endInclusive)
if (appendedKeys.size < 2) {
continue
}
val newAxis = KeyformAxis(parameterId, appendedKeys)
val replicated =
buildList {
for (keyIndex in appendedKeys.indices) {
for (cell in working.cells) {
add(KeyformCell(cell.coordinate + keyIndex, cell.form))
}
}
}
working = KeyformGrid(working.axes + newAxis, replicated)
}
}
return working
}
/**
* The given key candidates sorted ascending with near-duplicates (within EPS_KEY) merged.
*
* Merging on the evaluator's own snap tolerance rather than exact equality: two keys closer than EPS_KEY
* are indistinguishable to bindBracket, so keeping both would build an axis with a span the evaluator
* treats as a step.
*
* @param FloatArray candidates The raw key values, in any order.
* @return FloatArray The sorted, de-duplicated keys.
*/
private fun distinctSortedKeys(candidates: FloatArray): FloatArray {
val sorted = candidates.sortedArray()
val kept = ArrayList<Float>(sorted.size)
for (candidate in sorted) {
if (kept.isEmpty() || abs(kept.last() - candidate) >= EPS_KEY) {
kept.add(candidate)
}
}
return kept.toFloatArray()
}
/**
* Whether inserting [keyValue] at [insertPosition] leaves every span on the axis wide enough to evaluate.
*
* A span below EPS_SPAN yields blend fraction 0 in bindBracket, so the lower key holds for the whole span
* and the upper key becomes unreachable - a grid the evaluator cannot resolve as authored.
*
* @param FloatArray existingKeys The axis's current keys, ascending.
* @param Float keyValue The candidate key value.
* @param Int insertPosition The index the key would take in the new array.
* @return Boolean True when both neighbouring spans stay at or above EPS_SPAN.
*/
private fun spansStayResolvable(existingKeys: FloatArray, keyValue: Float, insertPosition: Int): Boolean {
if (insertPosition > 0 && keyValue - existingKeys[insertPosition - 1] < EPS_SPAN) {
return false
}
if (insertPosition < existingKeys.size && existingKeys[insertPosition] - keyValue < EPS_SPAN) {
return false
}
return true
}
@@ -0,0 +1,320 @@
package org.umamo.runtime.keyform
import org.umamo.runtime.eval.EPS_SPAN
import org.umamo.runtime.model.ChannelValueKind
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.ParameterId
/*
* Exact-only keyform-grid compaction: drop every axis a track does not actually vary along, and every
* interior key that is bit-equal to the blend of its neighbours.
*
* This is what turns an imported Cubism rig into a sparse Umamo one. Cubism keys every channel on every
* cell of one bundled grid, so after the per-channel fan-out a typical drawable's opacity track is the
* same value repeated across the whole grid; compacting it to a constant retires the track entirely and
* the owner's static field takes over.
*
* EXACT, never an epsilon. A key that is merely close to its interpolated neighbours is a value the
* rigger chose, and silently replacing it would alter their rig - which the fidelity contract forbids.
* The greedy drop test compares against the same FormInterpolator expression refinedToUnion re-inserts
* with, and the drop set is then VERIFIED by running refinedToUnion itself and re-keeping any key whose
* restored slice is not bit-identical (two adjacent drops restore through a different rounding sequence
* than the one that justified them): compaction and refinement are mutual inverses by construction.
*
* OUT-OF-SPAN SAFETY. A pose outside any axis's key span makes the whole track fall back to its owner's
* static, so an axis whose keys do not bracket the parameter's range acts as a GATE - dropping it (or
* lifting the track to a constant that overwrites the static) would change what those poses render. The
* caller supplies the axis-spans-range predicate; a non-spanning axis is never dropped and a track whose
* last axis is non-spanning is never lifted.
*/
/**
* The outcome of compacting one track.
*
* @param TForm The cell payload type.
*/
sealed interface CompactionResult<TForm> {
/**
* The track never varies - it holds [form] at every pose, so it needs no grid at all and the value
* belongs in its owner's static field.
*/
class Constant<TForm>(val form: TForm) : CompactionResult<TForm>
/** The track still varies; [grid] is it, with the redundant axes and keys removed. */
class Reduced<TForm>(val grid: KeyformGrid<TForm>) : CompactionResult<TForm>
}
/**
* This grid with every redundant axis and interior key removed, or the constant it collapses to.
*
* An axis is redundant when every cell is bit-equal along it - the track simply does not respond to that
* parameter. An interior key is redundant when its whole slice is bit-equal to the blend of the slices on
* either side, so the evaluator would produce it anyway. Endpoint keys are never dropped: the blend test
* needs both neighbours, and dropping an endpoint would narrow the axis's span and change when the track
* falls out of range.
*
* A [valueKind] of FLAG restricts compaction to whole axes. A flag snaps to the floor cell rather than
* blending, so "equal to the blend of its neighbours" is not the right test for an interior flag key, and
* flag tracks are small enough that the conservatism costs nothing.
*
* A sparse grid is returned unchanged as [CompactionResult.Reduced] - the missing cells cannot be tested,
* and inventing them would be a repair this layer has no business making.
*
* @param FormInterpolator interpolator The blend and exact-equality tests; must be the same one
* [refinedToUnion] will later re-insert with.
* @param ChannelValueKind? valueKind The track's value kind when it is a channel track, or null for a
* geometry grid (which blends like a scalar).
* @param Function axisSpansRange Whether an axis's keys bracket its parameter's whole range. A
* non-spanning axis gates the track's out-of-span fallback to the owner's static, so it is never
* dropped and never lifted; channel compaction MUST pass the model-derived predicate (the permissive
* default exists for shape-only tests and single-grid callers with no parameter table in reach).
* @return CompactionResult The constant the track collapses to, or the reduced grid.
*/
fun <TForm> KeyformGrid<TForm>.compacted(
interpolator: FormInterpolator<TForm>,
valueKind: ChannelValueKind? = null,
axisSpansRange: (KeyformAxis) -> Boolean = { true },
): CompactionResult<TForm> {
if (!isDense) {
return CompactionResult.Reduced(this)
}
val allowsInteriorKeyDrop = valueKind != ChannelValueKind.FLAG
var working = this
// Axes first: dropping one shrinks every later pass, and it can expose a key that is now interpolable.
// The last axis is left for the constant check below, which has the form to hand back to the owner.
var axisIndex = 0
while (axisIndex < working.axes.size) {
if (working.axes.size > 1 && axisSpansRange(working.axes[axisIndex]) && working.isConstantAlong(axisIndex, interpolator)) {
working = working.withAxisDropped(axisIndex)
} else {
axisIndex++
}
}
// A single remaining axis that the track does not vary along leaves one constant form for the owner -
// but only when the axis spans its range, else out-of-span poses must keep falling to the static.
if (working.axes.size == 1 && axisSpansRange(working.axes[0]) && working.isConstantAlong(0, interpolator)) {
val soleForm = working.cells.firstOrNull()?.form ?: return CompactionResult.Reduced(working)
return CompactionResult.Constant(soleForm)
}
if (working.axes.isEmpty()) {
val soleForm = working.cells.firstOrNull()?.form ?: return CompactionResult.Reduced(working)
return CompactionResult.Constant(soleForm)
}
if (!allowsInteriorKeyDrop) {
return CompactionResult.Reduced(working)
}
return CompactionResult.Reduced(working.withVerifiedInteriorKeyDrops(interpolator))
}
/**
* This grid with every interior key dropped whose restoration by [refinedToUnion] is bit-exact.
*
* The greedy pass validates each drop against the CURRENT neighbours, but a neighbour used to justify a
* drop can itself drop later, and refinedToUnion then re-blends the first key from the surviving
* endpoints - a different IEEE-754 rounding sequence that matches only algebraically. So the greedy
* result is verified by running the ACTUAL inverse and re-keeping every key involved in a slice that did
* not restore bit-identically, until the round trip verifies.
*
* Terminates: a mismatched cell always involves at least one dropped key (a cell whose keys all survived
* is carried verbatim), so every iteration moves at least one key from dropped to kept.
*
* @param FormInterpolator interpolator The blend and exact-equality tests.
* @return KeyformGrid The reduced grid whose refinement restores this grid bit-for-bit.
*/
private fun <TForm> KeyformGrid<TForm>.withVerifiedInteriorKeyDrops(interpolator: FormInterpolator<TForm>): KeyformGrid<TForm> {
val mustKeep = HashMap<ParameterId, MutableSet<Float>>()
while (true) {
val reduced = withGreedyInteriorKeyDrops(interpolator, mustKeep)
if (reduced === this) {
return this
}
val unionKeysByParameter = axes.associate { axis -> axis.parameterId to axis.keys }
val restored = reduced.refinedToUnion(unionKeysByParameter, emptyMap(), interpolator)
val offending = mismatchedKeyValues(restored, interpolator)
if (offending.isEmpty()) {
return reduced
}
for ((parameterId, keyValues) in offending) {
mustKeep.getOrPut(parameterId) { HashSet() }.addAll(keyValues)
}
}
}
/**
* The original greedy interior-key drop pass, skipping any key value listed in [mustKeep].
*
* @param FormInterpolator interpolator The blend and exact-equality tests.
* @param Map mustKeep Key values (per parameter) that a prior verification round proved non-restorable.
* @return KeyformGrid The reduced grid, or this same instance when nothing dropped.
*/
private fun <TForm> KeyformGrid<TForm>.withGreedyInteriorKeyDrops(
interpolator: FormInterpolator<TForm>,
mustKeep: Map<ParameterId, Set<Float>>,
): KeyformGrid<TForm> {
var working = this
for (targetAxisIndex in working.axes.indices) {
var keyIndex = 1
while (keyIndex < working.axes[targetAxisIndex].keys.size - 1) {
val axis = working.axes[targetAxisIndex]
val keptExplicitly = mustKeep[axis.parameterId]?.contains(axis.keys[keyIndex]) == true
if (!keptExplicitly && working.isKeyInterpolable(targetAxisIndex, keyIndex, interpolator)) {
working = working.withKeyIndexDropped(targetAxisIndex, keyIndex)
} else {
keyIndex++
}
}
}
return working
}
/**
* The key values (per parameter) touched by any cell of this grid whose counterpart in [restored] is not
* bit-identical.
*
* Conservative on purpose: every coordinate of a mismatched cell is reported, including keys that were
* never dropped - re-keeping a kept key is a no-op, and the dropped key among them is the one that makes
* the next verification round converge.
*
* @param KeyformGrid restored This grid's shape rebuilt from the reduced grid by [refinedToUnion].
* @param FormInterpolator interpolator Supplies the exact-equality test.
* @return Map The offending key values per parameter; empty when the round trip is bit-exact.
*/
private fun <TForm> KeyformGrid<TForm>.mismatchedKeyValues(
restored: KeyformGrid<TForm>,
interpolator: FormInterpolator<TForm>,
): Map<ParameterId, Set<Float>> {
val offending = HashMap<ParameterId, MutableSet<Float>>()
val restoredByIndex = restored.cells.associate { cell -> restored.linearIndexOf(cell.coordinate) to cell.form }
for (cell in cells) {
val counterpart = restoredByIndex[linearIndexOf(cell.coordinate)]
if (counterpart != null && interpolator.isExactlyEqual(counterpart, cell.form)) {
continue
}
for (axisIndex in axes.indices) {
val axis = axes[axisIndex]
offending.getOrPut(axis.parameterId) { HashSet() }.add(axis.keys[cell.coordinate[axisIndex]])
}
}
return offending
}
/**
* Whether every cell of this grid is bit-equal to its counterpart at key index 0 along [axisIndex].
*
* @param Int axisIndex The axis to test.
* @param FormInterpolator interpolator Supplies the exact-equality test.
* @return Boolean True when the track does not vary along that axis.
*/
private fun <TForm> KeyformGrid<TForm>.isConstantAlong(axisIndex: Int, interpolator: FormInterpolator<TForm>): Boolean {
val keyCount = axes[axisIndex].keys.size
if (keyCount <= 1) {
return true
}
val formByIndex = cells.associate { cell -> linearIndexOf(cell.coordinate) to cell.form }
for (cell in cells) {
if (cell.coordinate[axisIndex] == 0) {
continue
}
val baseCoordinate = cell.coordinate.copyOf().also { it[axisIndex] = 0 }
val baseForm = formByIndex[linearIndexOf(baseCoordinate)] ?: return false
if (!interpolator.isExactlyEqual(baseForm, cell.form)) {
return false
}
}
return true
}
/**
* Whether the whole slice at [keyIndex] on [axisIndex] is bit-equal to the blend of its neighbours - so
* the evaluator would reproduce it exactly without the key being stored.
*
* @param Int axisIndex The axis the key sits on.
* @param Int keyIndex The interior key's index.
* @param FormInterpolator interpolator The blend and exact-equality tests.
* @return Boolean True when the key carries no information.
*/
private fun <TForm> KeyformGrid<TForm>.isKeyInterpolable(
axisIndex: Int,
keyIndex: Int,
interpolator: FormInterpolator<TForm>,
): Boolean {
val keys = axes[axisIndex].keys
val span = keys[keyIndex + 1] - keys[keyIndex - 1]
if (span < EPS_SPAN) {
return false
}
val fraction = (keys[keyIndex] - keys[keyIndex - 1]) / span
val formByIndex = cells.associate { cell -> linearIndexOf(cell.coordinate) to cell.form }
for (cell in cells) {
if (cell.coordinate[axisIndex] != keyIndex) {
continue
}
val lowerCoordinate = cell.coordinate.copyOf().also { it[axisIndex] = keyIndex - 1 }
val upperCoordinate = cell.coordinate.copyOf().also { it[axisIndex] = keyIndex + 1 }
val lowerForm = formByIndex[linearIndexOf(lowerCoordinate)] ?: return false
val upperForm = formByIndex[linearIndexOf(upperCoordinate)] ?: return false
if (!interpolator.isExactlyEqual(interpolator.interpolate(lowerForm, upperForm, fraction), cell.form)) {
return false
}
}
return true
}
/**
* This grid with [axisIndex] removed, keeping the key-index-0 slice.
*
* Only ever called on an axis this track is constant along, so which slice survives is immaterial - unlike
* [withAxisCollapsed], which must pick a slice by parameter value because it is discarding real motion.
*
* @param Int axisIndex The axis to drop.
* @return KeyformGrid The grid one dimension smaller.
*/
private fun <TForm> KeyformGrid<TForm>.withAxisDropped(axisIndex: Int): KeyformGrid<TForm> {
val newAxes = axes.filterIndexed { index, _ -> index != axisIndex }
val newCells =
cells
.filter { cell -> cell.coordinate[axisIndex] == 0 }
.map { cell ->
val reduced = IntArray(cell.coordinate.size - 1)
var writeIndex = 0
for (readIndex in cell.coordinate.indices) {
if (readIndex != axisIndex) {
reduced[writeIndex] = cell.coordinate[readIndex]
writeIndex++
}
}
KeyformCell(reduced, cell.form)
}
return KeyformGrid(newAxes, newCells)
}
/**
* This grid with key [keyIndex] dropped from [axisIndex], re-projecting the coordinates above it.
*
* The index-addressed counterpart of [withKeyRemoved], without that function's collapse guard: compaction
* only ever drops interior keys, so at least the two endpoints always remain.
*
* @param Int axisIndex The axis to drop a key from.
* @param Int keyIndex The key index to drop.
* @return KeyformGrid The grid with the key removed.
*/
private fun <TForm> KeyformGrid<TForm>.withKeyIndexDropped(axisIndex: Int, keyIndex: Int): KeyformGrid<TForm> {
val oldKeys = axes[axisIndex].keys
val newKeys = FloatArray(oldKeys.size - 1)
oldKeys.copyInto(newKeys, destinationOffset = 0, startIndex = 0, endIndex = keyIndex)
oldKeys.copyInto(newKeys, destinationOffset = keyIndex, startIndex = keyIndex + 1, endIndex = oldKeys.size)
val newAxes = axes.toMutableList()
newAxes[axisIndex] = KeyformAxis(axes[axisIndex].parameterId, newKeys)
val newCells =
cells.mapNotNull { cell ->
val keyOnAxis = cell.coordinate[axisIndex]
when {
keyOnAxis == keyIndex -> null
keyOnAxis > keyIndex -> KeyformCell(cell.coordinate.copyOf().also { it[axisIndex] = keyOnAxis - 1 }, cell.form)
else -> cell
}
}
return KeyformGrid(newAxes.toList(), newCells)
}
@@ -0,0 +1,278 @@
package org.umamo.runtime.keyform
import org.umamo.runtime.eval.EPS_KEY
import org.umamo.runtime.model.ChannelGrids
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.FormChannel
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.ParameterId
import kotlin.math.abs
/*
* Pure shape queries and shape edits over a KeyformGrid: strides, the linear cell index, density
* checks, and axis removal. Nothing here interpolates a form and nothing here evaluates a pose - the
* multilinear blend stays in runtime.eval, which this package must never duplicate.
*
* This lives in :runtime rather than :edit because the CMO3 / MOC3 importers need it and :runtime
* cannot depend on :edit.
*/
/**
* The grid's linear cell extent: the product of every axis's key count.
*
* Zero for a grid carrying an empty axis, which is a malformed grid rather than a rest cell; the
* delta-texture sizing in :render floors its own copy at 1 because a texture cannot be zero-wide.
*
* @return Int The number of cells a dense grid of this shape holds.
*/
val KeyformGrid<*>.cellCount: Int
get() = axes.fold(1) { count, axis -> count * axis.keys.size }
/**
* Whether this grid holds exactly one cell per coordinate in its shape.
*
* A CMO3 grid can arrive SPARSE - Cmo3Import drops cells whose form guid does not resolve - and a
* sparse grid blends toward zero rather than erroring. Compaction and refine both refuse a sparse
* grid rather than inventing the missing cells, so they ask this first.
*
* @return Boolean True when the grid is dense and every cell index is in range and distinct.
*/
val KeyformGrid<*>.isDense: Boolean
get() {
val expectedCellCount = cellCount
if (expectedCellCount <= 0 || cells.size != expectedCellCount) {
return false
}
val seenIndices = HashSet<Int>(cells.size)
for (cell in cells) {
if (cell.coordinate.size != axes.size) {
return false
}
val linearIndex = linearIndexOf(cell.coordinate)
if (linearIndex < 0 || linearIndex >= expectedCellCount || !seenIndices.add(linearIndex)) {
return false
}
}
return true
}
/**
* The index of the axis keying on [parameterId], or -1 when this grid has no such axis.
*
* @param ParameterId parameterId The parameter to look for.
* @return Int The axis index, or -1 when absent.
*/
fun KeyformGrid<*>.axisIndexOf(parameterId: ParameterId): Int = axes.indexOfFirst { axis -> axis.parameterId == parameterId }
/**
* This grid with the axis for [parameterId] removed, collapsing that dimension to the key nearest
* [keepKeyValue]. Returns this same instance when the grid has no such axis (so a caller can skip
* untouched entities by identity), or null when removing the axis leaves no axes at all (the entity
* becomes unkeyed). The surviving cells are those whose coordinate on the dropped axis is the kept key
* index, each re-projected to the N-1 coordinate; the form payloads are carried through untouched.
*
* The kept slice is the NEAREST key, not an interpolated one, so collapsing an axis whose kept value
* falls between keys discards the interpolated pose rather than baking it.
*
* @param ParameterId parameterId The axis parameter to remove.
* @param Float keepKeyValue The parameter value whose nearest key slice survives (the deleted default).
* @return KeyformGrid The collapsed grid, this if the axis was absent, or null if no axes remain.
*/
fun <TForm> KeyformGrid<TForm>.withAxisCollapsed(parameterId: ParameterId, keepKeyValue: Float): KeyformGrid<TForm>? {
val axisIndex = axisIndexOf(parameterId)
if (axisIndex < 0) {
return this
}
val newAxes = axes.filterIndexed { index, _ -> index != axisIndex }
if (newAxes.isEmpty()) {
return null
}
val keepIndex = nearestKeyIndex(axes[axisIndex].keys, keepKeyValue)
val newCells =
cells
.filter { cell -> cell.coordinate[axisIndex] == keepIndex }
.map { cell -> KeyformCell(cell.coordinate.withElementRemoved(axisIndex), cell.form) }
return KeyformGrid(newAxes, newCells)
}
/**
* This grid with the axis for [from] retargeted onto [to]: same key values and cells, new parameter id.
* Returns this same instance when the grid has no [from] axis. When [to] is already an axis, that
* destination axis is collapsed to the key nearest [destinationKeepValue] first (its motion is
* discarded) so the grid never carries two axes on the same parameter; the surviving [from] axis is
* then renamed to [to]. Key values are kept absolute (not range-remapped) so authored positions stay
* intact when the destination's min/max differ.
*
* @param ParameterId from The axis parameter to retarget away from.
* @param ParameterId to The parameter the axis should key on after the move.
* @param Float destinationKeepValue Kept-slice value when [to] already occupies an axis (its default).
* @return KeyformGrid The retargeted grid, or this if [from] was absent.
*/
fun <TForm> KeyformGrid<TForm>.withAxisRetargeted(
from: ParameterId,
to: ParameterId,
destinationKeepValue: Float,
): KeyformGrid<TForm> {
val fromIndex = axisIndexOf(from)
if (fromIndex < 0) {
return this
}
if (from == to) {
return this
}
val toIndex = axisIndexOf(to)
if (toIndex >= 0) {
// Both axes present: drop the destination's motion, then rename the source onto it.
val withoutDestination = withAxisCollapsed(to, destinationKeepValue)
// [from] is still present (both were axes), so the collapse cannot empty the grid.
return withoutDestination!!.withAxisRetargeted(from, to, destinationKeepValue)
}
val newAxes = axes.toMutableList()
newAxes[fromIndex] = KeyformAxis(to, axes[fromIndex].keys.copyOf())
return KeyformGrid(newAxes, cells)
}
/**
* Every channel track with the axis for [from] retargeted onto [to]. Tracks that never keyed [from]
* are left untouched by identity; returns this same instance when nothing changed.
*
* @param ParameterId from The axis parameter to retarget away from.
* @param ParameterId to The parameter each matching axis should key on after the move.
* @param Float destinationKeepValue Kept-slice value when a track already keys [to].
* @return ChannelGrids The retargeted tracks, or this if none referenced [from].
*/
fun ChannelGrids.withAxisRetargeted(
from: ParameterId,
to: ParameterId,
destinationKeepValue: Float,
): ChannelGrids {
var changed = false
val scrubbed = LinkedHashMap<FormChannel, KeyformGrid<ChannelValue>>(gridsByChannel.size)
for ((channel, grid) in gridsByChannel) {
val retargeted = grid.withAxisRetargeted(from, to, destinationKeepValue)
if (retargeted !== grid) {
changed = true
}
scrubbed[channel] = retargeted
}
return if (changed) ChannelGrids(scrubbed) else this
}
/**
* The index of the key on [parameterId]'s axis that [value] sits exactly on, or -1.
*
* "Exactly" means within the evaluator's own EPS_KEY snap tolerance, so this agrees with what is actually
* being rendered: if the pose resolves to a key, this finds it. Authoring ops use it to decide whether an
* insert lands on an existing key (overwrite) or between two (reshape).
*
* @param ParameterId parameterId The axis to look on.
* @param Float value The pose value.
* @return Int The key index, or -1 when the axis is absent or no key is in range.
*/
fun KeyformGrid<*>.keyIndexAt(parameterId: ParameterId, value: Float): Int {
val axisIndex = axisIndexOf(parameterId)
if (axisIndex < 0) {
return -1
}
return axes[axisIndex].keys.indexOfFirst { key -> abs(key - value) < EPS_KEY }
}
/**
* The result of collapsing an axis out of a whole owner's channel tracks: the surviving tracks, plus the
* value each fully-collapsed track held on its kept slice.
*
* The lifted value is what the owner's static field must take over so the collapse preserves the neutral
* look - dropping a track without lifting it would snap the channel back to whatever the static happened
* to hold (typically the import-time value), visibly changing the rig.
*
* @property ChannelGrids channelGrids The scrubbed tracks.
* @property Map lifted Per fully-collapsed channel, the value its kept slice held.
*/
class CollapsedChannels(
val channelGrids: ChannelGrids,
val lifted: Map<FormChannel, ChannelValue>,
)
/**
* Every one of this owner's channel tracks with the axis for [parameterId] collapsed out, lifting the
* kept slice's value of any track that drops entirely.
*
* The whole-owner counterpart of [withAxisCollapsed], so deleting a parameter scrubs every track in one
* walk rather than needing a hand-written case per channel - a hand-rolled enumeration is exactly the kind
* of list a channel like a glue's intensity grid could quietly be left off. A track left with no axes is
* dropped, and the value of its kept slice is returned
* in [CollapsedChannels.lifted] for the caller to write into the owner's static. A sparse grid missing
* its kept cell lifts nothing (the static keeps its current value). Returns this same grids instance
* (with an empty lifted map) when no track referenced the parameter.
*
* @param ParameterId parameterId The axis parameter to remove from every track.
* @param Float keepKeyValue The parameter value whose nearest key slice survives.
* @return CollapsedChannels The scrubbed tracks plus the lifted slice values.
*/
fun ChannelGrids.withAxisCollapsedLifting(parameterId: ParameterId, keepKeyValue: Float): CollapsedChannels {
var changed = false
val scrubbed = LinkedHashMap<FormChannel, KeyformGrid<ChannelValue>>(gridsByChannel.size)
val lifted = LinkedHashMap<FormChannel, ChannelValue>()
for ((channel, grid) in gridsByChannel) {
val collapsed = grid.withAxisCollapsed(parameterId, keepKeyValue)
if (collapsed === grid) {
scrubbed[channel] = grid
continue
}
changed = true
if (collapsed != null) {
scrubbed[channel] = collapsed
continue
}
val axisIndex = grid.axisIndexOf(parameterId)
val keepIndex = nearestKeyIndex(grid.axes[axisIndex].keys, keepKeyValue)
val keptCell = grid.cells.firstOrNull { cell -> cell.coordinate.getOrNull(axisIndex) == keepIndex }
if (keptCell != null) {
lifted[channel] = keptCell.form
}
}
return if (changed) CollapsedChannels(ChannelGrids(scrubbed), lifted) else CollapsedChannels(this, emptyMap())
}
/**
* The index of the key in [keys] nearest [value] (0 for an empty axis, defensively).
*
* @param FloatArray keys The axis's key positions.
* @param Float value The parameter value to match.
* @return Int The nearest key's index.
*/
private fun nearestKeyIndex(keys: FloatArray, value: Float): Int {
if (keys.isEmpty()) {
return 0
}
var bestIndex = 0
var bestDistance = abs(keys[0] - value)
for (keyIndex in 1 until keys.size) {
val distance = abs(keys[keyIndex] - value)
if (distance < bestDistance) {
bestDistance = distance
bestIndex = keyIndex
}
}
return bestIndex
}
/**
* A copy of this coordinate array with the element at [removeIndex] dropped (length shrinks by one).
*
* @param Int removeIndex The element index to drop.
* @return IntArray The shortened coordinate.
*/
private fun IntArray.withElementRemoved(removeIndex: Int): IntArray {
val result = IntArray(size - 1)
var writeIndex = 0
for (readIndex in indices) {
if (readIndex != removeIndex) {
result[writeIndex] = this[readIndex]
writeIndex++
}
}
return result
}
@@ -0,0 +1,245 @@
package org.umamo.runtime.model
/*
* Where a document's art came from: the artwork files it was imported from, each with the layer
* inventory it had at that import, and the per-tile link back to one of those layers.
*
* Model state because re-import is a model operation: the reconcile diffs a re-read file against
* the inventory recorded here and rebinds tiles through the refs, so both have to survive undo, a
* document swap, and the native format. Pixels are deliberately absent - a tile's raster belongs to
* the document, and the source file itself is linked, never embedded.
*/
/**
* One artwork file the document was imported from, and the layers it had when it was last read.
*
* The inventory is the re-import baseline: a later read of the same file is diffed against it to
* classify each layer as matched, added, removed, or renamed. It records identity and layout only,
* never pixels, so a document with hundreds of layers carries it for free.
*
* @property ArtSourceId id The document-local identity every [SourceLayerRef] points at.
* @property String name The file's display name (its file name at import).
* @property String? path The advisory external path the file was read from, or null when
* unknown or platform-volatile; a missing file only stalls re-import, never the rig.
* @property String format The source format's file extension ("psd", "clip", "kra", or a
* flat raster's), recorded so a listing can say what a file is without re-reading it.
* @property List<ArtSourceLayer> layers The layer inventory as of the last import, in the file's own
* draw order (top-most first); empty for a source whose inventory was never walked.
* @property String? contentHash The whole-file content hash (SHA-256 hex) of the bytes the
* document last read for this file, or null when it never read bytes (a CMO3-origin source). What
* the watcher compares a save against, so an unchanged file is never re-read.
* @property Long? lastModified The file's modification time (epoch milliseconds) when the
* document last read it - or, for a CMO3-origin source, when the official editor did - or null when
* neither is known. The stale-at-open check falls back to it where no hash was recorded, since a
* CMO3 keeps the time but not a hash.
* @property Int offsetX How far right of the document canvas's top-left corner the file's
* own top-left corner sits, in pixels: the translation from the file's own canvas to the document
* canvas, in the viewport's world axes (x right, z up). Every read of the file is placed by it before
* the model sees the art, so the inventory rows, the birth meshes, and the reload's frame comparisons
* all live in the document's coordinates. Zero for a file that set or shares the document's frame (a
* rig's first artwork, a CMO3's own layered image); a later file is placed by the import's Align anchor
* and Offset rows.
* @property Int offsetZ How far UP from the document canvas's top-left corner the file's
* top-left corner sits, in pixels; a file placed lower on the canvas carries a negative value, and a
* layer's canvas y (down) is its own top minus this. See [offsetX].
*/
data class ArtSource(
val id: ArtSourceId,
val name: String,
val path: String?,
val format: String,
val layers: List<ArtSourceLayer> = emptyList(),
val contentHash: String? = null,
val lastModified: Long? = null,
val offsetX: Int = 0,
val offsetZ: Int = 0,
)
/**
* One layer of an [ArtSource]'s inventory: what the reader knew about it at import, without pixels.
*
* Skipped layers (non-raster, empty) are listed too, so a re-import can tell "this layer was there
* and unusable" from "this layer is new".
*
* @property String key The reader's layer key - the same string a [SourceLayerRef] carries.
* @property String name The layer's name at import.
* @property String groupPath The slash-joined enclosing-folder path at import ("" at the root).
* @property Int left The layer's position on the DOCUMENT canvas, top-left origin in source
* pixels: the file's own position plus its source's [ArtSource.offsetX], the frame every drawable's
* positions share.
* @property Int top See [left]; y runs down, so it is the file's own top minus [ArtSource.offsetZ].
* @property Int width The layer's raster width in source pixels.
* @property Int height The layer's raster height in source pixels.
* @property Boolean visible The layer's own eye toggle at import.
* @property Boolean present Whether the file still had this layer at the last read. False keeps the row
* for a layer the file lost while a tile still binds it, so the Sources space can name and size it and
* the matcher can score candidates against it; such a row leaves the inventory once nothing binds it.
* @property String? contentHash The content hash (SHA-256 hex) of the layer's pixels at the last read, or
* null where the art was never decoded (a CMO3's decomposed tree). A renamed layer whose pixels did
* not change is recognized by it outright.
* @property Boolean empty Whether the layer had no pixel with any alpha at the last read - erased to
* nothing rather than deleted. A tile bound to such a layer keeps its art and reads as needing review,
* since the artist may have meant either; false where the art was never decoded.
* @property Boolean replaced Meaningful only while [present] is false: the row was lost because Replace
* Artwork repointed the file at art that mints other keys, not because the layer left the file - so the
* row can say which. A row lost before the replace keeps false.
* @property Boolean ignored Whether a reload leaves this layer out of the rig: a present layer no tile
* binds that the rigger keeps in the file but not in the model (a sketch, a reference), marked from its
* Sources row or by Delete Art under the import setting, and carried across every refresh until the row
* clears it. Meaningless while a tile binds the key.
*/
data class ArtSourceLayer(
val key: String,
val name: String,
val groupPath: String,
val left: Int,
val top: Int,
val width: Int,
val height: Int,
val visible: Boolean,
val present: Boolean = true,
val contentHash: String? = null,
val empty: Boolean = false,
val replaced: Boolean = false,
val ignored: Boolean = false,
)
/**
* A tile's link to the source layer its art came from: which file, and which layer within it.
*
* The key is whatever the reader minted for the layer and is opaque here: a CLIP layer uuid, a Krita
* layer uuid, a PSD lyid, or a PSD name-plus-order fallback. [stableKey] says which of those it is
* in the one way that matters - whether the key survives a rename or reorder in the art program - so
* the reconcile knows when to trust it outright and a listing knows what to show.
*
* @property ArtSourceId sourceId The [ArtSource] the layer belongs to.
* @property String layerKey The reader's key for the layer within that source.
* @property Boolean stableKey Whether the key is a format-minted id (true) or a name-and-order
* fallback that only holds as long as the artist's layer organization does (false).
*/
data class SourceLayerRef(
val sourceId: ArtSourceId,
val layerKey: String,
val stableKey: Boolean,
)
/**
* Where a delta places one child among a container's existing children.
*/
sealed interface OrgSlot {
/**
* Directly after [anchor], a child the container already has (or one the same delta placed before it).
*
* @property OrgChild anchor The child to follow.
*/
data class After(val anchor: OrgChild) : OrgSlot
/**
* Directly before [anchor], a child the container already has.
*
* @property OrgChild anchor The child to precede.
*/
data class Before(val anchor: OrgChild) : OrgSlot
/** After every child the container has. */
data object End : OrgSlot
}
/**
* One child a delta places inside the model's existing org tree: a reload found a layer in a folder
* the document already keeps as a part (or at the root), and the file says where among that folder's
* layers it sits, so the drawable lands there rather than at the bottom. An anchor the container no
* longer has places the child at the end.
*
* @property PartId? container The part whose children it joins, or null for the root.
* @property OrgChild child The child: a drawable of the delta, or one of its new parts.
* @property OrgSlot slot Where among the container's children it goes.
*/
data class OrgInsertion(
val container: PartId?,
val child: OrgChild,
val slot: OrgSlot,
)
/**
* What one artwork file adds to a model: the file's record, its tiles, the drawables and parts born
* from its layers, and where they join the org tree - a fresh file's whole tree after the model's root
* children, a listed file's new layers placed among the children the model already has. A delta
* rather than a model, so the same additions can be appended to a fresh model at open or to a document
* already being rigged.
*
* Every id in here is already minted past the receiving model's (`ArtMesh<n>`, `Part<n>`, `art-<k>`),
* and the new parts' children reference only ids in this delta. Pixels are absent - they travel
* beside it to the document's raster store.
*
* @property ArtSource source The file and its layer inventory.
* @property List<AtlasTile> tiles One unplaced tile per imported layer, bound to that layer.
* @property List<Drawable> drawables One drawable per tile, over its birth mesh.
* @property List<Part> parts One NEW part per folder the model has no part for, nested by the
* parts' own children.
* @property List<OrgChild> rootChildren A fresh file's top-level order, appended after the model's own;
* empty for a listed file, whose new children are [insertions].
* @property List insertions A listed file's new children placed among the existing ones - at
* the root or inside a part the document already keeps for the folder - in the order the file gives
* them, each anchored to its nearest sibling in the file; applied in list order, so a child may anchor
* on one placed before it. Empty for a fresh file, whose folders are all new.
*/
data class ArtworkAdditions(
val source: ArtSource,
val tiles: List<AtlasTile>,
val drawables: List<Drawable>,
val parts: List<Part>,
val rootChildren: List<OrgChild>,
val insertions: List<OrgInsertion> = emptyList(),
)
/**
* One tile a reload supersedes: the id of the tile the art used to live in, and the tile that holds it
* now - a fresh id (`<root>~<n>`), the new size, no placement yet, the old pin, and [AtlasTile.replaces]
* naming the old one.
*
* @property AtlasTileId oldId The superseded tile's id; its pixels stay in the document's raster store.
* @property AtlasTile tile The replacement, unplaced.
*/
data class ReplacedTile(
val oldId: AtlasTileId,
val tile: AtlasTile,
)
/**
* What re-reading one artwork file changes in a model: the file's record with its NEW inventory, the
* tiles whose art changed (each superseded by a fresh, unplaced tile), the meshes the drawables over
* them take (an untouched birth quad re-born over the new art, an edited mesh carried with its
* coordinates remapped so every vertex samples the same canvas pixel as before), the layers the file
* gained, the drawables whose edited mesh the new opaque art now reaches past, and the drawables whose
* visibility follows the file's eye toggle.
*
* A delta rather than a model, like [ArtworkAdditions]: the same plan applies to the live model and
* to the operation strip's rerun over its base. Pixels travel beside it to the raster store. A layer
* the file lost is deliberately absent - its tile keeps its art and its binding, and the new inventory
* carries its row flagged not present ([ArtSourceLayer.present]), which is what the Sources space shows
* as needing review.
*
* @property ArtSource source The file's record, carrying the inventory as just read.
* @property List replacedTiles The tiles whose art changed, each with its replacement.
* @property Map drawableMeshes The mesh each affected drawable takes, keyed by drawable;
* texture coordinates in the ART frame of the drawable's new tile, which the pack that follows
* converts exactly as it does an import's.
* @property ArtworkAdditions? additions The layers the file gained, minted under [source], or null.
* @property List<DrawableId> outgrown Drawables whose kept mesh no longer covers the new opaque art.
* @property List<AtlasTileId> retiredTiles Tiles a rebinding made redundant: a lost layer's rig work took
* the layer a reload had minted a fresh, untouched drawable for, so that drawable and its tile go (the
* pixels stay in the raster store for undo). Never a replaced tile; a part minted for the drawable stays.
* @property Map drawableVisibility The visibility each drawable takes, keyed by drawable, where
* the file's eye toggle changed since the last read and the drawable still showed the OLD state; a
* drawable the rigger toggled since is absent, since that toggle is rig work.
*/
data class ArtworkReload(
val source: ArtSource,
val replacedTiles: List<ReplacedTile>,
val drawableMeshes: Map<DrawableId, DrawableMesh>,
val additions: ArtworkAdditions?,
val outgrown: List<DrawableId>,
val retiredTiles: List<AtlasTileId> = emptyList(),
val drawableVisibility: Map<DrawableId, Boolean> = emptyMap(),
)
@@ -0,0 +1,284 @@
package org.umamo.runtime.model
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
/*
* Where a document's source art sits on its atlas pages, and the affine algebra that maps between the
* two frames.
*
* Model state rather than render state: a placement is authored (a repack moves it), so it has to
* survive undo, diff, and export like any other document content. It lives here, in the module with no
* dependencies, because every consumer needs it - the renderer to sample, the UV editor to map, and the
* CMO3 export to write - and the export path deliberately cannot see the renderer.
*/
/**
* Where one tile's upright source art sits on an atlas page: the transform the packer applied to it, as
* translation / scale / rotation.
*
* A Transform/Rotation/Scale(TRS) rather than a rect because that is what the source formats actually
* carry and what the corpus actually uses. Rotation and scale both occur, and a rect-plus-quarter-turn
* model would silently discard them on import. A packer that only ever emits axis-aligned unit-scale
* placements writes the constrained subset (scale 1, rotation 0) and loses nothing.
*
* Rotation is DEGREES, counter-clockwise, about the layer's own origin, applied after scale; the frame
* is page pixels with y running DOWN (v = 0 is the page's top row), matching how the decoder emits rows
* and how the sampler addresses them.
*
* [pageIndex] indexes [PuppetAtlas.pages], which is the DOCUMENT's page order. For an IMPORTED
* document it is deliberately NOT the renderer's page numbering: the two are derived independently
* (the renderer collects pages in drawable-encounter order and renumbers when one fails to decode),
* so an index is only ever valid against the list it came from. A page set Umamo generates itself
* (a repack's) is built index-parallel to [PuppetAtlas.pages], so for generated sets the two
* numberings coincide by construction.
*
* @property Int pageIndex The atlas page the art packs onto, indexing [PuppetAtlas.pages].
* @property Float positionX The packing origin's x on the page, in pixels (fractional in real files).
* @property Float positionY The packing origin's y on the page, in pixels.
* @property Float scaleX The horizontal scale the packer applied (negative mirrors).
* @property Float scaleY The vertical scale the packer applied (negative mirrors).
* @property Float rotationDegrees The rotation the packer applied, counter-clockwise degrees.
*/
data class AtlasPlacement(
val pageIndex: Int,
val positionX: Float,
val positionY: Float,
val scaleX: Float,
val scaleY: Float,
val rotationDegrees: Float,
)
/**
* One drawable's resolved link to its source art: which tile it samples, and how its stored atlas
* texture coordinates map back into that tile's own pixel frame.
*
* A null [placement] means the drawable renders from the art directly rather than from a packed page -
* its stored uvs already address the tile image, so the mapping is the identity. Applying a placement
* inverse to those would be a double transform.
*
* The page dimensions ride here rather than being looked up per call because a binding is resolved once
* and then applied per vertex, and because a drawable sampling its art directly has no page at all.
*
* @property String layerKey The tile this drawable samples.
* @property AtlasPlacement? placement The packing transform, or null when the drawable samples the art directly.
* @property Int pageWidth The atlas page's width in pixels.
* @property Int pageHeight The atlas page's height in pixels.
*/
data class DrawableLayerBinding(
val layerKey: String,
val placement: AtlasPlacement?,
val pageWidth: Int,
val pageHeight: Int,
)
/**
* The placement's inverse as a 2x3 affine (m00, m01, m02, m10, m11, m12) mapping page pixels back to
* layer pixels.
*
* The forward transform is `atlas = R(angle) . S . layer + position`, so the inverse is
* `layer = S^-1 . R(-angle) . (atlas - position)`. Resolved once per placement so a whole mesh
* converts without recomputing the trigonometry per vertex.
*
* @param AtlasPlacement placement The packing transform to invert.
* @return FloatArray? The inverse affine, or null when the placement is degenerate (a zero scale).
*/
fun inversePlacementAffine(placement: AtlasPlacement): FloatArray? {
if (placement.scaleX == 0f || placement.scaleY == 0f) {
return null
}
val radians = placement.rotationDegrees.toDouble() * PI / 180.0
val cosine = cos(radians)
val sine = sin(radians)
// R(-angle) then S^-1, i.e. rows scaled by the inverse scale after the transposed rotation.
val m00 = (cosine / placement.scaleX).toFloat()
val m01 = (sine / placement.scaleX).toFloat()
val m10 = (-sine / placement.scaleY).toFloat()
val m11 = (cosine / placement.scaleY).toFloat()
return floatArrayOf(
m00,
m01,
-(m00 * placement.positionX + m01 * placement.positionY),
m10,
m11,
-(m10 * placement.positionX + m11 * placement.positionY),
)
}
/**
* The placement's forward transform as a 2x3 affine (m00, m01, m02, m10, m11, m12) mapping layer
* pixels to page pixels - [atlasPixelOf]'s algebra as a matrix, for callers that compose it with
* other affines rather than applying it pointwise.
*
* @param AtlasPlacement placement The packing transform.
* @return FloatArray The forward affine.
*/
fun placementAffine(placement: AtlasPlacement): FloatArray {
val radians = placement.rotationDegrees.toDouble() * PI / 180.0
val cosine = cos(radians)
val sine = sin(radians)
return floatArrayOf(
(cosine * placement.scaleX).toFloat(),
(-sine * placement.scaleY).toFloat(),
placement.positionX,
(sine * placement.scaleX).toFloat(),
(cosine * placement.scaleY).toFloat(),
placement.positionY,
)
}
/**
* Composes two 2x3 affines: the result applies [inner] first, then [outer].
*
* @param FloatArray outer The affine applied second.
* @param FloatArray inner The affine applied first.
* @return FloatArray The composition, a fresh array.
*/
fun composeAffine(outer: FloatArray, inner: FloatArray): FloatArray =
floatArrayOf(
outer[0] * inner[0] + outer[1] * inner[3],
outer[0] * inner[1] + outer[1] * inner[4],
outer[0] * inner[2] + outer[1] * inner[5] + outer[2],
outer[3] * inner[0] + outer[4] * inner[3],
outer[3] * inner[1] + outer[4] * inner[4],
outer[3] * inner[2] + outer[4] * inner[5] + outer[5],
)
/**
* The atlas-page pixel a layer pixel packs to (the forward transform).
*
* @param AtlasPlacement placement The packing transform.
* @param Float layerX The layer-local x in pixels.
* @param Float layerY The layer-local y in pixels.
* @return FloatArray The (x, y) page pixel.
*/
fun atlasPixelOf(placement: AtlasPlacement, layerX: Float, layerY: Float): FloatArray {
val radians = placement.rotationDegrees.toDouble() * PI / 180.0
val cosine = cos(radians)
val sine = sin(radians)
val scaledX = layerX * placement.scaleX
val scaledY = layerY * placement.scaleY
return floatArrayOf(
(cosine * scaledX - sine * scaledY).toFloat() + placement.positionX,
(sine * scaledX + cosine * scaledY).toFloat() + placement.positionY,
)
}
/**
* The layer pixel an atlas-page pixel came from (the inverse transform).
*
* @param AtlasPlacement placement The packing transform.
* @param Float atlasX The page x in pixels.
* @param Float atlasY The page y in pixels.
* @return FloatArray? The (x, y) layer pixel, or null when the placement is degenerate.
*/
fun layerPixelOf(placement: AtlasPlacement, atlasX: Float, atlasY: Float): FloatArray? {
val inverse = inversePlacementAffine(placement) ?: return null
return floatArrayOf(
inverse[0] * atlasX + inverse[1] * atlasY + inverse[2],
inverse[3] * atlasX + inverse[4] * atlasY + inverse[5],
)
}
/**
* The whole atlas-uv to layer-uv mapping for a binding, as one 2x3 affine (m00, m01, m02, m10, m11,
* m12) over NORMALIZED coordinates.
*
* The per-vertex chain is uv times the page size, through the placement inverse, divided by the layer's
* size - all affine, so it folds into a single matrix that any consumer can apply in either direction
* (see [invertUvAffine]). A drawable sampling its art directly has stored uvs that already address the
* tile image, so its mapping is the identity rather than a placement inverse; applying a placement
* there would be a double transform.
*
* @param DrawableLayerBinding binding The drawable's binding.
* @param Int layerWidth The source tile's width in pixels.
* @param Int layerHeight The source tile's height in pixels.
* @return FloatArray? The atlas-uv to layer-uv affine, or null when it cannot be formed.
*/
fun layerUvAffineOf(binding: DrawableLayerBinding, layerWidth: Int, layerHeight: Int): FloatArray? {
val placement = binding.placement ?: return identityUvAffine()
if (layerWidth <= 0 || layerHeight <= 0) {
return null
}
val inverse = inversePlacementAffine(placement) ?: return null
return floatArrayOf(
inverse[0] * binding.pageWidth / layerWidth,
inverse[1] * binding.pageHeight / layerWidth,
inverse[2] / layerWidth,
inverse[3] * binding.pageWidth / layerHeight,
inverse[4] * binding.pageHeight / layerHeight,
inverse[5] / layerHeight,
)
}
/** The uv affine that changes nothing - the mapping of a drawable whose uvs already address its art. */
fun identityUvAffine(): FloatArray = floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f)
/**
* Inverts a 2x3 uv affine, turning a mapping INTO a frame into the mapping back OUT of it.
*
* @param FloatArray affine The affine to invert (m00, m01, m02, m10, m11, m12).
* @return FloatArray? The inverse, or null when the affine is degenerate (a zero determinant).
*/
fun invertUvAffine(affine: FloatArray): FloatArray? {
if (affine.size < 6) {
return null
}
val determinant = affine[0] * affine[4] - affine[1] * affine[3]
if (determinant == 0f) {
return null
}
val m00 = affine[4] / determinant
val m01 = -affine[1] / determinant
val m10 = -affine[3] / determinant
val m11 = affine[0] / determinant
return floatArrayOf(
m00,
m01,
-(m00 * affine[2] + m01 * affine[5]),
m10,
m11,
-(m10 * affine[2] + m11 * affine[5]),
)
}
/**
* Applies a 2x3 uv affine to a whole interleaved (u, v) array.
*
* @param FloatArray uvs The coordinates to map.
* @param FloatArray affine The affine to apply.
* @return FloatArray The mapped coordinates, a fresh array.
*/
fun applyUvAffine(uvs: FloatArray, affine: FloatArray): FloatArray {
val mapped = FloatArray(uvs.size)
var componentIndex = 0
while (componentIndex + 1 < uvs.size) {
val u = uvs[componentIndex]
val v = uvs[componentIndex + 1]
mapped[componentIndex] = affine[0] * u + affine[1] * v + affine[2]
mapped[componentIndex + 1] = affine[3] * u + affine[4] * v + affine[5]
componentIndex += 2
}
return mapped
}
/**
* Maps a drawable's stored texture coordinates into its source tile's own [0,1] frame - the mapping a
* layer view draws.
*
* @param FloatArray atlasUvs The drawable's stored texture coordinates, interleaved (u, v).
* @param DrawableLayerBinding binding The drawable's binding.
* @param Int layerWidth The source tile's width in pixels.
* @param Int layerHeight The source tile's height in pixels.
* @return FloatArray? The layer-frame uvs, or null when the mapping cannot be formed.
*/
fun layerUvsFromAtlasUvs(
atlasUvs: FloatArray,
binding: DrawableLayerBinding,
layerWidth: Int,
layerHeight: Int,
): FloatArray? {
val affine = layerUvAffineOf(binding, layerWidth, layerHeight) ?: return null
return applyUvAffine(atlasUvs, affine)
}
@@ -0,0 +1,111 @@
package org.umamo.runtime.model
/**
* How a drawable or a layer composite blends its color against what's already drawn. Mirrors
* Cubism's color blend modes: the three legacy pre-5.3 modes (bare CMO3 tokens, fixed-function
* blending) plus the fifteen 5.3 modes (shader compositing). An `enum` (not sealed) because the set
* is fixed and each case is a plain value with no extra data.
*
* Each constant cites its CMO3 ColorComposition token and its MOC3 packed colorMode int
* (sections 153/157, `colorMode or (alphaMode shl 8)`); the mapping lives in explicit functions
* (BlendModeMapping), never in ordinals.
*
* 描画オブジェクト/オフスクリーン合成のカラーブレンドモード。Cubism のブレンドモードに対応。
*/
enum class BlendMode {
/** Legacy Normal. CMO3 `NORMAL`; MOC3 colorMode 0 (constant-flags bits clear). */
Normal,
/** Add (Before 5.3), premultiplied fixed-function. CMO3 `ADD`; MOC3 colorMode 1 (constant-flags bit 0). */
AdditivePremultiplied,
/** Multiply (Before 5.3), premultiplied fixed-function. CMO3 `MULTIPLY`; MOC3 colorMode 2 (constant-flags bit 1). */
MultiplyPremultiplied,
/** Add (5.3+). CMO3 `ADD_R2_TSL`; MOC3 colorMode 3. */
Additive,
/** Add (Glow) (5.3). CMO3 `ADD_R2`; MOC3 colorMode 4. */
AdditiveGlow,
/** Darken (5.3). CMO3 `DARKEN`; MOC3 colorMode 5. */
Darken,
/** Multiply (5.3+). CMO3 `MULTIPLY_R2`; MOC3 colorMode 6. */
Multiply,
/** Color burn (5.3). CMO3 `COLORBURN_TSL`; MOC3 colorMode 7. */
ColorBurn,
/** Linear burn (5.3). CMO3 `LINEARBURN_TSL`; MOC3 colorMode 8. */
LinearBurn,
/** Lighten (5.3). CMO3 `LIGHTEN`; MOC3 colorMode 9. */
Lighten,
/** Screen (5.3). CMO3 `SCREEN`; MOC3 colorMode 10. */
Screen,
/** Color dodge (5.3). CMO3 `COLORDODGE_TSL`; MOC3 colorMode 11. */
ColorDodge,
/** Overlay (5.3). CMO3 `OVERLAY`; MOC3 colorMode 12. */
Overlay,
/** Soft light (5.3). CMO3 `SOFTLIGHT`; MOC3 colorMode 13. */
SoftLight,
/** Hard light (5.3). CMO3 `HARDLIGHT`; MOC3 colorMode 14. */
HardLight,
/** Linear light (5.3). CMO3 `LINEARLIGHT_TSL`; MOC3 colorMode 15. */
LinearLight,
/** Hue (5.3, HSL non-separable). CMO3 `HSL_HUE`; MOC3 colorMode 16. */
Hue,
/** Color (5.3, HSL non-separable). CMO3 `HSL_COLOR`; MOC3 colorMode 17. */
Color,
;
/**
* True for the three pre-5.3 modes, whose semantics are plain fixed-function blending; every
* other mode requires the destination-sampling composite path.
*/
val isLegacy: Boolean get() = this == Normal || this == AdditivePremultiplied || this == MultiplyPremultiplied
/**
* Whether this color blend mode ignores the Alpha blend setting. Per the Cubism editor, the pre-5.3
* "Add (Before 5.3)" and "Multiply (Before 5.3)" modes composite in premultiplied format and disregard
* the Alpha blend selection. Drives the composite math and the properties panel alpha-field visibility.
*/
val ignoresAlphaBlend: Boolean get() = this == AdditivePremultiplied || this == MultiplyPremultiplied
}
/**
* How a drawable or a layer composite combines its ALPHA with the destination - Cubism 5.3's
* Porter-Duff-style alpha blend list, orthogonal to [BlendMode]. Pre-5.3 sources have no alpha
* mode; they behave as [Over].
*
* Each constant cites its CMO3 AlphaComposition token and MOC3 packed alphaMode int
* (sections 153/157, bits 8-15).
*
* アルファブレンドモード(Cubism 5.3)。カラーブレンドとは独立。
*/
enum class AlphaBlendMode {
/** Over (the default; pre-5.3 behavior). CMO3 `OVER`; MOC3 alphaMode 0. */
Over,
/** Atop. CMO3 `ATOP`; MOC3 alphaMode 1. */
Atop,
/** Out. CMO3 `OUT`; MOC3 alphaMode 2. */
Out,
/** Conjoint over. CMO3 `CONJOINT`; MOC3 alphaMode 3. */
Conjoint,
/** Disjoint over. CMO3 `DISJOINT`; MOC3 alphaMode 4. */
Disjoint,
}
@@ -0,0 +1,94 @@
package org.umamo.runtime.model
/**
* One point of a blend-weight limit curve: at [value] on the constraint parameter, the blend
* shape's weight is capped to [weight].
*
* ブレンドウェイト制限カーブの 1 点。制約パラメータが [value] のとき重みは [weight] に制限される。
*
* @property Float value The constraint parameter's value this point sits at.
* @property Float weight The weight cap at that value (0..1).
*/
data class BlendWeightLimitPoint(
val value: Float,
val weight: Float,
)
/**
* A blend-weight limit ("blend shape limit" in the Cubism editor): a piecewise-linear, end-clamped
* curve over ANOTHER parameter's value that caps a blend shape's weight. A binding's effective
* multiplier is the MINIMUM over all of its limits (1 when it has none).
*
* CMO3: MorphTargetBlendWeightConstraint - the flat (constraintParameterGuid,
* constraintParameterValue, blendWeight) records grouped per constraint parameter into one curve.
*
* ブレンドウェイト制限。別パラメータ値に対する区分線形カーブで重みを制限し、複数あれば最小値を取る。
*
* @property ParameterId parameterId The constraint parameter whose value drives this curve.
* @property List points The curve points, sorted ascending by value.
*/
data class BlendWeightLimit(
val parameterId: ParameterId,
val points: List<BlendWeightLimitPoint>,
)
/**
* A blend shape ("MorphTarget" in CMO3): an ADDITIVE deformation on one object, driven by one
* parameter. Where a keyform grid interpolates BETWEEN absolute forms (parameters select shapes),
* a blend shape ADDS a weighted delta on top of the grid result (parameters add shapes), and
* multiple bindings on the same object stack by summation.
*
* [keys] always contains the neutral key at parameter VALUE 0, not at the parameter's default.
* Ingest inserts the neutral when the document does not key value 0, so [forms] at [neutralIndex]
* is null in practice (a morph authored exactly at 0 would occupy the slot but is never read - the
* neutral key contributes zero by definition, and baked files store an all-zero delta row there).
* A morph authored AT the parameter's default (non-zero) is an ordinary non-neutral key: the
* Umamo C++ runtime applies it at the default pose. Non-neutral forms are stored exactly as the
* object's grid stores its forms ([MeshForm] position deltas are relative to the rest mesh,
* [WarpForm]/[RotationForm] are absolute); deriving the neutral-relative delta each key contributes
* is the evaluator's job, not this type's.
*
* CMO3: ACParameterControllableSource.keyformMorphTargetSet -> KeyFormMorphTargetSet - one
* KeyFormMorphTarget per (parameterGuid, keyValue, keyformGuid); one binding groups a source's
* morph targets sharing a driving parameter.
*
* ブレンドシェイプ(CMO3 の MorphTarget)。格子補間の結果に加算される差分で、同一オブジェクト上の
* 複数バインディングは合算される。[neutralIndex] は寄与ゼロのキー(フォームは null)。
*
* @property ParameterId parameterId The driving parameter.
* @property FloatArray keys The parameter values the forms are keyed at, ascending,
* including the inserted neutral key.
* @property Int neutralIndex Index into [keys] of the zero-contribution (rest) key.
* @property List forms One form per key, parallel to [keys]; null at the neutral
* key when the neutral was inserted rather than authored.
* @property List limits Blend-weight limit curves; the effective weight multiplier is
* their minimum (1 when empty).
*/
data class BlendShapeBinding<TForm : Any>(
val parameterId: ParameterId,
val keys: FloatArray,
val neutralIndex: Int,
val forms: List<TForm?>,
val limits: List<BlendWeightLimit> = emptyList(),
) {
// data class with an array field: generated equals/hashCode use referential array equality,
// which is wrong for value semantics (same rationale as Keyform).
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is BlendShapeBinding<*>) return false
return parameterId == other.parameterId &&
keys.contentEquals(other.keys) &&
neutralIndex == other.neutralIndex &&
forms == other.forms &&
limits == other.limits
}
override fun hashCode(): Int {
var hash = parameterId.hashCode()
hash = 31 * hash + keys.contentHashCode()
hash = 31 * hash + neutralIndex
hash = 31 * hash + forms.hashCode()
hash = 31 * hash + limits.hashCode()
return hash
}
}
@@ -0,0 +1,35 @@
package org.umamo.runtime.model
/**
* A straight-alpha-free RGB color channel triple, 0..1 per channel - the multiply/screen color
* payload of a layer composite. Channels are the editor hex value / 255 as float32 (CMO3
* `CFloatColor` red/green/blue; MOC3 color-table rows 108-113 carry the identical floats). The
* source formats' alpha attribute is always 1.0 in every observed sample, so it is not modeled.
*
* 乗算色/スクリーン色の RGB 値(0..1)。
*/
data class ColorRgb(
val red: Float,
val green: Float,
val blue: Float,
) {
companion object {
/** The multiply-color identity (#FFFFFF - multiplying by it changes nothing). */
val MultiplyIdentity: ColorRgb = ColorRgb(1f, 1f, 1f)
/** The screen-color identity (#000000 - screening with it changes nothing). */
val ScreenIdentity: ColorRgb = ColorRgb(0f, 0f, 0f)
}
/**
* This color with every channel clamped into 0..1.
*
* Additive accumulation (blend-shape color deltas, the deformer screen composition) can leave the
* range at the ends of a keyed span, and the clamp belongs AFTER the whole sum rather than per
* term - clamping each contribution would bias a record whose neighbours pull the other way.
*
* @return ColorRgb The clamped color.
*/
fun coerceToUnit(): ColorRgb =
ColorRgb(red.coerceIn(0f, 1f), green.coerceIn(0f, 1f), blue.coerceIn(0f, 1f))
}
@@ -0,0 +1,178 @@
package org.umamo.runtime.model
/**
* A deformer in the rig hierarchy.
*
* Cubism deformation is parameter-driven morph blending, not skeletal - there are exactly two
* deformer kinds, so a `sealed interface` captures the closed taxonomy and forces `when`s over it to
* be exhaustive (adding a third kind becomes a compile error until handled everywhere). Deformers nest
* via [parent] (the transform hierarchy a drawable inherits); each also belongs to a part via [partId]
* (the organizational tree) - two independent hierarchies, mirroring CMO3's `targetDeformerGuid` vs
* `parentGuid`.
*
* リグ階層の変形器。Cubism は2種(ワープ/回転)のみ。変形系統([parent])と組織系統([partId])は別。
*/
sealed interface Deformer {
val id: DeformerId
/** The user-facing display name (CMO3 localName), e.g. "Warp Deformer of Bag front12"; the id when unnamed. */
val name: String
/** Parent deformer in the nesting (transform) hierarchy, or null at the root. */
val parent: DeformerId?
/** The part this deformer belongs to (organizational tree), or null at the root. */
val partId: PartId?
/**
* The deformer's per-channel keyform tracks.
*
* On the interface rather than only the subtypes because every generic walk over a rig - the
* parameter-delete scrub, the panel's effective-parameter set, the clamped-pose axis collection -
* needs the tracks without caring which kind of deformer carries them.
*/
val channelGrids: ChannelGrids
/**
* Blender-style selectable toggle: an unselectable deformer cannot be picked in the viewport.
* Maps inverted to CMO3's isLocked (Cubism lock = not selectable), which the CMO3 export
* lowering emits as isLocked = !isSelectable.
*/
val isSelectable: Boolean
/**
* The editor's eye toggle - a hidden deformer and everything under it does not render.
*
* MOC3 §5.6 s13; CMO3 ACParameterControllableSource.isVisible. A bake normally DELETES what the
* editor hides, so almost every imported deformer is visible; Azxiana is the one corpus model that
* keeps 7 hidden ones. Umamo's own export always carries hidden deformers (the export options
* offer no deformer toggle), which is what makes this round-trip rather than decay to true.
*/
val isVisible: Boolean
/**
* The deformer's second MOC3 flag (§5.6 s14), carried so a bake reproduces it.
*
* It is 1 on every deformer of every corpus model, so its meaning is unpinned - it is NOT the
* visibility toggle ([isVisible] is, by analogy with the art-mesh pair that a CMO3 join proved).
* Nothing reads it; it exists so the value survives a round trip instead of being invented.
*
* ONLY MOC3 HAS THIS. "Enabled" is just a guess as to what it is since it seems to behave like an enabled toggle.
*/
val isEnabled: Boolean
/**
* Warp deformer - a free-form-deformation (FFD) lattice: a [rows] × [columns] grid of control
* points whose displacement bends the bound geometry. The control-point positions are animated
* per keyform; only the lattice dimensions are static.
*/
data class Warp(
override val id: DeformerId,
override val name: String,
override val parent: DeformerId?,
override val partId: PartId?,
val rows: Int,
val columns: Int,
/** FFD interpolation mode: true = bilinear (quad), false = triangle split (the Umamo C++ Runtime's warp mode). */
val isQuadTransform: Boolean,
/**
* Per-parameter lattice control-point forms, or null if unkeyed.
*
* A warp carries no separate rest lattice, so this is the ONLY source of its geometry - an unkeyed
* warp therefore still cannot render, unlike an unkeyed drawable which falls back to its rest mesh.
*/
val geometryGrid: KeyformGrid<WarpLatticeForm>?,
/**
* The deformer's per-channel render tracks (opacity, multiply / screen color), each falling back to
* the statics below. These CASCADE onto every drawable under the deformer.
*/
override val channelGrids: ChannelGrids = ChannelGrids.Empty,
/** Static opacity used when [channelGrids] has no opacity track. */
val opacity: Float = 1f,
/** Static multiply color used when [channelGrids] has no multiply track. */
val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity,
/** Static screen color used when [channelGrids] has no screen track. */
val screenColor: ColorRgb = ColorRgb.ScreenIdentity,
override val isSelectable: Boolean = true,
override val isVisible: Boolean = true,
override val isEnabled: Boolean = true,
/**
* Additive blend-shape bindings on the lattice control points, applied on top of the
* [geometryGrid] result; empty when the deformer has none. (CMO3 keyformMorphTargetSet.)
*/
val blendShapes: List<BlendShapeBinding<WarpForm>> = emptyList(),
) : Deformer
/**
* Rotation deformer - a nesting pivot transform. Its origin/angle/scale are animated per keyform
* [baseAngle] is the static editor reference angle.
*/
data class Rotation(
override val id: DeformerId,
override val name: String,
override val parent: DeformerId?,
override val partId: PartId?,
val baseAngle: Float,
/** Per-parameter pivot-transform forms (origin / angle / scale), or null if unkeyed. */
val geometryGrid: KeyformGrid<RotationPivotForm>?,
/**
* The deformer's per-channel tracks: the render channels (opacity, multiply / screen color) that
* cascade onto every drawable underneath, plus the two reflection FLAGS. The flags live here rather
* than on the pivot form because they snap to the floor cell instead of blending, so they do not
* belong beside values that interpolate.
*/
override val channelGrids: ChannelGrids = ChannelGrids.Empty,
/** Static opacity used when [channelGrids] has no opacity track. */
val opacity: Float = 1f,
/** Static multiply color used when [channelGrids] has no multiply track. */
val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity,
/** Static screen color used when [channelGrids] has no screen track. */
val screenColor: ColorRgb = ColorRgb.ScreenIdentity,
/** Static horizontal reflection used when [channelGrids] has no flip-X track. */
val flipX: Boolean = false,
/** Static vertical reflection used when [channelGrids] has no flip-Y track. */
val flipY: Boolean = false,
override val isSelectable: Boolean = true,
override val isVisible: Boolean = true,
override val isEnabled: Boolean = true,
/**
* Additive blend-shape bindings on the pivot transform, applied on top of the [geometryGrid]
* result; empty when the deformer has none. (CMO3 keyformMorphTargetSet.)
*/
val blendShapes: List<BlendShapeBinding<RotationForm>> = emptyList(),
) : Deformer
}
/*
* The statics every deformer subtype carries, read through the sealed supertype.
*
* Deformer is a sealed interface whose statics live on the subtypes, so anything wanting "this deformer's
* opacity" had to write the two-branch when itself - and three separate copies of each had accumulated
* (the Properties row, the edit op, and their tests), so adding a third subtype meant fixing them in
* lockstep and any divergence would silently make the panel disagree with the edit. One definition here,
* exhaustive over the sealed type, so a new subtype is a compile error in exactly one place.
*/
/** This deformer's static opacity, whichever subtype it is. */
val Deformer.opacity: Float
get() =
when (this) {
is Deformer.Warp -> opacity
is Deformer.Rotation -> opacity
}
/** This deformer's static multiply color, whichever subtype it is. */
val Deformer.multiplyColor: ColorRgb
get() =
when (this) {
is Deformer.Warp -> multiplyColor
is Deformer.Rotation -> multiplyColor
}
/** This deformer's static screen color, whichever subtype it is. */
val Deformer.screenColor: ColorRgb
get() =
when (this) {
is Deformer.Warp -> screenColor
is Deformer.Rotation -> screenColor
}
@@ -0,0 +1,87 @@
package org.umamo.runtime.model
/**
* An art mesh's static (rest-pose) geometry: interleaved [positions] and [uvs] (x then y per vertex)
* and the triangle [indices] (three per polygon). Deformation deltas live in the drawable's keyform
* grid; this is the base the deltas are applied to in `p = base + Σ wᵢ·Δᵢ`.
*
* A plain `class`, not a `data class`: the fields are arrays, whose identity-based `equals` would make
* a generated structural `equals` quietly wrong (the same trap [Keyform] sidesteps by hand). A mesh is
* referenced, not value-compared, so reference identity is the honest default here.
*/
class DrawableMesh(
val positions: FloatArray,
val uvs: FloatArray,
val indices: IntArray,
) {
/** Vertex count - two floats (x, y) per vertex. */
val vertexCount: Int get() = positions.size / 2
/** Triangle (polygon) count - three indices per triangle. */
val triangleCount: Int get() = indices.size / 3
}
/** The two triangles a birth quad is always wound with: corners in the order left-top, right-top, right-bottom, left-bottom. */
private val BIRTH_QUAD_INDICES = intArrayOf(0, 1, 2, 0, 2, 3)
/**
* Whether this mesh is still the quad an artwork import gave the drawable at birth, untouched since:
* four corners wound as the import winds them, an axis-aligned rectangle, and texture coordinates that
* are the same rectangle in the tile's art - each corner samples exactly the art pixel under it. A
* moved vertex breaks the alignment or the position-to-texel agreement, a subdivision the count, so no
* edit history is needed to tell an untouched quad from an authored mesh.
*
* Read on a reload to decide whether the drawable gets a fresh quad over the new art (an untouched
* quad has nothing to preserve) or keeps its mesh.
*
* @param FloatArray artUvs The mesh's texture coordinates in the ART frame (0..1 across the tile).
* @param Int tileWidth The tile's width in pixels.
* @param Int tileHeight The tile's height in pixels.
* @param Float layerLeft The layer's canvas x at the last read - the art frame's origin.
* @param Float layerTop The layer's canvas y at the last read.
* @param Float tolerance How far, in pixels, a corner may sit from its texel before the quad
* counts as edited; half a pixel absorbs float round trips.
* @return Boolean True for an untouched birth quad.
*/
fun DrawableMesh.isUntouchedBirthQuad(
artUvs: FloatArray,
tileWidth: Int,
tileHeight: Int,
layerLeft: Float,
layerTop: Float,
tolerance: Float = 0.1f,
): Boolean {
if (vertexCount != 4 || artUvs.size != 8 || !indices.contentEquals(BIRTH_QUAD_INDICES)) {
return false
}
val left = positions[0]
val top = positions[1]
val right = positions[2]
val bottom = positions[5]
val axisAligned =
near(positions[3], top, tolerance) &&
near(positions[4], right, tolerance) &&
near(positions[6], left, tolerance) &&
near(positions[7], bottom, tolerance)
if (!axisAligned || right <= left || bottom <= top) {
return false
}
for (corner in 0 until 4) {
val texelX = artUvs[corner * 2] * tileWidth + layerLeft
val texelY = artUvs[corner * 2 + 1] * tileHeight + layerTop
if (!near(texelX, positions[corner * 2], tolerance) || !near(texelY, positions[corner * 2 + 1], tolerance)) {
return false
}
}
return true
}
/**
* Whether two coordinates agree within [tolerance].
*
* @param Float first One coordinate.
* @param Float second The other.
* @param Float tolerance The largest difference that still counts as agreement.
* @return Boolean True when they agree.
*/
private fun near(first: Float, second: Float, tolerance: Float): Boolean = kotlin.math.abs(first - second) <= tolerance
@@ -0,0 +1,126 @@
package org.umamo.runtime.model
/*
* The per-channel keyform tracks: an entity's animatable non-geometry properties, each keyed on its own
* axes at its own key positions rather than riding one bundled keyform cell.
*
* Cubism's keyform cell is all-or-nothing - CArtMeshForm carries positions, draw order, opacity, and the
* multiply/screen tints together, so keying any one of them keys all of them. Splitting them lets a
* rigger key opacity on one parameter without touching geometry, which is the whole point: the bundled
* shape cannot express it at all. ONE enum plus ONE map rather than a map per value type, because every
* generic walk over an entity's channels - the parameter-delete scrub, compaction, the export refine,
* the dope-sheet track list - needs to iterate them uniformly, and a flag channel fits no scalar/color
* split.
*/
/** The kind of value a [FormChannel] stores, and therefore how it interpolates between keys. */
enum class ChannelValueKind {
/** Blends linearly. */
SCALAR,
/** Blends linearly per component. */
COLOR,
/** Snaps to the floor cell - a boolean has no meaningful midpoint. */
FLAG,
}
/**
* One animatable non-geometry channel of a keyable entity.
*
* Every format citation for a keyformed scalar or color lives here, now that the bundled form classes
* have retired to being import intermediates. Adding a channel later is one constant, not a new field
* on every owner.
*/
enum class FormChannel(val valueKind: ChannelValueKind) {
// CMO3: CArtMeshForm field drawOrder / CPartForm field drawOrder; MOC3 §5.6 keyform draw order.
DRAW_ORDER(ChannelValueKind.SCALAR),
// CMO3: CArtMeshForm / CPartForm / ACDeformerForm field opacity; MOC3 §5.6 keyform opacity.
OPACITY(ChannelValueKind.SCALAR),
// CMO3: CArtMeshForm / CPartForm / ACDeformerForm field multiplyColor; MOC3 color-table rows 108-113.
MULTIPLY_COLOR(ChannelValueKind.COLOR),
// CMO3: CArtMeshForm / CPartForm / ACDeformerForm field screenColor; MOC3 color-table rows 108-113.
SCREEN_COLOR(ChannelValueKind.COLOR),
// CMO3: CRotationDeformerForm field isReflectX; MOC3 §5.6 s66 rotation reflect x. The Umamo C++
// Runtime snaps this per grid cell into the affine's flipX, so it is NOT interpolable.
FLIP_X(ChannelValueKind.FLAG),
// CMO3: CRotationDeformerForm field isReflectY; MOC3 §5.6 s67 rotation reflect y.
FLIP_Y(ChannelValueKind.FLAG),
// CMO3: CGlueForm field intensity; MOC3 §5.6 s100 glue intensities.
GLUE_INTENSITY(ChannelValueKind.SCALAR),
}
/**
* The value stored in one cell of a channel track.
*
* Sealed so interpolation is an exhaustive `when` rather than a strategy object: adding a fourth value
* kind becomes a compile error at every site that has to handle it.
*/
sealed interface ChannelValue {
/** The channel's [ChannelValueKind], so a generic walk can check a value against its channel. */
val valueKind: ChannelValueKind
/** A linearly blended scalar (opacity, draw order, glue intensity). */
data class Scalar(val value: Float) : ChannelValue {
override val valueKind: ChannelValueKind get() = ChannelValueKind.SCALAR
}
/** A per-component blended color (the multiply / screen tints). */
data class Color(val color: ColorRgb) : ChannelValue {
override val valueKind: ChannelValueKind get() = ChannelValueKind.COLOR
}
/** A boolean that snaps to the floor cell (the rotation deformer's reflection flags). */
data class Flag(val flag: Boolean) : ChannelValue {
override val valueKind: ChannelValueKind get() = ChannelValueKind.FLAG
}
}
/**
* One owner's non-geometry channel tracks, keyed by channel.
*
* A plain class with referential equality, matching [KeyformGrid], so the renderer's identity-based
* model diff keeps behaving exactly as it does today - a data class here would make an unrelated
* deep compare run on every frame's reconcile. A channel with no entry falls back to the owner's
* static field for that property, which after import compaction is the overwhelmingly common case;
* [Empty] is shared so it allocates nothing.
*/
class ChannelGrids(val gridsByChannel: Map<FormChannel, KeyformGrid<ChannelValue>>) {
/** True when this owner has no channel tracks at all (every property reads its static value). */
val isEmpty: Boolean get() = gridsByChannel.isEmpty()
/**
* The track for [channel], or null when this owner does not key it.
*
* @param FormChannel channel The channel to look up.
* @return KeyformGrid? The channel's track, or null when unkeyed.
*/
operator fun get(channel: FormChannel): KeyformGrid<ChannelValue>? = gridsByChannel[channel]
/**
* Whether this owner's [channel] track holds any value other than [identity].
*
* A track's mere PRESENCE is not use. A MOC3 import fans every channel out of one bundled grid, so a
* drawable that was never tinted still gets a color track of pure identity cells - and compaction
* deliberately leaves it alone when its axis does not bracket the parameter's range, since an
* out-of-span pose has to fall back to the static. Counting that as "the document uses color"
* makes an export warn about losing a tint that does not exist.
*
* @param FormChannel channel The channel to inspect.
* @param ChannelValue identity The channel's neutral value.
* @return Boolean True when some cell differs from the identity.
*/
fun varies(channel: FormChannel, identity: ChannelValue): Boolean =
this[channel]?.cells?.any { cell -> cell.form != identity } ?: false
companion object {
/** The shared no-tracks instance - every property falls back to its owner's static value. */
val Empty: ChannelGrids = ChannelGrids(emptyMap())
}
}
@@ -0,0 +1,41 @@
package org.umamo.runtime.model
/*
* The geometry half of a split keyform: the only channel whose payload is per-vertex / per-control-point,
* the only one the GPU consumes, and the only one whose out-of-range pose HIDES its entity. That is why
* geometry stays a separate typed field on each owner rather than another FormChannel entry - a scalar
* track can never be handed to the delta-texture bake by mistake, because it would not type-check.
*
* These mirror the bundled MeshForm / WarpForm / RotationForm minus their scalar and color channels, which
* moved to ChannelGrids. The bundled classes stay as the import intermediate and the blend-shape payload.
*/
/**
* A drawable keyform's geometry: per-vertex position deltas (interleaved x,y) relative to the mesh base.
*
* Stored as deltas rather than absolute positions to match the GPU vertex-shader morph `p = base + Σ wᵢ·Δᵢ`
* - the delta table is exactly what the shader texel-fetches per active corner.
*/
class MeshDeltaForm(val positionDeltas: FloatArray)
/**
* A warp deformer keyform's geometry: the ABSOLUTE FFD lattice control-point positions (interleaved x,y).
*
* Absolute, not deltas: a warp source carries no separate rest lattice to be relative to, so these forms
* are the only place the lattice geometry exists. That is why an unkeyed warp cannot yet render.
*/
class WarpLatticeForm(val controlPoints: FloatArray)
/**
* A rotation deformer keyform's geometry: the ABSOLUTE pivot transform captured at one grid cell.
*
* The reflection flags that rode the bundled RotationForm are now [FormChannel.FLIP_X] / [FormChannel.FLIP_Y]
* channels, because they snap to the floor cell rather than blending and so do not belong beside values
* that interpolate.
*/
class RotationPivotForm(
val originX: Float,
val originY: Float,
val angle: Float,
val scale: Float,
)
@@ -0,0 +1,77 @@
package org.umamo.runtime.model
/**
* One glued vertex pair: vertex [indexA] of the glue's mesh A welded to vertex [indexB] of mesh B, each
* pulled toward the other by its per-side weight. Indices are into the meshes' deformed position arrays,
* so each importer has to land them in that space: a CMO3 import resolves that format's stable vertex
* UIDs, while MOC3 (§5.6 s99) already stores them mesh-local.
*/
class GluePair(
val indexA: Int,
val indexB: Int,
val weightA: Float,
val weightB: Float,
)
/**
* A glue keyform: the weld intensity (0 = no weld, 1 = full) at one grid cell.
*
* Retained as the CMO3 / MOC3 import intermediate; the model itself keys weld strength through
* [FormChannel.GLUE_INTENSITY] on [Glue.channelGrids].
*/
class GlueForm(val intensity: Float)
/**
* A glue affecter - seam-welds two art meshes' shared-edge vertices so they move together (a tail's
* two skinned strips, a sleeve seam, …). It runs after both meshes are deformed: for each [GluePair]
* each side slides toward the other by `weight · intensity` from the pre-blend positions -
* `A' = A + (B−A)·wA·i`, `B' = B + (A−B)·wB·i`. Without it the welded strips drift apart into "two
* copies".
*
* Weld strength is the [FormChannel.GLUE_INTENSITY] track when one is keyed, else the static
* [intensity] - which is 1 (full weld) for a glue that was never animated.
*/
class Glue(
val meshA: DrawableId,
val meshB: DrawableId,
val pairs: List<GluePair>,
val channelGrids: ChannelGrids = ChannelGrids.Empty,
val intensity: Float = 1f,
/**
* The source's authored identifier (MOC3 §5.6 s90, e.g. "Glue__ArtMesh48__ArtMesh49"), or null
* when the source carried none.
*
* A plain string rather than a typed id because nothing REFERENCES a glue - it is addressed only by
* list position, so there is no lookup for an id type to make safe. It is carried purely so a
* round trip writes back the name the model was authored with instead of a synthesized one.
*/
val id: String? = null,
) {
/**
* This glue with the given fields replaced, every other one carried over.
*
* Every rewrite goes through here rather than the constructor, so changing one field cannot silently
* drop another - a positional rebuild that stops early resets the rest to their defaults, and [id]
* is the one whose default is indistinguishable from a source that carried none.
*
* Hand-written rather than a `data class` conversion: the generated `equals`/`hashCode` would
* compare [pairs] and the channel grids by reference anyway, so that would buy this one method at
* the cost of a misleading equality contract.
*
* @param DrawableId meshA The first welded mesh.
* @param DrawableId meshB The second welded mesh.
* @param List<GluePair> pairs The welded vertex pairs.
* @param ChannelGrids channelGrids The keyed channel tracks.
* @param Float intensity The static weld strength.
* @param String? id The source's authored identifier.
* @return Glue The rewritten glue.
*/
fun copy(
meshA: DrawableId = this.meshA,
meshB: DrawableId = this.meshB,
pairs: List<GluePair> = this.pairs,
channelGrids: ChannelGrids = this.channelGrids,
intensity: Float = this.intensity,
id: String? = this.id,
): Glue = Glue(meshA, meshB, pairs, channelGrids, intensity, id)
}
@@ -0,0 +1,50 @@
package org.umamo.runtime.model
import kotlin.jvm.JvmInline
/**
* Typed identifiers for model entities.
*
* Each is a `@JvmInline value class` - a zero-cost wrapper the compiler erases to the bare
* underlying value where it can, while keeping the types distinct at compile time. This replaces
* the "stringly-typed" anti-pattern (`Map<String, …>` where any String fits any slot): you can't
* pass a [DrawableId] where a [PartId] is wanted. Cheap safety, no allocation.
*
* The import is load-bearing, not noise: `kotlin.jvm.*` is a default import only on JVM targets, so
* without it this file stops compiling the moment a non-JVM target (Kotlin/Native, for iPadOS) is
* added. The annotation itself is an optional expectation, so non-JVM targets simply ignore it.
*/
@JvmInline
value class PartId(val raw: String)
@JvmInline
value class DrawableId(val raw: String)
@JvmInline
value class DeformerId(val raw: String)
@JvmInline
value class ParameterId(val raw: String)
@JvmInline
value class ParameterGroupId(val raw: String)
@JvmInline
value class KeyformId(val raw: String)
/**
* One piece of source art in the document's atlas.
*
* Distinct from a source-LAYER identity, which says which artwork file and layer a tile came from:
* this only names a tile within one document, and the two coincide only for a rig built from layered
* art in the first place.
*/
@JvmInline
value class AtlasTileId(val raw: String)
/**
* One artwork file in the document's source list ([PuppetModel.sources]) - what a tile's
* [SourceLayerRef] names as the file half of its binding.
*/
@JvmInline
value class ArtSourceId(val raw: String)
@@ -0,0 +1,82 @@
package org.umamo.runtime.model
/*
* How a keyform channel is ADDRESSED: an entity plus one of its channels.
*
* In :runtime rather than :edit because it is vocabulary about the model, not about editing - the renderer
* needs it too, to accept per-channel overrides for a value the user has typed but not yet keyed, and
* :render depends on :runtime but not on :edit.
*/
/**
* The entity a keyform channel belongs to.
*
* Its own taxonomy rather than [SelectionTarget] because a glue is keyable but not selectable, and a glue
* carries no id - it is addressed by the mesh pair it welds, which is stable across edits in a way a list
* index is not.
*/
sealed interface KeyformOwner {
/** A textured drawable mesh. */
data class Drawable(val id: DrawableId) : KeyformOwner
/** An organizational tree part. */
data class Part(val id: PartId) : KeyformOwner
/** A warp or rotation deformer. */
data class Deformer(val id: DeformerId) : KeyformOwner
/** A glue affecter, addressed by the pair of meshes it welds. */
data class Glue(val meshA: DrawableId, val meshB: DrawableId) : KeyformOwner
}
/**
* One keyable property: an entity and one of its channels.
*
* This is what a keyform insert aims at, and what the properties panel and the keyform sheet both resolve
* a hover or a click into.
*
* @property KeyformOwner owner The entity.
* @property FormChannel channel The channel on it.
*/
data class KeyableTarget(
val owner: KeyformOwner,
val channel: FormChannel,
)
/**
* One keyform TRACK: an entity's geometry, or one of its channels.
*
* The sheet edits both with the same three gestures (drag a key, insert one, remove one), so it addresses
* them through one type rather than branching per gesture. They stay distinct cases rather than folding
* geometry into [FormChannel] because geometry is a separate typed field on every owner precisely so a
* scalar track can never reach the delta-texture builder - a GEOMETRY channel constant would undo that.
*/
sealed interface KeyformTrackRef {
/** The entity the track belongs to. */
val owner: KeyformOwner
/** A channel track, holding [ChannelValue] cells. */
data class Channel(val target: KeyableTarget) : KeyformTrackRef {
override val owner: KeyformOwner get() = target.owner
}
/** The owner's geometry track, holding whichever form type that owner deforms with. */
data class Geometry(override val owner: KeyformOwner) : KeyformTrackRef
}
/**
* This model's channel tracks for [owner], or null when it has no such entity.
*
* Public and here rather than private in an editing file because both the edit ops and the UI's keyed-field
* tinting need it, and two copies of an owner dispatch is exactly how the two drift.
*
* @param KeyformOwner owner The entity to look up.
* @return ChannelGrids? Its tracks, or null when the entity is absent.
*/
fun PuppetModel.channelGridsOf(owner: KeyformOwner): ChannelGrids? =
when (owner) {
is KeyformOwner.Drawable -> drawables.firstOrNull { it.id == owner.id }?.channelGrids
is KeyformOwner.Part -> parts.firstOrNull { it.id == owner.id }?.channelGrids
is KeyformOwner.Deformer -> deformers.firstOrNull { it.id == owner.id }?.channelGrids
is KeyformOwner.Glue -> glues.firstOrNull { it.meshA == owner.meshA && it.meshB == owner.meshB }?.channelGrids
}
@@ -0,0 +1,153 @@
package org.umamo.runtime.model
/**
* One axis of a keyform grid: the parameter it keys on and the key values along it (the parameter
* values where keyforms exist, e.g. `[-1, 0, 1]`).
*/
class KeyformAxis(
val parameterId: ParameterId,
val keys: FloatArray,
)
/**
* A single keyform cell: its N-D [coordinate] (key index per axis, in [KeyformGrid.axes] order) and
* the deformation [form] captured at that parameter combination.
*/
class KeyformCell<TForm>(
val coordinate: IntArray,
val form: TForm,
)
/**
* The keyform grid for one controllable entity (drawable / deformer): the [axes] (one parameter each)
* and the keyed [cells]. `cells.size == Π(axis key counts)` - the "interpolation" count the editor
* reports. Cells are tagged with their coordinate rather than stored row-major, so the evaluator
* can build whatever lookup the deformation math needs.
*/
class KeyformGrid<TForm>(
val axes: List<KeyformAxis>,
val cells: List<KeyformCell<TForm>>,
) {
/**
* This grid's per-axis strides for folding a coordinate into a linear cell index.
*
* Axis 0 is the FASTEST varying (stride 1). The resulting index is the shared contract between a
* WeightedCell, a stored cell, and the GPU delta texture's column - defined HERE, on the type that
* owns it, so the evaluator, the shape queries, and the grid algebra cannot drift apart.
*
* @return IntArray One stride per axis, in axis order.
*/
fun strides(): IntArray {
val strides = IntArray(axes.size)
var stride = 1
for (axisIndex in axes.indices) {
strides[axisIndex] = stride
stride *= axes[axisIndex].keys.size
}
return strides
}
/**
* Folds a per-axis key-index [coordinate] into this grid's linear cell index.
*
* A coordinate shorter than the axis list contributes only the axes it covers, matching the
* defensive handling of a malformed imported cell.
*
* @param IntArray coordinate The key index per axis, in axis order.
* @return Int The stride-folded linear index.
*/
fun linearIndexOf(coordinate: IntArray): Int {
val strides = strides()
var linearIndex = 0
val axisCount = minOf(coordinate.size, strides.size)
for (axisIndex in 0 until axisCount) {
linearIndex += coordinate[axisIndex] * strides[axisIndex]
}
return linearIndex
}
/**
* The cells indexed by their stride-folded linear index, built on first use and cached.
*
* Cached because the grid is immutable and the per-frame evaluator once rebuilt this map on every
* channel sample of every entity - hundreds of transient HashMaps per scrub frame on a corpus rig.
* PUBLICATION mode: a racing first read may compute twice but never blocks, and the render thread
* must never take a lock.
*/
val cellsByLinearIndex: Map<Int, KeyformCell<TForm>> by lazy(LazyThreadSafetyMode.PUBLICATION) {
val byIndex = HashMap<Int, KeyformCell<TForm>>(cells.size)
for (cell in cells) {
byIndex[linearIndexOf(cell.coordinate)] = cell
}
byIndex
}
}
/**
* A drawable keyform: per-vertex position deltas (interleaved x,y) relative to the mesh base
* (`p = base + Σ wᵢ·Δᵢ`, stored as deltas to match the GPU vertex-shader morph), plus the animatable
* scalars that ride on the same keyform. [drawOrder] (Cubism default 500) is the primary render-order
* sort key; [opacity] (0..1) scales the drawable's alpha; [multiplyColor] / [screenColor] tint the
* drawable per the Cubism per-art-mesh color (CMO3 `CArtMeshForm.multiplyColor`/`screenColor`, MOC3
* color-table rows 108-113), left at their identities on pre-5.3 sources. All blend with the same
* multilinear weights as the positions.
*/
class MeshForm(
val positionDeltas: FloatArray,
// Defaults are Cubism's own (drawOrder 500, fully opaque, identity tints); the CMO3 importer always
// sets them explicitly, so the defaults only serve geometry-only unit tests that don't exercise these.
val drawOrder: Float = DEFAULT_DRAW_ORDER.toFloat(),
val opacity: Float = 1f,
val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity,
val screenColor: ColorRgb = ColorRgb.ScreenIdentity,
)
/**
* A part keyform: the animatable per-cell channels of a part, riding the part's own keyform grid.
* [drawOrder] positions a grouped part's stacking slot (Cubism `CPartForm.drawOrder`); the
* remaining channels are the layer composite's keyformed state ([opacity], [multiplyColor],
* [screenColor] - CMO3 `CPartForm.opacity`/`multiplyColor`/`screenColor`, MOC3 §5.6 section 161 +
* the color-table offscreen prefix rows), meaningful only when the part's group mode is Isolated
* and left at their identities otherwise.
*/
class PartForm(
val drawOrder: Float,
val opacity: Float = 1f,
val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity,
val screenColor: ColorRgb = ColorRgb.ScreenIdentity,
)
/**
* A warp-deformer keyform: the absolute FFD control-point positions (interleaved x,y). Warp
* sources carry no separate rest lattice, so the forms are kept absolute; the evaluator interpolates
* them directly.
*
* [opacity] / [multiplyColor] / [screenColor] are the deformer's own render channels, which CASCADE
* down the deformer chain onto every drawable underneath (see `DeformerCascade`). Riggers use the
* opacity as a parameter-driven subtree show/hide switch, so dropping it renders whole effect
* subtrees permanently visible. (CMO3 `ACDeformerForm.opacity`/`multiplyColor`/`screenColor`;
* MOC3 `WarpKeyform`.) A deformer has no draw order - that is a drawable/part concept.
*/
class WarpForm(
val controlPoints: FloatArray,
val opacity: Float = 1f,
val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity,
val screenColor: ColorRgb = ColorRgb.ScreenIdentity,
)
/**
* A rotation-deformer keyform: the absolute pivot transform captured at this grid cell, plus the
* same cascading render channels a [WarpForm] carries.
*/
class RotationForm(
val originX: Float,
val originY: Float,
val angle: Float,
val scale: Float,
/** Reflection flags (the Umamo C++ Runtime snaps these per grid cell into the affine's flipX/flipY). */
val flipX: Boolean,
val flipY: Boolean,
val opacity: Float = 1f,
val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity,
val screenColor: ColorRgb = ColorRgb.ScreenIdentity,
)
@@ -0,0 +1,105 @@
package org.umamo.runtime.model
/**
* The two parameter kinds Cubism distinguishes: a NORMAL parameter drives keyform-grid
* interpolation (circle points on the slider); a BLEND_SHAPE parameter drives additive
* [BlendShapeBinding] deltas (square points).
*
* CMO3: CParameterSource field paramType (NORMAL | MORPH_TARGET). MOC3 v4+: Parameter types,
* section index 114 (0 normal, 1 blend-shape).
*/
enum class ParameterKind {
NORMAL,
BLEND_SHAPE,
}
/**
* An animation axis, e.g. `ParamAngleX`. Drives keyform blending at runtime.
*
* [id] is the format-level identifier (`ParamAngleX`, …) - kept verbatim for interop, never
* localised. [name] is the user-facing display name (the editor's `cdi3`-style label), free to
* localise.
*/
data class Parameter(
val id: ParameterId,
val name: String,
val min: Float,
val max: Float,
val default: Float,
val kind: ParameterKind = ParameterKind.NORMAL,
/**
* Whether the axis WRAPS at its limits instead of clamping - a value past [max] re-enters at [min].
*
* Used for continuously-cycling rigs (a spinning wheel, a looping tail). MOC3 §5.5 s54. The
* evaluator does not honor it yet, so it feeds the runtime-target feature scan and MOC3
* round-trip fidelity rather than driving deformation.
*/
val repeat: Boolean = false,
)
/**
* A LINKED ("combined") pair of parameters that the editor presents as a single 2D pad instead of two
* independent sliders - e.g. head "Angle X" + "Angle Y" shown as one grid control. [horizontal] drives
* the X axis (Cubism's first/topmost member of the pair), [vertical] drives the Y axis (the next member
* in document order). Both remain ordinary, independently-keyable [Parameter]s; this record only states
* that they should be scrubbed together as a 2D unit.
*
* @property ParameterId horizontal The X-axis parameter (the pair's first/topmost member).
* @property ParameterId vertical The Y-axis parameter (the pair's second/bottommost member).
*/
data class ParameterLink(
val horizontal: ParameterId,
val vertical: ParameterId,
)
/**
* One node of the parameter-panel group tree - Cubism's "CParameterGroup" organisation, the
* collapsible groups the editor sorts parameters into. A node is either a leaf [Param] (one
* parameter axis) or a [Group] (a named group holding ordered child nodes, which may nest). The
* tree records panel layout only; the flat [Parameter] list remains the authoritative source of axes
* (live values, ranges, links). A model with no groups has an empty tree, and callers fall back to
* rendering the flat list.
*/
sealed interface ParameterNode {
/**
* A leaf node binding one parameter axis into the panel tree by its id.
*
* @property ParameterId id The parameter this leaf represents.
*/
data class Param(val id: ParameterId) : ParameterNode
/**
* A named group of parameters, holding its [children] in editor panel order; groups may nest.
*
* @property ParameterGroupId id The group's stable identifier (display names are not unique).
* @property String name The group's display label (user data - never localised).
* @property Boolean initiallyOpen The editor's saved expanded state (CMO3 folderIsOpened).
* @property List children The ordered child nodes (parameters and/or nested groups).
*/
data class Group(
val id: ParameterGroupId,
val name: String,
val initiallyOpen: Boolean,
val children: List<ParameterNode>,
) : ParameterNode
}
/**
* A captured delta at a specific parameter value. The runtime blends across the N-D grid of
* keyforms: `p = base + Σ wᵢ·Δᵢ` (multilinear interpolation). Weights are cheap and computed
* CPU-side per frame; the per-vertex delta-sum runs in the vertex shader (see `:render`).
*/
data class Keyform(
val atValue: Float,
val delta: FloatArray,
) {
// data class with an array field: generated equals/hashCode use referential array equality,
// which is wrong for value semantics. Override so two keyforms with equal deltas compare equal.
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Keyform) return false
return atValue == other.atValue && delta.contentEquals(other.delta)
}
override fun hashCode(): Int = 31 * atValue.hashCode() + delta.contentHashCode()
}
@@ -0,0 +1,110 @@
package org.umamo.runtime.model
/*
* The rigger's coordinate frame. Every X or Z the rigger reads or types is measured from the world axes:
* (0, 0) is where the viewport's axis lines cross, the world origin, with X+ right and Z+ up.
*
* World space itself does not move. Its zero stays at the canvas's top-left corner (canvas x, negated
* canvas y), because the evaluator, the renderer, every importer and exporter, UMA, and every undo snapshot
* share it, and the rigger would see no difference if it were re-based. Only the numbers that cross the
* display boundary convert, through these helpers, and nothing shows a raw world coordinate.
*
* The Origin fields are the one reading that cannot be measured from the origin, because they place it.
* They are measured on the canvas instead, from its bottom-left corner with Z up, so they count the same
* direction as every other number.
*
* World z already grows upward, so the panel's Z is world z with only the origin subtracted - no sign flip.
*/
/**
* The origin-relative X of a world x: how far right of the world axes it sits.
*
* @param Float worldX A world-space x.
* @return Float The X the rigger reads.
*/
fun PuppetModel.originRelativeX(worldX: Float): Float = worldX - worldOriginX
/**
* The origin-relative Z of a world z: how far above the world axes it sits.
*
* @param Float worldZ A world-space z (grows upward).
* @return Float The Z the rigger reads.
*/
fun PuppetModel.originRelativeZ(worldZ: Float): Float = worldZ - worldOriginZ
/**
* The world x of an origin-relative X - the inverse of [originRelativeX].
*
* @param Float originRelativeX An X measured from the world axes.
* @return Float The world-space x.
*/
fun PuppetModel.worldXFromOriginRelative(originRelativeX: Float): Float = originRelativeX + worldOriginX
/**
* The world z of an origin-relative Z - the inverse of [originRelativeZ].
*
* @param Float originRelativeZ A Z measured from the world axes.
* @return Float The world-space z.
*/
fun PuppetModel.worldZFromOriginRelative(originRelativeZ: Float): Float = originRelativeZ + worldOriginZ
/**
* How far the world origin sits from the canvas's left edge, in canvas pixels - the Origin X reading.
*
* @return Float The origin's distance from the canvas's left edge.
*/
fun PuppetModel.originFromCanvasLeft(): Float = worldOriginX
/**
* How far the world origin sits above the canvas's bottom edge, in canvas pixels - the Origin Z reading.
*
* The canvas grows and shrinks at its bottom edge while the origin keeps its world point, so a canvas height
* change moves this reading by the same amount. With no canvas (height 0) it is the raw world z.
*
* @return Float The origin's height above the canvas's bottom edge.
*/
fun PuppetModel.originFromCanvasBottom(): Float = worldOriginZ + canvasHeight
/**
* The world-origin x for an Origin X reading - the inverse of [originFromCanvasLeft]. The canvas's left edge
* is world x 0, so this is the identity; it exists so both Origin rows convert the same way.
*
* @param Float fromCanvasLeft The origin's distance from the canvas's left edge.
* @return Float The world-origin x to store.
*/
fun PuppetModel.worldOriginXFromCanvasLeft(fromCanvasLeft: Float): Float = fromCanvasLeft
/**
* The world-origin z for an Origin Z reading - the inverse of [originFromCanvasBottom].
*
* @param Float fromCanvasBottom The origin's height above the canvas's bottom edge.
* @return Float The world-origin z to store.
*/
fun PuppetModel.worldOriginZFromCanvasBottom(fromCanvasBottom: Float): Float = fromCanvasBottom - canvasHeight
/**
* The world-origin x of a canvas's center - the default origin every importer and a new document derive.
*
* @param Float canvasWidth The canvas width, in canvas pixels.
* @return Float The world-origin x.
*/
fun canvasCenterWorldOriginX(canvasWidth: Float): Float = canvasWidth / 2f
/**
* The world-origin z of a canvas's center - the default origin every importer and a new document derive.
* The center is half the height down from the canvas's top edge, and world z is the negated canvas y.
*
* @param Float canvasHeight The canvas height, in canvas pixels.
* @return Float The world-origin z.
*/
fun canvasCenterWorldOriginZ(canvasHeight: Float): Float = -(canvasHeight / 2f)
/**
* Whether the world origin sits exactly on the canvas center, the default [canvasCenterWorldOriginX] and
* [canvasCenterWorldOriginZ] derive. A CMO3 stores no authored origin and its import derives the center, so
* only a centered origin survives a CMO3 round trip.
*
* @return Boolean True when the origin is the canvas center.
*/
fun PuppetModel.isOriginAtCanvasCenter(): Boolean =
worldOriginX == canvasCenterWorldOriginX(canvasWidth) && worldOriginZ == canvasCenterWorldOriginZ(canvasHeight)
@@ -0,0 +1,69 @@
package org.umamo.runtime.model
/**
* How a part groups its subtree for rendering. Three levels of one grouping mode - Cubism models
* these as two entangled checkboxes ("Group by Draw Order" and "offscreen drawing", the latter
* forcing the former on); Umamo folds them into a single sealed type so the illegal combination is
* unrepresentable and the Cubism naming stops at the CMO3/MOC3 import boundary.
*/
sealed interface PartGroupMode {
/**
* Transparent to draw order - the subtree's drawables stack individually with the enclosing
* group's. (Cubism: both checkboxes off.)
*/
data object PassThrough : PartGroupMode
/**
* The whole subtree takes one slot in the parent's stacking and orders internally among
* itself. (Cubism "Group by Draw Order"; CMO3 CPartSource.enableDrawOrderGroup.)
*/
data object Grouped : PartGroupMode
/**
* Grouped, and additionally rendered to its own layer and composited back into the scene as one
* unit per the part's [Part.composite] settings. Payload-free: the compositing settings live on the
* part (latent), not on the mode, so they survive the part leaving and re-entering Isolated. (Cubism
* 5.3 "offscreen drawing"; CMO3 CPartSource.useOffscreen; MOC3 §5.6 sections 152-163.)
*/
data object Isolated : PartGroupMode
}
/**
* A part's latent compositing settings: how the subtree's rendered layer blends back into the scene
* when the part's group mode is [PartGroupMode.Isolated]. Stored on [Part.composite] independent of the
* mode, so the settings survive the part leaving and re-entering Isolated (and the UMA native format can
* track them). The keyformed composite channels (opacity, multiply/screen colors) ride the part's
* [Part.channelGrids]; the static fallbacks here apply when that grid is absent, mirroring the
* [Part.drawOrder] + grid pattern. (Cubism 5.3 "offscreen drawing" - CMO3
* `CPartSource.useOffscreen` and friends; MOC3 §5.6 sections 152-163.)
*/
data class PartComposite(
/** The composite's color blend mode. (CMO3 colorComposition; MOC3 s157 colorMode.) */
val blendMode: BlendMode = BlendMode.Normal,
/** The composite's alpha blend mode. (CMO3 alphaComposition; MOC3 s157 alphaMode.) */
val alphaBlendMode: AlphaBlendMode = AlphaBlendMode.Over,
/**
* Drawables whose alpha clips the whole composite (Cubism clipping masks at the part level).
* Always drawables - a part chosen as Clipping ID in the editor is expanded to its constituent
* drawables at authoring time. (CMO3 clipGuidList; MOC3 offscreen mask prefix.)
*/
val maskedBy: List<DrawableId> = emptyList(),
/**
* Parts whose descendant drawables also clip the composite - an Umamo extension over the Cubism data
* model, which stores only drawable ids. Keeping the part reference (rather than expanding it at
* authoring time, as Cubism does) means the mask follows the part as its children change. The render
* tree sees the expansion, never these ids: [PuppetModel.deriveRenderRoot] resolves each part to its
* descendant drawables and merges them into [maskedBy] for the [RenderGroup] it builds, so the stored
* value keeps the grouping for the UI while the renderer stays drawable-only. A CMO3 export flattens
* this away (that format has nowhere to put it); UMA will carry it.
*/
val maskedByParts: List<PartId> = emptyList(),
/** When true, the clip is inverted - the composite shows outside the [maskedBy] coverage. (CMO3 invertClippingMask; MOC3 offscreen flags bit 3.) */
val invertMask: Boolean = false,
/** Static composite opacity (0..1) when the part has no keyform grid. (CMO3 CPartForm.opacity; MOC3 s161.) */
val opacity: Float = 1f,
/** Static multiply color when the part has no keyform grid. (CMO3 CPartForm.multiplyColor.) */
val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity,
/** Static screen color when the part has no keyform grid. (CMO3 CPartForm.screenColor.) */
val screenColor: ColorRgb = ColorRgb.ScreenIdentity,
)
@@ -0,0 +1,191 @@
package org.umamo.runtime.model
/*
* The document's atlas: the pages it packs onto and the tiles packed onto them.
*
* This is the source-to-atlas indirection made explicit. A drawable's uvs address a page, but what
* they MEAN is a position in its source art, and the placement is the only thing that connects the
* two - so a repack that moves pixels around a page must move uvs with them and leave the art mapping
* untouched. Keeping the placement as model state is what lets a repack be an undoable edit and lets
* an export write where the art actually went, rather than both guessing from uvs.
*/
/**
* One packed page's dimensions.
*
* Pixels are not model state - a page's bytes belong to the document, and hundreds of undo snapshots
* holding them would be ruinous - but the SIZE is, because a placement in page pixels means nothing
* without it and every uv derivation needs it.
*
* @property Int width The page width in pixels.
* @property Int height The page height in pixels.
*/
data class AtlasPage(
val width: Int,
val height: Int,
)
/**
* One piece of source art the atlas packs: its identity, its size, and where it landed.
*
* A tile is per ARTWORK, not per drawable - several drawables can sample one piece of art, and they all
* move together when it is repacked, which is why the placement lives here and not on the drawable.
*
* A null [placement] means the art is in the document but was never packed onto a page; drawables
* bound to it sample it directly and their uvs already address it.
*
* A [pinned] tile is one a rigger placed by hand and wants kept: a repack packs the other tiles
* around it and leaves its placement - page, position, rotation, and scale - exactly as it is.
* Record data, not editor state: it changes what a repack produces, so it persists on the tile in a
* `.uma` (docs/format/UMA.md § 5.4). CMO3 and MOC3 have nowhere to hold it, so the model diff
* ignores it and an export never sees it. A tile without a placement is never pinned - there is
* nothing to keep.
*
* @property AtlasTileId id The tile's stable document-local identity.
* @property String name The tile's display name.
* @property Int width The art's width in pixels.
* @property Int height The art's height in pixels.
* @property AtlasPlacement? placement Where it sits on its page, or null when it was never packed.
* @property SourceLayerRef? source The source layer this tile's art came from - the artwork file
* and the layer key within it - or null when the document retains no binding (a MOC3-origin rig;
* a CMO3-origin one recovers a name-keyed ref from its image chain). Editor and native-format
* data: no container format encodes it, the model diff reads it as tile metadata, and an export
* never sees it.
* @property Boolean pinned Whether a repack keeps this tile's placement where it is.
* @property AtlasTileId? replaces The tile this one superseded when its source layer was reloaded,
* or null for a tile born at import. A tile's pixels are immutable: reloading a layer mints a new
* tile (id `<root>~<n>`, see [reloadTileId]) so the old tile and its pixels stay addressable for undo,
* and this is the lineage a consumer keyed on the ORIGINAL tile follows - a CMO3 export resolves the
* reloaded tile to the model image its root imported from. Editor and native-format data, like [source].
*/
data class AtlasTile(
val id: AtlasTileId,
val name: String,
val width: Int,
val height: Int,
val placement: AtlasPlacement? = null,
val source: SourceLayerRef? = null,
val pinned: Boolean = false,
val replaces: AtlasTileId? = null,
)
/** The separator between a reloaded tile's root id and its revision number. */
private const val TILE_REVISION_SEPARATOR = '~'
/**
* The id this tile's lineage started from: the id before any `~<n>` revision suffix, or the id itself
* for a tile born at import. Readable from the id alone, so a consumer holding only the id (the CMO3
* export's model-image web) needs no tile lookup.
*/
val AtlasTileId.lineageRoot: AtlasTileId
get() {
val separator = raw.lastIndexOf(TILE_REVISION_SEPARATOR)
if (separator <= 0 || raw.substring(separator + 1).toIntOrNull() == null) {
return this
}
return AtlasTileId(raw.substring(0, separator))
}
/**
* The revision a tile id carries: 0 for a tile born at import, n for the n-th reload of its lineage.
*/
val AtlasTileId.revision: Int
get() {
val separator = raw.lastIndexOf(TILE_REVISION_SEPARATOR)
if (separator <= 0) {
return 0
}
return raw.substring(separator + 1).toIntOrNull() ?: 0
}
/**
* The id the next reload of [previous]'s lineage mints: the lineage root with the revision after
* [previous]'s, skipping any id [taken] already holds so a lineage can never collide with a tile the
* document happens to name that way.
*
* @param AtlasTileId previous The tile being superseded.
* @param Set taken Every tile id the document has.
* @return AtlasTileId The new tile's id.
*/
fun reloadTileId(previous: AtlasTileId, taken: Set<AtlasTileId>): AtlasTileId {
val root = previous.lineageRoot
var revision = previous.revision + 1
while (true) {
val candidate = AtlasTileId("${root.raw}$TILE_REVISION_SEPARATOR$revision")
if (candidate !in taken) {
return candidate
}
revision++
}
}
/**
* The policy the atlas's pages are composed under: which alpha counts as opaque when a tile is
* trimmed to its content, and how far each tile's edge color is bled, at zero alpha, into the gutter
* around it.
*
* Model state because the pages are DERIVED state. A placement records only where a tile's art
* sits, not which opaque sub-rectangle the packer trimmed it to or how wide a band it extruded, so a
* derivation re-runs both on the same pixels and must do so under the policy the pack used - held
* here, beside the placements, so an undo across a repack that changed the threshold re-derives the
* pages that repack composed rather than the current default's. Options that only decide WHERE
* tiles land (gutter, rotation, page shape) leave no trace here: the placements are their record.
*
* The defaults match the packer's own defaults; this module cannot see the packer, so the two are
* kept equal by the derivation gate that composes a pack's pages back from a lowered model.
*
* @property Int alphaThreshold Minimum alpha byte (1..255) for a pixel to count as opaque when trimming.
* @property Int extrude How many pixels of each tile's edge color are bled outward, at zero alpha.
*/
data class AtlasComposition(
val alphaThreshold: Int = 1,
val extrude: Int = 2,
) {
init {
require(alphaThreshold in 1..255) { "alphaThreshold must be in 1..255: $alphaThreshold" }
require(extrude >= 0) { "extrude must be non-negative: $extrude" }
}
companion object {
/** The policy of an atlas nothing has repacked: the packer's defaults. */
val Default: AtlasComposition = AtlasComposition()
}
}
/**
* A document's whole atlas: its pages and the tiles packed onto them.
*
* Empty for a document with no source art at all - a MOC3-origin rig, whose pages are the packed
* endpoint of someone else's pipeline and whose tiles were never separable.
*
* @property List<AtlasPage> pages The packed pages, in the document's own page order.
* @property List<AtlasTile> tiles Every piece of source art, in document order.
* @property Boolean storedUvsAddressPages Whether the drawables' stored texture coordinates address the
* packed PAGES rather than the art itself.
*
* A fact about the document, fixed when it was read, and deliberately NOT the display mode: a rigger
* toggling between the artwork and the atlas changes which texture is sampled, never what the stored
* coordinates mean. False for a document saved sampling its per-layer rasters - a packed atlas can
* sit beside it untouched - where the coordinates already address the art and inverting a placement
* over them would throw every mesh clear of its artwork.
* @property AtlasComposition composition The trim and extrusion policy the pages derive under - the one
* the last repack packed with, or the default for an atlas nothing has repacked.
*/
data class PuppetAtlas(
val pages: List<AtlasPage> = emptyList(),
val tiles: List<AtlasTile> = emptyList(),
val storedUvsAddressPages: Boolean = true,
val composition: AtlasComposition = AtlasComposition.Default,
) {
/** True when the document carries no source art at all. */
val isEmpty: Boolean
get() = pages.isEmpty() && tiles.isEmpty()
/** Tiles by id, for the per-drawable resolution every uv derivation starts from. */
val tileById: Map<AtlasTileId, AtlasTile> by lazy { tiles.associateBy { tile -> tile.id } }
companion object {
/** The atlas of a document with no source art. */
val Empty: PuppetAtlas = PuppetAtlas()
}
}
@@ -0,0 +1,434 @@
package org.umamo.runtime.model
/**
* The whole rig as a concrete, in-memory puppet: what `:runtime` evaluates and the editor renders.
* A parsed `.cmo3` / `.moc3` maps into this; the deformation core depends only on this model, never
* on the format's serialization quirks (that mapping lives in `:interop`).
*/
data class PuppetModel(
val parameters: List<Parameter>,
val parts: List<Part>,
val deformers: List<Deformer>,
val drawables: List<Drawable>,
/**
* The organizational tree's top level: sub-parts and drawables interleaved in parts-panel order, the
* same ordered child list as [Part.children]. Single source of truth for top-level structure and
* order; [parts] / [drawables] are flat lookup lists. Draw order derives from this (deriveRenderRoot).
*/
val rootChildren: List<OrgChild>,
/** The organizational tree root (the Parts panel's top), or null if the model is flat. */
val rootPartId: PartId?,
/** Glue affecters - seam-weld pairs of drawables' shared vertices after deformation. */
val glues: List<Glue> = emptyList(),
/**
* The draw-order group tree (Cubism's "Group by Draw Order" hierarchy) used to compute render order. A
* group-less model is one flat [RenderGroup]; empty (the default) means "fall back to the flat base order".
*/
val renderRoot: RenderGroup = RenderGroup(null, DEFAULT_DRAW_ORDER, emptyList()),
/**
* LINKED ("combined") parameter pairs - each renders as one 2D pad instead of two sliders. Empty
* (the default) means every parameter is an independent 1D axis. Both members of a link also remain
* in [parameters]; this list only records the X/Y pairing.
*/
val parameterLinks: List<ParameterLink> = emptyList(),
/**
* The parameter-panel group tree (Cubism's CParameterGroup organisation): the root group's children
* in panel order, each a [ParameterNode.Param] or a (possibly nested) [ParameterNode.Group]. Empty
* (the default) means the model has no groups, so the panel renders the flat [parameters] list. This
* is layout only - every leaf id also appears in [parameters], which stays the authoritative axis list.
*/
val parameterTree: List<ParameterNode> = emptyList(),
/**
* The document canvas size in world units (canvas px), or 0 when the source carried no canvas.
* Drawable rest positions live in canvas space, with the canvas rect spanning [0, canvasWidth] x
* [0, canvasHeight] (art may overhang it).
*/
val canvasWidth: Float = 0f,
/** The document canvas height in world units; see [canvasWidth]. */
val canvasHeight: Float = 0f,
/**
* The world origin in WORLD space (the deform eval's output space, canvas x / negated canvas y, whose
* zero is the canvas's top-left corner) - where the viewport's axis lines cross, the anchor for
* origin-relative operations (the 2D cursor's snap home, frame grids), and the zero point of every
* coordinate the rigger reads or types. Never shown raw: the helpers in OriginRelativeCoordinates.kt
* convert at the display boundary.
*
* Imported documents put it at the canvas center. A CMO3 import derives the center rather than reading
* CModelInfo.originInPixels, which is (0, 0) in every corpus model; a MOC3 import reads CanvasInfo's
* origin. (0, 0) when the source carried no canvas.
*
* Axis names follow the viewport's convention, X right, Y forward (depth), and Z up: wherever a name
* says it is world space, its vertical axis is Z (worldOriginZ, Cursor2d.worldZ, screenToWorldZ,
* setWorldOrigin(x, z)). Space-agnostic math keeps x / y - interleaved [x, y] arrays, MeshBounds, deltas,
* the camera's center, GLSL vec2 - as do canvas, screen, UV, and NDC names, and the deform eval's
* pre-negation space, whose y still grows downward.
*/
val worldOriginX: Float = 0f,
/** The world origin's z (up) in world space (negated canvas y); see [worldOriginX]. */
val worldOriginZ: Float = 0f,
/**
* Pixels per unit is used only for runtime export. It is stored inside of UMA and CMO3, but it is
* not used for anything internal to Umamo.
*
* Canvas pixels per model unit - the scale factor between the source's model space and the world
* space everything here is expressed in - or null when the document has no bake scale of its own.
*
* MOC3 stores geometry in model units around its canvas origin and this factor converts it, so a
* MOC3-origin document carries the value its file recorded. A CMO3 authors directly in canvas
* pixels and its `CModelInfo.pixelsPerUnit` is 1 on every corpus model, which describes the project
* rather than any bake - so a CMO3-origin document carries null and the export picks a default.
* Nothing in the editor or the evaluator reads it - both work purely in world space - but an EXPORT
* cannot invert the import without it: the root-space affine and the scale of every root-path
* rotation deformer both fold it in.
*
* NULLABLE rather than a sentinel because 1 is a legitimate bake scale. Inferring the origin from
* the magnitude instead would rescale a moc whose own scale happens to be 1 by the canvas width.
*/
val pixelsPerUnit: Float? = null,
/**
* The document's runtime-compatibility target; [RuntimeTarget.NoTarget] restricts nothing. Gates
* editing controls only - never rendering or saving. See [RuntimeTarget].
*/
val runtimeTarget: RuntimeTarget = RuntimeTarget.NoTarget,
/**
* Whether the puppet displays from its SOURCE ARTWORK rather than from the packed atlas pages.
*
* A display choice, but document content: the source formats author it (CMO3 stores it on its
* texture manager) and a rigger's answer to "am I looking at the art or at the pack?" belongs to
* the document, not to the app. Nothing in the evaluator reads it - it selects which texture the
* renderer samples, and false (the atlas) is the default because that is what a document carrying
* no such flag means.
*
* Honoring it is best-effort per drawable: art the document does not retain keeps rendering from
* the atlas, so the puppet stays whole rather than developing holes.
*/
val rendersFromSourceLayers: Boolean = false,
/**
* The document's source art and where it packs onto the atlas pages.
*
* Document content, and authored: a repack moves placements, so they have to undo, diff, and export
* like anything else the rigger changes. Empty for a document with no separable source art - a
* MOC3-origin rig, whose pages arrived already packed.
*
* Pixels are deliberately absent. A page's bytes and a tile's raster belong to the document, which
* loads them once; putting them here would put them in every undo snapshot.
*/
val atlas: PuppetAtlas = PuppetAtlas.Empty,
/**
* The artwork files this document was imported from, each with its layer inventory as of its last
* read - the baseline a re-import diffs against - or empty for a document with no linked source art.
*
* Document content, like the atlas: a re-import rebinds tiles through it, so it undoes and persists
* with the rest of the model. The UMA sources entry encodes it; the diff and every export ignore it.
*/
val sources: List<ArtSource> = emptyList(),
) {
/**
* Every part by id, built once per model instance.
*
* The model is immutable, so this cannot go stale, and the pose evaluation runs it every frame -
* rebuilding the map there allocates one entry per part per frame for data that never changes.
* Outside the primary constructor deliberately: it is derived, not state, and must stay out of
* `equals`, `hashCode`, and `copy`.
*/
val partById: Map<PartId, Part> by lazy { parts.associateBy { part -> part.id } }
}
/**
* Cubism's neutral draw order: the midpoint of the 0-1000 scale a part's slot and an art mesh's stacking
* both sort on, and what the official editor's Inspector shows for an untouched object.
*
* One constant for both, because it is one number in the format - a drawable's order is merely carried as a
* (keyable, therefore fractional) Float, so the Float sites read it .toFloat() rather than keeping a second
* copy that can drift.
*/
const val DEFAULT_DRAW_ORDER = 500
/**
* One ordered child of the organizational tree: a sub-part or a drawable. Cubism's parts panel keeps
* sub-parts and drawables in one interleaved sibling order per level (a loose mesh can sit between two
* folders), and that order is also the draw-order tiebreak. This sealed type is how [Part.children] and
* [PuppetModel.rootChildren] express that single order, instead of splitting parts and drawables apart.
*/
sealed interface OrgChild {
/**
* A sub-part child.
*
* @property PartId id The sub-part.
*/
data class Part(val id: PartId) : OrgChild
/**
* A drawable child.
*
* @property DrawableId id The drawable.
*/
data class Drawable(val id: DrawableId) : OrgChild
}
/** A node in the parts tree - the organizational hierarchy shown in the Parts panel. */
data class Part(
val id: PartId,
val name: String,
/**
* This part's ordered children - sub-parts and drawables interleaved, in parts-panel (top = front)
* order. The single source of truth for the hierarchy AND the panel order at this level; draw order
* derives from it (see [PuppetModel.deriveRenderRoot]).
*/
val children: List<OrgChild>,
/** The Parts-panel eyeball: when false, this part and everything under it are hidden (cascades). */
val isVisible: Boolean = true,
/** A "Guide Image" / sketch part - an editor reference overlay, excluded from runtime (MOC3) export. */
val isSketch: Boolean = false,
/**
* Blender-style selectable toggle: an unselectable part cannot be picked in the viewport.
* Maps inverted to CMO3's isLocked (Cubism lock = not selectable), which the CMO3 export
* lowering emits as isLocked = !isSelectable.
*/
val isSelectable: Boolean = true,
/**
* How this part groups its subtree for rendering: transparent to draw order (PassThrough),
* one slot in the parent's stacking (Grouped), or composited as one layer (Isolated).
* See [PartGroupMode].
*/
val groupMode: PartGroupMode = PartGroupMode.PassThrough,
/**
* The part's own draw order (0-1000, default 500) - the sort key for its slot when it is
* grouped or isolated. (CMO3 CPartForm.drawOrder / defaultOrder_forEditor.)
*/
val drawOrder: Int = DEFAULT_DRAW_ORDER,
/**
* The part's per-channel keyform tracks, empty for a fully static part.
*
* [FormChannel.DRAW_ORDER] animates a grouped part's stacking slot per pose, like a drawable's own
* draw order; [FormChannel.OPACITY] and the two color channels key an isolated part's composite.
* Each channel falls back to [drawOrder] / [composite] when it has no track.
*/
val channelGrids: ChannelGrids = ChannelGrids.Empty,
/**
* The part's compositing settings, stored latently regardless of [groupMode] so they survive the
* part leaving and re-entering [PartGroupMode.Isolated] (and so the UMA format can track them). Only
* applied while the part is Isolated - see [activeComposite], the accessor the render pipeline reads.
*/
val composite: PartComposite = PartComposite(),
/**
* Additive blend-shape bindings on this part's channels, applied on top of [channelGrids]; empty
* when the part has none.
*
* A part owns only ONE blendable channel - its draw order - so unlike a drawable or a deformer
* these records carry no geometry and no color. The effect is on stacking: a record can lift a
* grouped part's whole subtree in front of its siblings for the span of a parameter.
*/
val blendShapes: List<BlendShapeBinding<PartForm>> = emptyList(),
) {
/** True when this part composites its subtree as one layer. */
val isIsolated: Boolean
get() = groupMode is PartGroupMode.Isolated
/**
* The composite to apply when rendering: [composite] while the part is [PartGroupMode.Isolated], else
* null. The single "is this part compositing" signal the render tree keys off (its null-ness decides
* the offscreen-layer boundary), so the latent [composite] of a non-isolated part is never applied.
*/
val activeComposite: PartComposite?
get() = composite.takeIf { isIsolated }
}
/**
* A textured triangle mesh - the thing actually drawn. Two bindings place it: [partId] (organizational
* tree) and [parentDeformerId] (the deformer chain that deforms it) - these are independent
* hierarchies in Cubism.
*/
data class Drawable(
val id: DrawableId,
/** The user-facing display name (CMO3 localName), e.g. "ArtMesh1"; the id when unnamed. */
val name: String,
/** The innermost deformer that deforms this drawable, or null if it is undeformed. */
val parentDeformerId: DeformerId?,
val blendMode: BlendMode,
/** Drawables whose alpha clips this one (Cubism clipping masks). */
val maskedBy: List<DrawableId>,
/** Rest-pose mesh, or null if the source carried no geometry. */
val mesh: DrawableMesh?,
/**
* Per-parameter morph deltas over the mesh, or null if the drawable is unkeyed.
*
* An unkeyed drawable is a NORMAL state - freshly created, or one whose last keyform axis was
* removed - and renders at its rest mesh rather than vanishing.
*/
val geometryGrid: KeyformGrid<MeshDeltaForm>?,
/**
* The drawable's per-channel keyform tracks (draw order, opacity, multiply / screen color), each
* falling back to the statics below when it has no track.
*/
val channelGrids: ChannelGrids = ChannelGrids.Empty,
/** Static draw order (Cubism's 500) used when [channelGrids] has no draw-order track. */
val drawOrder: Float = DEFAULT_DRAW_ORDER.toFloat(),
/** Static opacity used when [channelGrids] has no opacity track. */
val opacity: Float = 1f,
/** Static multiply color used when [channelGrids] has no multiply track. */
val multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity,
/** Static screen color used when [channelGrids] has no screen track. */
val screenColor: ColorRgb = ColorRgb.ScreenIdentity,
/** When true, the clip is inverted - this drawable shows outside the [maskedBy] coverage. */
val invertMask: Boolean = false,
/**
* How the drawable's alpha combines with the destination (Cubism 5.3); pre-5.3 sources have no
* alpha mode and stay [AlphaBlendMode.Over]. (CMO3 alphaComposition; MOC3 s153 alphaMode.)
*/
val alphaBlendMode: AlphaBlendMode = AlphaBlendMode.Over,
/**
* When true, back faces are culled - a mesh flipped inside-out by deformation disappears
* instead of showing mirrored. Default false = double-sided, Cubism's default. (CMO3 culling;
* MOC3 = the INVERSE of drawable constant-flags bit 2, IS_DOUBLE_SIDED.)
*/
val culling: Boolean = false,
/** The drawable's own Parts-panel eyeball; the effective shown-state also folds in ancestor parts. */
val isVisible: Boolean = true,
/**
* Blender-style selectable toggle: an unselectable drawable cannot be picked in the viewport.
* Maps inverted to CMO3's isLocked (Cubism lock = not selectable), which the CMO3 export
* lowering emits as isLocked = !isSelectable.
*/
val isSelectable: Boolean = true,
/**
* The drawable whose texture-atlas binding this one shares, or null when it binds by its own [id].
* The atlas page mapping is keyed by the SOURCE format's drawable ids (see PuppetTextures), so a
* session-created copy (Object-mode duplicate) carries its source's id here and the renderer
* resolves the atlas through it; a copy of a copy inherits the original. Editor-only - no source
* format persists it.
*/
val textureSourceId: DrawableId? = null,
/**
* Which atlas page this drawable samples (MOC3 §5.6 s41), or -1 when the source carried none.
*
* Distinct from [textureSourceId], which says WHOSE binding to use; this is the binding itself.
* The renderer does not read it - it resolves pages through the source document's own map, keyed by
* drawable id - but a detached [PuppetModel] otherwise has no texture binding at all, so an export
* could not say which page a drawable belongs to. CMO3 has no equivalent field (it binds through
* the layered-art web instead), so a CMO3-origin drawable leaves this at -1.
*/
val texturePage: Int = -1,
/**
* The atlas tile whose art this drawable samples, or null when the document retains none for it.
*
* Distinct from [texturePage], which names a page in the RENDERER's numbering: this names a piece of
* source art in [PuppetModel.atlas], and the placement on that tile is what says where the art sits
* on its page. A drawable with no tile has no source-art view and renders from the atlas alone.
*/
val atlasTileId: AtlasTileId? = null,
/**
* Additive blend-shape bindings on this drawable's mesh, applied on top of the [geometryGrid]
* result; empty when the drawable has none. (CMO3 keyformMorphTargetSet.)
*/
val blendShapes: List<BlendShapeBinding<MeshForm>> = emptyList(),
)
/**
* The drawables that are actually shown, after cascading the Parts-panel visibility toggles: a drawable is
* shown only when its own [Drawable.isVisible] is set and every ancestor part up the tree is visible.
* This is Cubism's editor-preview rule - hiding a folder hides everything inside it (e.g. a hidden
* `[Guide Image]` sketch part hides its art) - and it is static (the eyeball is an authoring toggle, not
* parameter-animated), so callers compute it once. It gates only what is drawn: a hidden drawable that is
* still a mask source or a glue partner must keep being deformed, so apply those gates elsewhere.
*
* @return Set<DrawableId> The ids of the drawables to draw.
*/
fun PuppetModel.visibleDrawableIds(): Set<DrawableId> {
val partById = parts.associateBy { it.id }
val drawableById = drawables.associateBy { it.id }
val shown = HashSet<DrawableId>()
fun walk(children: List<OrgChild>, ancestorsVisible: Boolean) {
for (child in children) {
when (child) {
is OrgChild.Drawable -> {
val drawable = drawableById[child.id] ?: continue
if (ancestorsVisible && drawable.isVisible) {
shown.add(child.id)
}
}
is OrgChild.Part -> {
val part = partById[child.id] ?: continue
walk(part.children, ancestorsVisible && part.isVisible)
}
}
}
}
walk(rootChildren, ancestorsVisible = true)
return shown
}
/**
* The owning part of each drawable, derived from the org tree (the drawable's parent in [rootChildren] /
* [Part.children]), or null for a root-level drawable. Since membership lives only in the tree, this is how
* the few sites that need "which part owns this mesh" (the Inspector) read it - computed once per model.
*
* @return Map<DrawableId, PartId?> Drawable id to its owning part id, or null at the root.
*/
fun PuppetModel.partByDrawable(): Map<DrawableId, PartId?> {
val partById = parts.associateBy { it.id }
val owner = HashMap<DrawableId, PartId?>()
fun walk(children: List<OrgChild>, parent: PartId?) {
for (child in children) {
when (child) {
is OrgChild.Drawable -> owner[child.id] = parent
is OrgChild.Part -> partById[child.id]?.let { walk(it.children, child.id) }
}
}
}
walk(rootChildren, parent = null)
return owner
}
/**
* The first drawable in Parts-panel order (top = front) that can actually be edited: it carries a mesh
* and is shown (its own [Drawable.isVisible] is set and every ancestor part is visible). Edit mode seeds
* onto this when nothing is selected or remembered, so a fresh document lands on the topmost editable mesh
* instead of an inert Edit session. A drawable without a mesh, or a hidden one, leaves the gizmo overlay
* with nothing to draw, so both are skipped. The scan is the same forward pre-order walk of the org tree
* as [visibleDrawableIds], short-circuiting at the first match. Only when the org tree carries no drawable
* at all (a degenerate model with an empty [rootChildren]) does it fall back to a flat scan of [drawables];
* a populated tree that yields no shown, meshed drawable returns null (nothing editable to seed onto).
*
* @return DrawableId? The topmost editable drawable, or null when the model has none.
*/
fun PuppetModel.firstEditableDrawableInPanelOrder(): DrawableId? {
val partById = parts.associateBy { it.id }
val drawableById = drawables.associateBy { it.id }
fun walk(children: List<OrgChild>, ancestorsVisible: Boolean): DrawableId? {
for (child in children) {
when (child) {
is OrgChild.Drawable -> {
val drawable = drawableById[child.id] ?: continue
if (ancestorsVisible && drawable.isVisible && drawable.mesh != null) {
return child.id
}
}
is OrgChild.Part -> {
val part = partById[child.id] ?: continue
val found = walk(part.children, ancestorsVisible && part.isVisible)
if (found != null) {
return found
}
}
}
}
return null
}
val fromTree = walk(rootChildren, ancestorsVisible = true)
if (fromTree != null) {
return fromTree
}
// Degenerate model with no org tree: the visibility cascade has nothing to say, so fall back to the
// flat list (a drawable's own eyeball still gates it).
if (rootChildren.isEmpty()) {
return drawables.firstOrNull { candidate -> candidate.mesh != null && candidate.isVisible }?.id
}
return null
}
@@ -0,0 +1,356 @@
package org.umamo.runtime.model
/*
* Pure per-drawable index queries over a PuppetModel. The picking-oriented queries are shared by
* every platform viewport service (the desktop offscreen renderer today, the Android GLES service
* when it lands): the pickable geometry sets picking iterates, and the display lookups the overlap
* picker labels rows with. The atlas queries resolve a drawable's or tile's source-art binding, the
* same resolution the renderer and UV editor build on. All derive from the model alone, so callers
* recompute them on each model swap.
*/
/**
* The per-drawable triangle indices picking iterates: the shown, meshed drawables only, so
* unshown / mesh-less drawables are never hit.
*
* @return Map<DrawableId, IntArray> Drawable id to its triangle indices.
*/
fun PuppetModel.pickableIndicesByDrawable(): Map<DrawableId, IntArray> =
visibleDrawableIds().let { shownIds ->
drawables
.filter { drawable -> drawable.id in shownIds }
.mapNotNull { drawable ->
drawable.mesh?.takeIf { it.indices.isNotEmpty() }?.let { drawable.id to it.indices }
}
.toMap()
}
/**
* The per-drawable full-atlas UVs for the same pickable set as [pickableIndicesByDrawable], so
* picking can interpolate a hit point's UV and sample the atlas alpha.
*
* @return Map<DrawableId, FloatArray> Drawable id to its mesh UVs.
*/
fun PuppetModel.pickableUvsByDrawable(): Map<DrawableId, FloatArray> =
visibleDrawableIds().let { shownIds ->
drawables
.filter { drawable -> drawable.id in shownIds }
.mapNotNull { drawable ->
drawable.mesh?.takeIf { it.indices.isNotEmpty() }?.let { drawable.id to it.uvs }
}
.toMap()
}
/**
* Drawable id to owning part name, for the overlap-picker row labels.
*
* @return Map<DrawableId, String> Drawable id to its owning part's name.
*/
fun PuppetModel.partNameByDrawable(): Map<DrawableId, String> =
parts.associate { part -> part.id to part.name }.let { partNameById ->
val ownerByDrawable = partByDrawable()
drawables
.mapNotNull { drawable ->
ownerByDrawable[drawable.id]?.let { partId -> partNameById[partId]?.let { name -> drawable.id to name } }
}
.toMap()
}
/**
* Drawable id to its own display name, for the overlap-picker row labels. Names are returned as the
* model holds them - a blank one is a display decision the caller makes, not a lookup failure.
*
* @return Map<DrawableId, String> Drawable id to its name.
*/
fun PuppetModel.drawableNameByDrawable(): Map<DrawableId, String> =
drawables.associate { drawable -> drawable.id to drawable.name }
/**
* Drawable id to the source-format id its atlas region is keyed by: itself, or its texture source for
* a session-created duplicate (a copy of a copy resolves to the original).
*
* @return Map<DrawableId, String> Drawable id to its atlas lookup key.
*/
fun PuppetModel.atlasKeyByDrawable(): Map<DrawableId, String> =
drawables.associate { drawable -> drawable.id to (drawable.textureSourceId ?: drawable.id).raw }
/**
* How one drawable's stored texture coordinates map back into its source art's own pixel frame.
*
* The single resolution every source-art consumer starts from - the renderer sampling per-layer
* textures, the UV editor drawing a mapping over the artwork - so the tile lookup, the page lookup, and
* the packed-versus-direct decision are made once here rather than reassembled at each call site.
*
* A placement applies only when the document's stored coordinates address the packed pages and this
* tile was actually packed; otherwise the coordinates already address the art and the mapping is the
* identity. The DISPLAY mode is deliberately not consulted - it decides which texture is sampled, not
* what the coordinates mean, and reinterpreting them on a toggle would draw every mesh at its atlas
* position.
*
* @param Drawable drawable The drawable to resolve.
* @return DrawableLayerBinding? The binding, or null when the document retains no art for it.
*/
fun PuppetModel.atlasBindingFor(drawable: Drawable): DrawableLayerBinding? =
drawable.atlasTileId?.let { tileId -> atlasBindingForTile(tileId) }
/**
* Every drawable sampling each tile, in document order.
*
* The inverse of [Drawable.atlasTileId], and the answer to "how many drawables share this art" -
* duplicated art is common, and a surface offering a tile needs to say what picking it will select.
*
* @return Map<AtlasTileId, List<DrawableId>> Tile to its drawables; a tile nothing samples is absent.
*/
fun PuppetModel.drawableIdsByAtlasTile(): Map<AtlasTileId, List<DrawableId>> {
val byTile = LinkedHashMap<AtlasTileId, MutableList<DrawableId>>()
for (drawable in drawables) {
val tileId = drawable.atlasTileId ?: continue
byTile.getOrPut(tileId) { ArrayList() }.add(drawable.id)
}
return byTile
}
/**
* How a tile's stored texture coordinates map back into its own pixel frame.
*
* The placement is a property of the TILE, so every drawable over one piece of art shares this binding -
* which is what lets the editor describe a tile's frame without first deciding which of its users to
* ask, and keeps that frame stable as the selection narrows.
*
* @param AtlasTileId tileId The tile to resolve.
* @return DrawableLayerBinding? The binding, or null when the tile is unknown or its page is missing.
*/
fun PuppetModel.atlasBindingForTile(tileId: AtlasTileId): DrawableLayerBinding? = atlas.bindingForTile(tileId)
/**
* How a tile's stored texture coordinates map back into its own pixel frame, resolved against THIS
* atlas value's pages.
*
* The atlas-level form of [PuppetModel.atlasBindingForTile], for callers holding an atlas that is not
* the model's own - a repack reads a tile's OLD mapping against the current page inventory and its NEW
* one against the replacement inventory, and the page a placement names supplies the normalization,
* so the two reads must not share pages.
*
* @param AtlasTileId tileId The tile to resolve.
* @return DrawableLayerBinding? The binding, or null when the tile is unknown or its page is missing.
*/
fun PuppetAtlas.bindingForTile(tileId: AtlasTileId): DrawableLayerBinding? {
val tile = tileById[tileId] ?: return null
val placement = tile.placement?.takeIf { storedUvsAddressPages }
val page = placement?.let { packed -> pages.getOrNull(packed.pageIndex) }
if (placement != null && page == null) {
// A placement naming a page the document does not have is broken wiring, not a tile that is
// sampled directly - resolving it to the identity would silently draw the wrong frame.
return null
}
return DrawableLayerBinding(tile.id.raw, placement, page?.width ?: 0, page?.height ?: 0)
}
/**
* The whole stored-uv to art-uv mapping of a tile under this atlas value, as one 2x3 affine - the
* [bindingForTile] resolution folded with the tile's own size through [layerUvAffineOf], so every
* consumer that needs the mapping rather than the binding (a repack's re-derivation, a mesh-reach
* measurement) reads it from one place.
*
* @param AtlasTileId tileId The tile to resolve.
* @return FloatArray? The affine, or null when the binding or the mapping cannot be formed.
*/
fun PuppetAtlas.storedToArtAffineForTile(tileId: AtlasTileId): FloatArray? {
val tile = tileById[tileId] ?: return null
val binding = bindingForTile(tileId) ?: return null
return layerUvAffineOf(binding, tile.width, tile.height)
}
/**
* Part id to every drawable in its subtree, walking nested parts. The inverse direction of
* [partByDrawable], and the resolution behind a part used as a clip mask ([PartComposite.maskedByParts]):
* masking by a part means masking by all of its descendant drawables, recomputed from the tree so the mask
* follows the part as its children change. A part with no drawables under it maps to an empty list.
*
* @return Map<PartId, List<DrawableId>> Part id to its descendant drawables, in tree order.
*/
fun PuppetModel.drawablesByPartSubtree(): Map<PartId, List<DrawableId>> {
val partById = parts.associateBy { part -> part.id }
val collected = HashMap<PartId, List<DrawableId>>(parts.size)
fun collect(partId: PartId, guard: MutableSet<PartId>): List<DrawableId> {
collected[partId]?.let { return it }
// A malformed tree could cycle; the guard makes this terminate rather than blow the stack.
if (!guard.add(partId)) {
return emptyList()
}
val part = partById[partId]
val gathered =
if (part == null) {
emptyList()
} else {
val into = ArrayList<DrawableId>()
for (child in part.children) {
when (child) {
is OrgChild.Drawable -> into.add(child.id)
is OrgChild.Part -> into.addAll(collect(child.id, guard))
}
}
into
}
guard.remove(partId)
collected[partId] = gathered
return gathered
}
for (part in parts) {
collect(part.id, mutableSetOf())
}
return collected
}
/**
* Part id to the part that owns it, for the parts nested under another part. A top-level part (one sitting
* in [PuppetModel.rootChildren]) has no entry. Part membership lives only in the org tree - there is no
* back-pointer on [Part] - so this is the part-side counterpart of [partByDrawable], recomputed from the
* child lists.
*
* @return Map<PartId, PartId> Nested part id to its owning part.
*/
fun PuppetModel.parentPartByPart(): Map<PartId, PartId> {
val parentOf = HashMap<PartId, PartId>(parts.size)
for (part in parts) {
for (child in part.children) {
if (child is OrgChild.Part) {
parentOf[child.id] = part.id
}
}
}
return parentOf
}
/**
* Every part in [id]'s org-tree subtree, including [id] itself. The set a part may NOT be re-homed under -
* doing so would orphan a cycle - so the org-move guard and the Properties picker's candidate filter derive
* from this one definition instead of each walking the tree its own way (they walked it in OPPOSITE
* directions before this existed, which is exactly how two implementations of one invariant drift).
*
* The org tree is the only hierarchy source for parts: a part's children live in [Part.children], and there
* is no parent back-pointer, so this walks DOWN like [deformerSelfAndDescendants] does.
*
* @param PartId id The part whose subtree to collect.
* @return Set<PartId> The part and every part beneath it.
*/
fun PuppetModel.partSelfAndDescendants(id: PartId): Set<PartId> {
val partById = parts.associateBy { part -> part.id }
val collected = LinkedHashSet<PartId>()
fun walk(current: PartId) {
// add() guards a malformed (already cyclic) tree from recursing forever.
if (!collected.add(current)) {
return
}
partById[current]?.children?.forEach { child ->
if (child is OrgChild.Part) {
walk(child.id)
}
}
}
walk(id)
return collected
}
/**
* Every deformer in [id]'s nesting subtree, including [id] itself. The set a deformer may NOT be re-nested
* under - doing so would make the hierarchy a cycle - so both the move guard and the Properties picker's
* candidate filter derive from this one definition rather than each rolling their own walk.
*
* @param DeformerId id The deformer whose subtree to collect.
* @return Set<DeformerId> The deformer and everything nested beneath it.
*/
fun PuppetModel.deformerSelfAndDescendants(id: DeformerId): Set<DeformerId> {
val childrenByParent = deformers.groupBy { deformer -> deformer.parent }
val collected = LinkedHashSet<DeformerId>()
fun walk(current: DeformerId) {
// add() guards a malformed (already cyclic) hierarchy from recursing forever.
if (!collected.add(current)) {
return
}
childrenByParent[current]?.forEach { child -> walk(child.id) }
}
walk(id)
return collected
}
/**
* A composite's clip masks as ONE flat drawable list: its direct [PartComposite.maskedBy] plus every
* drawable beneath each [PartComposite.maskedByParts] entry, de-duplicated (a drawable masked both
* directly and through an ancestor part counts once).
*
* This is the single definition of "what actually clips this layer". The render tree resolves composites
* through it, and an exporter to a format that cannot express part masks MUST use it too, so the two can
* never disagree about the clipping the user sees.
*
* Takes the part-subtree index rather than building it: both callers resolve MANY composites in one pass,
* and [drawablesByPartSubtree] walks the whole part tree, so building it per composite would make a model
* with K part-masked composites over N parts cost O(K*N) on every render-root derive. Pass
* `drawablesByPartSubtree()` computed once for the batch.
*
* @param PartComposite composite The authored composite.
* @param Map subtrees Each part's descendant drawables, from [drawablesByPartSubtree], built once per batch.
* @return List<DrawableId> The effective clip masks, in order.
*/
fun flattenedMasks(composite: PartComposite, subtrees: Map<PartId, List<DrawableId>>): List<DrawableId> {
if (composite.maskedByParts.isEmpty()) {
return composite.maskedBy
}
val expanded = composite.maskedByParts.flatMap { maskPartId -> subtrees[maskPartId].orEmpty() }
return (composite.maskedBy + expanded).distinct()
}
/**
* A copy of this model with every part composite's part-masks expanded into plain drawable masks and
* [PartComposite.maskedByParts] emptied - the conversion an export to a drawable-only mask format (CMO3,
* MOC3) MUST apply.
*
* Call it and the clipping SURVIVES the export exactly as the viewport shows it; what is lost is only the
* authoring grouping ("masked by this part", which follows the part as its children change), because those
* formats have nowhere to record it. Skipping this call would instead drop the part masks outright and
* silently change how the model renders - so exporters flatten, never ignore. UMA keeps the grouping and
* needs no flattening.
*
* @return PuppetModel The model with part-masks flattened, or [this] when none are used.
*/
fun PuppetModel.withPartMasksFlattened(): PuppetModel {
if (parts.none { part -> part.composite.maskedByParts.isNotEmpty() }) {
return this
}
// One index for the whole batch (see flattenedMasks).
val subtrees = drawablesByPartSubtree()
val flattened =
parts.map { part ->
val composite = part.composite
if (composite.maskedByParts.isEmpty()) {
part
} else {
part.copy(
composite = composite.copy(maskedBy = flattenedMasks(composite, subtrees), maskedByParts = emptyList()),
)
}
}
return copy(parts = flattened).withDerivedRenderRoot()
}
/**
* The drawable's 5.3 per-art-mesh multiply color for display in the Properties panel.
*
* A plain static read now that the tint is its own channel: it used to have to reach into the first
* keyform cell, which was only representative because the editor wrote the color across every cell.
*
* @return ColorRgb The drawable's static multiply color.
*/
fun Drawable.displayMultiplyColor(): ColorRgb = multiplyColor
/**
* The drawable's 5.3 per-art-mesh screen color for display in the Properties panel; see
* [displayMultiplyColor].
*
* @return ColorRgb The drawable's screen color, or [ColorRgb.ScreenIdentity] when unkeyed.
*/
fun Drawable.displayScreenColor(): ColorRgb = screenColor
@@ -0,0 +1,39 @@
package org.umamo.runtime.model
/**
* A node in the render-order tree - Cubism's draw-order group hierarchy. The model carries this tree so the
* renderer can reproduce the hierarchical render order: a drawable's draw order sorts it only
* among its group siblings, and a "Group by Draw Order" part moves as a unit positioned by the part's
* draw order. A model with no draw-order groups is one flat [RenderGroup] of all drawables - equivalent to a
* global sort (what `paintOrder` does).
*/
sealed interface RenderNode
/** A drawable leaf; its sort key is its own pose-blended draw order, quantised to an int. */
data class RenderDrawable(val id: DrawableId) : RenderNode
/**
* A draw-order group: the implicit root, or a part whose [PartGroupMode] is Grouped or Isolated. Its
* [children] sort among themselves (in [drawOrder]-then-panel order); the group as a whole takes [drawOrder]
* (the part's draw order) as its sort key in its parent, so a child can't escape the group's slot.
* Basically, override the draw order of children of the part.
*
* @param PartId? partId The owning part, or null for the implicit root.
* @param Int drawOrder The part's default-pose draw order - the static fallback sort key.
* @param List<RenderNode> children The group's members, in parts-panel (authoring) order.
* @param ChannelGrids channelGrids The owning part's per-channel keyform tracks, copied from the
* part onto the derived render tree. DRAW_ORDER blends per pose
* into the sort key; OPACITY and the color channels feed an
* isolated part's composite. A channel with no track falls back
* to [drawOrder] / [composite].
* @param PartComposite? composite The owning part's compositing settings, or null when the part
* is not isolated - carried on the render tree so the renderer
* can composite the group's subtree as one layer.
*/
data class RenderGroup(
val partId: PartId?,
val drawOrder: Int,
val children: List<RenderNode>,
val channelGrids: ChannelGrids = ChannelGrids.Empty,
val composite: PartComposite? = null,
) : RenderNode
@@ -0,0 +1,103 @@
package org.umamo.runtime.model
/**
* A copy of this model with [PuppetModel.renderRoot] recomputed from the current org tree. Every edit that
* changes the org tree (a move, a delete) ends with this, so draw order stays a consistent derivation of
* the tree rather than something the edit has to maintain by hand.
*
* @return PuppetModel This model with a freshly derived render root.
*/
fun PuppetModel.withDerivedRenderRoot(): PuppetModel = copy(renderRoot = deriveRenderRoot())
/**
* Derives the draw-order group tree ([PuppetModel.renderRoot]) from the organizational tree. The org tree
* ([PuppetModel.rootChildren] / [Part.children]) is the single source of truth for hierarchy + panel
* order; draw order is a pure function of it plus the explicit draw-order levers ([Part.groupMode] /
* [Part.drawOrder] / [Part.channelGrids], and each drawable's keyformed draw order). This walks the org
* tree to materialise the structure the renderer consumes, so any org-tree edit yields correct draw order
* by recomputing it - there is no parallel render structure to drift out of sync.
*
* Mirrors Cubism: panel order is top = front, so the render tree (back-to-front) walks each child list
* reversed; a grouped or isolated part becomes a [RenderGroup] boundary (carrying its part draw order
* and grid), a pass-through part is transparent (its children hoist into the enclosing group). A safety
* net appends any drawable the org walk missed, so the render never silently drops a mesh.
*
* @return RenderGroup The derived render-order root.
*/
fun PuppetModel.deriveRenderRoot(): RenderGroup {
val partById = parts.associateBy { it.id }
val drawableIds = drawables.mapTo(HashSet()) { it.id }
// Parts used as clip masks are an Umamo extension the renderer never sees: expand each to its
// descendant drawables here, so a RenderGroup's composite carries one flat drawable-only mask list.
// Shares flattenedMasks with the export path, so what ships can never clip differently from what the
// viewport shows. Most models mask by drawables alone and short-circuit without walking anything.
//
// The index is built at most once per derive, and only when some composite actually uses part masks -
// building it per composite would cost O(parts * masked composites) on every model mutation.
val maskSubtrees by lazy { drawablesByPartSubtree() }
fun resolvedComposite(part: Part): PartComposite? {
val composite = part.activeComposite ?: return null
if (composite.maskedByParts.isEmpty()) {
return composite
}
// maskedByParts is CLEARED, not just expanded: PartComposite documents that the render tree sees the
// expansion and never these ids, so leaving them would let any consumer that later honors them apply
// the same drawables twice.
return composite.copy(maskedBy = flattenedMasks(composite, maskSubtrees), maskedByParts = emptyList())
}
fun collect(children: List<OrgChild>, into: ArrayList<RenderNode>) {
// Panel order is top = front; render order is back-to-front, so walk reversed.
for (child in children.asReversed()) {
when (child) {
is OrgChild.Drawable ->
if (child.id in drawableIds) {
into.add(RenderDrawable(child.id))
}
is OrgChild.Part -> {
val part = partById[child.id] ?: continue
if (part.groupMode is PartGroupMode.PassThrough) {
collect(part.children, into) // transparent: hoist its children up
} else {
val groupChildren = ArrayList<RenderNode>()
collect(part.children, groupChildren)
into.add(
RenderGroup(
part.id,
part.drawOrder,
groupChildren,
part.channelGrids,
resolvedComposite(part),
),
)
}
}
}
}
}
val rootNodes = ArrayList<RenderNode>()
collect(rootChildren, rootNodes)
val root = RenderGroup(null, DEFAULT_DRAW_ORDER, rootNodes)
// Safety net: append any drawable the org walk did not place (e.g. one reachable only under a deformer),
// so the render never silently drops a mesh.
val placed = HashSet<DrawableId>()
fun collectPlaced(node: RenderNode) {
when (node) {
is RenderDrawable -> placed.add(node.id)
is RenderGroup -> node.children.forEach(::collectPlaced)
}
}
collectPlaced(root)
val missing = drawables.map { it.id }.filter { it !in placed }.map { RenderDrawable(it) }
return if (missing.isEmpty()) {
root
} else {
root.copy(children = root.children + missing)
}
}
@@ -0,0 +1,101 @@
package org.umamo.runtime.model
/**
* The restricted features this document ACTUALLY USES under [target] - the decision aid the
* Properties Document tab marks its per-target restricted list with. A feature the target supports
* is never reported, and neither is a restricted feature the document does not use. A MOC3
* export's own "was removed" notices come from the version-downgrade pass, not from here.
*
* [RuntimeFeature.MotionSync] and [RuntimeFeature.ArtPath] are never reported: they are not
* representable in [PuppetModel] (motion-sync is a sidecar family, an art path survives only as CMO3
* round-trip payload), so an export dialog cannot warn about them from the model alone.
*
* Latent state does not count as use: a non-isolated part's stored [Part.composite] is invisible
* to both renderer and runtime, so only isolated parts' composites are scanned.
*
* @param RuntimeTarget target The target to diff against.
* @return Set The restricted features in use; empty when the document fits the target.
*/
fun PuppetModel.unsupportedFeaturesInUse(target: RuntimeTarget): Set<RuntimeFeature> {
val unsupportedFeatures = RuntimeFeature.entries.filterNot { feature -> target.supports(feature) }
if (unsupportedFeatures.isEmpty()) {
return emptySet()
}
// Materialized once for the whole scan rather than inside every feature branch.
val activeComposites = parts.mapNotNull { part -> part.activeComposite }
return unsupportedFeatures.filterTo(linkedSetOf()) { feature -> usesFeature(feature, activeComposites) }
}
/**
* Whether the document uses [feature] at all, independent of any target.
*
* @param RuntimeFeature feature The feature to probe for.
* @param List activeComposites The isolated parts' composites, precomputed by the caller.
* @return Boolean True when the feature is present somewhere in the document.
*/
private fun PuppetModel.usesFeature(feature: RuntimeFeature, activeComposites: List<PartComposite>): Boolean =
when (feature) {
RuntimeFeature.WarpQuadTransform ->
deformers.any { deformer -> deformer is Deformer.Warp && deformer.isQuadTransform }
RuntimeFeature.ReversedMask ->
drawables.any { drawable -> drawable.invertMask } || activeComposites.any { composite -> composite.invertMask }
RuntimeFeature.MeshWarpBlendShapes ->
drawables.any { drawable -> drawable.blendShapes.isNotEmpty() } ||
deformers.any { deformer -> deformer is Deformer.Warp && deformer.blendShapes.isNotEmpty() }
RuntimeFeature.BlendShapeParameters ->
parameters.any { parameter -> parameter.kind == ParameterKind.BLEND_SHAPE }
RuntimeFeature.MultiplyColor -> usesColorChannel(FormChannel.MULTIPLY_COLOR, ColorRgb.MultiplyIdentity)
RuntimeFeature.ScreenColor -> usesColorChannel(FormChannel.SCREEN_COLOR, ColorRgb.ScreenIdentity)
RuntimeFeature.ExtendedBlendShapes ->
deformers.any { deformer -> deformer is Deformer.Rotation && deformer.blendShapes.isNotEmpty() }
RuntimeFeature.ExtendedBlendModes ->
drawables.any { drawable -> !drawable.blendMode.isLegacy || drawable.alphaBlendMode != AlphaBlendMode.Over } ||
activeComposites.any { composite -> !composite.blendMode.isLegacy || composite.alphaBlendMode != AlphaBlendMode.Over }
RuntimeFeature.PartComposite -> parts.any { part -> part.isIsolated }
RuntimeFeature.ParameterRepeat -> parameters.any { parameter -> parameter.repeat }
RuntimeFeature.MotionSync,
RuntimeFeature.ArtPath,
-> false
}
/**
* Whether any drawable, deformer, or isolated part tints through [channel] - a non-identity static,
* or a keyform track holding some non-identity cell. A track of pure identity cells is not use, so
* the track side goes through [ChannelGrids.varies] rather than a mere presence check.
*
* @param FormChannel channel The color channel (multiply or screen).
* @param ColorRgb identity That channel's identity color (leaves pixels unchanged).
* @return Boolean True when the channel is in use somewhere.
*/
private fun PuppetModel.usesColorChannel(channel: FormChannel, identity: ColorRgb): Boolean {
val isMultiply = channel == FormChannel.MULTIPLY_COLOR
val identityValue = ChannelValue.Color(identity)
val drawableUses =
drawables.any { drawable ->
val staticColor = if (isMultiply) drawable.multiplyColor else drawable.screenColor
staticColor != identity || drawable.channelGrids.varies(channel, identityValue)
}
val deformerUses =
deformers.any { deformer ->
val staticColor = if (isMultiply) deformer.multiplyColor else deformer.screenColor
staticColor != identity || deformer.channelGrids.varies(channel, identityValue)
}
// A part's color track keys its composite, so it only counts while the part is isolated.
val compositeUses =
parts.any { part ->
val composite = part.activeComposite ?: return@any false
val staticColor = if (isMultiply) composite.multiplyColor else composite.screenColor
staticColor != identity || part.channelGrids.varies(channel, identityValue)
}
return drawableUses || deformerUses || compositeUses
}
@@ -0,0 +1,165 @@
package org.umamo.runtime.model
/**
* The document's runtime-compatibility target: which runtime the rigger intends this puppet to run
* on, selected in Properties > Document > Runtime.
*
* A target gates EDITING CONTROLS ONLY. It never gates rendering (a document whose content already
* exceeds the target keeps rendering everything), never gates saving to the native format or to
* CMO3 (both always carry every feature), and only informs MOC3 export, where it selects the moc
* version and drives the feature-strip confirmation. This mirrors the official editor's own
* "Model target version selection" behavior, which likewise keeps out-of-target data in the file.
*
* Ayagami is a third-party runtime (not an Umamo project) that is effectively Cubism 5.0
* compatible at present per its maintainer; it has its own entry, rather than aliasing Cubism50,
* so its capabilities can advance independently of the Cubism ladder.
*/
enum class RuntimeTarget(
/**
* The verbatim product name shown in the target dropdown. Cubism entries display this
* directly; NoTarget's phrasing and Ayagami's equivalence parenthetical are chrome, so those
* two resolve through the string catalog instead - with the name "Ayagami" itself kept
* verbatim inside the localized string, and its level fed from [cubismLevelText] so the label
* can never drift from the gating level.
*/
val displayName: String,
/**
* The Cubism feature ceiling as major * 10 + minor (30, 33, 40, 42, 50, 53), or null for no
* ceiling at all. [supports] compares features against this level.
*/
val cubismLevel: Int?,
) {
/** No restriction - every feature Umamo models is authorable. */
NoTarget("No Target", null),
/** The Ayagami third-party runtime - effectively Cubism 5.0 at present (see the class docblock). */
Ayagami("Ayagami", 50),
Cubism30("Cubism 3.0", 30),
Cubism33("Cubism 3.3", 33),
Cubism40("Cubism 4.0", 40),
Cubism42("Cubism 4.2", 42),
Cubism50("Cubism 5.0", 50),
Cubism53("Cubism 5.3", 53),
;
/**
* Whether this target's runtime supports authoring [feature].
*
* The thresholds follow the official Cubism Editor's "Model target version selection" dialog,
* which is the authority for edit gating even where the MOC3 section table disagrees (the new
* warp method is gated at 3.3 though the WARP_MODE section only exists from moc v3, and the
* reversed mask at 4.0 though its constant-flag bit exists from moc v1) - editor parity is the
* product requirement; the section-level nuances belong to export lowering.
*
* @param RuntimeFeature feature The feature to check.
* @return Boolean True when the feature may be authored under this target.
*/
fun supports(feature: RuntimeFeature): Boolean {
val level = cubismLevel ?: return true
return when (feature) {
RuntimeFeature.WarpQuadTransform -> level >= 33
RuntimeFeature.ReversedMask -> level >= 40
RuntimeFeature.MeshWarpBlendShapes,
RuntimeFeature.BlendShapeParameters,
RuntimeFeature.MultiplyColor,
RuntimeFeature.ScreenColor,
-> level >= 42
RuntimeFeature.ExtendedBlendShapes,
RuntimeFeature.MotionSync,
-> level >= 50
RuntimeFeature.ExtendedBlendModes,
RuntimeFeature.PartComposite,
RuntimeFeature.ParameterRepeat,
-> level >= 53
RuntimeFeature.ArtPath -> false
}
}
/**
* The Cubism ceiling as display text ("5.0"), or null for no ceiling. Derived from
* [cubismLevel] so UI text can never drift from the gating level.
*
* @return String? The version text, or null when this target has no Cubism ceiling.
*/
fun cubismLevelText(): String? {
val level = cubismLevel ?: return null
return "${level / 10}.${level % 10}"
}
/**
* The features this target restricts, in [RuntimeFeature] declaration (version-tier) order -
* the "unsupported list" the Document > Runtime section shows. Always derived from [supports],
* never a hardcoded per-target list.
*
* @return List The restricted features; empty when nothing is restricted.
*/
fun restrictedFeatures(): List<RuntimeFeature> = RuntimeFeature.entries.filterNot { feature -> supports(feature) }
}
/**
* A version-gated authoring feature - the unit the runtime repository restricts.
*
* Tier source of truth: the official Cubism Editor's "Model target version selection" dialog (its
* restriction list is transcribed per entry below), cross-cited to docs/format/MOC3.md where a moc
* section backs the feature. Entries are declared in ascending version-tier order so
* [RuntimeTarget.restrictedFeatures] lists them oldest-tier first.
*
* Some entries are informational only: Umamo has no authoring surface (or no model representation)
* for them yet, so they appear in the restricted list and, where representable, in
* [unsupportedFeaturesInUse], but gate no control.
*
* Part-typed composite masks ([PartComposite.maskedByParts], an Umamo extension) are deliberately
* NOT a feature here: the part reference decomposes into its descendant drawable ids at the
* CMO3/MOC3 boundary, so the exported result works on every target and there is nothing to
* restrict or strip.
*/
enum class RuntimeFeature {
/**
* The bilinear (quad) warp interpolation mode, [Deformer.Warp.isQuadTransform]. Official
* dialog: "New warp deformer method - SDK3.3/Cubism3.3 or later". (MOC3 §5.6 WARP_MODE s101,
* absent = triangle split.)
*/
WarpQuadTransform,
/** Inverted clipping, [Drawable.invertMask] / [PartComposite.invertMask]. Official dialog: "Reversed Mask - SDK4.0+". (MOC3 §5.5 constant-flag bit 3.) */
ReversedMask,
/** Blend shapes on art meshes and warp deformers. Official dialog: "Blend Shape - SDK4.2+ (Form of ArtMesh and Warp Deformer)". (MOC3 §5.6 blend-shape sections 115-136.) */
MeshWarpBlendShapes,
/** Blend-shape parameters ([ParameterKind.BLEND_SHAPE]) - same 4.2 tier as the forms they drive. (MOC3 §5.5 Parameter.Types s114.) */
BlendShapeParameters,
/** The multiply tint on drawables, deformers, and composites. Official dialog: "Multiply Color - SDK4.2+". (MOC3 color tables s105-113.) */
MultiplyColor,
/** The screen tint on drawables, deformers, and composites. Official dialog: "Screen Color - SDK4.2+". (MOC3 color tables s105-113.) */
ScreenColor,
/**
* Blend shapes beyond meshes and warps - parts, rotation deformers, glue, and the scalar
* channels. Official dialog: "Blend Shape - SDK5.0+ (Part, ArtMesh, Warp Deformer, Rotation
* Deformer, Glue)". Only the rotation-deformer slice is modeled in [PuppetModel] today.
*/
ExtendedBlendShapes,
/** Motion-sync (the motionsync3.json sidecar family). Official dialog: "Motion-sync - SDK5.0+". Informational only - not modeled. */
MotionSync,
/**
* The Cubism 5.3 blend-mode family: the 15 non-legacy color modes ([BlendMode.isLegacy] false)
* AND the [AlphaBlendMode] list. Official dialog: "Blend mode - SDK5.3+". (MOC3 §5.6 s153/s157
* packed blend.)
*/
ExtendedBlendModes,
/** Offscreen drawing - [PartGroupMode.Isolated] plus [PartComposite]. Official dialog: "Offscreen drawing - SDK5.3+". (MOC3 §5.6 sections 152-163.) */
PartComposite,
/** Parameter repeat flags. A 5.3 moc feature (MOC3 §5.5 s54). Informational only - not modeled. */
ParameterRepeat,
/** Vector-line art paths. Official dialog: "ArtPath - SDK(N/A)/Latest Cubism only". Informational only - CMO3 round-trip payload, not modeled. */
ArtPath,
}
@@ -0,0 +1,125 @@
package org.umamo.runtime.eval
import org.umamo.runtime.model.ChannelGrids
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.ColorRgb
import org.umamo.runtime.model.FormChannel
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.ParameterId
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Pins the per-channel pose sampling: the static fallback (untracked, or out of range - which NEVER
* hides), the override precedence (a pending unkeyed edit wins over both track and static), the
* flag channel's floor-cell snap, and allAxes' flatten across every track.
*/
class ChannelSamplingTest {
private val angleX = ParameterId("ParamAngleX")
private val angleY = ParameterId("ParamAngleY")
/** A one-axis track on the given parameter, each cell holding the matching value. */
private fun track(parameterId: ParameterId, keys: FloatArray, values: List<ChannelValue>): KeyformGrid<ChannelValue> =
KeyformGrid(
listOf(KeyformAxis(parameterId, keys)),
values.mapIndexed { keyIndex, value -> KeyformCell(intArrayOf(keyIndex), value) },
)
/** A pose lambda reading angleX only. */
private fun poseX(value: Float): (ParameterId) -> Float = { parameterId -> if (parameterId == angleX) value else 0f }
private fun scalarTrack(vararg values: Float): KeyformGrid<ChannelValue> =
track(angleX, FloatArray(values.size) { keyIndex -> keyIndex.toFloat() }, values.map { value -> ChannelValue.Scalar(value) })
/** An untracked channel reads the static, and a tracked one blends its own grid at the pose. */
@Test
fun scalarAtFallsBackToStaticAndBlendsWhenTracked() {
val grids = ChannelGrids(mapOf(FormChannel.OPACITY to scalarTrack(0f, 1f)))
assertEquals(0.25f, grids.scalarAt(FormChannel.DRAW_ORDER, 0.25f, poseX(0.5f)), "untracked channel reads the static")
assertEquals(1f, grids.scalarAt(FormChannel.OPACITY, 0.25f, poseX(1f)), "on-key pose reads the cell")
assertEquals(0.5f, grids.scalarAt(FormChannel.OPACITY, 0.25f, poseX(0.5f)), "between keys blends")
}
/** Out of the track's range falls back to the static - keying opacity never hides the art. */
@Test
fun scalarAtOutOfRangeFallsBackToStatic() {
val grids = ChannelGrids(mapOf(FormChannel.OPACITY to scalarTrack(0f, 1f)))
assertEquals(0.25f, grids.scalarAt(FormChannel.OPACITY, 0.25f, poseX(5f)))
}
/** A pending scalar override wins over both the track and the static. */
@Test
fun scalarAtOverrideWinsOverTrackAndStatic() {
val grids = ChannelGrids(mapOf(FormChannel.OPACITY to scalarTrack(0f, 1f)))
val override = ChannelValue.Scalar(0.7f)
assertEquals(0.7f, grids.scalarAt(FormChannel.OPACITY, 0.25f, poseX(1f), override), "override beats the track")
assertEquals(0.7f, grids.scalarAt(FormChannel.DRAW_ORDER, 0.25f, poseX(1f), override), "override beats the static")
}
/** Color sampling mirrors the scalar precedence, blending per component. */
@Test
fun colorAtBlendsPerComponentWithSamePrecedence() {
val colorTrack =
track(
angleX,
floatArrayOf(0f, 1f),
listOf(ChannelValue.Color(ColorRgb(0f, 0f, 1f)), ChannelValue.Color(ColorRgb(1f, 0f, 0f))),
)
val grids = ChannelGrids(mapOf(FormChannel.MULTIPLY_COLOR to colorTrack))
val staticColor = ColorRgb(0.2f, 0.4f, 0.6f)
assertEquals(staticColor, grids.colorAt(FormChannel.SCREEN_COLOR, staticColor, poseX(0.5f)), "untracked channel reads the static")
assertEquals(ColorRgb(0.5f, 0f, 0.5f), grids.colorAt(FormChannel.MULTIPLY_COLOR, staticColor, poseX(0.5f)))
assertEquals(staticColor, grids.colorAt(FormChannel.MULTIPLY_COLOR, staticColor, poseX(5f)), "out of range falls back")
val override = ChannelValue.Color(ColorRgb(0.9f, 0.9f, 0.9f))
assertEquals(override.color, grids.colorAt(FormChannel.MULTIPLY_COLOR, staticColor, poseX(0.5f), override))
}
/** A flag snaps to the FLOOR cell between keys rather than blending a boolean. */
@Test
fun flagAtSnapsToTheFloorCell() {
val flagTrack = track(angleX, floatArrayOf(0f, 1f), listOf(ChannelValue.Flag(false), ChannelValue.Flag(true)))
val grids = ChannelGrids(mapOf(FormChannel.FLIP_X to flagTrack))
assertFalse(grids.flagAt(FormChannel.FLIP_X, true, poseX(0.5f)), "midway reads the lower key's flag")
assertTrue(grids.flagAt(FormChannel.FLIP_X, false, poseX(1f)), "on the upper key reads it exactly")
assertTrue(grids.flagAt(FormChannel.FLIP_Y, true, poseX(0.5f)), "untracked channel reads the static")
assertTrue(grids.flagAt(FormChannel.FLIP_X, true, poseX(5f)), "out of range falls back")
assertTrue(grids.flagAt(FormChannel.FLIP_X, false, poseX(0.5f), ChannelValue.Flag(true)), "override wins")
}
/** scalarOrNull reports absence itself: untracked and out-of-range are null, override still wins. */
@Test
fun scalarOrNullDistinguishesAbsenceFromValue() {
val grids = ChannelGrids(mapOf(FormChannel.OPACITY to scalarTrack(0f, 1f)))
assertNull(grids.scalarOrNull(FormChannel.DRAW_ORDER, poseX(0.5f)), "untracked channel is absent")
assertNull(grids.scalarOrNull(FormChannel.OPACITY, poseX(5f)), "out of range is absent")
assertEquals(0.5f, grids.scalarOrNull(FormChannel.OPACITY, poseX(0.5f)))
assertEquals(0.7f, grids.scalarOrNull(FormChannel.DRAW_ORDER, poseX(0.5f), ChannelValue.Scalar(0.7f)))
}
/**
* allAxes is a FLATTEN in channel order, not a dedupe: two tracks keying the same parameter each
* contribute their own axis, because each track brackets its own keys.
*/
@Test
fun allAxesFlattensEveryTrackAxisInChannelOrder() {
val opacityTrack = scalarTrack(0f, 1f)
val drawOrderTrack = track(angleY, floatArrayOf(-1f, 1f), listOf(ChannelValue.Scalar(400f), ChannelValue.Scalar(600f)))
val glueTrack = track(angleX, floatArrayOf(0f, 2f), listOf(ChannelValue.Scalar(0f), ChannelValue.Scalar(1f)))
val grids =
ChannelGrids(
linkedMapOf(
FormChannel.OPACITY to opacityTrack,
FormChannel.DRAW_ORDER to drawOrderTrack,
FormChannel.GLUE_INTENSITY to glueTrack,
),
)
val axes = grids.allAxes()
assertEquals(listOf(angleX, angleY, angleX), axes.map { axis -> axis.parameterId })
assertEquals(emptyList(), ChannelGrids.Empty.allAxes())
}
}
@@ -0,0 +1,298 @@
package org.umamo.runtime.eval
import org.umamo.runtime.model.BlendMode
import org.umamo.runtime.model.Drawable
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.MeshDeltaForm
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.RotationPivotForm
import org.umamo.runtime.model.WarpLatticeForm
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins the pure grid-sampling layer: bindBracket's range/snap contract, gridCorners' multilinear
* corner selection (including the 16-corner budget), and the pose-sampling helpers the renderer's
* evaluator and the MOC3 import both call (meshGridDefaultDeltas, warpControlPointsAt,
* rotationFormAt).
*
* The grid ALGEBRA (seeding, insertion, compaction) is pinned in runtime.keyform; this file pins the
* read side that every other feature blends through.
*/
class KeyformGridSamplingTest {
private val angleX = ParameterId("ParamAngleX")
private val angleY = ParameterId("ParamAngleY")
/** A pose lambda over explicit per-parameter values, defaulting unmentioned parameters to zero. */
private fun pose(vararg values: Pair<ParameterId, Float>): (ParameterId) -> Float {
val byId = values.toMap()
return { parameterId -> byId[parameterId] ?: 0f }
}
/** An axis-only grid (gridCorners reads no cells), each axis holding keys 0..count-1. */
private fun axisOnlyGrid(vararg axes: Pair<ParameterId, FloatArray>): KeyformGrid<WarpLatticeForm> =
KeyformGrid(axes.map { (parameterId, keys) -> KeyformAxis(parameterId, keys) }, emptyList())
/** A value inside the bracket snaps by fraction; assertEquals on floats pins it exactly. */
@Test
fun bindBracketBetweenKeysReturnsLowerIndexAndFraction() {
val bracket = assertNotNull(bindBracket(floatArrayOf(0f, 1f, 2f), 0.25f))
assertEquals(0, bracket.index)
assertEquals(0.25f, bracket.fraction)
}
/** A value landing exactly on an interior key brackets that key with zero fraction. */
@Test
fun bindBracketExactKeyHitSnapsWithZeroFraction() {
assertEquals(AxisBracket(1, 0f), bindBracket(floatArrayOf(0f, 1f, 2f), 1f))
}
/** Out of range hides the entity: below the first key and at/above last-key + EPS_KEY are null. */
@Test
fun bindBracketOutOfRangeReturnsNull() {
val keys = floatArrayOf(0f, 1f, 2f)
assertNull(bindBracket(keys, -0.5f))
assertNull(bindBracket(keys, 2.5f))
assertNull(bindBracket(keys, 2f + EPS_KEY))
}
/** Authoring hold clamps past the ends onto the nearest key instead of hiding. */
@Test
fun gridCornersHoldingClampsPastTheEnds() {
val grid = axisOnlyGrid(angleX to floatArrayOf(0f, 1f, 2f))
val pastLast = assertNotNull(gridCornersHolding(grid, pose(angleX to 10f)))
assertEquals(listOf(WeightedCell(2, 1f)), pastLast, "past the last key holds the last slice")
val beforeFirst = assertNotNull(gridCornersHolding(grid, pose(angleX to -10f)))
assertEquals(listOf(WeightedCell(0, 1f)), beforeFirst, "before the first key holds the first slice")
}
/** Within EPS_KEY of a key the value snaps onto it; just outside it interpolates. */
@Test
fun bindBracketSnapsOnlyWithinEpsilonOfAKey() {
val keys = floatArrayOf(0f, 1f, 2f)
assertEquals(AxisBracket(1, 0f), bindBracket(keys, 1f + 0.0005f), "inside EPS_KEY snaps")
val outside = assertNotNull(bindBracket(keys, 1f + 0.002f))
assertEquals(1, outside.index)
assertTrue(outside.fraction > 0f, "outside EPS_KEY interpolates")
}
/** The snap window extends past the LAST key too, so a slider resting a hair over stays keyed. */
@Test
fun bindBracketSnapsJustAboveTheLastKey() {
assertEquals(AxisBracket(2, 0f), bindBracket(floatArrayOf(0f, 1f, 2f), 2.0005f))
}
/** A single-key axis brackets only within its snap window and hides everywhere else. */
@Test
fun bindBracketSingleKeyAxisSnapsOrHides() {
assertEquals(AxisBracket(0, 0f), bindBracket(floatArrayOf(0.5f), 0.5f))
assertNull(bindBracket(floatArrayOf(0.5f), 0.6f))
}
/** An axis-less (empty-keys) bracket is the zero bracket - the entity never hides on it. */
@Test
fun bindBracketEmptyKeysReturnsZeroBracket() {
assertEquals(AxisBracket(0, 0f), bindBracket(floatArrayOf(), 12f))
}
/** One fractional axis doubles the corner set; the two weights are the complementary fractions. */
@Test
fun gridCornersOneFractionalAxisYieldsTwoWeightedCells() {
val grid = axisOnlyGrid(angleX to floatArrayOf(0f, 1f))
val corners = assertNotNull(gridCorners(grid, pose(angleX to 0.25f)))
assertEquals(mapOf(0 to 0.75f, 1 to 0.25f), corners.associate { corner -> corner.linearIndex to corner.weight })
}
/** Two fractional axes fold to four bilinear corners whose weights multiply and sum to one. */
@Test
fun gridCornersTwoFractionalAxesYieldFourBilinearCorners() {
val grid = axisOnlyGrid(angleX to floatArrayOf(0f, 1f), angleY to floatArrayOf(0f, 1f))
val corners = assertNotNull(gridCorners(grid, pose(angleX to 0.5f, angleY to 0.25f)))
val weightByIndex = corners.associate { corner -> corner.linearIndex to corner.weight }
assertEquals(mapOf(0 to 0.375f, 1 to 0.375f, 2 to 0.125f, 3 to 0.125f), weightByIndex)
assertEquals(1f, corners.map { corner -> corner.weight }.sum())
}
/** A pose exactly on every key resolves to the single matching cell at full weight. */
@Test
fun gridCornersOnKeyPoseYieldsOneFullWeightCell() {
val grid = axisOnlyGrid(angleX to floatArrayOf(0f, 1f), angleY to floatArrayOf(0f, 1f))
val corners = assertNotNull(gridCorners(grid, pose(angleX to 1f, angleY to 0f)))
assertEquals(listOf(WeightedCell(1, 1f)), corners)
}
/** Any single controlling axis out of range hides the whole entity. */
@Test
fun gridCornersOutOfRangeAxisReturnsNull() {
val grid = axisOnlyGrid(angleX to floatArrayOf(0f, 1f), angleY to floatArrayOf(0f, 1f))
assertNull(gridCorners(grid, pose(angleX to 0.5f, angleY to 2f)))
}
/**
* Past the 16-corner budget an axis snaps to its lower key instead of splitting: five fractional
* two-key axes yield 16 corners (four split), with the fifth axis pinned at key 0 - every linear
* index stays below the fifth axis's stride.
*/
@Test
fun gridCornersFifthFractionalAxisSnapsWithinCornerBudget() {
val parameterIds = (1..5).map { axisNumber -> ParameterId("ParamAxis$axisNumber") }
val grid =
KeyformGrid<WarpLatticeForm>(
parameterIds.map { parameterId -> KeyformAxis(parameterId, floatArrayOf(0f, 1f)) },
emptyList(),
)
val corners = assertNotNull(gridCorners(grid) { 0.5f })
assertEquals(16, corners.size)
val fifthAxisStride = 16
assertTrue(corners.all { corner -> corner.linearIndex < fifthAxisStride }, "the snapped axis contributes only its lower key")
assertEquals(1f, corners.map { corner -> corner.weight }.sum())
}
/** The exposed cell index is the grid's own cached one, and it round-trips every coordinate. */
@Test
fun cellsByLinearIndexDelegatesToTheGridAndRoundTripsCoordinates() {
val cells =
listOf(
KeyformCell(intArrayOf(0, 0), WarpLatticeForm(floatArrayOf(0f))),
KeyformCell(intArrayOf(1, 0), WarpLatticeForm(floatArrayOf(1f))),
KeyformCell(intArrayOf(2, 0), WarpLatticeForm(floatArrayOf(2f))),
KeyformCell(intArrayOf(0, 1), WarpLatticeForm(floatArrayOf(3f))),
KeyformCell(intArrayOf(1, 1), WarpLatticeForm(floatArrayOf(4f))),
KeyformCell(intArrayOf(2, 1), WarpLatticeForm(floatArrayOf(5f))),
)
val grid =
KeyformGrid(
listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f, 2f)), KeyformAxis(angleY, floatArrayOf(0f, 1f))),
cells,
)
val byIndex = cellsByLinearIndex(grid)
assertSame(grid.cellsByLinearIndex, byIndex)
for (cell in cells) {
assertSame(cell, byIndex[grid.linearIndexOf(cell.coordinate)])
}
}
/** A drawable with the given one-axis geometry grid on angleX; the mesh itself is never read. */
private fun gridded(grid: KeyformGrid<MeshDeltaForm>?): Drawable =
Drawable(
id = DrawableId("d1"),
name = "d1",
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = null,
geometryGrid = grid,
)
/** An ungridded drawable has no delta reference. */
@Test
fun meshGridDefaultDeltasUngriddedDrawableReturnsNull() {
assertNull(meshGridDefaultDeltas(gridded(null)) { 0f })
}
/** A default pose outside the grid's range has no reference either (the reference is then zero). */
@Test
fun meshGridDefaultDeltasOutOfRangeDefaultReturnsNull() {
val grid =
KeyformGrid(
listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f))),
listOf(
KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(0f, 0f))),
KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(2f, 4f))),
),
)
assertNull(meshGridDefaultDeltas(gridded(grid)) { 5f })
}
/** The reference is the grid form blended at the default pose, sized like a cell's delta array. */
@Test
fun meshGridDefaultDeltasBlendsAtTheDefaultPose() {
val grid =
KeyformGrid(
listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f))),
listOf(
KeyformCell(intArrayOf(0), MeshDeltaForm(floatArrayOf(0f, 0f))),
KeyformCell(intArrayOf(1), MeshDeltaForm(floatArrayOf(2f, 4f))),
),
)
val deltas = assertNotNull(meshGridDefaultDeltas(gridded(grid)) { 0.5f })
assertEquals(listOf(1f, 2f), deltas.toList())
}
/** A one-axis warp grid with the given control points per key. */
private fun warpGrid(vararg controlPointsPerKey: FloatArray): KeyformGrid<WarpLatticeForm> =
KeyformGrid(
listOf(KeyformAxis(angleX, FloatArray(controlPointsPerKey.size) { keyIndex -> keyIndex.toFloat() })),
controlPointsPerKey.mapIndexed { keyIndex, points -> KeyformCell(intArrayOf(keyIndex), WarpLatticeForm(points)) },
)
/** An unkeyed warp has no lattice at all. */
@Test
fun warpControlPointsAtNullGridReturnsNull() {
assertNull(warpControlPointsAt(null, pose()))
}
/** On a key the lattice is that cell's points exactly; between keys it blends componentwise. */
@Test
fun warpControlPointsAtBlendsBetweenKeys() {
val grid = warpGrid(floatArrayOf(0f, 10f), floatArrayOf(4f, 30f))
assertEquals(listOf(0f, 10f), assertNotNull(warpControlPointsAt(grid, pose(angleX to 0f))).toList())
assertEquals(listOf(2f, 20f), assertNotNull(warpControlPointsAt(grid, pose(angleX to 0.5f))).toList())
}
/** Out of range or no resolvable cell both yield null rather than a partial lattice. */
@Test
fun warpControlPointsAtOutOfRangeOrCellLessReturnsNull() {
val grid = warpGrid(floatArrayOf(0f), floatArrayOf(4f))
assertNull(warpControlPointsAt(grid, pose(angleX to 9f)))
val cellLess = KeyformGrid<WarpLatticeForm>(listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f))), emptyList())
assertNull(warpControlPointsAt(cellLess, pose(angleX to 0.5f)))
}
/** A one-axis rotation grid with the given pivot forms per key. */
private fun rotationGrid(vararg formsPerKey: RotationPivotForm): KeyformGrid<RotationPivotForm> =
KeyformGrid(
listOf(KeyformAxis(angleX, FloatArray(formsPerKey.size) { keyIndex -> keyIndex.toFloat() })),
formsPerKey.mapIndexed { keyIndex, form -> KeyformCell(intArrayOf(keyIndex), form) },
)
/** An unkeyed rotation has no transform. */
@Test
fun rotationFormAtNullGridReturnsNull() {
assertNull(rotationFormAt(null, pose()))
}
/** On a key the transform is that cell's exactly; between keys every component lerps. */
@Test
fun rotationFormAtBlendsBetweenKeys() {
val grid =
rotationGrid(
RotationPivotForm(originX = 0f, originY = 10f, angle = 0f, scale = 1f),
RotationPivotForm(originX = 4f, originY = 30f, angle = 90f, scale = 3f),
)
val atKey = assertNotNull(rotationFormAt(grid, pose(angleX to 1f)))
assertEquals(4f, atKey.originX)
assertEquals(90f, atKey.angle)
val midway = assertNotNull(rotationFormAt(grid, pose(angleX to 0.5f)))
assertEquals(2f, midway.originX)
assertEquals(20f, midway.originY)
assertEquals(45f, midway.angle)
assertEquals(2f, midway.scale)
}
/** Out of range or no resolvable cell both yield null rather than an identity transform. */
@Test
fun rotationFormAtOutOfRangeOrCellLessReturnsNull() {
val grid = rotationGrid(RotationPivotForm(0f, 0f, 0f, 1f))
assertNull(rotationFormAt(grid, pose(angleX to 9f)))
val cellLess = KeyformGrid<RotationPivotForm>(listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f))), emptyList())
assertNull(rotationFormAt(cellLess, pose(angleX to 0.5f)))
}
}
@@ -0,0 +1,358 @@
package org.umamo.runtime.keyform
import org.umamo.runtime.model.ChannelGrids
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.ChannelValueKind
import org.umamo.runtime.model.ColorRgb
import org.umamo.runtime.model.DrawableId
import org.umamo.runtime.model.FormChannel
import org.umamo.runtime.model.Glue
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import org.umamo.runtime.model.PuppetModel
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins exact-only compaction and, most importantly, that compaction and refinement are MUTUAL INVERSES
* bit-for-bit.
*
* That property is the whole basis for compacting an imported rig: a key is dropped only when the stored
* form is bit-equal to the blend of its neighbours, and refinement restores it by evaluating the very same
* FormInterpolator expression on the very same inputs, so IEEE-754 determinism does the rest. It is a
* theorem about shared code, not about tolerance - which is why this file asserts equality exactly, while
* KeyformGridAlgebraTest's arbitrary key insertion may only assert to a bound.
*/
class KeyformCompactionTest {
private val angleX = ParameterId("ParamAngleX")
private val angleY = ParameterId("ParamAngleY")
private fun scalar(value: Float): ChannelValue = ChannelValue.Scalar(value)
/** A one-axis scalar track on angleX. */
private fun track(keys: FloatArray, values: FloatArray): KeyformGrid<ChannelValue> =
KeyformGrid(
listOf(KeyformAxis(angleX, keys)),
values.mapIndexed { keyIndex, value -> KeyformCell(intArrayOf(keyIndex), scalar(value)) },
)
/** Every cell's value in linear-index order, so two grids of the same shape compare directly. */
private fun valuesInIndexOrder(grid: KeyformGrid<ChannelValue>): List<ChannelValue> =
(0 until grid.cellCount).map { linearIndex ->
grid.cells.first { cell -> grid.linearIndexOf(cell.coordinate) == linearIndex }.form
}
/** A track holding one value everywhere collapses to that constant, freeing its owner's static field. */
@Test
fun aConstantTrackCollapsesToItsValue() {
val result = track(floatArrayOf(-1f, 0f, 1f), floatArrayOf(7f, 7f, 7f)).compacted(ChannelValueInterpolator)
assertEquals(scalar(7f), assertIs<CompactionResult.Constant<ChannelValue>>(result).form)
}
/** A perfectly linear track keeps only its endpoints - the interior keys carry no information. */
@Test
fun aLinearTrackKeepsOnlyItsEndpoints() {
val result = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 50f, 100f)).compacted(ChannelValueInterpolator)
val reduced = assertIs<CompactionResult.Reduced<ChannelValue>>(result).grid
assertEquals(listOf(0f, 10f), reduced.axes.single().keys.toList())
}
/** A key that genuinely bends the curve survives, however slightly it differs from the blend. */
@Test
fun aBendingKeySurvives() {
val result = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 50.0001f, 100f)).compacted(ChannelValueInterpolator)
val reduced = assertIs<CompactionResult.Reduced<ChannelValue>>(result).grid
assertEquals(listOf(0f, 5f, 10f), reduced.axes.single().keys.toList(), "an exact-only test never rounds a rigger's value away")
}
/** An axis the track does not respond to is dropped entirely, even when another axis still varies. */
@Test
fun aConstantAxisIsDropped() {
val axes = listOf(KeyformAxis(angleX, floatArrayOf(0f, 10f)), KeyformAxis(angleY, floatArrayOf(0f, 1f)))
// Varies along angleX, identical along angleY.
val cells =
listOf(
KeyformCell(intArrayOf(0, 0), scalar(0f)),
KeyformCell(intArrayOf(1, 0), scalar(100f)),
KeyformCell(intArrayOf(0, 1), scalar(0f)),
KeyformCell(intArrayOf(1, 1), scalar(100f)),
)
val result = KeyformGrid(axes, cells).compacted(ChannelValueInterpolator)
val reduced = assertIs<CompactionResult.Reduced<ChannelValue>>(result).grid
assertEquals(listOf(angleX), reduced.axes.map { axis -> axis.parameterId })
assertEquals(listOf(scalar(0f), scalar(100f)), valuesInIndexOrder(reduced))
}
/** Colors compact per component, so an identity tint across a whole grid becomes one constant. */
@Test
fun aConstantColorTrackCollapses() {
val grid =
KeyformGrid(
listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f, 2f))),
List(3) { keyIndex -> KeyformCell<ChannelValue>(intArrayOf(keyIndex), ChannelValue.Color(ColorRgb.MultiplyIdentity)) },
)
val result = grid.compacted(ChannelValueInterpolator, ChannelValueKind.COLOR)
assertEquals(ChannelValue.Color(ColorRgb.MultiplyIdentity), assertIs<CompactionResult.Constant<ChannelValue>>(result).form)
}
/**
* A flag track drops constant AXES but never an interior key: a flag snaps to the floor cell instead
* of blending, so "equal to the blend of its neighbours" is not a sound drop test for one.
*/
@Test
fun aFlagTrackKeepsItsInteriorKeys() {
val grid =
KeyformGrid(
listOf(KeyformAxis(angleX, floatArrayOf(0f, 5f, 10f))),
listOf<KeyformCell<ChannelValue>>(
KeyformCell(intArrayOf(0), ChannelValue.Flag(false)),
KeyformCell(intArrayOf(1), ChannelValue.Flag(false)),
KeyformCell(intArrayOf(2), ChannelValue.Flag(true)),
),
)
val reduced = assertIs<CompactionResult.Reduced<ChannelValue>>(grid.compacted(ChannelValueInterpolator, ChannelValueKind.FLAG)).grid
assertEquals(listOf(0f, 5f, 10f), reduced.axes.single().keys.toList())
}
/**
* Two ADJACENT interpolable keys are the trap the greedy pass falls into: the first key's drop is
* justified against a neighbour that itself drops next, and refinement then rebuilds the first from
* the surviving endpoints - a different IEEE-754 rounding sequence. The values below are a concrete
* float32 case where that direct rebuild differs by an ULP (found by exhaustive search), so this test
* fails against an unverified greedy drop pass.
*/
@Test
fun adjacentInterpolableKeysStayMutualInverses() {
val v0 = scalar(0.102f)
val v3 = scalar(0.1014f)
// Constructed to make the greedy pass drop key 1 (against 0 and 3) and then key 3 (against 0 and 4).
val v2 = ChannelValueInterpolator.interpolate(v0, v3, 0.75f)
val v1 = ChannelValueInterpolator.interpolate(v0, v2, 1f / 3f)
val original =
KeyformGrid(
listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f, 3f, 4f))),
listOf(v0, v1, v2, v3).mapIndexed { keyIndex, value -> KeyformCell(intArrayOf(keyIndex), value) },
)
val reduced = assertIs<CompactionResult.Reduced<ChannelValue>>(original.compacted(ChannelValueInterpolator)).grid
val restored =
reduced.refinedToUnion(
mapOf(angleX to original.axes.single().keys),
emptyMap(),
ChannelValueInterpolator,
)
assertEquals(listOf(0f, 1f, 3f, 4f), restored.axes.single().keys.toList())
assertEquals(valuesInIndexOrder(original), valuesInIndexOrder(restored), "every dropped key restores bit-for-bit")
}
/**
* An axis whose keys do not bracket the parameter's range gates the track's out-of-span fallback to
* the owner's static, so it is never dropped and its track is never lifted to a constant.
*/
@Test
fun aNonSpanningConstantAxisIsNeverDroppedOrLifted() {
val spans: (KeyformAxis) -> Boolean = { axis -> axis.keys.first() <= -1f && axis.keys.last() >= 1f }
// Constant along a NON-spanning sole axis: kept as-is, because poses below 0.5 read the static.
val gated = track(floatArrayOf(0.5f, 1f), floatArrayOf(0.4f, 0.4f))
val gatedResult = gated.compacted(ChannelValueInterpolator, axisSpansRange = spans)
assertSame(gated, assertIs<CompactionResult.Reduced<ChannelValue>>(gatedResult).grid)
// The same constant on a spanning axis lifts as before.
val spanning = track(floatArrayOf(-1f, 1f), floatArrayOf(0.4f, 0.4f))
val liftedResult = spanning.compacted(ChannelValueInterpolator, axisSpansRange = spans)
assertEquals(scalar(0.4f), assertIs<CompactionResult.Constant<ChannelValue>>(liftedResult).form)
// Mixed: the spanning constant axis drops, the non-spanning one survives as the gate.
val axes = listOf(KeyformAxis(angleX, floatArrayOf(-1f, 1f)), KeyformAxis(angleY, floatArrayOf(0.5f, 1f)))
val cells =
listOf(
KeyformCell(intArrayOf(0, 0), scalar(0.4f)),
KeyformCell(intArrayOf(1, 0), scalar(0.4f)),
KeyformCell(intArrayOf(0, 1), scalar(0.4f)),
KeyformCell(intArrayOf(1, 1), scalar(0.4f)),
)
val mixedResult = KeyformGrid(axes, cells).compacted(ChannelValueInterpolator, axisSpansRange = spans)
val mixedReduced = assertIs<CompactionResult.Reduced<ChannelValue>>(mixedResult).grid
assertEquals(listOf(angleY), mixedReduced.axes.map { axis -> axis.parameterId }, "only the gate axis survives")
}
/**
* The model-level pass derives the spanning gate from the parameter table: a glue keyed constant 0.4
* on keys [0.5, 1.0] of a -1..1 parameter welds at the 1.0 static fallback below 0.5, so lifting the
* constant would change those poses. The track must survive and the static must keep its value; the
* same constant on a spanning axis lifts as before.
*/
@Test
fun modelCompactionKeepsTheOutOfSpanStaticFallback() {
val gatedTrack =
KeyformGrid(
listOf(KeyformAxis(angleX, floatArrayOf(0.5f, 1f))),
listOf<KeyformCell<ChannelValue>>(
KeyformCell(intArrayOf(0), scalar(0.4f)),
KeyformCell(intArrayOf(1), scalar(0.4f)),
),
)
val spanningTrack =
KeyformGrid(
listOf(KeyformAxis(angleX, floatArrayOf(-1f, 1f))),
listOf<KeyformCell<ChannelValue>>(
KeyformCell(intArrayOf(0), scalar(0.4f)),
KeyformCell(intArrayOf(1), scalar(0.4f)),
),
)
val model =
PuppetModel(
parameters = listOf(Parameter(angleX, angleX.raw, min = -1f, max = 1f, default = 0f)),
parts = emptyList(),
deformers = emptyList(),
drawables = emptyList(),
rootChildren = emptyList(),
rootPartId = null,
glues =
listOf(
Glue(DrawableId("a"), DrawableId("b"), emptyList(), ChannelGrids(mapOf(FormChannel.GLUE_INTENSITY to gatedTrack))),
Glue(DrawableId("c"), DrawableId("d"), emptyList(), ChannelGrids(mapOf(FormChannel.GLUE_INTENSITY to spanningTrack))),
),
)
val compacted = model.withChannelsCompacted()
val gated = compacted.glues.first { glue -> glue.meshA == DrawableId("a") }
assertSame(gatedTrack, gated.channelGrids[FormChannel.GLUE_INTENSITY], "the non-spanning track survives untouched")
assertEquals(1f, gated.intensity, "the full-weld fallback below the span keeps its static")
val lifted = compacted.glues.first { glue -> glue.meshA == DrawableId("c") }
assertEquals(null, lifted.channelGrids[FormChannel.GLUE_INTENSITY], "the spanning constant still lifts")
assertEquals(0.4f, lifted.intensity)
}
/**
* A compacted glue keeps its authored id.
*
* Compaction runs on the MOC3 import path itself, so a glue whose intensity track lifts passes
* through here before any export sees it. The id exists purely so a round trip writes back the name
* the model was authored with, which a rewrite that dropped it would silently defeat - the export
* would synthesize `Glue_ArtMeshNN_ArtMeshMM_` and nothing would report a loss.
*/
@Test
fun aCompactedGlueKeepsItsAuthoredId() {
val spanningTrack =
KeyformGrid(
listOf(KeyformAxis(angleX, floatArrayOf(-1f, 1f))),
listOf<KeyformCell<ChannelValue>>(
KeyformCell(intArrayOf(0), scalar(0.4f)),
KeyformCell(intArrayOf(1), scalar(0.4f)),
),
)
val model =
PuppetModel(
parameters = listOf(Parameter(angleX, angleX.raw, min = -1f, max = 1f, default = 0f)),
parts = emptyList(),
deformers = emptyList(),
drawables = emptyList(),
rootChildren = emptyList(),
rootPartId = null,
glues =
listOf(
Glue(
DrawableId("a"),
DrawableId("b"),
emptyList(),
ChannelGrids(mapOf(FormChannel.GLUE_INTENSITY to spanningTrack)),
id = "Glue__ArtMesh48__ArtMesh49",
),
),
)
val compacted = model.withChannelsCompacted()
// The glue IS rewritten here - its track lifts to a static - so this is the rewrite that must
// carry the id, not a pass-through that trivially would.
assertEquals(0.4f, compacted.glues.single().intensity, "the spanning constant lifted")
assertEquals("Glue__ArtMesh48__ArtMesh49", compacted.glues.single().id)
}
/** A sparse grid is passed straight through - its missing cells cannot be tested, so nothing is dropped. */
@Test
fun aSparseGridIsUntouched() {
val dense = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 50f, 100f))
val sparse = KeyformGrid(dense.axes, dense.cells.drop(1))
assertSame(sparse, assertIs<CompactionResult.Reduced<ChannelValue>>(sparse.compacted(ChannelValueInterpolator)).grid)
}
/**
* THE invariant: compact, then refine back onto the original key set, and every stored value is
* bit-identical to what it was. This is the property an importer's compaction pass and an exporter's
* union bake both rest on.
*/
@Test
fun compactionAndRefinementAreMutualInverses() {
val originals =
listOf(
// Exactly linear - loses its interior key to compaction, so refinement has to rebuild it.
track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 50f, 100f)),
// Irregular key spacing, so the rebuilt fraction is not a tidy one half.
track(floatArrayOf(-30f, -7f, 30f), floatArrayOf(1f, (1f + 59f * (23f / 60f)), 60f)),
// Constant, which compacts all the way out and must replicate back.
track(floatArrayOf(-1f, 0f, 1f), floatArrayOf(0.25f, 0.25f, 0.25f)),
// Genuinely bending, so nothing is dropped and refinement is a no-op.
track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 90f, 100f)),
)
for (original in originals) {
val originalKeys = original.axes.single().keys
val compacted = original.compacted(ChannelValueInterpolator)
val restored =
when (compacted) {
is CompactionResult.Constant ->
KeyformGrid(
listOf(KeyformAxis(angleX, floatArrayOf(originalKeys.first(), originalKeys.last()))),
listOf(KeyformCell(intArrayOf(0), compacted.form), KeyformCell(intArrayOf(1), compacted.form)),
).refinedToUnion(mapOf(angleX to originalKeys), emptyMap(), ChannelValueInterpolator)
is CompactionResult.Reduced ->
compacted.grid.refinedToUnion(mapOf(angleX to originalKeys), emptyMap(), ChannelValueInterpolator)
}
assertEquals(originalKeys.toList(), restored.axes.single().keys.toList(), "every original key is restored")
assertEquals(valuesInIndexOrder(original), valuesInIndexOrder(restored), "restored bit-for-bit")
}
}
/**
* Refinement is span-clamped: a union key outside a track's own key span is NOT inserted. Widening the
* span would resurrect a track its author keyed to fall out of range - the toggle-part pattern - which
* is a change to the rig, not a change in precision.
*/
@Test
fun refinementNeverWidensAnExistingSpan() {
val narrow = track(floatArrayOf(-1f, 1f), floatArrayOf(0f, 100f))
val refined = narrow.refinedToUnion(mapOf(angleX to floatArrayOf(-30f, 0f, 30f)), emptyMap(), ChannelValueInterpolator)
assertEquals(listOf(-1f, 0f, 1f), refined.axes.single().keys.toList(), "only the interior union key is taken")
}
/**
* A parameter the track does not key at all gets an appended axis spanning the parameter's own range -
* safe precisely because the track is constant along it, so the widening carries no motion.
*/
@Test
fun refinementAppendsAWholeAxisForAnUnkeyedParameter() {
val single = track(floatArrayOf(0f, 10f), floatArrayOf(0f, 100f))
val refined =
single.refinedToUnion(
mapOf(angleY to floatArrayOf(0f)),
mapOf(angleY to -1f..1f),
ChannelValueInterpolator,
)
assertEquals(listOf(angleX, angleY), refined.axes.map { axis -> axis.parameterId }, "the new axis is appended")
assertEquals(listOf(-1f, 0f, 1f), refined.axes[1].keys.toList())
assertTrue(refined.isDense)
assertEquals(6, refined.cells.size)
}
}
@@ -0,0 +1,333 @@
package org.umamo.runtime.keyform
import org.umamo.runtime.eval.EPS_SPAN
import org.umamo.runtime.eval.gridCorners
import org.umamo.runtime.model.ChannelValue
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.Parameter
import org.umamo.runtime.model.ParameterId
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins the keyform authoring algebra: seeding an axis spans the parameter range and leaves the entity
* looking unchanged, key insertion fills a whole slice by interpolation, removal collapses rather than
* leaving a one-key axis that would hide the entity, and capture always lands on an exact cell.
*
* The refusals matter as much as the successes - a key too close to an existing one, or a span the
* evaluator resolves as a step, produces a grid that cannot be evaluated as authored.
*/
class KeyformGridAlgebraTest {
private val angleX = ParameterId("ParamAngleX")
private val angleY = ParameterId("ParamAngleY")
private fun parameter(id: ParameterId, min: Float = -1f, default: Float = 0f, max: Float = 1f): Parameter =
Parameter(id, id.raw, min = min, max = max, default = default)
private fun scalar(value: Float): ChannelValue = ChannelValue.Scalar(value)
private fun scalarOf(cell: KeyformCell<ChannelValue>): Float = (cell.form as ChannelValue.Scalar).value
/** A one-axis track on angleX with the given keys, each cell holding the matching value. */
private fun track(keys: FloatArray, values: FloatArray): KeyformGrid<ChannelValue> =
KeyformGrid(
listOf(KeyformAxis(angleX, keys)),
values.mapIndexed { keyIndex, value -> KeyformCell(intArrayOf(keyIndex), scalar(value)) },
)
/** The track's value at [poseValue], read through the real evaluator rather than a reimplementation. */
private fun sample(grid: KeyformGrid<ChannelValue>, poseValue: Float, otherValue: Float = 0f): Float? {
val corners = gridCorners(grid) { parameterId -> if (parameterId == angleX) poseValue else otherValue } ?: return null
val formByIndex = grid.cells.associate { cell -> grid.linearIndexOf(cell.coordinate) to cell.form }
var total = 0f
for (corner in corners) {
total += corner.weight * ((formByIndex[corner.linearIndex] as? ChannelValue.Scalar)?.value ?: 0f)
}
return total
}
/** Seeding a fresh axis spans min..max so the entity never falls out of range inside the slider. */
@Test
fun seedingSpansTheParameterRange() {
val seeded = null.withAxisSeeded(parameter(angleX, min = -30f, default = 0f, max = 30f), scalar(0.5f))
assertNotNull(seeded)
assertEquals(listOf(-30f, 0f, 30f), seeded.axes.single().keys.toList())
assertEquals(listOf(0.5f, 0.5f, 0.5f), seeded.cells.map { cell -> scalarOf(cell) }, "every seeded key holds the current value")
}
/** A default that coincides with an endpoint collapses to two keys rather than a degenerate span. */
@Test
fun seedingDeduplicatesACoincidentDefault() {
val seeded = null.withAxisSeeded(parameter(angleX, min = 0f, default = 0f, max = 1f), scalar(1f))
assertEquals(listOf(0f, 1f), assertNotNull(seeded).axes.single().keys.toList())
}
/** A parameter that cannot yield two distinct keys is refused rather than seeded into a hiding axis. */
@Test
fun seedingRefusesADegenerateRange() {
assertNull(null.withAxisSeeded(parameter(angleX, min = 0f, default = 0f, max = 0f), scalar(1f)))
}
/** Binding a second parameter appends its axis and replicates the grid, so nothing moves. */
@Test
fun seedingASecondAxisAppendsAndReplicates() {
val existing = track(floatArrayOf(-1f, 1f), floatArrayOf(10f, 20f))
val seeded = assertNotNull(existing.withAxisSeeded(parameter(angleY), scalar(99f)))
assertEquals(listOf(angleX, angleY), seeded.axes.map { axis -> axis.parameterId }, "the new axis is appended, not spliced")
assertEquals(6, seeded.cells.size)
assertTrue(seeded.isDense)
// The pre-existing motion is unchanged at every angleY key, which is what makes binding non-destructive.
for (poseY in listOf(-1f, 0f, 1f)) {
assertEquals(15f, sample(seeded, poseValue = 0f, otherValue = poseY))
}
}
/**
* Inserting a key leaves the evaluated curve alone - it adds a sample, not a shape change.
*
* Asserted to a tolerance, NOT bit-equality, and deliberately so: re-associating one linear blend into
* two consecutive ones is exact in the reals but lands a few ULP apart in float (pose 6 evaluates
* 60.000004 before the insert and 60.0 after). The bit-exact claim in this layer belongs only to
* compaction and refinement being mutual inverses, which evaluate the SAME expression on the SAME
* inputs - see KeyformCompactionTest. Asserting bit-equality here would be claiming something the
* arithmetic does not support.
*/
@Test
fun insertingAKeyPreservesTheCurve() {
val before = track(floatArrayOf(0f, 10f), floatArrayOf(0f, 100f))
val after = before.withKeyInserted(angleX, 2.5f, ChannelValueInterpolator)
assertEquals(listOf(0f, 2.5f, 10f), after.axes.single().keys.toList())
assertEquals(25f, scalarOf(after.cells.first { cell -> cell.coordinate.single() == 1 }))
for (poseValue in listOf(0f, 1f, 2.5f, 6f, 10f)) {
val beforeValue = assertNotNull(sample(before, poseValue))
val afterValue = assertNotNull(sample(after, poseValue))
assertEquals(beforeValue, afterValue, absoluteTolerance = 1e-3f, message = "pose $poseValue is unchanged")
}
}
/** Inserting on a multi-axis grid adds a whole slice, one cell per key of every other axis. */
@Test
fun insertingAddsAWholeSliceNotOneCell() {
val axes = listOf(KeyformAxis(angleX, floatArrayOf(0f, 10f)), KeyformAxis(angleY, floatArrayOf(0f, 1f)))
val cells =
listOf(
KeyformCell(intArrayOf(0, 0), scalar(0f)),
KeyformCell(intArrayOf(1, 0), scalar(100f)),
KeyformCell(intArrayOf(0, 1), scalar(0f)),
KeyformCell(intArrayOf(1, 1), scalar(200f)),
)
val after = KeyformGrid(axes, cells).withKeyInserted(angleX, 5f, ChannelValueInterpolator)
assertEquals(6, after.cells.size, "a 2x2 grid gains a column, not a single cell")
assertTrue(after.isDense)
val insertedSlice = after.cells.filter { cell -> cell.coordinate[0] == 1 }.sortedBy { cell -> cell.coordinate[1] }
assertEquals(listOf(50f, 100f), insertedSlice.map { cell -> scalarOf(cell) }, "each new cell blends its own row")
}
/** A key within the evaluator's snap tolerance of an existing one is refused, not stacked beside it. */
@Test
fun insertingRefusesAKeyInsideTheSnapTolerance() {
val before = track(floatArrayOf(0f, 10f), floatArrayOf(0f, 100f))
assertSame(before, before.withKeyInserted(angleX, 0.0005f, ChannelValueInterpolator))
}
/** A key that would leave a span the evaluator resolves as a step is refused. */
@Test
fun insertingRefusesASubResolutionSpan() {
val before = track(floatArrayOf(0f, 10f), floatArrayOf(0f, 100f))
assertSame(before, before.withKeyInserted(angleX, 0.0012f, ChannelValueInterpolator))
}
/** Beyond the span, Extend replicates the end slice - constant extrapolation, never a projected trend. */
@Test
fun insertingBeyondTheSpanExtrapolatesFlat() {
val before = track(floatArrayOf(0f, 10f), floatArrayOf(0f, 100f))
val after = before.withKeyInserted(angleX, 20f, ChannelValueInterpolator, OutOfSpanKeyPolicy.Extend)
assertEquals(listOf(0f, 10f, 20f), after.axes.single().keys.toList())
assertEquals(100f, scalarOf(after.cells.first { cell -> cell.coordinate.single() == 2 }), "the end value is held, not projected to 200")
assertSame(before, before.withKeyInserted(angleX, 20f, ChannelValueInterpolator, OutOfSpanKeyPolicy.Reject))
}
/** Removing an interior key leaves the axis intact and re-projects the coordinates above it. */
@Test
fun removingAnInteriorKeyKeepsTheAxis() {
val before = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 40f, 100f))
val after = assertNotNull(before.withKeyRemoved(angleX, keyIndex = 1))
assertEquals(listOf(0f, 10f), after.axes.single().keys.toList())
assertEquals(listOf(0f, 100f), after.cells.map { cell -> scalarOf(cell) })
}
/**
* Removing down to one key collapses the axis instead of leaving a stub, because a single-key axis
* resolves only within EPS_KEY of that key and hides the entity everywhere else.
*/
@Test
fun removingBelowTwoKeysCollapsesTheAxis() {
val before = track(floatArrayOf(0f, 10f), floatArrayOf(7f, 100f))
// Sole axis, so the collapse leaves the entity unkeyed entirely.
assertNull(before.withKeyRemoved(angleX, keyIndex = 1))
val twoAxis = assertNotNull(before.withAxisSeeded(parameter(angleY), scalar(0f)))
val collapsed = assertNotNull(twoAxis.withKeyRemoved(angleX, keyIndex = 1))
assertEquals(listOf(angleY), collapsed.axes.map { axis -> axis.parameterId }, "angleX collapsed rather than keeping one key")
}
/** Capture inserts a key at the pose, writes exactly one cell, and leaves every other pose alone. */
@Test
fun captureWritesOneCellAtThePose() {
val before = track(floatArrayOf(0f, 10f), floatArrayOf(0f, 100f))
val after = before.withFormCaptured({ 4f }, scalar(80f), ChannelValueInterpolator)
assertEquals(listOf(0f, 4f, 10f), after.axes.single().keys.toList())
assertEquals(80f, assertNotNull(sample(after, 4f)), "the captured value lands exactly on the pose")
assertEquals(0f, assertNotNull(sample(after, 0f)), "the endpoints are untouched")
assertEquals(100f, assertNotNull(sample(after, 10f)))
}
/** Capturing at an existing key overwrites that cell without reshaping the axis. */
@Test
fun captureOnAnExistingKeyDoesNotReshape() {
val before = track(floatArrayOf(0f, 10f), floatArrayOf(0f, 100f))
val after = before.withFormCaptured({ 10f }, scalar(55f), ChannelValueInterpolator)
assertEquals(listOf(0f, 10f), after.axes.single().keys.toList())
assertEquals(55f, assertNotNull(sample(after, 10f)))
}
/** A sparse grid is refused by every reshaping op rather than being silently repaired. */
@Test
fun sparseGridsAreRefused() {
val dense = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 40f, 100f))
val sparse = KeyformGrid(dense.axes, dense.cells.drop(1))
assertSame(sparse, sparse.withKeyInserted(angleX, 2f, ChannelValueInterpolator))
assertSame(sparse, sparse.withKeyRemoved(angleX, keyIndex = 1))
assertSame(sparse, sparse.withFormCaptured({ 2f }, scalar(1f), ChannelValueInterpolator))
}
/** Moving a key changes only WHERE it applies; the value it holds rides along. */
@Test
fun movingAKeyCarriesItsValue() {
val before = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 42f, 100f))
val after = before.withKeyMoved(angleX, keyIndex = 1, newValue = 8f)
assertEquals(listOf(0f, 8f, 10f), after.axes.single().keys.toList())
assertEquals(42f, assertNotNull(sample(after, 8f)), "the moved key still holds what it held")
}
/**
* A key may CROSS its neighbours; the axis re-sorts and the cells permute to match.
*
* The permutation is the whole cost of allowing it. A cell's coordinate on an axis is a key ORDINAL
* and the evaluator requires an ascending axis, so re-sorting the keys alone would still satisfy
* isDense while silently applying every form at the wrong position.
*/
@Test
fun movingAcrossANeighbourPermutesTheCells() {
val before = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 42f, 100f))
val crossed = before.withKeyMoved(angleX, keyIndex = 1, newValue = 20f)
assertEquals(listOf(0f, 10f, 20f), crossed.axes.single().keys.toList(), "the axis re-sorts")
assertTrue(crossed.isDense, "and stays dense")
assertEquals(42f, assertNotNull(sample(crossed, 20f)), "the moved key still holds what it held")
assertEquals(100f, assertNotNull(sample(crossed, 10f)), "the key it passed still holds what it held")
assertEquals(0f, assertNotNull(sample(crossed, 0f)), "and the untouched key is untouched")
}
/** Crossing works downward too, and the whole run of passed keys shifts up by one ordinal. */
@Test
fun movingDownAcrossSeveralNeighbours() {
val before = track(floatArrayOf(0f, 5f, 10f, 15f), floatArrayOf(0f, 42f, 100f, 7f))
val crossed = before.withKeyMoved(angleX, keyIndex = 3, newValue = 2f)
assertEquals(listOf(0f, 2f, 5f, 10f), crossed.axes.single().keys.toList())
assertTrue(crossed.isDense)
assertEquals(7f, assertNotNull(sample(crossed, 2f)), "the dragged key kept its value across three crossings")
assertEquals(42f, assertNotNull(sample(crossed, 5f)))
assertEquals(100f, assertNotNull(sample(crossed, 10f)))
}
/**
* A destination that would collide with another key is nudged just far enough to stay resolvable.
*
* Not a spacing preference: two keys closer than EPS_SPAN make the evaluator read fraction 0 across the
* gap, so the nearer one becomes unreachable and the blend degenerates into a step.
*/
@Test
fun aCollidingDestinationStaysResolvable() {
val before = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 42f, 100f))
val landed = before.withKeyMoved(angleX, keyIndex = 0, newValue = 5f)
val keys = landed.axes.single().keys.toList()
assertTrue(keys[1] - keys[0] >= EPS_SPAN, "the two keys stay at least a resolvable span apart")
assertEquals(42f, assertNotNull(sample(landed, 5f)), "the key it landed beside is still reachable")
}
/**
* A key dropped exactly onto the LAST key is nudged inward, never past it.
*
* Outward would put it beyond the axis's own span - and so beyond the parameter's range, where the
* evaluator brackets nothing and every entity keyed on it disappears. That is the difference between
* a sub-pixel nudge and a vanishing rig.
*/
@Test
fun aCollisionAtAnEndpointNudgesInward() {
val before = track(floatArrayOf(-30f, 0f, 30f), floatArrayOf(0f, 42f, 100f))
val onTheLast = before.withKeyMoved(angleX, keyIndex = 1, newValue = 30f)
val highest = onTheLast.axes.single().keys.max()
assertEquals(30f, highest, "the axis did not grow past where it already reached")
val onTheFirst = before.withKeyMoved(angleX, keyIndex = 1, newValue = -30f)
assertEquals(-30f, onTheFirst.axes.single().keys.min(), "and not below it either")
}
/** The mover's new ordinal is reported, so whatever is holding that key can follow it. */
@Test
fun theNewOrdinalIsReported() {
val before = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 42f, 100f))
assertEquals(2, before.keyIndexAfterMove(angleX, keyIndex = 1, newValue = 20f), "crossed to the end")
assertEquals(0, before.keyIndexAfterMove(angleX, keyIndex = 2, newValue = -5f), "crossed to the start")
assertEquals(1, before.keyIndexAfterMove(angleX, keyIndex = 1, newValue = 6f), "stayed put")
}
/** An endpoint has one wall only, so a move can still widen the axis - that is real authoring. */
@Test
fun movingAnEndpointResizesTheSpan() {
val before = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 42f, 100f))
val widened = before.withKeyMoved(angleX, keyIndex = 2, newValue = 30f)
assertEquals(listOf(0f, 5f, 30f), widened.axes.single().keys.toList())
}
/** A move to where the key already sits, or on a missing axis, records nothing. */
@Test
fun aPointlessMoveIsARefusal() {
val before = track(floatArrayOf(0f, 5f, 10f), floatArrayOf(0f, 42f, 100f))
assertSame(before, before.withKeyMoved(angleX, keyIndex = 1, newValue = 5f))
assertSame(before, before.withKeyMoved(angleY, keyIndex = 0, newValue = 1f))
}
/**
* The collision nudge never lands ON another key, even where the only gap is one it created itself.
*
* The nudge is measured against the NEAREST key, so on a crowded axis "nearest + EPS_SPAN" can be
* exactly where the next key along already sits - and two keys closer than EPS_SPAN is the
* unresolvable span the nudge exists to prevent (bindBracket gives such a span fraction 0, so the
* upper key can never be reached). A move that cannot be made resolvable is refused instead.
*/
@Test
fun theCollisionNudgeNeverLandsOnAnotherKey() {
val crowded = track(floatArrayOf(0f, EPS_SPAN, 10f), floatArrayOf(0f, 1f, 2f))
// Aimed just above the key at 0: the nearest is 0, so the nudge goes to 0 + EPS_SPAN - which is
// exactly the second key.
assertNull(
crowded.keyDestinationFor(angleX, keyIndex = 2, newValue = EPS_SPAN / 3f),
"nudging onto an existing key is refused rather than authored",
)
assertSame(crowded, crowded.withKeyMoved(angleX, keyIndex = 2, newValue = EPS_SPAN / 3f), "so the move is a no-op")
// The same axis still accepts a destination with room on both sides.
val moved = crowded.withKeyMoved(angleX, keyIndex = 2, newValue = 5f)
assertEquals(listOf(0f, EPS_SPAN, 5f), moved.axes.single().keys.toList())
}
}
@@ -0,0 +1,182 @@
package org.umamo.runtime.keyform
import org.umamo.runtime.eval.cellsByLinearIndex
import org.umamo.runtime.model.GlueForm
import org.umamo.runtime.model.KeyformAxis
import org.umamo.runtime.model.KeyformCell
import org.umamo.runtime.model.KeyformGrid
import org.umamo.runtime.model.ParameterId
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins the keyform-grid shape layer: the stride folding (which must agree with the evaluator's own,
* since the resulting linear index is the shared contract between a weighted corner, a stored cell,
* and the GPU delta texture's column), the coordinate round trip, the density check that compaction
* and refine gate on, and withAxisCollapsed's coordinate re-projection.
*/
class KeyformGridShapeTest {
private val angleX = ParameterId("ParamAngleX")
private val angleY = ParameterId("ParamAngleY")
private val angleZ = ParameterId("ParamAngleZ")
/**
* Unfolds a linear index back into a per-axis coordinate - the inverse of linearIndexOf, kept as a
* fixture helper (production code only ever folds).
*/
private fun KeyformGrid<*>.coordinateOf(linearIndex: Int): IntArray {
val coordinate = IntArray(axes.size)
var remaining = linearIndex
for (axisIndex in axes.indices) {
val keyCount = axes[axisIndex].keys.size
if (keyCount <= 0) {
continue
}
coordinate[axisIndex] = remaining % keyCount
remaining /= keyCount
}
return coordinate
}
/**
* A dense grid over the given axis key counts, each cell carrying its own linear index as its
* payload so a re-shape can be traced by value.
*/
private fun denseGrid(vararg keyCounts: Int): KeyformGrid<GlueForm> {
val parameterIds = listOf(angleX, angleY, angleZ)
val axes =
keyCounts.mapIndexed { axisIndex, keyCount ->
KeyformAxis(parameterIds[axisIndex], FloatArray(keyCount) { keyIndex -> keyIndex.toFloat() })
}
val grid = KeyformGrid(axes, emptyList<KeyformCell<GlueForm>>())
val cells =
(0 until grid.cellCount).map { linearIndex ->
KeyformCell(grid.coordinateOf(linearIndex), GlueForm(linearIndex.toFloat()))
}
return KeyformGrid(axes, cells)
}
/** cellCount is the product of the axis key counts, and 1 for an axis-less grid. */
@Test
fun cellCountIsTheAxisProduct() {
assertEquals(6, denseGrid(3, 2).cellCount)
assertEquals(24, denseGrid(4, 3, 2).cellCount)
assertEquals(1, KeyformGrid(emptyList(), listOf(KeyformCell(intArrayOf(), GlueForm(1f)))).cellCount)
}
/**
* The stride folding matches the evaluator's cellsByLinearIndex exactly. Both now share
* KeyformGrid's own members, so this pins the contract rather than guarding a duplicate.
*/
@Test
fun linearIndexMatchesTheEvaluatorFolding() {
for (grid in listOf(denseGrid(3, 2), denseGrid(4, 3, 2), denseGrid(5))) {
val evaluatorIndexed = cellsByLinearIndex(grid)
for (cell in grid.cells) {
val shapeIndex = grid.linearIndexOf(cell.coordinate)
assertSame(cell, evaluatorIndexed[shapeIndex], "cell ${cell.coordinate.toList()} folds to the same index")
}
}
}
/** coordinateOf inverts linearIndexOf for every cell in the grid's shape. */
@Test
fun coordinateRoundTripsThroughLinearIndex() {
val grid = denseGrid(4, 3, 2)
for (linearIndex in 0 until grid.cellCount) {
assertEquals(linearIndex, grid.linearIndexOf(grid.coordinateOf(linearIndex)))
}
}
/** Axis 0 varies fastest, matching the evaluator's stride accumulation order. */
@Test
fun axisZeroVariesFastest() {
val grid = denseGrid(3, 2)
assertEquals(listOf(1, 3), grid.strides().toList())
assertEquals(listOf(1, 0), grid.coordinateOf(1).toList(), "the second cell steps along axis 0")
}
/** A grid with one cell per coordinate is dense; a grid missing a cell is not. */
@Test
fun densityDetectsAMissingCell() {
val dense = denseGrid(3, 2)
assertTrue(dense.isDense)
val sparse = KeyformGrid(dense.axes, dense.cells.drop(1))
assertFalse(sparse.isDense, "a dropped cell makes the grid sparse")
val duplicated = KeyformGrid(dense.axes, dense.cells.dropLast(1) + dense.cells.first())
assertFalse(duplicated.isDense, "a duplicated coordinate makes the grid sparse")
}
/** axisIndexOf finds an axis by parameter and reports -1 when the grid has none. */
@Test
fun axisIndexOfLocatesTheAxis() {
val grid = denseGrid(3, 2)
assertEquals(0, grid.axisIndexOf(angleX))
assertEquals(1, grid.axisIndexOf(angleY))
assertEquals(-1, grid.axisIndexOf(angleZ))
}
/** withAxisCollapsed drops the named axis and re-projects each surviving cell's coordinate. */
@Test
fun withAxisCollapsedReprojectsCoordinates() {
val axes = listOf(KeyformAxis(angleX, floatArrayOf(0f, 1f)), KeyformAxis(angleY, floatArrayOf(0f, 1f)))
val cells =
listOf(
KeyformCell(intArrayOf(0, 0), GlueForm(0f)),
KeyformCell(intArrayOf(0, 1), GlueForm(1f)),
KeyformCell(intArrayOf(1, 0), GlueForm(2f)),
KeyformCell(intArrayOf(1, 1), GlueForm(3f)),
)
// Collapse angleX keeping the value-0 slice (key index 0): surviving cells are (0,0) and (0,1).
val collapsed = KeyformGrid(axes, cells).withAxisCollapsed(angleX, keepKeyValue = 0f)!!
assertEquals(listOf(angleY), collapsed.axes.map { axis -> axis.parameterId })
assertEquals(listOf(listOf(0), listOf(1)), collapsed.cells.map { cell -> cell.coordinate.toList() })
assertEquals(listOf(0f, 1f), collapsed.cells.map { cell -> cell.form.intensity })
}
/** The kept slice is the NEAREST key, so a value between keys snaps rather than interpolating. */
@Test
fun withAxisCollapsedSnapsToTheNearestKey() {
val grid = denseGrid(3, 2)
// angleX keys are 0, 1, 2; 1.6 is nearest key index 2, whose cells are linear indices 2 and 5.
val collapsed = grid.withAxisCollapsed(angleX, keepKeyValue = 1.6f)!!
assertEquals(listOf(2f, 5f), collapsed.cells.map { cell -> cell.form.intensity })
}
/** withAxisCollapsed returns the same instance when the grid has no such axis. */
@Test
fun withAxisCollapsedAbsentAxisReturnsSame() {
val grid = denseGrid(3, 2)
assertSame(grid, grid.withAxisCollapsed(angleZ, keepKeyValue = 0f))
}
/** Collapsing the only axis leaves nothing to key on, so the grid becomes null (the entity unkeyed). */
@Test
fun withAxisCollapsedSoleAxisBecomesNull() {
assertNull(denseGrid(3).withAxisCollapsed(angleX, keepKeyValue = 0f))
}
/** withAxisRetargeted renames the axis and keeps key values / cells. */
@Test
fun withAxisRetargetedRenamesAxisKeepsKeys() {
val grid = denseGrid(3)
val retargeted = grid.withAxisRetargeted(angleX, angleY, destinationKeepValue = 0f)
assertEquals(listOf(angleY), retargeted.axes.map { it.parameterId })
assertTrue(retargeted.axes.single().keys.contentEquals(grid.axes.single().keys))
assertEquals(grid.cells.map { it.form.intensity }, retargeted.cells.map { it.form.intensity })
}
/** withAxisRetargeted collapses an existing destination axis before renaming the source onto it. */
@Test
fun withAxisRetargetedCollapsesExistingDestination() {
val grid = denseGrid(3, 2)
// Destination default 0 keeps angleY key index 0; then angleX renames onto angleY.
val retargeted = grid.withAxisRetargeted(angleX, angleY, destinationKeepValue = 0f)
assertEquals(listOf(angleY), retargeted.axes.map { it.parameterId })
assertEquals(listOf(0f, 1f, 2f), retargeted.cells.map { it.form.intensity })
}
}
@@ -0,0 +1,69 @@
package org.umamo.runtime.model
import kotlin.math.abs
import kotlin.test.Test
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
/**
* Pins the placement's matrix form against its pointwise reference, and the affine composition the
* export's transform rewrites lean on: forward-composed-with-inverse must be the identity for every
* placement shape the corpus contains.
*/
class AtlasPlacementAffineTest {
private fun placementOf(
positionX: Float = 0f,
positionY: Float = 0f,
scaleX: Float = 1f,
scaleY: Float = 1f,
rotationDegrees: Float = 0f,
): AtlasPlacement = AtlasPlacement(0, positionX, positionY, scaleX, scaleY, rotationDegrees)
private val shapes =
listOf(
placementOf(),
placementOf(positionX = 137.5f, positionY = -12.25f),
placementOf(rotationDegrees = 90f, positionX = 40f),
placementOf(rotationDegrees = 33.7f, scaleX = 0.5f, scaleY = 2f, positionX = 7f, positionY = 9f),
placementOf(scaleX = -1f, positionY = 512f),
)
private fun applyAffine(affine: FloatArray, x: Float, y: Float): FloatArray =
floatArrayOf(
affine[0] * x + affine[1] * y + affine[2],
affine[3] * x + affine[4] * y + affine[5],
)
@Test
fun placementAffineMatchesAtlasPixelOf() {
val probePoints = listOf(0f to 0f, 12f to 34f, -5f to 100f, 250.5f to 0.25f)
for (placement in shapes) {
val affine = placementAffine(placement)
for ((layerX, layerY) in probePoints) {
val pointwise = atlasPixelOf(placement, layerX, layerY)
val viaMatrix = applyAffine(affine, layerX, layerY)
assertTrue(
abs(pointwise[0] - viaMatrix[0]) < 1e-3f && abs(pointwise[1] - viaMatrix[1]) < 1e-3f,
"$placement at ($layerX, $layerY): pointwise (${pointwise[0]}, ${pointwise[1]})" +
" vs matrix (${viaMatrix[0]}, ${viaMatrix[1]})",
)
}
}
}
@Test
fun composeWithInverseIsIdentity() {
for (placement in shapes) {
val forward = placementAffine(placement)
val inverse = assertNotNull(inversePlacementAffine(placement), "$placement inverts")
val composed = composeAffine(forward, inverse)
val identity = floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f)
for (componentIndex in identity.indices) {
assertTrue(
abs(composed[componentIndex] - identity[componentIndex]) < 1e-3f,
"$placement component $componentIndex: ${composed[componentIndex]}",
)
}
}
}
}
@@ -0,0 +1,73 @@
package org.umamo.runtime.model
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* Pins the deformer subtree query behind both the reparent cycle guard and the Properties picker's
* candidate filter: a deformer plus everything nested beneath it, which is exactly the set it may not be
* re-nested under. Sharing one definition is what keeps the picker from offering a target the move would
* then silently refuse.
*/
class DeformerSubtreeTest {
private val rootId = DeformerId("root")
private val childId = DeformerId("child")
private val grandchildId = DeformerId("grandchild")
private val siblingId = DeformerId("sibling")
private fun warp(id: DeformerId, parent: DeformerId?): Deformer.Warp =
Deformer.Warp(
id = id,
name = id.raw,
parent = parent,
partId = null,
rows = 2,
columns = 2,
isQuadTransform = false,
geometryGrid = null,
)
/** root > child > grandchild, with an unrelated sibling at the armature root. */
private fun model(): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts = emptyList(),
deformers =
listOf(
warp(rootId, null),
warp(childId, rootId),
warp(grandchildId, childId),
warp(siblingId, null),
),
drawables = emptyList(),
rootChildren = emptyList(),
rootPartId = null,
)
@Test
fun collectsTheDeformerAndEveryDescendant() {
assertEquals(setOf(rootId, childId, grandchildId), model().deformerSelfAndDescendants(rootId))
assertEquals(setOf(childId, grandchildId), model().deformerSelfAndDescendants(childId))
// A leaf is just itself - self-parenting is still refused because the set contains it.
assertEquals(setOf(grandchildId), model().deformerSelfAndDescendants(grandchildId))
}
@Test
fun excludesUnrelatedBranchesSoTheyStayValidParents() {
val forbidden = model().deformerSelfAndDescendants(rootId)
assertTrue(siblingId !in forbidden, "an unrelated deformer is a legal parent")
}
@Test
fun aMoveIntoTheOwnSubtreeIsRefusedAndAnUnrelatedOneIsNot() {
val base = model()
// Every member of the subtree is an illegal parent for root, self included.
for (candidate in base.deformerSelfAndDescendants(rootId)) {
assertTrue(candidate in base.deformerSelfAndDescendants(rootId))
}
// The picker filters on exactly this, so what it offers is what the move accepts.
assertTrue(rootId in base.deformerSelfAndDescendants(rootId), "self is in the forbidden set")
assertTrue(grandchildId in base.deformerSelfAndDescendants(rootId), "a descendant is forbidden")
}
}
@@ -0,0 +1,77 @@
package org.umamo.runtime.model
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
/**
* Unit-tests [firstEditableDrawableInPanelOrder]: Edit mode seeds onto the topmost drawable in Parts-panel
* order (top = front) that both carries a mesh and is shown, so a fresh document never opens Edit on
* nothing. Corpus-free - hand-built trees exercise panel order, the mesh-less skip, the visibility
* cascade, the empty-tree flat fallback, and the nothing-editable null.
*/
class FirstEditableDrawableTest {
private fun mesh(): DrawableMesh = DrawableMesh(floatArrayOf(0f, 0f), floatArrayOf(0f, 0f), intArrayOf())
private fun drawable(id: String, hasMesh: Boolean = true, isVisible: Boolean = true): Drawable =
Drawable(
id = DrawableId(id),
name = id,
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = if (hasMesh) mesh() else null,
geometryGrid = null,
isVisible = isVisible,
)
@Test
fun picksFrontOfPanelOrder() {
val drawables = listOf(drawable("front"), drawable("back"))
// Panel order top = front: "front" precedes "back" at the root.
val rootChildren = listOf(OrgChild.Drawable(DrawableId("front")), OrgChild.Drawable(DrawableId("back")))
val model = PuppetModel(emptyList(), emptyList(), emptyList(), drawables, rootChildren, rootPartId = null)
assertEquals(DrawableId("front"), model.firstEditableDrawableInPanelOrder())
}
@Test
fun skipsMeshlessAndHiddenDrawables() {
val hiddenPart = Part(PartId("hidden"), "[Guide Image]", listOf(OrgChild.Drawable(DrawableId("inHidden"))), isVisible = false)
val drawables =
listOf(
drawable("noMesh", hasMesh = false), // no mesh → skipped
drawable("inHidden", hasMesh = true), // ancestor part hidden → skipped
drawable("ownHidden", hasMesh = true, isVisible = false), // own eyeball off → skipped
drawable("editable", hasMesh = true), // first shown + meshed → the pick
)
val rootChildren =
listOf(
OrgChild.Drawable(DrawableId("noMesh")),
OrgChild.Part(PartId("hidden")),
OrgChild.Drawable(DrawableId("ownHidden")),
OrgChild.Drawable(DrawableId("editable")),
)
val model = PuppetModel(emptyList(), listOf(hiddenPart), emptyList(), drawables, rootChildren, rootPartId = null)
assertEquals(DrawableId("editable"), model.firstEditableDrawableInPanelOrder())
}
@Test
fun returnsNullWhenNothingEditable() {
val drawables = listOf(drawable("a", hasMesh = false), drawable("b", hasMesh = true, isVisible = false))
val rootChildren = listOf(OrgChild.Drawable(DrawableId("a")), OrgChild.Drawable(DrawableId("b")))
val model = PuppetModel(emptyList(), emptyList(), emptyList(), drawables, rootChildren, rootPartId = null)
assertNull(model.firstEditableDrawableInPanelOrder())
}
@Test
fun fallsBackToFlatListWhenTreeIsEmpty() {
// A degenerate model with no org tree still finds its meshed, visible drawable.
val drawables = listOf(drawable("orphan", hasMesh = true))
val model = PuppetModel(emptyList(), emptyList(), emptyList(), drawables, rootChildren = emptyList(), rootPartId = null)
assertEquals(DrawableId("orphan"), model.firstEditableDrawableInPanelOrder())
}
}
@@ -0,0 +1,110 @@
package org.umamo.runtime.model
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
/**
* Unit-tests the rigger's coordinate frame: positions read from the world axes, and the Origin fields read
* from the canvas's bottom-left corner with Z up. Corpus-free - hand-built models with a canvas and an origin
* exercise the default center origin, both round trips off center, the canvas-less model, and a canvas height
* change.
*/
class OriginRelativeCoordinatesTest {
/**
* A model with no content, a [width] x [height] canvas, and its world origin at ([originX], [originZ]).
*
* @param Float width The canvas width.
* @param Float height The canvas height.
* @param Float originX The world-origin x.
* @param Float originZ The world-origin z (up; world space, negated canvas y).
* @return PuppetModel The model.
*/
private fun model(width: Float, height: Float, originX: Float, originZ: Float): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts = emptyList(),
deformers = emptyList(),
drawables = emptyList(),
rootChildren = emptyList(),
rootPartId = null,
canvasWidth = width,
canvasHeight = height,
worldOriginX = originX,
worldOriginZ = originZ,
)
/** The origin every importer derives: the center of a 1200 x 1200 canvas, stored as (600, -600). */
private val centered = model(1200f, 1200f, 600f, -600f)
@Test
fun theDefaultOriginReadsFromTheCanvasBottomLeft() {
assertEquals(600f, centered.originFromCanvasLeft())
assertEquals(600f, centered.originFromCanvasBottom(), "Z counts up from the bottom edge, so the center reads positive")
}
@Test
fun positionsReadFromTheWorldAxes() {
// The world point the axes cross at reads (0, 0).
assertEquals(0f, centered.originRelativeX(600f))
assertEquals(0f, centered.originRelativeZ(-600f))
// The canvas's top-left corner (world zero) sits left of and above the axes.
assertEquals(-600f, centered.originRelativeX(0f))
assertEquals(600f, centered.originRelativeZ(0f))
}
@Test
fun positionsRoundTripOffCenter() {
val offCenter = model(1000f, 800f, 250f, -600f)
assertEquals(40f, offCenter.originRelativeX(offCenter.worldXFromOriginRelative(40f)))
assertEquals(-75f, offCenter.originRelativeZ(offCenter.worldZFromOriginRelative(-75f)))
assertEquals(310f, offCenter.worldXFromOriginRelative(offCenter.originRelativeX(310f)))
assertEquals(-120f, offCenter.worldZFromOriginRelative(offCenter.originRelativeZ(-120f)))
}
@Test
fun theOriginRoundTripsThroughTheCanvasReading() {
val offCenter = model(1000f, 800f, 250f, -600f)
// Stored 600 below the top of an 800-tall canvas, so 200 above its bottom.
assertEquals(250f, offCenter.originFromCanvasLeft())
assertEquals(200f, offCenter.originFromCanvasBottom())
assertEquals(250f, offCenter.worldOriginXFromCanvasLeft(offCenter.originFromCanvasLeft()))
assertEquals(-600f, offCenter.worldOriginZFromCanvasBottom(offCenter.originFromCanvasBottom()))
assertEquals(-500f, offCenter.worldOriginZFromCanvasBottom(300f), "typing 300 puts the origin 300 above the bottom edge")
}
@Test
fun aCanvaslessModelReadsWorldSpace() {
val canvasless = model(0f, 0f, 0f, 0f)
assertEquals(35f, canvasless.originRelativeX(35f))
assertEquals(-12f, canvasless.originRelativeZ(-12f))
assertEquals(0f, canvasless.originFromCanvasBottom(), "with no canvas the bottom reading is the raw world z")
}
@Test
fun aCanvasHeightChangeMovesOnlyTheOriginZReading() {
// The canvas grows at its bottom edge and the origin keeps its world point.
val taller = centered.copy(canvasHeight = 1300f)
assertEquals(700f, taller.originFromCanvasBottom(), "the bottom edge moved 100 further from the origin")
assertEquals(600f, taller.originFromCanvasLeft())
assertEquals(centered.originRelativeX(420f), taller.originRelativeX(420f), "positions still read from the same axes")
assertEquals(centered.originRelativeZ(-300f), taller.originRelativeZ(-300f))
}
@Test
fun theCanvasCenterOriginIsTheImportersDefault() {
assertEquals(600f, canvasCenterWorldOriginX(1200f))
assertEquals(-400f, canvasCenterWorldOriginZ(800f), "half the height down from the top edge, negated into world z")
assertEquals(0f, canvasCenterWorldOriginX(0f), "no canvas keeps the (0, 0) origin")
assertTrue(centered.isOriginAtCanvasCenter())
assertTrue(model(0f, 0f, 0f, 0f).isOriginAtCanvasCenter(), "a canvas-less model's (0, 0) origin is its center")
assertFalse(centered.copy(worldOriginZ = -500f).isOriginAtCanvasCenter(), "a moved origin is off center")
assertFalse(centered.copy(canvasHeight = 1300f).isOriginAtCanvasCenter(), "a resized canvas leaves the origin behind")
}
}
@@ -0,0 +1,155 @@
package org.umamo.runtime.model
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
/**
* Pins the part-as-mask extension: a part used as a clip mask expands to its descendant drawables (through
* nested parts) in the DERIVED render tree only, while the authored composite keeps the part reference for
* the UI. Also pins the dedup when a drawable is masked both directly and through an ancestor part.
*/
class PartMaskResolveTest {
private val maskLeafId = DrawableId("maskLeaf")
private val maskNestedId = DrawableId("maskNested")
private val subjectId = DrawableId("subject")
private val maskPartId = PartId("maskPart")
private val nestedPartId = PartId("nestedPart")
private val subjectPartId = PartId("subjectPart")
private fun drawable(id: DrawableId): Drawable =
Drawable(
id = id,
name = id.raw,
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = null,
geometryGrid = null,
)
/** A mask part holding one drawable plus a nested part holding another, beside an isolated subject part. */
private fun model(composite: PartComposite): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts =
listOf(
Part(maskPartId, "maskPart", children = listOf(OrgChild.Drawable(maskLeafId), OrgChild.Part(nestedPartId))),
Part(nestedPartId, "nestedPart", children = listOf(OrgChild.Drawable(maskNestedId))),
Part(
subjectPartId,
"subjectPart",
children = listOf(OrgChild.Drawable(subjectId)),
groupMode = PartGroupMode.Isolated,
composite = composite,
),
),
deformers = emptyList(),
drawables = listOf(drawable(maskLeafId), drawable(maskNestedId), drawable(subjectId)),
rootChildren = listOf(OrgChild.Part(maskPartId), OrgChild.Part(subjectPartId)),
rootPartId = null,
)
/** The composite the render tree carries for the subject part. */
private fun renderedComposite(model: PuppetModel): PartComposite? {
val root = model.deriveRenderRoot()
fun find(node: RenderNode): RenderGroup? =
when (node) {
is RenderDrawable -> null
is RenderGroup ->
if (node.partId == subjectPartId) {
node
} else {
node.children.firstNotNullOfOrNull { child -> find(child) }
}
}
return find(root)?.composite
}
@Test
fun parentPartLookupCoversNestedPartsOnly() {
// Part membership lives only in the tree, so the Properties panel needs this to show a nested part's
// owner; a top-level part has no entry and reads as unbound.
val parents = model(PartComposite()).parentPartByPart()
assertEquals(maskPartId, parents[nestedPartId])
assertNull(parents[maskPartId], "a top-level part has no owning part")
assertNull(parents[subjectPartId])
}
@Test
fun subtreeQueryWalksNestedParts() {
val subtrees = model(PartComposite()).drawablesByPartSubtree()
assertEquals(listOf(maskLeafId, maskNestedId), subtrees[maskPartId], "nested part contributes its drawables")
assertEquals(listOf(maskNestedId), subtrees[nestedPartId])
assertEquals(listOf(subjectId), subtrees[subjectPartId])
}
@Test
fun aMaskPartExpandsToItsDescendantDrawablesInTheRenderTree() {
val authored = PartComposite(maskedByParts = listOf(maskPartId))
val model = model(authored)
assertEquals(listOf(maskLeafId, maskNestedId), renderedComposite(model)?.maskedBy, "expanded for the renderer")
// The authored value is untouched, so the panel still shows the part, not its expansion.
val storedComposite = model.parts.first { it.id == subjectPartId }.composite
assertEquals(listOf(maskPartId), storedComposite.maskedByParts)
assertTrue(storedComposite.maskedBy.isEmpty())
}
@Test
fun theRenderCompositeCarriesNoPartIdsAtAll() {
// PartComposite documents that the render tree sees the EXPANSION and never the part ids. Leaving
// them beside the expansion would let any consumer that later honours them clip by the same drawables
// twice, so the resolved copy must clear the field, not merely add to maskedBy.
val authored = PartComposite(maskedByParts = listOf(maskPartId))
val rendered = renderedComposite(model(authored))
assertTrue(rendered?.maskedByParts?.isEmpty() == true, "the renderer must not receive part ids")
assertEquals(listOf(maskLeafId, maskNestedId), rendered.maskedBy)
}
@Test
fun directAndPartReachedMasksMergeWithoutDuplicates() {
// maskLeaf is masked directly AND sits under the masking part: it must appear once.
val authored = PartComposite(maskedBy = listOf(maskLeafId), maskedByParts = listOf(maskPartId))
assertEquals(listOf(maskLeafId, maskNestedId), renderedComposite(model(authored))?.maskedBy)
}
@Test
fun flatteningForExportPreservesExactlyWhatTheRendererClipsWith() {
// The guarantee behind withPartMasksFlattened: an export to a drawable-only mask format (CMO3) keeps
// the clipping the viewport shows. Only the "masked by this part" grouping is lost, which those
// formats cannot record - so the conversion is explicit, never a silent drop.
val authored = PartComposite(maskedBy = listOf(maskLeafId), maskedByParts = listOf(maskPartId))
val model = model(authored)
val rendered = renderedComposite(model)?.maskedBy
val exported = model.withPartMasksFlattened()
val exportedComposite = exported.parts.first { it.id == subjectPartId }.composite
assertEquals(rendered, exportedComposite.maskedBy, "export clips exactly as the viewport does")
assertTrue(exportedComposite.maskedByParts.isEmpty(), "the part reference is expanded, not carried")
// Flattening is idempotent, and the render tree of a flattened model is unchanged.
assertEquals(rendered, renderedComposite(exported)?.maskedBy)
assertSame(exported, exported.withPartMasksFlattened())
}
@Test
fun flatteningIsAnIdentityForAModelWithNoPartMasks() {
// The common case pays nothing and an exporter can call it unconditionally.
val model = model(PartComposite(maskedBy = listOf(maskLeafId)))
assertSame(model, model.withPartMasksFlattened())
}
@Test
fun withoutPartMasksTheCompositeInstanceIsPassedThroughUntouched() {
// The common case pays nothing: no part masks means the authored composite reaches the render tree
// as the very same instance.
val authored = PartComposite(maskedBy = listOf(maskLeafId))
val model = model(authored)
assertSame(model.parts.first { it.id == subjectPartId }.composite, renderedComposite(model))
}
}
@@ -0,0 +1,74 @@
package org.umamo.runtime.model
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* Pins the part subtree query behind both the org-move cycle guard and the Properties picker's owner
* filter: a part plus every part beneath it, which is exactly the set it may NOT be re-homed under.
*
* This replaced two private implementations that walked the tree in OPPOSITE directions - one down from
* the part, one up the parent chain - so the point of the test is that ONE definition serves both, and
* that a malformed (already cyclic) tree terminates rather than hanging the editor.
*/
class PartSubtreeTest {
private val rootId = PartId("root")
private val childId = PartId("child")
private val grandchildId = PartId("grandchild")
private val siblingId = PartId("sibling")
private fun part(id: PartId, children: List<OrgChild> = emptyList()): Part = Part(id, id.raw, children = children)
/** root > child > grandchild, with an unrelated sibling at the top level. */
private fun model(): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts =
listOf(
part(rootId, listOf(OrgChild.Part(childId))),
part(childId, listOf(OrgChild.Part(grandchildId))),
part(grandchildId),
part(siblingId),
),
deformers = emptyList(),
drawables = emptyList(),
rootChildren = listOf(OrgChild.Part(rootId), OrgChild.Part(siblingId)),
rootPartId = null,
)
@Test
fun collectsThePartAndEveryDescendant() {
assertEquals(setOf(rootId, childId, grandchildId), model().partSelfAndDescendants(rootId))
assertEquals(setOf(childId, grandchildId), model().partSelfAndDescendants(childId))
// A leaf is just itself - self-parenting is still refused because the set contains it.
assertEquals(setOf(grandchildId), model().partSelfAndDescendants(grandchildId))
}
@Test
fun excludesUnrelatedBranchesSoTheyStayValidOwners() {
val forbidden = model().partSelfAndDescendants(rootId)
assertTrue(siblingId !in forbidden, "an unrelated part is a legal owner")
assertTrue(rootId in forbidden, "self is in the forbidden set")
assertTrue(grandchildId in forbidden, "a descendant is forbidden")
}
@Test
fun aMalformedCyclicTreeTerminates() {
// child claims root as a child, so the tree already contains a cycle. The walk must stop, not hang.
val cyclic =
model().copy(
parts =
listOf(
part(rootId, listOf(OrgChild.Part(childId))),
part(childId, listOf(OrgChild.Part(rootId))),
),
)
assertEquals(setOf(rootId, childId), cyclic.partSelfAndDescendants(rootId))
}
@Test
fun aPartMissingFromTheListIsJustItself() {
assertEquals(setOf(PartId("ghost")), model().partSelfAndDescendants(PartId("ghost")))
}
}
@@ -0,0 +1,215 @@
package org.umamo.runtime.model
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Covers how a drawable resolves to its source art: which tile, whether it reads a packed page or the
* art directly, and which page's dimensions the mapping is built against.
*
* The packed-versus-direct decision is the load-bearing one. It used to be read off CMO3 resource
* identity at import; the model derives it instead, from whether the document's stored coordinates
* address the packed pages ([PuppetAtlas.storedUvsAddressPages]) and whether the tile was packed at
* all. Getting it wrong does not fail loudly - it silently swaps a drawable's UV editor between the
* layer frame and the atlas frame - so each arm is pinned here.
*/
class PuppetAtlasTest {
private fun drawable(rawId: String, tileId: String? = null): Drawable =
Drawable(
id = DrawableId(rawId),
name = rawId,
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = null,
geometryGrid = null,
atlasTileId = tileId?.let { raw -> AtlasTileId(raw) },
)
private fun modelOf(atlas: PuppetAtlas, fromSourceLayers: Boolean = false, vararg drawables: Drawable): PuppetModel =
PuppetModel(
parameters = emptyList(),
parts = emptyList(),
deformers = emptyList(),
drawables = drawables.toList(),
rootChildren = drawables.map { entry -> OrgChild.Drawable(entry.id) },
rootPartId = null,
rendersFromSourceLayers = fromSourceLayers,
atlas = atlas,
)
private fun packedTile(rawId: String, pageIndex: Int = 0): AtlasTile =
AtlasTile(
id = AtlasTileId(rawId),
name = "Art",
width = 8,
height = 16,
placement = AtlasPlacement(pageIndex, 4f, 6f, scaleX = 1f, scaleY = 1f, rotationDegrees = 0f),
)
private fun unpackedTile(rawId: String): AtlasTile = AtlasTile(AtlasTileId(rawId), "Art", 8, 16)
@Test
fun aPackedTileInAtlasModeCarriesItsPlacementAndItsPageSize() {
val model =
modelOf(
PuppetAtlas(pages = listOf(AtlasPage(64, 32)), tiles = listOf(packedTile("t0"))),
drawables = arrayOf(drawable("a", "t0")),
)
val binding = assertNotNull(model.atlasBindingFor(model.drawables.single()))
assertEquals("t0", binding.layerKey)
assertNotNull(binding.placement, "a packed tile in atlas mode reads its page")
assertEquals(64, binding.pageWidth)
assertEquals(32, binding.pageHeight)
}
@Test
fun aTileThatWasNeverPackedIsReadDirectly() {
val model =
modelOf(
PuppetAtlas(pages = listOf(AtlasPage(64, 32)), tiles = listOf(unpackedTile("t0"))),
drawables = arrayOf(drawable("a", "t0")),
)
val binding = assertNotNull(model.atlasBindingFor(model.drawables.single()))
assertNull(binding.placement, "art that was never packed is sampled where it lies")
assertTrue(
layerUvAffineOf(binding, 8, 16).contentEquals(identityUvAffine()),
"so its stored coordinates already address it and the mapping is the identity",
)
}
/**
* Which frame the stored coordinates are in is a fact about the FILE, not about what is on screen.
*
* A document whose drawables sample the packed pages has page-space coordinates whether or not the
* rigger is currently looking at the artwork - so toggling the display must not reinterpret them.
* Deriving the frame from the display mode looked right at import, where the two agree, and broke
* the moment anyone flipped the switch: the layer view drew every mesh at its atlas position.
*/
@Test
fun theDisplayModeDoesNotReinterpretStoredCoordinates() {
val atlas = PuppetAtlas(pages = listOf(AtlasPage(64, 32)), tiles = listOf(packedTile("t0")))
val showingAtlas = modelOf(atlas, fromSourceLayers = false, drawables = arrayOf(drawable("a", "t0")))
val showingArtwork = showingAtlas.copy(rendersFromSourceLayers = true)
assertEquals(
showingAtlas.atlasBindingFor(showingAtlas.drawables.single()),
showingArtwork.atlasBindingFor(showingArtwork.drawables.single()),
"the mapping is the same either way - only which texture is sampled differs",
)
assertNotNull(
showingArtwork.atlasBindingFor(showingArtwork.drawables.single())?.placement,
"packed art keeps its placement while the artwork is displayed",
)
}
/**
* A document saved sampling its per-layer rasters has coordinates that already address the art.
*
* The corpus case is a model saved in combined-layer display mode: a packed atlas sits beside it,
* but the drawables point at the layer images, so inverting a page-space placement over those
* coordinates would throw every mesh thousands of pixels away.
*/
@Test
fun aDocumentWhoseCoordinatesAddressTheArtMapsThroughTheIdentity() {
val model =
modelOf(
PuppetAtlas(
pages = listOf(AtlasPage(64, 32)),
tiles = listOf(packedTile("t0")),
storedUvsAddressPages = false,
),
drawables = arrayOf(drawable("a", "t0")),
)
val binding = assertNotNull(model.atlasBindingFor(model.drawables.single()))
assertNull(binding.placement, "the coordinates already address the art, so recovery is the identity")
}
@Test
fun aDrawableWithNoTileHasNoBinding() {
val model =
modelOf(PuppetAtlas(tiles = listOf(unpackedTile("t0"))), drawables = arrayOf(drawable("a")))
assertNull(model.atlasBindingFor(model.drawables.single()), "no tile means no source-art view")
}
@Test
fun aPlacementNamingAMissingPageResolvesToNothingRatherThanTheIdentity() {
// Broken wiring, not a directly-sampled tile: answering "identity" would draw the mesh in the
// wrong frame instead of admitting the binding cannot be formed.
val model =
modelOf(
PuppetAtlas(pages = emptyList(), tiles = listOf(packedTile("t0", pageIndex = 3))),
drawables = arrayOf(drawable("a", "t0")),
)
assertNull(model.atlasBindingFor(model.drawables.single()))
}
@Test
fun anUnknownTileIdResolvesToNothing() {
val model = modelOf(PuppetAtlas(tiles = listOf(unpackedTile("t0"))), drawables = arrayOf(drawable("a", "gone")))
assertNull(model.atlasBindingFor(model.drawables.single()))
assertNull(model.atlasBindingForTile(AtlasTileId("gone")))
}
@Test
fun everyDrawableOverOneTileSharesItsBinding() {
val model =
modelOf(
PuppetAtlas(pages = listOf(AtlasPage(64, 32)), tiles = listOf(packedTile("t0"))),
drawables = arrayOf(drawable("a", "t0"), drawable("b", "t0")),
)
val first = assertNotNull(model.atlasBindingFor(model.drawables[0]))
val second = assertNotNull(model.atlasBindingFor(model.drawables[1]))
assertEquals(first, second, "the placement belongs to the art, so its users cannot disagree")
assertEquals(first, model.atlasBindingForTile(AtlasTileId("t0")), "and the tile answers the same alone")
}
@Test
fun theTileInverseNamesEveryDrawableInDocumentOrder() {
val model =
modelOf(
PuppetAtlas(tiles = listOf(unpackedTile("t0"), unpackedTile("t1"))),
drawables = arrayOf(drawable("a", "t0"), drawable("b", "t1"), drawable("c", "t0"), drawable("d")),
)
assertEquals(
mapOf(
AtlasTileId("t0") to listOf(DrawableId("a"), DrawableId("c")),
AtlasTileId("t1") to listOf(DrawableId("b")),
),
model.drawableIdsByAtlasTile(),
"a drawable with no tile is absent, and the rest keep document order",
)
}
@Test
fun anEmptyAtlasReportsEmpty() {
assertTrue(PuppetAtlas.Empty.isEmpty)
assertTrue(PuppetAtlas(pages = listOf(AtlasPage(1, 1))).isEmpty.not(), "a page alone is still an atlas")
}
/**
* A tile's source binding is document data that rides through every tile edit: a placement change
* copies the tile and must keep the binding, and a model with no linked art has no sources at all.
*/
@Test
fun aTileKeepsItsSourceBindingThroughAPlacementChange() {
val source = SourceLayerRef(ArtSourceId("art-0"), layerKey = "lyid:7", stableKey = true)
val tile = unpackedTile("t0").copy(source = source)
val placed = tile.copy(placement = AtlasPlacement(0, 1f, 2f, scaleX = 1f, scaleY = 1f, rotationDegrees = 0f))
assertEquals(source, placed.source, "the binding is what the tile IS, not where it packs")
assertNull(unpackedTile("t1").source, "a tile with no retained binding has none")
assertTrue(modelOf(PuppetAtlas.Empty).sources.isEmpty(), "a document with no linked art lists no sources")
}
}
@@ -0,0 +1,111 @@
package org.umamo.runtime.model
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
/**
* Unit-tests the per-drawable service queries in PuppetModelQueries: the pickable sets exclude
* hidden and mesh-less drawables, the part-name lookup follows the org tree, and the atlas key
* resolves a duplicate to its texture source.
*/
class PuppetModelQueriesTest {
private val meshedId = DrawableId("meshed")
private val hiddenId = DrawableId("hidden")
private val meshlessId = DrawableId("meshless")
private val duplicateId = DrawableId("duplicate")
/**
* A quad mesh so pickable queries have geometry to report.
*
* @return DrawableMesh The mesh.
*/
private fun quadMesh(): DrawableMesh =
DrawableMesh(
positions = floatArrayOf(0f, 0f, 10f, 0f, 0f, 10f, 10f, 10f),
uvs = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f),
indices = intArrayOf(0, 1, 2, 1, 3, 2),
)
/**
* A minimal drawable for query tests.
*
* @param DrawableId id The drawable's id.
* @param DrawableMesh? mesh Its mesh, or null for a geometry-less drawable.
* @param Boolean isVisible Its own eyeball flag.
* @param DrawableId? textureSource Its texture source when it is a duplicate.
* @return Drawable The drawable.
*/
private fun drawable(id: DrawableId, mesh: DrawableMesh?, isVisible: Boolean = true, textureSource: DrawableId? = null): Drawable =
Drawable(
id = id,
name = id.raw,
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = mesh,
geometryGrid = null,
isVisible = isVisible,
textureSourceId = textureSource,
)
/**
* A model with one part ("Face") owning the meshed drawable, plus hidden / mesh-less / duplicate
* drawables at the root.
*
* @return PuppetModel The fixture model.
*/
private fun model(): PuppetModel {
val facePart = Part(PartId("face"), "Face", children = listOf(OrgChild.Drawable(meshedId)))
return PuppetModel(
parameters = emptyList(),
parts = listOf(facePart),
deformers = emptyList(),
drawables =
listOf(
drawable(meshedId, quadMesh()),
drawable(hiddenId, quadMesh(), isVisible = false),
drawable(meshlessId, mesh = null),
drawable(duplicateId, quadMesh(), textureSource = meshedId),
),
rootChildren =
listOf(
OrgChild.Part(PartId("face")),
OrgChild.Drawable(hiddenId),
OrgChild.Drawable(meshlessId),
OrgChild.Drawable(duplicateId),
),
rootPartId = null,
)
}
@Test
fun pickableSetsExcludeHiddenAndMeshless() {
val model = model()
assertEquals(setOf(meshedId, duplicateId), model.pickableIndicesByDrawable().keys)
assertEquals(setOf(meshedId, duplicateId), model.pickableUvsByDrawable().keys)
}
@Test
fun pickableGeometryMatchesTheMesh() {
val model = model()
val mesh = quadMesh()
assertEquals(mesh.indices.toList(), model.pickableIndicesByDrawable().getValue(meshedId).toList())
assertEquals(mesh.uvs.toList(), model.pickableUvsByDrawable().getValue(meshedId).toList())
}
@Test
fun partNamesFollowTheOrgTree() {
val names = model().partNameByDrawable()
assertEquals("Face", names[meshedId])
// Root-level drawables have no owning part, so no label entry.
assertNull(names[hiddenId])
}
@Test
fun atlasKeyResolvesDuplicateToItsSource() {
val keys = model().atlasKeyByDrawable()
assertEquals(meshedId.raw, keys[duplicateId])
assertEquals(meshedId.raw, keys[meshedId])
}
}
@@ -0,0 +1,192 @@
package org.umamo.runtime.model
import kotlin.test.Test
import kotlin.test.assertEquals
/**
* Pins the strip diff: a restricted feature is reported only when the document actually uses it,
* latent state never counts, and a supporting target reports nothing.
*/
class RuntimeFeatureScanTest {
private val drawableId = DrawableId("drawable")
private val partId = PartId("part")
private val deformerId = DeformerId("deformer")
private val parameterId = ParameterId("Param")
private fun drawable(
blendMode: BlendMode = BlendMode.Normal,
alphaBlendMode: AlphaBlendMode = AlphaBlendMode.Over,
invertMask: Boolean = false,
multiplyColor: ColorRgb = ColorRgb.MultiplyIdentity,
blendShapes: List<BlendShapeBinding<MeshForm>> = emptyList(),
): Drawable =
Drawable(
id = drawableId,
name = drawableId.raw,
parentDeformerId = null,
blendMode = blendMode,
maskedBy = emptyList(),
mesh = null,
geometryGrid = null,
alphaBlendMode = alphaBlendMode,
invertMask = invertMask,
multiplyColor = multiplyColor,
blendShapes = blendShapes,
)
private fun model(
drawables: List<Drawable> = emptyList(),
parts: List<Part> = emptyList(),
deformers: List<Deformer> = emptyList(),
parameters: List<Parameter> = emptyList(),
): PuppetModel =
PuppetModel(
parameters = parameters,
parts = parts,
deformers = deformers,
drawables = drawables,
rootChildren = drawables.map { drawable -> OrgChild.Drawable(drawable.id) } + parts.map { part -> OrgChild.Part(part.id) },
rootPartId = null,
)
@Test
fun bareModelReportsNothingUnderAnyTarget() {
val bare = model()
RuntimeTarget.entries.forEach { target ->
assertEquals(emptySet(), bare.unsupportedFeaturesInUse(target), "bare model under $target")
}
}
@Test
fun supportingTargetsReportNothing() {
val kitchenSink =
model(
drawables = listOf(drawable(blendMode = BlendMode.Overlay, invertMask = true)),
parts = listOf(Part(partId, "part", children = emptyList(), groupMode = PartGroupMode.Isolated)),
)
assertEquals(emptySet(), kitchenSink.unsupportedFeaturesInUse(RuntimeTarget.NoTarget))
assertEquals(emptySet(), kitchenSink.unsupportedFeaturesInUse(RuntimeTarget.Cubism53))
}
@Test
fun isolatedPartReportsPartCompositeOnly() {
val isolated = model(parts = listOf(Part(partId, "part", children = emptyList(), groupMode = PartGroupMode.Isolated)))
assertEquals(setOf(RuntimeFeature.PartComposite), isolated.unsupportedFeaturesInUse(RuntimeTarget.Cubism50))
}
@Test
fun latentCompositeDoesNotCount() {
// A PassThrough part with stored composite settings is invisible to the runtime - not "in use".
val latent =
model(
parts =
listOf(
Part(
partId,
"part",
children = emptyList(),
groupMode = PartGroupMode.PassThrough,
composite = PartComposite(blendMode = BlendMode.Overlay, invertMask = true),
),
),
)
assertEquals(emptySet(), latent.unsupportedFeaturesInUse(RuntimeTarget.Cubism30))
}
@Test
fun extendedBlendModesCoverColorAndAlpha() {
val extendedColor = model(drawables = listOf(drawable(blendMode = BlendMode.Overlay)))
assertEquals(setOf(RuntimeFeature.ExtendedBlendModes), extendedColor.unsupportedFeaturesInUse(RuntimeTarget.Cubism50))
val extendedAlpha = model(drawables = listOf(drawable(alphaBlendMode = AlphaBlendMode.Atop)))
assertEquals(setOf(RuntimeFeature.ExtendedBlendModes), extendedAlpha.unsupportedFeaturesInUse(RuntimeTarget.Cubism50))
}
@Test
fun reversedMaskReportsBelowFourOh() {
val inverted = model(drawables = listOf(drawable(invertMask = true)))
assertEquals(setOf(RuntimeFeature.ReversedMask), inverted.unsupportedFeaturesInUse(RuntimeTarget.Cubism33))
assertEquals(emptySet(), inverted.unsupportedFeaturesInUse(RuntimeTarget.Cubism40))
}
@Test
fun multiplyColorStaticReportsBelowFourTwo() {
val tinted = model(drawables = listOf(drawable(multiplyColor = ColorRgb(0.5f, 0.5f, 0.5f))))
assertEquals(setOf(RuntimeFeature.MultiplyColor), tinted.unsupportedFeaturesInUse(RuntimeTarget.Cubism40))
assertEquals(emptySet(), tinted.unsupportedFeaturesInUse(RuntimeTarget.Cubism42))
}
@Test
fun quadWarpReportsBelowThreeThree() {
val quadWarp =
model(
deformers =
listOf(
Deformer.Warp(
id = deformerId,
name = "warp",
parent = null,
partId = null,
rows = 2,
columns = 2,
isQuadTransform = true,
geometryGrid = null,
),
),
)
assertEquals(setOf(RuntimeFeature.WarpQuadTransform), quadWarp.unsupportedFeaturesInUse(RuntimeTarget.Cubism30))
assertEquals(emptySet(), quadWarp.unsupportedFeaturesInUse(RuntimeTarget.Cubism33))
}
@Test
fun rotationBlendShapesReportBelowFiveOh() {
val binding = BlendShapeBinding<RotationForm>(parameterId, floatArrayOf(0f, 1f), 0, listOf(null, null))
val rotation =
model(
deformers =
listOf(
Deformer.Rotation(
id = deformerId,
name = "rotation",
parent = null,
partId = null,
baseAngle = 0f,
geometryGrid = null,
blendShapes = listOf(binding),
),
),
)
assertEquals(setOf(RuntimeFeature.ExtendedBlendShapes), rotation.unsupportedFeaturesInUse(RuntimeTarget.Cubism42))
assertEquals(emptySet(), rotation.unsupportedFeaturesInUse(RuntimeTarget.Cubism50))
}
@Test
fun blendShapeParametersReportBelowFourTwo() {
val blendShapeParameter = model(parameters = listOf(Parameter(parameterId, "Param", 0f, 1f, 0f, ParameterKind.BLEND_SHAPE)))
assertEquals(
setOf(RuntimeFeature.BlendShapeParameters),
blendShapeParameter.unsupportedFeaturesInUse(RuntimeTarget.Cubism40),
)
assertEquals(emptySet(), blendShapeParameter.unsupportedFeaturesInUse(RuntimeTarget.Cubism42))
}
@Test
fun partMasksAreNotAFeature() {
// Part-typed composite masks decompose to drawable ids at the CMO3/MOC3 boundary, so their use
// is never reported under any target - only the offscreen composite itself is a 5.3 feature.
val partMasked =
model(
parts =
listOf(
Part(
partId,
"part",
children = emptyList(),
groupMode = PartGroupMode.Isolated,
composite = PartComposite(maskedByParts = listOf(partId)),
),
),
)
assertEquals(emptySet(), partMasked.unsupportedFeaturesInUse(RuntimeTarget.Cubism53))
assertEquals(setOf(RuntimeFeature.PartComposite), partMasked.unsupportedFeaturesInUse(RuntimeTarget.Cubism50))
}
}
@@ -0,0 +1,77 @@
package org.umamo.runtime.model
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Pins the runtime repository's capability matrix to the official Cubism Editor's "Model target
* version selection" dialog, both sides of every version boundary. (The format-version mapping
* each target persists as is pinned in :interop's RuntimeTargetMappingTest.)
*/
class RuntimeTargetTest {
@Test
fun featureBoundariesMatchTheOfficialDialog() {
// New warp deformer method: SDK3.3+.
assertTrue(!RuntimeTarget.Cubism30.supports(RuntimeFeature.WarpQuadTransform))
assertTrue(RuntimeTarget.Cubism33.supports(RuntimeFeature.WarpQuadTransform))
// Reversed Mask: SDK4.0+.
assertTrue(!RuntimeTarget.Cubism33.supports(RuntimeFeature.ReversedMask))
assertTrue(RuntimeTarget.Cubism40.supports(RuntimeFeature.ReversedMask))
// Blend Shape (art mesh + warp), blend-shape parameters, multiply color, screen color: SDK4.2+.
listOf(
RuntimeFeature.MeshWarpBlendShapes,
RuntimeFeature.BlendShapeParameters,
RuntimeFeature.MultiplyColor,
RuntimeFeature.ScreenColor,
).forEach { feature ->
assertTrue(!RuntimeTarget.Cubism40.supports(feature), "$feature is 4.2+, not 4.0")
assertTrue(RuntimeTarget.Cubism42.supports(feature), "$feature is supported at 4.2")
}
// Blend Shape (part / rotation / glue / scalar) and motion-sync: SDK5.0+.
listOf(RuntimeFeature.ExtendedBlendShapes, RuntimeFeature.MotionSync).forEach { feature ->
assertTrue(!RuntimeTarget.Cubism42.supports(feature), "$feature is 5.0+, not 4.2")
assertTrue(RuntimeTarget.Cubism50.supports(feature), "$feature is supported at 5.0")
}
// Blend mode, offscreen drawing, parameter repeat: SDK5.3+.
listOf(RuntimeFeature.ExtendedBlendModes, RuntimeFeature.PartComposite, RuntimeFeature.ParameterRepeat)
.forEach { feature ->
assertTrue(!RuntimeTarget.Cubism50.supports(feature), "$feature is 5.3+, not 5.0")
assertTrue(RuntimeTarget.Cubism53.supports(feature), "$feature is supported at 5.3")
}
// ArtPath is "Latest Cubism only": no Cubism ceiling allows it.
assertTrue(!RuntimeTarget.Cubism53.supports(RuntimeFeature.ArtPath), "ArtPath is beyond every Cubism target")
assertTrue(RuntimeTarget.NoTarget.supports(RuntimeFeature.ArtPath), "ArtPath is authorable with no target")
}
@Test
fun restrictedListsDeriveFromTheMatrix() {
assertEquals(emptyList(), RuntimeTarget.NoTarget.restrictedFeatures(), "NoTarget restricts nothing")
assertEquals(
RuntimeTarget.Cubism50.restrictedFeatures(),
RuntimeTarget.Ayagami.restrictedFeatures(),
"Ayagami is effectively Cubism 5.0 at present",
)
assertEquals(listOf(RuntimeFeature.ArtPath), RuntimeTarget.Cubism53.restrictedFeatures())
assertEquals(
RuntimeFeature.entries.toList(),
RuntimeTarget.Cubism30.restrictedFeatures(),
"every feature postdates Cubism 3.0",
)
}
@Test
fun displayNamesAreDistinctAndNonBlank() {
val names = RuntimeTarget.entries.map { target -> target.displayName }
assertEquals(names.size, names.toSet().size, "display names are distinct")
assertTrue(names.none { name -> name.isBlank() }, "display names are non-blank")
}
@Test
fun cubismLevelTextTracksTheGatingLevel() {
assertNull(RuntimeTarget.NoTarget.cubismLevelText(), "no ceiling, no text")
assertEquals("5.0", RuntimeTarget.Ayagami.cubismLevelText(), "the Ayagami label's level feed")
assertEquals("3.3", RuntimeTarget.Cubism33.cubismLevelText())
}
}
@@ -0,0 +1,59 @@
package org.umamo.runtime.model
import kotlin.test.Test
import kotlin.test.assertEquals
/**
* Unit-tests [visibleDrawableIds]: the Parts-panel eyeball cascades down the org tree, so a drawable is
* shown only when its own flag and every ancestor part are visible. Corpus-free - a hand-built tree
* exercises own-hidden, direct-parent-hidden, ancestor-hidden, and root-level (no part) cases.
*/
class VisibilityCascadeTest {
private fun drawable(id: String, isVisible: Boolean): Drawable =
Drawable(
id = DrawableId(id),
name = id,
parentDeformerId = null,
blendMode = BlendMode.Normal,
maskedBy = emptyList(),
mesh = null,
geometryGrid = null,
isVisible = isVisible,
)
@Test
fun cascadesEyeballThroughAncestorParts() {
val parts =
listOf(
Part(PartId("root"), "Root", listOf(OrgChild.Part(PartId("hidden")), OrgChild.Part(PartId("shown"))), isVisible = true),
Part(
PartId("hidden"),
"[Guide Image]",
listOf(OrgChild.Part(PartId("grandchild")), OrgChild.Drawable(DrawableId("inHidden"))),
isVisible = false,
),
Part(PartId("grandchild"), "Under Hidden", listOf(OrgChild.Drawable(DrawableId("underHidden"))), isVisible = true),
Part(
PartId("shown"),
"Visible Folder",
listOf(OrgChild.Drawable(DrawableId("inShown")), OrgChild.Drawable(DrawableId("ownHidden"))),
isVisible = true,
),
)
val drawables =
listOf(
drawable("inHidden", isVisible = true), // parent hidden → excluded
drawable("underHidden", isVisible = true), // grandparent hidden → excluded
drawable("inShown", isVisible = true), // all visible → shown
drawable("ownHidden", isVisible = false), // own eyeball off → excluded
drawable("rootLevel", isVisible = true), // no part → shown
)
// Top level: the "root" folder plus a loose root-level mesh.
val rootChildren = listOf(OrgChild.Part(PartId("root")), OrgChild.Drawable(DrawableId("rootLevel")))
val model = PuppetModel(emptyList(), parts, emptyList(), drawables, rootChildren, rootPartId = PartId("root"))
val shown = model.visibleDrawableIds()
assertEquals(setOf(DrawableId("inShown"), DrawableId("rootLevel")), shown)
}
}