Refactor code for consistency and readability

- Updated import statements to use consistent formatting across files.
- Adjusted method definitions and class constructors for uniform spacing and style.
- Simplified promise handling and error messages in state handlers.
- Enhanced state transition logic in various state handlers.
- Improved quirk animation handling in WaitStateHandler.
- Streamlined animation loading and caching mechanisms in AnimationLoader.
- Updated Vite configuration for aliasing.
This commit is contained in:
2025-05-24 01:14:35 +02:00
parent 658e1e64b2
commit 60aad20b5e
23 changed files with 4217 additions and 1281 deletions

View File

@ -1,70 +0,0 @@
{
"extends": [
"eslint:recommended"
],
"env": {
"browser": true,
"es2022": true,
"node": true
},
"parserOptions": {
"ecmaVersion": 2022,
"sourceType": "module"
},
"rules": {
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"no-unused-vars": [
"warn",
{
"argsIgnorePattern": "^_"
}
],
"no-console": [
"warn"
],
"max-len": [
"warn",
{
"code": 120
}
]
},
"overrides": [
{
"files": [
"examples/**/*.js"
],
"rules": {
"no-console": "off"
}
},
{
"files": [
"src/**/*.js"
],
"rules": {
"no-console": "off"
}
}
],
"ignorePatterns": [
"node_modules/",
"dist/",
"docs/"
]
}

41
.gitignore vendored
View File

@ -1,3 +1,30 @@
# Temporary files
*.tmp
*.temp
# Documentation output
/docs/
# Animation assets (if storing locally)
/assets/models/
/assets/animations/
# Example build outputs
/examples/dist/
# 3D Models (optional - remove if you want to commit models)
*.gltf
*.glb
*.fbx
*.obj
*.dae
# Three.js cache
.three-cache/
# Editor (optional - remove if you want to commit editor files)
.vscode/
# Created by https://www.toptal.com/developers/gitignore/api/windows,macos,linux,visualstudiocode,webstorm,vim,emacs,node
# Edit at https://www.toptal.com/developers/gitignore?templates=windows,macos,linux,visualstudiocode,webstorm,vim,emacs,node
@ -418,17 +445,3 @@ $RECYCLE.BIN/
*.lnk
# End of https://www.toptal.com/developers/gitignore/api/windows,macos,linux,visualstudiocode,webstorm,vim,emacs,node
# Build outputs
docs/
# Temporary files
*.tmp
*.temp
# 3D Models (optional - remove if you want to commit models)
*.gltf
*.glb
*.fbx
*.obj
*.dae

View File

@ -5,9 +5,18 @@ All notable changes to the Owen Animation System will be documented in this file
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.0.1] - 2025-05-24
### Changed
- 🎨 Standardized code style throughout the codebase
- 🔧 Converted semicolons to non-semicolons according to JavaScript Standard Style
- 📝 Improved code consistency and readability
## [1.0.0] - 2025-05-23
### Added
- 🎉 Initial release of Owen Animation System
- ✨ Complete state machine implementation with Wait, React, Type, and Sleep states
- 🤖 Emotional response system for character animations
@ -21,7 +30,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- 📦 TypeScript type definitions
- 🛠️ Development tooling (ESLint, Vite, JSDoc)
[1.0.1]: https://gitea.kajkowalski.nl/kjanat/Owen/releases/tag/v1.0.1
### Architecture
- **Core Classes:**
- `OwenAnimationContext` - Main system controller
- `AnimationClip` - Individual animation management
@ -43,6 +55,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `OwenSystemFactory` - Main system assembly factory
### Features
- **Animation System:**
- Support for Loop (L), Quirk (Q), Transition (T), and Nested animations
- Automatic metadata parsing from animation names
@ -63,6 +76,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Vite development server setup
### Documentation
- Complete README with installation and usage instructions
- API documentation via JSDoc
- Code examples for basic and advanced usage
@ -70,9 +84,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Troubleshooting section
### Examples
- Basic browser demo with Three.js integration
- Simple Node.js example for testing
- Interactive controls for state transitions
- Mock model implementation for development
[1.0.0]: https://github.com/your-username/owen-animation-system/releases/tag/v1.0.0
[1.0.0]: https://gitea.kajkowalski.nl/kjanat/Owen/releases/tag/v1.0.0

View File

