Improved Bone Mapping modal

This commit is contained in:
Bruno Fargnoli 2026-07-15 10:55:42 +02:00
parent 22b8fce11e
commit e427092a4d
13 changed files with 292 additions and 7 deletions

BIN
resources/rigs/rig-bird.glb Normal file

Binary file not shown.

Binary file not shown.

BIN
resources/rigs/rig-fox.glb Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -3,12 +3,20 @@
// bones (target, right column) so clips can be retargeted. Mirrors the
// mesh2motion mapping UI: drag a source bone onto a target row, or click a
// source then a target. Auto-Map fills the mapping heuristically.
//
// To make it obvious *where* each bone lives (names alone rarely tell you), the
// far-left column shows two live 3D skeletons — the reference (source) on top
// and the user's mesh (target) below. Click a bone in a view to select it (same
// as clicking its row), and hovering a list row flashes that bone in 3D.
import { useEffect, useMemo, useState } from 'react'
import BoneSkeletonView from './BoneSkeletonView'
export default function BoneMappingModal({
referenceLabel,
sourceBones,
targetBones,
sourceSkeleton,
targetSkeleton,
initialMapping,
onAutoMap,
onSave,
@ -18,6 +26,9 @@ export default function BoneMappingModal({
const [sourceFilter, setSourceFilter] = useState('')
const [targetFilter, setTargetFilter] = useState('')
const [pickedSource, setPickedSource] = useState(null)
const [pickedTarget, setPickedTarget] = useState(null)
const [hoverSource, setHoverSource] = useState(null)
const [hoverTarget, setHoverTarget] = useState(null)
const [dragSource, setDragSource] = useState(null)
// Close on Escape.
@ -28,6 +39,7 @@ export default function BoneMappingModal({
}, [onClose])
const mappedSources = useMemo(() => new Set(Object.values(mapping)), [mapping])
const mappedTargets = useMemo(() => new Set(Object.keys(mapping)), [mapping])
const mappedCount = Object.keys(mapping).length
const filteredSources = useMemo(
@ -59,6 +71,7 @@ export default function BoneMappingModal({
}
const handleTargetClick = targetName => {
setPickedTarget(targetName)
if (pickedSource) assign(targetName, pickedSource)
}
@ -67,6 +80,13 @@ export default function BoneMappingModal({
setDragSource(null)
}
const toggleSource = name => setPickedSource(prev => (prev === name ? null : name))
// Bones to highlight in each 3D view: what the user is hovering in the list
// takes priority (so a hover flashes its location), else the current pick.
const sourceHighlight = hoverSource || pickedSource
const targetHighlight = hoverTarget || pickedTarget
return (
<div className="mesh-editor-bonemap__overlay" onClick={onClose}>
<div className="mesh-editor-bonemap" onClick={e => e.stopPropagation()}>
@ -74,8 +94,9 @@ export default function BoneMappingModal({
<div>
<h2 className="mesh-editor-bonemap__title">Map bones — {referenceLabel}</h2>
<p className="mesh-editor-bonemap__subtitle">
Assign each animation (source) bone to a bone on your mesh (target). Drag a source
bone onto a target, or click a source then a target. {mappedCount} mapped.
Assign each animation (source) bone to a bone on your mesh (target). Rotate the 3D
views and click a bone to select it, drag a source bone onto a target, or click a
source then a target. {mappedCount} mapped.
</p>
</div>
<button type="button" className="mesh-editor-bonemap__close" onClick={onClose} title="Close">
@ -84,6 +105,24 @@ export default function BoneMappingModal({
</div>
<div className="mesh-editor-bonemap__body">
{/* 3D SKELETON VIEWS */}
<div className="mesh-editor-bonemap__views">
<BoneSkeletonView
title={`Source · ${referenceLabel}`}
skeleton={sourceSkeleton}
selectedBone={sourceHighlight}
mappedBones={mappedSources}
onSelectBone={toggleSource}
/>
<BoneSkeletonView
title="Target · your mesh"
skeleton={targetSkeleton}
selectedBone={targetHighlight}
mappedBones={mappedTargets}
onSelectBone={handleTargetClick}
/>
</div>
{/* SOURCE column */}
<div className="mesh-editor-bonemap__col">
<div className="mesh-editor-bonemap__col-head">
@ -106,7 +145,9 @@ export default function BoneMappingModal({
draggable
onDragStart={() => setDragSource(name)}
onDragEnd={() => setDragSource(null)}
onClick={() => setPickedSource(pickedSource === name ? null : name)}
onClick={() => toggleSource(name)}
onMouseEnter={() => setHoverSource(name)}
onMouseLeave={() => setHoverSource(null)}
title={used ? `${name} (mapped)` : name}
>
<span className="material-symbols-outlined mesh-editor-bonemap__grip">drag_indicator</span>
@ -149,6 +190,8 @@ export default function BoneMappingModal({
key={name}
className={`mesh-editor-bonemap__target ${src ? 'mesh-editor-bonemap__target--mapped' : ''} ${pickedSource ? 'mesh-editor-bonemap__target--droppable' : ''}`}
onClick={() => handleTargetClick(name)}
onMouseEnter={() => setHoverTarget(name)}
onMouseLeave={() => setHoverTarget(null)}
onDragOver={e => e.preventDefault()}
onDrop={() => handleDrop(name)}
>

View file

@ -0,0 +1,134 @@
// A small, self-contained 3D skeleton viewer used inside the Bone-mapping modal
// so you can rotate a rig and click its bones to see where each one is (helpful
// when a bone's name alone doesn't tell you which limb it drives).
//
// IMPORTANT: it renders from the PLAIN data returned by
// `extractSkeletonFromObject` (joints/segments/names), NOT the live THREE scene.
// The reference/target scenes are shared objects also used for retargeting and
// preview — dropping them into another <Canvas> via <primitive> would reparent
// them and break those flows. Rebuilding the bones as our own geometry (like
// SkeletonOverlay does) keeps the source objects untouched.
import { useMemo } from 'react'
import { Canvas } from '@react-three/fiber'
import { OrbitControls, Html, PerspectiveCamera } from '@react-three/drei'
import * as THREE from 'three'
const BONE_COLOR = '#6c8cff'
const JOINT_COLOR = '#c9d4ff'
const MAPPED_COLOR = '#5ad19a'
const SELECTED_COLOR = '#8ff5ff'
// Bounds (center + radius) of the skeleton's joints, for camera framing.
function computeBounds(joints) {
const box = new THREE.Box3()
const p = new THREE.Vector3()
for (let i = 0; i < joints.length; i += 3) {
box.expandByPoint(p.set(joints[i], joints[i + 1], joints[i + 2]))
}
if (box.isEmpty()) return { center: [0, 0, 0], radius: 1 }
const center = box.getCenter(new THREE.Vector3())
const radius = Math.max(box.getSize(p).length() * 0.5, 1e-3)
return { center: [center.x, center.y, center.z], radius }
}
function Scene({ skeleton, selectedBone, mappedBones, onSelectBone }) {
const { center, radius } = useMemo(() => computeBounds(skeleton.joints), [skeleton])
const lineGeometry = useMemo(() => {
if (!skeleton.segments?.length) return null
const geo = new THREE.BufferGeometry()
geo.setAttribute('position', new THREE.BufferAttribute(skeleton.segments, 3))
return geo
}, [skeleton])
const jointRadius = Math.max(radius * 0.025, 1e-4)
const hitRadius = Math.max(radius * 0.06, jointRadius * 2)
// Camera framed from the front, a little above center.
const dist = radius * 2.6
const camPos = [center[0], center[1] + radius * 0.15, center[2] + dist]
const selectedIndex = selectedBone == null
? -1
: skeleton.names.findIndex(n => n === selectedBone)
return (
<>
<PerspectiveCamera makeDefault position={camPos} fov={40} near={radius * 0.01} far={radius * 40} />
<OrbitControls target={center} enablePan={false} makeDefault />
<ambientLight intensity={0.9} />
{lineGeometry && (
<lineSegments geometry={lineGeometry}>
<lineBasicMaterial color={BONE_COLOR} transparent opacity={0.85} />
</lineSegments>
)}
{skeleton.names.map((name, i) => {
const x = skeleton.joints[i * 3]
const y = skeleton.joints[i * 3 + 1]
const z = skeleton.joints[i * 3 + 2]
const isSelected = i === selectedIndex
const isMapped = mappedBones?.has(name)
const color = isSelected ? SELECTED_COLOR : isMapped ? MAPPED_COLOR : JOINT_COLOR
return (
<group key={`${name}_${i}`} position={[x, y, z]}>
{/* Visible joint dot */}
<mesh>
<sphereGeometry args={[isSelected ? jointRadius * 1.7 : jointRadius, 12, 12]} />
<meshBasicMaterial color={color} />
</mesh>
{/* Larger invisible hit target so small joints are easy to click */}
<mesh
onClick={e => { e.stopPropagation(); onSelectBone(name) }}
onPointerOver={e => { e.stopPropagation(); document.body.style.cursor = 'pointer' }}
onPointerOut={() => { document.body.style.cursor = '' }}
>
<sphereGeometry args={[hitRadius, 8, 8]} />
<meshBasicMaterial transparent opacity={0} depthWrite={false} />
</mesh>
{isSelected && (
<Html center zIndexRange={[20, 0]} className="mesh-editor-bonemap-view__label-anchor">
<div className="mesh-editor-bonemap-view__label">{name}</div>
</Html>
)}
</group>
)
})}
</>
)
}
export default function BoneSkeletonView({
title,
skeleton,
selectedBone = null,
mappedBones = null,
onSelectBone,
}) {
const hasBones = skeleton && skeleton.names?.length
return (
<div className="mesh-editor-bonemap-view">
<div className="mesh-editor-bonemap-view__head">
<span className="mesh-editor-bonemap-view__title">{title}</span>
<span className="mesh-editor-bonemap-view__selected">
{selectedBone || 'Click / hover a bone'}
</span>
</div>
<div className="mesh-editor-bonemap-view__canvas">
{hasBones ? (
<Canvas dpr={[1, 2]} gl={{ antialias: true, alpha: true }} frameloop="demand">
<Scene
skeleton={skeleton}
selectedBone={selectedBone}
mappedBones={mappedBones}
onSelectBone={onSelectBone}
/>
</Canvas>
) : (
<div className="mesh-editor-bonemap-view__empty">No skeleton</div>
)}
</div>
</div>
)
}

View file

@ -817,8 +817,8 @@
.mesh-editor-bonemap {
display: flex;
flex-direction: column;
width: min(920px, 96vw);
height: min(720px, 90vh);
width: min(1240px, 96vw);
height: min(760px, 92vh);
background: var(--surface-container, #1e1e22);
border: 1px solid var(--outline-variant, #2a2a30);
border-radius: 14px;
@ -866,11 +866,87 @@
flex: 1;
min-height: 0;
display: grid;
grid-template-columns: 1fr auto 1fr;
grid-template-columns: minmax(240px, 300px) 1fr auto 1fr;
gap: 0.75rem;
padding: 1rem 1.25rem;
}
/* Left column: two stacked 3D skeleton viewers (source over target). */
.mesh-editor-bonemap__views {
display: flex;
flex-direction: column;
gap: 0.6rem;
min-height: 0;
}
.mesh-editor-bonemap-view {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.mesh-editor-bonemap-view__head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 0.5rem;
}
.mesh-editor-bonemap-view__title {
font-weight: 600;
font-size: 0.8rem;
}
.mesh-editor-bonemap-view__selected {
font-size: 0.72rem;
color: #8ff5ff;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 55%;
}
.mesh-editor-bonemap-view__canvas {
flex: 1;
min-height: 0;
position: relative;
border: 1px solid var(--outline-variant, #2a2a30);
border-radius: 10px;
background:
radial-gradient(120% 120% at 50% 0%, rgba(108, 140, 255, 0.08), transparent 60%),
var(--surface, #141418);
overflow: hidden;
}
.mesh-editor-bonemap-view__empty {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
color: var(--on-surface-variant);
font-size: 0.8rem;
}
.mesh-editor-bonemap-view__label-anchor {
pointer-events: none;
}
.mesh-editor-bonemap-view__label {
transform: translateY(-1.4rem);
padding: 0.15rem 0.45rem;
border-radius: 6px;
background: rgba(12, 14, 20, 0.9);
border: 1px solid rgba(143, 245, 255, 0.5);
color: #eaf7ff;
font-size: 0.72rem;
font-weight: 600;
white-space: nowrap;
pointer-events: none;
}
.mesh-editor-bonemap__col {
display: flex;
flex-direction: column;

View file

@ -155,7 +155,7 @@ import SkeletonOverlay from '../components/meshEditor/SkeletonOverlay'
import SkeletonPanel from '../components/meshEditor/SkeletonPanel'
import AnimatedMeshPreview from '../components/meshEditor/AnimatedMeshPreview'
import BoneMappingModal from '../components/meshEditor/BoneMappingModal'
import { loadReferenceScene, loadTargetScene, autoMapBones, retargetAnimationClip, findUpperArmTargets, getReference } from '../utils/animationLibrary'
import { loadReferenceScene, loadReferenceRigScene, loadTargetScene, autoMapBones, retargetAnimationClip, findUpperArmTargets, getReference } from '../utils/animationLibrary'
import OptimizeToolsPanel from '../components/meshEditor/OptimizeToolsPanel'
import { autoUv as runAutoUvService, autoRetopo as runAutoRetopoService, optimizeMesh as runOptimizeService, repairMesh as runRepairService, autoRig as runAutoRigService, ensureDesktopService } from '../utils/meshTools'
@ -460,6 +460,7 @@ export default function MeshEditorPage() {
const [animClips, setAnimClips] = useState([]) // [{ name }] for the selected reference
const [selectedAnimation, setSelectedAnimation] = useState(null)
const [showBoneMapping, setShowBoneMapping] = useState(false)
const [boneMapSkeletons, setBoneMapSkeletons] = useState(null) // { source, target } skeleton data for the mapping 3D views
const [animLoading, setAnimLoading] = useState(false)
const [animError, setAnimError] = useState(null)
const [animRetargeting, setAnimRetargeting] = useState(null) // clip name currently retargeting
@ -4200,6 +4201,7 @@ export default function MeshEditorPage() {
const handleSelectAnimReference = useCallback(async (referenceId) => {
setAnimReferenceId(referenceId)
setAnimMapping(null)
setBoneMapSkeletons(null)
setAnimClips([])
setSelectedAnimation(null)
setAnimPreview(null)
@ -4237,6 +4239,22 @@ export default function MeshEditorPage() {
}
setAnimLoading(false)
}
// Build the plain skeleton data (joints/segments/names) that feeds the modal's
// two 3D bone views. Source prefers the clean skeleton-only rig GLB (same bone
// names as the animation GLB, no skinned mesh); falls back to the loaded
// reference scene. Target comes from the user's loaded rigged scene.
let source = null
try {
const rig = await loadReferenceRigScene(animReferenceId)
source = extractSkeletonFromObject(rig.scene)
} catch (err) {
console.warn('Rig GLB unavailable, using the animation scene skeleton:', err)
}
if (!source && animSourceRef.current?.scene) source = extractSkeletonFromObject(animSourceRef.current.scene)
const target = animTargetRef.current?.scene ? extractSkeletonFromObject(animTargetRef.current.scene) : null
setBoneMapSkeletons({ source, target })
setShowBoneMapping(true)
}, [animReferenceId, ensureAnimTargetScene])
@ -7349,6 +7367,8 @@ export default function MeshEditorPage() {
referenceLabel={getReference(animReferenceId)?.label || 'Reference'}
sourceBones={animSourceRef.current.boneNames}
targetBones={animTargetRef.current.boneNames}
sourceSkeleton={boneMapSkeletons?.source}
targetSkeleton={boneMapSkeletons?.target}
initialMapping={animMapping}
onAutoMap={handleAutoMapBones}
onSave={handleSaveBoneMapping}

View file

@ -103,6 +103,18 @@ export async function loadReferenceScene(referenceId) {
}
}
// Load a reference species' clean skeleton-only rig (resources/rigs/rig-<dir>.glb)
// for the bone-mapping 3D preview. These share the exact bone names of the
// species' animation GLB but carry no skinned mesh, so they render as a tidy
// armature. Returns { scene }; callers extract the skeleton from it.
export async function loadReferenceRigScene(referenceId) {
const ref = getReference(referenceId)
if (!ref) throw new Error(`Unknown animation reference: ${referenceId}`)
const gltf = await loadGlbFromUrl(resourceUrl(`rigs/rig-${ref.dir}.glb`))
gltf.scene.updateMatrixWorld(true)
return { scene: gltf.scene }
}
// Load the user's rigged mesh as an animatable SkinnedMesh. Prefers the freshly
// generated rig blob; falls back to (re)loading the mesh's source URL.
export async function loadTargetScene({ riggedBuffer, modelUrl }) {