Spaces:
Running
Running
Download src/character.js from Afredbilli/Cilo: direct link, hf CLI and curl.
- Browser
- Download file 15.9 kB
-
https://huggingface.co/spaces/Afredbilli/Cilo/resolve/main/src/character.js
- Command line
-
hf download hf://spaces/Afredbilli/Cilo/src/character.js
-
curl -L -o character.js https://huggingface.co/spaces/Afredbilli/Cilo/resolve/main/src/character.js
15.9 kB
| import * as THREE from "three"; | |
| import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"; | |
| // ============================================= | |
| // CHARACTER CONFIGURATION | |
| // ============================================= | |
| const CHARACTER_CONFIG = { | |
| modelPath: "./assets/viking.glb", | |
| // Desired in-game character height. | |
| targetHeight: 1.8, | |
| walkSpeed: 3, | |
| runSpeed: 6, | |
| rotationSpeed: 10, | |
| showSkeleton: false | |
| }; | |
| // ============================================= | |
| // CHARACTER FACTORY | |
| // ============================================= | |
| export async function createCharacter(scene) { | |
| const root = new THREE.Group(); | |
| root.name = "player-character"; | |
| scene.add(root); | |
| let model = null; | |
| let mixer = null; | |
| let skeletonHelper = null; | |
| const animations = {}; | |
| let currentAction = null; | |
| let currentActionName = "idle"; | |
| let isMoving = false; | |
| let isRunning = false; | |
| let isAttacking = false; | |
| let isBlocking = false; | |
| let attackCooldown = 0; | |
| let attackDuration = 0.7; | |
| let attackElapsed = 0; | |
| const moveDirection = new THREE.Vector3(); | |
| const targetRotation = new THREE.Quaternion(); | |
| const lookMatrix = new THREE.Matrix4(); | |
| // ========================================= | |
| // LOAD GLB | |
| // ========================================= | |
| async function loadModel() { | |
| const loader = new GLTFLoader(); | |
| const gltf = await loader.loadAsync( | |
| CHARACTER_CONFIG.modelPath | |
| ); | |
| model = gltf.scene; | |
| model.name = "viking-model"; | |
| // ----------------------------------------- | |
| // MATERIAL / TEXTURE FIX | |
| // ----------------------------------------- | |
| model.traverse(object => { | |
| if (!object.isMesh) { | |
| return; | |
| } | |
| object.castShadow = true; | |
| object.receiveShadow = true; | |
| const materials = Array.isArray(object.material) | |
| ? object.material | |
| : [object.material]; | |
| for (const material of materials) { | |
| if (!material) { | |
| continue; | |
| } | |
| // GLTFLoader normally does this automatically, | |
| // but explicitly setting it makes sure color | |
| // textures are interpreted correctly. | |
| if (material.map) { | |
| material.map.colorSpace = | |
| THREE.SRGBColorSpace; | |
| material.map.needsUpdate = true; | |
| } | |
| if (material.emissiveMap) { | |
| material.emissiveMap.colorSpace = | |
| THREE.SRGBColorSpace; | |
| material.emissiveMap.needsUpdate = true; | |
| } | |
| material.needsUpdate = true; | |
| } | |
| }); | |
| // ----------------------------------------- | |
| // NORMALIZE MODEL SIZE | |
| // ----------------------------------------- | |
| normalizeCharacter(model); | |
| root.add(model); | |
| // ----------------------------------------- | |
| // ANIMATION SETUP | |
| // ----------------------------------------- | |
| setupAnimations(gltf.animations); | |
| if (CHARACTER_CONFIG.showSkeleton) { | |
| skeletonHelper = | |
| new THREE.SkeletonHelper(model); | |
| scene.add(skeletonHelper); | |
| } | |
| console.info( | |
| "======================================" | |
| ); | |
| console.info("VIKING MODEL"); | |
| console.info( | |
| "Height:", | |
| getModelHeight(model).toFixed(3) | |
| ); | |
| console.info( | |
| "Animations:", | |
| gltf.animations.length | |
| ); | |
| console.info( | |
| "Skinned meshes:", | |
| countSkinnedMeshes(model) | |
| ); | |
| console.info( | |
| "======================================" | |
| ); | |
| return model; | |
| } | |
| // ========================================= | |
| // NORMALIZE CHARACTER | |
| // ========================================= | |
| function normalizeCharacter(object) { | |
| // First calculate the original bounds. | |
| const bounds = new THREE.Box3() | |
| .setFromObject(object); | |
| const originalSize = | |
| bounds.getSize(new THREE.Vector3()); | |
| const originalHeight = | |
| originalSize.y; | |
| if ( | |
| !Number.isFinite(originalHeight) || | |
| originalHeight <= 0 | |
| ) { | |
| throw new Error( | |
| "The Viking GLB has an invalid model height." | |
| ); | |
| } | |
| // Scale based on actual height. | |
| const scale = | |
| CHARACTER_CONFIG.targetHeight / | |
| originalHeight; | |
| object.scale.setScalar(scale); | |
| // Recalculate after scaling. | |
| object.updateMatrixWorld(true); | |
| const scaledBounds = | |
| new THREE.Box3() | |
| .setFromObject(object); | |
| const center = | |
| scaledBounds.getCenter( | |
| new THREE.Vector3() | |
| ); | |
| // Center the character horizontally. | |
| object.position.x -= center.x; | |
| object.position.z -= center.z; | |
| // Put the feet exactly on the world ground. | |
| object.position.y -= scaledBounds.min.y; | |
| object.updateMatrixWorld(true); | |
| console.info( | |
| `Character normalized: ` + | |
| `${originalHeight.toFixed(2)} → ` + | |
| `${CHARACTER_CONFIG.targetHeight.toFixed(2)} units` | |
| ); | |
| } | |
| function getModelHeight(object) { | |
| const bounds = new THREE.Box3() | |
| .setFromObject(object); | |
| return bounds.max.y - bounds.min.y; | |
| } | |
| function countSkinnedMeshes(object) { | |
| let count = 0; | |
| object.traverse(child => { | |
| if (child.isSkinnedMesh) { | |
| count++; | |
| } | |
| }); | |
| return count; | |
| } | |
| // ========================================= | |
| // ANIMATION SETUP | |
| // ========================================= | |
| function setupAnimations(clips) { | |
| if (!model || clips.length === 0) { | |
| console.warn( | |
| "No embedded animations found in the GLB." | |
| ); | |
| return; | |
| } | |
| mixer = new THREE.AnimationMixer(model); | |
| for (const clip of clips) { | |
| const name = clip.name.toLowerCase(); | |
| animations[name] = clip; | |
| console.info( | |
| `Animation available: ` + | |
| `${clip.name} ` + | |
| `(${clip.duration.toFixed(2)}s)` | |
| ); | |
| } | |
| playBestAnimation([ | |
| "idle", | |
| "standing", | |
| "breathing" | |
| ]); | |
| } | |
| function findAnimation(candidates) { | |
| const entries = | |
| Object.entries(animations); | |
| // Exact match first. | |
| for (const candidate of candidates) { | |
| const exact = entries.find( | |
| ([name]) => name === candidate | |
| ); | |
| if (exact) { | |
| return exact[1]; | |
| } | |
| } | |
| // Then partial match. | |
| for (const candidate of candidates) { | |
| const partial = entries.find( | |
| ([name]) => name.includes(candidate) | |
| ); | |
| if (partial) { | |
| return partial[1]; | |
| } | |
| } | |
| return null; | |
| } | |
| function playBestAnimation( | |
| candidates, | |
| options = {} | |
| ) { | |
| const clip = findAnimation(candidates); | |
| if (!clip || !mixer) { | |
| return false; | |
| } | |
| return playAnimation( | |
| clip, | |
| options | |
| ); | |
| } | |
| function playAnimation( | |
| clip, | |
| options = {} | |
| ) { | |
| if (!mixer || !clip) { | |
| return false; | |
| } | |
| const { | |
| loop = THREE.LoopRepeat, | |
| fadeDuration = 0.2, | |
| timeScale = 1, | |
| clampWhenFinished = false | |
| } = options; | |
| const nextAction = | |
| mixer.clipAction(clip); | |
| if (currentAction === nextAction) { | |
| return true; | |
| } | |
| nextAction.reset(); | |
| nextAction.enabled = true; | |
| nextAction.setLoop(loop); | |
| nextAction.clampWhenFinished = | |
| clampWhenFinished; | |
| nextAction.timeScale = | |
| timeScale; | |
| nextAction.fadeIn( | |
| fadeDuration | |
| ); | |
| if (currentAction) { | |
| currentAction.fadeOut( | |
| fadeDuration | |
| ); | |
| } | |
| nextAction.play(); | |
| currentAction = nextAction; | |
| currentActionName = | |
| clip.name.toLowerCase(); | |
| return true; | |
| } | |
| // ========================================= | |
| // LOCOMOTION | |
| // ========================================= | |
| function updateLocomotionAnimation() { | |
| if (isAttacking || isBlocking) { | |
| return; | |
| } | |
| if (isMoving && isRunning) { | |
| if ( | |
| !playBestAnimation([ | |
| "run", | |
| "running", | |
| "sprint" | |
| ]) | |
| ) { | |
| playBestAnimation([ | |
| "walk", | |
| "walking" | |
| ]); | |
| } | |
| return; | |
| } | |
| if (isMoving) { | |
| playBestAnimation([ | |
| "walk", | |
| "walking", | |
| "run" | |
| ]); | |
| return; | |
| } | |
| playBestAnimation([ | |
| "idle", | |
| "standing", | |
| "breathing" | |
| ]); | |
| } | |
| // ========================================= | |
| // MOVEMENT | |
| // ========================================= | |
| function move( | |
| x, | |
| z, | |
| running = false, | |
| delta = 1 / 60 | |
| ) { | |
| if ( | |
| isAttacking || | |
| isBlocking | |
| ) { | |
| return; | |
| } | |
| moveDirection.set( | |
| x, | |
| 0, | |
| z | |
| ); | |
| if ( | |
| moveDirection.lengthSq() > 1 | |
| ) { | |
| moveDirection.normalize(); | |
| } | |
| isMoving = | |
| moveDirection.lengthSq() > 0.001; | |
| isRunning = running; | |
| if (!isMoving) { | |
| updateLocomotionAnimation(); | |
| return; | |
| } | |
| const speed = running | |
| ? CHARACTER_CONFIG.runSpeed | |
| : CHARACTER_CONFIG.walkSpeed; | |
| root.position.addScaledVector( | |
| moveDirection, | |
| speed * delta | |
| ); | |
| // Face movement direction. | |
| const direction = | |
| moveDirection.clone().normalize(); | |
| lookMatrix.lookAt( | |
| new THREE.Vector3(), | |
| direction, | |
| new THREE.Vector3(0, 1, 0) | |
| ); | |
| targetRotation | |
| .setFromRotationMatrix( | |
| lookMatrix | |
| ); | |
| root.quaternion.slerp( | |
| targetRotation, | |
| 1 - Math.exp( | |
| -CHARACTER_CONFIG.rotationSpeed * | |
| delta | |
| ) | |
| ); | |
| updateLocomotionAnimation(); | |
| } | |
| // ========================================= | |
| // ATTACK | |
| // ========================================= | |
| function attack() { | |
| if ( | |
| isAttacking || | |
| isBlocking || | |
| attackCooldown > 0 | |
| ) { | |
| return false; | |
| } | |
| const attackClip = | |
| findAnimation([ | |
| "slash", | |
| "attack", | |
| "sword", | |
| "melee", | |
| "swing" | |
| ]); | |
| if (!attackClip) { | |
| console.warn( | |
| "No slash/attack animation found." | |
| ); | |
| return false; | |
| } | |
| isAttacking = true; | |
| attackElapsed = 0; | |
| attackDuration = | |
| attackClip.duration; | |
| attackCooldown = | |
| attackDuration + 0.1; | |
| playAnimation( | |
| attackClip, | |
| { | |
| loop: THREE.LoopOnce, | |
| fadeDuration: 0.08, | |
| clampWhenFinished: true | |
| } | |
| ); | |
| return true; | |
| } | |
| // ========================================= | |
| // BLOCK | |
| // ========================================= | |
| function block(enabled = true) { | |
| if ( | |
| enabled && | |
| isAttacking | |
| ) { | |
| return false; | |
| } | |
| if ( | |
| isBlocking === enabled | |
| ) { | |
| return true; | |
| } | |
| isBlocking = enabled; | |
| if (enabled) { | |
| const success = | |
| playBestAnimation([ | |
| "block", | |
| "blocking", | |
| "shield", | |
| "defend", | |
| "guard" | |
| ]); | |
| if (!success) { | |
| isBlocking = false; | |
| console.warn( | |
| "No blocking animation found." | |
| ); | |
| return false; | |
| } | |
| } else { | |
| updateLocomotionAnimation(); | |
| } | |
| return true; | |
| } | |
| // ========================================= | |
| // UPDATE | |
| // ========================================= | |
| function update(delta) { | |
| if (mixer) { | |
| mixer.update(delta); | |
| } | |
| attackCooldown = | |
| Math.max( | |
| 0, | |
| attackCooldown - delta | |
| ); | |
| if (isAttacking) { | |
| attackElapsed += delta; | |
| if ( | |
| attackElapsed >= | |
| attackDuration | |
| ) { | |
| isAttacking = false; | |
| updateLocomotionAnimation(); | |
| } | |
| } | |
| if (skeletonHelper) { | |
| skeletonHelper.updateMatrixWorld( | |
| true | |
| ); | |
| } | |
| } | |
| // ========================================= | |
| // INITIALIZATION | |
| // ========================================= | |
| try { | |
| await loadModel(); | |
| return createPublicAPI(); | |
| } catch (error) { | |
| scene.remove(root); | |
| console.error( | |
| "Unable to load Viking GLB:", | |
| error | |
| ); | |
| throw new Error( | |
| `Could not load ` + | |
| `${CHARACTER_CONFIG.modelPath}. ` + | |
| `Check that the file exists in ` + | |
| `assets/. Details: ${error.message}` | |
| ); | |
| } | |
| // ========================================= | |
| // PUBLIC API | |
| // ========================================= | |
| function createPublicAPI() { | |
| return { | |
| root, | |
| model, | |
| get position() { | |
| return root.position; | |
| }, | |
| get isMoving() { | |
| return isMoving; | |
| }, | |
| get isRunning() { | |
| return isRunning; | |
| }, | |
| get isAttacking() { | |
| return isAttacking; | |
| }, | |
| get isBlocking() { | |
| return isBlocking; | |
| }, | |
| get currentAnimation() { | |
| return currentActionName; | |
| }, | |
| move, | |
| attack, | |
| block, | |
| update, | |
| getForwardDirection() { | |
| return new THREE.Vector3( | |
| 0, | |
| 0, | |
| -1 | |
| ) | |
| .applyQuaternion( | |
| root.quaternion | |
| ) | |
| .normalize(); | |
| }, | |
| dispose() { | |
| if (mixer) { | |
| mixer.stopAllAction(); | |
| mixer.uncacheRoot(model); | |
| } | |
| if (skeletonHelper) { | |
| scene.remove( | |
| skeletonHelper | |
| ); | |
| skeletonHelper.dispose?.(); | |
| } | |
| root.removeFromParent(); | |
| } | |
| }; | |
| } | |
| } |