@ -2,6 +2,10 @@
A comprehensive Three.js animation system for character state management with clean architecture principles, dependency injection, and factory patterns.
[![Gitea Issues](https://img.shields.io/gitea/issues/all/kjanat/Owen?gitea_url=https%3A%2F%2Fgitea.kajkowalski.nl%2F)](https://gitea.kajkowalski.nl/kjanat/Owen/issues)
[![Gitea Pull Requests](https://img.shields.io/gitea/pull-requests/all/kjanat/Owen?gitea_url=https%3A%2F%2Fgitea.kajkowalski.nl%2F)](https://gitea.kajkowalski.nl/kjanat/Owen/pulls)
[![Gitea Release](https://img.shields.io/gitea/v/release/kjanat/Owen?gitea_url=https%3A%2F%2Fgitea.kajkowalski.nl&include_prereleases&sort=semver)](https://gitea.kajkowalski.nl/kjanat/Owen/tags)
## 🎯 Overview
The Owen Animation System is a sophisticated character animation framework built for Three.js that manages complex state machines, emotional responses, and animation transitions. It's designed with clean architecture principles to be maintainable, extensible, and testable.
@ -181,7 +185,6 @@ Owen/
│ └── basic-demo.js # Basic usage example
├── package.json
├── vite.config.js
├── .eslintrc.json
├── jsdoc.config.json
└── README.md
```
@ -228,9 +231,10 @@ Documentation will be generated in the `docs/` directory.
- `npm run dev` - Start development server
- `npm run build` - Build for production
- `npm run preview` - Preview production build
- `npm run lint` - Run ESLint
- `npm run lint:fix` - Fix ESLint issues
- `npm run lint` - Run StandardJS linting
- `npm run lint:fix` - Fix StandardJS issues
- `npm run docs` - Generate JSDoc documentation
- `npm run format` - Format code with Prettier
## 🎮 Demo Controls

View File

@ -1,332 +0,0 @@
/**
* @fileoverview Basic example of using the Owen Animation System
* @author Owen Animation System
*/
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { OwenSystemFactory, States } from '../src/index.js';
/**
* Basic Owen Animation System demo
* @class
*/
class OwenDemo {
/**
* Create the demo
*/
constructor() {
/**
* The Three.js scene
* @type {THREE.Scene}
*/
this.scene = new THREE.Scene();
/**
* The Three.js camera
* @type {THREE.PerspectiveCamera}
*/
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
/**
* The Three.js renderer
* @type {THREE.WebGLRenderer}
*/
this.renderer = new THREE.WebGLRenderer({ antialias: true });
/**
* The Owen animation system
* @type {OwenAnimationContext|null}
*/
this.owenSystem = null;
/**
* Clock for tracking time
* @type {THREE.Clock}
*/
this.clock = new THREE.Clock();
}
/**
* Initialize the demo
* @returns {Promise<void>}
*/
async init() {
// Setup renderer
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setClearColor(0x1a1a1a);
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.appendChild(this.renderer.domElement);
// Setup camera
this.camera.position.set(0, 1.6, 3);
this.camera.lookAt(0, 1, 0);
// Add lighting
this.setupLighting();
// Load Owen model (replace with your model path)
await this.loadOwenModel();
// Setup event listeners
this.setupEventListeners();
// Start render loop
this.animate();
console.log('Owen Demo initialized');
}
/**
* Setup scene lighting
* @private
* @returns {void}
*/
setupLighting() {
// Ambient light
const ambientLight = new THREE.AmbientLight(0x404040, 0.4);
this.scene.add(ambientLight);
// Directional light
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(5, 10, 5);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
this.scene.add(directionalLight);
// Fill light
const fillLight = new THREE.DirectionalLight(0x8bb7f0, 0.3);
fillLight.position.set(-5, 5, -5);
this.scene.add(fillLight);
}
/**
* Load the Owen character model
* @private
* @returns {Promise<void>}
*/
async loadOwenModel() {
try {
const loader = new GLTFLoader();
// Replace 'path/to/owen.gltf' with your actual model path
const gltf = await new Promise((resolve, reject) => {
loader.load(
'path/to/owen.gltf', // Update this path
resolve,
(progress) => console.log('Loading progress:', progress.loaded / progress.total * 100 + '%'),
reject
);
});
const model = gltf.scene;
model.position.set(0, 0, 0);
model.scale.setScalar(1);
// Enable shadows
model.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
this.scene.add(model);
// Create Owen animation system
this.owenSystem = await OwenSystemFactory.createOwenSystem(gltf, this.scene);
console.log('Owen model loaded and animation system created');
this.logSystemInfo();
} catch (error) {
console.error('Error loading Owen model:', error);
// Create a placeholder cube for demo purposes
this.createPlaceholderModel();
}
}
/**
* Create a placeholder model for demo purposes
* @private
* @returns {void}
*/
createPlaceholderModel() {
const geometry = new THREE.BoxGeometry(1, 2, 1);
const material = new THREE.MeshPhongMaterial({ color: 0x6699ff });
const cube = new THREE.Mesh(geometry, material);
cube.position.set(0, 1, 0);
cube.castShadow = true;
cube.receiveShadow = true;
this.scene.add(cube);
console.log('Created placeholder model (cube)');
}
/**
* Setup event listeners for user interaction
* @private
* @returns {void}
*/
setupEventListeners() {
// Keyboard controls
document.addEventListener('keydown', (event) => {
if (!this.owenSystem) return;
switch (event.key) {
case '1':
this.owenSystem.transitionTo(States.WAIT);
break;
case '2':
this.owenSystem.transitionTo(States.REACT);
break;
case '3':
this.owenSystem.transitionTo(States.TYPE);
break;
case '4':
this.owenSystem.transitionTo(States.SLEEP);
break;
case ' ':
this.sendTestMessage();
break;
}
});
// Mouse interaction
document.addEventListener('click', () => {
if (this.owenSystem) {
this.owenSystem.onUserActivity();
}
});
// Window resize
window.addEventListener('resize', () => {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
});
// Add instructions to the page
this.addInstructions();
}
/**
* Add on-screen instructions
* @private
* @returns {void}
*/
addInstructions() {
const instructions = document.createElement('div');
instructions.innerHTML = `
<div style="position: absolute; top: 10px; left: 10px; color: white; ` +
`font-family: monospace; font-size: 14px; line-height: 1.4;">
<h3>Owen Animation System Demo</h3>
<p><strong>Controls:</strong></p>
<p>1 - Wait State</p>
<p>2 - React State</p>
<p>3 - Type State</p>
<p>4 - Sleep State</p>
<p>Space - Send Test Message</p>
<p>Click - User Activity</p>
<br>
<p><strong>Current State:</strong> <span id="current-state">-</span></p>
<p><strong>Available Transitions:</strong> <span id="transitions">-</span></p>
</div>
`;
document.body.appendChild(instructions);
}
/**
* Send a test message to Owen
* @private
* @returns {void}
*/
sendTestMessage() {
if (!this.owenSystem) return;
const testMessages = [
'Hello Owen!',
'How are you doing?',
'This is urgent!',
'Great work!',
'Error in the system!',
'I\'m feeling sad today'
];
const randomMessage = testMessages[Math.floor(Math.random() * testMessages.length)];
console.log(`Sending message: "${randomMessage}"`);
this.owenSystem.handleUserMessage(randomMessage);
}
/**
* Log system information
* @private
* @returns {void}
*/
logSystemInfo() {
if (!this.owenSystem) return;
console.log('=== Owen System Info ===');
console.log('Available States:', this.owenSystem.getAvailableStates());
console.log('Available Clips:', this.owenSystem.getAvailableClips());
console.log('Current State:', this.owenSystem.getCurrentState());
console.log('========================');
}
/**
* Update UI with current system state
* @private
* @returns {void}
*/
updateUI() {
if (!this.owenSystem) return;
const currentStateElement = document.getElementById('current-state');
const transitionsElement = document.getElementById('transitions');
if (currentStateElement) {
currentStateElement.textContent = this.owenSystem.getCurrentState();
}
if (transitionsElement) {
transitionsElement.textContent = this.owenSystem.getAvailableTransitions().join(', ');
}
}
/**
* Main animation loop
* @private
* @returns {void}
*/
animate() {
requestAnimationFrame(() => this.animate());
const deltaTime = this.clock.getDelta() * 1000; // Convert to milliseconds
// Update Owen system
if (this.owenSystem) {
this.owenSystem.update(deltaTime);
}
// Update UI
this.updateUI();
// Render scene
this.renderer.render(this.scene, this.camera);
}
}
// Initialize the demo when the page loads
window.addEventListener('load', async () => {
const demo = new OwenDemo();
try {
await demo.init();
} catch (error) {
console.error('Failed to initialize Owen demo:', error);
}
});
export default OwenDemo;

View File

@ -3,9 +3,9 @@
* @author Owen Animation System
*/
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { OwenSystemFactory, States } from '../src/index.js';
import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { OwenSystemFactory, States } from '../src/index.js'
/**
* Basic Owen Animation System demo
@ -15,67 +15,67 @@ class OwenDemo {
/**
* Create the demo
*/
constructor() {
constructor () {
/**
* The Three.js scene
* @type {THREE.Scene}
*/
this.scene = new THREE.Scene();
this.scene = new THREE.Scene()
/**
* The Three.js camera
* @type {THREE.PerspectiveCamera}
*/
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
/**
* The Three.js renderer
* @type {THREE.WebGLRenderer}
*/
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.renderer = new THREE.WebGLRenderer({ antialias: true })
/**
* The Owen animation system
* @type {OwenAnimationContext|null}
*/
this.owenSystem = null;
this.owenSystem = null
/**
* Clock for tracking time
* @type {THREE.Clock}
*/
this.clock = new THREE.Clock();
this.clock = new THREE.Clock()
}
/**
* Initialize the demo
* @returns {Promise<void>}
*/
async init() {
async init () {
// Setup renderer
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setClearColor(0x1a1a1a);
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.appendChild(this.renderer.domElement);
this.renderer.setSize(window.innerWidth, window.innerHeight)
this.renderer.setClearColor(0x1a1a1a)
this.renderer.shadowMap.enabled = true
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap
document.body.appendChild(this.renderer.domElement)
// Setup camera
this.camera.position.set(0, 1.6, 3);
this.camera.lookAt(0, 1, 0);
this.camera.position.set(0, 1.6, 3)
this.camera.lookAt(0, 1, 0)
// Add lighting
this.setupLighting();
this.setupLighting()
// Load Owen model (replace with your model path)
await this.loadOwenModel();
await this.loadOwenModel()
// Setup event listeners
this.setupEventListeners();
this.setupEventListeners()
// Start render loop
this.animate();
this.animate()
console.log('Owen Demo initialized');
console.log('Owen Demo initialized')
}
/**
@ -83,23 +83,23 @@ class OwenDemo {
* @private
* @returns {void}
*/
setupLighting() {
setupLighting () {
// Ambient light
const ambientLight = new THREE.AmbientLight(0x404040, 0.4);
this.scene.add(ambientLight);
const ambientLight = new THREE.AmbientLight(0x404040, 0.4)
this.scene.add(ambientLight)
// Directional light
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(5, 10, 5);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
this.scene.add(directionalLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8)
directionalLight.position.set(5, 10, 5)
directionalLight.castShadow = true
directionalLight.shadow.mapSize.width = 2048
directionalLight.shadow.mapSize.height = 2048
this.scene.add(directionalLight)
// Fill light
const fillLight = new THREE.DirectionalLight(0x8bb7f0, 0.3);
fillLight.position.set(-5, 5, -5);
this.scene.add(fillLight);
const fillLight = new THREE.DirectionalLight(0x8bb7f0, 0.3)
fillLight.position.set(-5, 5, -5)
this.scene.add(fillLight)
}
/**
@ -107,9 +107,9 @@ class OwenDemo {
* @private
* @returns {Promise<void>}
*/
async loadOwenModel() {
async loadOwenModel () {
try {
const loader = new GLTFLoader();
const loader = new GLTFLoader()
// Replace 'path/to/owen.gltf' with your actual model path
const gltf = await new Promise((resolve, reject) => {
@ -118,34 +118,33 @@ class OwenDemo {
resolve,
(progress) => console.log('Loading progress:', progress.loaded / progress.total * 100 + '%'),
reject
);
});
)
})
const model = gltf.scene;
model.position.set(0, 0, 0);
model.scale.setScalar(1);
const model = gltf.scene
model.position.set(0, 0, 0)
model.scale.setScalar(1)
// Enable shadows
model.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
child.castShadow = true
child.receiveShadow = true
}
});
})
this.scene.add(model);
this.scene.add(model)
// Create Owen animation system
this.owenSystem = await OwenSystemFactory.createOwenSystem(gltf, this.scene);
console.log('Owen model loaded and animation system created');
this.logSystemInfo();
this.owenSystem = await OwenSystemFactory.createOwenSystem(gltf, this.scene)
console.log('Owen model loaded and animation system created')
this.logSystemInfo()
} catch (error) {
console.error('Error loading Owen model:', error);
console.error('Error loading Owen model:', error)
// Create a placeholder cube for demo purposes
this.createPlaceholderModel();
this.createPlaceholderModel()
}
}
@ -154,16 +153,16 @@ class OwenDemo {
* @private
* @returns {void}
*/
createPlaceholderModel() {
const geometry = new THREE.BoxGeometry(1, 2, 1);
const material = new THREE.MeshPhongMaterial({ color: 0x6699ff });
const cube = new THREE.Mesh(geometry, material);
cube.position.set(0, 1, 0);
cube.castShadow = true;
cube.receiveShadow = true;
this.scene.add(cube);
createPlaceholderModel () {
const geometry = new THREE.BoxGeometry(1, 2, 1)
const material = new THREE.MeshPhongMaterial({ color: 0x6699ff })
const cube = new THREE.Mesh(geometry, material)
cube.position.set(0, 1, 0)
cube.castShadow = true
cube.receiveShadow = true
this.scene.add(cube)
console.log('Created placeholder model (cube)');
console.log('Created placeholder model (cube)')
}
/**
@ -171,46 +170,46 @@ class OwenDemo {
* @private
* @returns {void}
*/
setupEventListeners() {
setupEventListeners () {
// Keyboard controls
document.addEventListener('keydown', (event) => {
if (!this.owenSystem) return;
if (!this.owenSystem) return
switch (event.key) {
case '1':
this.owenSystem.transitionTo(States.WAIT);
break;
this.owenSystem.transitionTo(States.WAIT)
break
case '2':
this.owenSystem.transitionTo(States.REACT);
break;
this.owenSystem.transitionTo(States.REACT)
break
case '3':
this.owenSystem.transitionTo(States.TYPE);
break;
this.owenSystem.transitionTo(States.TYPE)
break
case '4':
this.owenSystem.transitionTo(States.SLEEP);
break;
this.owenSystem.transitionTo(States.SLEEP)
break
case ' ':
this.sendTestMessage();
break;
this.sendTestMessage()
break
}
});
})
// Mouse interaction
document.addEventListener('click', () => {
if (this.owenSystem) {
this.owenSystem.onUserActivity();
this.owenSystem.onUserActivity()
}
});
})
// Window resize
window.addEventListener('resize', () => {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
});
this.camera.aspect = window.innerWidth / window.innerHeight
this.camera.updateProjectionMatrix()
this.renderer.setSize(window.innerWidth, window.innerHeight)
})
// Add instructions to the page
this.addInstructions();
this.addInstructions()
}
/**
@ -218,8 +217,8 @@ class OwenDemo {
* @private
* @returns {void}
*/
addInstructions() {
const instructions = document.createElement('div');
addInstructions () {
const instructions = document.createElement('div')
instructions.innerHTML = `
<div style="position: absolute; top: 10px; left: 10px; color: white; ` +
`font-family: monospace; font-size: 14px; line-height: 1.4;">
@ -235,8 +234,8 @@ class OwenDemo {
<p><strong>Current State:</strong> <span id="current-state">-</span></p>
<p><strong>Available Transitions:</strong> <span id="transitions">-</span></p>
</div>
`;
document.body.appendChild(instructions);
`
document.body.appendChild(instructions)
}
/**
@ -244,8 +243,8 @@ class OwenDemo {
* @private
* @returns {void}
*/
sendTestMessage() {
if (!this.owenSystem) return;
sendTestMessage () {
if (!this.owenSystem) return
const testMessages = [
'Hello Owen!',
@ -254,11 +253,11 @@ class OwenDemo {
'Great work!',
'Error in the system!',
'I\'m feeling sad today'
];
]
const randomMessage = testMessages[ Math.floor(Math.random() * testMessages.length) ];
console.log(`Sending message: "${randomMessage}"`);
this.owenSystem.handleUserMessage(randomMessage);
const randomMessage = testMessages[Math.floor(Math.random() * testMessages.length)]
console.log(`Sending message: "${randomMessage}"`)
this.owenSystem.handleUserMessage(randomMessage)
}
/**
@ -266,14 +265,14 @@ class OwenDemo {
* @private
* @returns {void}
*/
logSystemInfo() {
if (!this.owenSystem) return;
logSystemInfo () {
if (!this.owenSystem) return
console.log('=== Owen System Info ===');
console.log('Available States:', this.owenSystem.getAvailableStates());
console.log('Available Clips:', this.owenSystem.getAvailableClips());
console.log('Current State:', this.owenSystem.getCurrentState());
console.log('========================');
console.log('=== Owen System Info ===')
console.log('Available States:', this.owenSystem.getAvailableStates())
console.log('Available Clips:', this.owenSystem.getAvailableClips())
console.log('Current State:', this.owenSystem.getCurrentState())
console.log('========================')
}
/**
@ -281,18 +280,18 @@ class OwenDemo {
* @private
* @returns {void}
*/
updateUI() {
if (!this.owenSystem) return;
updateUI () {
if (!this.owenSystem) return
const currentStateElement = document.getElementById('current-state');
const transitionsElement = document.getElementById('transitions');
const currentStateElement = document.getElementById('current-state')
const transitionsElement = document.getElementById('transitions')
if (currentStateElement) {
currentStateElement.textContent = this.owenSystem.getCurrentState();
currentStateElement.textContent = this.owenSystem.getCurrentState()
}
if (transitionsElement) {
transitionsElement.textContent = this.owenSystem.getAvailableTransitions().join(', ');
transitionsElement.textContent = this.owenSystem.getAvailableTransitions().join(', ')
}
}
@ -301,32 +300,32 @@ class OwenDemo {
* @private
* @returns {void}
*/
animate() {
requestAnimationFrame(() => this.animate());
animate () {
requestAnimationFrame(() => this.animate())
const deltaTime = this.clock.getDelta() * 1000; // Convert to milliseconds
const deltaTime = this.clock.getDelta() * 1000 // Convert to milliseconds
// Update Owen system
if (this.owenSystem) {
this.owenSystem.update(deltaTime);
this.owenSystem.update(deltaTime)
}
// Update UI
this.updateUI();
this.updateUI()
// Render scene
this.renderer.render(this.scene, this.camera);
this.renderer.render(this.scene, this.camera)
}
}
// Initialize the demo when the page loads
window.addEventListener('load', async () => {
const demo = new OwenDemo();
const demo = new OwenDemo()
try {
await demo.init();
await demo.init()
} catch (error) {
console.error('Failed to initialize Owen demo:', error);
console.error('Failed to initialize Owen demo:', error)
}
});
})
export default OwenDemo;
export default OwenDemo

View File

@ -1,15 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Owen Animation System - Basic Demo</title>
<style>
body {
margin: 0;
overflow: hidden;
background: #1a1a1a;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
#loading {
@ -26,20 +26,20 @@
display: none;
}
</style>
</head>
<body>
</head>
<body>
<div id="loading">Loading Owen Animation System...</div>
<script type="module">
import './basic-demo.js';
import "./basic-demo.js";
// Hide loading screen after a short delay
setTimeout(() => {
const loading = document.getElementById('loading');
const loading = document.getElementById("loading");
if (loading) {
loading.classList.add('hidden');
loading.classList.add("hidden");
}
}, 3000);
</script>
</body>
</body>
</html>

View File

@ -3,39 +3,38 @@
* @author Owen Animation System
*/
import { OwenSystemFactory, States } from '../src/index.js';
import { OwenSystemFactory, States } from '../src/index.js'
/**
* Simple example of using Owen Animation System
* This example shows how to use the system without a browser environment
*/
class SimpleOwenExample {
constructor() {
this.owenSystem = null;
constructor () {
this.owenSystem = null
}
/**
* Initialize the Owen system with a mock model
* @returns {Promise<void>}
*/
async init() {
async init () {
try {
// Create a mock GLTF model for demonstration
const mockModel = this.createMockModel();
const mockModel = this.createMockModel()
// Create the Owen system
this.owenSystem = await OwenSystemFactory.createBasicOwenSystem(mockModel);
this.owenSystem = await OwenSystemFactory.createBasicOwenSystem(mockModel)
console.log('✅ Owen Animation System initialized successfully!');
console.log('📊 System Info:');
console.log(` Available States: ${this.owenSystem.getAvailableStates().join(', ')}`);
console.log(` Current State: ${this.owenSystem.getCurrentState()}`);
console.log('✅ Owen Animation System initialized successfully!')
console.log('📊 System Info:')
console.log(` Available States: ${this.owenSystem.getAvailableStates().join(', ')}`)
console.log(` Current State: ${this.owenSystem.getCurrentState()}`)
// Run some example interactions
await this.runExamples();
await this.runExamples()
} catch (error) {
console.error('❌ Failed to initialize Owen system:', error.message);
console.error('❌ Failed to initialize Owen system:', error.message)
}
}
@ -43,7 +42,7 @@ class SimpleOwenExample {
* Create a mock 3D model for demonstration purposes
* @returns {Object} Mock model object
*/
createMockModel() {
createMockModel () {
return {
animations: [
{ name: 'wait_idle_L' },
@ -63,46 +62,46 @@ class SimpleOwenExample {
],
scene: {},
userData: {}
};
}
}
/**
* Run example interactions with the Owen system
* @returns {Promise<void>}
*/
async runExamples() {
console.log('\n🎬 Running example interactions...\n');
async runExamples () {
console.log('\n🎬 Running example interactions...\n')
// Example 1: Basic state transitions
console.log('📝 Example 1: Manual state transitions');
await this.demonstrateStateTransitions();
console.log('📝 Example 1: Manual state transitions')
await this.demonstrateStateTransitions()
// Example 2: Message handling
console.log('\n📝 Example 2: Message handling with emotions');
await this.demonstrateMessageHandling();
console.log('\n📝 Example 2: Message handling with emotions')
await this.demonstrateMessageHandling()
// Example 3: System update loop
console.log('\n📝 Example 3: System update simulation');
this.demonstrateUpdateLoop();
console.log('\n📝 Example 3: System update simulation')
this.demonstrateUpdateLoop()
console.log('\n✨ All examples completed!');
console.log('\n✨ All examples completed!')
}
/**
* Demonstrate manual state transitions
* @returns {Promise<void>}
*/
async demonstrateStateTransitions() {
const states = [ States.REACT, States.TYPE, States.WAIT, States.SLEEP ];
async demonstrateStateTransitions () {
const states = [States.REACT, States.TYPE, States.WAIT, States.SLEEP]
for (const state of states) {
console.log(`🔄 Transitioning to ${state.toUpperCase()} state...`);
await this.owenSystem.transitionTo(state);
console.log(` ✓ Current state: ${this.owenSystem.getCurrentState()}`);
console.log(` ✓ Available transitions: ${this.owenSystem.getAvailableTransitions().join(', ')}`);
console.log(`🔄 Transitioning to ${state.toUpperCase()} state...`)
await this.owenSystem.transitionTo(state)
console.log(` ✓ Current state: ${this.owenSystem.getCurrentState()}`)
console.log(` ✓ Available transitions: ${this.owenSystem.getAvailableTransitions().join(', ')}`)
// Simulate some time passing
await this.sleep(500);
await this.sleep(500)
}
}
@ -110,23 +109,23 @@ class SimpleOwenExample {
* Demonstrate message handling with emotional responses
* @returns {Promise<void>}
*/
async demonstrateMessageHandling() {
async demonstrateMessageHandling () {
const messages = [
{ text: 'Hello Owen!', expected: 'neutral response' },
{ text: 'This is urgent!', expected: 'angry/urgent response' },
{ text: 'Great work!', expected: 'happy response' },
{ text: 'There\'s an error in the system', expected: 'shocked response' },
{ text: 'I\'m feeling sad today', expected: 'sad response' }
];
]
for (const message of messages) {
console.log(`💬 Sending message: "${message.text}"`);
console.log(` Expected: ${message.expected}`);
console.log(`💬 Sending message: "${message.text}"`)
console.log(` Expected: ${message.expected}`)
await this.owenSystem.handleUserMessage(message.text);
console.log(` ✓ Current state after message: ${this.owenSystem.getCurrentState()}`);
await this.owenSystem.handleUserMessage(message.text)
console.log(` ✓ Current state after message: ${this.owenSystem.getCurrentState()}`)
await this.sleep(300);
await this.sleep(300)
}
}
@ -134,26 +133,26 @@ class SimpleOwenExample {
* Demonstrate the system update loop
* @returns {void}
*/
demonstrateUpdateLoop() {
console.log('⏱️ Simulating update loop for 3 seconds...');
demonstrateUpdateLoop () {
console.log('⏱️ Simulating update loop for 3 seconds...')
let iterations = 0;
const startTime = Date.now();
let iterations = 0
const startTime = Date.now()
const updateLoop = () => {
const deltaTime = 16.67; // ~60 FPS
this.owenSystem.update(deltaTime);
iterations++;
const deltaTime = 16.67 // ~60 FPS
this.owenSystem.update(deltaTime)
iterations++
if (Date.now() - startTime < 3000) {
setTimeout(updateLoop, 16);
setTimeout(updateLoop, 16)
} else {
console.log(` ✓ Completed ${iterations} update iterations`);
console.log(` ✓ Final state: ${this.owenSystem.getCurrentState()}`);
console.log(` ✓ Completed ${iterations} update iterations`)
console.log(` ✓ Final state: ${this.owenSystem.getCurrentState()}`)
}
}
};
updateLoop();
updateLoop()
}
/**
@ -161,24 +160,24 @@ class SimpleOwenExample {
* @param {number} ms - Milliseconds to sleep
* @returns {Promise<void>}
*/
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
}
// Run the example if this file is executed directly
if (import.meta.url === `file://${process.argv[ 1 ]}`) {
console.log('🚀 Starting Owen Animation System Example\n');
if (import.meta.url === `file://${process.argv[1]}`) {
console.log('🚀 Starting Owen Animation System Example\n')
const example = new SimpleOwenExample();
const example = new SimpleOwenExample()
example.init()
.then(() => {
console.log('\n🎉 Example completed successfully!');
console.log('💡 Try modifying this example or check out the browser demo in examples/index.html');
console.log('\n🎉 Example completed successfully!')
console.log('💡 Try modifying this example or check out the browser demo in examples/index.html')
})
.catch(error => {
console.error('\n💥 Example failed:', error);
});
console.error('\n💥 Example failed:', error)
})
}
export default SimpleOwenExample;
export default SimpleOwenExample

