Skip to content

Import a 3D Model and automatically assign and export animations

TypeScript

Add remix feature to site to combine a couple animations

Scott Petrovic4895b508372e
diff --git a/src/Mesh2MotionEngine.ts b/src/Mesh2MotionEngine.ts
index c14c257..a37e097 100644
--- a/src/Mesh2MotionEngine.ts
+++ b/src/Mesh2MotionEngine.ts
@@ -77,6 +77,10 @@ export class Mesh2MotionEngine {
public transform_space_type: TransformSpace = TransformSpace.Global
private readonly clock = new THREE.Clock()
+ private readonly frame_listeners: Array<(delta_time: number) => void> = []
+
+ // pages that animate their own model (like the Composer) provide it here, so shared controls like wireframe find it
+ private active_skinned_meshes_provider: (() => THREE.SkinnedMesh[]) | null = null
private readonly scene_environment: SceneEnvironmentManager
private readonly eventListeners: EventListeners
private readonly camera_shake: CameraShake
@@ -177,6 +181,28 @@ export class Mesh2MotionEngine {
this.scene_environment.set_fog_enabled(enabled)
}
+ /**
+ * Registers a callback that runs every frame before the scene renders.
+ * Pages that drive their own animation (like the Composer) use this instead of a separate render loop.
+ */
+ public add_frame_listener (listener: (delta_time: number) => void): void {
+ this.frame_listeners.push(listener)
+ }
+
+ public set_active_skinned_meshes_provider (provider: () => THREE.SkinnedMesh[]): void {
+ this.active_skinned_meshes_provider = provider
+ }
+
+ /**
+ * Skinned meshes currently shown and animated in the viewport.
+ */
+ public active_skinned_meshes (): THREE.SkinnedMesh[] {
+ if (this.active_skinned_meshes_provider !== null) {
+ return this.active_skinned_meshes_provider()
+ }
+ return this.animations_listing_step.active_skinned_meshes()
+ }
+
public enable_orbit_controls (enabled: boolean): void {
this.scene_environment.enable_orbit_controls(enabled)
}
@@ -480,6 +506,8 @@ export class Mesh2MotionEngine {
this.animations_listing_step.frame_change(delta_time)
}
+ this.frame_listeners.forEach((listener) => { listener(delta_time) })
+
this.renderer.render(this.scene, this.camera)
// view helper
diff --git a/src/composer/ComposerClipBuilder.test.ts b/src/composer/ComposerClipBuilder.test.ts
new file mode 100644
index 0000000..9697eaf
--- /dev/null
+++ b/src/composer/ComposerClipBuilder.test.ts
@@ -0,0 +1,211 @@
+import { describe, it, expect } from 'vitest'
+import {
+ AnimationClip, Bone, Euler, type KeyframeTrack, NumberKeyframeTrack, Quaternion, QuaternionKeyframeTrack, Skeleton, VectorKeyframeTrack
+} from 'three'
+import { ComposerClipBuilder } from './ComposerClipBuilder'
+
+const fps = 10
+
+/**
+ * Small version of the human rig: root > pelvis > (spine_01 > upperarm_l), (thigh_l > calf_l)
+ */
+function make_skeleton (): Skeleton {
+ const names = ['root', 'pelvis', 'spine_01', 'upperarm_l', 'thigh_l', 'calf_l']
+ const bones: Record<string, Bone> = {}
+ names.forEach((name) => {
+ bones[name] = new Bone()
+ bones[name].name = name
+ })
+
+ bones.root.add(bones.pelvis)
+ bones.pelvis.add(bones.spine_01, bones.thigh_l)
+ bones.spine_01.add(bones.upperarm_l)
+ bones.thigh_l.add(bones.calf_l)
+
+ return new Skeleton(names.map(name => bones[name]))
+}
+
+const upper_body_bone_names = ComposerClipBuilder.upper_body_bone_names(make_skeleton(), 'spine_01')
+
+// rotation tracks that hold one constant number on every bone, so it is easy to tell which clip a track came from
+function constant_rotation_tracks (bone_names: string[], marker: number, duration: number): QuaternionKeyframeTrack[] {
+ return bone_names.map(bone_name =>
+ new QuaternionKeyframeTrack(`${bone_name}.quaternion`, [0, duration], [marker, 0, 0, 1, marker, 0, 0, 1])
+ )
+}
+
+function find_track (clip: AnimationClip, name: string): KeyframeTrack {
+ const track = clip.tracks.find(t => t.name === name)
+ if (track === undefined) {
+ throw new Error(`Track ${name} not found`)
+ }
+ return track
+}
+
+function value_at_frame (track: KeyframeTrack, frame: number): number[] {
+ const size = track.getValueSize()
+ return Array.from(track.values.slice(frame * size, frame * size + size))
+}
+
+describe('ComposerClipBuilder.upper_body_bone_names', () => {
+ it('includes the upper body root and everything below it', () => {
+ expect([...upper_body_bone_names].sort()).toEqual(['spine_01', 'upperarm_l'])
+ })
+
+ it('is empty when the bone is missing', () => {
+ expect(ComposerClipBuilder.upper_body_bone_names(make_skeleton(), 'chest').size).toBe(0)
+ })
+})
+
+describe('ComposerClipBuilder.compose_clip', () => {
+ const all_bones = ['root', 'pelvis', 'spine_01', 'upperarm_l', 'thigh_l', 'calf_l']
+
+ it('takes upper bones from the upper clip and every other bone from the lower clip', () => {
+ const upper_clip = new AnimationClip('wave', 1, constant_rotation_tracks(all_bones, 0.1, 1))
+ const lower_clip = new AnimationClip('walk', 1, constant_rotation_tracks(all_bones, 0.9, 1))
+
+ const clip = ComposerClipBuilder.compose_clip({ upper_clip, lower_clip, upper_body_bone_names, fps, name: 'combo' })
+
+ expect(clip.tracks).toHaveLength(all_bones.length)
+ expect(value_at_frame(find_track(clip, 'spine_01.quaternion'), 0)[0]).toBeCloseTo(0.1)
+ expect(value_at_frame(find_track(clip, 'upperarm_l.quaternion'), 0)[0]).toBeCloseTo(0.1)
+ expect(value_at_frame(find_track(clip, 'pelvis.quaternion'), 0)[0]).toBeCloseTo(0.9)
+ expect(value_at_frame(find_track(clip, 'calf_l.quaternion'), 0)[0]).toBeCloseTo(0.9)
+ expect(clip.name).toBe('combo')
+ })
+
+ it('keeps root motion and hip height from the lower clip only', () => {
+ const upper_clip = new AnimationClip('wave', 1, [
+ new VectorKeyframeTrack('pelvis.position', [0, 1], [0, 5, 0, 0, 5, 0])
+ ])
+ const lower_clip = new AnimationClip('walk', 1, [
+ new VectorKeyframeTrack('root.position', [0, 1], [0, 0, 0, 0, 0, 2]),
+ new VectorKeyframeTrack('pelvis.position', [0, 1], [0, 1, 0, 0, 1, 0])
+ ])
+
+ const clip = ComposerClipBuilder.compose_clip({ upper_clip, lower_clip, upper_body_bone_names, fps, name: 'combo' })
+
+ expect(clip.tracks.map(t => t.name).sort()).toEqual(['pelvis.position', 'root.position'])
+ expect(value_at_frame(find_track(clip, 'pelvis.position'), 0)).toEqual([0, 1, 0])
+ expect(value_at_frame(find_track(clip, 'root.position'), 10)[2]).toBeCloseTo(2)
+ })
+
+ it('stretches a shorter upper clip to the length of the lower clip', () => {
+ // upper clip rises from 0 to 1 over half a second
+ const upper_clip = new AnimationClip('wave', 0.5, [
+ new NumberKeyframeTrack('spine_01.morph', [0, 0.5], [0, 1])
+ ])
+ const lower_clip = new AnimationClip('walk', 2, constant_rotation_tracks(['pelvis'], 0, 2))
+
+ const clip = ComposerClipBuilder.compose_clip({ upper_clip, lower_clip, upper_body_bone_names, fps, name: 'combo' })
+ const upper_track = find_track(clip, 'spine_01.morph')
+
+ expect(clip.duration).toBe(2)
+ expect(upper_track.times).toHaveLength(21) // 2 seconds at 10 fps, including the last frame
+ expect(value_at_frame(upper_track, 5)[0]).toBeCloseTo(0.25) // a quarter of the way through
+ expect(value_at_frame(upper_track, 10)[0]).toBeCloseTo(0.5) // halfway
+ expect(value_at_frame(upper_track, 20)[0]).toBeCloseTo(1) // ends together with the lower clip
+ })
+
+ it('stretches a shorter lower clip to the length of the upper clip', () => {
+ const upper_clip = new AnimationClip('wave', 3, constant_rotation_tracks(['spine_01'], 0.1, 3))
+ // lower clip moves the root from 0 to 2 over one second
+ const lower_clip = new AnimationClip('walk', 1, [
+ new VectorKeyframeTrack('root.position', [0, 1], [0, 0, 0, 0, 0, 2])
+ ])
+
+ const clip = ComposerClipBuilder.compose_clip({ upper_clip, lower_clip, upper_body_bone_names, fps, name: 'combo' })
+ const root_track = find_track(clip, 'root.position')
+
+ expect(clip.duration).toBe(3)
+ expect(root_track.times[root_track.times.length - 1]).toBeCloseTo(3)
+ expect(value_at_frame(root_track, 15)[2]).toBeCloseTo(1) // halfway
+ expect(value_at_frame(root_track, 30)[2]).toBeCloseTo(2) // ends together with the upper clip
+ })
+
+ it('uses the upper clip length when the lower clip is a single pose', () => {
+ const upper_clip = new AnimationClip('wave', 1.5, constant_rotation_tracks(['spine_01'], 0.1, 1.5))
+ const lower_clip = new AnimationClip('pose', 0, [
+ new QuaternionKeyframeTrack('pelvis.quaternion', [0], [0.9, 0, 0, 1])
+ ])
+
+ const clip = ComposerClipBuilder.compose_clip({ upper_clip, lower_clip, upper_body_bone_names, fps, name: 'combo' })
+
+ expect(clip.duration).toBe(1.5)
+ expect(value_at_frame(find_track(clip, 'pelvis.quaternion'), 15)[0]).toBeCloseTo(0.9)
+ })
+
+ it('does not change the source clips', () => {
+ const upper_clip = new AnimationClip('wave', 1, constant_rotation_tracks(['spine_01'], 0.1, 1))
+ const lower_clip = new AnimationClip('walk', 1, constant_rotation_tracks(['pelvis'], 0.9, 1))
+
+ ComposerClipBuilder.compose_clip({ upper_clip, lower_clip, upper_body_bone_names, fps, name: 'combo' })
+
+ expect(Array.from(upper_clip.tracks[0].times)).toEqual([0, 1])
+ expect(Array.from(lower_clip.tracks[0].times)).toEqual([0, 1])
+ })
+})
+
+describe('ComposerClipBuilder upright upper body', () => {
+ // turning the hips this far forward is roughly what a crouch does
+ const hips_tilted = new Quaternion().setFromEuler(new Euler(Math.PI / 4, 0, 0))
+ const spine_twist = new Quaternion().setFromEuler(new Euler(0, Math.PI / 6, 0))
+
+ function rotation_track (bone_name: string, rotation: Quaternion, duration: number = 1): QuaternionKeyframeTrack {
+ const values = [...rotation.toArray(), ...rotation.toArray()]
+ return new QuaternionKeyframeTrack(`${bone_name}.quaternion`, [0, duration], values)
+ }
+
+ function frame_rotation (clip: AnimationClip, bone_name: string, frame: number): Quaternion {
+ return new Quaternion().fromArray(value_at_frame(find_track(clip, `${bone_name}.quaternion`), frame))
+ }
+
+ it('finds the upper body root and the bones between it and the skeleton root', () => {
+ const rig = ComposerClipBuilder.upright_upper_body_rig(make_skeleton(), 'spine_01')
+
+ expect(rig?.upper_body_root.name).toBe('spine_01')
+ expect(rig?.parent_chain.map(bone => bone.name)).toEqual(['pelvis'])
+ expect(ComposerClipBuilder.upright_upper_body_rig(make_skeleton(), 'chest')).toBeUndefined()
+ })
+
+ it('keeps the upper body facing the way it did in the upper clip', () => {
+ const rig = ComposerClipBuilder.upright_upper_body_rig(make_skeleton(), 'spine_01')
+ const upper_clip = new AnimationClip('wave', 1, [rotation_track('spine_01', spine_twist)])
+ const lower_clip = new AnimationClip('crouch', 1, [rotation_track('pelvis', hips_tilted)])
+
+ const clip = ComposerClipBuilder.compose_clip({
+ upper_clip, lower_clip, upper_body_bone_names, fps, name: 'combo', upright_upper_body: rig
+ })
+
+ // the hips still tilt, but hips * spine ends up where the upper clip had it (upper clip hips are at rest)
+ const pelvis = frame_rotation(clip, 'pelvis', 5)
+ const spine = frame_rotation(clip, 'spine_01', 5)
+ expect(pelvis.angleTo(hips_tilted)).toBeCloseTo(0)
+ expect(pelvis.multiply(spine).angleTo(spine_twist)).toBeCloseTo(0)
+ })
+
+ it('makes no difference when both clips have the same hips', () => {
+ const rig = ComposerClipBuilder.upright_upper_body_rig(make_skeleton(), 'spine_01')
+ const upper_clip = new AnimationClip('wave', 1, [rotation_track('pelvis', hips_tilted), rotation_track('spine_01', spine_twist)])
+ const lower_clip = new AnimationClip('walk', 1, [rotation_track('pelvis', hips_tilted)])
+
+ const clip = ComposerClipBuilder.compose_clip({
+ upper_clip, lower_clip, upper_body_bone_names, fps, name: 'combo', upright_upper_body: rig
+ })
+
+ expect(frame_rotation(clip, 'spine_01', 3).angleTo(spine_twist)).toBeCloseTo(0)
+ })
+
+ it('adds an upper body root track when the upper clip has none', () => {
+ const rig = ComposerClipBuilder.upright_upper_body_rig(make_skeleton(), 'spine_01')
+ const upper_clip = new AnimationClip('wave', 1, [rotation_track('upperarm_l', spine_twist)])
+ const lower_clip = new AnimationClip('crouch', 1, [rotation_track('pelvis', hips_tilted)])
+
+ const clip = ComposerClipBuilder.compose_clip({
+ upper_clip, lower_clip, upper_body_bone_names, fps, name: 'combo', upright_upper_body: rig
+ })
+
+ // the spine cancels the hip tilt, so the upper body stays at its rest orientation
+ expect(frame_rotation(clip, 'spine_01', 0).angleTo(hips_tilted.clone().invert())).toBeCloseTo(0)
+ })
+})
diff --git a/src/composer/ComposerClipBuilder.ts b/src/composer/ComposerClipBuilder.ts
new file mode 100644
index 0000000..2b629b3
--- /dev/null
+++ b/src/composer/ComposerClipBuilder.ts
@@ -0,0 +1,235 @@
+import {
+ AnimationClip, type Bone, type Interpolant, type KeyframeTrack, type Object3D, PropertyBinding,
+ Quaternion, QuaternionKeyframeTrack, type Skeleton
+} from 'three'
+
+export interface ComposeClipOptions {
+ upper_clip: AnimationClip
+ lower_clip: AnimationClip
+ // bones driven by the upper clip. every other bone is driven by the lower clip
+ upper_body_bone_names: Set<string>
+ // frames per second the combined clip is baked at
+ fps: number
+ name: string
+ // when set, the upper body keeps the orientation it had in the upper clip instead of following the lower clip's hips
+ upright_upper_body?: UprightUpperBodyRig
+}
+
+export interface BoneRestRotation {
+ name: string
+ rest_quaternion: Quaternion
+}
+
+/**
+ * Bones needed to keep the upper body upright. Bones without a rotation track in a clip use their rest rotation.
+ */
+export interface UprightUpperBodyRig {
+ upper_body_root: BoneRestRotation // e.g. spine_01
+ // bones between the skeleton root and the upper body root, top first (e.g. pelvis)
+ parent_chain: BoneRestRotation[]
+}
+
+type KeyframeTrackConstructor = new (name: string, times: ArrayLike<number>, values: ArrayLike<number>) => KeyframeTrack
+type InterpolatableTrack = KeyframeTrack & { createInterpolant: () => Interpolant }
+
+/**
+ * Builds a new animation by taking the upper body tracks from one clip
+ * and the lower body tracks (including root motion and hip height) from another.
+ */
+export class ComposerClipBuilder {
+ /**
+ * Names of the bone with the given name and every bone below it.
+ * @returns an empty set if the bone is not in the skeleton
+ */
+ static upper_body_bone_names (skeleton: Skeleton, upper_body_root_bone_name: string): Set<string> {
+ const bone_names = new Set<string>()
+ const upper_body_root: Bone | undefined = skeleton.bones.find(bone => bone.name === upper_body_root_bone_name)
+
+ upper_body_root?.traverse((child) => {
+ bone_names.add(child.name)
+ })
+
+ return bone_names
+ }
+
+ /**
+ * Finds the bones needed to keep the upper body upright.
+ * The skeleton's top bone (root) is left out of the parent chain, so turning and moving the
+ * whole character still carries the upper body along with it.
+ * @returns undefined if the upper body root bone is not in the skeleton
+ */
+ static upright_upper_body_rig (skeleton: Skeleton, upper_body_root_bone_name: string): UprightUpperBodyRig | undefined {
+ const upper_body_root: Bone | undefined = skeleton.bones.find(bone => bone.name === upper_body_root_bone_name)
+ if (upper_body_root === undefined) {
+ return undefined
+ }
+
+ const skeleton_bones = new Set<Object3D>(skeleton.bones)
+ const parents: Bone[] = []
+ let parent: Object3D | null = upper_body_root.parent
+ while (parent !== null && skeleton_bones.has(parent)) {
+ parents.unshift(parent as Bone)
+ parent = parent.parent
+ }
+
+ const rest_rotation = (bone: Bone): BoneRestRotation => ({ name: bone.name, rest_quaternion: bone.quaternion.clone() })
+ return {
+ upper_body_root: rest_rotation(upper_body_root),
+ parent_chain: parents.slice(1).map(rest_rotation)
+ }
+ }
+
+ /**
+ * The longer of the two clips sets the length. The shorter clip is stretched to that length
+ * (its key times are scaled up), so both halves start and end together and the result loops cleanly.
+ * Both clips are sampled at the same frame times, so tracks with different key times line up.
+ */
+ static compose_clip (options: ComposeClipOptions): AnimationClip {
+ const { upper_clip, lower_clip, upper_body_bone_names, fps, name } = options
+
+ // a single pose (zero length) clip holds its pose for the whole length of the other clip
+ const duration: number = Math.max(upper_clip.duration, lower_clip.duration)
+ const frame_times: Float32Array = ComposerClipBuilder.frame_times(duration, fps)
+
+ const upper_tracks: KeyframeTrack[] = upper_clip.tracks
+ .filter(track => upper_body_bone_names.has(ComposerClipBuilder.bone_name_for_track(track)))
+ .map(track => ComposerClipBuilder.resample_track(track, frame_times, upper_clip.duration, duration))
+
+ const lower_tracks: KeyframeTrack[] = lower_clip.tracks
+ .filter(track => !upper_body_bone_names.has(ComposerClipBuilder.bone_name_for_track(track)))
+ .map(track => ComposerClipBuilder.resample_track(track, frame_times, lower_clip.duration, duration))
+
+ const tracks: KeyframeTrack[] = [...lower_tracks, ...upper_tracks]
+
+ if (options.upright_upper_body !== undefined) {
+ const rig: UprightUpperBodyRig = options.upright_upper_body
+ const upright_track_name = `${rig.upper_body_root.name}.quaternion`
+ const upright_track = new QuaternionKeyframeTrack(
+ upright_track_name,
+ frame_times.slice(),
+ ComposerClipBuilder.upright_rotations(upper_clip, lower_clip, rig, frame_times, duration)
+ )
+
+ const existing_index: number = tracks.findIndex(track => track.name === upright_track_name)
+ if (existing_index === -1) {
+ tracks.push(upright_track)
+ } else {
+ tracks[existing_index] = upright_track
+ }
+ }
+
+ return new AnimationClip(name, duration, tracks)
+ }
+
+ /**
+ * Rotations for the upper body root that cancel out the difference between the lower and upper clip's hips:
+ * upper_root = inverse(lower_chain) * upper_chain * upper_root_from_upper_clip
+ * so the upper body faces the same way relative to the character as it did in the upper clip.
+ */
+ private static upright_rotations (
+ upper_clip: AnimationClip,
+ lower_clip: AnimationClip,
+ rig: UprightUpperBodyRig,
+ frame_times: Float32Array,
+ duration: number
+ ): Float32Array {
+ const upper_root_rotations = ComposerClipBuilder.sample_rotations(upper_clip, rig.upper_body_root, frame_times, duration)
+ const upper_chain = rig.parent_chain.map(bone => ComposerClipBuilder.sample_rotations(upper_clip, bone, frame_times, duration))
+ const lower_chain = rig.parent_chain.map(bone => ComposerClipBuilder.sample_rotations(lower_clip, bone, frame_times, duration))
+
+ const values = new Float32Array(frame_times.length * 4)
+ const lower_chain_rotation = new Quaternion()
+ const upper_chain_rotation = new Quaternion()
+ const bone_rotation = new Quaternion()
+ const result = new Quaternion()
+ const previous_result = new Quaternion()
+
+ for (let frame = 0; frame < frame_times.length; frame++) {
+ lower_chain_rotation.identity()
+ upper_chain_rotation.identity()
+ for (let i = 0; i < rig.parent_chain.length; i++) {
+ lower_chain_rotation.multiply(bone_rotation.fromArray(lower_chain[i], frame * 4))
+ upper_chain_rotation.multiply(bone_rotation.fromArray(upper_chain[i], frame * 4))
+ }
+
+ result.copy(lower_chain_rotation.invert())
+ .multiply(upper_chain_rotation)
+ .multiply(bone_rotation.fromArray(upper_root_rotations, frame * 4))
+ .normalize()
+
+ // q and -q are the same rotation. keep neighbouring frames on the same side so interpolation doesn't spin the long way round
+ if (frame > 0 && result.dot(previous_result) < 0) {
+ result.set(-result.x, -result.y, -result.z, -result.w)
+ }
+ previous_result.copy(result)
+ result.toArray(values, frame * 4)
+ }
+
+ return values
+ }
+
+ // rotation of a bone at every frame time, or its rest rotation if the clip doesn't animate it
+ private static sample_rotations (clip: AnimationClip, bone: BoneRestRotation, frame_times: Float32Array, duration: number): Float32Array {
+ const track: KeyframeTrack | undefined = clip.tracks.find(t => t.name === `${bone.name}.quaternion`)
+ if (track !== undefined) {
+ return ComposerClipBuilder.sample_track_values(track, frame_times, clip.duration, duration)
+ }
+
+ const values = new Float32Array(frame_times.length * 4)
+ for (let frame = 0; frame < frame_times.length; frame++) {
+ bone.rest_quaternion.toArray(values, frame * 4)
+ }
+ return values
+ }
+
+ static bone_name_for_track (track: KeyframeTrack): string {
+ return PropertyBinding.parseTrackName(track.name).nodeName
+ }
+
+ /**
+ * Times for every frame from 0 to the duration. The last frame lands exactly on the duration.
+ */
+ static frame_times (duration: number, fps: number): Float32Array {
+ const last_frame: number = Math.max(0, Math.round(duration * fps))
+ const times = new Float32Array(last_frame + 1)
+ for (let frame = 0; frame <= last_frame; frame++) {
+ times[frame] = Math.min(frame / fps, duration)
+ }
+ return times
+ }
+
+ /**
+ * Samples the track at each frame time, with the source clip stretched to the combined clip's duration.
+ */
+ private static resample_track (
+ track: KeyframeTrack, frame_times: Float32Array, source_duration: number, duration: number
+ ): KeyframeTrack {
+ const values: Float32Array = ComposerClipBuilder.sample_track_values(track, frame_times, source_duration, duration)
+ const TrackType = track.constructor as KeyframeTrackConstructor
+ const resampled_track: KeyframeTrack = new TrackType(track.name, frame_times.slice(), values)
+ resampled_track.setInterpolation(track.getInterpolation())
+ return resampled_track
+ }
+
+ private static sample_track_values (
+ track: KeyframeTrack, frame_times: Float32Array, source_duration: number, duration: number
+ ): Float32Array {
+ const value_size: number = track.getValueSize()
+ const values = new Float32Array(frame_times.length * value_size)
+ // createInterpolant picks the right interpolation for the track type (slerp for quaternions),
+ // but it is assigned at runtime by setInterpolation(), so it is missing from the three.js types
+ const interpolant: Interpolant = (track as InterpolatableTrack).createInterpolant()
+
+ // maps a time in the combined clip to the same point in the source clip. a zero length source always samples its first frame
+ const time_scale: number = duration > 0 ? source_duration / duration : 0
+
+ frame_times.forEach((time: number, frame: number) => {
+ const sample: ArrayLike<number> = interpolant.evaluate(time * time_scale)
+ for (let i = 0; i < value_size; i++) {
+ values[frame * value_size + i] = sample[i]
+ }
+ })
+
+ return values
+ }
+}
diff --git a/src/composer/ComposerConfig.ts b/src/composer/ComposerConfig.ts
new file mode 100644
index 0000000..0fa642e
--- /dev/null
+++ b/src/composer/ComposerConfig.ts
@@ -0,0 +1,20 @@
+import { SkeletonType } from '../lib/enums/SkeletonType.ts'
+
+/**
+ * Settings for the Composer page. The Composer only supports the human rig for now.
+ */
+export class ComposerConfig {
+ static readonly skeleton_type: SkeletonType = SkeletonType.Human
+
+ // model variation (from the asset manifest) shown in the preview. variations are already rigged
+ static readonly model_variation_name: string = 'base'
+
+ // clip name of the animation that both slots start with
+ static readonly default_animation_name: string = 'Idle_A'
+
+ // this bone and everything below it is the upper half. everything else (root, pelvis, legs) is the lower half
+ static readonly upper_body_root_bone_name: string = 'spine_01'
+
+ // path from the composer page to the static root
+ static readonly static_root_path: string = '../'
+}
diff --git a/src/composer/ComposerExport.test.ts b/src/composer/ComposerExport.test.ts
new file mode 100644
index 0000000..d78ec77
--- /dev/null
+++ b/src/composer/ComposerExport.test.ts
@@ -0,0 +1,16 @@
+import { describe, it, expect } from 'vitest'
+import { ComposerExport } from './ComposerExport'
+
+describe('ComposerExport.clean_name', () => {
+ it('replaces spaces with underscores', () => {
+ expect(ComposerExport.clean_name(' Wave while walking ')).toBe('Wave_while_walking')
+ })
+
+ it('removes characters that are not safe in file names', () => {
+ expect(ComposerExport.clean_name('Punch/Walk: v2?')).toBe('PunchWalk_v2')
+ })
+
+ it('keeps letters, numbers, underscores and dashes', () => {
+ expect(ComposerExport.clean_name('Idle-A_2_Remix')).toBe('Idle-A_2_Remix')
+ })
+})
diff --git a/src/composer/ComposerExport.ts b/src/composer/ComposerExport.ts
new file mode 100644
index 0000000..df0e0e0
--- /dev/null
+++ b/src/composer/ComposerExport.ts
@@ -0,0 +1,99 @@
+import { type AnimationClip, type SkinnedMesh } from 'three'
+import { type DownloadSettings } from '../lib/processes/export-to-file/DownloadSettings.ts'
+import { type StepExportToFile } from '../lib/processes/export-to-file/StepExportToFile.ts'
+import { DownloadSuccessDialog } from '../lib/components/download-success/DownloadSuccessDialog.ts'
+import { ModalDialog } from '../lib/ModalDialog.ts'
+
+export interface ComposerExportData {
+ clip: AnimationClip
+ skinned_meshes: SkinnedMesh[]
+}
+
+/**
+ * The download button on the Composer page. The file is named after the animations in the slots.
+ * Downloads go through the same export step and download options as the Explore page.
+ */
+export class ComposerExport {
+ private readonly dom_export_button: HTMLButtonElement | null = document.querySelector('#export-composer-button')
+
+ private export_name: string = 'Animation_Remix'
+ private is_exporting: boolean = false
+ private has_export_data: boolean = false
+
+ constructor (
+ private readonly file_export_step: StepExportToFile,
+ private readonly download_settings: DownloadSettings,
+ private readonly get_export_data: () => ComposerExportData | null
+ ) {
+ // the button always downloads one animation
+ const count_element = this.dom_export_button?.querySelector('#animation-selection-count')
+ if (count_element !== null && count_element !== undefined) {
+ count_element.textContent = '1'
+ }
+
+ this.add_event_listeners()
+ this.update_button_state()
+ }
+
+ /**
+ * Name for the downloaded file and the animation inside it, e.g. 'Wave_Walk_Remix'.
+ */
+ public set_export_name (name: string): void {
+ const cleaned_name: string = ComposerExport.clean_name(name)
+ if (cleaned_name !== '') {
+ this.export_name = cleaned_name
+ }
+ }
+
+ /**
+ * Turns the download button off while the composed animation is out of date (a slot is still downloading).
+ */
+ public set_export_ready (is_ready: boolean): void {
+ this.has_export_data = is_ready
+ this.update_button_state()
+ }
+
+ // names end up as file names and animation names in game engines, so keep them simple
+ static clean_name (name: string): string {
+ return name.trim().replace(/\s+/g, '_').replace(/[^A-Za-z0-9_-]/g, '')
+ }
+
+ private add_event_listeners (): void {
+ this.dom_export_button?.addEventListener('click', () => {
+ this.export().catch((error: unknown) => {
+ console.error('Composer export failed:', error)
+ const error_message = error instanceof Error ? error.message : 'Failed to export file.'
+ new ModalDialog('Export failed', error_message).show()
+ })
+ })
+ }
+
+ private async export (): Promise<void> {
+ const export_data: ComposerExportData | null = this.get_export_data()
+ if (export_data === null || this.is_exporting) {
+ return
+ }
+
+ const name: string = this.export_name
+ const clip: AnimationClip = export_data.clip.clone()
+ clip.name = name
+
+ this.is_exporting = true
+ this.update_button_state()
+ try {
+ this.file_export_step.set_animation_clips_to_export([{ clip, mirror_export_mode: 'none' }])
+ await this.file_export_step.export(export_data.skinned_meshes, name, this.download_settings)
+ } finally {
+ this.is_exporting = false
+ this.update_button_state()
+ }
+
+ new DownloadSuccessDialog().show()
+ }
+
+ private update_button_state (): void {
+ if (this.dom_export_button !== null) {
+ this.dom_export_button.disabled = !this.has_export_data || this.is_exporting
+ }
+ }
+}
diff --git a/src/composer/ComposerLibraryList.ts b/src/composer/ComposerLibraryList.ts
new file mode 100644
index 0000000..8daea5b
--- /dev/null
+++ b/src/composer/ComposerLibraryList.ts
@@ -0,0 +1,147 @@
+import { type SkeletonType } from '../lib/enums/SkeletonType.ts'
+import { type ThemeManager } from '../lib/ThemeManager.ts'
+import { type AnimationEntry } from '../lib/processes/animations-listing/interfaces/AnimationEntry.ts'
+import { AnimationPreviewVideos } from '../lib/processes/animations-listing/AnimationPreviewVideos.ts'
+/**
+ * Library of animations shown on the Composer page. Animations are not selected here.
+ * They are dragged onto a slot, which reads the animation id from the drag data.
+ */
+export class ComposerLibraryList {
+ // data transfer type for drags, so slots can ignore files or text dragged in from elsewhere
+ static readonly drag_data_type: string = 'application/x-mesh2motion-animation-id'
+
+ // added to the body while a tile is dragged, so every slot can show it accepts drops
+ static readonly dragging_body_class: string = 'composer-is-dragging'
+
+ private entries: AnimationEntry[] = []
+ private readonly tile_elements = new Map<string, HTMLElement>()
+ private readonly preview_videos: AnimationPreviewVideos = new AnimationPreviewVideos()
+
+ constructor (
+ private readonly list_container: HTMLElement,
+ private readonly filter_input: HTMLInputElement | null,
+ private readonly count_element: HTMLElement | null,
+ private readonly theme_manager: ThemeManager,
+ private readonly skeleton_type: SkeletonType
+ ) {
+ this.add_event_listeners()
+ }
+
+ public set_animations (entries: AnimationEntry[]): void {
+ this.entries = entries
+ this.build_tiles()
+ }
+
+ /**
+ * Marks the tiles that are in a slot, so it is clear which animations make up the result.
+ */
+ public set_slot_markers (upper_animation_id: string | null, lower_animation_id: string | null): void {
+ this.tile_elements.forEach((tile, animation_id) => {
+ tile.classList.toggle('in-upper-slot', animation_id === upper_animation_id)
+ tile.classList.toggle('in-lower-slot', animation_id === lower_animation_id)
+ })
+ }
+
+ public scroll_to_animation (animation_id: string): void {
+ this.tile_elements.get(animation_id)?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
+ }
+
+ static display_name (animation_name: string): string {
+ return animation_name.replace(/_/g, ' ')
+ }
+
+ private build_tiles (): void {
+ this.tile_elements.clear()
+ const theme_name: string = this.theme_manager.get_current_theme()
+
+ this.list_container.innerHTML = this.entries.map((entry) => {
+ const name: string = ComposerLibraryList.display_name(entry.name)
+ // custom imports have no preview video
+ const is_custom_import: boolean = entry.metadata.source_type === 'custom-import'
+ const preview_src: string | null = is_custom_import
+ ? null
+ : AnimationPreviewVideos.preview_src(this.skeleton_type, theme_name, entry.name)
+ const data_src_attribute: string = preview_src === null ? '' : ` data-src="${preview_src}"`
+ const preview_html: string = is_custom_import
+ ? '<div class="anim-preview-placeholder composer-custom-preview"><span class="composer-imported-chip">Imported</span></div>'
+ : `<div class="anim-preview-placeholder"${data_src_attribute}></div>`
+
+ return `
+ <div class="composer-library-item" draggable="true" data-animation-id="${entry.id}" title="Drag ${name} onto a slot">
+ <span class="composer-drag-grip" aria-hidden="true"></span>
+ <span class="composer-slot-badge composer-slot-badge-upper" aria-hidden="true">Upper</span>
+ <span class="composer-slot-badge composer-slot-badge-lower" aria-hidden="true">Lower</span>
+ <div class="composer-library-item-preview">
+ ${preview_html}
+ </div>
+ <span class="composer-library-item-name">${name}</span>
+ </div>`
+ }).join('') + '<div class="composer-library-empty" style="display: none">No animations match the filter.</div>'
+
+ this.list_container.querySelectorAll<HTMLElement>('.composer-library-item').forEach((tile) => {
+ this.tile_elements.set(tile.dataset.animationId ?? '', tile)
+ })
+
+ this.apply_filter()
+ this.preview_videos.observe_placeholders(this.list_container)
+ }
+
+ /**
+ * Hides tiles that don't match the filter text. Tiles are hidden instead of rebuilt so their videos keep playing.
+ */
+ private apply_filter (): void {
+ // names can use underscores or spaces, so compare with spaces. tags like 'combat' match too
+ const search_text: string = (this.filter_input?.value ?? '').toLowerCase().replace(/_/g, ' ').trim()
+ let visible_count: number = 0
+
+ this.entries.forEach((entry) => {
+ const matches: boolean = entry.name.toLowerCase().replace(/_/g, ' ').includes(search_text) ||
+ entry.metadata.tags.some(tag => tag.toLowerCase().includes(search_text))
+
+ const tile = this.tile_elements.get(entry.id)
+ if (tile !== undefined) {
+ tile.style.display = matches ? '' : 'none'
+ }
+ if (matches) {
+ visible_count++
+ }
+ })
+
+ const empty_message = this.list_container.querySelector<HTMLElement>('.composer-library-empty')
+ if (empty_message !== null) {
+ empty_message.style.display = visible_count === 0 ? '' : 'none'
+ }
+
+ if (this.count_element !== null) {
+ this.count_element.textContent = `${visible_count} ${visible_count === 1 ? 'result' : 'results'}`
+ }
+ }
+
+ private add_event_listeners (): void {
+ this.filter_input?.addEventListener('input', () => { this.apply_filter() })
+
+ // preview video file names depend on the theme
+ this.theme_manager.addEventListener('theme-changed', () => { this.build_tiles() })
+
+ this.list_container.addEventListener('dragstart', (event: DragEvent) => {
+ const tile = (event.target as HTMLElement).closest<HTMLElement>('.composer-library-item')
+ const animation_id = tile?.dataset.animationId
+ if (tile === null || tile === undefined || animation_id === undefined || event.dataTransfer === null) {
+ return
+ }
+
+ event.dataTransfer.setData(ComposerLibraryList.drag_data_type, animation_id)
+ event.dataTransfer.setData('text/plain', animation_id)
+ event.dataTransfer.effectAllowed = 'copy'
+
+ tile.classList.add('is-dragging')
+ document.body.classList.add(ComposerLibraryList.dragging_body_class)
+ })
+
+ // fires on the dragged tile whether the drop landed on a slot or was cancelled
+ this.list_container.addEventListener('dragend', (event: DragEvent) => {
+ (event.target as HTMLElement).closest('.composer-library-item')?.classList.remove('is-dragging')
+ document.body.classList.remove(ComposerLibraryList.dragging_body_class)
+ })
+ }
+}
diff --git a/src/composer/ComposerModelLoader.ts b/src/composer/ComposerModelLoader.ts
new file mode 100644
index 0000000..922efb6
--- /dev/null
+++ b/src/composer/ComposerModelLoader.ts
@@ -0,0 +1,49 @@
+import { SkinnedMesh } from 'three'
+import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
+import { RigConfig } from '../lib/RigConfig.ts'
+import { Utility } from '../lib/Utilities.ts'
+import { ComposerConfig } from './ComposerConfig.ts'
+
+/**
+ * Loads the pre-rigged human model that the Composer previews animations on.
+ * Model variations are already skinned, so the Composer can skip the load/edit/skin steps.
+ */
+export class ComposerModelLoader {
+ private readonly gltf_loader: GLTFLoader = new GLTFLoader()
+
+ public async load (): Promise<SkinnedMesh[]> {
+ const model_file: string = this.model_file_path()
+ const gltf = await this.gltf_loader.loadAsync(`${ComposerConfig.static_root_path}${model_file}`)
+
+ const skinned_meshes: SkinnedMesh[] = []
+ gltf.scene.traverse((child) => {
+ if (child instanceof SkinnedMesh) {
+ child.castShadow = true
+ child.receiveShadow = true
+ skinned_meshes.push(child)
+ }
+ })
+
+ if (skinned_meshes.length === 0) {
+ throw new Error(`No skinned meshes found in ${model_file}`)
+ }
+
+ Utility.parent_root_bones_to_skinned_meshes(skinned_meshes)
+ return skinned_meshes
+ }
+
+ private model_file_path (): string {
+ const rig = RigConfig.by_skeleton_type(ComposerConfig.skeleton_type)
+ if (rig === undefined) {
+ throw new Error(`Rig for ${ComposerConfig.skeleton_type} is not in the asset manifest`)
+ }
+
+ const variation = rig.model_variations.find(v => v.name === ComposerConfig.model_variation_name) ??
+ rig.model_variations[0]
+ if (variation === undefined) {
+ throw new Error(`Rig ${rig.rig_display_name} has no rigged model variations`)
+ }
+
+ return variation.model_file
+ }
+}
diff --git a/src/composer/ComposerPreview.ts b/src/composer/ComposerPreview.ts
new file mode 100644
index 0000000..9d7fb2d
--- /dev/null
+++ b/src/composer/ComposerPreview.ts
@@ -0,0 +1,53 @@
+import { type AnimationAction, type AnimationClip, AnimationMixer, Object3D, type SkinnedMesh } from 'three'
+import { AnimationPlayer } from '../lib/processes/animations-listing/AnimationPlayer.ts'
+
+/**
+ * Plays the composed animation on the preview model and keeps the
+ * shared animation player controls (play/pause, scrubber) in sync.
+ */
+export class ComposerPreview {
+ private readonly animation_player: AnimationPlayer = new AnimationPlayer()
+ private animation_mixer: AnimationMixer = new AnimationMixer(new Object3D())
+ private skinned_meshes: SkinnedMesh[] = []
+ private current_clip: AnimationClip | null = null
+
+ public set_skinned_meshes (skinned_meshes: SkinnedMesh[]): void {
+ this.skinned_meshes = skinned_meshes
+ if (this.current_clip !== null) {
+ this.play_clip(this.current_clip)
+ }
+ }
+
+ public play_clip (clip: AnimationClip): void {
+ this.current_clip = clip
+
+ // a new mixer clears the cached actions, so a rebuilt clip with the same name still updates
+ this.animation_mixer.stopAllAction()
+ this.animation_mixer = new AnimationMixer(new Object3D())
+
+ const actions: AnimationAction[] = this.skinned_meshes.map((skinned_mesh: SkinnedMesh) => {
+ this.reset_root_bone_position(skinned_mesh)
+ const action: AnimationAction = this.animation_mixer.clipAction(clip, skinned_mesh)
+ action.play()
+ return action
+ })
+
+ if (actions.length > 0) {
+ this.animation_player.set_animation(clip, actions)
+ }
+ }
+
+ public frame_change (delta_time: number): void {
+ this.animation_mixer.update(delta_time)
+ this.animation_player.update(delta_time)
+ }
+
+ // not every clip has root bone keyframes, so clear any offset left over from the previous clip
+ private reset_root_bone_position (skinned_mesh: SkinnedMesh): void {
+ const root_bone = skinned_mesh.skeleton.bones[0]
+ if (root_bone !== undefined) {
+ root_bone.position.set(0, 0, 0)
+ root_bone.updateMatrixWorld(true)
+ }
+ }
+}
diff --git a/src/composer/ComposerSlots.ts b/src/composer/ComposerSlots.ts
new file mode 100644
index 0000000..f692eb9
--- /dev/null
+++ b/src/composer/ComposerSlots.ts
@@ -0,0 +1,107 @@
+import { ComposerLibraryList } from './ComposerLibraryList.ts'
+
+export type ComposerSlotName = 'upper' | 'lower'
+
+export interface SlotAnimationDroppedDetail {
+ slot: ComposerSlotName
+ animation_id: string
+}
+
+export interface SlotDisplay {
+ animation_name: string
+ is_loading: boolean
+}
+
+/**
+ * The upper body and lower body slots on the Composer page. Library tiles are dropped onto them.
+ *
+ * Dispatches 'slot-animation-dropped' (SlotAnimationDroppedDetail).
+ */
+export class ComposerSlots extends EventTarget {
+ static readonly slot_names: ComposerSlotName[] = ['upper', 'lower']
+
+ private readonly slot_elements = new Map<ComposerSlotName, HTMLElement>()
+
+ constructor () {
+ super()
+
+ ComposerSlots.slot_names.forEach((slot) => {
+ const element = document.querySelector<HTMLElement>(`#composer-${slot}-slot`)
+ if (element === null) {
+ console.error(`Composer slot element for '${slot}' is missing from the page`)
+ return
+ }
+
+ this.slot_elements.set(slot, element)
+ this.add_slot_event_listeners(slot, element)
+ })
+ }
+
+ public show (slot: ComposerSlotName, display: SlotDisplay): void {
+ const element = this.slot_elements.get(slot)
+ if (element === undefined) {
+ return
+ }
+
+ const display_name: string = ComposerLibraryList.display_name(display.animation_name)
+ const name_element = element.querySelector('.composer-slot-animation-name')
+ if (name_element !== null) {
+ name_element.textContent = display_name
+ }
+
+ // names can be cut off in the narrow slots, so the full name shows on hover
+ const half_label: string = slot === 'upper' ? 'Upper body' : 'Lower body'
+ element.title = `${half_label}: ${display_name}. Drop an animation here to replace it.`
+ element.classList.toggle('is-loading', display.is_loading)
+ }
+
+ private add_slot_event_listeners (slot: ComposerSlotName, element: HTMLElement): void {
+ // dragenter/dragleave also fire when moving over child elements, so count them to know when the cursor really left
+ let drag_depth: number = 0
+
+ element.addEventListener('dragenter', (event: DragEvent) => {
+ if (!this.is_animation_drag(event)) {
+ return
+ }
+ event.preventDefault()
+ drag_depth++
+ element.classList.add('is-drag-over')
+ })
+
+ // dropping is only allowed when dragover is cancelled
+ element.addEventListener('dragover', (event: DragEvent) => {
+ if (!this.is_animation_drag(event)) {
+ return
+ }
+ event.preventDefault()
+ if (event.dataTransfer !== null) {
+ event.dataTransfer.dropEffect = 'copy'
+ }
+ })
+
+ element.addEventListener('dragleave', () => {
+ drag_depth = Math.max(0, drag_depth - 1)
+ if (drag_depth === 0) {
+ element.classList.remove('is-drag-over')
+ }
+ })
+
+ element.addEventListener('drop', (event: DragEvent) => {
+ drag_depth = 0
+ element.classList.remove('is-drag-over')
+
+ const animation_id = event.dataTransfer?.getData(ComposerLibraryList.drag_data_type) ?? ''
+ if (animation_id === '') {
+ return
+ }
+
+ event.preventDefault()
+ this.dispatchEvent(new CustomEvent<SlotAnimationDroppedDetail>('slot-animation-dropped', { detail: { slot, animation_id } }))
+ })
+ }
+
+ // the data itself can only be read on drop, but the types are visible while dragging
+ private is_animation_drag (event: DragEvent): boolean {
+ return event.dataTransfer?.types.includes(ComposerLibraryList.drag_data_type) ?? false
+ }
+}
diff --git a/src/composer/composer.css b/src/composer/composer.css
new file mode 100644
index 0000000..c24274f
--- /dev/null
+++ b/src/composer/composer.css
@@ -0,0 +1,349 @@
+:root {
+ --composer-accent: var(--button-primary-bg);
+}
+
+#composer-panel {
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+ /* 24rem fit three tiles per row before the library list got its 0.75rem inner padding and 0.5rem tile gap.
+ the extra 2rem covers that padding on both sides plus the wider gaps, keeping three tiles per row */
+ width: 26rem;
+ max-width: 100%;
+ /* styles.css pads every div. override it with side padding only; content-box keeps the content width */
+ box-sizing: content-box;
+ padding: 0 1rem;
+ /* fill the panel height so only the library grid scrolls */
+ height: calc(100dvh - var(--navigation-height) - 1.5rem);
+}
+
+#composer-panel h1 {
+ font-size: 1.7rem;
+ margin: 0;
+}
+
+#composer-panel h2 {
+ font-size: 1.1rem;
+ margin: 0;
+}
+
+.composer-intro {
+ margin: 0;
+ color: var(--text-primary);
+}
+
+#composer-status {
+ color: var(--text-primary);
+ font-style: italic;
+}
+
+/* ---------- slots ---------- */
+
+#composer-slots {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 0.5rem;
+}
+
+.composer-slot {
+ position: relative;
+ display: flex;
+ align-items: center;
+ gap: 0.6rem;
+ min-width: 0;
+ padding: 0.75rem 0.85rem;
+ border: 2px dashed var(--bg-tertiary);
+ border-radius: 8px;
+ background: var(--bg-alternate);
+ transition: border-color 0.15s ease, background-color 0.15s ease, transform 0.15s ease, box-shadow 0.15s ease;
+}
+
+.composer-slot-figure {
+ flex-shrink: 0;
+ width: 20px;
+ height: 32px;
+}
+
+.composer-slot-figure rect,
+.composer-slot-figure circle {
+ fill: var(--bg-tertiary);
+ opacity: 0.45;
+}
+
+/* highlight the half of the body each slot controls */
+.composer-slot[data-slot="upper"] .figure-upper,
+.composer-slot[data-slot="lower"] .figure-lower {
+ fill: var(--text-primary);
+ opacity: 1;
+}
+
+.composer-slot-animation-name {
+ flex-grow: 1;
+ min-width: 0;
+ font-size: 0.95rem;
+ color: var(--text-primary);
+ line-height: 1.25;
+ /* long names wrap to a second line, then clamp with an ellipsis */
+ overflow: hidden;
+ overflow-wrap: anywhere;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+ line-clamp: 2;
+}
+
+.composer-slot.is-loading .composer-slot-animation-name::after {
+ content: ' …';
+ color: var(--text-primary);
+}
+
+/* while a tile is being dragged, every slot pulses to show it accepts drops */
+body.composer-is-dragging .composer-slot {
+ border-color: var(--composer-accent);
+ animation: composer-slot-pulse 1.2s ease-in-out infinite;
+}
+
+/* the slot under the cursor */
+.composer-slot.is-drag-over,
+body.composer-is-dragging .composer-slot.is-drag-over {
+ border-style: solid;
+ border-color: var(--composer-accent);
+ background: color-mix(in srgb, var(--composer-accent) 30%, var(--bg-alternate));
+ transform: scale(1.02);
+ animation: none;
+}
+
+@keyframes composer-slot-pulse {
+ 0%, 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--composer-accent) 0%, transparent); }
+ 50% { box-shadow: 0 0 0 4px color-mix(in srgb, var(--composer-accent) 45%, transparent); }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ body.composer-is-dragging .composer-slot {
+ animation: none;
+ }
+}
+
+/* ---------- library ---------- */
+
+#composer-library {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+ flex-grow: 1;
+ min-height: 0;
+ padding: 0;
+}
+
+/* filter input with the animation count overlaid on its right edge */
+.composer-library-filter-wrap {
+ position: relative;
+}
+
+#composer-library-filter {
+ width: 100%;
+ box-sizing: border-box;
+ margin-bottom: 0;
+ padding-right: 7.5rem; /* keep typed text clear of the count overlay */
+}
+
+#composer-library-count {
+ position: absolute;
+ top: 50%;
+ right: 1.25rem;
+ transform: translateY(-50%);
+ color: var(--text-primary);
+ font-size: 0.9rem;
+ pointer-events: none; /* clicks fall through to the input */
+}
+
+/*
+ * The list and tiles use the same sizes and colors as the Explore animation listing (#animations-items in styles.css).
+ * Only the drag cues (grip, hover outline, slot badges) are specific to the Composer.
+ */
+#composer-library-items {
+ display: flex;
+ flex-wrap: wrap;
+ align-content: flex-start;
+ gap: 0.5rem;
+ flex-grow: 1;
+ min-height: 10rem;
+ overflow-y: auto;
+ overflow-x: hidden;
+ padding: 0.75rem;
+ background: var(--bg-alternate);
+ border: 1px solid var(--bg-tertiary);
+}
+
+/* styles.css pads every div. the Explore listing turns that off for its tiles too */
+#composer-library-items div {
+ padding: 0;
+}
+
+.composer-library-empty {
+ width: 100%;
+ color: var(--text-primary);
+}
+
+#composer-library-items .composer-library-empty {
+ padding: 1rem;
+}
+
+.composer-library-item {
+ position: relative;
+ display: inline-flex;
+ flex-direction: column;
+ justify-content: flex-start;
+ width: 103px;
+ height: 160px;
+ background: transparent;
+ cursor: grab;
+ user-select: none;
+ transition: opacity 0.15s ease;
+}
+
+/* frame around the preview video. matches the play button around Explore previews (button.secondary-button.play) */
+#composer-library-items .composer-library-item-preview {
+ display: flex;
+ flex: 0 0 auto;
+ height: 123px; /* same height as the Explore preview button */
+ align-items: center;
+ justify-content: center;
+ box-sizing: border-box;
+ width: 100%;
+ border: 1px solid var(--bg-tertiary);
+ background: linear-gradient(0deg, var(--bg-alternate) 0%, var(--bg-tertiary) 100%);
+}
+
+/* same hover as the Explore previews */
+#composer-library-items .composer-library-item:hover .composer-library-item-preview {
+ border-color: var(--text-primary);
+ background: var(--bg-alternate);
+ transition: all 0.4s ease;
+}
+
+.composer-library-item:active {
+ cursor: grabbing;
+}
+
+/* the tile being dragged stays in place as a faded ghost */
+.composer-library-item.is-dragging {
+ opacity: 0.4;
+}
+
+.composer-library-item .anim-preview-placeholder,
+.composer-library-item .anim-preview {
+ display: block;
+ width: 100px;
+ height: 120px;
+ margin: 0;
+ border-radius: 0;
+ background: var(--bg-primary);
+ object-fit: cover;
+ /* videos are draggable on their own, so let the tile handle the drag */
+ pointer-events: none;
+}
+
+/* imported animations have no preview video. a chip in the middle of the frame marks them.
+ declared after the placeholder rule above so its flex display wins over display: block */
+.composer-library-item .anim-preview-placeholder.composer-custom-preview {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+/* same colors and pill shape as the custom animation badge on the Explore listing (.anim-custom-badge) */
+.composer-imported-chip {
+ padding: 0.25rem 0.6rem;
+ border-radius: 999px;
+ background: var(--button-alternate-bg);
+ color: #ffffff;
+ font-size: 0.75rem;
+ line-height: 1.2;
+}
+
+.composer-library-item-name {
+ width: 100px;
+ margin: 0.2rem auto;
+ font-size: 88%;
+ line-height: 120%;
+ text-align: left;
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+ line-clamp: 2;
+ overflow-wrap: anywhere;
+}
+
+/* dotted grip, the usual sign that something can be dragged */
+.composer-drag-grip {
+ display: inline-block;
+ flex-shrink: 0;
+ width: 10px;
+ height: 16px;
+ background-image: radial-gradient(circle, var(--text-alternate) 1.5px, transparent 1.6px);
+ background-size: 5px 5px;
+}
+
+.composer-library-item .composer-drag-grip {
+ position: absolute;
+ top: 8px;
+ left: 8px;
+ z-index: 2;
+ opacity: 0.7;
+ background-image: radial-gradient(circle, var(--text-primary) 1.5px, transparent 1.6px);
+ filter: drop-shadow(0 0 1px var(--bg-primary));
+}
+
+.composer-library-item:hover .composer-drag-grip {
+ opacity: 1;
+}
+
+/* badges show which tiles are in a slot */
+.composer-slot-badge {
+ display: none;
+ position: absolute;
+ top: 6px;
+ right: 6px;
+ z-index: 2;
+ padding: 0 0.3rem;
+ border-radius: 999px;
+ font-size: 0.65rem;
+ text-transform: uppercase;
+ color: white;
+ background: var(--composer-accent);
+}
+
+.composer-library-item.in-upper-slot .composer-slot-badge-upper,
+.composer-library-item.in-lower-slot .composer-slot-badge-lower {
+ display: inline-block;
+}
+
+/* both badges on one tile: stack the lower badge under the upper one */
+.composer-library-item.in-upper-slot .composer-slot-badge-lower {
+ top: 24px;
+}
+
+/* ---------- export ---------- */
+
+#composer-export {
+ display: flex;
+ justify-content: flex-end;
+}
+
+#composer-export #export-composer-button {
+ white-space: nowrap;
+}
+
+@media (max-width: 980px) {
+ #composer-panel {
+ box-sizing: border-box;
+ width: 100%;
+ height: auto;
+ }
+
+ #composer-library-items {
+ max-height: 50vh;
+ }
+}
diff --git a/src/composer/composer.ts b/src/composer/composer.ts
new file mode 100644
index 0000000..c95446e
--- /dev/null
+++ b/src/composer/composer.ts
@@ -0,0 +1,335 @@
+/// <reference types="vite/client" />
+import { type AnimationClip, type Skeleton, type SkinnedMesh, Vector3 } from 'three'
+import { RigConfig } from '../lib/RigConfig.ts'
+import { Utility } from '../lib/Utilities.ts'
+import { Mesh2MotionEngine } from '../Mesh2MotionEngine.ts'
+import { AnimationLoader } from '../lib/processes/animations-listing/AnimationLoader.ts'
+import { AnimationLibrary } from '../lib/processes/animations-listing/AnimationLibrary.ts'
+import { type AnimationEntry } from '../lib/processes/animations-listing/interfaces/AnimationEntry.ts'
+import { CustomAnimationImporter } from '../lib/processes/animations-listing/CustomAnimationImporter.ts'
+import { ImportAnimationsButton } from '../lib/processes/animations-listing/ImportAnimationsButton.ts'
+import { type TransformedAnimationClipPair } from '../lib/processes/animations-listing/interfaces/TransformedAnimationClipPair.ts'
+import { ComposerClipBuilder } from './ComposerClipBuilder.ts'
+import { ComposerConfig } from './ComposerConfig.ts'
+import { ComposerModelLoader } from './ComposerModelLoader.ts'
+import { ComposerPreview } from './ComposerPreview.ts'
+import { ComposerLibraryList } from './ComposerLibraryList.ts'
+import { ComposerSlots, type ComposerSlotName, type SlotAnimationDroppedDetail } from './ComposerSlots.ts'
+import { ComposerExport } from './ComposerExport.ts'
+
+/**
+ * Composer page: combines the upper half of one animation with the lower half
+ * of another, previews the result, and exports it as a new animation.
+ */
+class ComposerModule {
+ private static readonly fallback_fps: number = 24
+
+ private readonly mesh2motion_engine: Mesh2MotionEngine
+ private readonly model_loader: ComposerModelLoader = new ComposerModelLoader()
+ private readonly animation_loader: AnimationLoader = new AnimationLoader()
+ private readonly animation_library: AnimationLibrary = new AnimationLibrary(this.animation_loader)
+ private readonly preview: ComposerPreview
+ private readonly slots: ComposerSlots = new ComposerSlots()
+ private readonly library_list: ComposerLibraryList | null = null
+ private readonly composer_export: ComposerExport
+
+ // same GLB/FBX import the Explore page uses. imported animations join the library list
+ private readonly custom_animation_importer: CustomAnimationImporter
+ private readonly import_animations_button: ImportAnimationsButton
+
+ // preview model. the composed animation plays on it and it is what gets exported
+ private skinned_meshes: SkinnedMesh[] = []
+
+ // animation id (from the animation library) assigned to each slot
+ private readonly slot_animation_ids: Record<ComposerSlotName, string | null> = { upper: null, lower: null }
+
+ // bones driven by the upper slot. found from the model's skeleton once it loads
+ private upper_body_bone_names: Set<string> = new Set<string>()
+
+ // result of combining both slots. this is what the preview plays and what gets exported
+ private composed_clip: AnimationClip | null = null
+ private composition_request_id: number = 0
+
+ private readonly dom_status: HTMLElement | null = document.querySelector('#composer-status')
+
+ constructor () {
+ this.mesh2motion_engine = new Mesh2MotionEngine()
+ this.mesh2motion_engine.set_camera_position(new Vector3().set(6, 5, 11))
+
+ this.preview = new ComposerPreview()
+ this.mesh2motion_engine.add_frame_listener((delta_time: number) => {
+ this.preview.frame_change(delta_time)
+ })
+ this.mesh2motion_engine.set_active_skinned_meshes_provider(() => this.skinned_meshes)
+
+ const library_container = document.querySelector<HTMLElement>('#composer-library-items')
+ if (library_container !== null) {
+ this.library_list = new ComposerLibraryList(
+ library_container,
+ document.querySelector<HTMLInputElement>('#composer-library-filter'),
+ document.querySelector<HTMLElement>('#composer-library-count'),
+ this.mesh2motion_engine.get_theme_manager(),
+ ComposerConfig.skeleton_type
+ )
+ }
+
+ this.composer_export = new ComposerExport(
+ this.mesh2motion_engine.file_export_step,
+ this.mesh2motion_engine.download_settings,
+ () => {
+ if (this.composed_clip === null || this.skinned_meshes.length === 0) {
+ return null
+ }
+ return { clip: this.composed_clip, skinned_meshes: this.skinned_meshes }
+ }
+ )
+
+ this.custom_animation_importer = new CustomAnimationImporter(this.animation_loader)
+ this.custom_animation_importer.set_import_context_provider(() => {
+ return {
+ skinned_meshes_to_animate: this.skinned_meshes,
+ skeleton_scale: 1.0, // the Composer model is not rescaled
+ skeleton_type: ComposerConfig.skeleton_type
+ }
+ })
+ this.import_animations_button = new ImportAnimationsButton(
+ this.custom_animation_importer,
+ this.mesh2motion_engine.ui.dom_import_animations_button,
+ this.mesh2motion_engine.ui.dom_import_animations_input
+ )
+ // imports are validated against the model's skeleton, so wait until it loads
+ this.import_animations_button.set_enabled(false)
+
+ this.add_event_listeners()
+ }
+
+ public start (): void {
+ this.init().catch((error: unknown) => {
+ console.error('Failed to start the Composer:', error)
+ this.set_status('Something went wrong loading Remix. Try reloading the page.')
+ })
+ }
+
+ private async init (): Promise<void> {
+ this.mesh2motion_engine.show_animation_player(true)
+ this.mesh2motion_engine.download_settings.update_download_settings_ui_visibility(ComposerConfig.skeleton_type)
+
+ // lists every animation right away. each one downloads the first time it goes into a slot
+ this.animation_loader.set_static_root_path(ComposerConfig.static_root_path)
+ this.animation_library.reset(ComposerConfig.skeleton_type, 1.0)
+ this.library_list?.set_animations(this.animation_library.all())
+
+ const default_entry: AnimationEntry | undefined = this.find_default_animation()
+ if (default_entry === undefined) {
+ throw new Error(`Default animation ${ComposerConfig.default_animation_name} is not in the animation library`)
+ }
+ this.slot_animation_ids.upper = default_entry.id
+ this.slot_animation_ids.lower = default_entry.id
+ this.render_slots()
+
+ // shared header controls. the skeleton toggle is hidden until a page turns it on
+ if (this.mesh2motion_engine.ui.dom_show_skeleton_container !== null) {
+ this.mesh2motion_engine.ui.dom_show_skeleton_container.style.display = 'inline-flex'
+ }
+
+ this.set_status('Loading model…')
+ this.use_skinned_meshes(await this.model_loader.load())
+ this.import_animations_button.set_enabled(true)
+
+ this.set_status('')
+ await this.update_composition()
+ }
+
+ /**
+ * Shows the given model. The composed animation plays on it and it is what gets exported.
+ */
+ private use_skinned_meshes (skinned_meshes: SkinnedMesh[]): void {
+ const skeleton = skinned_meshes[0]?.skeleton
+ if (skeleton === undefined) {
+ throw new Error('The model has no skinned meshes')
+ }
+
+ const upper_body_bone_names = ComposerClipBuilder.upper_body_bone_names(skeleton, ComposerConfig.upper_body_root_bone_name)
+ if (upper_body_bone_names.size === 0) {
+ throw new Error(`Bone ${ComposerConfig.upper_body_root_bone_name} is not in the model's skeleton`)
+ }
+ this.upper_body_bone_names = upper_body_bone_names
+
+ this.skinned_meshes.forEach((mesh) => { Utility.remove_object_with_children(mesh) })
+ this.skinned_meshes = skinned_meshes
+ this.mesh2motion_engine.get_scene().add(...skinned_meshes)
+ this.preview.set_skinned_meshes(skinned_meshes)
+
+ this.rebuild_skeleton_helper(skeleton)
+ this.apply_wireframe_setting()
+ }
+
+ private rebuild_skeleton_helper (skeleton: Skeleton): void {
+ this.mesh2motion_engine.regenerate_skeleton_helper(skeleton)
+ this.mesh2motion_engine.sync_skeleton_helper_joint_visibility()
+
+ if (this.mesh2motion_engine.skeleton_helper !== undefined) {
+ this.mesh2motion_engine.skeleton_helper.visible = this.mesh2motion_engine.ui.dom_show_skeleton_checkbox?.checked ?? false
+ }
+ }
+
+ // a newly loaded model should match the wireframe toggle
+ private apply_wireframe_setting (): void {
+ const is_wireframe: boolean = this.mesh2motion_engine.ui.dom_wireframe_checkbox?.checked ?? false
+ this.skinned_meshes.forEach((mesh) => {
+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material]
+ materials.forEach((material) => {
+ if ('wireframe' in material) {
+ material.wireframe = is_wireframe
+ }
+ })
+ })
+ }
+
+ private add_event_listeners (): void {
+ this.slots.addEventListener('slot-animation-dropped', (event: Event) => {
+ const { slot, animation_id } = (event as CustomEvent<SlotAnimationDroppedDetail>).detail
+ this.change_slot_animation(slot, animation_id)
+ })
+
+ this.custom_animation_importer.addEventListener('import-success', (event: Event) => {
+ const new_clips = (event as CustomEvent<TransformedAnimationClipPair[]>).detail
+ this.add_imported_animations(new_clips)
+ })
+ }
+
+ /**
+ * Adds imported animations to the library list so they can be dragged onto a slot.
+ */
+ private add_imported_animations (clip_pairs: TransformedAnimationClipPair[]): void {
+ const new_entries: AnimationEntry[] = this.animation_library.add_loaded_clips(clip_pairs)
+ this.library_list?.set_animations(this.animation_library.all())
+ this.render_slots()
+
+ if (new_entries.length > 0) {
+ this.library_list?.scroll_to_animation(new_entries[0].id)
+ }
+ }
+
+ /**
+ * Puts an animation from the library into one of the slots and rebuilds the preview.
+ * If the animation fails to download, the slot goes back to what it had before.
+ */
+ public async set_slot_animation (slot: ComposerSlotName, animation_id: string): Promise<void> {
+ if (this.animation_library.find(animation_id) === undefined) {
+ throw new Error(`Unknown animation: ${animation_id}`)
+ }
+
+ const previous_animation_id: string | null = this.slot_animation_ids[slot]
+ this.slot_animation_ids[slot] = animation_id
+
+ try {
+ await this.update_composition()
+ } catch (error) {
+ // the preview still plays the previous result, which matches the restored slot
+ this.slot_animation_ids[slot] = previous_animation_id
+ this.render_slots()
+ this.composer_export.set_export_ready(this.composed_clip !== null)
+ throw error
+ }
+ }
+
+ public get_composed_clip (): AnimationClip | null {
+ return this.composed_clip
+ }
+
+ // UI handlers don't wait for the result, so failures are reported here
+ private change_slot_animation (slot: ComposerSlotName, animation_id: string): void {
+ this.set_status('')
+ this.set_slot_animation(slot, animation_id).catch((error: unknown) => {
+ console.error(`Failed to put ${animation_id} in the ${slot} slot:`, error)
+ const name = ComposerLibraryList.display_name(this.animation_library.find(animation_id)?.name ?? animation_id)
+ this.set_status(`Couldn't load ${name}. Check your connection and try again.`)
+ })
+ }
+
+ /**
+ * Downloads the animations in both slots (if needed) and plays the result.
+ */
+ private async update_composition (): Promise<void> {
+ // shows the new animation name right away, with a loading marker until it downloads
+ this.render_slots()
+
+ const upper_id = this.slot_animation_ids.upper
+ const lower_id = this.slot_animation_ids.lower
+
+ // before the model loads there is nothing to preview yet. init() composes once it is ready
+ if (upper_id === null || lower_id === null || this.upper_body_bone_names.size === 0) {
+ return
+ }
+
+ // slots can change again while animations download. only the newest request gets to update the preview
+ const request_id: number = ++this.composition_request_id
+
+ // the current result no longer matches the slots, so don't let it be downloaded
+ this.composer_export.set_export_ready(false)
+
+ const [upper_entry, lower_entry] = await this.animation_library.load_many([upper_id, lower_id])
+ if (request_id !== this.composition_request_id) {
+ return
+ }
+ this.render_slots()
+
+ const upper_clip = upper_entry.clip_pair?.display_animation_clip
+ const lower_clip = lower_entry.clip_pair?.display_animation_clip
+ if (upper_clip === undefined || lower_clip === undefined) {
+ throw new Error('Slot animations finished loading without animation data')
+ }
+
+ this.composed_clip = ComposerClipBuilder.compose_clip({
+ upper_clip,
+ lower_clip,
+ upper_body_bone_names: this.upper_body_bone_names,
+ fps: RigConfig.by_skeleton_type(ComposerConfig.skeleton_type)?.fps ?? ComposerModule.fallback_fps,
+ name: `${upper_entry.name}_${lower_entry.name}_Remix`
+ })
+ this.preview.play_clip(this.composed_clip)
+
+ this.composer_export.set_export_name(this.composed_clip.name)
+ this.composer_export.set_export_ready(true)
+ }
+
+ private render_slots (): void {
+ ComposerSlots.slot_names.forEach((slot) => {
+ const animation_id = this.slot_animation_ids[slot]
+ const entry = animation_id === null ? undefined : this.animation_library.find(animation_id)
+ if (entry === undefined) {
+ return
+ }
+
+ this.slots.show(slot, {
+ animation_name: entry.name,
+ is_loading: entry.state !== 'loaded'
+ })
+ })
+
+ this.library_list?.set_slot_markers(this.slot_animation_ids.upper, this.slot_animation_ids.lower)
+ }
+
+ private find_default_animation (): AnimationEntry | undefined {
+ return this.animation_library.all().find(entry => entry.name === ComposerConfig.default_animation_name)
+ }
+
+ private set_status (message: string): void {
+ if (this.dom_status !== null) {
+ this.dom_status.textContent = message
+ this.dom_status.style.display = message === '' ? 'none' : 'block'
+ }
+ }
+}
+
+const composer_app = new ComposerModule()
+
+// handy for trying combinations from the browser console during development
+if (import.meta.env.DEV) {
+ (window as unknown as { composer_app: ComposerModule }).composer_app = composer_app
+}
+
+document.addEventListener('DOMContentLoaded', () => {
+ composer_app.start()
+})
diff --git a/src/composer/index.html b/src/composer/index.html
new file mode 100644
index 0000000..17c6e78
--- /dev/null
+++ b/src/composer/index.html
@@ -0,0 +1,109 @@
+<!DOCTYPE html>
+<html lang="en">
+
+ <head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Remix - Mesh2Motion</title>
+ <link rel="icon" type="image/png" href="../images/favicon.png"/>
+
+ <!-- Stylesheets-->
+ <link href="../styles.css" rel="stylesheet" crossorigin="anonymous" />
+ <link rel="stylesheet" href="../radio-button-group.css" crossorigin="anonymous" />
+ <link rel="stylesheet" href="../animation-player.css" crossorigin="anonymous" />
+ <link rel="stylesheet" href="../settings-dropdown.css" crossorigin="anonymous" />
+ <link rel="stylesheet" href="../dialog.css" crossorigin="anonymous" />
+ <link rel="stylesheet" href="../offline.css" crossorigin="anonymous" /> <link rel="stylesheet" href="./composer.css" crossorigin="anonymous" />
+ </head>
+
+ <body style="margin: 0">
+
+ <nav>
+ <div style="display: inline-flex; align-items: center;">
+ <a id="logo-branding" href="https://mesh2motion.org">
+ <img src="../images/mesh2motion.svg" width="130" alt="Mesh2Motion logo" />
+ </a>
+ <a href="/">Explore</a>
+ <a href="/create.html">Use Your Model</a>
+ <a href="/retarget/index.html">Use Your Rigged Model</a>
+ <span class="active-nav-item">Remix</span>
+ </div>
+
+ <div style="display: inline-flex; align-items: center;">
+ <div id="top-nav-links-mount"></div>
+ </div>
+ </nav>
+
+ <div id="header-ui-mount"></div>
+
+ <!-- Tool Options Panel -->
+ <div id="tool-panel">
+ <div id="composer-panel">
+ <h1>Remix Animations</h1>
+ <p class="composer-intro">Create a new animation by dragging animations to the upper and lower animation slots.</p>
+
+ <div id="composer-status" style="display: none"></div>
+
+ <!-- slots that hold the animation for each half of the body. library tiles are dropped here -->
+ <div id="composer-slots">
+ <div id="composer-upper-slot" class="composer-slot" data-slot="upper" title="Drop an animation here">
+ <svg class="composer-slot-figure" viewBox="0 0 40 64" aria-hidden="true">
+ <circle class="figure-upper" cx="20" cy="7" r="6" />
+ <rect class="figure-upper" x="13" y="14" width="14" height="17" rx="3" />
+ <rect class="figure-upper" x="6" y="15" width="5" height="17" rx="2.5" />
+ <rect class="figure-upper" x="29" y="15" width="5" height="17" rx="2.5" />
+ <rect class="figure-lower" x="13" y="32" width="14" height="6" rx="2" />
+ <rect class="figure-lower" x="13" y="39" width="6" height="22" rx="3" />
+ <rect class="figure-lower" x="21" y="39" width="6" height="22" rx="3" />
+ </svg>
+ <span class="composer-slot-animation-name">—</span>
+ </div>
+
+ <div id="composer-lower-slot" class="composer-slot" data-slot="lower" title="Drop an animation here">
+ <svg class="composer-slot-figure" viewBox="0 0 40 64" aria-hidden="true">
+ <circle class="figure-upper" cx="20" cy="7" r="6" />
+ <rect class="figure-upper" x="13" y="14" width="14" height="17" rx="3" />
+ <rect class="figure-upper" x="6" y="15" width="5" height="17" rx="2.5" />
+ <rect class="figure-upper" x="29" y="15" width="5" height="17" rx="2.5" />
+ <rect class="figure-lower" x="13" y="32" width="14" height="6" rx="2" />
+ <rect class="figure-lower" x="13" y="39" width="6" height="22" rx="3" />
+ <rect class="figure-lower" x="21" y="39" width="6" height="22" rx="3" />
+ </svg>
+ <span class="composer-slot-animation-name">—</span>
+ </div>
+ </div>
+
+ <!-- animation library. tiles are dragged onto the slots above -->
+ <div id="composer-library">
+ <div class="composer-library-filter-wrap">
+ <input type="text" id="composer-library-filter" placeholder="Filter animations" aria-label="Filter animations">
+ <span id="composer-library-count" aria-live="polite">0 results</span>
+ </div>
+ <div id="composer-library-items"></div>
+ </div>
+
+ <!-- download the result with the shared download options -->
+ <!-- same layout as the Explore page: import button to the left of the download control.
+ CustomAnimationImporter binds to these ids -->
+ <div id="composer-export" class="download-actions-row">
+ <button class="secondary-button" id="import-animations-button" disabled data-tippy-content="Import GLB or FBX animations. Mesh2Motion rigs are supported, and Mixamo animations can be retargeted onto the Human rig." aria-label="Import GLB or FBX animations. Mesh2Motion rigs are supported, and Mixamo animations can be retargeted onto the Human rig.">
+ <img src="../images/icons/upload.svg" alt="Upload" width="20" height="20" />
+ </button>
+ <input id="import-animations-input" type="file" accept=".glb,.fbx" multiple style="display:none" />
+
+ <div id="download-control-mount"></div>
+ </div>
+ </div>
+ </div>
+
+ <div id="animation-player-mount"></div>
+
+ <!-- 3d view controls shown on bottom right. This helps with click events -->
+ <div id="view-control-hitbox"></div>
+
+ <!-- build version information-->
+ <span id="build-version"></span>
+
+ <script type="module" src="./composer.ts"></script>
+ </body>
+</html>
diff --git a/src/create.html b/src/create.html
index c93b845..6d089ec 100644
--- a/src/create.html
+++ b/src/create.html
@@ -34,6 +34,7 @@
<a href="/">Explore</a>
<span class="active-nav-item">Use Your Model</span>
<a href="/retarget/index.html">Use Your Rigged Model</a>
+ <a href="/composer/index.html">Remix</a>
</div>
<div style="display: inline-flex; align-items: center;">
diff --git a/src/dialog.css b/src/dialog.css
index 2fe4058..d95ac77 100644
--- a/src/dialog.css
+++ b/src/dialog.css
@@ -186,7 +186,7 @@
}
.variation-loading-text {
- color: var(--text-alternate);
+ color: var(--text-primary);
white-space: nowrap;
flex-shrink: 0;
}
diff --git a/src/index.html b/src/index.html
index 5b60b1f..609e9a4 100644
--- a/src/index.html
+++ b/src/index.html
@@ -29,6 +29,7 @@
<span class="active-nav-item">Explore</span>
<a href="/create.html">Use Your Model</a>
<a href="/retarget/index.html">Use Your Rigged Model</a>
+ <a href="/composer/index.html">Remix</a>
</div>
<div style="display: inline-flex; align-items: center;">
diff --git a/src/lib/DOMUtilities.ts b/src/lib/DOMUtilities.ts
index c5a8933..1c01f8f 100644
--- a/src/lib/DOMUtilities.ts
+++ b/src/lib/DOMUtilities.ts
@@ -80,8 +80,6 @@ export class DOMUtilities {
mount.style.alignItems = 'center'
mount.innerHTML = `
- <a href="#" id="learn-link">Learn</a>
- <a href="#" id="attribution-link">Contributors</a>
<a href="${nav_links.support_href}" id="nav-support-mesh2motion" target="_blank">💗</a>
<a href="${nav_links.github_href}" id="nav-github" target="_blank">
<img src="${nav_links.github_icon_src}" width="24" height="24" alt="GitHub" />
@@ -266,6 +264,16 @@ export class DOMUtilities {
private static get_download_control_config (): DownloadControlConfig {
const defaults = DOMUtilities.download_control_defaults
+ // the composer exports one animation it builds itself, so it needs its own button id
+ // to stay clear of the Explore export handler that listens for 'export-button'
+ if (DOMUtilities.is_composer_page()) {
+ return {
+ export_button_id: 'export-composer-button',
+ download_icon_src: '../images/icons/download.svg',
+ tooltip: 'Download the composed animation as a single file.'
+ }
+ }
+
if (DOMUtilities.is_retarget_page()) {
return {
export_button_id: 'export-retargeting-button',
@@ -278,7 +286,7 @@ export class DOMUtilities {
}
private static get_download_settings_icon_src (): string {
- if (DOMUtilities.is_retarget_page()) {
+ if (DOMUtilities.is_retarget_page() || DOMUtilities.is_composer_page()) {
return '../images/icons/arrow-dropdown.svg'
}
@@ -394,6 +402,11 @@ export class DOMUtilities {
return path_name.includes('/retarget/')
}
+ private static is_composer_page (): boolean {
+ const path_name = window.location.pathname.toLowerCase()
+ return path_name.includes('/composer/')
+ }
+
/**
* Render shared nav settings dropdown markup into the provided mount element.
*/
@@ -442,6 +455,11 @@ export class DOMUtilities {
<label for="solid-background-toggle">Solid background</label>
<input type="checkbox" id="solid-background-toggle" ${defaults.solid_background_enabled ? 'checked' : ''} />
</div>
+
+ <hr class="settings-dropdown-divider" />
+
+ <a href="#" id="learn-link" class="settings-dropdown-row settings-dropdown-link">Learn</a>
+ <a href="#" id="attribution-link" class="settings-dropdown-row settings-dropdown-link">Contributors</a>
</div>
</div>
`
diff --git a/src/lib/EventListeners.ts b/src/lib/EventListeners.ts
index bed0cfd..048939c 100644
--- a/src/lib/EventListeners.ts
+++ b/src/lib/EventListeners.ts
@@ -278,7 +278,7 @@ export class EventListeners {
this.bootstrap.ui.dom_wireframe_checkbox?.addEventListener('change', (event: Event) => {
const is_wireframe = (event.target as HTMLInputElement).checked
- const skinned_meshes = this.bootstrap.animations_listing_step.active_skinned_meshes()
+ const skinned_meshes = this.bootstrap.active_skinned_meshes()
skinned_meshes.forEach((mesh) => {
const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material]
materials.forEach((mat: Material) => {
diff --git a/src/lib/SettingsDropdownManager.ts b/src/lib/SettingsDropdownManager.ts
index ee47f48..a96b063 100644
--- a/src/lib/SettingsDropdownManager.ts
+++ b/src/lib/SettingsDropdownManager.ts
@@ -50,6 +50,11 @@ export class SettingsDropdownManager {
}
})
+ // close the menu when one of its links (Learn, Contributors) opens a dialog
+ dropdown_content.querySelectorAll('.settings-dropdown-link').forEach((link) => {
+ link.addEventListener('click', () => { this.close_dropdown() })
+ })
+
document.addEventListener('keydown', (event: KeyboardEvent) => {
if (event.key === 'Escape') {
this.close_dropdown()
diff --git a/src/lib/Utilities.ts b/src/lib/Utilities.ts
index 71052ac..6a26983 100644
--- a/src/lib/Utilities.ts
+++ b/src/lib/Utilities.ts
@@ -1,5 +1,5 @@
import {
- Vector3, Vector2, type Object3D, Mesh, Group, Bone, type Skeleton, Euler, Raycaster,
+ Vector3, Vector2, type Object3D, Mesh, Group, Bone, type Skeleton, type SkinnedMesh, Euler, Raycaster,
type PerspectiveCamera, type Scene, type Object3DEventMap, type BufferAttribute, type BufferGeometry, type InterleavedBufferAttribute
} from 'three'
import BoneTransformState from './interfaces/BoneTransformState'
@@ -68,6 +68,25 @@ export class Utility {
})
}
+ /**
+ * Re-parents each skeleton's root bone to be a child of its skinned mesh.
+ * Pre-rigged model GLBs (like model variations) keep their bones beside the mesh. This matches
+ * the structure created by StepWeightSkin, so the export path can treat both cases identically.
+ */
+ static parent_root_bones_to_skinned_meshes (skinned_meshes: SkinnedMesh[]): void {
+ const processed_skeletons = new Set<Skeleton>()
+
+ for (const mesh of skinned_meshes) {
+ if (processed_skeletons.has(mesh.skeleton)) continue
+ processed_skeletons.add(mesh.skeleton)
+
+ const root_bone = mesh.skeleton.bones[0]
+ if (root_bone !== undefined) {
+ mesh.add(root_bone)
+ }
+ }
+ }
+
static remove_object_with_children (obj: Object3D): void {
if (obj.children.length > 0) {
obj.children.forEach((child: Object3D) => {
diff --git a/src/lib/processes/animations-listing/AnimationPreviewVideos.ts b/src/lib/processes/animations-listing/AnimationPreviewVideos.ts
new file mode 100644
index 0000000..08fa368
--- /dev/null
+++ b/src/lib/processes/animations-listing/AnimationPreviewVideos.ts
@@ -0,0 +1,72 @@
+import { type SkeletonType } from '../../enums/SkeletonType'
+import { RigConfig } from '../../RigConfig'
+
+/**
+ * Looping MP4 previews for library animations. Lists can hold hundreds of animations and only so many
+ * videos can play at once, so placeholders are only turned into videos once they scroll into view.
+ */
+export class AnimationPreviewVideos {
+ private observer: IntersectionObserver | null = null
+
+ /**
+ * URL of the preview video for a library animation. Custom imports have no preview.
+ * @returns null if the rig is not in RigConfig
+ */
+ static preview_src (skeleton_type: SkeletonType, theme_name: string, animation_name: string): string | null {
+ const preview_folder: string | undefined = RigConfig.by_skeleton_type(skeleton_type)?.animation_preview_folder
+ if (preview_folder === undefined) {
+ console.error('Unknown skeleton type for animation previews. Add the rig to RigConfig.ts.')
+ return null
+ }
+ return `../animpreviews/${preview_folder}/${theme_name}_${animation_name}.mp4`
+ }
+
+ static create_video (src: string, width: number = 100, height: number = 120): HTMLVideoElement {
+ const video = document.createElement('video')
+ video.className = 'anim-preview'
+ video.src = src
+ video.width = width
+ video.height = height
+ video.loop = true
+ video.muted = true
+ video.playsInline = true // tells mobile browsers to play inline instead of going fullscreen
+ video.autoplay = true
+ return video
+ }
+
+ /**
+ * Watches every '.anim-preview-placeholder' with a data-src in the container and swaps in a
+ * video once it comes into view. Stops watching any placeholders from a previous call.
+ */
+ public observe_placeholders (container: HTMLElement): void {
+ this.disconnect()
+
+ this.observer = new IntersectionObserver((entries: IntersectionObserverEntry[]) => {
+ entries.forEach((entry) => {
+ const placeholder = entry.target as HTMLElement
+
+ // abort if animation entry is outside active viewing area (but don't unload - causes popping)
+ if (!entry.isIntersecting || placeholder.querySelector('video') !== null) {
+ return
+ }
+
+ const src = placeholder.getAttribute('data-src')
+ if (src === null || src === '') {
+ return
+ }
+
+ placeholder.innerHTML = ''
+ placeholder.appendChild(AnimationPreviewVideos.create_video(src))
+ })
+ }, { rootMargin: '300px' }) // rootMargin pre-loads videos before they scroll into view to reduce popping
+
+ container.querySelectorAll('.anim-preview-placeholder').forEach((placeholder) => {
+ this.observer?.observe(placeholder)
+ })
+ }
+
+ public disconnect (): void {
+ this.observer?.disconnect()
+ this.observer = null
+ }
+}
diff --git a/src/lib/processes/animations-listing/AnimationSearch.ts b/src/lib/processes/animations-listing/AnimationSearch.ts
index 8896b1a..6e202f6 100644
--- a/src/lib/processes/animations-listing/AnimationSearch.ts
+++ b/src/lib/processes/animations-listing/AnimationSearch.ts
@@ -1,6 +1,6 @@
import { type ThemeManager } from '../../ThemeManager'
import { SkeletonType } from '../../enums/SkeletonType'
-import { RigConfig } from '../../RigConfig'
+import { AnimationPreviewVideos } from './AnimationPreviewVideos'
import { type AnimationWithState } from './interfaces/AnimationWithState'
import { type AnimationEntry } from './interfaces/AnimationEntry'
import { type AnimationExportSelection, type AnimationMirrorExportMode } from './interfaces/AnimationExportSelection'
@@ -28,7 +28,7 @@ export class AnimationSearch extends EventTarget {
private readonly row_elements = new Map<string, HTMLElement>()
private no_animations_message: HTMLElement | null = null
private request_animation_tile: HTMLElement | null = null
- private lazy_video_observer: IntersectionObserver | null = null
+ private readonly preview_videos: AnimationPreviewVideos = new AnimationPreviewVideos()
private static readonly mirror_mode_cycle: AnimationMirrorExportMode[] = ['none', 'mirrored', 'both']
@@ -411,28 +411,23 @@ export class AnimationSearch extends EventTarget {
return
}
- this.lazy_video_observer?.disconnect()
+ this.preview_videos.disconnect()
this.row_elements.clear()
+ const theme_name: string = this.theme_manager.get_current_theme()
+
const rows_html = this.all_animations.map((animation_clip) => {
// Check if this animation was previously checked
const was_checked: boolean = animation_clip.isChecked ?? false
const checked_attribute = was_checked ? 'checked' : ''
- // build out where the video previews will be stored
- // each skeleton type has its own folder
- const preview_folder: string = RigConfig.by_skeleton_type(this.skeleton_type)?.animation_preview_folder ?? 'error'
- if (preview_folder === 'error') {
- console.error('Unknown skeleton type for animation previews. Add the rig to RigConfig.ts.')
- }
-
- const anim_name: string = animation_clip.name
- const theme_name: string = this.theme_manager.get_current_theme()
const is_custom_animation = animation_clip.metadata?.source_type === 'custom-import'
- const preview_data_src_attribute = is_custom_animation
- ? ''
- : ` data-src="../animpreviews/${preview_folder}/${theme_name}_${anim_name}.mp4"`
+ // each skeleton type has its own folder of preview videos. custom imports have none
+ const preview_src: string | null = is_custom_animation
+ ? null
+ : AnimationPreviewVideos.preview_src(this.skeleton_type, theme_name, animation_clip.name)
+ const preview_data_src_attribute = preview_src === null ? '' : ` data-src="${preview_src}"`
const custom_animation_badge_html = is_custom_animation
? '<span class="anim-custom-badge" title="Custom animation" aria-label="Custom animation">C</span>'
@@ -487,54 +482,9 @@ export class AnimationSearch extends EventTarget {
this.render_filtered_animations(this.filter_input?.value.toLowerCase() ?? '')
- // only so many WebM videos can be playing at the same time
+ // only so many videos can be playing at the same time
// so this is an optimization to convert only elements in the active scroll area to video elements
- this.setup_lazy_video_loading()
- }
-
- /**
- * Sets up lazy loading for video previews using Intersection Observer.
- * Only loads video elements when their placeholders are visible in the viewport.
- */
- private setup_lazy_video_loading (): void {
- // Only set up IntersectionObserver if the container exists
- // any animation entry that is in view will run this code to convert it to a video element
- this.lazy_video_observer = new IntersectionObserver((entries: IntersectionObserverEntry[], _obs: IntersectionObserver) => {
- entries.forEach(entry => {
- const placeholder = entry.target as HTMLElement
-
- // abort if animation entry is outside active viewing area (but don't unload - causes popping)
- if (!entry.isIntersecting) {
- return
- }
-
- // if element is already a video, and it is in view, don't convert
- // it to a video again, it is ok so abort any further work
- const existing_video = placeholder.querySelector('video')
- if (existing_video != null) {
- return
- }
-
- // element that just came into view and needs to be converted
- // to a video element
- const video = document.createElement('video')
- video.className = 'anim-preview'
- const src = placeholder.getAttribute('data-src') ?? ''
- video.src = src
- video.width = 100
- video.height = 120
- video.loop = true
- video.muted = true
- video.playsInline = true // tells mobile browsers to play inline instead of going fullscreen
- video.autoplay = true
- placeholder.innerHTML = ''
- placeholder.appendChild(video)
- })
- }, { rootMargin: '300px' }) // rootMargin pre-loads videos before they scroll into view to reduce popping
-
- // grabs all the animation list elements and tells the observer to start watching them for processing
- const placeholders = this.animation_list_container?.querySelectorAll('.anim-preview-placeholder')
- placeholders?.forEach(ph => { this.lazy_video_observer?.observe(ph) })
+ this.preview_videos.observe_placeholders(this.animation_list_container)
}
public animation_name_clean (input: string): string {
diff --git a/src/lib/processes/animations-listing/CustomAnimationImporter.ts b/src/lib/processes/animations-listing/CustomAnimationImporter.ts
index dbe8dbe..bddcd02 100644
--- a/src/lib/processes/animations-listing/CustomAnimationImporter.ts
+++ b/src/lib/processes/animations-listing/CustomAnimationImporter.ts
@@ -1,4 +1,3 @@
-import { UI } from '../../UI.ts'
import { ModalDialog } from '../../ModalDialog.ts'
import { type AnimationClip, type SkinnedMesh } from 'three'
import { type AnimationLoader, type LoadedAnimationSource } from './AnimationLoader.ts'
@@ -15,27 +14,23 @@ export interface AnimationImportContext {
}
/**
- * Handles the importing of custom animations from GLB and FBX files.
- * This class encapsulates the UI and logic for the import process.
+ * Imports custom animations from GLB and FBX files.
+ * This is only the import logic: it doesn't touch the DOM. Whatever page owns the import
+ * button wires it up (see ImportAnimationsButton) and hands the chosen files to import_files().
*
* Animations authored on the Mesh2Motion rig are used as they are. Animations authored on
* another humanoid rig (Mixamo, etc) are retargeted onto the human skeleton.
*/
export class CustomAnimationImporter extends EventTarget {
- private readonly ui: UI
private readonly animation_loader: AnimationLoader
private skinned_meshes_to_animate: SkinnedMesh[] = []
private skeleton_scale: number = 1.0
private skeleton_type: SkeletonType = SkeletonType.None
private import_context_provider: (() => AnimationImportContext) | null = null
- private enabled: boolean = true
- private has_added_event_listeners: boolean = false
constructor (animation_loader: AnimationLoader) {
super()
- this.ui = UI.getInstance()
this.animation_loader = animation_loader
- this.add_event_listeners()
}
public set_import_context (context: AnimationImportContext): void {
@@ -48,65 +43,20 @@ export class CustomAnimationImporter extends EventTarget {
this.import_context_provider = provider
}
- public set_enabled (enabled: boolean): void {
- this.enabled = enabled
- if (this.ui.dom_import_animations_button != null) {
- this.ui.dom_import_animations_button.disabled = !enabled
- }
- }
-
- public is_enabled (): boolean {
- return this.enabled
- }
-
- private add_event_listeners (): void {
- if (this.has_added_event_listeners) {
- return
- }
-
- this.ui.dom_import_animations_button?.addEventListener('click', () => {
- if (!this.is_enabled()) {
- return
- }
- this.sync_import_context_from_provider()
- this.ui.dom_import_animations_input?.click()
- })
-
- this.ui.dom_import_animations_input?.addEventListener('change', (event) => {
- void this.handle_import_animations_input_change(event)
- })
-
- this.has_added_event_listeners = true
- }
-
- private async handle_import_animations_input_change (event: Event): Promise<void> {
- if (!this.is_enabled()) {
- return
- }
-
+ /**
+ * Imports each file in turn. Results are shown in dialogs, and every successful file
+ * dispatches an 'import-success' event with its clips.
+ */
+ public async import_files (files: File[]): Promise<void> {
this.sync_import_context_from_provider()
- // potentially allow multiple files
- const input = event.target as HTMLInputElement
- const files = input.files
- if (files === null || files.length === 0) {
- return
- }
-
- this.set_enabled(false) // disable to prevent double-clicks during processing
-
- try {
- for (const file of Array.from(files)) {
- const file_name = file.name.toLowerCase()
- if (!file_name.endsWith('.glb') && !file_name.endsWith('.fbx')) {
- new ModalDialog('Unsupported file type. Please select a GLB or FBX file.', 'Error').show()
- continue
- }
- await this.import_animation_file(file)
+ for (const file of files) {
+ const file_name = file.name.toLowerCase()
+ if (!file_name.endsWith('.glb') && !file_name.endsWith('.fbx')) {
+ new ModalDialog('Unsupported file type. Please select a GLB or FBX file.', 'Error').show()
+ continue
}
- } finally {
- input.value = ''
- this.set_enabled(true)
+ await this.import_animation_file(file)
}
}
diff --git a/src/lib/processes/animations-listing/ImportAnimationsButton.ts b/src/lib/processes/animations-listing/ImportAnimationsButton.ts
new file mode 100644
index 0000000..7dc55bc
--- /dev/null
+++ b/src/lib/processes/animations-listing/ImportAnimationsButton.ts
@@ -0,0 +1,89 @@
+import { type CustomAnimationImporter } from './CustomAnimationImporter.ts'
+
+/**
+ * Connects an "Import animations" button and its hidden file input to a CustomAnimationImporter.
+ * Only the page (or step) that is currently showing the button should create one, and it
+ * should dispose() it when it is done so listeners never stack up on the shared elements.
+ */
+export class ImportAnimationsButton {
+ private readonly importer: CustomAnimationImporter
+ private readonly button: HTMLButtonElement | null
+ private readonly input: HTMLInputElement | null
+ private readonly listeners_abort_controller: AbortController = new AbortController()
+ private enabled: boolean = true
+ private is_importing: boolean = false
+
+ constructor (
+ importer: CustomAnimationImporter,
+ button: HTMLButtonElement | null,
+ input: HTMLInputElement | null
+ ) {
+ this.importer = importer
+ this.button = button
+ this.input = input
+ this.add_event_listeners()
+ this.update_button_state()
+ }
+
+ /**
+ * Turns the button off, for example until there is a model to validate imports against
+ */
+ public set_enabled (enabled: boolean): void {
+ this.enabled = enabled
+ this.update_button_state()
+ }
+
+ /**
+ * Removes the listeners from the button and input
+ */
+ public dispose (): void {
+ this.listeners_abort_controller.abort()
+ }
+
+ private can_import (): boolean {
+ return this.enabled && !this.is_importing
+ }
+
+ private update_button_state (): void {
+ if (this.button !== null) {
+ this.button.disabled = !this.can_import()
+ }
+ }
+
+ private add_event_listeners (): void {
+ const signal: AbortSignal = this.listeners_abort_controller.signal
+
+ this.button?.addEventListener('click', () => {
+ if (this.can_import()) {
+ this.input?.click()
+ }
+ }, { signal })
+
+ this.input?.addEventListener('change', () => {
+ void this.import_selected_files()
+ }, { signal })
+ }
+
+ private async import_selected_files (): Promise<void> {
+ if (this.input === null || !this.can_import()) {
+ return
+ }
+
+ const files: File[] = Array.from(this.input.files ?? [])
+ if (files.length === 0) {
+ return
+ }
+
+ // off while importing to prevent double-clicks during processing
+ this.is_importing = true
+ this.update_button_state()
+
+ try {
+ await this.importer.import_files(files)
+ } finally {
+ this.input.value = '' // lets the same file be picked again
+ this.is_importing = false
+ this.update_button_state()
+ }
+ }
+}
diff --git a/src/lib/processes/animations-listing/ModelVariationSwitcher.ts b/src/lib/processes/animations-listing/ModelVariationSwitcher.ts
index 33a29ba..451375a 100644
--- a/src/lib/processes/animations-listing/ModelVariationSwitcher.ts
+++ b/src/lib/processes/animations-listing/ModelVariationSwitcher.ts
@@ -1,4 +1,5 @@
-import { Skeleton, SkinnedMesh } from 'three'
+import { SkinnedMesh } from 'three'
+import { Utility } from '../../Utilities'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import tippy from 'tippy.js'
import { RigConfig, type ModelVariation, type RigConfigEntry } from '../../RigConfig'
@@ -250,7 +251,7 @@ export class ModelVariationSwitcher extends EventTarget {
}
})
- this.normalize_skinned_meshes(skinned_meshes)
+ Utility.parent_root_bones_to_skinned_meshes(skinned_meshes)
this.dispatchEvent(new CustomEvent('variation-changed', {
detail: { model_file, skinned_meshes, expandArms: expand_arms, pelvis_position_scale }
@@ -271,25 +272,6 @@ export class ModelVariationSwitcher extends EventTarget {
)
}
- /**
- * Re-parents each skeleton's root bone to be a child of its skinned mesh.
- * This matches the structure created by StepWeightSkin in the normal pipeline,
- * so the export path can treat both cases identically.
- */
- private normalize_skinned_meshes (skinned_meshes: SkinnedMesh[]): void {
- const processed_skeletons = new Set<Skeleton>()
-
- for (const mesh of skinned_meshes) {
- if (processed_skeletons.has(mesh.skeleton)) continue
- processed_skeletons.add(mesh.skeleton)
-
- const root_bone = mesh.skeleton.bones[0]
- if (root_bone !== undefined) {
- mesh.add(root_bone)
- }
- }
- }
-
private add_event_listeners (): void {
if (this.added_event_listeners) return
this.added_event_listeners = true
diff --git a/src/lib/processes/animations-listing/StepAnimationsListing.ts b/src/lib/processes/animations-listing/StepAnimationsListing.ts
index dca92b5..c14a6aa 100644
--- a/src/lib/processes/animations-listing/StepAnimationsListing.ts
+++ b/src/lib/processes/animations-listing/StepAnimationsListing.ts
@@ -11,6 +11,7 @@ import { AnimationLoader, type AnimationLoadProgress } from './AnimationLoader.t
import { AnimationLibrary, type AnimationLibraryLoadProgress } from './AnimationLibrary.ts'
import { AnimationLibraryProgressBar } from './AnimationLibraryProgressBar.ts'
import { CustomAnimationImporter } from './CustomAnimationImporter.ts'
+import { ImportAnimationsButton } from './ImportAnimationsButton.ts'
import { type ModelVariationSwitcher } from './ModelVariationSwitcher.ts'
import { SkeletonType } from '../../enums/SkeletonType.ts'
@@ -47,6 +48,8 @@ export class StepAnimationsListing extends EventTarget {
private model_variation_pelvis_position_scale: number = 1.0
private readonly custom_animation_importer: CustomAnimationImporter
+ // wired up in begin() so pages that never show this step don't listen to the import button
+ private import_animations_button: ImportAnimationsButton | null = null
private readonly props_manager: PropsManager = new PropsManager()
private _added_event_listeners: boolean = false
@@ -125,7 +128,12 @@ export class StepAnimationsListing extends EventTarget {
}
this.reset_step_data()
- this.custom_animation_importer.set_enabled(true)
+ this.import_animations_button?.dispose()
+ this.import_animations_button = new ImportAnimationsButton(
+ this.custom_animation_importer,
+ this.ui.dom_import_animations_button,
+ this.ui.dom_import_animations_input
+ )
this.skeleton_type = skeleton_type
this.props_manager.begin(skeleton_type, skeleton_scale)
diff --git a/src/lib/processes/animations-listing/props/props.css b/src/lib/processes/animations-listing/props/props.css
index 43d8bf8..118686f 100644
--- a/src/lib/processes/animations-listing/props/props.css
+++ b/src/lib/processes/animations-listing/props/props.css
@@ -56,7 +56,7 @@
flex-direction: row;
align-items: center;
gap: 0.5rem;
- color: var(--text-alternate);
+ color: var(--text-primary);
}
.prop-picker-label {
diff --git a/src/retarget/index.html b/src/retarget/index.html
index 57ceab2..42194ec 100644
--- a/src/retarget/index.html
+++ b/src/retarget/index.html
@@ -27,6 +27,7 @@
<a href="/">Explore</a>
<a href="/create.html" >Use Your Model</a>
<span class="active-nav-item">Use Your Rigged Model</span>
+ <a href="/composer/index.html">Remix</a>
</div>
<div style="display: inline-flex; align-items: center;">
diff --git a/src/settings-dropdown.css b/src/settings-dropdown.css
index 36e7b2f..139e8ea 100644
--- a/src/settings-dropdown.css
+++ b/src/settings-dropdown.css
@@ -62,6 +62,22 @@
height: 16px;
}
+.settings-dropdown-divider {
+ border: none;
+ border-top: 1px solid var(--bg-tertiary);
+ margin: 0.35rem 0;
+}
+
+.settings-dropdown-link {
+ font-size: 0.95rem;
+ color: inherit;
+ text-decoration: none;
+}
+
+.settings-dropdown-link:hover {
+ background: var(--bg-alternate);
+}
+
.settings-dropdown-slider-row {
flex-direction: column;
align-items: flex-start;
diff --git a/src/styles.css b/src/styles.css
index d469ac7..7707aca 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -151,7 +151,7 @@ div, p {
}
#animation-listing-count {
- color: var(--text-alternate)
+ color: var(--text-primary)
}
/* indicator on download buton with how many are selected */
@@ -216,6 +216,7 @@ input[type="text"] {
background-color: var(--bg-primary);
border: 1px solid var(--bg-tertiary);
color: var(--text-primary);
+ font-size: 1rem;
}
input[type="text"]::placeholder {
color: var(--text-primary);
@@ -351,7 +352,8 @@ button:disabled {
}
.download-combo #export-button,
-.download-combo #export-retargeting-button {
+.download-combo #export-retargeting-button,
+.download-combo #export-composer-button {
margin-right: 0;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
@@ -396,6 +398,20 @@ button:disabled {
box-shadow: 0 6px 14px rgba(0, 0, 0, 0.25);
}
+/* light theme: white panel, selected options keep the normal text color */
+[data-theme="light"] .download-settings-panel {
+ background: white;
+}
+
+[data-theme="light"] .download-settings-panel .toggle input:checked + label {
+ background-color: color-mix(in srgb, var(--radio-button-group-bg) 45%, white);
+}
+
+[data-theme="light"] .download-settings-panel .toggle input:checked + label,
+[data-theme="light"] .download-settings-panel .toggle input:checked + label::before {
+ color: var(--text-primary);
+}
+
.download-settings-panel[hidden] {
display: none;
}
@@ -408,7 +424,7 @@ button:disabled {
}
.download-settings-label {
- color: var(--text-alternate);
+ color: var(--text-primary);
font-size: 1.0rem;
white-space: pre; /* no line breaks */
}
@@ -536,7 +552,7 @@ option {
display: inline-flex;
align-items: center;
gap: 0.3rem;
- color: var(--text-alternate);
+ color: var(--text-primary);
}
#model-pose-instructions {
@@ -909,7 +925,7 @@ input[type="file"] {
}
.pill-switch-label {
- color: var(--text-alternate);
+ color: var(--text-primary);
font-size: 0.95rem;
padding: 0;
}
@@ -978,7 +994,7 @@ input[type="file"] {
#selected-bone-overlay .selected-bone-overlay-label {
font-size: 70%;
- color: var(--text-alternate);
+ color: var(--text-primary);
margin:0;
padding:0;
}
@@ -1094,7 +1110,7 @@ div.modal-dialog-body p.survey-thank-you {
left: 0;
padding: 0.5rem 0.7rem;
font-size: 0.8rem;
- color: var(--text-alternate);
+ color: var(--text-primary);
}
/* loading progress bar for animations */
diff --git a/vite.config.js b/vite.config.js
index 01161f5..9912820 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -28,7 +28,8 @@ export default defineConfig({
input: {
main: resolve(__dirname, 'src/index.html'),
create: resolve(__dirname, 'src/create.html'),
- retarget: resolve(__dirname, 'src/retarget/index.html')
+ retarget: resolve(__dirname, 'src/retarget/index.html'),
+ composer: resolve(__dirname, 'src/composer/index.html')
}
}
},