"""
高级骨骼动画系统使用示例
提供各种使用场景的代码示例
"""

def example_basic_usage(world):
    """
    基本使用示例
    """
    print("=== 高级骨骼动画插件基本使用示例 ===")
    
    # 获取插件实例
    plugin = world.plugin_manager.get_plugin("advanced_skeletal_animation")
    if not plugin:
        print("错误: 高级骨骼动画插件未加载")
        return
        
    core_system = plugin.get_core_system()
    
    # 1. 加载简单的Actor
    print("1. 加载Actor...")
    actor, actor_id = core_system.load_actor(
        model_path="models/characters/robot.egg",
        position=(0, 0, 0),
        scale=1.0
    )
    
    if actor:
        print(f"   成功加载Actor: {actor_id}")
        
        # 2. 获取可用动画
        animations = core_system.get_actor_animations(actor_id)
        print(f"2. 可用动画: {animations}")
        
        # 3. 播放动画
        if animations:
            print("3. 播放第一个动画...")
            core_system.play_animation(
                actor_id=actor_id,
                anim_name=animations[0],
                loop=True,
                play_rate=1.0
            )
            
        # 4. 获取动画信息
        if animations:
            info = core_system.get_animation_info(actor_id, animations[0])
            print(f"4. 动画信息: {info}")
            
    print("=== 基本使用示例结束 ===\n")


def example_advanced_usage(world):
    """
    高级使用示例
    """
    print("=== 高级骨骼动画插件高级使用示例 ===")
    
    # 获取插件实例
    plugin = world.plugin_manager.get_plugin("advanced_skeletal_animation")
    if not plugin:
        print("错误: 高级骨骼动画插件未加载")
        return
        
    core_system = plugin.get_core_system()
    
    # 1. 加载带多个动画的Actor
    print("1. 加载带多个动画的Actor...")
    anim_dict = {
        "walk": "models/anim/walk.egg",
        "run": "models/anim/run.egg",
        "jump": "models/anim/jump.egg",
        "idle": "models/anim/idle.egg"
    }
    
    actor, actor_id = core_system.load_actor(
        model_path="models/characters/hero.egg",
        anim_dict=anim_dict,
        position=(5, 0, 0),
        scale=1.2
    )
    
    if actor:
        print(f"   成功加载Actor: {actor_id}")
        
        # 2. 播放循环动画
        print("2. 播放循环idle动画...")
        core_system.play_animation(actor_id, "idle", loop=True)
        
        # 3. 3秒后切换到walk动画
        def switch_to_walk():
            print("3. 切换到walk动画...")
            core_system.stop_animation(actor_id, "idle")
            core_system.play_animation(actor_id, "walk", loop=True)
            
        # 使用Panda3D的任务系统在3秒后执行
        def schedule_task(task):
            if task.time >= 3.0:
                switch_to_walk()
                return task.done
            return task.cont
            
        world.taskMgr.doMethodLater(3.0, schedule_task, "switch_animation_task")
        
        # 4. 动画混合示例
        print("4. 创建动画混合...")
        core_system.blend_animations(
            actor_id, 
            "walk", 
            "run", 
            blend_time=2.0
        )
        
    print("=== 高级使用示例结束 ===\n")


def example_state_machine_usage(world):
    """
    状态机使用示例
    """
    print("=== 动画状态机使用示例 ===")
    
    # 获取插件实例
    plugin = world.plugin_manager.get_plugin("advanced_skeletal_animation")
    if not plugin:
        print("错误: 高级骨骼动画插件未加载")
        return
        
    core_system = plugin.get_core_system()
    
    # 加载Actor
    actor, actor_id = core_system.load_actor(
        model_path="models/characters/character.egg",
        anim_dict={
            "idle": "models/anim/idle.egg",
            "walk": "models/anim/walk.egg",
            "run": "models/anim/run.egg"
        },
        position=(10, 0, 0)
    )
    
    if actor:
        # 导入状态机类
        from .advanced import AnimationStateMachine
        
        # 创建状态机
        state_machine = AnimationStateMachine(actor)
        
        # 添加状态
        state_machine.add_state("idle", "idle", loop=True)
        state_machine.add_state("walk", "walk", loop=True)
        state_machine.add_state("run", "run", loop=True)
        
        # 设置转换
        state_machine.set_transition("idle", "walk")
        state_machine.set_transition("walk", "run")
        state_machine.set_transition("run", "idle")
        
        # 进入初始状态
        state_machine.enter_state("idle")
        
        # 添加到更新任务中
        def state_machine_update(task):
            dt = globalClock.getDt()
            state_machine.update(dt)
            return task.cont
            
        world.taskMgr.add(state_machine_update, f"state_machine_update_{actor_id}")
        
        print(f"状态机已为Actor {actor_id} 创建并启动")
        
    print("=== 状态机使用示例结束 ===\n")


def example_network_sync_usage(world):
    """
    网络同步使用示例
    """
    print("=== 网络同步使用示例 ===")
    
    # 获取插件实例
    plugin = world.plugin_manager.get_plugin("advanced_skeletal_animation")
    if not plugin:
        print("错误: 高级骨骼动画插件未加载")
        return
        
    core_system = plugin.get_core_system()
    network_system = plugin.get_network_system()
    
    # 设置网络模式
    from .network import NetworkMode, SyncMode
    network_system.set_network_mode(NetworkMode.SERVER)
    network_system.set_sync_mode(SyncMode.STATE_SYNC)
    
    # 加载Actor并注册网络同步
    actor, actor_id = core_system.load_actor(
        model_path="models/characters/player.egg",
        anim_dict={
            "idle": "models/anim/idle.egg",
            "walk": "models/anim/walk.egg"
        },
        position=(15, 0, 0)
    )
    
    if actor:
        network_id = network_system.register_actor_for_sync(actor_id)
        print(f"Actor {actor_id} 已注册网络同步 (网络ID: {network_id})")
        
        # 播放动画
        core_system.play_animation(actor_id, "walk", loop=True)
        
    print("=== 网络同步使用示例结束 ===\n")