3311
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,17 +1,18 @@
{
"name": "owen-animation-system",
"version": "1.0.0",
"name": "@kjanat/owen",
"version": "1.0.1",
"description": "A comprehensive Three.js animation system for character state management with clean architecture principles",
"main": "src/index.js",
"types": "src/index.d.ts",
"type": "module",
"scripts": {
"dev": "vite",
"dev": "vite --host",
"build": "vite build",
"preview": "vite preview",
"lint": "eslint src --ext .js",
"lint:fix": "eslint src --ext .js --fix",
"docs": "jsdoc -c jsdoc.config.json"
"lint": "standard",
"lint:fix": "standard --fix",
"docs": "jsdoc -c jsdoc.config.json",
"format": "npx prettier --ignore-path --write '**/*.{html,css}' 'docs/**/*.{html,css}'"
},
"keywords": [
"three.js",
@ -21,17 +22,29 @@
"gltf",
"3d"
],
"author": "Owen Animation System",
"author": "Kaj \"@kjanat\" Kowalski",
"license": "AGPL-3.0-only OR LicenseRef-Commercial",
"dependencies": {
"three": "^0.176.0"
},
"devDependencies": {
"vite": "^6.3.5",
"eslint": "^9.27.0",
"jsdoc": "^4.0.2"
"jsdoc": "^4.0.2",
"pre-commit": "^1.2.2",
"standard": "*",
"vite": "^6.3.5"
},
"engines": {
"node": ">=16.0.0"
}
},
"standard": {
"globals": [
"requestAnimationFrame"
]
},
"pre-commit": [
"lint:fix",
"lint",
"docs",
"format"
]
}

