@zephyr3d/scene 0.9.1 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/animation/animationset.js +135 -133
- package/dist/animation/animationset.js.map +1 -1
- package/dist/animation/cloth/gpu_cloth_system.js +9 -1
- package/dist/animation/cloth/gpu_cloth_system.js.map +1 -1
- package/dist/animation/fixed_geometry_cache_track.js +5 -1
- package/dist/animation/fixed_geometry_cache_track.js.map +1 -1
- package/dist/animation/geometry_cache_utils.js +20 -4
- package/dist/animation/geometry_cache_utils.js.map +1 -1
- package/dist/animation/ik/ik_angle_constraint.js +2 -6
- package/dist/animation/ik/ik_angle_constraint.js.map +1 -1
- package/dist/animation/ik/two_bone_ik_solver.js +2 -6
- package/dist/animation/ik/two_bone_ik_solver.js.map +1 -1
- package/dist/animation/joint_dynamics/collision.js +60 -12
- package/dist/animation/joint_dynamics/collision.js.map +1 -1
- package/dist/animation/joint_dynamics/constraints.js +20 -4
- package/dist/animation/joint_dynamics/constraints.js.map +1 -1
- package/dist/animation/joint_dynamics/controller.js +151 -103
- package/dist/animation/joint_dynamics/controller.js.map +1 -1
- package/dist/animation/joint_dynamics/solver.js +21 -11
- package/dist/animation/joint_dynamics/solver.js.map +1 -1
- package/dist/animation/joint_dynamics/types.js +15 -3
- package/dist/animation/joint_dynamics/types.js.map +1 -1
- package/dist/animation/pca_geometry_cache_track.js +5 -1
- package/dist/animation/pca_geometry_cache_track.js.map +1 -1
- package/dist/animation/skeleton.js +2 -2
- package/dist/animation/skeleton.js.map +1 -1
- package/dist/animation/skeleton_modifier.js +2 -6
- package/dist/animation/skeleton_modifier.js.map +1 -1
- package/dist/animation/spring/spring_system.js +87 -114
- package/dist/animation/spring/spring_system.js.map +1 -1
- package/dist/app/app.js.map +1 -1
- package/dist/app/engine.js +1 -1
- package/dist/app/engine.js.map +1 -1
- package/dist/app/screen.js +4 -4
- package/dist/app/screen.js.map +1 -1
- package/dist/app/scriptingsystem.js +24 -1
- package/dist/app/scriptingsystem.js.map +1 -1
- package/dist/app/scriptregistry.js +22 -1
- package/dist/app/scriptregistry.js.map +1 -1
- package/dist/asset/assetmanager.js +2 -2
- package/dist/asset/assetmanager.js.map +1 -1
- package/dist/asset/model.js +3 -3
- package/dist/asset/model.js.map +1 -1
- package/dist/camera/camera.js +185 -185
- package/dist/camera/camera.js.map +1 -1
- package/dist/camera/orbit.js.map +1 -1
- package/dist/index.d.ts +794 -261
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/material/material.js +290 -288
- package/dist/material/material.js.map +1 -1
- package/dist/material/mixins/lightmodel/pbrmetallicroughness.js.map +1 -1
- package/dist/material/sprite.js +6 -6
- package/dist/material/sprite.js.map +1 -1
- package/dist/material/terrain-cm.js +2 -2
- package/dist/material/terrain-cm.js.map +1 -1
- package/dist/posteffect/taa.js +31 -39
- package/dist/posteffect/taa.js.map +1 -1
- package/dist/render/drawable.js +5 -1
- package/dist/render/drawable.js.map +1 -1
- package/dist/render/rendergraph/device_pool_allocator.js +29 -3
- package/dist/render/rendergraph/device_pool_allocator.js.map +1 -1
- package/dist/render/rendergraph/executor.js +283 -33
- package/dist/render/rendergraph/executor.js.map +1 -1
- package/dist/render/rendergraph/forward_plus_builder.js +338 -108
- package/dist/render/rendergraph/forward_plus_builder.js.map +1 -1
- package/dist/render/rendergraph/history_resource_manager.js +236 -156
- package/dist/render/rendergraph/history_resource_manager.js.map +1 -1
- package/dist/render/rendergraph/history_resources.js +10 -0
- package/dist/render/rendergraph/history_resources.js.map +1 -0
- package/dist/render/rendergraph/rendergraph.js +162 -35
- package/dist/render/rendergraph/rendergraph.js.map +1 -1
- package/dist/render/rendergraph/types.js +36 -16
- package/dist/render/rendergraph/types.js.map +1 -1
- package/dist/render/rendertarget.js +5 -1
- package/dist/render/rendertarget.js.map +1 -1
- package/dist/render/screenrendertarget.js +5 -1
- package/dist/render/screenrendertarget.js.map +1 -1
- package/dist/render/sky.js +4 -4
- package/dist/render/sky.js.map +1 -1
- package/dist/scene/basesprite.js +2 -2
- package/dist/scene/basesprite.js.map +1 -1
- package/dist/scene/graph_node.js +1 -1
- package/dist/scene/graph_node.js.map +1 -1
- package/dist/scene/mesh.js +4 -20
- package/dist/scene/mesh.js.map +1 -1
- package/dist/scene/particlesys.js +1 -1
- package/dist/scene/particlesys.js.map +1 -1
- package/dist/scene/scene_node.js +2 -2
- package/dist/scene/scene_node.js.map +1 -1
- package/dist/scene/script_attachment.js +15 -3
- package/dist/scene/script_attachment.js.map +1 -1
- package/dist/scene/terrain-cm/terrain-cm.js +3 -3
- package/dist/scene/terrain-cm/terrain-cm.js.map +1 -1
- package/dist/shadow/shadowmapper.js.map +1 -1
- package/dist/shapes/box.js +1 -1
- package/dist/shapes/box.js.map +1 -1
- package/dist/shapes/capsule.js +0 -3
- package/dist/shapes/capsule.js.map +1 -1
- package/dist/shapes/cylinder.js +0 -3
- package/dist/shapes/cylinder.js.map +1 -1
- package/dist/shapes/plane.js +0 -3
- package/dist/shapes/plane.js.map +1 -1
- package/dist/shapes/tetrahedron.js +3 -9
- package/dist/shapes/tetrahedron.js.map +1 -1
- package/dist/shapes/torus.js +4 -7
- package/dist/shapes/torus.js.map +1 -1
- package/dist/utility/blueprint/material/inputs.js +3 -3
- package/dist/utility/blueprint/material/inputs.js.map +1 -1
- package/dist/utility/blueprint/material/ir.js +493 -493
- package/dist/utility/blueprint/material/ir.js.map +1 -1
- package/dist/utility/serialization/manager.js +34 -3
- package/dist/utility/serialization/manager.js.map +1 -1
- package/dist/utility/serialization/scene/animation.js +45 -0
- package/dist/utility/serialization/scene/animation.js.map +1 -1
- package/dist/utility/serialization/scene/camera.js +53 -0
- package/dist/utility/serialization/scene/camera.js.map +1 -1
- package/dist/utility/serialization/scene/common.js +10 -0
- package/dist/utility/serialization/scene/common.js.map +1 -1
- package/dist/utility/serialization/scene/light.js +30 -0
- package/dist/utility/serialization/scene/light.js.map +1 -1
- package/dist/utility/serialization/scene/material.js +63 -0
- package/dist/utility/serialization/scene/material.js.map +1 -1
- package/dist/utility/serialization/scene/mesh.js +11 -0
- package/dist/utility/serialization/scene/mesh.js.map +1 -1
- package/dist/utility/serialization/scene/misc.js +2 -0
- package/dist/utility/serialization/scene/misc.js.map +1 -1
- package/dist/utility/serialization/scene/node.js +19 -0
- package/dist/utility/serialization/scene/node.js.map +1 -1
- package/dist/utility/serialization/scene/particle.js +22 -0
- package/dist/utility/serialization/scene/particle.js.map +1 -1
- package/dist/utility/serialization/scene/primitive.js +33 -0
- package/dist/utility/serialization/scene/primitive.js.map +1 -1
- package/dist/utility/serialization/scene/scene.js +39 -0
- package/dist/utility/serialization/scene/scene.js.map +1 -1
- package/dist/utility/serialization/scene/script.js +2 -0
- package/dist/utility/serialization/scene/script.js.map +1 -1
- package/dist/utility/serialization/scene/sprite.js +6 -0
- package/dist/utility/serialization/scene/sprite.js.map +1 -1
- package/dist/utility/serialization/scene/terrain.js +9 -0
- package/dist/utility/serialization/scene/terrain.js.map +1 -1
- package/dist/utility/serialization/scene/water.js +21 -0
- package/dist/utility/serialization/scene/water.js.map +1 -1
- package/dist/utility/serialization/types.js +5 -1
- package/dist/utility/serialization/types.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spring_system.js","sources":["../../../src/animation/spring/spring_system.ts"],"sourcesContent":["import { Vector3, Quaternion } from '@zephyr3d/base';\r\nimport type { SpringChain } from './spring_chain';\r\nimport { IKUtils } from '../ik/ik_utils';\r\nimport type { SpringCollider } from './spring_collider';\r\nimport {\r\n resolveSphereCollision,\r\n resolveCapsuleCollision,\r\n resolvePlaneCollision,\r\n type CapsuleCollider,\r\n type PlaneCollider,\r\n type SphereCollider,\r\n updateColliderFromNode\r\n} from './spring_collider';\r\n\r\n/**\r\n * Options for creating a SpringSystem\r\n *\r\n * @public\r\n */\r\nexport interface SpringSystemOptions {\r\n /** Number of constraint solver iterations (default: 5) */\r\n iterations?: number;\r\n /** Gravity force vector (default: (0, -9.8, 0)) */\r\n gravity?: Vector3;\r\n /** Wind force vector (default: (0, 0, 0)) */\r\n wind?: Vector3;\r\n /** Enable inertial forces (centrifugal/Coriolis) when root rotates (default: true) */\r\n enableInertialForces?: boolean;\r\n /** Centrifugal force multiplier (default: 1.0) */\r\n centrifugalScale?: number;\r\n /** Coriolis force multiplier (default: 1.0) */\r\n coriolisScale?: number;\r\n /**\r\n * Constraint solver type (default: 'verlet').\r\n * - 'verlet': Classic Verlet integration with iterative position correction.\r\n * stiffness [0-1] controls correction strength per iteration.\r\n * - 'xpbd': Extended Position-Based Dynamics (Müller et al. 2020).\r\n * Uses compliance (inverse stiffness in m/N) for physically correct,\r\n * iteration-count-independent constraint solving.\r\n */\r\n solver?: 'verlet' | 'xpbd';\r\n /**\r\n * How strongly particles are pulled toward current animated pose [0-1].\r\n * This preserves the authored hair shape while still allowing secondary motion.\r\n * Higher values keep the original hairstyle better.\r\n */\r\n poseFollow?: number;\r\n /**\r\n * Optional root-follow override [0-1].\r\n * If provided, pose follow is interpolated from root to tip.\r\n */\r\n poseFollowRoot?: number;\r\n /**\r\n * Optional tip-follow override [0-1].\r\n * If provided, pose follow is interpolated from root to tip.\r\n */\r\n poseFollowTip?: number;\r\n /**\r\n * Exponent used when interpolating root->tip follow.\r\n * 1 = linear, >1 keeps root stiffer and tip looser.\r\n */\r\n poseFollowExponent?: number;\r\n /**\r\n * Optional per-step limit for deviation from animated pose.\r\n * 0 disables clamping. Useful to prevent extreme stretch under high acceleration.\r\n */\r\n maxPoseOffset?: number;\r\n /**\r\n * Optional root max-offset override.\r\n * If provided, max offset is interpolated from root to tip.\r\n */\r\n maxPoseOffsetRoot?: number;\r\n /**\r\n * Optional tip max-offset override.\r\n * If provided, max offset is interpolated from root to tip.\r\n */\r\n maxPoseOffsetTip?: number;\r\n}\r\n\r\nconst FIXED_SIMULATION_TIME_STEP = 1 / 60;\r\nconst MAX_ACCUMULATED_SIMULATION_TIME = 1 / 20;\r\nconst MAX_SIMULATION_STEPS_PER_UPDATE = Math.max(\r\n 1,\r\n Math.ceil(MAX_ACCUMULATED_SIMULATION_TIME / FIXED_SIMULATION_TIME_STEP)\r\n);\r\nconst DEFAULT_PARTICLE_TARGET_SMOOTHING_TIME = 1 / 30;\r\nconst DEFAULT_COLLIDER_SMOOTHING_TIME = 1 / 30;\r\n\r\n/**\r\n * Physics engine for spring-based particle simulation\r\n * Uses Verlet integration and iterative constraint solving\r\n *\r\n * @public\r\n */\r\nexport class SpringSystem {\r\n private _chain: SpringChain;\r\n private _iterations: number;\r\n private _gravity: Vector3;\r\n private _wind: Vector3;\r\n private _enableInertialForces: boolean;\r\n private _centrifugalScale: number;\r\n private _coriolisScale: number;\r\n private _colliders: SpringCollider[];\r\n private _solver: 'verlet' | 'xpbd';\r\n private _poseFollow: number;\r\n private _maxPoseOffset: number;\r\n private _poseFollowRoot: number;\r\n private _poseFollowTip: number;\r\n private _poseFollowExponent: number;\r\n private _maxPoseOffsetRoot: number;\r\n private _maxPoseOffsetTip: number;\r\n private _timeAccumulator: number;\r\n private _smoothedParticleTargets: WeakMap<object, Vector3>;\r\n private _smoothedSphereCenters: WeakMap<SphereCollider, Vector3>;\r\n private _smoothedCapsuleEndpoints: WeakMap<CapsuleCollider, { start: Vector3; end: Vector3 }>;\r\n private _smoothedPlaneData: WeakMap<PlaneCollider, { point: Vector3; normal: Vector3 }>;\r\n\r\n constructor(chain: SpringChain, options?: SpringSystemOptions) {\r\n this._chain = chain;\r\n this._iterations = options?.iterations ?? 5;\r\n this._gravity = options?.gravity?.clone() ?? new Vector3(0, -9.8, 0);\r\n this._wind = options?.wind?.clone() ?? new Vector3(0, 0, 0);\r\n this._enableInertialForces = options?.enableInertialForces ?? true;\r\n this._centrifugalScale = options?.centrifugalScale ?? 1.0;\r\n this._coriolisScale = options?.coriolisScale ?? 1.0;\r\n this._colliders = [];\r\n this._solver = options?.solver ?? 'verlet';\r\n this._poseFollow = Math.max(0, Math.min(1, options?.poseFollow ?? 0.35));\r\n this._maxPoseOffset = Math.max(0, options?.maxPoseOffset ?? 0);\r\n this._poseFollowRoot = Math.max(0, Math.min(1, options?.poseFollowRoot ?? this._poseFollow));\r\n this._poseFollowTip = Math.max(0, Math.min(1, options?.poseFollowTip ?? this._poseFollow));\r\n this._poseFollowExponent = Math.max(0.1, options?.poseFollowExponent ?? 1.6);\r\n this._maxPoseOffsetRoot = Math.max(0, options?.maxPoseOffsetRoot ?? this._maxPoseOffset);\r\n this._maxPoseOffsetTip = Math.max(0, options?.maxPoseOffsetTip ?? this._maxPoseOffset);\r\n this._timeAccumulator = 0;\r\n this._smoothedParticleTargets = new WeakMap();\r\n this._smoothedSphereCenters = new WeakMap();\r\n this._smoothedCapsuleEndpoints = new WeakMap();\r\n this._smoothedPlaneData = new WeakMap();\r\n }\r\n\r\n /**\r\n * Updates the physics simulation\r\n * @param deltaTime - Time step in seconds\r\n */\r\n update(deltaTime: number): void {\r\n const frameDt = Math.min(Math.max(Number(deltaTime) || 0, 0), MAX_ACCUMULATED_SIMULATION_TIME);\r\n if (frameDt <= 0) {\r\n return;\r\n }\r\n this._timeAccumulator = Math.min(this._timeAccumulator + frameDt, MAX_ACCUMULATED_SIMULATION_TIME);\r\n const stepCount = Math.min(\r\n MAX_SIMULATION_STEPS_PER_UPDATE,\r\n Math.floor((this._timeAccumulator + 1e-8) / FIXED_SIMULATION_TIME_STEP)\r\n );\r\n if (stepCount <= 0) {\r\n return;\r\n }\r\n this._timeAccumulator = Math.max(0, this._timeAccumulator - stepCount * FIXED_SIMULATION_TIME_STEP);\r\n for (let i = 0; i < stepCount; i++) {\r\n this.simulateStep(FIXED_SIMULATION_TIME_STEP, i === 0 ? frameDt : 0);\r\n }\r\n }\r\n\r\n private simulateStep(dt: number, inputDeltaTime: number): void {\r\n // Step 1: Save all particle positions before updating\r\n if (this._enableInertialForces) {\r\n for (const p of this._chain.particles) {\r\n p.lastFramePosition.set(p.position);\r\n }\r\n }\r\n\r\n // Step 2: Update fixed particles from their scene nodes\r\n this.updateFixedParticles(inputDeltaTime);\r\n\r\n // Step 3: Calculate global rotation parameters\r\n let rotationCenter: Vector3 | null = null;\r\n let angularVelocity: Vector3 | null = null;\r\n\r\n if (this._enableInertialForces && dt > 0.0001) {\r\n const result = this.calculateGlobalRotation(dt);\r\n rotationCenter = result.center;\r\n angularVelocity = result.omega;\r\n }\r\n\r\n // Step 4: Verlet integration with inertial forces\r\n for (let i = 0; i < this._chain.particles.length; i++) {\r\n const p = this._chain.particles[i];\r\n if (p.fixed) {\r\n continue;\r\n }\r\n\r\n // Calculate velocity (implicit in Verlet)\r\n const velocity = Vector3.sub(p.position, p.prevPosition, new Vector3());\r\n velocity.scaleBy(p.damping);\r\n\r\n // Apply external forces (gravity + wind)\r\n const acceleration = Vector3.add(this._gravity, this._wind, new Vector3());\r\n\r\n // Apply inertial forces from rotating reference frame\r\n if (this._enableInertialForces && rotationCenter && angularVelocity) {\r\n const inertialAccel = this.calculateInertialAcceleration(\r\n p,\r\n rotationCenter,\r\n angularVelocity,\r\n velocity,\r\n this._centrifugalScale,\r\n this._coriolisScale\r\n );\r\n Vector3.add(acceleration, inertialAccel, acceleration);\r\n }\r\n\r\n const positionDelta = Vector3.scale(acceleration, dt * dt, new Vector3());\r\n Vector3.add(velocity, positionDelta, velocity);\r\n\r\n // Update position\r\n p.prevPosition.set(p.position);\r\n Vector3.add(p.position, velocity, p.position);\r\n }\r\n\r\n // Step 5: Iteratively solve constraints\r\n if (this._solver === 'xpbd') {\r\n // Reset Lagrange multipliers at the start of each time step\r\n for (const constraint of this._chain.constraints) {\r\n constraint.lambda = 0;\r\n }\r\n }\r\n for (let iter = 0; iter < this._iterations; iter++) {\r\n for (const constraint of this._chain.constraints) {\r\n if (this._solver === 'xpbd') {\r\n this.solveConstraintXPBD(constraint, dt);\r\n } else {\r\n this.solveConstraint(constraint);\r\n }\r\n }\r\n\r\n // Pull particles back toward the animated pose to preserve hair silhouette.\r\n // Normalize follow strength across solver iterations so tuning stays intuitive.\r\n this.solvePosePreservation(this._iterations);\r\n\r\n // Apply collision constraints\r\n this.solveCollisions(inputDeltaTime);\r\n }\r\n }\r\n\r\n /**\r\n * Updates fixed particles to match their scene node positions\r\n */\r\n private updateFixedParticles(deltaTime: number): void {\r\n const blend = this.getTemporalBlendFactor(deltaTime, DEFAULT_PARTICLE_TARGET_SMOOTHING_TIME);\r\n for (const particle of this._chain.particles) {\r\n if (!particle.node) {\r\n continue;\r\n }\r\n const worldMatrix = particle.node.worldMatrix;\r\n const worldPos = new Vector3(worldMatrix.m03, worldMatrix.m13, worldMatrix.m23);\r\n const smoothedTarget = this.getSmoothedParticleTarget(particle, worldPos, blend);\r\n particle.animPosition.set(smoothedTarget);\r\n if (particle.fixed) {\r\n particle.position.set(smoothedTarget);\r\n particle.prevPosition.set(smoothedTarget);\r\n\r\n // Maintain position history for rotation center estimation\r\n if (this._enableInertialForces) {\r\n if (!particle.positionHistory) {\r\n particle.positionHistory = [];\r\n }\r\n particle.positionHistory.push(smoothedTarget.clone());\r\n // Keep only last 5 frames\r\n if (particle.positionHistory.length > 5) {\r\n particle.positionHistory.shift();\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Solves pose preservation (long-range attachment to animated pose).\r\n * This keeps strands close to authored shape while preserving dynamic movement.\r\n */\r\n private solvePosePreservation(totalIterations: number): void {\r\n if (this._poseFollowRoot <= 0 && this._poseFollowTip <= 0) {\r\n return;\r\n }\r\n\r\n const lastIndex = Math.max(1, this._chain.particles.length - 1);\r\n for (let i = 0; i < this._chain.particles.length; i++) {\r\n const particle = this._chain.particles[i];\r\n if (particle.fixed) {\r\n continue;\r\n }\r\n\r\n const t = Math.pow(i / lastIndex, this._poseFollowExponent);\r\n const particlePoseFollow = this.lerp(this._poseFollowRoot, this._poseFollowTip, t);\r\n // Convert user-facing per-frame follow into per-iteration follow:\r\n // effective = 1 - (1 - follow)^iterations\r\n const iterationFollow =\r\n totalIterations > 1\r\n ? 1 - Math.pow(Math.max(0, 1 - particlePoseFollow), 1 / totalIterations)\r\n : particlePoseFollow;\r\n const toAnim = Vector3.sub(particle.animPosition, particle.position, new Vector3());\r\n const correction = Vector3.scale(toAnim, iterationFollow, new Vector3());\r\n Vector3.add(particle.position, correction, particle.position);\r\n\r\n const particleMaxPoseOffset = this.lerp(this._maxPoseOffsetRoot, this._maxPoseOffsetTip, t);\r\n if (particleMaxPoseOffset > 0) {\r\n const offset = Vector3.sub(particle.position, particle.animPosition, new Vector3());\r\n const offsetLen = offset.magnitude;\r\n if (offsetLen > particleMaxPoseOffset && offsetLen > 1e-6) {\r\n offset.scaleBy(particleMaxPoseOffset / offsetLen);\r\n Vector3.add(particle.animPosition, offset, particle.position);\r\n }\r\n }\r\n }\r\n }\r\n\r\n private lerp(a: number, b: number, t: number): number {\r\n return a + (b - a) * t;\r\n }\r\n\r\n /**\r\n * Calculates global rotation parameters from fixed particle movements\r\n * Uses position history to estimate rotation center\r\n */\r\n private calculateGlobalRotation(dt: number): { center: Vector3; omega: Vector3 } {\r\n // Collect fixed particles with movement\r\n const fixedParticles: any[] = [];\r\n const velocities: Vector3[] = [];\r\n\r\n for (const p of this._chain.particles) {\r\n if (!p.fixed) {\r\n continue;\r\n }\r\n\r\n const velocity = Vector3.sub(p.position, p.lastFramePosition, new Vector3());\r\n velocity.scaleBy(1.0 / dt);\r\n\r\n if (velocity.magnitudeSq > 0.001) {\r\n fixedParticles.push(p);\r\n velocities.push(velocity);\r\n }\r\n }\r\n\r\n if (fixedParticles.length === 0) {\r\n return { center: new Vector3(0, 0, 0), omega: new Vector3(0, 0, 0) };\r\n }\r\n\r\n // Estimate rotation center using position history\r\n let center: Vector3;\r\n\r\n if (fixedParticles.length === 1) {\r\n // Single fixed particle: use position history to estimate rotation center\r\n center = this.estimateRotationCenterFromHistory(fixedParticles[0], velocities[0]);\r\n } else {\r\n // Multiple fixed particles: use their average position\r\n center = new Vector3(0, 0, 0);\r\n for (const p of fixedParticles) {\r\n Vector3.add(center, p.position, center);\r\n }\r\n center.scaleBy(1.0 / fixedParticles.length);\r\n }\r\n\r\n // Estimate angular velocity\r\n let sumOmega = new Vector3(0, 0, 0);\r\n let count = 0;\r\n\r\n for (let i = 0; i < fixedParticles.length; i++) {\r\n const r = Vector3.sub(fixedParticles[i].position, center, new Vector3());\r\n const v = velocities[i];\r\n const rLengthSq = r.magnitudeSq;\r\n\r\n if (rLengthSq > 0.0001) {\r\n // ω = (r × v) / |r|²\r\n const omega = Vector3.cross(r, v, new Vector3());\r\n omega.scaleBy(1.0 / rLengthSq);\r\n Vector3.add(sumOmega, omega, sumOmega);\r\n count++;\r\n }\r\n }\r\n\r\n if (count > 0) {\r\n sumOmega.scaleBy(1.0 / count);\r\n }\r\n\r\n return { center, omega: sumOmega };\r\n }\r\n\r\n /**\r\n * Estimates rotation center from a single particle's position history\r\n * Uses circular motion fitting\r\n */\r\n private estimateRotationCenterFromHistory(particle: any, currentVelocity: Vector3): Vector3 {\r\n const history = particle.positionHistory;\r\n if (!history || history.length < 3) {\r\n // Not enough history: estimate using velocity perpendicular direction\r\n // Assume rotation center is perpendicular to velocity\r\n // Use a default radius based on velocity magnitude\r\n const speed = currentVelocity.magnitude;\r\n if (speed < 0.001) {\r\n return particle.position.clone();\r\n }\r\n\r\n // Estimate radius: for typical character rotation, assume ~0.5-1.0m radius\r\n const estimatedRadius = Math.max(0.5, speed * 0.5);\r\n\r\n // Direction perpendicular to velocity (in the plane of motion)\r\n // We need to guess which perpendicular direction - use cross product with up vector\r\n const up = new Vector3(0, 1, 0);\r\n const perpDir = Vector3.cross(currentVelocity, up, new Vector3());\r\n\r\n if (perpDir.magnitudeSq < 0.0001) {\r\n // Velocity is vertical, use another perpendicular\r\n perpDir.set(new Vector3(1, 0, 0));\r\n } else {\r\n perpDir.inplaceNormalize();\r\n }\r\n\r\n // Rotation center is perpendicular to velocity\r\n const center = Vector3.add(\r\n particle.position,\r\n Vector3.scale(perpDir, estimatedRadius, new Vector3()),\r\n new Vector3()\r\n );\r\n return center;\r\n }\r\n\r\n // Fit a circle through the last 3 positions\r\n // Use positions at indices: 0 (oldest), middle, last (newest)\r\n const p1 = history[0];\r\n const p2 = history[Math.floor(history.length / 2)];\r\n const p3 = history[history.length - 1];\r\n\r\n // Calculate circle center from 3 points\r\n const center = this.calculateCircleCenter(p1, p2, p3);\r\n return center;\r\n }\r\n\r\n /**\r\n * Calculates the center of a circle passing through 3 points\r\n * Uses perpendicular bisector method\r\n */\r\n private calculateCircleCenter(p1: Vector3, p2: Vector3, p3: Vector3): Vector3 {\r\n // Midpoints\r\n const mid12 = Vector3.scale(Vector3.add(p1, p2, new Vector3()), 0.5, new Vector3());\r\n const mid23 = Vector3.scale(Vector3.add(p2, p3, new Vector3()), 0.5, new Vector3());\r\n\r\n // Direction vectors\r\n const dir12 = Vector3.sub(p2, p1, new Vector3());\r\n const dir23 = Vector3.sub(p3, p2, new Vector3());\r\n\r\n // Normal vectors (perpendicular bisectors)\r\n // For 3D, we need to find perpendiculars in the plane of the three points\r\n const normal = Vector3.cross(dir12, dir23, new Vector3());\r\n\r\n if (normal.magnitudeSq < 0.0001) {\r\n // Points are collinear, return midpoint\r\n return Vector3.scale(\r\n Vector3.add(Vector3.add(p1, p2, new Vector3()), p3, new Vector3()),\r\n 1.0 / 3.0,\r\n new Vector3()\r\n );\r\n }\r\n\r\n normal.inplaceNormalize();\r\n\r\n // Perpendicular to dir12 in the plane\r\n const perp12 = Vector3.cross(dir12, normal, new Vector3()).inplaceNormalize();\r\n\r\n // Perpendicular to dir23 in the plane\r\n const perp23 = Vector3.cross(dir23, normal, new Vector3()).inplaceNormalize();\r\n\r\n // Find intersection of two lines:\r\n // Line 1: mid12 + t * perp12\r\n // Line 2: mid23 + s * perp23\r\n // Solve: mid12 + t * perp12 = mid23 + s * perp23\r\n\r\n const diff = Vector3.sub(mid23, mid12, new Vector3());\r\n\r\n // Use 2D projection for simplicity (project onto plane perpendicular to normal)\r\n // Solve in the plane: t * perp12 - s * perp23 = diff\r\n // Use least squares or pick the dominant components\r\n\r\n const det = perp12.x * perp23.y - perp12.y * perp23.x;\r\n\r\n if (Math.abs(det) > 0.0001) {\r\n const t = (diff.x * perp23.y - diff.y * perp23.x) / det;\r\n const center = Vector3.add(mid12, Vector3.scale(perp12, t, new Vector3()), new Vector3());\r\n return center;\r\n }\r\n\r\n // Fallback: use centroid\r\n return Vector3.scale(\r\n Vector3.add(Vector3.add(p1, p2, new Vector3()), p3, new Vector3()),\r\n 1.0 / 3.0,\r\n new Vector3()\r\n );\r\n }\r\n\r\n /**\r\n * Calculates inertial acceleration for a particle in a rotating reference frame\r\n */\r\n private calculateInertialAcceleration(\r\n particle: any,\r\n rotationCenter: Vector3,\r\n angularVelocity: Vector3,\r\n particleVelocity: Vector3,\r\n centrifugalScale: number,\r\n coriolisScale: number\r\n ): Vector3 {\r\n // Vector from rotation center to particle\r\n const r = Vector3.sub(particle.position, rotationCenter, new Vector3());\r\n\r\n // Centrifugal acceleration: a_centrifugal = ω × (ω × r)\r\n const omegaCrossR = Vector3.cross(angularVelocity, r, new Vector3());\r\n const centrifugalAccel = Vector3.cross(angularVelocity, omegaCrossR, new Vector3());\r\n centrifugalAccel.scaleBy(centrifugalScale);\r\n\r\n // Coriolis acceleration: a_coriolis = -2ω × v_relative\r\n // v_relative is the particle's velocity in the rotating frame\r\n // Use the velocity passed in (already calculated from prevPosition)\r\n const coriolisAccel = Vector3.cross(angularVelocity, particleVelocity, new Vector3());\r\n coriolisAccel.scaleBy(-2.0 * coriolisScale);\r\n\r\n // Total inertial acceleration\r\n const totalAccel = Vector3.add(centrifugalAccel, coriolisAccel, new Vector3());\r\n return totalAccel;\r\n }\r\n\r\n /**\r\n * Solves a single spring constraint using XPBD (Extended Position-Based Dynamics).\r\n *\r\n * Reference: Müller et al., \"Detailed Rigid Body Simulation with Extended Position Based Dynamics\", 2020.\r\n *\r\n * The XPBD correction for a distance constraint C(x) = |x_b - x_a| - L is:\r\n * α̃ = compliance / dt² (scaled compliance)\r\n * Δλ = (-C - α̃·λ) / (w_a + w_b + α̃)\r\n * λ += Δλ\r\n * Δx_a = -w_a · Δλ · n̂\r\n * Δx_b = +w_b · Δλ · n̂\r\n * where w = 1/mass (0 for fixed particles), n̂ = unit vector from a to b.\r\n */\r\n private solveConstraintXPBD(constraint: any, dt: number): void {\r\n const pA = this._chain.particles[constraint.particleA];\r\n const pB = this._chain.particles[constraint.particleB];\r\n\r\n const wA = pA.fixed ? 0 : 1.0 / pA.mass;\r\n const wB = pB.fixed ? 0 : 1.0 / pB.mass;\r\n const wSum = wA + wB;\r\n if (wSum < 1e-10) {\r\n return;\r\n }\r\n\r\n const delta = Vector3.sub(pB.position, pA.position, new Vector3());\r\n const currentLength = delta.magnitude;\r\n if (currentLength < 0.0001) {\r\n return;\r\n }\r\n\r\n // Constraint value C = currentLength - restLength\r\n const C = currentLength - constraint.restLength;\r\n\r\n // Scaled compliance: α̃ = compliance / dt²\r\n const alphaTilde = constraint.compliance / (dt * dt);\r\n\r\n // XPBD Lagrange multiplier update\r\n const deltaLambda = (-C - alphaTilde * constraint.lambda) / (wSum + alphaTilde);\r\n constraint.lambda += deltaLambda;\r\n\r\n // Correction direction (unit vector from A to B)\r\n const n = Vector3.scale(delta, 1.0 / currentLength, new Vector3());\r\n\r\n if (!pA.fixed) {\r\n // Δx_a = -w_a · Δλ · n̂\r\n Vector3.add(pA.position, Vector3.scale(n, -wA * deltaLambda, new Vector3()), pA.position);\r\n }\r\n if (!pB.fixed) {\r\n // Δx_b = +w_b · Δλ · n̂\r\n Vector3.add(pB.position, Vector3.scale(n, wB * deltaLambda, new Vector3()), pB.position);\r\n }\r\n }\r\n\r\n /**\r\n * Solves a single spring constraint (Verlet / PBD)\r\n */\r\n private solveConstraint(constraint: any): void {\r\n const pA = this._chain.particles[constraint.particleA];\r\n const pB = this._chain.particles[constraint.particleB];\r\n\r\n // Calculate current distance\r\n const delta = Vector3.sub(pB.position, pA.position, new Vector3());\r\n const currentLength = delta.magnitude;\r\n\r\n if (currentLength < 0.0001) {\r\n return;\r\n } // Avoid division by zero\r\n\r\n // Calculate correction\r\n const diff = (currentLength - constraint.restLength) / currentLength;\r\n const correction = Vector3.scale(delta, diff * constraint.stiffness * 0.5, new Vector3());\r\n\r\n // Apply correction (considering mass and fixed state)\r\n if (!pA.fixed) {\r\n Vector3.add(pA.position, correction, pA.position);\r\n }\r\n if (!pB.fixed) {\r\n Vector3.sub(pB.position, correction, pB.position);\r\n }\r\n }\r\n\r\n /**\r\n * Solves collisions for all particles\r\n */\r\n private solveCollisions(deltaTime: number): void {\r\n // Update dynamic colliders from their nodes\r\n const blend = this.getTemporalBlendFactor(deltaTime, DEFAULT_COLLIDER_SMOOTHING_TIME);\r\n const spheres: { particleCollider: SphereCollider; collider: SphereCollider }[] = [];\r\n const capsules: { particleCollider: CapsuleCollider; collider: CapsuleCollider }[] = [];\r\n const planes: { particleCollider: PlaneCollider; collider: PlaneCollider }[] = [];\r\n for (const collider of this._colliders) {\r\n if (collider.node) {\r\n updateColliderFromNode(collider);\r\n }\r\n if (!collider.enabled) {\r\n continue;\r\n }\r\n switch (collider.type) {\r\n case 'sphere': {\r\n const source = collider as SphereCollider;\r\n spheres.push({\r\n particleCollider: source,\r\n collider: {\r\n ...source,\r\n center: this.getSmoothedSphereCenter(source, blend)\r\n }\r\n });\r\n break;\r\n }\r\n case 'capsule': {\r\n const source = collider as CapsuleCollider;\r\n const endpoints = this.getSmoothedCapsuleEndpoints(source, blend);\r\n capsules.push({\r\n particleCollider: source,\r\n collider: {\r\n ...source,\r\n start: endpoints.start,\r\n end: endpoints.end\r\n }\r\n });\r\n break;\r\n }\r\n case 'plane': {\r\n const source = collider as PlaneCollider;\r\n const plane = this.getSmoothedPlaneData(source, blend);\r\n planes.push({\r\n particleCollider: source,\r\n collider: {\r\n ...source,\r\n point: plane.point,\r\n normal: plane.normal\r\n }\r\n });\r\n break;\r\n }\r\n }\r\n }\r\n\r\n // Check each particle against all colliders\r\n for (const particle of this._chain.particles) {\r\n if (particle.fixed) {\r\n continue; // Skip fixed particles\r\n }\r\n\r\n for (const collider of spheres) {\r\n resolveSphereCollision(particle.position, collider.collider);\r\n }\r\n for (const collider of capsules) {\r\n resolveCapsuleCollision(particle.position, collider.collider);\r\n }\r\n for (const collider of planes) {\r\n resolvePlaneCollision(particle.position, collider.collider);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Applies simulation results to scene nodes\r\n * @param weight - Blend weight [0-1] (default: 1.0)\r\n */\r\n applyToNodes(weight: number = 1.0): void {\r\n for (let i = 0; i < this._chain.particles.length - 1; i++) {\r\n const particle = this._chain.particles[i];\r\n const nextParticle = this._chain.particles[i + 1];\r\n const node = particle.node;\r\n\r\n // Skip if no node\r\n if (!node) {\r\n continue;\r\n }\r\n\r\n // Get current bone direction from node's world matrix (before physics)\r\n // This reflects the current animation/skeleton state\r\n const currentBonePos = new Vector3(node.worldMatrix.m03, node.worldMatrix.m13, node.worldMatrix.m23);\r\n\r\n const nextNode = nextParticle.node;\r\n if (!nextNode) {\r\n continue;\r\n }\r\n\r\n const nextBonePos = new Vector3(\r\n nextNode.worldMatrix.m03,\r\n nextNode.worldMatrix.m13,\r\n nextNode.worldMatrix.m23\r\n );\r\n const originalDir = Vector3.sub(nextBonePos, currentBonePos, new Vector3());\r\n\r\n // Get current bone rotation from node's world matrix\r\n const currentBoneRotation = new Quaternion();\r\n node.worldMatrix.decompose(null, currentBoneRotation, null);\r\n\r\n // Calculate new direction from physics simulation\r\n const newDir = Vector3.sub(nextParticle.position, particle.position, new Vector3());\r\n\r\n // Calculate rotation needed to align original direction to new direction\r\n const deltaRotation = new Quaternion();\r\n IKUtils.fromToRotation(originalDir, newDir, deltaRotation);\r\n\r\n // Calculate new world rotation\r\n let worldRotation = Quaternion.multiply(deltaRotation, currentBoneRotation, new Quaternion());\r\n\r\n // Blend with current rotation based on weight\r\n if (weight < 1) {\r\n Quaternion.slerp(currentBoneRotation, worldRotation, weight, worldRotation);\r\n }\r\n\r\n // Convert world rotation to local rotation (relative to parent)\r\n const parent = node.parent;\r\n if (parent) {\r\n const parentWorldRotation = new Quaternion();\r\n parent.worldMatrix.decompose(null, parentWorldRotation, null);\r\n\r\n // localRotation = conjugate(parentWorldRotation) * worldRotation\r\n const parentInvRotation = Quaternion.conjugate(parentWorldRotation, new Quaternion());\r\n const localRotation = Quaternion.multiply(parentInvRotation, worldRotation, new Quaternion());\r\n\r\n node.rotation = localRotation;\r\n } else {\r\n // Root node has no parent, world rotation is local rotation\r\n node.rotation = worldRotation;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Resets the simulation to initial state\r\n */\r\n reset(): void {\r\n this._chain.reset();\r\n for (const particle of this._chain.particles) {\r\n particle.animPosition.set(particle.originalPosition);\r\n particle.lastFramePosition.set(particle.originalPosition);\r\n if (particle.positionHistory) {\r\n particle.positionHistory.length = 0;\r\n }\r\n }\r\n this._timeAccumulator = 0;\r\n this._smoothedParticleTargets = new WeakMap();\r\n this._smoothedSphereCenters = new WeakMap();\r\n this._smoothedCapsuleEndpoints = new WeakMap();\r\n this._smoothedPlaneData = new WeakMap();\r\n }\r\n\r\n /**\r\n * Gets the spring chain\r\n */\r\n get chain(): SpringChain {\r\n return this._chain;\r\n }\r\n\r\n /**\r\n * Gets the current gravity\r\n */\r\n get gravity(): Vector3 {\r\n return this._gravity;\r\n }\r\n\r\n set gravity(gravity: Vector3) {\r\n this._gravity.set(gravity);\r\n }\r\n\r\n /**\r\n * Gets the current wind\r\n */\r\n get wind(): Vector3 {\r\n return this._wind;\r\n }\r\n\r\n set wind(wind: Vector3) {\r\n this._wind.set(wind);\r\n }\r\n\r\n /**\r\n * Gets the number of iterations\r\n */\r\n get iterations(): number {\r\n return this._iterations;\r\n }\r\n\r\n set iterations(count: number) {\r\n this._iterations = Math.max(1, count);\r\n }\r\n\r\n /**\r\n * Gets whether inertial forces are enabled\r\n */\r\n get enableInertialForces(): boolean {\r\n return this._enableInertialForces;\r\n }\r\n\r\n set enableInertialForces(enabled: boolean) {\r\n this._enableInertialForces = enabled;\r\n }\r\n\r\n /**\r\n * Gets the centrifugal force scale\r\n */\r\n get centrifugalScale(): number {\r\n return this._centrifugalScale;\r\n }\r\n\r\n set centrifugalScale(scale: number) {\r\n this._centrifugalScale = Math.max(0, scale);\r\n }\r\n\r\n /**\r\n * Gets the Coriolis force scale\r\n */\r\n get coriolisScale(): number {\r\n return this._coriolisScale;\r\n }\r\n\r\n /**\r\n * Sets the Coriolis force scale\r\n */\r\n set coriolisScale(scale: number) {\r\n this._coriolisScale = Math.max(0, scale);\r\n }\r\n\r\n /**\r\n * Gets the constraint solver type\r\n */\r\n get solver(): 'verlet' | 'xpbd' {\r\n return this._solver;\r\n }\r\n\r\n /**\r\n * Sets the constraint solver type.\r\n * Switching to 'xpbd' resets all Lagrange multipliers.\r\n */\r\n set solver(type: 'verlet' | 'xpbd') {\r\n if (this._solver !== type) {\r\n this._solver = type;\r\n if (type === 'xpbd') {\r\n for (const c of this._chain.constraints) {\r\n c.lambda = 0;\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Gets pose preservation strength [0-1]\r\n */\r\n get poseFollow(): number {\r\n return this._poseFollow;\r\n }\r\n\r\n /**\r\n * Sets pose preservation strength [0-1]\r\n */\r\n set poseFollow(value: number) {\r\n const v = Math.max(0, Math.min(1, value));\r\n this._poseFollow = v;\r\n this._poseFollowRoot = v;\r\n this._poseFollowTip = v;\r\n }\r\n\r\n /**\r\n * Gets max allowed deviation from animated pose\r\n */\r\n get maxPoseOffset(): number {\r\n return this._maxPoseOffset;\r\n }\r\n\r\n /**\r\n * Sets max allowed deviation from animated pose. 0 disables clamping.\r\n */\r\n set maxPoseOffset(value: number) {\r\n const v = Math.max(0, value);\r\n this._maxPoseOffset = v;\r\n this._maxPoseOffsetRoot = v;\r\n this._maxPoseOffsetTip = v;\r\n }\r\n\r\n /**\r\n * Gets root pose follow strength [0-1]\r\n */\r\n get poseFollowRoot(): number {\r\n return this._poseFollowRoot;\r\n }\r\n\r\n /**\r\n * Sets root pose follow strength [0-1]\r\n */\r\n set poseFollowRoot(value: number) {\r\n this._poseFollowRoot = Math.max(0, Math.min(1, value));\r\n }\r\n\r\n /**\r\n * Gets tip pose follow strength [0-1]\r\n */\r\n get poseFollowTip(): number {\r\n return this._poseFollowTip;\r\n }\r\n\r\n /**\r\n * Sets tip pose follow strength [0-1]\r\n */\r\n set poseFollowTip(value: number) {\r\n this._poseFollowTip = Math.max(0, Math.min(1, value));\r\n }\r\n\r\n /**\r\n * Gets exponent for root->tip interpolation\r\n */\r\n get poseFollowExponent(): number {\r\n return this._poseFollowExponent;\r\n }\r\n\r\n /**\r\n * Sets exponent for root->tip interpolation\r\n */\r\n set poseFollowExponent(value: number) {\r\n this._poseFollowExponent = Math.max(0.1, value);\r\n }\r\n\r\n /**\r\n * Gets root max allowed deviation from animated pose\r\n */\r\n get maxPoseOffsetRoot(): number {\r\n return this._maxPoseOffsetRoot;\r\n }\r\n\r\n /**\r\n * Sets root max allowed deviation from animated pose\r\n */\r\n set maxPoseOffsetRoot(value: number) {\r\n this._maxPoseOffsetRoot = Math.max(0, value);\r\n }\r\n\r\n /**\r\n * Gets tip max allowed deviation from animated pose\r\n */\r\n get maxPoseOffsetTip(): number {\r\n return this._maxPoseOffsetTip;\r\n }\r\n\r\n /**\r\n * Sets tip max allowed deviation from animated pose\r\n */\r\n set maxPoseOffsetTip(value: number) {\r\n this._maxPoseOffsetTip = Math.max(0, value);\r\n }\r\n\r\n /**\r\n * Adds a collider to the system\r\n */\r\n addCollider(collider: SpringCollider): void {\r\n this._colliders.push(collider);\r\n this._smoothedSphereCenters = new WeakMap();\r\n this._smoothedCapsuleEndpoints = new WeakMap();\r\n this._smoothedPlaneData = new WeakMap();\r\n }\r\n\r\n /**\r\n * Removes a collider from the system\r\n */\r\n removeCollider(collider: SpringCollider): boolean {\r\n const index = this._colliders.indexOf(collider);\r\n if (index >= 0) {\r\n this._colliders.splice(index, 1);\r\n this._smoothedSphereCenters = new WeakMap();\r\n this._smoothedCapsuleEndpoints = new WeakMap();\r\n this._smoothedPlaneData = new WeakMap();\r\n return true;\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Clears all colliders\r\n */\r\n clearColliders(): void {\r\n this._colliders = [];\r\n this._smoothedSphereCenters = new WeakMap();\r\n this._smoothedCapsuleEndpoints = new WeakMap();\r\n this._smoothedPlaneData = new WeakMap();\r\n }\r\n\r\n /**\r\n * Gets all colliders\r\n */\r\n get colliders(): SpringCollider[] {\r\n return this._colliders;\r\n }\r\n\r\n private getTemporalBlendFactor(deltaTime: number, smoothingTime: number): number {\r\n const dt = Math.min(Math.max(Number(deltaTime) || 0, 0), MAX_ACCUMULATED_SIMULATION_TIME);\r\n if (smoothingTime <= 0) {\r\n return 1;\r\n }\r\n if (dt <= 0) {\r\n return 0;\r\n }\r\n return 1 - Math.exp(-dt / smoothingTime);\r\n }\r\n\r\n private getSmoothedParticleTarget(target: object, current: Vector3, blend: number): Vector3 {\r\n const cached = this._smoothedParticleTargets.get(target);\r\n if (!cached || blend >= 1) {\r\n const next = current.clone();\r\n this._smoothedParticleTargets.set(target, next);\r\n return next;\r\n }\r\n cached.setXYZ(\r\n cached.x + (current.x - cached.x) * blend,\r\n cached.y + (current.y - cached.y) * blend,\r\n cached.z + (current.z - cached.z) * blend\r\n );\r\n return cached;\r\n }\r\n\r\n private getSmoothedSphereCenter(collider: SphereCollider, blend: number): Vector3 {\r\n const current = collider.center?.clone() ?? new Vector3();\r\n const cached = this._smoothedSphereCenters.get(collider);\r\n if (!cached || blend >= 1) {\r\n this._smoothedSphereCenters.set(collider, current);\r\n return current;\r\n }\r\n cached.setXYZ(\r\n cached.x + (current.x - cached.x) * blend,\r\n cached.y + (current.y - cached.y) * blend,\r\n cached.z + (current.z - cached.z) * blend\r\n );\r\n return cached;\r\n }\r\n\r\n private getSmoothedCapsuleEndpoints(\r\n collider: CapsuleCollider,\r\n blend: number\r\n ): { start: Vector3; end: Vector3 } {\r\n const currentStart = collider.start?.clone() ?? new Vector3();\r\n const currentEnd = collider.end?.clone() ?? new Vector3();\r\n const cached = this._smoothedCapsuleEndpoints.get(collider);\r\n if (!cached || blend >= 1) {\r\n const next = {\r\n start: currentStart,\r\n end: currentEnd\r\n };\r\n this._smoothedCapsuleEndpoints.set(collider, next);\r\n return next;\r\n }\r\n cached.start.setXYZ(\r\n cached.start.x + (currentStart.x - cached.start.x) * blend,\r\n cached.start.y + (currentStart.y - cached.start.y) * blend,\r\n cached.start.z + (currentStart.z - cached.start.z) * blend\r\n );\r\n cached.end.setXYZ(\r\n cached.end.x + (currentEnd.x - cached.end.x) * blend,\r\n cached.end.y + (currentEnd.y - cached.end.y) * blend,\r\n cached.end.z + (currentEnd.z - cached.end.z) * blend\r\n );\r\n return cached;\r\n }\r\n\r\n private getSmoothedPlaneData(collider: PlaneCollider, blend: number): { point: Vector3; normal: Vector3 } {\r\n const currentPoint = collider.point?.clone() ?? new Vector3();\r\n const currentNormal = collider.normal?.clone() ?? Vector3.axisPY();\r\n if (currentNormal.magnitudeSq > 1e-8) {\r\n currentNormal.inplaceNormalize();\r\n } else {\r\n currentNormal.setXYZ(0, 1, 0);\r\n }\r\n const cached = this._smoothedPlaneData.get(collider);\r\n if (!cached || blend >= 1) {\r\n const next = {\r\n point: currentPoint,\r\n normal: currentNormal\r\n };\r\n this._smoothedPlaneData.set(collider, next);\r\n return next;\r\n }\r\n cached.point.setXYZ(\r\n cached.point.x + (currentPoint.x - cached.point.x) * blend,\r\n cached.point.y + (currentPoint.y - cached.point.y) * blend,\r\n cached.point.z + (currentPoint.z - cached.point.z) * blend\r\n );\r\n cached.normal.setXYZ(\r\n cached.normal.x + (currentNormal.x - cached.normal.x) * blend,\r\n cached.normal.y + (currentNormal.y - cached.normal.y) * blend,\r\n cached.normal.z + (currentNormal.z - cached.normal.z) * blend\r\n );\r\n if (cached.normal.magnitudeSq > 1e-8) {\r\n cached.normal.inplaceNormalize();\r\n } else {\r\n cached.normal.setXYZ(0, 1, 0);\r\n }\r\n return cached;\r\n }\r\n}\r\n"],"names":["FIXED_SIMULATION_TIME_STEP","MAX_ACCUMULATED_SIMULATION_TIME","MAX_SIMULATION_STEPS_PER_UPDATE","Math","max","ceil","DEFAULT_PARTICLE_TARGET_SMOOTHING_TIME","DEFAULT_COLLIDER_SMOOTHING_TIME","SpringSystem","_chain","_iterations","_gravity","_wind","_enableInertialForces","_centrifugalScale","_coriolisScale","_colliders","_solver","_poseFollow","_maxPoseOffset","_poseFollowRoot","_poseFollowTip","_poseFollowExponent","_maxPoseOffsetRoot","_maxPoseOffsetTip","_timeAccumulator","_smoothedParticleTargets","_smoothedSphereCenters","_smoothedCapsuleEndpoints","_smoothedPlaneData","chain","options","iterations","gravity","clone","Vector3","wind","enableInertialForces","centrifugalScale","coriolisScale","solver","min","poseFollow","maxPoseOffset","poseFollowRoot","poseFollowTip","poseFollowExponent","maxPoseOffsetRoot","maxPoseOffsetTip","WeakMap","update","deltaTime","frameDt","Number","stepCount","floor","i","simulateStep","dt","inputDeltaTime","p","particles","lastFramePosition","set","position","updateFixedParticles","rotationCenter","angularVelocity","result","calculateGlobalRotation","center","omega","length","fixed","velocity","sub","prevPosition","scaleBy","damping","acceleration","add","inertialAccel","calculateInertialAcceleration","positionDelta","scale","constraint","constraints","lambda","iter","solveConstraintXPBD","solveConstraint","solvePosePreservation","solveCollisions","blend","getTemporalBlendFactor","particle","node","worldMatrix","worldPos","m03","m13","m23","smoothedTarget","getSmoothedParticleTarget","animPosition","positionHistory","push","shift","totalIterations","lastIndex","t","pow","particlePoseFollow","lerp","iterationFollow","toAnim","correction","particleMaxPoseOffset","offset","offsetLen","magnitude","a","b","fixedParticles","velocities","magnitudeSq","estimateRotationCenterFromHistory","sumOmega","count","r","v","rLengthSq","cross","currentVelocity","history","speed","estimatedRadius","up","perpDir","inplaceNormalize","p1","p2","p3","calculateCircleCenter","mid12","mid23","dir12","dir23","normal","perp12","perp23","diff","det","x","y","abs","particleVelocity","omegaCrossR","centrifugalAccel","coriolisAccel","totalAccel","pA","particleA","pB","particleB","wA","mass","wB","wSum","delta","currentLength","C","restLength","alphaTilde","compliance","deltaLambda","n","stiffness","spheres","capsules","planes","collider","updateColliderFromNode","enabled","type","source","particleCollider","getSmoothedSphereCenter","endpoints","getSmoothedCapsuleEndpoints","start","end","plane","getSmoothedPlaneData","point","resolveSphereCollision","resolveCapsuleCollision","resolvePlaneCollision","applyToNodes","weight","nextParticle","currentBonePos","nextNode","nextBonePos","originalDir","currentBoneRotation","Quaternion","decompose","newDir","deltaRotation","IKUtils","fromToRotation","worldRotation","multiply","slerp","parent","parentWorldRotation","parentInvRotation","conjugate","localRotation","rotation","reset","originalPosition","c","value","addCollider","removeCollider","index","indexOf","splice","clearColliders","colliders","smoothingTime","exp","target","current","cached","get","next","setXYZ","z","currentStart","currentEnd","currentPoint","currentNormal","axisPY"],"mappings":";;;;AA+EA,MAAMA,6BAA6B,CAAI,GAAA,EAAA;AACvC,MAAMC,kCAAkC,CAAI,GAAA,EAAA;AAC5C,MAAMC,+BAAAA,GAAkCC,KAAKC,GAAG,CAC9C,GACAD,IAAKE,CAAAA,IAAI,CAACJ,+BAAkCD,GAAAA,0BAAAA,CAAAA,CAAAA;AAE9C,MAAMM,yCAAyC,CAAI,GAAA,EAAA;AACnD,MAAMC,kCAAkC,CAAI,GAAA,EAAA;AAE5C;;;;;AAKC,IACM,MAAMC,YAAAA,CAAAA;IACHC,MAAoB;IACpBC,WAAoB;IACpBC,QAAkB;IAClBC,KAAe;IACfC,qBAA+B;IAC/BC,iBAA0B;IAC1BC,cAAuB;IACvBC,UAA6B;IAC7BC,OAA2B;IAC3BC,WAAoB;IACpBC,cAAuB;IACvBC,eAAwB;IACxBC,cAAuB;IACvBC,mBAA4B;IAC5BC,kBAA2B;IAC3BC,iBAA0B;IAC1BC,gBAAyB;IACzBC,wBAAmD;IACnDC,sBAAyD;IACzDC,yBAAsF;IACtFC,kBAAgF;IAExF,WAAYC,CAAAA,KAAkB,EAAEC,OA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1C,KAAK,CAACzC,CAAC,GAAI0F,CAAAA,YAAAA,CAAa1F,CAAC,GAAGmF,MAAAA,CAAO1C,KAAK,CAACzC,CAAAA,IAAK5D,KACrD+I,EAAAA,MAAAA,CAAO1C,KAAK,CAACxC,CAAC,GAAG,CAACyF,YAAAA,CAAazF,CAAC,GAAGkF,MAAO1C,CAAAA,KAAK,CAACxC,CAAAA,IAAK7D,KAAAA,EACrD+I,MAAO1C,CAAAA,KAAK,CAAC8C,CAAC,GAAG,CAACG,YAAaH,CAAAA,CAAC,GAAGJ,MAAAA,CAAO1C,KAAK,CAAC8C,CAAAA,IAAKnJ,KAAAA,CAAAA;QAEvD+I,MAAOxF,CAAAA,MAAM,CAAC2F,MAAM,CAClBH,MAAAA,CAAOxF,MAAM,CAACK,CAAC,GAAI2F,CAAAA,aAAAA,CAAc3F,CAAC,GAAGmF,MAAAA,CAAOxF,MAAM,CAACK,CAAAA,IAAK5D,KACxD+I,EAAAA,MAAAA,CAAOxF,MAAM,CAACM,CAAC,GAAG,CAAC0F,aAAAA,CAAc1F,CAAC,GAAGkF,MAAOxF,CAAAA,MAAM,CAACM,CAAAA,IAAK7D,KAAAA,EACxD+I,MAAOxF,CAAAA,MAAM,CAAC4F,CAAC,GAAG,CAACI,aAAcJ,CAAAA,CAAC,GAAGJ,MAAAA,CAAOxF,MAAM,CAAC4F,CAAAA,IAAKnJ,KAAAA,CAAAA;AAE1D,QAAA,IAAI+I,MAAOxF,CAAAA,MAAM,CAACvB,WAAW,GAAG,IAAM,EAAA;YACpC+G,MAAOxF,CAAAA,MAAM,CAACT,gBAAgB,EAAA;SACzB,MAAA;AACLiG,YAAAA,MAAAA,CAAOxF,MAAM,CAAC2F,MAAM,CAAC,GAAG,CAAG,EAAA,CAAA,CAAA;AAC7B;QACA,OAAOH,MAAAA;AACT;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"spring_system.js","sources":["../../../src/animation/spring/spring_system.ts"],"sourcesContent":["import { Vector3, Quaternion } from '@zephyr3d/base';\nimport type { SpringChain } from './spring_chain';\nimport { IKUtils } from '../ik/ik_utils';\nimport type { SpringCollider } from './spring_collider';\nimport {\n resolveSphereCollision,\n resolveCapsuleCollision,\n resolvePlaneCollision,\n type CapsuleCollider,\n type PlaneCollider,\n type SphereCollider,\n updateColliderFromNode\n} from './spring_collider';\n\n/**\n * Options for creating a SpringSystem\n *\n * @public\n */\nexport interface SpringSystemOptions {\n /** Number of constraint solver iterations (default: 5) */\n iterations?: number;\n /** Gravity force vector (default: (0, -9.8, 0)) */\n gravity?: Vector3;\n /** Wind force vector (default: (0, 0, 0)) */\n wind?: Vector3;\n /** Enable inertial forces (centrifugal/Coriolis) when root rotates (default: true) */\n enableInertialForces?: boolean;\n /** Centrifugal force multiplier (default: 1.0) */\n centrifugalScale?: number;\n /** Coriolis force multiplier (default: 1.0) */\n coriolisScale?: number;\n /**\n * Constraint solver type (default: 'verlet').\n * - 'verlet': Classic Verlet integration with iterative position correction.\n * stiffness [0-1] controls correction strength per iteration.\n * - 'xpbd': Extended Position-Based Dynamics (Müller et al. 2020).\n * Uses compliance (inverse stiffness in m/N) for physically correct,\n * iteration-count-independent constraint solving.\n */\n solver?: 'verlet' | 'xpbd';\n /**\n * How strongly particles are pulled toward current animated pose [0-1].\n * This preserves the authored hair shape while still allowing secondary motion.\n * Higher values keep the original hairstyle better.\n */\n poseFollow?: number;\n /**\n * Optional root-follow override [0-1].\n * If provided, pose follow is interpolated from root to tip.\n */\n poseFollowRoot?: number;\n /**\n * Optional tip-follow override [0-1].\n * If provided, pose follow is interpolated from root to tip.\n */\n poseFollowTip?: number;\n /**\n * Exponent used when interpolating root-to-tip follow.\n * `1` is linear; values `\\> 1` keep the root stiffer and the tip looser.\n */\n poseFollowExponent?: number;\n /**\n * Optional per-step limit for deviation from animated pose.\n * 0 disables clamping. Useful to prevent extreme stretch under high acceleration.\n */\n maxPoseOffset?: number;\n /**\n * Optional root max-offset override.\n * If provided, max offset is interpolated from root to tip.\n */\n maxPoseOffsetRoot?: number;\n /**\n * Optional tip max-offset override.\n * If provided, max offset is interpolated from root to tip.\n */\n maxPoseOffsetTip?: number;\n}\n\nconst FIXED_SIMULATION_TIME_STEP = 1 / 60;\nconst MAX_ACCUMULATED_SIMULATION_TIME = 1 / 20;\nconst MAX_SIMULATION_STEPS_PER_UPDATE = Math.max(\n 1,\n Math.ceil(MAX_ACCUMULATED_SIMULATION_TIME / FIXED_SIMULATION_TIME_STEP)\n);\nconst DEFAULT_PARTICLE_TARGET_SMOOTHING_TIME = 1 / 30;\nconst DEFAULT_COLLIDER_SMOOTHING_TIME = 1 / 30;\n\n/**\n * Physics engine for spring-based particle simulation\n * Uses Verlet integration and iterative constraint solving\n *\n * @public\n */\nexport class SpringSystem {\n private _chain: SpringChain;\n private _iterations: number;\n private _gravity: Vector3;\n private _wind: Vector3;\n private _enableInertialForces: boolean;\n private _centrifugalScale: number;\n private _coriolisScale: number;\n private _colliders: SpringCollider[];\n private _solver: 'verlet' | 'xpbd';\n private _poseFollow: number;\n private _maxPoseOffset: number;\n private _poseFollowRoot: number;\n private _poseFollowTip: number;\n private _poseFollowExponent: number;\n private _maxPoseOffsetRoot: number;\n private _maxPoseOffsetTip: number;\n private _timeAccumulator: number;\n private _smoothedParticleTargets: WeakMap<object, Vector3>;\n private _smoothedSphereCenters: WeakMap<SphereCollider, Vector3>;\n private _smoothedCapsuleEndpoints: WeakMap<CapsuleCollider, { start: Vector3; end: Vector3 }>;\n private _smoothedPlaneData: WeakMap<PlaneCollider, { point: Vector3; normal: Vector3 }>;\n\n constructor(chain: SpringChain, options?: SpringSystemOptions) {\n this._chain = chain;\n this._iterations = options?.iterations ?? 5;\n this._gravity = options?.gravity?.clone() ?? new Vector3(0, -9.8, 0);\n this._wind = options?.wind?.clone() ?? new Vector3(0, 0, 0);\n this._enableInertialForces = options?.enableInertialForces ?? true;\n this._centrifugalScale = options?.centrifugalScale ?? 1.0;\n this._coriolisScale = options?.coriolisScale ?? 1.0;\n this._colliders = [];\n this._solver = options?.solver ?? 'verlet';\n this._poseFollow = Math.max(0, Math.min(1, options?.poseFollow ?? 0.35));\n this._maxPoseOffset = Math.max(0, options?.maxPoseOffset ?? 0);\n this._poseFollowRoot = Math.max(0, Math.min(1, options?.poseFollowRoot ?? this._poseFollow));\n this._poseFollowTip = Math.max(0, Math.min(1, options?.poseFollowTip ?? this._poseFollow));\n this._poseFollowExponent = Math.max(0.1, options?.poseFollowExponent ?? 1.6);\n this._maxPoseOffsetRoot = Math.max(0, options?.maxPoseOffsetRoot ?? this._maxPoseOffset);\n this._maxPoseOffsetTip = Math.max(0, options?.maxPoseOffsetTip ?? this._maxPoseOffset);\n this._timeAccumulator = 0;\n this._smoothedParticleTargets = new WeakMap();\n this._smoothedSphereCenters = new WeakMap();\n this._smoothedCapsuleEndpoints = new WeakMap();\n this._smoothedPlaneData = new WeakMap();\n }\n\n /**\n * Updates the physics simulation\n * @param deltaTime - Time step in seconds\n */\n update(deltaTime: number): void {\n const frameDt = Math.min(Math.max(Number(deltaTime) || 0, 0), MAX_ACCUMULATED_SIMULATION_TIME);\n if (frameDt <= 0) {\n return;\n }\n this._timeAccumulator = Math.min(this._timeAccumulator + frameDt, MAX_ACCUMULATED_SIMULATION_TIME);\n const stepCount = Math.min(\n MAX_SIMULATION_STEPS_PER_UPDATE,\n Math.floor((this._timeAccumulator + 1e-8) / FIXED_SIMULATION_TIME_STEP)\n );\n if (stepCount <= 0) {\n return;\n }\n this._timeAccumulator = Math.max(0, this._timeAccumulator - stepCount * FIXED_SIMULATION_TIME_STEP);\n for (let i = 0; i < stepCount; i++) {\n this.simulateStep(FIXED_SIMULATION_TIME_STEP, i === 0 ? frameDt : 0);\n }\n }\n\n private simulateStep(dt: number, inputDeltaTime: number): void {\n // Step 1: Save all particle positions before updating\n if (this._enableInertialForces) {\n for (const p of this._chain.particles) {\n p.lastFramePosition.set(p.position);\n }\n }\n\n // Step 2: Update fixed particles from their scene nodes\n this.updateFixedParticles(inputDeltaTime);\n\n // Step 3: Calculate global rotation parameters\n let rotationCenter: Vector3 | null = null;\n let angularVelocity: Vector3 | null = null;\n\n if (this._enableInertialForces && dt > 0.0001) {\n const result = this.calculateGlobalRotation(dt);\n rotationCenter = result.center;\n angularVelocity = result.omega;\n }\n\n // Step 4: Verlet integration with inertial forces\n for (let i = 0; i < this._chain.particles.length; i++) {\n const p = this._chain.particles[i];\n if (p.fixed) {\n continue;\n }\n\n // Calculate velocity (implicit in Verlet)\n const velocity = Vector3.sub(p.position, p.prevPosition, new Vector3());\n velocity.scaleBy(p.damping);\n\n // Apply external forces (gravity + wind)\n const acceleration = Vector3.add(this._gravity, this._wind, new Vector3());\n\n // Apply inertial forces from rotating reference frame\n if (this._enableInertialForces && rotationCenter && angularVelocity) {\n const inertialAccel = this.calculateInertialAcceleration(\n p,\n rotationCenter,\n angularVelocity,\n velocity,\n this._centrifugalScale,\n this._coriolisScale\n );\n Vector3.add(acceleration, inertialAccel, acceleration);\n }\n\n const positionDelta = Vector3.scale(acceleration, dt * dt, new Vector3());\n Vector3.add(velocity, positionDelta, velocity);\n\n // Update position\n p.prevPosition.set(p.position);\n Vector3.add(p.position, velocity, p.position);\n }\n\n // Step 5: Iteratively solve constraints\n if (this._solver === 'xpbd') {\n // Reset Lagrange multipliers at the start of each time step\n for (const constraint of this._chain.constraints) {\n constraint.lambda = 0;\n }\n }\n for (let iter = 0; iter < this._iterations; iter++) {\n for (const constraint of this._chain.constraints) {\n if (this._solver === 'xpbd') {\n this.solveConstraintXPBD(constraint, dt);\n } else {\n this.solveConstraint(constraint);\n }\n }\n\n // Pull particles back toward the animated pose to preserve hair silhouette.\n // Normalize follow strength across solver iterations so tuning stays intuitive.\n this.solvePosePreservation(this._iterations);\n\n // Apply collision constraints\n this.solveCollisions(inputDeltaTime);\n }\n }\n\n /**\n * Updates fixed particles to match their scene node positions\n */\n private updateFixedParticles(deltaTime: number): void {\n const blend = this.getTemporalBlendFactor(deltaTime, DEFAULT_PARTICLE_TARGET_SMOOTHING_TIME);\n for (const particle of this._chain.particles) {\n if (!particle.node) {\n continue;\n }\n const worldMatrix = particle.node.worldMatrix;\n const worldPos = new Vector3(worldMatrix.m03, worldMatrix.m13, worldMatrix.m23);\n const smoothedTarget = this.getSmoothedParticleTarget(particle, worldPos, blend);\n particle.animPosition.set(smoothedTarget);\n if (particle.fixed) {\n particle.position.set(smoothedTarget);\n particle.prevPosition.set(smoothedTarget);\n\n // Maintain position history for rotation center estimation\n if (this._enableInertialForces) {\n if (!particle.positionHistory) {\n particle.positionHistory = [];\n }\n particle.positionHistory.push(smoothedTarget.clone());\n // Keep only last 5 frames\n if (particle.positionHistory.length > 5) {\n particle.positionHistory.shift();\n }\n }\n }\n }\n }\n\n /**\n * Solves pose preservation (long-range attachment to animated pose).\n * This keeps strands close to authored shape while preserving dynamic movement.\n */\n private solvePosePreservation(totalIterations: number): void {\n if (this._poseFollowRoot <= 0 && this._poseFollowTip <= 0) {\n return;\n }\n\n const lastIndex = Math.max(1, this._chain.particles.length - 1);\n for (let i = 0; i < this._chain.particles.length; i++) {\n const particle = this._chain.particles[i];\n if (particle.fixed) {\n continue;\n }\n\n const t = Math.pow(i / lastIndex, this._poseFollowExponent);\n const particlePoseFollow = this.lerp(this._poseFollowRoot, this._poseFollowTip, t);\n // Convert user-facing per-frame follow into per-iteration follow:\n // effective = 1 - (1 - follow)^iterations\n const iterationFollow =\n totalIterations > 1\n ? 1 - Math.pow(Math.max(0, 1 - particlePoseFollow), 1 / totalIterations)\n : particlePoseFollow;\n const toAnim = Vector3.sub(particle.animPosition, particle.position, new Vector3());\n const correction = Vector3.scale(toAnim, iterationFollow, new Vector3());\n Vector3.add(particle.position, correction, particle.position);\n\n const particleMaxPoseOffset = this.lerp(this._maxPoseOffsetRoot, this._maxPoseOffsetTip, t);\n if (particleMaxPoseOffset > 0) {\n const offset = Vector3.sub(particle.position, particle.animPosition, new Vector3());\n const offsetLen = offset.magnitude;\n if (offsetLen > particleMaxPoseOffset && offsetLen > 1e-6) {\n offset.scaleBy(particleMaxPoseOffset / offsetLen);\n Vector3.add(particle.animPosition, offset, particle.position);\n }\n }\n }\n }\n\n private lerp(a: number, b: number, t: number): number {\n return a + (b - a) * t;\n }\n\n /**\n * Calculates global rotation parameters from fixed particle movements\n * Uses position history to estimate rotation center\n */\n private calculateGlobalRotation(dt: number): { center: Vector3; omega: Vector3 } {\n // Collect fixed particles with movement\n const fixedParticles: any[] = [];\n const velocities: Vector3[] = [];\n\n for (const p of this._chain.particles) {\n if (!p.fixed) {\n continue;\n }\n\n const velocity = Vector3.sub(p.position, p.lastFramePosition, new Vector3());\n velocity.scaleBy(1.0 / dt);\n\n if (velocity.magnitudeSq > 0.001) {\n fixedParticles.push(p);\n velocities.push(velocity);\n }\n }\n\n if (fixedParticles.length === 0) {\n return { center: new Vector3(0, 0, 0), omega: new Vector3(0, 0, 0) };\n }\n\n // Estimate rotation center using position history\n let center: Vector3;\n\n if (fixedParticles.length === 1) {\n // Single fixed particle: use position history to estimate rotation center\n center = this.estimateRotationCenterFromHistory(fixedParticles[0], velocities[0]);\n } else {\n // Multiple fixed particles: use their average position\n center = new Vector3(0, 0, 0);\n for (const p of fixedParticles) {\n Vector3.add(center, p.position, center);\n }\n center.scaleBy(1.0 / fixedParticles.length);\n }\n\n // Estimate angular velocity\n let sumOmega = new Vector3(0, 0, 0);\n let count = 0;\n\n for (let i = 0; i < fixedParticles.length; i++) {\n const r = Vector3.sub(fixedParticles[i].position, center, new Vector3());\n const v = velocities[i];\n const rLengthSq = r.magnitudeSq;\n\n if (rLengthSq > 0.0001) {\n // ω = (r × v) / |r|²\n const omega = Vector3.cross(r, v, new Vector3());\n omega.scaleBy(1.0 / rLengthSq);\n Vector3.add(sumOmega, omega, sumOmega);\n count++;\n }\n }\n\n if (count > 0) {\n sumOmega.scaleBy(1.0 / count);\n }\n\n return { center, omega: sumOmega };\n }\n\n /**\n * Estimates rotation center from a single particle's position history\n * Uses circular motion fitting\n */\n private estimateRotationCenterFromHistory(particle: any, currentVelocity: Vector3): Vector3 {\n const history = particle.positionHistory;\n if (!history || history.length < 3) {\n // Not enough history: estimate using velocity perpendicular direction\n // Assume rotation center is perpendicular to velocity\n // Use a default radius based on velocity magnitude\n const speed = currentVelocity.magnitude;\n if (speed < 0.001) {\n return particle.position.clone();\n }\n\n // Estimate radius: for typical character rotation, assume ~0.5-1.0m radius\n const estimatedRadius = Math.max(0.5, speed * 0.5);\n\n // Direction perpendicular to velocity (in the plane of motion)\n // We need to guess which perpendicular direction - use cross product with up vector\n const up = new Vector3(0, 1, 0);\n const perpDir = Vector3.cross(currentVelocity, up, new Vector3());\n\n if (perpDir.magnitudeSq < 0.0001) {\n // Velocity is vertical, use another perpendicular\n perpDir.set(new Vector3(1, 0, 0));\n } else {\n perpDir.inplaceNormalize();\n }\n\n // Rotation center is perpendicular to velocity\n const center = Vector3.add(\n particle.position,\n Vector3.scale(perpDir, estimatedRadius, new Vector3()),\n new Vector3()\n );\n return center;\n }\n\n // Fit a circle through the last 3 positions\n // Use positions at indices: 0 (oldest), middle, last (newest)\n const p1 = history[0];\n const p2 = history[Math.floor(history.length / 2)];\n const p3 = history[history.length - 1];\n\n // Calculate circle center from 3 points\n const center = this.calculateCircleCenter(p1, p2, p3);\n return center;\n }\n\n /**\n * Calculates the center of a circle passing through 3 points\n * Uses perpendicular bisector method\n */\n private calculateCircleCenter(p1: Vector3, p2: Vector3, p3: Vector3): Vector3 {\n // Midpoints\n const mid12 = Vector3.scale(Vector3.add(p1, p2, new Vector3()), 0.5, new Vector3());\n const mid23 = Vector3.scale(Vector3.add(p2, p3, new Vector3()), 0.5, new Vector3());\n\n // Direction vectors\n const dir12 = Vector3.sub(p2, p1, new Vector3());\n const dir23 = Vector3.sub(p3, p2, new Vector3());\n\n // Normal vectors (perpendicular bisectors)\n // For 3D, we need to find perpendiculars in the plane of the three points\n const normal = Vector3.cross(dir12, dir23, new Vector3());\n\n if (normal.magnitudeSq < 0.0001) {\n // Points are collinear, return midpoint\n return Vector3.scale(\n Vector3.add(Vector3.add(p1, p2, new Vector3()), p3, new Vector3()),\n 1.0 / 3.0,\n new Vector3()\n );\n }\n\n normal.inplaceNormalize();\n\n // Perpendicular to dir12 in the plane\n const perp12 = Vector3.cross(dir12, normal, new Vector3()).inplaceNormalize();\n\n // Perpendicular to dir23 in the plane\n const perp23 = Vector3.cross(dir23, normal, new Vector3()).inplaceNormalize();\n\n // Find intersection of two lines:\n // Line 1: mid12 + t * perp12\n // Line 2: mid23 + s * perp23\n // Solve: mid12 + t * perp12 = mid23 + s * perp23\n\n const diff = Vector3.sub(mid23, mid12, new Vector3());\n\n // Use 2D projection for simplicity (project onto plane perpendicular to normal)\n // Solve in the plane: t * perp12 - s * perp23 = diff\n // Use least squares or pick the dominant components\n\n const det = perp12.x * perp23.y - perp12.y * perp23.x;\n\n if (Math.abs(det) > 0.0001) {\n const t = (diff.x * perp23.y - diff.y * perp23.x) / det;\n const center = Vector3.add(mid12, Vector3.scale(perp12, t, new Vector3()), new Vector3());\n return center;\n }\n\n // Fallback: use centroid\n return Vector3.scale(\n Vector3.add(Vector3.add(p1, p2, new Vector3()), p3, new Vector3()),\n 1.0 / 3.0,\n new Vector3()\n );\n }\n\n /**\n * Calculates inertial acceleration for a particle in a rotating reference frame\n */\n private calculateInertialAcceleration(\n particle: any,\n rotationCenter: Vector3,\n angularVelocity: Vector3,\n particleVelocity: Vector3,\n centrifugalScale: number,\n coriolisScale: number\n ): Vector3 {\n // Vector from rotation center to particle\n const r = Vector3.sub(particle.position, rotationCenter, new Vector3());\n\n // Centrifugal acceleration: a_centrifugal = ω × (ω × r)\n const omegaCrossR = Vector3.cross(angularVelocity, r, new Vector3());\n const centrifugalAccel = Vector3.cross(angularVelocity, omegaCrossR, new Vector3());\n centrifugalAccel.scaleBy(centrifugalScale);\n\n // Coriolis acceleration: a_coriolis = -2ω × v_relative\n // v_relative is the particle's velocity in the rotating frame\n // Use the velocity passed in (already calculated from prevPosition)\n const coriolisAccel = Vector3.cross(angularVelocity, particleVelocity, new Vector3());\n coriolisAccel.scaleBy(-2.0 * coriolisScale);\n\n // Total inertial acceleration\n const totalAccel = Vector3.add(centrifugalAccel, coriolisAccel, new Vector3());\n return totalAccel;\n }\n\n /**\n * Solves a single spring constraint using XPBD (Extended Position-Based Dynamics).\n *\n * Reference: Müller et al., \"Detailed Rigid Body Simulation with Extended Position Based Dynamics\", 2020.\n */\n private solveConstraintXPBD(constraint: any, dt: number): void {\n const pA = this._chain.particles[constraint.particleA];\n const pB = this._chain.particles[constraint.particleB];\n\n const wA = pA.fixed ? 0 : 1.0 / pA.mass;\n const wB = pB.fixed ? 0 : 1.0 / pB.mass;\n const wSum = wA + wB;\n if (wSum < 1e-10) {\n return;\n }\n\n const delta = Vector3.sub(pB.position, pA.position, new Vector3());\n const currentLength = delta.magnitude;\n if (currentLength < 0.0001) {\n return;\n }\n\n // Constraint value C = currentLength - restLength\n const C = currentLength - constraint.restLength;\n\n // Scaled compliance: alphaTilde = compliance / dt^2\n const alphaTilde = constraint.compliance / (dt * dt);\n\n // XPBD Lagrange multiplier update\n const deltaLambda = (-C - alphaTilde * constraint.lambda) / (wSum + alphaTilde);\n constraint.lambda += deltaLambda;\n\n // Correction direction (unit vector from A to B)\n const n = Vector3.scale(delta, 1.0 / currentLength, new Vector3());\n\n if (!pA.fixed) {\n // deltaX_a = -w_a * deltaLambda * n\n Vector3.add(pA.position, Vector3.scale(n, -wA * deltaLambda, new Vector3()), pA.position);\n }\n if (!pB.fixed) {\n // deltaX_b = +w_b * deltaLambda * n\n Vector3.add(pB.position, Vector3.scale(n, wB * deltaLambda, new Vector3()), pB.position);\n }\n }\n\n /**\n * Solves a single spring constraint (Verlet / PBD)\n */\n private solveConstraint(constraint: any): void {\n const pA = this._chain.particles[constraint.particleA];\n const pB = this._chain.particles[constraint.particleB];\n\n // Calculate current distance\n const delta = Vector3.sub(pB.position, pA.position, new Vector3());\n const currentLength = delta.magnitude;\n\n if (currentLength < 0.0001) {\n return;\n } // Avoid division by zero\n\n // Calculate correction\n const diff = (currentLength - constraint.restLength) / currentLength;\n const correction = Vector3.scale(delta, diff * constraint.stiffness * 0.5, new Vector3());\n\n // Apply correction (considering mass and fixed state)\n if (!pA.fixed) {\n Vector3.add(pA.position, correction, pA.position);\n }\n if (!pB.fixed) {\n Vector3.sub(pB.position, correction, pB.position);\n }\n }\n\n /**\n * Solves collisions for all particles\n */\n private solveCollisions(deltaTime: number): void {\n // Update dynamic colliders from their nodes\n const blend = this.getTemporalBlendFactor(deltaTime, DEFAULT_COLLIDER_SMOOTHING_TIME);\n const spheres: { particleCollider: SphereCollider; collider: SphereCollider }[] = [];\n const capsules: { particleCollider: CapsuleCollider; collider: CapsuleCollider }[] = [];\n const planes: { particleCollider: PlaneCollider; collider: PlaneCollider }[] = [];\n for (const collider of this._colliders) {\n if (collider.node) {\n updateColliderFromNode(collider);\n }\n if (!collider.enabled) {\n continue;\n }\n switch (collider.type) {\n case 'sphere': {\n const source = collider as SphereCollider;\n spheres.push({\n particleCollider: source,\n collider: {\n ...source,\n center: this.getSmoothedSphereCenter(source, blend)\n }\n });\n break;\n }\n case 'capsule': {\n const source = collider as CapsuleCollider;\n const endpoints = this.getSmoothedCapsuleEndpoints(source, blend);\n capsules.push({\n particleCollider: source,\n collider: {\n ...source,\n start: endpoints.start,\n end: endpoints.end\n }\n });\n break;\n }\n case 'plane': {\n const source = collider as PlaneCollider;\n const plane = this.getSmoothedPlaneData(source, blend);\n planes.push({\n particleCollider: source,\n collider: {\n ...source,\n point: plane.point,\n normal: plane.normal\n }\n });\n break;\n }\n }\n }\n\n // Check each particle against all colliders\n for (const particle of this._chain.particles) {\n if (particle.fixed) {\n continue; // Skip fixed particles\n }\n\n for (const collider of spheres) {\n resolveSphereCollision(particle.position, collider.collider);\n }\n for (const collider of capsules) {\n resolveCapsuleCollision(particle.position, collider.collider);\n }\n for (const collider of planes) {\n resolvePlaneCollision(particle.position, collider.collider);\n }\n }\n }\n\n /**\n * Applies simulation results to scene nodes\n * @param weight - Blend weight [0-1] (default: 1.0)\n */\n applyToNodes(weight: number = 1.0): void {\n for (let i = 0; i < this._chain.particles.length - 1; i++) {\n const particle = this._chain.particles[i];\n const nextParticle = this._chain.particles[i + 1];\n const node = particle.node;\n\n // Skip if no node\n if (!node) {\n continue;\n }\n\n // Get current bone direction from node's world matrix (before physics)\n // This reflects the current animation/skeleton state\n const currentBonePos = new Vector3(node.worldMatrix.m03, node.worldMatrix.m13, node.worldMatrix.m23);\n\n const nextNode = nextParticle.node;\n if (!nextNode) {\n continue;\n }\n\n const nextBonePos = new Vector3(\n nextNode.worldMatrix.m03,\n nextNode.worldMatrix.m13,\n nextNode.worldMatrix.m23\n );\n const originalDir = Vector3.sub(nextBonePos, currentBonePos, new Vector3());\n\n // Get current bone rotation from node's world matrix\n const currentBoneRotation = new Quaternion();\n node.worldMatrix.decompose(null, currentBoneRotation, null);\n\n // Calculate new direction from physics simulation\n const newDir = Vector3.sub(nextParticle.position, particle.position, new Vector3());\n\n // Calculate rotation needed to align original direction to new direction\n const deltaRotation = new Quaternion();\n IKUtils.fromToRotation(originalDir, newDir, deltaRotation);\n\n // Calculate new world rotation\n let worldRotation = Quaternion.multiply(deltaRotation, currentBoneRotation, new Quaternion());\n\n // Blend with current rotation based on weight\n if (weight < 1) {\n Quaternion.slerp(currentBoneRotation, worldRotation, weight, worldRotation);\n }\n\n // Convert world rotation to local rotation (relative to parent)\n const parent = node.parent;\n if (parent) {\n const parentWorldRotation = new Quaternion();\n parent.worldMatrix.decompose(null, parentWorldRotation, null);\n\n // localRotation = conjugate(parentWorldRotation) * worldRotation\n const parentInvRotation = Quaternion.conjugate(parentWorldRotation, new Quaternion());\n const localRotation = Quaternion.multiply(parentInvRotation, worldRotation, new Quaternion());\n\n node.rotation = localRotation;\n } else {\n // Root node has no parent, world rotation is local rotation\n node.rotation = worldRotation;\n }\n }\n }\n\n /**\n * Resets the simulation to initial state\n */\n reset(): void {\n this._chain.reset();\n for (const particle of this._chain.particles) {\n particle.animPosition.set(particle.originalPosition);\n particle.lastFramePosition.set(particle.originalPosition);\n if (particle.positionHistory) {\n particle.positionHistory.length = 0;\n }\n }\n this._timeAccumulator = 0;\n this._smoothedParticleTargets = new WeakMap();\n this._smoothedSphereCenters = new WeakMap();\n this._smoothedCapsuleEndpoints = new WeakMap();\n this._smoothedPlaneData = new WeakMap();\n }\n\n /**\n * Gets the spring chain\n */\n get chain(): SpringChain {\n return this._chain;\n }\n\n /**\n * Gets the current gravity\n */\n get gravity(): Vector3 {\n return this._gravity;\n }\n\n set gravity(gravity: Vector3) {\n this._gravity.set(gravity);\n }\n\n /**\n * Gets the current wind\n */\n get wind(): Vector3 {\n return this._wind;\n }\n\n set wind(wind: Vector3) {\n this._wind.set(wind);\n }\n\n /**\n * Gets the number of iterations\n */\n get iterations(): number {\n return this._iterations;\n }\n\n set iterations(count: number) {\n this._iterations = Math.max(1, count);\n }\n\n /**\n * Gets whether inertial forces are enabled\n */\n get enableInertialForces(): boolean {\n return this._enableInertialForces;\n }\n\n set enableInertialForces(enabled: boolean) {\n this._enableInertialForces = enabled;\n }\n\n /**\n * Gets the centrifugal force scale\n */\n get centrifugalScale(): number {\n return this._centrifugalScale;\n }\n\n set centrifugalScale(scale: number) {\n this._centrifugalScale = Math.max(0, scale);\n }\n\n /**\n * Gets the Coriolis force scale\n */\n get coriolisScale(): number {\n return this._coriolisScale;\n }\n\n set coriolisScale(scale: number) {\n this._coriolisScale = Math.max(0, scale);\n }\n\n /**\n * Gets the constraint solver type\n */\n get solver(): 'verlet' | 'xpbd' {\n return this._solver;\n }\n\n set solver(type: 'verlet' | 'xpbd') {\n if (this._solver !== type) {\n this._solver = type;\n if (type === 'xpbd') {\n for (const c of this._chain.constraints) {\n c.lambda = 0;\n }\n }\n }\n }\n\n /**\n * Gets pose preservation strength [0-1]\n */\n get poseFollow(): number {\n return this._poseFollow;\n }\n\n set poseFollow(value: number) {\n const v = Math.max(0, Math.min(1, value));\n this._poseFollow = v;\n this._poseFollowRoot = v;\n this._poseFollowTip = v;\n }\n\n /**\n * Gets max allowed deviation from animated pose\n */\n get maxPoseOffset(): number {\n return this._maxPoseOffset;\n }\n\n set maxPoseOffset(value: number) {\n const v = Math.max(0, value);\n this._maxPoseOffset = v;\n this._maxPoseOffsetRoot = v;\n this._maxPoseOffsetTip = v;\n }\n\n /**\n * Gets root pose follow strength [0-1]\n */\n get poseFollowRoot(): number {\n return this._poseFollowRoot;\n }\n\n set poseFollowRoot(value: number) {\n this._poseFollowRoot = Math.max(0, Math.min(1, value));\n }\n\n /**\n * Gets tip pose follow strength [0-1]\n */\n get poseFollowTip(): number {\n return this._poseFollowTip;\n }\n\n set poseFollowTip(value: number) {\n this._poseFollowTip = Math.max(0, Math.min(1, value));\n }\n\n /**\n * Gets exponent for root-to-tip interpolation\n */\n get poseFollowExponent(): number {\n return this._poseFollowExponent;\n }\n\n set poseFollowExponent(value: number) {\n this._poseFollowExponent = Math.max(0.1, value);\n }\n\n /**\n * Gets root max allowed deviation from animated pose\n */\n get maxPoseOffsetRoot(): number {\n return this._maxPoseOffsetRoot;\n }\n\n set maxPoseOffsetRoot(value: number) {\n this._maxPoseOffsetRoot = Math.max(0, value);\n }\n\n /**\n * Gets tip max allowed deviation from animated pose\n */\n get maxPoseOffsetTip(): number {\n return this._maxPoseOffsetTip;\n }\n\n set maxPoseOffsetTip(value: number) {\n this._maxPoseOffsetTip = Math.max(0, value);\n }\n\n /**\n * Adds a collider to the system\n */\n addCollider(collider: SpringCollider): void {\n this._colliders.push(collider);\n this._smoothedSphereCenters = new WeakMap();\n this._smoothedCapsuleEndpoints = new WeakMap();\n this._smoothedPlaneData = new WeakMap();\n }\n\n /**\n * Removes a collider from the system\n */\n removeCollider(collider: SpringCollider): boolean {\n const index = this._colliders.indexOf(collider);\n if (index >= 0) {\n this._colliders.splice(index, 1);\n this._smoothedSphereCenters = new WeakMap();\n this._smoothedCapsuleEndpoints = new WeakMap();\n this._smoothedPlaneData = new WeakMap();\n return true;\n }\n return false;\n }\n\n /**\n * Clears all colliders\n */\n clearColliders(): void {\n this._colliders = [];\n this._smoothedSphereCenters = new WeakMap();\n this._smoothedCapsuleEndpoints = new WeakMap();\n this._smoothedPlaneData = new WeakMap();\n }\n\n /**\n * Gets all colliders\n */\n get colliders(): SpringCollider[] {\n return this._colliders;\n }\n\n private getTemporalBlendFactor(deltaTime: number, smoothingTime: number): number {\n const dt = Math.min(Math.max(Number(deltaTime) || 0, 0), MAX_ACCUMULATED_SIMULATION_TIME);\n if (smoothingTime <= 0) {\n return 1;\n }\n if (dt <= 0) {\n return 0;\n }\n return 1 - Math.exp(-dt / smoothingTime);\n }\n\n private getSmoothedParticleTarget(target: object, current: Vector3, blend: number): Vector3 {\n const cached = this._smoothedParticleTargets.get(target);\n if (!cached || blend >= 1) {\n const next = current.clone();\n this._smoothedParticleTargets.set(target, next);\n return next;\n }\n cached.setXYZ(\n cached.x + (current.x - cached.x) * blend,\n cached.y + (current.y - cached.y) * blend,\n cached.z + (current.z - cached.z) * blend\n );\n return cached;\n }\n\n private getSmoothedSphereCenter(collider: SphereCollider, blend: number): Vector3 {\n const current = collider.center?.clone() ?? new Vector3();\n const cached = this._smoothedSphereCenters.get(collider);\n if (!cached || blend >= 1) {\n this._smoothedSphereCenters.set(collider, current);\n return current;\n }\n cached.setXYZ(\n cached.x + (current.x - cached.x) * blend,\n cached.y + (current.y - cached.y) * blend,\n cached.z + (current.z - cached.z) * blend\n );\n return cached;\n }\n\n private getSmoothedCapsuleEndpoints(\n collider: CapsuleCollider,\n blend: number\n ): { start: Vector3; end: Vector3 } {\n const currentStart = collider.start?.clone() ?? new Vector3();\n const currentEnd = collider.end?.clone() ?? new Vector3();\n const cached = this._smoothedCapsuleEndpoints.get(collider);\n if (!cached || blend >= 1) {\n const next = {\n start: currentStart,\n end: currentEnd\n };\n this._smoothedCapsuleEndpoints.set(collider, next);\n return next;\n }\n cached.start.setXYZ(\n cached.start.x + (currentStart.x - cached.start.x) * blend,\n cached.start.y + (currentStart.y - cached.start.y) * blend,\n cached.start.z + (currentStart.z - cached.start.z) * blend\n );\n cached.end.setXYZ(\n cached.end.x + (currentEnd.x - cached.end.x) * blend,\n cached.end.y + (currentEnd.y - cached.end.y) * blend,\n cached.end.z + (currentEnd.z - cached.end.z) * blend\n );\n return cached;\n }\n\n private getSmoothedPlaneData(collider: PlaneCollider, blend: number): { point: Vector3; normal: Vector3 } {\n const currentPoint = collider.point?.clone() ?? new Vector3();\n const currentNormal = collider.normal?.clone() ?? Vector3.axisPY();\n if (currentNormal.magnitudeSq > 1e-8) {\n currentNormal.inplaceNormalize();\n } else {\n currentNormal.setXYZ(0, 1, 0);\n }\n const cached = this._smoothedPlaneData.get(collider);\n if (!cached || blend >= 1) {\n const next = {\n point: currentPoint,\n normal: currentNormal\n };\n this._smoothedPlaneData.set(collider, next);\n return next;\n }\n cached.point.setXYZ(\n cached.point.x + (currentPoint.x - cached.point.x) * blend,\n cached.point.y + (currentPoint.y - cached.point.y) * blend,\n cached.point.z + (currentPoint.z - cached.point.z) * blend\n );\n cached.normal.setXYZ(\n cached.normal.x + (currentNormal.x - cached.normal.x) * blend,\n cached.normal.y + (currentNormal.y - cached.normal.y) * blend,\n cached.normal.z + (currentNormal.z - cached.normal.z) * blend\n );\n if (cached.normal.magnitudeSq > 1e-8) {\n cached.normal.inplaceNormalize();\n } else {\n cached.normal.setXYZ(0, 1, 0);\n }\n return cached;\n }\n}\n"],"names":["FIXED_SIMULATION_TIME_STEP","MAX_ACCUMULATED_SIMULATION_TIME","MAX_SIMULATION_STEPS_PER_UPDATE","Math","max","ceil","DEFAULT_PARTICLE_TARGET_SMOOTHING_TIME","DEFAULT_COLLIDER_SMOOTHING_TIME","SpringSystem","_chain","_iterations","_gravity","_wind","_enableInertialForces","_centrifugalScale","_coriolisScale","_colliders","_solver","_poseFollow","_maxPoseOffset","_poseFollowRoot","_poseFollowTip","_poseFollowExponent","_maxPoseOffsetRoot","_maxPoseOffsetTip","_timeAccumulator","_smoothedParticleTargets","_smoothedSphereCenters","_smoothedCapsuleEndpoints","_smoothedPlaneData","chain","options","iterations","gravity","clone","Vector3","wind","enableInertialForces","centrifugalScale","coriolisScale","solver","min","poseFollow","maxPoseOffset","poseFollowRoot","poseFollowTip","poseFollowExponent","maxPoseOffsetRoot","maxPoseOffsetTip","WeakMap","update","deltaTime","frameDt","Number","stepCount","floor","i","simulateStep","dt","inputDeltaTime","p","particles","lastFramePosition","set","position","updateFixedParticles","rotationCenter","angularVelocity","result","calculateGlobalRotation","center","omega","length","fixed","velocity","sub","prevPosition","scaleBy","damping","acceleration","add","inertialAccel","calculateInertialAcceleration","positionDelta","scale","constraint","constraints","lambda","iter","solveConstraintXPBD","solveConstraint","solvePosePreservation","solveCollisions","blend","getTemporalBlendFactor","particle","node","worldMatrix","worldPos","m03","m13","m23","smoothedTarget","getSmoothedParticleTarget","animPosition","positionHistory","push","shift","totalIterations","lastIndex","t","pow","particlePoseFollow","lerp","iterationFollow","toAnim","correction","particleMaxPoseOffset","offset","offsetLen","magnitude","a","b","fixedParticles","velocities","magnitudeSq","estimateRotationCenterFromHistory","sumOmega","count","r","v","rLengthSq","cross","currentVelocity","history","speed","estimatedRadius","up","perpDir","inplaceNormalize","p1","p2","p3","calculateCircleCenter","mid12","mid23","dir12","dir23","normal","perp12","perp23","diff","det","x","y","abs","particleVelocity","omegaCrossR","centrifugalAccel","coriolisAccel","totalAccel","pA","particleA","pB","particleB","wA","mass","wB","wSum","delta","currentLength","C","restLength","alphaTilde","compliance","deltaLambda","n","stiffness","spheres","capsules","planes","collider","updateColliderFromNode","enabled","type","source","particleCollider","getSmoothedSphereCenter","endpoints","getSmoothedCapsuleEndpoints","start","end","plane","getSmoothedPlaneData","point","resolveSphereCollision","resolveCapsuleCollision","resolvePlaneCollision","applyToNodes","weight","nextParticle","currentBonePos","nextNode","nextBonePos","originalDir","currentBoneRotation","Quaternion","decompose","newDir","deltaRotation","IKUtils","fromToRotation","worldRotation","multiply","slerp","parent","parentWorldRotation","parentInvRotation","conjugate","localRotation","rotation","reset","originalPosition","c","value","addCollider","removeCollider","index","indexOf","splice","clearColliders","colliders","smoothingTime","exp","target","current","cached","get","next","setXYZ","z","currentStart","currentEnd","currentPoint","currentNormal","axisPY"],"mappings":";;;;AA+EA,MAAMA,6BAA6B,CAAI,GAAA,EAAA;AACvC,MAAMC,kCAAkC,CAAI,GAAA,EAAA;AAC5C,MAAMC,+BAAAA,GAAkCC,KAAKC,GAAG,CAC9C,GACAD,IAAKE,CAAAA,IAAI,CAACJ,+BAAkCD,GAAAA,0BAAAA,CAAAA,CAAAA;AAE9C,MAAMM,yCAAyC,CAAI,GAAA,EAAA;AACnD,MAAMC,kCAAkC,CAAI,GAAA,EAAA;AAE5C;;;;;AAKC,IACM,MAAMC,YAAAA,CAAAA;IACHC,MAAoB;IACpBC,WAAoB;IACpBC,QAAkB;IAClBC,KAAe;IACfC,qBAA+B;IAC/BC,iBAA0B;IAC1BC,cAAuB;IACvBC,UAA6B;IAC7BC,OAA2B;IAC3BC,WAAoB;IACpBC,cAAuB;IACvBC,eAAwB;IACxBC,cAAuB;IACvBC,mBAA4B;IAC5BC,kBAA2B;IAC3BC,iBAA0B;IAC1BC,gBAAyB;IACzBC,wBAAmD;IACnDC,sBAAyD;IACzDC,yBAAsF;IACtFC,kBAAgF;IAExF,WAAYC,CAAAA,KAAkB,EAAEC,OAA6B,CAAE;QAC7D,IAAI,CAACtB,MAAM,GAAGqB,KAAAA;AACd,QAAA,IAAI,CAACpB,WAAW,GAAGqB,OAAAA,EAASC,UAAc,IAAA,CAAA;QAC1C,IAAI,CAACrB,QAAQ,GAAGoB,OAASE,EAAAA,OAAAA,EAASC,WAAW,IAAIC,OAAAA,CAAQ,CAAG,EAAA,IAAM,EAAA,CAAA,CAAA;QAClE,IAAI,CAACvB,KAAK,GAAGmB,OAAAA,EAASK,MAAMF,KAAW,EAAA,IAAA,IAAIC,OAAQ,CAAA,CAAA,EAAG,CAAG,EAAA,CAAA,CAAA;AACzD,QAAA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CAAOxF,MAAM,CAACK,CAAC,GAAI2F,CAAAA,aAAAA,CAAc3F,CAAC,GAAGmF,MAAAA,CAAOxF,MAAM,CAACK,CAAAA,IAAK5D,KACxD+I,EAAAA,MAAAA,CAAOxF,MAAM,CAACM,CAAC,GAAG,CAAC0F,aAAAA,CAAc1F,CAAC,GAAGkF,MAAOxF,CAAAA,MAAM,CAACM,CAAAA,IAAK7D,KAAAA,EACxD+I,MAAOxF,CAAAA,MAAM,CAAC4F,CAAC,GAAG,CAACI,aAAcJ,CAAAA,CAAC,GAAGJ,MAAAA,CAAOxF,MAAM,CAAC4F,CAAAA,IAAKnJ,KAAAA,CAAAA;AAE1D,QAAA,IAAI+I,MAAOxF,CAAAA,MAAM,CAACvB,WAAW,GAAG,IAAM,EAAA;YACpC+G,MAAOxF,CAAAA,MAAM,CAACT,gBAAgB,EAAA;SACzB,MAAA;AACLiG,YAAAA,MAAAA,CAAOxF,MAAM,CAAC2F,MAAM,CAAC,GAAG,CAAG,EAAA,CAAA,CAAA;AAC7B;QACA,OAAOH,MAAAA;AACT;AACF;;;;"}
|
package/dist/app/app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.js","sources":["../../src/app/app.ts"],"sourcesContent":["import type { Nullable, RequireOptionals, VFS } from '@zephyr3d/base';\r\nimport { Observable, flushPendingDisposals } from '@zephyr3d/base';\r\nimport type { AbstractDevice, DeviceBackend } from '@zephyr3d/device';\r\nimport { InputManager } from './inputmgr';\r\nimport { Engine } from './engine';\r\nimport { getApp, setApp } from './api';\r\nimport type { ScreenConfig } from './screen';\r\n\r\ntype appEventMap = {\r\n /**\r\n * Emitted when the drawing surface (canvas/device) is resized.\r\n *\r\n * @param width - New drawable width in device pixels.\r\n * @param height - New drawable height in device pixels.\r\n */\r\n resize: [width: number, height: number];\r\n /**\r\n * Emitted every frame with timing information.\r\n *\r\n * @param deltaTimeMs - Elapsed time since last frame in milliseconds.\r\n * @param elapsedTimeMs - Elapsed time since app start in milliseconds.\r\n */\r\n tick: [deltaTimeMs: number, elapsedTimeMs: number];\r\n /** Pointer/mouse and keyboard input events forwarded by the Application. */\r\n click: [evt: PointerEvent];\r\n dblclick: [evt: PointerEvent];\r\n pointerdown: [evt: PointerEvent];\r\n pointerup: [evt: PointerEvent];\r\n pointermove: [evt: PointerEvent];\r\n pointercancel: [evt: PointerEvent];\r\n pointerenter: [evt: PointerEvent];\r\n pointerleave: [evt: PointerEvent];\r\n pointerover: [evt: PointerEvent];\r\n pointerout: [evt: PointerEvent];\r\n wheel: [evt: WheelEvent];\r\n keydown: [evt: KeyboardEvent];\r\n keyup: [evt: KeyboardEvent];\r\n keypress: [evt: KeyboardEvent];\r\n drag: [evt: DragEvent];\r\n dragenter: [evt: DragEvent];\r\n dragleave: [evt: DragEvent];\r\n dragover: [evt: DragEvent];\r\n dragstart: [evt: DragEvent];\r\n dragend: [evt: DragEvent];\r\n drop: [evt: DragEvent];\r\n};\r\n\r\n/** Editor Mode */\r\nexport type EditorMode = 'editor' | 'editor-preview' | 'none';\r\n\r\n/**\r\n * Options for Application.\r\n *\r\n * @public\r\n */\r\nexport interface AppOptions {\r\n /**\r\n * Target canvas element to attach the rendering device to.\r\n */\r\n canvas: HTMLCanvasElement;\r\n /**\r\n * Device backend implementation to use for GPU creation (e.g., WebGL/WebGPU backend).\r\n */\r\n backend: DeviceBackend;\r\n /**\r\n * Whether to enable multi-sample anti-aliasing (MSAA) if supported by the backend.\r\n * Defaults to false.\r\n */\r\n enableMSAA?: boolean;\r\n /**\r\n * Device pixel ratio used when creating the device. Defaults to `window.devicePixelRatio` or 1.\r\n */\r\n pixelRatio?: number;\r\n}\r\n\r\n/**\r\n * Creation options for Application.\r\n *\r\n * Provides the canvas, device backend, and optional runtime and device configuration.\r\n * @public\r\n */\r\nexport interface AppCreationOptions extends AppOptions {\r\n /**\r\n * Options for the runtime scripting system.\r\n */\r\n runtimeOptions?: {\r\n /**\r\n * Virtual file system used to load scripts. Defaults to HttpFS at '.' if not provided.\r\n */\r\n VFS?: VFS;\r\n /**\r\n * Root directory for script files. Defaults to '/'.\r\n */\r\n scriptsRoot?: string;\r\n /**\r\n * Whether the application is running in editor mode. Should be true for user applications.\r\n */\r\n editorMode?: EditorMode;\r\n /**\r\n * Whether the runtime scripting system is enabled. Should be true for user applications.\r\n */\r\n enabled?: boolean;\r\n /**\r\n * Screen configuration\r\n */\r\n screen?: ScreenConfig;\r\n };\r\n}\r\n\r\n/**\r\n * Log severity levels.\r\n * @public\r\n */\r\nexport type LogMode = 'info' | 'warn' | 'error' | 'debug';\r\n\r\n/**\r\n * Application\r\n *\r\n * Entry-point and lifecycle coordinator for the engine. Responsible for:\r\n * - Creating and owning the rendering device from a chosen backend.\r\n * - Managing the per-frame loop, including timing and viewport setup.\r\n * - Forwarding device/DOM input events via an observable event map.\r\n * - Hosting the runtime scripting system and input manager.\r\n *\r\n * Singleton:\r\n * - Only one instance may exist at a time. Access via `{@link getApp}`.\r\n *\r\n * Events:\r\n * - See `appEventMap` for all emitted events (resize, tick, pointer/keyboard/drag).\r\n *\r\n * Usage:\r\n * - Construct with `AppOptions`, await `ready()`, then call `run()` to start the loop.\r\n *\r\n * @public\r\n */\r\nexport class Application extends Observable<appEventMap> {\r\n private readonly _options: RequireOptionals<AppOptions>;\r\n private _device: Nullable<AbstractDevice>;\r\n private readonly _inputManager: InputManager;\r\n private readonly _engine: Engine;\r\n private readonly _editorMode: EditorMode;\r\n private _ready: boolean;\r\n /**\r\n * Construct the Application singleton with the provided options.\r\n *\r\n * Throws if an instance already exists.\r\n *\r\n * @param opt - Application creation options (canvas, backend, and optional runtime/device settings).\r\n */\r\n constructor(opt: AppCreationOptions) {\r\n super();\r\n if (getApp()) {\r\n throw new Error('It is not allowed to have multiple Application instances');\r\n }\r\n setApp(this);\r\n\r\n this._options = {\r\n backend: opt.backend,\r\n enableMSAA: opt.enableMSAA ?? false,\r\n pixelRatio: opt.pixelRatio ?? window.devicePixelRatio ?? 1,\r\n canvas: opt.canvas\r\n };\r\n this._inputManager = new InputManager(this);\r\n this._engine = new Engine(\r\n opt.runtimeOptions?.VFS,\r\n opt.runtimeOptions?.scriptsRoot,\r\n opt.runtimeOptions?.enabled\r\n );\r\n if (opt.runtimeOptions?.screen) {\r\n this._engine.screen.config = opt.runtimeOptions.screen;\r\n }\r\n this._editorMode = opt.runtimeOptions?.editorMode ?? 'none';\r\n this._device = null;\r\n this._ready = false;\r\n }\r\n /**\r\n * Editor mode\r\n */\r\n get editorMode() {\r\n return this._editorMode;\r\n }\r\n /**\r\n * The input manager instance handling pointer/keyboard event routing.\r\n */\r\n get inputManager() {\r\n return this._inputManager;\r\n }\r\n /**\r\n * Get the instanceof {@link Engine}.\r\n */\r\n get engine() {\r\n return this._engine;\r\n }\r\n /**\r\n * The (sanitized) options used to create this application.\r\n *\r\n * Note: Defaults are applied for `enableMSAA` and `pixelRatio` if omitted.\r\n */\r\n get options() {\r\n return this._options;\r\n }\r\n /**\r\n * The initialized rendering device.\r\n *\r\n * Available after `await ready()`.\r\n */\r\n get device() {\r\n return this._device!;\r\n }\r\n /**\r\n * Convenience accessor for the device type name provided by the backend.\r\n */\r\n get deviceType() {\r\n return this._options.backend.typeName();\r\n }\r\n /**\r\n * Set keyboard focus to the device's canvas element.\r\n */\r\n focus() {\r\n this._device!.canvas.focus();\r\n }\r\n /**\r\n * Initialize the rendering device and start input processing.\r\n *\r\n * @throws If device creation fails.\r\n */\r\n async ready() {\r\n if (!this._ready) {\r\n this._device = await this._options.backend.createDevice(this._options.canvas, {\r\n dpr: this._options.pixelRatio,\r\n msaa: !!this._options.enableMSAA\r\n });\r\n if (!this._device) {\r\n throw new Error('App.init(): create device failed');\r\n }\r\n this._device.canvas.focus();\r\n await this._engine.init();\r\n this._inputManager.start();\r\n this._device.on('resize', (width, height) => {\r\n this._engine.screen.resolveViewport();\r\n this.dispatchEvent('resize', width, height);\r\n });\r\n this._ready = true;\r\n }\r\n }\r\n /**\r\n * Render a single frame.\r\n *\r\n * Steps:\r\n * - Flushes pending disposals from the previous frame.\r\n * - Clears device state (framebuffer, viewport, scissor).\r\n * - Queries frame timing from the device (`elapsedFrame`, `elapsedOverall`).\r\n * - Updates the runtime manager (scripting/behaviors).\r\n * - Emits `tick` with delta/elapsed times.\r\n *\r\n * Safe to call manually; also used by the run loop.\r\n */\r\n frame() {\r\n // Processes all pending disposals from the previous frame.\r\n flushPendingDisposals();\r\n if (this._ready) {\r\n this.device.setFramebuffer(null);\r\n this.device.setViewport(null);\r\n this.device.setScissor(null);\r\n const dt = this.device.frameInfo.elapsedFrame;\r\n const elapsed = this.device.frameInfo.elapsedOverall;\r\n this.dispatchEvent('tick', dt, elapsed);\r\n this._engine.update(dt * 0.001, elapsed * 0.001);\r\n this._engine.render();\r\n }\r\n }\r\n /**\r\n * Start the application's render loop.\r\n *\r\n * Uses the device's internal scheduling (`device.runLoop`) to repeatedly call `frame()`.\r\n */\r\n run() {\r\n this.device.runLoop(() => {\r\n this.frame();\r\n });\r\n }\r\n /**\r\n * Stop the application's render loop.\r\n *\r\n * Uses `device.exitLoop()` to end the scheduling started by `run()`.\r\n */\r\n stop() {\r\n this.device.exitLoop();\r\n }\r\n}\r\n"],"names":["Application","Observable","_options","_device","_inputManager","_engine","_editorMode","_ready","opt","getApp","Error","setApp","backend","enableMSAA","pixelRatio","window","devicePixelRatio","canvas","InputManager","Engine","runtimeOptions","VFS","scriptsRoot","enabled","screen","config","editorMode","inputManager","engine","options","device","deviceType","typeName","focus","ready","createDevice","dpr","msaa","init","start","on","width","height","resolveViewport","dispatchEvent","frame","flushPendingDisposals","setFramebuffer","setViewport","setScissor","dt","frameInfo","elapsedFrame","elapsed","elapsedOverall","update","render","run","runLoop","stop","exitLoop"],"mappings":";;;;;AAmHA;;;;;;;;;;;;;;;;;;;IAoBO,MAAMA,WAAoBC,SAAAA,UAAAA,CAAAA;IACdC,QAAuC;IAChDC,OAAkC;IACzBC,aAA4B;IAC5BC,OAAgB;IAChBC,WAAwB;IACjCC,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OC,EAAAA,MAAAA,CAAAA;AACtC,aAAA,CAAA;YACA,IAAI,CAACnC,MAAM,GAAG,IAAA;AAChB;AACF;AACA;;;;;;;;;;;AAWC,MACDsC,KAAQ,GAAA;;AAENC,QAAAA,qBAAAA,EAAAA;QACA,IAAI,IAAI,CAACvC,MAAM,EAAE;AACf,YAAA,IAAI,CAACuB,MAAM,CAACiB,cAAc,CAAC,IAAA,CAAA;AAC3B,YAAA,IAAI,CAACjB,MAAM,CAACkB,WAAW,CAAC,IAAA,CAAA;AACxB,YAAA,IAAI,CAAClB,MAAM,CAACmB,UAAU,CAAC,IAAA,CAAA;AACvB,YAAA,MAAMC,KAAK,IAAI,CAACpB,MAAM,CAACqB,SAAS,CAACC,YAAY;AAC7C,YAAA,MAAMC,UAAU,IAAI,CAACvB,MAAM,CAACqB,SAAS,CAACG,cAAc;AACpD,YAAA,IAAI,CAACV,aAAa,CAAC,MAAA,EAAQM,EAAIG,EAAAA,OAAAA,CAAAA;AAC/B,YAAA,IAAI,CAAChD,OAAO,CAACkD,MAAM,CAACL,EAAAA,GAAK,OAAOG,OAAU,GAAA,KAAA,CAAA;YAC1C,IAAI,CAAChD,OAAO,CAACmD,MAAM,EAAA;AACrB;AACF;AACA;;;;AAIC,MACDC,GAAM,GAAA;AACJ,QAAA,IAAI,CAAC3B,MAAM,CAAC4B,OAAO,CAAC,IAAA;AAClB,YAAA,IAAI,CAACb,KAAK,EAAA;AACZ,SAAA,CAAA;AACF;AACA;;;;AAIC,MACDc,IAAO,GAAA;QACL,IAAI,CAAC7B,MAAM,CAAC8B,QAAQ,EAAA;AACtB;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"app.js","sources":["../../src/app/app.ts"],"sourcesContent":["import type { Nullable, RequireOptionals, VFS } from '@zephyr3d/base';\r\nimport { Observable, flushPendingDisposals } from '@zephyr3d/base';\r\nimport type { AbstractDevice, DeviceBackend } from '@zephyr3d/device';\r\nimport { InputManager } from './inputmgr';\r\nimport { Engine } from './engine';\r\nimport { getApp, setApp } from './api';\r\nimport type { ScreenConfig } from './screen';\r\n\r\ntype appEventMap = {\r\n /**\r\n * Emitted when the drawing surface (canvas/device) is resized.\r\n *\r\n * @param width - New drawable width in device pixels.\r\n * @param height - New drawable height in device pixels.\r\n */\r\n resize: [width: number, height: number];\r\n /**\r\n * Emitted every frame with timing information.\r\n *\r\n * @param deltaTimeMs - Elapsed time since last frame in milliseconds.\r\n * @param elapsedTimeMs - Elapsed time since app start in milliseconds.\r\n */\r\n tick: [deltaTimeMs: number, elapsedTimeMs: number];\r\n /** Pointer/mouse and keyboard input events forwarded by the Application. */\r\n click: [evt: PointerEvent];\r\n dblclick: [evt: PointerEvent];\r\n pointerdown: [evt: PointerEvent];\r\n pointerup: [evt: PointerEvent];\r\n pointermove: [evt: PointerEvent];\r\n pointercancel: [evt: PointerEvent];\r\n pointerenter: [evt: PointerEvent];\r\n pointerleave: [evt: PointerEvent];\r\n pointerover: [evt: PointerEvent];\r\n pointerout: [evt: PointerEvent];\r\n wheel: [evt: WheelEvent];\r\n keydown: [evt: KeyboardEvent];\r\n keyup: [evt: KeyboardEvent];\r\n keypress: [evt: KeyboardEvent];\r\n drag: [evt: DragEvent];\r\n dragenter: [evt: DragEvent];\r\n dragleave: [evt: DragEvent];\r\n dragover: [evt: DragEvent];\r\n dragstart: [evt: DragEvent];\r\n dragend: [evt: DragEvent];\r\n drop: [evt: DragEvent];\r\n};\r\n\r\n/**\r\n * Application editor/runtime mode.\r\n *\r\n * @public\r\n */\r\nexport type EditorMode = 'editor' | 'editor-preview' | 'none';\r\n\r\n/**\r\n * Options for Application.\r\n *\r\n * @public\r\n */\r\nexport interface AppOptions {\r\n /**\r\n * Target canvas element to attach the rendering device to.\r\n */\r\n canvas: HTMLCanvasElement;\r\n /**\r\n * Device backend implementation to use for GPU creation (e.g., WebGL/WebGPU backend).\r\n */\r\n backend: DeviceBackend;\r\n /**\r\n * Whether to enable multi-sample anti-aliasing (MSAA) if supported by the backend.\r\n * Defaults to false.\r\n */\r\n enableMSAA?: boolean;\r\n /**\r\n * Device pixel ratio used when creating the device. Defaults to `window.devicePixelRatio` or `1`.\r\n */\r\n pixelRatio?: number;\r\n}\r\n\r\n/**\r\n * Creation options for Application.\r\n *\r\n * Provides the canvas, device backend, and optional runtime and device configuration.\r\n * @public\r\n */\r\nexport interface AppCreationOptions extends AppOptions {\r\n /**\r\n * Options for the runtime scripting system.\r\n */\r\n runtimeOptions?: {\r\n /**\r\n * Virtual file system used to load scripts. Defaults to HttpFS at '.' if not provided.\r\n */\r\n VFS?: VFS;\r\n /**\r\n * Root directory for script files. Defaults to '/'.\r\n */\r\n scriptsRoot?: string;\r\n /**\r\n * Whether the application is running in editor mode. Should be true for user applications.\r\n */\r\n editorMode?: EditorMode;\r\n /**\r\n * Whether the runtime scripting system is enabled. Should be true for user applications.\r\n */\r\n enabled?: boolean;\r\n /**\r\n * Screen configuration\r\n */\r\n screen?: ScreenConfig;\r\n };\r\n}\r\n\r\n/**\r\n * Log severity levels.\r\n * @public\r\n */\r\nexport type LogMode = 'info' | 'warn' | 'error' | 'debug';\r\n\r\n/**\r\n * Application\r\n *\r\n * Entry-point and lifecycle coordinator for the engine. Responsible for:\r\n * - Creating and owning the rendering device from a chosen backend.\r\n * - Managing the per-frame loop, including timing and viewport setup.\r\n * - Forwarding device/DOM input events via an observable event map.\r\n * - Hosting the runtime scripting system and input manager.\r\n *\r\n * Singleton:\r\n * - Only one instance may exist at a time. Access via `{@link getApp}`.\r\n *\r\n * Events:\r\n * - See `appEventMap` for all emitted events (resize, tick, pointer/keyboard/drag).\r\n *\r\n * Usage:\r\n * - Construct with `AppOptions`, await `ready()`, then call `run()` to start the loop.\r\n *\r\n * @public\r\n */\r\nexport class Application extends Observable<appEventMap> {\r\n private readonly _options: RequireOptionals<AppOptions>;\r\n private _device: Nullable<AbstractDevice>;\r\n private readonly _inputManager: InputManager;\r\n private readonly _engine: Engine;\r\n private readonly _editorMode: EditorMode;\r\n private _ready: boolean;\r\n /**\r\n * Construct the Application singleton with the provided options.\r\n *\r\n * Throws if an instance already exists.\r\n *\r\n * @param opt - Application creation options (canvas, backend, and optional runtime/device settings).\r\n */\r\n constructor(opt: AppCreationOptions) {\r\n super();\r\n if (getApp()) {\r\n throw new Error('It is not allowed to have multiple Application instances');\r\n }\r\n setApp(this);\r\n\r\n this._options = {\r\n backend: opt.backend,\r\n enableMSAA: opt.enableMSAA ?? false,\r\n pixelRatio: opt.pixelRatio ?? window.devicePixelRatio ?? 1,\r\n canvas: opt.canvas\r\n };\r\n this._inputManager = new InputManager(this);\r\n this._engine = new Engine(\r\n opt.runtimeOptions?.VFS,\r\n opt.runtimeOptions?.scriptsRoot,\r\n opt.runtimeOptions?.enabled\r\n );\r\n if (opt.runtimeOptions?.screen) {\r\n this._engine.screen.config = opt.runtimeOptions.screen;\r\n }\r\n this._editorMode = opt.runtimeOptions?.editorMode ?? 'none';\r\n this._device = null;\r\n this._ready = false;\r\n }\r\n /**\r\n * Editor mode\r\n */\r\n get editorMode() {\r\n return this._editorMode;\r\n }\r\n /**\r\n * The input manager instance handling pointer/keyboard event routing.\r\n */\r\n get inputManager() {\r\n return this._inputManager;\r\n }\r\n /**\r\n * Get the instanceof {@link Engine}.\r\n */\r\n get engine() {\r\n return this._engine;\r\n }\r\n /**\r\n * The (sanitized) options used to create this application.\r\n *\r\n * Note: Defaults are applied for `enableMSAA` and `pixelRatio` if omitted.\r\n */\r\n get options() {\r\n return this._options;\r\n }\r\n /**\r\n * The initialized rendering device.\r\n *\r\n * Available after `await ready()`.\r\n */\r\n get device() {\r\n return this._device!;\r\n }\r\n /**\r\n * Convenience accessor for the device type name provided by the backend.\r\n */\r\n get deviceType() {\r\n return this._options.backend.typeName();\r\n }\r\n /**\r\n * Set keyboard focus to the device's canvas element.\r\n */\r\n focus() {\r\n this._device!.canvas.focus();\r\n }\r\n /**\r\n * Initialize the rendering device and start input processing.\r\n *\r\n * @throws If device creation fails.\r\n */\r\n async ready() {\r\n if (!this._ready) {\r\n this._device = await this._options.backend.createDevice(this._options.canvas, {\r\n dpr: this._options.pixelRatio,\r\n msaa: !!this._options.enableMSAA\r\n });\r\n if (!this._device) {\r\n throw new Error('App.init(): create device failed');\r\n }\r\n this._device.canvas.focus();\r\n await this._engine.init();\r\n this._inputManager.start();\r\n this._device.on('resize', (width, height) => {\r\n this._engine.screen.resolveViewport();\r\n this.dispatchEvent('resize', width, height);\r\n });\r\n this._ready = true;\r\n }\r\n }\r\n /**\r\n * Render a single frame.\r\n *\r\n * Steps:\r\n * - Flushes pending disposals from the previous frame.\r\n * - Clears device state (framebuffer, viewport, scissor).\r\n * - Queries frame timing from the device (`elapsedFrame`, `elapsedOverall`).\r\n * - Updates the runtime manager (scripting/behaviors).\r\n * - Emits `tick` with delta/elapsed times.\r\n *\r\n * Safe to call manually; also used by the run loop.\r\n */\r\n frame() {\r\n // Processes all pending disposals from the previous frame.\r\n flushPendingDisposals();\r\n if (this._ready) {\r\n this.device.setFramebuffer(null);\r\n this.device.setViewport(null);\r\n this.device.setScissor(null);\r\n const dt = this.device.frameInfo.elapsedFrame;\r\n const elapsed = this.device.frameInfo.elapsedOverall;\r\n this.dispatchEvent('tick', dt, elapsed);\r\n this._engine.update(dt * 0.001, elapsed * 0.001);\r\n this._engine.render();\r\n }\r\n }\r\n /**\r\n * Start the application's render loop.\r\n *\r\n * Uses the device's internal scheduling (`device.runLoop`) to repeatedly call `frame()`.\r\n */\r\n run() {\r\n this.device.runLoop(() => {\r\n this.frame();\r\n });\r\n }\r\n /**\r\n * Stop the application's render loop.\r\n *\r\n * Uses `device.exitLoop()` to end the scheduling started by `run()`.\r\n */\r\n stop() {\r\n this.device.exitLoop();\r\n }\r\n}\r\n"],"names":["Application","Observable","_options","_device","_inputManager","_engine","_editorMode","_ready","opt","getApp","Error","setApp","backend","enableMSAA","pixelRatio","window","devicePixelRatio","canvas","InputManager","Engine","runtimeOptions","VFS","scriptsRoot","enabled","screen","config","editorMode","inputManager","engine","options","device","deviceType","typeName","focus","ready","createDevice","dpr","msaa","init","start","on","width","height","resolveViewport","dispatchEvent","frame","flushPendingDisposals","setFramebuffer","setViewport","setScissor","dt","frameInfo","elapsedFrame","elapsed","elapsedOverall","update","render","run","runLoop","stop","exitLoop"],"mappings":";;;;;AAuHA;;;;;;;;;;;;;;;;;;;IAoBO,MAAMA,WAAoBC,SAAAA,UAAAA,CAAAA;IACdC,QAAuC;IAChDC,OAAkC;IACzBC,aAA4B;IAC5BC,OAAgB;IAChBC,WAAwB;IACjCC,MAAgB;AACxB;;;;;;MAOA,WAAA,CAAYC,GAAuB,CAAE;QACnC,KAAK,EAAA;AACL,QAAA,IAAIC,MAAU,EAAA,EAAA;AACZ,YAAA,MAAM,IAAIC,KAAM,CAAA,0DAAA,CAAA;AAClB;AACAC,QAAAA,MAAAA,CAAO,IAAI,CAAA;QAEX,IAAI,CAACT,QAAQ,GAAG;AACdU,YAAAA,OAAAA,EAASJ,IAAII,OAAO;YACpBC,UAAYL,EAAAA,GAAAA,CAAIK,UAAU,IAAI,KAAA;AAC9BC,YAAAA,UAAAA,EAAYN,GAAIM,CAAAA,UAAU,IAAIC,MAAAA,CAAOC,gBAAgB,IAAI,CAAA;AACzDC,YAAAA,MAAAA,EAAQT,IAAIS;AACd,SAAA;AACA,QAAA,IAAI,CAACb,aAAa,GAAG,IAAIc,aAAa,IAAI,CAAA;AAC1C,QAAA,IAAI,CAACb,OAAO,GAAG,IAAIc,OACjBX,GAAIY,CAAAA,cAAc,EAAEC,GAAAA,EACpBb,IAAIY,cAAc,EAAEE,WACpBd,EAAAA,GAAAA,CAAIY,cAAc,EAAEG,OAAAA,CAAAA;QAEtB,IAAIf,GAAAA,CAAIY,cAAc,EAAEI,MAAQ,EAAA;YAC9B,IAAI,CAACnB,OAAO,CAACmB,MAAM,CAACC,MAAM,GAAGjB,GAAAA,CAAIY,cAAc,CAACI,MAAM;AACxD;AACA,QAAA,IAAI,CAAClB,WAAW,GAAGE,GAAIY,CAAAA,cAAc,EAA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A;;;;AAIC,MACDc,IAAO,GAAA;QACL,IAAI,CAAC7B,MAAM,CAAC8B,QAAQ,EAAA;AACtB;AACF;;;;"}
|
package/dist/app/engine.js
CHANGED
package/dist/app/engine.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine.js","sources":["../../src/app/engine.ts"],"sourcesContent":["import type { GenericConstructor, IDisposable, Nullable, ReadOptions } from '@zephyr3d/base';\r\nimport { MemoryFS, objectEntries } from '@zephyr3d/base';\r\nimport { DRef } from '@zephyr3d/base';\r\nimport { HttpFS, type VFS } from '@zephyr3d/base';\r\nimport { ScriptingSystem } from './scriptingsystem';\r\nimport type { Host } from './scriptingsystem';\r\nimport type { RuntimeScript, RuntimeScriptConfig } from './runtimescript';\r\nimport { ResourceManager } from '../utility/serialization/manager';\r\nimport type { Scene } from '../scene';\r\nimport {\r\n BoxShape,\r\n CapsuleShape,\r\n CylinderShape,\r\n PlaneShape,\r\n SphereShape,\r\n TetrahedronShape,\r\n TorusShape\r\n} from '../shapes';\r\nimport {\r\n BlinnMaterial,\r\n LambertMaterial,\r\n PBRMetallicRoughnessMaterial,\r\n PBRSpecularGlossinessMaterial,\r\n UnlitMaterial\r\n} from '../material';\r\nimport { StandardSpriteMaterial } from '../material/sprite_std';\r\nimport { ScreenAdapter } from './screen';\r\n\r\n/**\r\n * Interface for objects that can be rendered.\r\n *\r\n * @public\r\n */\r\nexport interface IRenderable extends IDisposable {\r\n render(): void;\r\n}\r\n\r\n/**\r\n * Interface for render hooks to customize rendering behavior.\r\n *\r\n * @public\r\n */\r\nexport interface IRenderHook {\r\n // If presents, called before rendering the renderable. Return `false` to skip rendering.\r\n beforeRender?: (renderable: any) => boolean | void;\r\n // If presents, called after rendering the renderable.\r\n afterRender?: (renderable: any) => void;\r\n}\r\n\r\n/**\r\n * Core engine class managing scripting, serialization, and rendering.\r\n *\r\n * Responsibilities:\r\n * - Manages a {@link ScriptingSystem} for dynamic script attachment and lifecycle.\r\n * - Manages a {@link ResourceManager} for loading scenes and assets.\r\n * - Maintains a list of active renderable objects to be rendered each frame.\r\n * - Provides methods to attach/detach scripts, update scripts, load scenes, and read files.\r\n * - Supports enabling/disabling of runtime operations.\r\n *\r\n * @remarks\r\n * The engine can be configured with a virtual file system (VFS) and script root path.\r\n * It exposes methods to manage scripts on host objects, update scripts each frame,\r\n * load scenes from files, and render active objects.\r\n *\r\n * @public\r\n */\r\nexport class Engine {\r\n private _builtinsVFS: Nullable<MemoryFS>;\r\n private _scriptingSystem: ScriptingSystem;\r\n private _resourceManager: ResourceManager;\r\n private _enabled: boolean;\r\n private _screen: ScreenAdapter;\r\n protected _activeRenderables: {\r\n renderable: DRef<IRenderable>;\r\n hook: Nullable<IRenderHook>;\r\n }[];\r\n private _loadingScenes: Partial<Record<string, Promise<Nullable<Scene>>>>;\r\n /**\r\n * Creates a new runtime manager.\r\n *\r\n * @param VFS - Optional virtual file system passed to the internal {@link ScriptingSystem}.\r\n * @param scriptsRoot - Optional scripts root path within the VFS. Defaults as in `ScriptingSystem`.\r\n * @param enabled - Whether runtime operations are active. Defaults to `true`.\r\n */\r\n constructor(VFS?: VFS, scriptsRoot?: string, enabled?: boolean) {\r\n VFS = VFS ?? new HttpFS('./');\r\n this._builtinsVFS = null;\r\n this._scriptingSystem = new ScriptingSystem({ VFS, scriptsRoot });\r\n this._resourceManager = new ResourceManager(VFS);\r\n this._enabled = enabled ?? true;\r\n this._activeRenderables = [];\r\n this._loadingScenes = {};\r\n this._screen = new ScreenAdapter();\r\n }\r\n /**\r\n * Exposes the instance of {@link ScriptingSystem}.\r\n */\r\n get scriptingSystem() {\r\n return this._scriptingSystem;\r\n }\r\n /**\r\n * Exposes the virtual file system used by the underlying {@link ScriptingSystem}'s registry.\r\n */\r\n get VFS() {\r\n return this._scriptingSystem.registry.VFS;\r\n }\r\n set VFS(vfs: VFS) {\r\n if (vfs !== this._resourceManager.VFS) {\r\n this._resourceManager.VFS?.close();\r\n this._resourceManager.VFS = vfs;\r\n this._scriptingSystem.registry.VFS = vfs;\r\n this.ensureBuiltinVFS();\r\n }\r\n }\r\n /**\r\n * Exposes the instance of {@link ResourceManager}.\r\n */\r\n get resourceManager() {\r\n return this._resourceManager;\r\n }\r\n /**\r\n * Exposes the instanceof {@link Screen}\r\n */\r\n get screen() {\r\n return this._screen;\r\n }\r\n /** @internal */\r\n async init() {\r\n await this.ensureBuiltinVFS();\r\n }\r\n /**\r\n * Detaches all scripts from all hosts, if enabled.\r\n *\r\n * No-op when `enabled === false`.\r\n */\r\n detachAllScripts() {\r\n if (this._enabled) {\r\n this._scriptingSystem.detachAllScripts();\r\n }\r\n }\r\n /**\r\n * Loads a runtime script class from file\r\n * @param module - file path\r\n * @returns The runtime script class or null\r\n */\r\n async loadRuntimeScriptClass<T extends Host = Host>(\r\n module: string\r\n ): Promise<Nullable<{ url: string; cls: GenericConstructor<RuntimeScript<T>> }>> {\r\n return await this._scriptingSystem.loadRuntimeScriptClass(module);\r\n }\r\n /**\r\n * Attaches a script module to the given host, if enabled.\r\n *\r\n * When disabled, this method resolves to `null` without side effects.\r\n *\r\n * @typeParam T - Host type.\r\n * @param host - Host object to attach the script to.\r\n * @param module - Module identifier to resolve and load.\r\n * @returns The `RuntimeScript<T>` instance, or `null` if disabled or on failure.\r\n */\r\n async attachScript<T extends Host>(\r\n host: Nullable<T>,\r\n module: string,\r\n config?: Nullable<RuntimeScriptConfig>\r\n ) {\r\n return this._enabled ? await this._scriptingSystem.attachScript(host, module, config) : null;\r\n }\r\n /**\r\n * Detaches a script from a host, by module ID or instance, if enabled.\r\n *\r\n * No-op when disabled.\r\n *\r\n * @typeParam T - Host type.\r\n * @param host - Host to detach from.\r\n * @param idOrInstance - Target script by module ID or instance reference.\r\n */\r\n detachScript<T extends Host>(host: T, idOrInstance: string | RuntimeScript<T>) {\r\n if (this._enabled) {\r\n this._scriptingSystem.detachScript(host, idOrInstance);\r\n }\r\n }\r\n /**\r\n * Gets all scripts attached to a host.\r\n *\r\n * Delegates to {@link ScriptingSystem.getScriptObjects}.\r\n *\r\n * @typeParam T - Expected script type.\r\n * @param host - Host object to query.\r\n * @returns Script instances attached to the host, or an empty array.\r\n */\r\n getScriptObjects<T extends RuntimeScript<any>>(host: unknown) {\r\n return this._scriptingSystem.getScriptObjects(host) as T[];\r\n }\r\n /**\r\n * Ticks all attached scripts by calling their `onUpdate` hooks, if enabled.\r\n *\r\n * Delegates to {@link ScriptingSystem.update}. No-op when disabled.\r\n *\r\n * @param deltaTime - Time since last update in Seconds.\r\n * @param elapsedTime - Total elapsed time in Seconds.\r\n */\r\n update(deltaTime: number, elapsedTime: number) {\r\n if (this._enabled) {\r\n this._scriptingSystem.update(deltaTime, elapsedTime);\r\n }\r\n }\r\n async loadSceneFromFile(path: string) {\r\n path = this.VFS.normalizePath(path);\r\n if (!this._loadingScenes[path]) {\r\n this._loadingScenes[path] = this._loadScene(path);\r\n }\r\n return this._loadingScenes[path]!;\r\n }\r\n setRenderable(renderable: Nullable<IRenderable>, layer = 0, hook?: IRenderHook) {\r\n if (!this._activeRenderables[layer]) {\r\n this._activeRenderables[layer] = {\r\n renderable: new DRef<IRenderable>(null),\r\n hook: null\r\n };\r\n }\r\n this._activeRenderables[layer].hook = hook ?? null;\r\n this._activeRenderables[layer].renderable.set(renderable);\r\n }\r\n async readFile<T extends ReadOptions['encoding'] = 'binary'>(path: string, encoding?: T) {\r\n try {\r\n const content = await this.VFS.readFile(path, { encoding: encoding ?? 'binary' });\r\n return content as T extends 'binary' ? ArrayBuffer : string;\r\n } catch (err) {\r\n console.error(`Read file '${path}' failed: ${err}`);\r\n return null;\r\n }\r\n }\r\n async startup(\r\n startupScene?: Nullable<string>,\r\n splashScreen?: Nullable<string>,\r\n startupScript?: Nullable<string>\r\n ) {\r\n const splashScreenLayer = 9999;\r\n if (splashScreen) {\r\n const splashScreenScene = await this.loadSceneFromFile(splashScreen);\r\n if (splashScreenScene) {\r\n this.setRenderable(splashScreenScene, splashScreenLayer);\r\n }\r\n }\r\n if (startupScript) {\r\n const path =\r\n startupScript.toLowerCase().endsWith('.ts') || startupScript.toLowerCase().endsWith('.js')\r\n ? startupScript.slice(0, -3)\r\n : startupScript;\r\n await this.attachScript(null, path);\r\n }\r\n if (startupScene) {\r\n const scene = await this.loadSceneFromFile(startupScene);\r\n this.setRenderable(scene, 0);\r\n }\r\n this.setRenderable(null, splashScreenLayer);\r\n }\r\n render() {\r\n this._activeRenderables.forEach((info) => {\r\n const render = info.hook?.beforeRender\r\n ? (info.hook.beforeRender(info.renderable.get() ?? null) ?? true)\r\n : true;\r\n if (render) {\r\n info.renderable.get()?.render();\r\n }\r\n if (info.hook?.afterRender) {\r\n info.hook.afterRender(info.renderable.get() ?? null);\r\n }\r\n });\r\n }\r\n private async ensureBuiltinVFS() {\r\n if (!this._builtinsVFS) {\r\n this._builtinsVFS = await this.createBuiltinVFS();\r\n }\r\n this.VFS.unmount('/assets/@builtins');\r\n this.VFS.mount('/assets/@builtins', this._builtinsVFS);\r\n }\r\n private async createBuiltinVFS() {\r\n const fs = new MemoryFS();\r\n const shapeClsMap = {\r\n '/primitives/box.zmsh': BoxShape,\r\n '/primitives/sphere.zmsh': SphereShape,\r\n '/primitives/cylinder.zmsh': CylinderShape,\r\n '/primitives/plane.zmsh': PlaneShape,\r\n '/primitives/torus.zmsh': TorusShape,\r\n '/primitives/tetrahedron.zmsh': TetrahedronShape,\r\n '/primitives/capsule.zmsh': CapsuleShape,\r\n '/materials/unlit.zmtl': UnlitMaterial,\r\n '/materials/lambert.zmtl': LambertMaterial,\r\n '/materials/blinnphong.zmtl': BlinnMaterial,\r\n '/materials/pbr_metallic_roughness.zmtl': PBRMetallicRoughnessMaterial,\r\n '/materials/pbr_specular_glossiness.zmtl': PBRSpecularGlossinessMaterial,\r\n '/materials/sprite_std.zmtl': StandardSpriteMaterial\r\n } as const;\r\n for (const [key] of objectEntries(shapeClsMap)) {\r\n const obj = new shapeClsMap[key]();\r\n await this.writeSerializableObject(fs, 'Default', obj, key);\r\n obj.dispose();\r\n }\r\n fs.readOnly = true;\r\n return fs;\r\n }\r\n private async writeSerializableObject(VFS: VFS, type: string, obj: any, path: string) {\r\n try {\r\n const data = await this.resourceManager.serializeObject(obj);\r\n const content = JSON.stringify({ type, data }, null, 2);\r\n await VFS.writeFile(path, content, { encoding: 'utf8', create: true });\r\n } catch (err) {\r\n console.error(`Write file '${path}' failed: ${err}`);\r\n }\r\n }\r\n private async _loadScene(path: string) {\r\n try {\r\n const scene = await this._resourceManager.loadScene(path);\r\n if (scene) {\r\n const sceneScripts =\r\n scene.scripts.length > 0\r\n ? scene.scripts\r\n : scene.script\r\n ? [{ script: scene.script, config: scene.scriptConfig }]\r\n : [];\r\n for (const attachment of sceneScripts) {\r\n if (!attachment.script) {\r\n continue;\r\n }\r\n try {\r\n await this.attachScript(\r\n scene,\r\n attachment.script,\r\n (attachment.config ?? null) as RuntimeScriptConfig | null\r\n );\r\n } catch (err) {\r\n console.error(`Attach script failed: ${err}`);\r\n }\r\n }\r\n const nodes: (typeof scene.rootNode)[] = [];\r\n scene.rootNode.iterate((node) => {\r\n nodes.push(node);\r\n });\r\n const attachTasks = nodes.map(async (node) => {\r\n const attachments =\r\n node.scripts.length > 0\r\n ? node.scripts\r\n : node.script\r\n ? [{ script: node.script, config: node.scriptConfig }]\r\n : [];\r\n for (const attachment of attachments) {\r\n if (!attachment.script) {\r\n continue;\r\n }\r\n try {\r\n await this.attachScript(\r\n node,\r\n attachment.script,\r\n (attachment.config ?? null) as RuntimeScriptConfig | null\r\n );\r\n } catch (err) {\r\n console.error(`Attach script failed: ${err}`);\r\n }\r\n }\r\n });\r\n if (attachTasks.length > 0) {\r\n await Promise.allSettled(attachTasks);\r\n }\r\n }\r\n return scene;\r\n } catch (err) {\r\n console.error(`Load scene from '${path}' failed: ${err}`);\r\n return null;\r\n }\r\n }\r\n}\r\n"],"names":["Engine","_builtinsVFS","_scriptingSystem","_resourceManager","_enabled","_screen","_activeRenderables","_loadingScenes","VFS","scriptsRoot","enabled","HttpFS","ScriptingSystem","ResourceManager","ScreenAdapter","scriptingSystem","registry","vfs","close","ensureBuiltinVFS","resourceManager","screen","init","detachAllScripts","loadRuntimeScriptClass","module","attachScript","host","config","detachScript","idOrInstance","getScriptObjects","update","deltaTime","elapsedTime","loadSceneFromFile","path","normalizePath","_loadScene","setRenderable","renderable","layer","hook","DRef","set","readFile","encoding","content","err","console","error","startup","startupScene","splashScreen","startupScript","splashScreenLayer","splashScreenScene","toLowerCase","endsWith","slice","scene","render","forEach","info","beforeRender","get","afterRender","createBuiltinVFS","unmount","mount","fs","MemoryFS","shapeClsMap","BoxShape","SphereShape","CylinderShape","PlaneShape","TorusShape","TetrahedronShape","CapsuleShape","UnlitMaterial","LambertMaterial","BlinnMaterial","PBRMetallicRoughnessMaterial","PBRSpecularGlossinessMaterial","StandardSpriteMaterial","key","objectEntries","obj","writeSerializableObject","dispose","readOnly","type","data","serializeObject","JSON","stringify","writeFile","create","loadScene","sceneScripts","scripts","length","script","scriptConfig","attachment","nodes","rootNode","iterate","node","push","attachTasks","map","attachments","Promise","allSettled"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA;;;;;;;;;;;;;;;;AAgBC,IACM,MAAMA,MAAAA,CAAAA;IACHC,YAAiC;IACjCC,gBAAkC;IAClCC,gBAAkC;IAClCC,QAAkB;IAClBC,OAAuB;IACrBC,kBAGN;IACIC,cAAkE;AAC1E;;;;;;AAMC,MACD,YAAYC,GAAS,EAAEC,WAAoB,EAAEC,OAAiB,CAAE;QAC9DF,GAAMA,GAAAA,GAAAA,IAAO,IAAIG,MAAO,CAAA,IAAA,CAAA;QACxB,IAAI,CAACV,YAAY,GAAG,IAAA;AACpB,QAAA,IAAI,CAACC,gBAAgB,GAAG,IAAIU,eAAgB,CAAA;AAAEJ,YAAAA,GAAAA;AAAKC,YAAAA;AAAY,SAAA,CAAA;AAC/D,QAAA,IAAI,CAACN,gBAAgB,GAAG,IAAIU,eAAgBL,CAAAA,GA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["../../src/app/engine.ts"],"sourcesContent":["import type { GenericConstructor, IDisposable, Nullable, ReadOptions } from '@zephyr3d/base';\r\nimport { MemoryFS, objectEntries } from '@zephyr3d/base';\r\nimport { DRef } from '@zephyr3d/base';\r\nimport { HttpFS, type VFS } from '@zephyr3d/base';\r\nimport { ScriptingSystem } from './scriptingsystem';\r\nimport type { Host } from './scriptingsystem';\r\nimport type { RuntimeScript, RuntimeScriptConfig } from './runtimescript';\r\nimport { ResourceManager } from '../utility/serialization/manager';\r\nimport type { Scene } from '../scene';\r\nimport {\r\n BoxShape,\r\n CapsuleShape,\r\n CylinderShape,\r\n PlaneShape,\r\n SphereShape,\r\n TetrahedronShape,\r\n TorusShape\r\n} from '../shapes';\r\nimport {\r\n BlinnMaterial,\r\n LambertMaterial,\r\n PBRMetallicRoughnessMaterial,\r\n PBRSpecularGlossinessMaterial,\r\n UnlitMaterial\r\n} from '../material';\r\nimport { StandardSpriteMaterial } from '../material/sprite_std';\r\nimport { ScreenAdapter } from './screen';\r\n\r\n/**\r\n * Interface for objects that can be rendered.\r\n *\r\n * @public\r\n */\r\nexport interface IRenderable extends IDisposable {\r\n render(): void;\r\n}\r\n\r\n/**\r\n * Interface for render hooks to customize rendering behavior.\r\n *\r\n * @public\r\n */\r\nexport interface IRenderHook {\r\n // If presents, called before rendering the renderable. Return `false` to skip rendering.\r\n beforeRender?: (renderable: any) => boolean | void;\r\n // If presents, called after rendering the renderable.\r\n afterRender?: (renderable: any) => void;\r\n}\r\n\r\n/**\r\n * Core engine class managing scripting, serialization, and rendering.\r\n *\r\n * Responsibilities:\r\n * - Manages a {@link ScriptingSystem} for dynamic script attachment and lifecycle.\r\n * - Manages a {@link ResourceManager} for loading scenes and assets.\r\n * - Maintains a list of active renderable objects to be rendered each frame.\r\n * - Provides methods to attach/detach scripts, update scripts, load scenes, and read files.\r\n * - Supports enabling/disabling of runtime operations.\r\n *\r\n * @remarks\r\n * The engine can be configured with a virtual file system (VFS) and script root path.\r\n * It exposes methods to manage scripts on host objects, update scripts each frame,\r\n * load scenes from files, and render active objects.\r\n *\r\n * @public\r\n */\r\nexport class Engine {\r\n private _builtinsVFS: Nullable<MemoryFS>;\r\n private _scriptingSystem: ScriptingSystem;\r\n private _resourceManager: ResourceManager;\r\n private _enabled: boolean;\r\n private _screen: ScreenAdapter;\r\n protected _activeRenderables: {\r\n renderable: DRef<IRenderable>;\r\n hook: Nullable<IRenderHook>;\r\n }[];\r\n private _loadingScenes: Partial<Record<string, Promise<Nullable<Scene>>>>;\r\n /**\r\n * Creates a new runtime manager.\r\n *\r\n * @param VFS - Optional virtual file system passed to the internal {@link ScriptingSystem}.\r\n * @param scriptsRoot - Optional scripts root path within the VFS. Defaults as in `ScriptingSystem`.\r\n * @param enabled - Whether runtime operations are active. Defaults to `true`.\r\n */\r\n constructor(VFS?: VFS, scriptsRoot?: string, enabled?: boolean) {\r\n VFS = VFS ?? new HttpFS('./');\r\n this._builtinsVFS = null;\r\n this._scriptingSystem = new ScriptingSystem({ VFS, scriptsRoot });\r\n this._resourceManager = new ResourceManager(VFS);\r\n this._enabled = enabled ?? true;\r\n this._activeRenderables = [];\r\n this._loadingScenes = {};\r\n this._screen = new ScreenAdapter();\r\n }\r\n /**\r\n * Exposes the instance of {@link ScriptingSystem}.\r\n */\r\n get scriptingSystem() {\r\n return this._scriptingSystem;\r\n }\r\n /**\r\n * Exposes the virtual file system used by the underlying {@link ScriptingSystem}'s registry.\r\n */\r\n get VFS() {\r\n return this._scriptingSystem.registry.VFS;\r\n }\r\n set VFS(vfs: VFS) {\r\n if (vfs !== this._resourceManager.VFS) {\r\n this._resourceManager.VFS?.close();\r\n this._resourceManager.VFS = vfs;\r\n this._scriptingSystem.registry.VFS = vfs;\r\n this.ensureBuiltinVFS();\r\n }\r\n }\r\n /**\r\n * Exposes the instance of {@link ResourceManager}.\r\n */\r\n get resourceManager() {\r\n return this._resourceManager;\r\n }\r\n /**\r\n * Exposes the active {@link ScreenAdapter}.\r\n */\r\n get screen() {\r\n return this._screen;\r\n }\r\n /** @internal */\r\n async init() {\r\n await this.ensureBuiltinVFS();\r\n }\r\n /**\r\n * Detaches all scripts from all hosts, if enabled.\r\n *\r\n * No-op when `enabled === false`.\r\n */\r\n detachAllScripts() {\r\n if (this._enabled) {\r\n this._scriptingSystem.detachAllScripts();\r\n }\r\n }\r\n /**\r\n * Loads a runtime script class from file\r\n * @param module - file path\r\n * @returns The runtime script class or null\r\n */\r\n async loadRuntimeScriptClass<T extends Host = Host>(\r\n module: string\r\n ): Promise<Nullable<{ url: string; cls: GenericConstructor<RuntimeScript<T>> }>> {\r\n return await this._scriptingSystem.loadRuntimeScriptClass(module);\r\n }\r\n /**\r\n * Attaches a script module to the given host, if enabled.\r\n *\r\n * When disabled, this method resolves to `null` without side effects.\r\n *\r\n * @typeParam T - Host type.\r\n * @param host - Host object to attach the script to.\r\n * @param module - Module identifier to resolve and load.\r\n * @returns The `RuntimeScript<T>` instance, or `null` if disabled or on failure.\r\n */\r\n async attachScript<T extends Host>(\r\n host: Nullable<T>,\r\n module: string,\r\n config?: Nullable<RuntimeScriptConfig>\r\n ) {\r\n return this._enabled ? await this._scriptingSystem.attachScript(host, module, config) : null;\r\n }\r\n /**\r\n * Detaches a script from a host, by module ID or instance, if enabled.\r\n *\r\n * No-op when disabled.\r\n *\r\n * @typeParam T - Host type.\r\n * @param host - Host to detach from.\r\n * @param idOrInstance - Target script by module ID or instance reference.\r\n */\r\n detachScript<T extends Host>(host: T, idOrInstance: string | RuntimeScript<T>) {\r\n if (this._enabled) {\r\n this._scriptingSystem.detachScript(host, idOrInstance);\r\n }\r\n }\r\n /**\r\n * Gets all scripts attached to a host.\r\n *\r\n * Delegates to {@link ScriptingSystem.getScriptObjects}.\r\n *\r\n * @typeParam T - Expected script type.\r\n * @param host - Host object to query.\r\n * @returns Script instances attached to the host, or an empty array.\r\n */\r\n getScriptObjects<T extends RuntimeScript<any>>(host: unknown) {\r\n return this._scriptingSystem.getScriptObjects(host) as T[];\r\n }\r\n /**\r\n * Ticks all attached scripts by calling their `onUpdate` hooks, if enabled.\r\n *\r\n * Delegates to {@link ScriptingSystem.update}. No-op when disabled.\r\n *\r\n * @param deltaTime - Time since last update in Seconds.\r\n * @param elapsedTime - Total elapsed time in Seconds.\r\n */\r\n update(deltaTime: number, elapsedTime: number) {\r\n if (this._enabled) {\r\n this._scriptingSystem.update(deltaTime, elapsedTime);\r\n }\r\n }\r\n async loadSceneFromFile(path: string) {\r\n path = this.VFS.normalizePath(path);\r\n if (!this._loadingScenes[path]) {\r\n this._loadingScenes[path] = this._loadScene(path);\r\n }\r\n return this._loadingScenes[path]!;\r\n }\r\n setRenderable(renderable: Nullable<IRenderable>, layer = 0, hook?: IRenderHook) {\r\n if (!this._activeRenderables[layer]) {\r\n this._activeRenderables[layer] = {\r\n renderable: new DRef<IRenderable>(null),\r\n hook: null\r\n };\r\n }\r\n this._activeRenderables[layer].hook = hook ?? null;\r\n this._activeRenderables[layer].renderable.set(renderable);\r\n }\r\n async readFile<T extends ReadOptions['encoding'] = 'binary'>(path: string, encoding?: T) {\r\n try {\r\n const content = await this.VFS.readFile(path, { encoding: encoding ?? 'binary' });\r\n return content as T extends 'binary' ? ArrayBuffer : string;\r\n } catch (err) {\r\n console.error(`Read file '${path}' failed: ${err}`);\r\n return null;\r\n }\r\n }\r\n async startup(\r\n startupScene?: Nullable<string>,\r\n splashScreen?: Nullable<string>,\r\n startupScript?: Nullable<string>\r\n ) {\r\n const splashScreenLayer = 9999;\r\n if (splashScreen) {\r\n const splashScreenScene = await this.loadSceneFromFile(splashScreen);\r\n if (splashScreenScene) {\r\n this.setRenderable(splashScreenScene, splashScreenLayer);\r\n }\r\n }\r\n if (startupScript) {\r\n const path =\r\n startupScript.toLowerCase().endsWith('.ts') || startupScript.toLowerCase().endsWith('.js')\r\n ? startupScript.slice(0, -3)\r\n : startupScript;\r\n await this.attachScript(null, path);\r\n }\r\n if (startupScene) {\r\n const scene = await this.loadSceneFromFile(startupScene);\r\n this.setRenderable(scene, 0);\r\n }\r\n this.setRenderable(null, splashScreenLayer);\r\n }\r\n render() {\r\n this._activeRenderables.forEach((info) => {\r\n const render = info.hook?.beforeRender\r\n ? (info.hook.beforeRender(info.renderable.get() ?? null) ?? true)\r\n : true;\r\n if (render) {\r\n info.renderable.get()?.render();\r\n }\r\n if (info.hook?.afterRender) {\r\n info.hook.afterRender(info.renderable.get() ?? null);\r\n }\r\n });\r\n }\r\n private async ensureBuiltinVFS() {\r\n if (!this._builtinsVFS) {\r\n this._builtinsVFS = await this.createBuiltinVFS();\r\n }\r\n this.VFS.unmount('/assets/@builtins');\r\n this.VFS.mount('/assets/@builtins', this._builtinsVFS);\r\n }\r\n private async createBuiltinVFS() {\r\n const fs = new MemoryFS();\r\n const shapeClsMap = {\r\n '/primitives/box.zmsh': BoxShape,\r\n '/primitives/sphere.zmsh': SphereShape,\r\n '/primitives/cylinder.zmsh': CylinderShape,\r\n '/primitives/plane.zmsh': PlaneShape,\r\n '/primitives/torus.zmsh': TorusShape,\r\n '/primitives/tetrahedron.zmsh': TetrahedronShape,\r\n '/primitives/capsule.zmsh': CapsuleShape,\r\n '/materials/unlit.zmtl': UnlitMaterial,\r\n '/materials/lambert.zmtl': LambertMaterial,\r\n '/materials/blinnphong.zmtl': BlinnMaterial,\r\n '/materials/pbr_metallic_roughness.zmtl': PBRMetallicRoughnessMaterial,\r\n '/materials/pbr_specular_glossiness.zmtl': PBRSpecularGlossinessMaterial,\r\n '/materials/sprite_std.zmtl': StandardSpriteMaterial\r\n } as const;\r\n for (const [key] of objectEntries(shapeClsMap)) {\r\n const obj = new shapeClsMap[key]();\r\n await this.writeSerializableObject(fs, 'Default', obj, key);\r\n obj.dispose();\r\n }\r\n fs.readOnly = true;\r\n return fs;\r\n }\r\n private async writeSerializableObject(VFS: VFS, type: string, obj: any, path: string) {\r\n try {\r\n const data = await this.resourceManager.serializeObject(obj);\r\n const content = JSON.stringify({ type, data }, null, 2);\r\n await VFS.writeFile(path, content, { encoding: 'utf8', create: true });\r\n } catch (err) {\r\n console.error(`Write file '${path}' failed: ${err}`);\r\n }\r\n }\r\n private async _loadScene(path: string) {\r\n try {\r\n const scene = await this._resourceManager.loadScene(path);\r\n if (scene) {\r\n const sceneScripts =\r\n scene.scripts.length > 0\r\n ? scene.scripts\r\n : scene.script\r\n ? [{ script: scene.script, config: scene.scriptConfig }]\r\n : [];\r\n for (const attachment of sceneScripts) {\r\n if (!attachment.script) {\r\n continue;\r\n }\r\n try {\r\n await this.attachScript(\r\n scene,\r\n attachment.script,\r\n (attachment.config ?? null) as RuntimeScriptConfig | null\r\n );\r\n } catch (err) {\r\n console.error(`Attach script failed: ${err}`);\r\n }\r\n }\r\n const nodes: (typeof scene.rootNode)[] = [];\r\n scene.rootNode.iterate((node) => {\r\n nodes.push(node);\r\n });\r\n const attachTasks = nodes.map(async (node) => {\r\n const attachments =\r\n node.scripts.length > 0\r\n ? node.scripts\r\n : node.script\r\n ? [{ script: node.script, config: node.scriptConfig }]\r\n : [];\r\n for (const attachment of attachments) {\r\n if (!attachment.script) {\r\n continue;\r\n }\r\n try {\r\n await this.attachScript(\r\n node,\r\n attachment.script,\r\n (attachment.config ?? null) as RuntimeScriptConfig | null\r\n );\r\n } catch (err) {\r\n console.error(`Attach script failed: ${err}`);\r\n }\r\n }\r\n });\r\n if (attachTasks.length > 0) {\r\n await Promise.allSettled(attachTasks);\r\n }\r\n }\r\n return scene;\r\n } catch (err) {\r\n console.error(`Load scene from '${path}' failed: ${err}`);\r\n return null;\r\n }\r\n }\r\n}\r\n"],"names":["Engine","_builtinsVFS","_scriptingSystem","_resourceManager","_enabled","_screen","_activeRenderables","_loadingScenes","VFS","scriptsRoot","enabled","HttpFS","ScriptingSystem","ResourceManager","ScreenAdapter","scriptingSystem","registry","vfs","close","ensureBuiltinVFS","resourceManager","screen","init","detachAllScripts","loadRuntimeScriptClass","module","attachScript","host","config","detachScript","idOrInstance","getScriptObjects","update","deltaTime","elapsedTime","loadSceneFromFile","path","normalizePath","_loadScene","setRenderable","renderable","layer","hook","DRef","set","readFile","encoding","content","err","console","error","startup","startupScene","splashScreen","startupScript","splashScreenLayer","splashScreenScene","toLowerCase","endsWith","slice","scene","render","forEach","info","beforeRender","get","afterRender","createBuiltinVFS","unmount","mount","fs","MemoryFS","shapeClsMap","BoxShape","SphereShape","CylinderShape","PlaneShape","TorusShape","TetrahedronShape","CapsuleShape","UnlitMaterial","LambertMaterial","BlinnMaterial","PBRMetallicRoughnessMaterial","PBRSpecularGlossinessMaterial","StandardSpriteMaterial","key","objectEntries","obj","writeSerializableObject","dispose","readOnly","type","data","serializeObject","JSON","stringify","writeFile","create","loadScene","sceneScripts","scripts","length","script","scriptConfig","attachment","nodes","rootNode","iterate","node","push","attachTasks","map","attachments","Promise","allSettled"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA;;;;;;;;;;;;;;;;AAgBC,IACM,MAAMA,MAAAA,CAAAA;IACHC,YAAiC;IACjCC,gBAAkC;IAClCC,gBAAkC;IAClCC,QAAkB;IAClBC,OAAuB;IACrBC,kBAGN;IACIC,cAAkE;AAC1E;;;;;;AAMC,MACD,YAAYC,GAAS,EAAEC,WAAoB,EAAEC,OAAiB,CAAE;QAC9DF,GAAMA,GAAAA,GAAAA,IAAO,IAAIG,MAAO,CAAA,IAAA,CAAA;QACxB,IAAI,CAACV,YAAY,GAAG,IAAA;AACpB,QAAA,IAAI,CAACC,gBAAgB,GAAG,IAAIU,eAAgB,CAAA;AAAEJ,YAAAA,GAAAA;AAAKC,YAAAA;AAAY,SAAA,CAAA;AAC/D,QAAA,IAAI,CAACN,gBAAgB,GAAG,IAAIU,eAAgBL,CAAAA,GAAAA,CAAAA;QAC5C,IAAI,CAACJ,QAAQ,GAAGM,OAAW,IAAA,IAAA;QAC3B,IAAI,CAACJ,kBAAkB,GAAG,EAAE;QAC5B,IAAI,CAACC,cAAc,GAAG,EAAC;QACvB,IAAI,CAACF,OAAO,GAAG,IAAIS,aAAAA,EAAA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AC,OAAOH,IAAAA,GAAAA;AACnC,oBAAA,MAAMI,WACJJ,GAAAA,IAAAA,CAAKR,OAAO,CAACC,MAAM,GAAG,CAClBO,GAAAA,IAAAA,CAAKR,OAAO,GACZQ,IAAKN,CAAAA,MAAM,GACT;AAAC,wBAAA;AAAEA,4BAAAA,MAAAA,EAAQM,KAAKN,MAAM;AAAE3E,4BAAAA,MAAAA,EAAQiF,KAAKL;AAAa;AAAE,qBAAA,GACpD,EAAE;oBACV,KAAK,MAAMC,cAAcQ,WAAa,CAAA;wBACpC,IAAI,CAACR,UAAWF,CAAAA,MAAM,EAAE;AACtB,4BAAA;AACF;wBACA,IAAI;4BACF,MAAM,IAAI,CAAC7E,YAAY,CACrBmF,IAAAA,EACAJ,WAAWF,MAAM,EAChBE,UAAW7E,CAAAA,MAAM,IAAI,IAAA,CAAA;AAE1B,yBAAA,CAAE,OAAOoB,GAAK,EAAA;AACZC,4BAAAA,OAAAA,CAAQC,KAAK,CAAC,CAAC,sBAAsB,EAAEF,GAAK,CAAA,CAAA,CAAA;AAC9C;AACF;AACF,iBAAA,CAAA;gBACA,IAAI+D,WAAAA,CAAYT,MAAM,GAAG,CAAG,EAAA;oBAC1B,MAAMY,OAAAA,CAAQC,UAAU,CAACJ,WAAAA,CAAAA;AAC3B;AACF;YACA,OAAOnD,KAAAA;AACT,SAAA,CAAE,OAAOZ,GAAK,EAAA;YACZC,OAAQC,CAAAA,KAAK,CAAC,CAAC,iBAAiB,EAAEd,IAAK,CAAA,UAAU,EAAEY,GAAK,CAAA,CAAA,CAAA;YACxD,OAAO,IAAA;AACT;AACF;AACF;;;;"}
|
package/dist/app/screen.js
CHANGED
|
@@ -16,7 +16,7 @@ import { getDevice } from './api.js';
|
|
|
16
16
|
* Creates a new {@link ScreenAdapter}.
|
|
17
17
|
*
|
|
18
18
|
* @param config - Optional initial screen configuration. If omitted,
|
|
19
|
-
* a default of 1280
|
|
19
|
+
* a default of `1280 x 720` with `cover` mode is used.
|
|
20
20
|
*/ constructor(config){
|
|
21
21
|
this._viewport = null;
|
|
22
22
|
this._transform = null;
|
|
@@ -250,7 +250,7 @@ import { getDevice } from './api.js';
|
|
|
250
250
|
*
|
|
251
251
|
* @param canvasPos - Point in canvas coordinates (CSS pixels).
|
|
252
252
|
* @param viewportPosOut - Optional output vector. If provided, it will be
|
|
253
|
-
* written into and returned; otherwise a new
|
|
253
|
+
* written into and returned; otherwise a new `Vector2` is allocated.
|
|
254
254
|
* @returns The point in viewport-local coordinates.
|
|
255
255
|
*/ canvasPosToViewport(canvasPos, viewportPosOut) {
|
|
256
256
|
return this.transformPoint(this.transform.canvasToViewport, canvasPos, viewportPosOut);
|
|
@@ -265,7 +265,7 @@ import { getDevice } from './api.js';
|
|
|
265
265
|
*
|
|
266
266
|
* @param canvasPos - Point in canvas coordinates (CSS pixels).
|
|
267
267
|
* @param logicPosOut - Optional output vector. If provided, it will be
|
|
268
|
-
* written into and returned; otherwise a new
|
|
268
|
+
* written into and returned; otherwise a new `Vector2` is allocated.
|
|
269
269
|
* @returns The point in logical (design resolution) coordinates.
|
|
270
270
|
*/ canvasPosToLogic(canvasPos, logicPosOut) {
|
|
271
271
|
return this.transformPoint(this.transform.canvasToLogic, canvasPos, logicPosOut);
|
|
@@ -281,7 +281,7 @@ import { getDevice } from './api.js';
|
|
|
281
281
|
* @param transform - Transform parameters (scale and offset).
|
|
282
282
|
* @param pointIn - Input point.
|
|
283
283
|
* @param pointOut - Optional output vector. If provided, it will be
|
|
284
|
-
* written into and returned; otherwise a new
|
|
284
|
+
* written into and returned; otherwise a new `Vector2` is allocated.
|
|
285
285
|
* @returns The transformed point.
|
|
286
286
|
*/ transformPoint(transform, pointIn, pointOut) {
|
|
287
287
|
const out = pointOut ?? new Vector2();
|