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,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,11 +217,11 @@ 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;">
`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>
@ -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,45 +1,45 @@
<!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;
}
body {
margin: 0;
overflow: hidden;
background: #1a1a1a;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
#loading {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 18px;
z-index: 1000;
}
#loading {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 18px;
z-index: 1000;
}
.hidden {
display: none;
}
.hidden {
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');
if (loading) {
loading.classList.add('hidden');
}
}, 3000);
// Hide loading screen after a short delay
setTimeout(() => {
const loading = document.getElementById("loading");
if (loading) {
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