View File

@ -3,8 +3,8 @@
* @module animation
*/
import * as THREE from 'three';
import { ClipTypes, Config } from '../constants.js';
import * as THREE from 'three'
import { ClipTypes, Config } from '../constants.js'
/**
* Represents a single animation clip with metadata and Three.js action
@ -17,36 +17,36 @@ export class AnimationClip {
* @param {THREE.AnimationClip} threeAnimation - The Three.js animation clip
* @param {Object} metadata - Parsed metadata from animation name
*/
constructor(name, threeAnimation, metadata) {
constructor (name, threeAnimation, metadata) {
/**
* The name of the animation clip
* @type {string}
*/
this.name = name;
this.name = name
/**
* The Three.js animation clip
* @type {THREE.AnimationClip}
*/
this.animation = threeAnimation;
this.animation = threeAnimation
/**
* Parsed metadata about the animation
* @type {Object}
*/
this.metadata = metadata;
this.metadata = metadata
/**
* The Three.js animation action
* @type {THREE.AnimationAction|null}
*/
this.action = null;
this.action = null
/**
* The animation mixer
* @type {THREE.AnimationMixer|null}
*/
this.mixer = null;
this.mixer = null
}
/**
@ -54,22 +54,22 @@ export class AnimationClip {
* @param {THREE.AnimationMixer} mixer - The animation mixer
* @returns {THREE.AnimationAction} The created action
*/
createAction(mixer) {
this.mixer = mixer;
this.action = mixer.clipAction(this.animation);
createAction (mixer) {
this.mixer = mixer
this.action = mixer.clipAction(this.animation)
// Configure based on type
if (
this.metadata.type === ClipTypes.LOOP ||
this.metadata.type === ClipTypes.NESTED_LOOP
) {
this.action.setLoop(THREE.LoopRepeat, Infinity);
this.action.setLoop(THREE.LoopRepeat, Infinity)
} else {
this.action.setLoop(THREE.LoopOnce);
this.action.clampWhenFinished = true;
this.action.setLoop(THREE.LoopOnce)
this.action.clampWhenFinished = true
}
return this.action;
return this.action
}
/**
@ -77,11 +77,11 @@ export class AnimationClip {
* @param {number} [fadeInDuration=0.3] - Fade in duration in seconds
* @returns {Promise<void>} Promise that resolves when fade in completes
*/
play(fadeInDuration = Config.DEFAULT_FADE_IN) {
play (fadeInDuration = Config.DEFAULT_FADE_IN) {
if (this.action) {
this.action.reset();
this.action.fadeIn(fadeInDuration);
this.action.play();
this.action.reset()
this.action.fadeIn(fadeInDuration)
this.action.play()
}
}
@ -90,14 +90,14 @@ export class AnimationClip {
* @param {number} [fadeOutDuration=0.3] - Fade out duration in seconds
* @returns {Promise<void>} Promise that resolves when fade out completes
*/
stop(fadeOutDuration = Config.DEFAULT_FADE_OUT) {
stop (fadeOutDuration = Config.DEFAULT_FADE_OUT) {
if (this.action) {
this.action.fadeOut(fadeOutDuration);
this.action.fadeOut(fadeOutDuration)
setTimeout(() => {
if (this.action) {
this.action.stop();
this.action.stop()
}
}, fadeOutDuration * 1000);
}, fadeOutDuration * 1000)
}
}
@ -105,8 +105,8 @@ export class AnimationClip {
* Check if the animation is currently playing
* @returns {boolean} True if playing, false otherwise
*/
isPlaying() {
return this.action?.isRunning() || false;
isPlaying () {
return this.action?.isRunning() || false
}
}
@ -119,18 +119,18 @@ export class AnimationClipFactory {
* Create an animation clip factory
* @param {AnimationLoader} animationLoader - The animation loader instance
*/
constructor(animationLoader) {
constructor (animationLoader) {
/**
* The animation loader for loading animation data
* @type {AnimationLoader}
*/
this.animationLoader = animationLoader;
this.animationLoader = animationLoader
/**
* Cache for created animation clips
* @type {Map<string, AnimationClip>}
*/
this.clipCache = new Map();
this.clipCache = new Map()
}
/**
@ -139,67 +139,67 @@ export class AnimationClipFactory {
* @param {string} name - The animation name to parse
* @returns {Object} Parsed metadata object
*/
parseAnimationName(name) {
const parts = name.split('_');
const state = parts[ 0 ];
const action = parts[ 1 ];
parseAnimationName (name) {
const parts = name.split('_')
const state = parts[0]
const action = parts[1]
// Handle transitions with emotions
if (parts[ 2 ]?.includes('2') && parts[ 3 ] === ClipTypes.TRANSITION) {
const [ , toState ] = parts[ 2 ].split('2');
if (parts[2]?.includes('2') && parts[3] === ClipTypes.TRANSITION) {
const [, toState] = parts[2].split('2')
return {
state,
action,
toState,
emotion: parts[ 2 ] || '',
emotion: parts[2] || '',
type: ClipTypes.TRANSITION,
isTransition: true,
hasEmotion: true,
};
hasEmotion: true
}
}
// Handle regular transitions
if (parts[ 2 ] === ClipTypes.TRANSITION) {
if (parts[2] === ClipTypes.TRANSITION) {
return {
state,
action,
type: ClipTypes.TRANSITION,
isTransition: true,
};
isTransition: true
}
}
// Handle nested animations
if (parts[ 2 ] === ClipTypes.NESTED_IN || parts[ 2 ] === ClipTypes.NESTED_OUT) {
if (parts[2] === ClipTypes.NESTED_IN || parts[2] === ClipTypes.NESTED_OUT) {
return {
state,
action,
type: parts[ 2 ],
nestedType: parts[ 3 ],
isNested: true,
};
type: parts[2],
nestedType: parts[3],
isNested: true
}
}
// Handle nested loops and quirks
if (
parts[ 3 ] === ClipTypes.NESTED_LOOP ||
parts[ 3 ] === ClipTypes.NESTED_QUIRK
parts[3] === ClipTypes.NESTED_LOOP ||
parts[3] === ClipTypes.NESTED_QUIRK
) {
return {
state,
action,
subAction: parts[ 2 ],
type: parts[ 3 ],
isNested: true,
};
subAction: parts[2],
type: parts[3],
isNested: true
}
}
// Handle standard loops and quirks
return {
state,
action,
type: parts[ 2 ],
isStandard: true,
};
type: parts[2],
isStandard: true
}
}
/**
@ -207,18 +207,18 @@ export class AnimationClipFactory {
* @param {string} name - The animation name
* @returns {Promise<AnimationClip>} The created animation clip
*/
async createClip(name) {
async createClip (name) {
if (this.clipCache.has(name)) {
return this.clipCache.get(name);
return this.clipCache.get(name)
}
const metadata = this.parseAnimationName(name);
const animation = await this.animationLoader.loadAnimation(name);
const metadata = this.parseAnimationName(name)
const animation = await this.animationLoader.loadAnimation(name)
const clip = new AnimationClip(name, animation, metadata);
this.clipCache.set(name, clip);
const clip = new AnimationClip(name, animation, metadata)
this.clipCache.set(name, clip)
return clip;
return clip
}
/**
@ -226,24 +226,24 @@ export class AnimationClipFactory {
* @param {THREE.Object3D} model - The 3D model containing animations
* @returns {Promise<Map<string, AnimationClip>>} Map of animation name to clip
*/
async createClipsFromModel(model) {
const clips = new Map();
const animations = model.animations || [];
async createClipsFromModel (model) {
const clips = new Map()
const animations = model.animations || []
for (const animation of animations) {
const clip = await this.createClip(animation.name, model);
clips.set(animation.name, clip);
const clip = await this.createClip(animation.name, model)
clips.set(animation.name, clip)
}
return clips;
return clips
}
/**
* Clear the clip cache
* @returns {void}
*/
clearCache() {
this.clipCache.clear();
clearCache () {
this.clipCache.clear()
}
/**
@ -251,7 +251,7 @@ export class AnimationClipFactory {
* @param {string} name - The animation name
* @returns {AnimationClip|undefined} The cached clip or undefined
*/
getCachedClip(name) {
return this.clipCache.get(name);
getCachedClip (name) {
return this.clipCache.get(name)
}
}

View File

@ -22,8 +22,8 @@ export const ClipTypes = {
/** Nested out transition */
NESTED_OUT: 'OUT_NT',
/** Transition animation */
TRANSITION: 'T',
};
TRANSITION: 'T'
}
/**
* Character animation states
@ -38,8 +38,8 @@ export const States = {
/** Typing response state */
TYPE: 'type',
/** Sleep/inactive state */
SLEEP: 'sleep',
};
SLEEP: 'sleep'
}
/**
* Character emotional states
@ -56,8 +56,8 @@ export const Emotions = {
/** Happy emotion */
HAPPY: 'ha',
/** Sad emotion */
SAD: 'sa',
};
SAD: 'sa'
}
/**
* Default configuration values
@ -74,5 +74,5 @@ export const Config = {
/** Default inactivity timeout (ms) */
INACTIVITY_TIMEOUT: 60000,
/** Quirk probability threshold */
QUIRK_PROBABILITY: 0.3,
};
QUIRK_PROBABILITY: 0.3
}

View File

@ -3,7 +3,7 @@
* @module core
*/
import { States, Emotions, Config } from '../constants.js';
import { States, Emotions, Config } from '../constants.js'
/**
* Main controller for the Owen animation system
@ -18,97 +18,97 @@ export class OwenAnimationContext {
* @param {AnimationClipFactory} animationClipFactory - Factory for creating clips
* @param {StateFactory} stateFactory - Factory for creating state handlers
*/
constructor(model, mixer, animationClipFactory, stateFactory) {
constructor (model, mixer, animationClipFactory, stateFactory) {
/**
* The 3D character model
* @type {THREE.Object3D}
*/
this.model = model;
this.model = model
/**
* The Three.js animation mixer
* @type {THREE.AnimationMixer}
*/
this.mixer = mixer;
this.mixer = mixer
/**
* Factory for creating animation clips
* @type {AnimationClipFactory}
*/
this.animationClipFactory = animationClipFactory;
this.animationClipFactory = animationClipFactory
/**
* Factory for creating state handlers
* @type {StateFactory}
*/
this.stateFactory = stateFactory;
this.stateFactory = stateFactory
/**
* Map of animation clips by name
* @type {Map<string, AnimationClip>}
*/
this.clips = new Map();
this.clips = new Map()
/**
* Map of state handlers by name
* @type {Map<string, StateHandler>}
*/
this.states = new Map();
this.states = new Map()
/**
* Current active state
* @type {string}
*/
this.currentState = States.WAIT;
this.currentState = States.WAIT
/**
* Current active state handler
* @type {StateHandler|null}
*/
this.currentStateHandler = null;
this.currentStateHandler = null
/**
* Timer for inactivity detection
* @type {number}
*/
this.inactivityTimer = 0;
this.inactivityTimer = 0
/**
* Inactivity timeout in milliseconds
* @type {number}
*/
this.inactivityTimeout = Config.INACTIVITY_TIMEOUT;
this.inactivityTimeout = Config.INACTIVITY_TIMEOUT
/**
* Whether the system is initialized
* @type {boolean}
*/
this.initialized = false;
this.initialized = false
}
/**
* Initialize the animation system
* @returns {Promise<void>}
*/
async initialize() {
if (this.initialized) return;
async initialize () {
if (this.initialized) return
// Create animation clips from model
this.clips = await this.animationClipFactory.createClipsFromModel(this.model);
this.clips = await this.animationClipFactory.createClipsFromModel(this.model)
// Create actions for all clips
for (const [ , clip ] of this.clips) {
clip.createAction(this.mixer);
for (const [, clip] of this.clips) {
clip.createAction(this.mixer)
}
// Initialize state handlers
this.initializeStates();
this.initializeStates()
// Start in wait state
await this.transitionTo(States.WAIT);
await this.transitionTo(States.WAIT)
this.initialized = true;
console.log('Owen Animation System initialized');
this.initialized = true
console.log('Owen Animation System initialized')
}
/**
@ -116,12 +116,12 @@ export class OwenAnimationContext {
* @private
* @returns {void}
*/
initializeStates() {
const stateNames = this.stateFactory.getAvailableStates();
initializeStates () {
const stateNames = this.stateFactory.getAvailableStates()
for (const stateName of stateNames) {
const handler = this.stateFactory.createStateHandler(stateName, this);
this.states.set(stateName, handler);
const handler = this.stateFactory.createStateHandler(stateName, this)
this.states.set(stateName, handler)
}
}
@ -132,28 +132,28 @@ export class OwenAnimationContext {
* @returns {Promise<void>}
* @throws {Error} If state is not found or transition is invalid
*/
async transitionTo(newStateName, emotion = Emotions.NEUTRAL) {
async transitionTo (newStateName, emotion = Emotions.NEUTRAL) {
if (!this.states.has(newStateName)) {
throw new Error(`State '${newStateName}' not found`);
throw new Error(`State '${newStateName}' not found`)
}
const oldState = this.currentState;
const newStateHandler = this.states.get(newStateName);
const oldState = this.currentState
const newStateHandler = this.states.get(newStateName)
console.log(`Transitioning from ${oldState} to ${newStateName}`);
console.log(`Transitioning from ${oldState} to ${newStateName}`)
// Exit current state
if (this.currentStateHandler) {
await this.currentStateHandler.exit(newStateName, emotion);
await this.currentStateHandler.exit(newStateName, emotion)
}
// Enter new state
this.currentState = newStateName;
this.currentStateHandler = newStateHandler;
await this.currentStateHandler.enter(oldState, emotion);
this.currentState = newStateName
this.currentStateHandler = newStateHandler
await this.currentStateHandler.enter(oldState, emotion)
// Reset inactivity timer
this.resetActivityTimer();
this.resetActivityTimer()
}
/**
@ -161,26 +161,26 @@ export class OwenAnimationContext {
* @param {string} message - The user message
* @returns {Promise<void>}
*/
async handleUserMessage(message) {
console.log(`Handling user message: "${message}"`);
async handleUserMessage (message) {
console.log(`Handling user message: "${message}"`)
this.onUserActivity();
this.onUserActivity()
// If sleeping, wake up first
if (this.currentState === States.SLEEP) {
await this.transitionTo(States.REACT);
await this.transitionTo(States.REACT)
}
// Let current state handle the message
if (this.currentStateHandler) {
await this.currentStateHandler.handleMessage(message);
await this.currentStateHandler.handleMessage(message)
}
// Transition to appropriate next state based on current state
if (this.currentState === States.WAIT) {
await this.transitionTo(States.REACT);
await this.transitionTo(States.REACT)
} else if (this.currentState === States.REACT) {
await this.transitionTo(States.TYPE);
await this.transitionTo(States.TYPE)
}
}
@ -188,12 +188,12 @@ export class OwenAnimationContext {
* Called when user activity is detected
* @returns {void}
*/
onUserActivity() {
this.resetActivityTimer();
onUserActivity () {
this.resetActivityTimer()
// Wake up if sleeping
if (this.currentState === States.SLEEP) {
this.transitionTo(States.WAIT);
this.transitionTo(States.WAIT)
}
}
@ -202,8 +202,8 @@ export class OwenAnimationContext {
* @private
* @returns {void}
*/
resetActivityTimer() {
this.inactivityTimer = 0;
resetActivityTimer () {
this.inactivityTimer = 0
}
/**
@ -211,9 +211,9 @@ export class OwenAnimationContext {
* @private
* @returns {Promise<void>}
*/
async handleInactivity() {
console.log('Inactivity detected, transitioning to sleep');
await this.transitionTo(States.SLEEP);
async handleInactivity () {
console.log('Inactivity detected, transitioning to sleep')
await this.transitionTo(States.SLEEP)
}
/**
@ -221,21 +221,21 @@ export class OwenAnimationContext {
* @param {number} deltaTime - Time elapsed since last update (ms)
* @returns {void}
*/
update(deltaTime) {
if (!this.initialized) return;
update (deltaTime) {
if (!this.initialized) return
// Update Three.js mixer
this.mixer.update(deltaTime / 1000); // Convert to seconds
this.mixer.update(deltaTime / 1000) // Convert to seconds
// Update current state
if (this.currentStateHandler) {
this.currentStateHandler.update(deltaTime);
this.currentStateHandler.update(deltaTime)
}
// Update inactivity timer
this.inactivityTimer += deltaTime;
this.inactivityTimer += deltaTime
if (this.inactivityTimer > this.inactivityTimeout && this.currentState !== States.SLEEP) {
this.handleInactivity();
this.handleInactivity()
}
}
@ -244,8 +244,8 @@ export class OwenAnimationContext {
* @param {string} name - The animation clip name
* @returns {AnimationClip|undefined} The animation clip or undefined if not found
*/
getClip(name) {
return this.clips.get(name);
getClip (name) {
return this.clips.get(name)
}
/**
@ -253,80 +253,80 @@ export class OwenAnimationContext {
* @param {string} pattern - Pattern to match (supports * wildcards)
* @returns {AnimationClip[]} Array of matching clips
*/
getClipsByPattern(pattern) {
const regex = new RegExp(pattern.replace(/\*/g, '.*'));
const matches = [];
getClipsByPattern (pattern) {
const regex = new RegExp(pattern.replace(/\*/g, '.*'))
const matches = []
for (const [ name, clip ] of this.clips) {
for (const [name, clip] of this.clips) {
if (regex.test(name)) {
matches.push(clip);
matches.push(clip)
}
}
return matches;
return matches
}
/**
* Get the current state name
* @returns {string} The current state name
*/
getCurrentState() {
return this.currentState;
getCurrentState () {
return this.currentState
}
/**
* Get the current state handler
* @returns {StateHandler|null} The current state handler
*/
getCurrentStateHandler() {
return this.currentStateHandler;
getCurrentStateHandler () {
return this.currentStateHandler
}
/**
* Get available transitions from current state
* @returns {string[]} Array of available state transitions
*/
getAvailableTransitions() {
getAvailableTransitions () {
if (this.currentStateHandler) {
return this.currentStateHandler.getAvailableTransitions();
return this.currentStateHandler.getAvailableTransitions()
}
return [];
return []
}
/**
* Get all available animation clip names
* @returns {string[]} Array of clip names
*/
getAvailableClips() {
return Array.from(this.clips.keys());
getAvailableClips () {
return Array.from(this.clips.keys())
}
/**
* Get all available state names
* @returns {string[]} Array of state names
*/
getAvailableStates() {
return Array.from(this.states.keys());
getAvailableStates () {
return Array.from(this.states.keys())
}
/**
* Dispose of the animation system and clean up resources
* @returns {void}
*/
dispose() {
dispose () {
// Stop all animations
for (const [ , clip ] of this.clips) {
for (const [, clip] of this.clips) {
if (clip.action) {
clip.action.stop();
clip.action.stop()
}
}
// Clear caches
this.clips.clear();
this.states.clear();
this.animationClipFactory.clearCache();
this.clips.clear()
this.states.clear()
this.animationClipFactory.clearCache()
this.initialized = false;
console.log('Owen Animation System disposed');
this.initialized = false
console.log('Owen Animation System disposed')
}
}

View File

@ -3,11 +3,11 @@
* @module factories
*/
import * as THREE from 'three';
import { OwenAnimationContext } from '../core/OwenAnimationContext.js';
import { AnimationClipFactory } from '../animation/AnimationClip.js';
import { GLTFAnimationLoader } from '../loaders/AnimationLoader.js';
import { StateFactory } from '../states/StateFactory.js';
import * as THREE from 'three'
import { OwenAnimationContext } from '../core/OwenAnimationContext.js'
import { AnimationClipFactory } from '../animation/AnimationClip.js'
import { GLTFAnimationLoader } from '../loaders/AnimationLoader.js'
import { StateFactory } from '../states/StateFactory.js'
/**
* Main factory for creating the complete Owen animation system
@ -22,24 +22,24 @@ export class OwenSystemFactory {
* @param {THREE.GLTFLoader} [options.gltfLoader] - Custom GLTF loader
* @returns {Promise<OwenAnimationContext>} The configured Owen system
*/
static async createOwenSystem(gltfModel, scene, options = {}) {
static async createOwenSystem (gltfModel, scene, options = {}) {
// Create Three.js animation mixer
const mixer = new THREE.AnimationMixer(gltfModel);
const mixer = new THREE.AnimationMixer(gltfModel)
// Create GLTF loader if not provided
const gltfLoader = options.gltfLoader || new THREE.GLTFLoader();
const gltfLoader = options.gltfLoader || new THREE.GLTFLoader()
// Create animation loader
const animationLoader = new GLTFAnimationLoader(gltfLoader);
const animationLoader = new GLTFAnimationLoader(gltfLoader)
// Preload animations from the model
await animationLoader.preloadAnimations(gltfModel);
await animationLoader.preloadAnimations(gltfModel)
// Create animation clip factory
const animationClipFactory = new AnimationClipFactory(animationLoader);
const animationClipFactory = new AnimationClipFactory(animationLoader)
// Create state factory
const stateFactory = new StateFactory();
const stateFactory = new StateFactory()
// Create the main Owen context
const owenContext = new OwenAnimationContext(
@ -47,12 +47,12 @@ export class OwenSystemFactory {
mixer,
animationClipFactory,
stateFactory
);
)
// Initialize the system
await owenContext.initialize();
await owenContext.initialize()
return owenContext;
return owenContext
}
/**
@ -60,11 +60,11 @@ export class OwenSystemFactory {
* @param {THREE.Object3D} model - The 3D model
* @returns {Promise<OwenAnimationContext>} The configured Owen system
*/
static async createBasicOwenSystem(model) {
const scene = new THREE.Scene();
scene.add(model);
static async createBasicOwenSystem (model) {
const scene = new THREE.Scene()
scene.add(model)
return await OwenSystemFactory.createOwenSystem(model, scene);
return await OwenSystemFactory.createOwenSystem(model, scene)
}
/**
@ -74,18 +74,18 @@ export class OwenSystemFactory {
* @param {Map<string, Function>} customStates - Map of state name to handler class
* @returns {Promise<OwenAnimationContext>} The configured Owen system
*/
static async createCustomOwenSystem(gltfModel, scene, customStates) {
const system = await OwenSystemFactory.createOwenSystem(gltfModel, scene);
static async createCustomOwenSystem (gltfModel, scene, customStates) {
const system = await OwenSystemFactory.createOwenSystem(gltfModel, scene)
// Register custom state handlers
const stateFactory = system.stateFactory;
for (const [ stateName, handlerClass ] of customStates) {
stateFactory.registerStateHandler(stateName, handlerClass);
const stateFactory = system.stateFactory
for (const [stateName, handlerClass] of customStates) {
stateFactory.registerStateHandler(stateName, handlerClass)
}
// Reinitialize with custom states
system.initializeStates();
system.initializeStates()
return system;
return system
}
}

View File

@ -4,32 +4,32 @@
*/
// Core exports
export { OwenAnimationContext } from './core/OwenAnimationContext.js';
// Import for default export
import { OwenSystemFactory } from './factories/OwenSystemFactory.js'
import { OwenAnimationContext } from './core/OwenAnimationContext.js'
import { States, Emotions, ClipTypes, Config } from './constants.js'
export { OwenAnimationContext } from './core/OwenAnimationContext.js'
// Animation system exports
export { AnimationClip, AnimationClipFactory } from './animation/AnimationClip.js';
export { AnimationClip, AnimationClipFactory } from './animation/AnimationClip.js'
// Loader exports
export { AnimationLoader, GLTFAnimationLoader } from './loaders/AnimationLoader.js';
export { AnimationLoader, GLTFAnimationLoader } from './loaders/AnimationLoader.js'
// State system exports
export { StateHandler } from './states/StateHandler.js';
export { WaitStateHandler } from './states/WaitStateHandler.js';
export { ReactStateHandler } from './states/ReactStateHandler.js';
export { TypeStateHandler } from './states/TypeStateHandler.js';
export { SleepStateHandler } from './states/SleepStateHandler.js';
export { StateFactory } from './states/StateFactory.js';
export { StateHandler } from './states/StateHandler.js'
export { WaitStateHandler } from './states/WaitStateHandler.js'
export { ReactStateHandler } from './states/ReactStateHandler.js'
export { TypeStateHandler } from './states/TypeStateHandler.js'
export { SleepStateHandler } from './states/SleepStateHandler.js'
export { StateFactory } from './states/StateFactory.js'
// Factory exports
export { OwenSystemFactory } from './factories/OwenSystemFactory.js';
export { OwenSystemFactory } from './factories/OwenSystemFactory.js'
// Constants exports
export { ClipTypes, States, Emotions, Config } from './constants.js';
// Import for default export
import { OwenSystemFactory } from './factories/OwenSystemFactory.js';
import { OwenAnimationContext } from './core/OwenAnimationContext.js';
import { States, Emotions, ClipTypes, Config } from './constants.js';
export { ClipTypes, States, Emotions, Config } from './constants.js'
/**
* Default export - the main factory for easy usage
@ -41,4 +41,4 @@ export default {
Emotions,
ClipTypes,
Config
};
}

View File

@ -16,8 +16,8 @@ export class AnimationLoader {
* @returns {Promise<THREE.AnimationClip>} The loaded animation clip
* @throws {Error} Must be implemented by subclasses
*/
async loadAnimation(_name) {
throw new Error('loadAnimation method must be implemented by subclasses');
async loadAnimation (_name) {
throw new Error('loadAnimation method must be implemented by subclasses')
}
}
@ -31,20 +31,20 @@ export class GLTFAnimationLoader extends AnimationLoader {
* Create a GLTF animation loader
* @param {THREE.GLTFLoader} gltfLoader - The Three.js GLTF loader instance
*/
constructor(gltfLoader) {
super();
constructor (gltfLoader) {
super()
/**
* The Three.js GLTF loader
* @type {THREE.GLTFLoader}
*/
this.gltfLoader = gltfLoader;
this.gltfLoader = gltfLoader
/**
* Cache for loaded animations
* @type {Map<string, THREE.AnimationClip>}
*/
this.animationCache = new Map();
this.animationCache = new Map()
}
/**
@ -53,14 +53,14 @@ export class GLTFAnimationLoader extends AnimationLoader {
* @returns {Promise<THREE.AnimationClip>} The loaded animation clip
* @throws {Error} If animation is not found
*/
async loadAnimation(name) {
async loadAnimation (name) {
if (this.animationCache.has(name)) {
return this.animationCache.get(name);
return this.animationCache.get(name)
}
// In a real implementation, this would load from GLTF files
// For now, we'll assume animations are already loaded in the model
throw new Error(`Animation '${name}' not found. Implement GLTF loading logic.`);
throw new Error(`Animation '${name}' not found. Implement GLTF loading logic.`)
}
/**
@ -68,10 +68,10 @@ export class GLTFAnimationLoader extends AnimationLoader {
* @param {Object} gltfModel - The loaded GLTF model
* @returns {Promise<void>}
*/
async preloadAnimations(gltfModel) {
async preloadAnimations (gltfModel) {
if (gltfModel.animations) {
for (const animation of gltfModel.animations) {
this.animationCache.set(animation.name, animation);
this.animationCache.set(animation.name, animation)
}
}
}
@ -80,15 +80,15 @@ export class GLTFAnimationLoader extends AnimationLoader {
* Clear the animation cache
* @returns {void}
*/
clearCache() {
this.animationCache.clear();
clearCache () {
this.animationCache.clear()
}
/**
* Get all cached animation names
* @returns {string[]} Array of cached animation names
*/
getCachedAnimationNames() {
return Array.from(this.animationCache.keys());
getCachedAnimationNames () {
return Array.from(this.animationCache.keys())
}
}

View File

@ -3,8 +3,8 @@
* @module states
*/
import { StateHandler } from './StateHandler.js';
import { States, Emotions } from '../constants.js';
import { StateHandler } from './StateHandler.js'
import { States, Emotions } from '../constants.js'
/**
* Handler for the React state
@ -16,14 +16,14 @@ export class ReactStateHandler extends StateHandler {
* Create a react state handler
* @param {OwenAnimationContext} context - The animation context
*/
constructor(context) {
super(States.REACT, context);
constructor (context) {
super(States.REACT, context)
/**
* Current emotional state
* @type {string}
*/
this.emotion = Emotions.NEUTRAL;
this.emotion = Emotions.NEUTRAL
}
/**
@ -32,15 +32,15 @@ export class ReactStateHandler extends StateHandler {
* @param {string} [emotion=Emotions.NEUTRAL] - The emotion to enter with
* @returns {Promise<void>}
*/
async enter(_fromState = null, emotion = Emotions.NEUTRAL) {
console.log(`Entering REACT state with emotion: ${emotion}`);
this.emotion = emotion;
async enter (_fromState = null, emotion = Emotions.NEUTRAL) {
console.log(`Entering REACT state with emotion: ${emotion}`)
this.emotion = emotion
// Play appropriate reaction
const reactionClip = this.context.getClip('react_idle_L');
const reactionClip = this.context.getClip('react_idle_L')
if (reactionClip) {
await reactionClip.play();
this.currentClip = reactionClip;
await reactionClip.play()
this.currentClip = reactionClip
}
}
@ -50,25 +50,25 @@ export class ReactStateHandler extends StateHandler {
* @param {string} [emotion=Emotions.NEUTRAL] - The emotion to exit with
* @returns {Promise<void>}
*/
async exit(toState = null, emotion = Emotions.NEUTRAL) {
console.log(`Exiting REACT state to ${toState} with emotion: ${emotion}`);
async exit (toState = null, emotion = Emotions.NEUTRAL) {
console.log(`Exiting REACT state to ${toState} with emotion: ${emotion}`)
if (this.currentClip) {
await this.stopCurrentClip();
await this.stopCurrentClip()
}
// Play emotional transition if available
let transitionName;
let transitionName
if (emotion !== Emotions.NEUTRAL) {
transitionName = `react_${this.emotion}2${toState}_${emotion}_T`;
transitionName = `react_${this.emotion}2${toState}_${emotion}_T`
} else {
transitionName = `react_2${toState}_T`;
transitionName = `react_2${toState}_T`
}
const transition = this.context.getClip(transitionName);
const transition = this.context.getClip(transitionName)
if (transition) {
await transition.play();
await this.waitForClipEnd(transition);
await transition.play()
await this.waitForClipEnd(transition)
}
}
@ -77,20 +77,20 @@ export class ReactStateHandler extends StateHandler {
* @param {string} message - The user message
* @returns {Promise<void>}
*/
async handleMessage(message) {
async handleMessage (message) {
// Analyze message sentiment to determine emotion
const emotion = this.analyzeMessageEmotion(message);
this.emotion = emotion;
const emotion = this.analyzeMessageEmotion(message)
this.emotion = emotion
// Play emotional reaction if needed
if (emotion !== Emotions.NEUTRAL) {
const emotionalReaction = this.context.getClip(`react_${emotion}_Q`);
const emotionalReaction = this.context.getClip(`react_${emotion}_Q`)
if (emotionalReaction) {
if (this.currentClip) {
await this.stopCurrentClip(0.2);
await this.stopCurrentClip(0.2)
}
await emotionalReaction.play();
await this.waitForClipEnd(emotionalReaction);
await emotionalReaction.play()
await this.waitForClipEnd(emotionalReaction)
}
}
}
@ -101,8 +101,8 @@ export class ReactStateHandler extends StateHandler {
* @param {string} message - The message to analyze
* @returns {string} The determined emotion
*/
analyzeMessageEmotion(message) {
const text = message.toLowerCase();
analyzeMessageEmotion (message) {
const text = message.toLowerCase()
// Check for urgent/angry indicators
if (
@ -111,7 +111,7 @@ export class ReactStateHandler extends StateHandler {
text.includes('asap') ||
text.includes('hurry')
) {
return Emotions.ANGRY;
return Emotions.ANGRY
}
// Check for error/shocked indicators
@ -122,7 +122,7 @@ export class ReactStateHandler extends StateHandler {
text.includes('bug') ||
text.includes('broken')
) {
return Emotions.SHOCKED;
return Emotions.SHOCKED
}
// Check for positive/happy indicators
@ -133,7 +133,7 @@ export class ReactStateHandler extends StateHandler {
text.includes('excellent') ||
text.includes('perfect')
) {
return Emotions.HAPPY;
return Emotions.HAPPY
}
// Check for sad indicators
@ -143,17 +143,17 @@ export class ReactStateHandler extends StateHandler {
text.includes('failed') ||
text.includes('wrong')
) {
return Emotions.SAD;
return Emotions.SAD
}
return Emotions.NEUTRAL;
return Emotions.NEUTRAL
}
/**
* Get available transitions from react state
* @returns {string[]} Array of available state transitions
*/
getAvailableTransitions() {
return [ States.TYPE, States.WAIT ];
getAvailableTransitions () {
return [States.TYPE, States.WAIT]
}
}

View File

@ -3,8 +3,8 @@
* @module states
*/
import { StateHandler } from './StateHandler.js';
import { States, Emotions } from '../constants.js';
import { StateHandler } from './StateHandler.js'
import { States, Emotions } from '../constants.js'
/**
* Handler for the Sleep state
@ -16,20 +16,20 @@ export class SleepStateHandler extends StateHandler {
* Create a sleep state handler
* @param {OwenAnimationContext} context - The animation context
*/
constructor(context) {
super(States.SLEEP, context);
constructor (context) {
super(States.SLEEP, context)
/**
* Sleep animation clip
* @type {AnimationClip|null}
*/
this.sleepClip = null;
this.sleepClip = null
/**
* Whether the character is in deep sleep
* @type {boolean}
*/
this.isDeepSleep = false;
this.isDeepSleep = false
}
/**
@ -38,24 +38,24 @@ export class SleepStateHandler extends StateHandler {
* @param {string} [_emotion=Emotions.NEUTRAL] - The emotion to enter with (unused)
* @returns {Promise<void>}
*/
async enter(fromState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Entering SLEEP state from ${fromState}`);
async enter (fromState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Entering SLEEP state from ${fromState}`)
// Play sleep transition if available
const sleepTransition = this.context.getClip('wait_2sleep_T');
const sleepTransition = this.context.getClip('wait_2sleep_T')
if (sleepTransition) {
await sleepTransition.play();
await this.waitForClipEnd(sleepTransition);
await sleepTransition.play()
await this.waitForClipEnd(sleepTransition)
}
// Start sleep loop
this.sleepClip = this.context.getClip('sleep_idle_L');
this.sleepClip = this.context.getClip('sleep_idle_L')
if (this.sleepClip) {
await this.sleepClip.play();
this.currentClip = this.sleepClip;
await this.sleepClip.play()
this.currentClip = this.sleepClip
}
this.isDeepSleep = true;
this.isDeepSleep = true
}
/**
@ -64,27 +64,27 @@ export class SleepStateHandler extends StateHandler {
* @param {string} [emotion=Emotions.NEUTRAL] - The emotion to exit with
* @returns {Promise<void>}
*/
async exit(toState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Exiting SLEEP state to ${toState}`);
this.isDeepSleep = false;
async exit (toState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Exiting SLEEP state to ${toState}`)
this.isDeepSleep = false
if (this.currentClip) {
await this.stopCurrentClip();
await this.stopCurrentClip()
}
// Play wake up animation
const wakeUpClip = this.context.getClip('sleep_wakeup_T');
const wakeUpClip = this.context.getClip('sleep_wakeup_T')
if (wakeUpClip) {
await wakeUpClip.play();
await this.waitForClipEnd(wakeUpClip);
await wakeUpClip.play()
await this.waitForClipEnd(wakeUpClip)
}
// Play transition to next state if available
const transitionName = `sleep_2${toState}_T`;
const transition = this.context.getClip(transitionName);
const transitionName = `sleep_2${toState}_T`
const transition = this.context.getClip(transitionName)
if (transition) {
await transition.play();
await this.waitForClipEnd(transition);
await transition.play()
await this.waitForClipEnd(transition)
}
}
@ -93,7 +93,7 @@ export class SleepStateHandler extends StateHandler {
* @param {number} _deltaTime - Time elapsed since last update (ms, unused)
* @returns {void}
*/
update(_deltaTime) {
update (_deltaTime) {
// Sleep state doesn't need regular updates
// Character remains asleep until external stimulus
}
@ -103,12 +103,12 @@ export class SleepStateHandler extends StateHandler {
* @param {string} _message - The user message (unused, just triggers wake up)
* @returns {Promise<void>}
*/
async handleMessage(_message) {
async handleMessage (_message) {
// Any message should wake up the character
if (this.isDeepSleep) {
console.log('Waking up due to user message');
console.log('Waking up due to user message')
// This will trigger a state transition to REACT
await this.context.transitionTo(States.REACT);
await this.context.transitionTo(States.REACT)
}
}
@ -116,25 +116,25 @@ export class SleepStateHandler extends StateHandler {
* Get available transitions from sleep state
* @returns {string[]} Array of available state transitions
*/
getAvailableTransitions() {
return [ States.WAIT, States.REACT ];
getAvailableTransitions () {
return [States.WAIT, States.REACT]
}
/**
* Check if in deep sleep
* @returns {boolean} True if in deep sleep, false otherwise
*/
isInDeepSleep() {
return this.isDeepSleep;
isInDeepSleep () {
return this.isDeepSleep
}
/**
* Force wake up from sleep
* @returns {Promise<void>}
*/
async wakeUp() {
async wakeUp () {
if (this.isDeepSleep) {
await this.context.transitionTo(States.WAIT);
await this.context.transitionTo(States.WAIT)
}
}
}

View File

@ -3,11 +3,11 @@
* @module states
*/
import { WaitStateHandler } from './WaitStateHandler.js';
import { ReactStateHandler } from './ReactStateHandler.js';
import { TypeStateHandler } from './TypeStateHandler.js';
import { SleepStateHandler } from './SleepStateHandler.js';
import { States } from '../constants.js';
import { WaitStateHandler } from './WaitStateHandler.js'
import { ReactStateHandler } from './ReactStateHandler.js'
import { TypeStateHandler } from './TypeStateHandler.js'
import { SleepStateHandler } from './SleepStateHandler.js'
import { States } from '../constants.js'
/**
* Factory for creating state handlers using dependency injection
@ -17,19 +17,19 @@ export class StateFactory {
/**
* Create a state factory
*/
constructor() {
constructor () {
/**
* Registry of state handler classes
* @type {Map<string, Function>}
* @private
*/
this.stateHandlers = new Map();
this.stateHandlers = new Map()
// Register default state handlers
this.registerStateHandler(States.WAIT, WaitStateHandler);
this.registerStateHandler(States.REACT, ReactStateHandler);
this.registerStateHandler(States.TYPE, TypeStateHandler);
this.registerStateHandler(States.SLEEP, SleepStateHandler);
this.registerStateHandler(States.WAIT, WaitStateHandler)
this.registerStateHandler(States.REACT, ReactStateHandler)
this.registerStateHandler(States.TYPE, TypeStateHandler)
this.registerStateHandler(States.SLEEP, SleepStateHandler)
}
/**
@ -38,8 +38,8 @@ export class StateFactory {
* @param {Function} handlerClass - The handler class constructor
* @returns {void}
*/
registerStateHandler(stateName, handlerClass) {
this.stateHandlers.set(stateName, handlerClass);
registerStateHandler (stateName, handlerClass) {
this.stateHandlers.set(stateName, handlerClass)
}
/**
@ -49,21 +49,21 @@ export class StateFactory {
* @returns {StateHandler} The created state handler
* @throws {Error} If state handler is not registered
*/
createStateHandler(stateName, context) {
const HandlerClass = this.stateHandlers.get(stateName);
createStateHandler (stateName, context) {
const HandlerClass = this.stateHandlers.get(stateName)
if (!HandlerClass) {
throw new Error(`No handler registered for state: ${stateName}`);
throw new Error(`No handler registered for state: ${stateName}`)
}
return new HandlerClass(context);
return new HandlerClass(context)
}
/**
* Get all available state names
* @returns {string[]} Array of registered state names
*/
getAvailableStates() {
return Array.from(this.stateHandlers.keys());
getAvailableStates () {
return Array.from(this.stateHandlers.keys())
}
/**
@ -71,8 +71,8 @@ export class StateFactory {
* @param {string} stateName - The state name to check
* @returns {boolean} True if registered, false otherwise
*/
isStateRegistered(stateName) {
return this.stateHandlers.has(stateName);
isStateRegistered (stateName) {
return this.stateHandlers.has(stateName)
}
/**
@ -80,7 +80,7 @@ export class StateFactory {
* @param {string} stateName - The state name to unregister
* @returns {boolean} True if removed, false if not found
*/
unregisterStateHandler(stateName) {
return this.stateHandlers.delete(stateName);
unregisterStateHandler (stateName) {
return this.stateHandlers.delete(stateName)
}
}

View File

@ -3,7 +3,7 @@
* @module StateHandler
*/
import { Emotions, Config } from '../constants.js';
import { Emotions, Config } from '../constants.js'
/**
* Abstract base class for state handlers
@ -16,30 +16,30 @@ export class StateHandler {
* @param {string} stateName - The name of the state
* @param {OwenAnimationContext} context - The animation context
*/
constructor(stateName, context) {
constructor (stateName, context) {
/**
* The name of this state
* @type {string}
*/
this.stateName = stateName;
this.stateName = stateName
/**
* The animation context
* @type {OwenAnimationContext}
*/
this.context = context;
this.context = context
/**
* Currently playing animation clip
* @type {AnimationClip|null}
*/
this.currentClip = null;
this.currentClip = null
/**
* Nested state information
* @type {Object|null}
*/
this.nestedState = null;
this.nestedState = null
}
/**
@ -50,8 +50,8 @@ export class StateHandler {
* @returns {Promise<void>}
* @throws {Error} Must be implemented by subclasses
*/
async enter(_fromState = null, _emotion = Emotions.NEUTRAL) {
throw new Error('enter method must be implemented by subclasses');
async enter (_fromState = null, _emotion = Emotions.NEUTRAL) {
throw new Error('enter method must be implemented by subclasses')
}
/**
@ -62,8 +62,8 @@ export class StateHandler {
* @returns {Promise<void>}
* @throws {Error} Must be implemented by subclasses
*/
async exit(_toState = null, _emotion = Emotions.NEUTRAL) {
throw new Error('exit method must be implemented by subclasses');
async exit (_toState = null, _emotion = Emotions.NEUTRAL) {
throw new Error('exit method must be implemented by subclasses')
}
/**
@ -71,7 +71,7 @@ export class StateHandler {
* @param {number} _deltaTime - Time elapsed since last update (ms, unused in base class)
* @returns {void}
*/
update(_deltaTime) {
update (_deltaTime) {
// Override in subclasses if needed
}
@ -80,7 +80,7 @@ export class StateHandler {
* @param {string} _message - The user message (unused in base class)
* @returns {Promise<void>}
*/
async handleMessage(_message) {
async handleMessage (_message) {
// Override in subclasses if needed
}
@ -88,8 +88,8 @@ export class StateHandler {
* Get available transitions from this state
* @returns {string[]} Array of state names that can be transitioned to
*/
getAvailableTransitions() {
return [];
getAvailableTransitions () {
return []
}
/**
@ -98,17 +98,17 @@ export class StateHandler {
* @param {AnimationClip} clip - The animation clip to wait for
* @returns {Promise<void>} Promise that resolves when the clip finishes
*/
async waitForClipEnd(clip) {
async waitForClipEnd (clip) {
return new Promise((resolve) => {
const checkFinished = () => {
if (!clip.isPlaying()) {
resolve();
resolve()
} else {
requestAnimationFrame(checkFinished);
requestAnimationFrame(checkFinished)
}
};
checkFinished();
});
}
checkFinished()
})
}
/**
@ -117,10 +117,10 @@ export class StateHandler {
* @param {number} [fadeOutDuration] - Fade out duration
* @returns {Promise<void>}
*/
async stopCurrentClip(fadeOutDuration = Config.DEFAULT_FADE_OUT) {
async stopCurrentClip (fadeOutDuration = Config.DEFAULT_FADE_OUT) {
if (this.currentClip) {
await this.currentClip.stop(fadeOutDuration);
this.currentClip = null;
await this.currentClip.stop(fadeOutDuration)
this.currentClip = null
}
}
}

View File

@ -3,8 +3,8 @@
* @module states
*/
import { StateHandler } from './StateHandler.js';
import { States, Emotions } from '../constants.js';
import { StateHandler } from './StateHandler.js'
import { States, Emotions } from '../constants.js'
/**
* Handler for the Type state
@ -16,20 +16,20 @@ export class TypeStateHandler extends StateHandler {
* Create a type state handler
* @param {OwenAnimationContext} context - The animation context
*/
constructor(context) {
super(States.TYPE, context);
constructor (context) {
super(States.TYPE, context)
/**
* Current emotional state
* @type {string}
*/
this.emotion = Emotions.NEUTRAL;
this.emotion = Emotions.NEUTRAL
/**
* Whether currently typing
* @type {boolean}
*/
this.isTyping = false;
this.isTyping = false
}
/**
@ -38,21 +38,21 @@ export class TypeStateHandler extends StateHandler {
* @param {string} [emotion=Emotions.NEUTRAL] - The emotion to enter with
* @returns {Promise<void>}
*/
async enter(_fromState = null, emotion = Emotions.NEUTRAL) {
console.log(`Entering TYPE state with emotion: ${emotion}`);
this.emotion = emotion;
this.isTyping = true;
async enter (_fromState = null, emotion = Emotions.NEUTRAL) {
console.log(`Entering TYPE state with emotion: ${emotion}`)
this.emotion = emotion
this.isTyping = true
// Play appropriate typing animation
let typingClipName = 'type_idle_L';
let typingClipName = 'type_idle_L'
if (emotion !== Emotions.NEUTRAL) {
typingClipName = `type_${emotion}_L`;
typingClipName = `type_${emotion}_L`
}
const typingClip = this.context.getClip(typingClipName);
const typingClip = this.context.getClip(typingClipName)
if (typingClip) {
await typingClip.play();
this.currentClip = typingClip;
await typingClip.play()
this.currentClip = typingClip
}
}
@ -62,24 +62,24 @@ export class TypeStateHandler extends StateHandler {
* @param {string} [_emotion=Emotions.NEUTRAL] - The emotion to exit with (unused)
* @returns {Promise<void>}
*/
async exit(toState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Exiting TYPE state to ${toState}`);
this.isTyping = false;
async exit (toState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Exiting TYPE state to ${toState}`)
this.isTyping = false
if (this.currentClip) {
await this.stopCurrentClip();
await this.stopCurrentClip()
}
// Play transition if available
let transitionName = `type_2${toState}_T`;
let transitionName = `type_2${toState}_T`
if (this.emotion !== Emotions.NEUTRAL) {
transitionName = `type_${this.emotion}2${toState}_T`;
transitionName = `type_${this.emotion}2${toState}_T`
}
const transition = this.context.getClip(transitionName);
const transition = this.context.getClip(transitionName)
if (transition) {
await transition.play();
await this.waitForClipEnd(transition);
await transition.play()
await this.waitForClipEnd(transition)
}
}
@ -87,34 +87,34 @@ export class TypeStateHandler extends StateHandler {
* Finish typing and prepare to transition
* @returns {Promise<void>}
*/
async finishTyping() {
if (!this.isTyping) return;
async finishTyping () {
if (!this.isTyping) return
// Play typing finish animation if available
const finishClip = this.context.getClip('type_finish_Q');
const finishClip = this.context.getClip('type_finish_Q')
if (finishClip && this.currentClip) {
await this.stopCurrentClip(0.2);
await finishClip.play();
await this.waitForClipEnd(finishClip);
await this.stopCurrentClip(0.2)
await finishClip.play()
await this.waitForClipEnd(finishClip)
}
this.isTyping = false;
this.isTyping = false
}
/**
* Get available transitions from type state
* @returns {string[]} Array of available state transitions
*/
getAvailableTransitions() {
return [ States.WAIT, States.REACT ];
getAvailableTransitions () {
return [States.WAIT, States.REACT]
}
/**
* Check if currently typing
* @returns {boolean} True if typing, false otherwise
*/
getIsTyping() {
return this.isTyping;
getIsTyping () {
return this.isTyping
}
/**
@ -122,7 +122,7 @@ export class TypeStateHandler extends StateHandler {
* @param {boolean} typing - Whether currently typing
* @returns {void}
*/
setTyping(typing) {
this.isTyping = typing;
setTyping (typing) {
this.isTyping = typing
}
}

View File

@ -3,8 +3,8 @@
* @module states
*/
import { StateHandler } from './StateHandler.js';
import { States, Emotions, Config } from '../constants.js';
import { StateHandler } from './StateHandler.js'
import { States, Emotions, Config } from '../constants.js'
/**
* Handler for the Wait/Idle state
@ -16,32 +16,32 @@ export class WaitStateHandler extends StateHandler {
* Create a wait state handler
* @param {OwenAnimationContext} context - The animation context
*/
constructor(context) {
super(States.WAIT, context);
constructor (context) {
super(States.WAIT, context)
/**
* The main idle animation clip
* @type {AnimationClip|null}
*/
this.idleClip = null;
this.idleClip = null
/**
* Available quirk animations
* @type {AnimationClip[]}
*/
this.quirks = [];
this.quirks = []
/**
* Timer for quirk animations
* @type {number}
*/
this.quirkTimer = 0;
this.quirkTimer = 0
/**
* Interval between quirk attempts (ms)
* @type {number}
*/
this.quirkInterval = Config.QUIRK_INTERVAL;
this.quirkInterval = Config.QUIRK_INTERVAL
}
/**
@ -50,19 +50,19 @@ export class WaitStateHandler extends StateHandler {
* @param {string} [emotion=Emotions.NEUTRAL] - The emotion to enter with
* @returns {Promise<void>}
*/
async enter(fromState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Entering WAIT state from ${fromState}`);
async enter (fromState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Entering WAIT state from ${fromState}`)
// Play idle loop
this.idleClip = this.context.getClip('wait_idle_L');
this.idleClip = this.context.getClip('wait_idle_L')
if (this.idleClip) {
await this.idleClip.play();
this.currentClip = this.idleClip;
await this.idleClip.play()
this.currentClip = this.idleClip
}
// Collect available quirks
this.quirks = this.context.getClipsByPattern('wait_*_Q');
this.quirkTimer = 0;
this.quirks = this.context.getClipsByPattern('wait_*_Q')
this.quirkTimer = 0
}
/**
@ -71,19 +71,19 @@ export class WaitStateHandler extends StateHandler {
* @param {string} [emotion=Emotions.NEUTRAL] - The emotion to exit with
* @returns {Promise<void>}
*/
async exit(toState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Exiting WAIT state to ${toState}`);
async exit (toState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Exiting WAIT state to ${toState}`)
if (this.currentClip) {
await this.stopCurrentClip();
await this.stopCurrentClip()
}
// Play transition if available
const transitionName = `wait_2${toState}_T`;
const transition = this.context.getClip(transitionName);
const transitionName = `wait_2${toState}_T`
const transition = this.context.getClip(transitionName)
if (transition) {
await transition.play();
await this.waitForClipEnd(transition);
await transition.play()
await this.waitForClipEnd(transition)
}
}
@ -92,13 +92,13 @@ export class WaitStateHandler extends StateHandler {
* @param {number} deltaTime - Time elapsed since last update (ms)
* @returns {void}
*/
update(deltaTime) {
this.quirkTimer += deltaTime;
update (deltaTime) {
this.quirkTimer += deltaTime
// Randomly play quirks
if (this.quirkTimer > this.quirkInterval && Math.random() < Config.QUIRK_PROBABILITY) {
this.playRandomQuirk();
this.quirkTimer = 0;
this.playRandomQuirk()
this.quirkTimer = 0
}
}
@ -107,24 +107,24 @@ export class WaitStateHandler extends StateHandler {
* @private
* @returns {Promise<void>}
*/
async playRandomQuirk() {
if (this.quirks.length === 0) return;
async playRandomQuirk () {
if (this.quirks.length === 0) return
const quirk = this.quirks[ Math.floor(Math.random() * this.quirks.length) ];
const quirk = this.quirks[Math.floor(Math.random() * this.quirks.length)]
// Fade out idle
if (this.idleClip) {
await this.idleClip.stop(0.2);
await this.idleClip.stop(0.2)
}
// Play quirk
await quirk.play();
await this.waitForClipEnd(quirk);
await quirk.play()
await this.waitForClipEnd(quirk)
// Return to idle
if (this.idleClip) {
await this.idleClip.play();
this.currentClip = this.idleClip;
await this.idleClip.play()
this.currentClip = this.idleClip
}
}
@ -132,7 +132,7 @@ export class WaitStateHandler extends StateHandler {
* Get available transitions from wait state
* @returns {string[]} Array of available state transitions
*/
getAvailableTransitions() {
return [ States.REACT, States.SLEEP ];
getAvailableTransitions () {
return [States.REACT, States.SLEEP]
}
}

View File

@ -1,4 +1,4 @@
import { defineConfig } from 'vite';
import { defineConfig } from 'vite'
export default defineConfig({
root: 'examples',
@ -17,7 +17,7 @@ export default defineConfig({
},
resolve: {
alias: {
'owen': '/src/index.js'
owen: '/src/index.js'
}
}
});
})