Import a 3D Model and automatically assign and export animations
TypeScript
First pass at creating and download a webm file when hitting a record button
Scott Petrovicb11d98256f15
diff --git a/package-lock.json b/package-lock.jsonindex 5b973f7..995e6f1 100644--- a/package-lock.json+++ b/package-lock.json@@ -8,6 +8,7 @@"name": "model-motionizer","version": "0.0.0","dependencies": {+ "file-saver": "^2.0.5","three": "0.175.0","vite-plugin-glsl": "^1.1.2"},@@ -1389,6 +1390,12 @@"node": "^10.12.0 || >=12.0.0"}},+ "node_modules/file-saver": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/file-saver/-/file-saver-2.0.5.tgz",+ "integrity": "sha512-P9bmyZ3h/PRG+Nzga+rbdI4OEpNDzAVyy74uVO9ATgzLK6VtAsYybF/+TOCvrc0MO793d6+42lLyZTw7/ArVzA==",+ "license": "MIT"+ },"node_modules/fill-range": {"version": "7.0.1","resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz",diff --git a/package.json b/package.jsonindex 9125394..cc8c70f 100644--- a/package.json+++ b/package.json@@ -18,6 +18,7 @@"vite": "^4.5.0"},"dependencies": {+ "file-saver": "^2.0.5","three": "0.175.0","vite-plugin-glsl": "^1.1.2"}diff --git a/src/lib/Utilities.ts b/src/lib/Utilities.tsindex 83125cd..b9be797 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, Euler, Raycaster, AnimationClip, KeyframeTrack,type PerspectiveCamera, type Scene, type Object3DEventMap, type BufferAttribute, type BufferGeometry, type InterleavedBufferAttribute} from 'three'import BoneTransformState from './models/BoneTransformState'@@ -289,4 +289,11 @@ export class Utility {return closest_bone_index}++ static deep_clone_animation_clips (animation_clips: AnimationClip[]): AnimationClip[] {+ return animation_clips.map((clip: AnimationClip) => {+ const tracks = clip.tracks.map((track: KeyframeTrack) => track.clone())+ return new AnimationClip(clip.name, clip.duration, tracks)+ })+ }}diff --git a/src/lib/processes/StepAnimationsListing.ts b/src/lib/processes/StepAnimationsListing.tsindex fa92f2d..09aa7dc 100644--- a/src/lib/processes/StepAnimationsListing.ts+++ b/src/lib/processes/StepAnimationsListing.ts@@ -8,6 +8,7 @@ import { AnimationClip, AnimationMixer, Quaternion, Vector3, type SkinnedMesh, ttype KeyframeTrack, type AnimationAction, type Object3D, Bone } from 'three'import { SkeletonType } from '../enums/SkeletonType.ts'+import { Utility } from '../Utilities.ts'// Note: EventTarget is a built-ininterface and do not need to import itexport class StepAnimationsListing extends EventTarget {@@ -154,7 +155,7 @@ export class StepAnimationsListing extends EventTarget {// load the animation clips into a new array// then, remove the animation position keyframes. That will mess up the skinning// process since we will be offsetting and moving the bone root positions- const cloned_anims: AnimationClip[] = this.deep_clone_animation_clips(gltf.animations)+ const cloned_anims: AnimationClip[] = Utility.deep_clone_animation_clips(gltf.animations)// only keep position tracksthis.remove_position_tracks(cloned_anims, true)@@ -350,11 +351,4 @@ export class StepAnimationsListing extends EventTarget {// helps ensure we don't add event listeners multiple timesthis.has_added_event_listeners = true}-- private deep_clone_animation_clips (animation_clips: AnimationClip[]): AnimationClip[] {- return animation_clips.map((clip: AnimationClip) => {- const tracks = clip.tracks.map(track => track.clone())- return new AnimationClip(clip.name, clip.duration, tracks)- })- }}diff --git a/src/preview-generator/README.md b/src/preview-generator/README.mdnew file mode 100644index 0000000..b396f9c--- /dev/null+++ b/src/preview-generator/README.md@@ -0,0 +1,19 @@+# Preview Generator++The goal of this preview generator is to create small animated clip previews to use in the animation listing.++++## Workflow++1. Background: Create a 3d setup scene that resembles what is in the application. Maybe we can reuse the Generator+2. Background: Load the human mesh skinned that includes all the animations and add to scene+2a. Background: specify video parameters like screen size, bitrate, and FPS+3. Use the MediaRecorder API to record the 3d canvas+ -- Loop through each animation and record each animation.+ a Start recording+ b Play animation clip+ c when animation clip ends, stop recording+ d save recording as animation_clip_x.webm to array somewhere+ e repeat to step a for each animation+ f when all the animations are done being recorded, save everything to a zip file and download\ No newline at end of filediff --git a/src/preview-generator/index.html b/src/preview-generator/index.htmlnew file mode 100644index 0000000..36a22bd--- /dev/null+++ b/src/preview-generator/index.html@@ -0,0 +1,17 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <title style="display: none">Mesh2Motion Preview Generation</title>+ <link rel="icon" type="image/png" href="./images/favicon.png"/>+ <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ </head>+ <body style="margin: 0">+ <script type="module" src="./preview-generator.ts"></script>+ <link href="../styles.css" rel="stylesheet" crossorigin="anonymous" />++ <button id="record-button" style="position: absolute; top: 20px; right: 20px;">Record</button>++ </body>+</html>\ No newline at end of filediff --git a/src/preview-generator/preview-generator.ts b/src/preview-generator/preview-generator.tsnew file mode 100644index 0000000..8c7969e--- /dev/null+++ b/src/preview-generator/preview-generator.ts@@ -0,0 +1,128 @@+import * as THREE from 'three'+import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'++import { Utility } from '../lib/Utilities.ts'+import { Generators } from '../lib/Generators.ts'+import { ThemeManager } from '../lib/ThemeManager.ts'++import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'+import { WebMRecorder } from './webm-recorder.ts'+import { saveAs } from 'file-saver';++export class PreviewGeneratorBootstrap {+ public readonly camera = Generators.create_camera()+ public readonly renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true })+ public controls: OrbitControls | undefined = undefined+ public readonly scene: THREE.Scene = new THREE.Scene()+ public readonly theme_manager = new ThemeManager()++ private environment_container: THREE.Group = new THREE.Group()++ // loading model and animation stuff+ private gltf_animation_loader: GLTFLoader = new GLTFLoader()++ constructor () {+ this.animate = this.animate.bind(this)+ this.gltf_animation_loader = new GLTFLoader()+ }++ public initialize (): void {+ this.setup_environment()++ // for now, let's load the human model+ this.load_human_model_and_animations()++ // setup event listener for record button+ const record_button = document.getElementById('record-button')+ record_button?.addEventListener('click', () => {+ this.start_recording()+ })++ this.animate()+ }++ private async start_recording (): Promise<void> {+ const recorder: WebMRecorder = new WebMRecorder(this.renderer)++ // TODO: play through each animation and do a recording+ // after all the animations are done zip up the results and download++ await recorder.record_webm(1, 'preview.webm').then(file => {+ console.log(file)+ saveAs(file, 'preview.webm')+ })+ }++ private load_human_model_and_animations (): void {+ // Load the human model here+ const filepath: string = '../animations/human-base-animations.glb'+ this.gltf_animation_loader.load(filepath, (gltf: any) => {+ // load the skinned mesh+ this.scene.add(...gltf.scene.children)++ // grab a list of the animations following logic of main Mesh2Motion app with cleanup+ const cloned_anims: THREE.AnimationClip[] = Utility.deep_clone_animation_clips(gltf.animations)+ console.log(cloned_anims)+ })+ }++ private setup_environment (): void {+ this.renderer.setSize(window.innerWidth, window.innerHeight)+ this.renderer.shadowMap.enabled = true++ // Set default camera position for front view+ // this will help because we first want the user to rotate the model to face the front+ this.camera.position.set(0, 1.7, 15) // X:0 (centered), Y:1.7 (eye-level), Z:5 (front view)++ Generators.create_window_resize_listener(this.renderer, this.camera)+ document.body.appendChild(this.renderer.domElement)++ // center orbit controls around mid-section area with target change+ this.controls = new OrbitControls(this.camera, this.renderer.domElement)+ this.controls.target.set(0, 0.9, 0)++ // Set zoom limits to prevent excessive zooming in or out+ this.controls.minDistance = 5 // Minimum zoom (closest to model)+ this.controls.maxDistance = 30 // Maximum zoom (farthest from model)++ this.controls.update()++ // basic things in another group, to better isolate what we are working on+ this.regenerate_floor_grid()+ }++ private animate (): void {+ requestAnimationFrame(this.animate)+ this.renderer.render(this.scene, this.camera)+ }++ public regenerate_floor_grid (): void {+ // remove previous setup objects from scene if they exist+ const setup_container = this.scene.getObjectByName('Setup objects')+ if (setup_container !== null) {+ this.scene.remove(setup_container)+ }++ // change color of grid based on theme+ let grid_color = 0x4b6368+ let floor_color = 0x2d4353+ let light_strength: number = 10+ if (this.theme_manager.get_current_theme() === 'light') {+ grid_color = 0xcccccc // light theme color+ floor_color = 0xecf0f1 // light theme color+ light_strength = 14+ }++ this.scene.fog = new THREE.Fog(floor_color, 20, 80)++ this.environment_container = new THREE.Group()+ this.environment_container.name = 'Setup objects'+ this.environment_container.add(...Generators.create_default_lights(light_strength))+ this.environment_container.add(...Generators.create_grid_helper(grid_color, floor_color))+ this.scene.add(this.environment_container)+ }+}++// Create an instance of the Bootstrap class when the script is loaded+const app = new PreviewGeneratorBootstrap()+app.initialize()diff --git a/src/preview-generator/webm-recorder.ts b/src/preview-generator/webm-recorder.tsnew file mode 100644index 0000000..b894d33--- /dev/null+++ b/src/preview-generator/webm-recorder.ts@@ -0,0 +1,55 @@+import * as THREE from 'three'++export class WebMRecorder {+ public width: number = 160+ public height: number = 120+ public fps: number = 24+ public kbps: number = 800++ public readonly recorded_files: File[] = []++ renderer_ref: THREE.WebGLRenderer++ constructor (renderer: THREE.WebGLRenderer) {+ this.renderer_ref = renderer+ }++ public async record_webm (duration_in_sec: number, fileName: string): Promise<File> {+ // store original size of renderer temporarily to capture a certain resolution+ const old_size = this.renderer_ref.getSize(new THREE.Vector2())+ const old_pr = this.renderer_ref.getPixelRatio()++ this.renderer_ref.setPixelRatio(1)+ this.renderer_ref.setSize(this.width, this.height, false)++ const stream: MediaStream = this.renderer_ref.domElement.captureStream(this.fps)+ const recorder = new MediaRecorder(stream, {+ mimeType: this.supported_webm_mime_type(),+ videoBitsPerSecond: this.kbps * 1000+ })++ const chunks: Blob[] = []+ recorder.ondataavailable = e => (e.data.size !== 0) && chunks.push(e.data)++ const stopped = new Promise(r => recorder.onstop = r)++ recorder.start()++ await new Promise(res => setTimeout(res, duration_in_sec * 1000))++ recorder.stop()++ await stopped++ // restore the renderer size and pixel ratio+ this.renderer_ref.setSize(old_size.x, old_size.y, false)+ this.renderer_ref.setPixelRatio(old_pr)++ return new File(chunks, fileName, { type: this.supported_webm_mime_type() })+ }++ private supported_webm_mime_type (): string {+ const prefs = ['video/webm;codecs=av01', 'video/webm;codecs=vp9', 'video/webm;codecs=vp8', 'video/webm']+ return prefs.find(m => MediaRecorder.isTypeSupported(m)) ?? 'video/webm'+ }+}diff --git a/src/script.ts b/src/script.tsindex 84f2bf7..7255524 100644--- a/src/script.ts+++ b/src/script.ts@@ -65,7 +65,7 @@ export class Bootstrap {this.setup_environment()this.eventListeners.addEventListeners()this.process_step = this.process_step_changed(ProcessStep.LoadModel)- this.animate()+ this.animate() // start the render loop which will continue rendering the scenethis.inject_build_version()} // end initialize()