Skip to content

Import a 3D Model and automatically assign and export animations

TypeScript

Start to build out export logic for the retargeted mesh

Scott Petrovic2483b2ae49c9
diff --git a/src/retarget/RetargetAnimationListing.ts b/src/retarget/RetargetAnimationListing.ts
index b312cc6..af3730e 100644
--- a/src/retarget/RetargetAnimationListing.ts
+++ b/src/retarget/RetargetAnimationListing.ts
@@ -7,6 +7,7 @@ import type { ThemeManager } from '../lib/ThemeManager.ts'
import { type TransformedAnimationClipPair } from '../lib/processes/animations-listing/interfaces/TransformedAnimationClipPair.ts'
import { AnimationRetargetService } from './AnimationRetargetService.ts'
import { type StepBoneMapping } from './steps/StepBoneMapping.ts'
+import { StepExportRetargetedAnimations } from './steps/StepExportRetargetedAnimations.ts'
/**
* RetargetAnimationListing - Handles animation listing and playback specifically for retargeting workflow
@@ -17,7 +18,7 @@ export class RetargetAnimationListing extends EventTarget {
private readonly animation_player: AnimationPlayer
private readonly animation_loader: AnimationLoader = new AnimationLoader()
private readonly step_bone_mapping: StepBoneMapping
-
+ private readonly step_export_retargeted_animations: StepExportRetargetedAnimations = new StepExportRetargetedAnimations()
private animation_clips_loaded: TransformedAnimationClipPair[] = []
private animation_mixer: AnimationMixer = new AnimationMixer(new Object3D())
private skinned_meshes_to_animate: SkinnedMesh[] = []
@@ -29,6 +30,8 @@ export class RetargetAnimationListing extends EventTarget {
private is_animations_active: boolean = false
+ private export_button: HTMLButtonElement | null = null
+
constructor (theme_manager: ThemeManager, step_bone_mapping: StepBoneMapping) {
super()
this.theme_manager = theme_manager
@@ -100,11 +103,11 @@ export class RetargetAnimationListing extends EventTarget {
*/
private update_export_button_enabled_state (): void {
// if there are no animations selected disable the download button
- const export_button = document.getElementById('export-retargeting-button') as HTMLButtonElement | null
+
const animations_selected_count: number = this.animation_search?.get_selected_animation_indices().length ?? 0
- if (export_button !== null) {
- export_button.disabled = animations_selected_count === 0
+ if (this.export_button !== null) {
+ this.export_button.disabled = animations_selected_count === 0
}
// update the count inside the export/download button
@@ -221,6 +224,16 @@ export class RetargetAnimationListing extends EventTarget {
// Add any retarget-specific event listeners here
// For now, keeping it minimal
this.setup_animation_loop()
+
+ // configure export animations button
+ this.export_button = document.getElementById('export-retargeting-button') as HTMLButtonElement
+ this.export_button?.addEventListener('click', () => {
+ this.step_export_retargeted_animations.set_animation_clips_to_export(
+ this.animation_clips_loaded.map(clip => clip.display_animation_clip),
+ this.get_selected_animation_indices()
+ )
+ this.step_export_retargeted_animations.export(this.skinned_meshes_to_animate, 'retargeted_animations')
+ })
}
public get_animation_player (): AnimationPlayer {
diff --git a/src/retarget/index.html b/src/retarget/index.html
index 7da19dd..3bf726c 100644
--- a/src/retarget/index.html
+++ b/src/retarget/index.html
@@ -135,6 +135,8 @@
</label>
</div>
+ <!-- I renamed the button ID since we need to process the aniamtions different
+ -->
<button id="export-retargeting-button" title="Export animations. Make sure to select the animations you want to export first.">
<span class="button-icon-group">
<span class="material-symbols-outlined">save_alt</span>
diff --git a/src/retarget/steps/StepExportRetargetedAnimations.ts b/src/retarget/steps/StepExportRetargetedAnimations.ts
new file mode 100644
index 0000000..edfe04f
--- /dev/null
+++ b/src/retarget/steps/StepExportRetargetedAnimations.ts
@@ -0,0 +1,112 @@
+import { Object3D, Scene, SkinnedMesh, type AnimationClip } from "three"
+import { GLTFExporter } from "three/examples/jsm/exporters/GLTFExporter"
+
+export class StepExportRetargetedAnimations extends EventTarget {
+ public animation_clips_to_export: AnimationClip[] = []
+
+ public set_animation_clips_to_export (all_animations_clips: AnimationClip[], animation_checkboxes: number[]): void {
+ this.animation_clips_to_export = []
+ animation_checkboxes.forEach((indx) => {
+ const original_clip: AnimationClip = all_animations_clips[indx]
+ const cloned_clip: AnimationClip = original_clip.clone()
+ this.animation_clips_to_export.push(cloned_clip)
+ })
+ }
+
+ public export (skinned_meshes: SkinnedMesh[], filename = 'exported_model'): void {
+ if (this.animation_clips_to_export.length === 0) {
+ console.log('ERROR: No animation clips added to export')
+ return
+ }
+
+ console.log('Starting the logic to do the exporting')
+ console.log(skinned_meshes)
+ console.log(this.animation_clips_to_export)
+ console.log('--------------------')
+
+ const export_scene = new Scene()
+
+ // When exporting to a file, we need to temporarily move the skinned mesh to a new scene
+ // skinned meshes can only be part of one scene at a time, so we must move it back to
+ // its original parent after exporting
+ const original_parents = new Map<SkinnedMesh, Object3D | null>()
+
+ skinned_meshes.forEach((final_skinned_mesh) => {
+ // Save the original parent
+ original_parents.set(final_skinned_mesh, final_skinned_mesh.parent)
+ export_scene.add(final_skinned_mesh)
+ })
+
+ // TODO: Figure out why the export_scene has no children that contain the skinned mesh
+ console.log('trying to export the following scene as a GLB ', export_scene)
+
+ this.export_glb(export_scene, this.animation_clips_to_export, filename)
+ .then(() => {
+ // Move the skinned meshes back to their original parents
+ skinned_meshes.forEach((final_skinned_mesh) => {
+ const original_par = original_parents.get(final_skinned_mesh)
+ if (original_par != null) {
+ original_par.add(final_skinned_mesh)
+ } else {
+ // If there was no original parent, remove it from the scene
+ export_scene.remove(final_skinned_mesh)
+ console.log('ERROR: No original parent found for skinned mesh when exporting and re-parenting to original scene')
+ }
+ })
+ })
+ .catch((error) => { console.log('Error exporting GLB:', error) })
+ }
+
+ public async export_glb (exported_scene: Scene, animations_to_export: AnimationClip[], file_name: string): Promise<void> {
+ await new Promise<void>((resolve, reject) => {
+ const gltf_exporter = new GLTFExporter()
+
+ const export_options = {
+ binary: true,
+ onlyVisible: false,
+ embedImages: true,
+ animations: animations_to_export
+ }
+
+ gltf_exporter.parse(
+ exported_scene,
+ (result: ArrayBuffer) => {
+ // Handle the result of the export
+ if (result !== null) {
+ this.save_array_buffer(result, `${file_name}.glb`)
+ resolve() // Resolve the promise when the export is complete
+ } else {
+ console.log('ERROR: result is not an instance of ArrayBuffer')
+ reject(new Error('Export result is not an ArrayBuffer'))
+ }
+ },
+ (error: any) => {
+ console.log('An error happened during parsing', error)
+ reject(error) // Reject the promise if an error occurs
+ },
+ export_options
+ )
+ })
+ }
+
+ /**
+ *
+ * @param blob
+ * @param filename
+ */
+ private save_file (blob: Blob, filename: string): void {
+ const export_button_hidden_link: HTMLAnchorElement | null = document.querySelector('#download-hidden-link')
+ if (export_button_hidden_link != null) {
+ export_button_hidden_link.href = URL.createObjectURL(blob)
+ export_button_hidden_link.download = filename
+ export_button_hidden_link.click()
+ } else {
+ console.log('ERROR: dom_export_button_hidden_link is null')
+ }
+ }
+
+ // used for GLB to turn content into a byte array for saving
+ private save_array_buffer (buffer: ArrayBuffer, filename: string): void {
+ this.save_file(new Blob([buffer], { type: 'application/octet-stream' }), filename)
+ }
+}