def example_lod_usage(world):
    """
    LOD系统使用示例
    """
    print("=== LOD系统使用示例 ===")
    
    # 获取插件实例
    plugin = world.plugin_manager.get_plugin("advanced_skeletal_animation")
    if not plugin:
        print("错误: 高级骨骼动画插件未加载")
        return
        
    core_system = plugin.get_core_system()
    lod_system = plugin.get_lod_system()
    
    # 设置LOD参数
    from .optimization import LODStrategy
    lod_system.set_lod_strategy(LODStrategy.DISTANCE_BASED)
    lod_system.set_distance_thresholds([10.0, 25.0, 50.0])
    
    # 加载多个Actor
    actors_data = [
        {"pos": (-5, -5, 0), "name": "actor_1"},
        {"pos": (5, -5, 0), "name": "actor_2"},
        {"pos": (0, -10, 0), "name": "actor_3"}
    ]
    
    for actor_data in actors_data:
        actor, actor_id = core_system.load_actor(
            model_path="models/characters/npc.egg",
            anim_dict={"idle": "models/anim/idle.egg"},
            actor_id=actor_data["name"],
            position=actor_data["pos"]
        )
        
        if actor:
            core_system.play_animation(actor_id, "idle", loop=True)
            print(f"加载Actor: {actor_id} 位置: {actor_data['pos']}")
            
    print("=== LOD系统使用示例结束 ===\n")


def example_compression_usage(world):
    """
    动画压缩使用示例
    """
    print("=== 动画压缩使用示例 ===")
    
    # 获取插件实例
    plugin = world.plugin_manager.get_plugin("advanced_skeletal_animation")
    if not plugin:
        print("错误: 高级骨骼动画插件未加载")
        return
        
    core_system = plugin.get_core_system()
    
    # 加载Actor
    actor, actor_id = core_system.load_actor(
        model_path="models/characters/compress_test.egg",
        anim_dict={"walk": "models/anim/walk.egg"},
        position=(20, 0, 0)
    )
    
    if actor:
        # 导入压缩类
        from .optimization import AnimationCompressor, CompressionMethod
        compressor = AnimationCompressor()
        
        # 压缩动画
        compressed_data = compressor.compress_animation(
            actor, 
            "walk", 
            CompressionMethod.KEYFRAME_REDUCTION
        )
        
        if compressed_data:
            stats = compressor.get_compression_stats(compressed_data)
            print(f"动画压缩统计: {stats}")
            
    print("=== 动画压缩使用示例结束 ===\n")


def run_all_examples(world):
    """
    运行所有示例
    """
    print("开始运行高级骨骼动画插件所有示例...")
    
    example_basic_usage(world)
    example_advanced_usage(world)
    example_state_machine_usage(world)
    example_network_sync_usage(world)
    example_lod_usage(world)
    example_compression_usage(world)
    
    print("所有示例运行完成!")


# 使用说明和API参考
USAGE_GUIDE = """
高级骨骼动画插件使用说明
=====================

1. 基本概念
----------
- Actor: 带有骨骼的3D模型对象
- Animation: 应用于Actor的动画序列
- Core System: 管理所有Actor和动画的中心控制器

2. 主要功能模块
--------------
- Core System: 核心动画管理
- Network System: 网络同步
- LOD System: 细节层次管理
- Cache Manager: 缓存管理
- State Machine: 动画状态机
- Curve Editor: 动画曲线编辑器
- Physics Integration: 物理集成
- Compressor: 动画压缩

3. 核心API
----------
SkeletalAnimationCore:
  - load_actor(): 加载Actor模型
  - unload_actor(): 卸载Actor
  - play_animation(): 播放动画
  - stop_animation(): 停止动画
  - set_animation_speed(): 设置动画速度
  - pause_animation(): 暂停动画
  - resume_animation(): 恢复动画
  - blend_animations(): 混合动画

4. 网络同步
----------
AnimationNetworkSync:
  - set_network_mode(): 设置网络模式
  - register_actor_for_sync(): 注册Actor同步
  - send_actor_state(): 发送状态
  - receive_actor_state(): 接收状态

5. 高级功能
----------
AnimationStateMachine:
  - add_state(): 添加状态
  - set_transition(): 设置转换
  - enter_state(): 进入状态

AnimationLODSystem:
  - set_lod_strategy(): 设置LOD策略
  - update_lod_levels(): 更新LOD级别

AnimationCompressor:
  - compress_animation(): 压缩动画
  - decompress_animation(): 解压缩动画

6. 性能优化
----------
- 使用LOD系统根据距离调整动画质量
- 使用缓存管理器提高加载性能
- 使用动画压缩减少内存占用
- 合理设置网络同步频率

7. 注意事项
----------
- 确保模型文件包含正确的骨骼信息
- 动画文件需要与模型骨骼结构匹配
- 插件会在禁用时自动清理所有加载的Actor
- 使用完毕后应调用unload_actor释放资源
- 大量Actor可能影响性能，注意优化
"""

if __name__ == "__main__":
    print(USAGE_GUIDE)