Import a 3D Model and automatically assign and export animations
TypeScript
Refactor to extract validation logic better
Scott Petrovic9c0f0cf67848
diff --git a/src/lib/processes/animations-listing/AnimationImportErrors.ts b/src/lib/processes/animations-listing/AnimationImportErrors.tsnew file mode 100644index 0000000..f1b7631--- /dev/null+++ b/src/lib/processes/animations-listing/AnimationImportErrors.ts@@ -0,0 +1,21 @@+// Custom error types for better error handling+export class NoAnimationsError extends Error {+ constructor (message: string = 'No animations found in the file.') {+ super(message)+ this.name = 'NoAnimationsError'+ }+}++export class IncompatibleSkeletonError extends Error {+ constructor (message: string = 'Animation skeleton is incompatible with target skeleton.') {+ super(message)+ this.name = 'IncompatibleSkeletonError'+ }+}++export class LoadError extends Error {+ constructor (message: string = 'Failed to load animation file.') {+ super(message)+ this.name = 'LoadError'+ }+}diff --git a/src/lib/processes/animations-listing/AnimationLoader.ts b/src/lib/processes/animations-listing/AnimationLoader.tsindex 9d2bca0..2e73d18 100644--- a/src/lib/processes/animations-listing/AnimationLoader.ts+++ b/src/lib/processes/animations-listing/AnimationLoader.ts@@ -1,8 +1,9 @@import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'-import { type AnimationClip, type SkinnedMesh } from 'three'+import { type AnimationClip } from 'three'import { AnimationUtility } from './AnimationUtility.ts'import { SkeletonType } from '../../enums/SkeletonType.ts'import { type TransformedAnimationClipPair } from './interfaces/TransformedAnimationClipPair.ts'+import { LoadError, NoAnimationsError } from './AnimationImportErrors.ts'export interface AnimationLoadProgress {loaded: number@@ -16,28 +17,6 @@ export interface AnimationLoadProgress {overallBytesTotal: number}-// Custom error types for better error handling-export class NoAnimationsError extends Error {- constructor (message: string = 'No animations found in the file.') {- super(message)- this.name = 'NoAnimationsError'- }-}--export class IncompatibleSkeletonError extends Error {- constructor (message: string = 'Animation skeleton is incompatible with target skeleton.') {- super(message)- this.name = 'IncompatibleSkeletonError'- }-}--export class LoadError extends Error {- constructor (message: string = 'Failed to load animation file.') {- super(message)- this.name = 'LoadError'- }-}-export class AnimationLoader extends EventTarget {private readonly gltf_loader: GLTFLoader = new GLTFLoader()private animations_file_path: string = 'animations/'@@ -146,78 +125,6 @@ export class AnimationLoader extends EventTarget {})}- /**- * Extracts bone name from animation track name- */- private extract_bone_name_from_track (track_name: string): string | null {- const bones_match = track_name.match(/\.bones\[([^\]]+)\]\.(?:quaternion|position|scale)$/)- if (bones_match !== null) {- return bones_match[1].toLowerCase()- }-- const simple_match = track_name.match(/^([^.]+)\.(?:quaternion|position|scale)$/)- if (simple_match !== null) {- return simple_match[1].toLowerCase()- }-- return null- }-- /**- * Gets all bone names referenced in animation clips- */- private get_animation_bone_names (animation_clips: AnimationClip[]): Set<string> {- const bone_names = new Set<string>()- animation_clips.forEach((clip) => {- clip.tracks.forEach((track) => {- const bone_name = this.extract_bone_name_from_track(track.name)- if (bone_name !== null) {- bone_names.add(bone_name)- }- })- })- return bone_names- }-- /**- * Validates that animation bones are compatible with target skeleton- * @throws {IncompatibleSkeletonError} If bones don't match- * @throws {NoAnimationsError} If no recognizable bone tracks found- */- public validate_animation_bones_match (- animation_clips: AnimationClip[],- skinned_meshes: SkinnedMesh[]- ): void {- if (skinned_meshes.length === 0) {- throw new Error('No skinned meshes available to validate animations.')- }-- // Get target bone names from skeleton- const target_bone_names = new Set<string>()- skinned_meshes.forEach((skinned_mesh) => {- skinned_mesh.skeleton.bones.forEach((bone) => {- target_bone_names.add(bone.name.toLowerCase())- })- })-- const animation_bone_names = this.get_animation_bone_names(animation_clips)-- if (animation_bone_names.size === 0) {- throw new NoAnimationsError('Imported animations do not contain recognizable bone tracks.')- }-- // Check bone count mismatch- if (animation_bone_names.size !== target_bone_names.size) {- throw new IncompatibleSkeletonError('bone count mismatch')- }-- // Check bone name mismatch (animation has bones not in target skeleton)- const missing_bones = Array.from(animation_bone_names).filter(bone => !target_bone_names.has(bone))- if (missing_bones.length > 0) {- throw new IncompatibleSkeletonError('bone names don\'t match')- }- }-/*** Loads animations from a local GLB file and validates against target skeleton.* @param file The GLB file to load@@ -225,12 +132,10 @@ export class AnimationLoader extends EventTarget {* @param skeleton_scale Scale factor to apply to position keyframes* @returns Promise that resolves with the loaded animation clips* @throws {NoAnimationsError} If no animations found in file- * @throws {IncompatibleSkeletonError} If animation bones don't match target skeleton* @throws {LoadError} If file cannot be loaded*/public async load_animations_from_file (file: File,- skinned_meshes: SkinnedMesh[],skeleton_scale: number = 1.0): Promise<TransformedAnimationClipPair[]> {const file_url = URL.createObjectURL(file)@@ -257,9 +162,6 @@ export class AnimationLoader extends EventTarget {throw new NoAnimationsError('No animations found in the GLB file.')}- // Validate bones match target skeleton throws error and exits loading if not compatible- this.validate_animation_bones_match(animations, skinned_meshes)-this.file_progress_map.set(file.name, { loaded: file_total, total: file_total })this.completed_files = 1this.emit_enhanced_progress(file.name, file_total, file_total)@@ -273,7 +175,7 @@ export class AnimationLoader extends EventTarget {this.emit_enhanced_progress(file.name, file_total, file_total)const error_message = error instanceof Error ? error.message : String(error)- if (error instanceof NoAnimationsError || error instanceof IncompatibleSkeletonError) {+ if (error instanceof NoAnimationsError) {reject(error)} else {reject(new LoadError(`Failed to process animations from ${file.name}: ${error_message}`))diff --git a/src/lib/processes/animations-listing/AnimationValidation.ts b/src/lib/processes/animations-listing/AnimationValidation.tsnew file mode 100644index 0000000..b61d2b7--- /dev/null+++ b/src/lib/processes/animations-listing/AnimationValidation.ts@@ -0,0 +1,74 @@+import { type AnimationClip, type SkinnedMesh } from 'three'+import { IncompatibleSkeletonError, NoAnimationsError } from './AnimationImportErrors.ts'++/**+ * Validates that animation bones are compatible with target skeleton+ * @throws {IncompatibleSkeletonError} If bones don't match+ * @throws {NoAnimationsError} If no recognizable bone tracks found+ */+export function validate_animation_bones_match (+ animation_clips: AnimationClip[],+ skinned_meshes: SkinnedMesh[]+): void {+ if (skinned_meshes.length === 0) {+ throw new Error('No skinned meshes available to validate animations.')+ }++ // Get target bone names from skeleton+ const target_bone_names = new Set<string>()+ skinned_meshes.forEach((skinned_mesh) => {+ skinned_mesh.skeleton.bones.forEach((bone) => {+ target_bone_names.add(bone.name.toLowerCase())+ })+ })++ const animation_bone_names = get_animation_bone_names(animation_clips)++ if (animation_bone_names.size === 0) {+ throw new NoAnimationsError('Imported animations do not contain recognizable bone tracks.')+ }++ // Check bone count mismatch+ if (animation_bone_names.size !== target_bone_names.size) {+ throw new IncompatibleSkeletonError('bone count mismatch')+ }++ // Check bone name mismatch (animation has bones not in target skeleton)+ const missing_bones = Array.from(animation_bone_names).filter(bone => !target_bone_names.has(bone))+ if (missing_bones.length > 0) {+ throw new IncompatibleSkeletonError('bone names don\'t match')+ }+}++/**+ * Gets all bone names referenced in animation clips+ */+function get_animation_bone_names (animation_clips: AnimationClip[]): Set<string> {+ const bone_names = new Set<string>()+ animation_clips.forEach((clip) => {+ clip.tracks.forEach((track) => {+ const bone_name = extract_bone_name_from_track(track.name)+ if (bone_name !== null) {+ bone_names.add(bone_name)+ }+ })+ })+ return bone_names+}++/**+ * Extracts bone name from animation track name+ */+function extract_bone_name_from_track (track_name: string): string | null {+ const bones_match = track_name.match(/\.bones\[([^\]]+)\]\.(?:quaternion|position|scale)$/)+ if (bones_match !== null) {+ return bones_match[1].toLowerCase()+ }++ const simple_match = track_name.match(/^([^.]+)\.(?:quaternion|position|scale)$/)+ if (simple_match !== null) {+ return simple_match[1].toLowerCase()+ }++ return null+}diff --git a/src/lib/processes/animations-listing/CustomAnimationImporter.ts b/src/lib/processes/animations-listing/CustomAnimationImporter.tsindex 3e64391..fa8a2d0 100644--- a/src/lib/processes/animations-listing/CustomAnimationImporter.ts+++ b/src/lib/processes/animations-listing/CustomAnimationImporter.ts@@ -1,7 +1,9 @@import { UI } from '../../UI.ts'import { ModalDialog } from '../../ModalDialog.ts'-import { type SkinnedMesh } from 'three'-import { type AnimationLoader, NoAnimationsError, IncompatibleSkeletonError, LoadError } from './AnimationLoader.ts'+import { type AnimationClip, type SkinnedMesh } from 'three'+import { type AnimationLoader } from './AnimationLoader.ts'+import { NoAnimationsError, IncompatibleSkeletonError, LoadError } from './AnimationImportErrors.ts'+import { validate_animation_bones_match } from './AnimationValidation.ts'import { type TransformedAnimationClipPair } from './interfaces/TransformedAnimationClipPair.ts'/**@@ -60,13 +62,15 @@ export class CustomAnimationImporter extends EventTarget {if (!this.is_enabled()) {return}++ // potentially allow multiple filesconst input = event.target as HTMLInputElementconst files = input.filesif (files === null || files.length === 0) {return}- this.set_enabled(false)+ this.set_enabled(false) // disable to prevent double-clicks during processingtry {for (const file of Array.from(files)) {@@ -87,10 +91,11 @@ export class CustomAnimationImporter extends EventTarget {try {const new_animation_clips = await this.animation_loader.load_animations_from_file(file,- this.skinned_meshes_to_animate,this.skeleton_scale)+ this.validate_loaded_animation_clips(new_animation_clips)+this.dispatchEvent(new CustomEvent<TransformedAnimationClipPair[]>('import-success', {detail: new_animation_clips}))@@ -104,29 +109,44 @@ export class CustomAnimationImporter extends EventTarget {return { success: true, clipCount: new_animation_clips.length }} catch (error) {- console.error('Failed to import animations:', error)+ return this.handle_import_error(error)+ }+ }- if (error instanceof NoAnimationsError) {- new ModalDialog('Import Error', 'No animations found in that glb file').show()- return { success: false, clipCount: 0 }- }+ private handle_import_error (error: unknown): { success: boolean, clipCount: number } {+ console.error('Failed to import animations:', error)- if (error instanceof IncompatibleSkeletonError) {- const error_message = error.message === 'bone_count_mismatch'- ? 'Bone count mismatch'- : 'Bone names don\'t match'- new ModalDialog('Import Error', error_message).show()- return { success: false, clipCount: 0 }- }+ if (error instanceof NoAnimationsError) {+ new ModalDialog('Import Error', 'No animations found in that glb file').show()+ return { success: false, clipCount: 0 }+ }- if (error instanceof LoadError) {- new ModalDialog('Import Error', 'failed to load the animation file').show()- return { success: false, clipCount: 0 }- }+ if (error instanceof IncompatibleSkeletonError) {+ const error_message = this.get_bone_validation_error_message(error)+ new ModalDialog('Import Error', error_message).show()+ return { success: false, clipCount: 0 }+ }- // Unknown error- new ModalDialog('Import Error', 'failed to import animations from the glb file').show()+ if (error instanceof LoadError) {+ new ModalDialog('Import Error', 'failed to load the animation file').show()return { success: false, clipCount: 0 }}++ // Unknown error+ new ModalDialog('Import Error', 'failed to import animations from the glb file').show()+ return { success: false, clipCount: 0 }+ }++ private get_bone_validation_error_message (error: IncompatibleSkeletonError): string {+ if (error.message === 'bone_count_mismatch' || error.message === 'bone count mismatch') {+ return 'Bone count mismatch'+ }++ return 'Bone names don\'t match'+ }++ private validate_loaded_animation_clips (new_animation_clips: TransformedAnimationClipPair[]): void {+ const clips_to_validate: AnimationClip[] = new_animation_clips.map((clip_pair) => clip_pair.display_animation_clip)+ validate_animation_bones_match(clips_to_validate, this.skinned_meshes_to_animate)}}