# 刚体动力学插件使用文档 ## 简介 刚体动力学插件是一个完整的物理模拟系统,基于Bullet物理引擎,提供了丰富的物理功能,包括刚体动力学、约束系统、车辆模拟、粒子系统等。 ## 功能特性 ### 1. 物理世界管理 - 重力设置和控制 - 时间步长和子步长模拟 - 性能监控和优化 - 多线程支持 - 空间分区优化 ### 2. 刚体系统 - 静态、动态、运动学刚体 - 多种碰撞形状(盒体、球体、胶囊体、圆锥体、圆柱体、凸包、网格、复合形状) - 质量、摩擦、弹性等物理属性 - 连续碰撞检测(CCD) - 力和扭矩应用 - 速度和加速度控制 - 能量计算(动能、势能) - 碰撞历史记录 ### 3. 材质系统 - 预定义常用材质(混凝土、木材、金属、橡胶、冰、沙、水、玻璃、肉体等) - 自定义材质属性 - 基础物理属性(摩擦、弹性、密度等) - 热力学属性(热导率、比热容等) - 电学属性(电导率、介电常数等) - 流体属性(粘度、表面张力等) - 视觉属性(颜色、粗糙度等) - 环境属性(耐候性、腐蚀率等) - 特殊属性(易燃性、毒性、放射性) - 高级材质功能 - 热膨胀和相变模拟 - 环境老化效应(雨水、紫外线、风力等) - 疲劳累积和损伤分析 - 化学反应和腐蚀模拟 - 流体动力学效应(阻力、升力、浮力) - 能量吸收和耗散 - 失效准则和结构完整性评估 - 动态摩擦和恢复系数计算 - 材质交互矩阵 - 材质状态管理(温度、湿度、磨损、疲劳、污染等) - 材质历史记录和统计分析 - 材质保存和加载 ### 4. 约束和关节 - 点对点约束 - 铰链约束 - 滑动约束 - 锥形扭转约束 - 6自由度约束 - 6自由度弹簧约束 - 齿轮约束 - 固定约束 - 约束组和标签管理 - 约束马达和弹簧控制 - 约束限制设置 - 约束状态监控 ### 5. 车辆系统 - 底盘和车轮物理 - 悬挂系统 - 引擎和刹车控制 - 转向系统 - 差速器类型支持 - 齿轮系统 - 发动机扭矩曲线 - 防抱死刹车(ABS) - 牵引力控制(TC) - 车身稳定控制(ESP) - 空气动力学效应 - 防倾杆系统 - 车辆损伤系统 - 燃料系统 - 性能统计 ### 6. 粒子系统 - 大量粒子模拟 - 多种粒子类型(烟雾、火焰、水、碎片、爆炸、火花、气泡、叶子、雪、雨等) - 发射器控制 - 粒子生命周期管理 - 环境影响(风力、温度等) - 特殊效果(涡流等) - 粒子子发射器 - 粒子轨迹和淡出效果 - 粒子碰撞和死亡回调 - 爆炸和火焰特效 ### 7. 调试和可视化 - 碰撞体可视化 - 约束可视化 - 接触点可视化 - 法线可视化 - 速度和力可视化 - 坐标轴可视化 - 质心可视化 - 休眠状态可视化 - 粒子轨迹可视化 - 性能监控面板 - 调试文本显示 - 可视化选项控制 ### 8. 实用工具 - 物理计算工具(质量计算、冲量应用、扭矩计算等) - 配置管理器 - 碰撞组定义 - 物理常量库 ## 安装和配置 ### 目录结构 ``` rigid_body_physics/ ├── __init__.py ├── plugin_manager.py ├── README.md ├── core/ │ ├── physics_world.py │ ├── rigid_body.py │ └── material.py ├── constraints/ │ └── constraint_manager.py ├── vehicles/ │ └── vehicle_system.py ├── particles/ │ └── particle_system.py ├── debug/ │ └── debug_tools.py ├── utils/ │ └── physics_utils.py └── config/ └── physics_config.json ``` ## 快速开始 ### 1. 初始化插件 ```python from plugins.user.rigid_body_physics.plugin_manager import RigidBodyPhysicsPlugin # 创建物理插件实例 physics_plugin = RigidBodyPhysicsPlugin(world_node=render) ``` ### 2. 创建刚体 ```python # 创建一个盒子形状的动态刚体 box_body = physics_plugin.create_rigid_body( node_path=box_node, shape_type='box', mass=1.0, body_type=RigidBody.DYNAMIC ) # 设置物理属性 box_body.set_friction(0.5) box_body.set_restitution(0.3) # 应用力和扭矩 box_body.apply_force(Vec3(0, 0, 100)) # 向上施加力 box_body.apply_torque(Vec3(0, 10, 0)) # 绕Y轴施加扭矩 ``` ### 3. 创建约束 ```python # 创建铰链约束 hinge_constraint = physics_plugin.create_constraint( constraint_type='hinge', body_a=body_a, body_b=body_b, pivot_a=Point3(0, 0, 0), pivot_b=Point3(0, 0, 0), axis_a=Vec3(0, 0, 1), axis_b=Vec3(0, 0, 1) ) ``` ### 4. 创建车辆 ```python # 定义车轮配置 wheel_configs = [ { 'connection_point': Point3(-1, 1, 0), 'wheel_direction': Vec3(0, 0, -1), 'wheel_axle': Vec3(1, 0, 0), 'wheel_radius': 0.3 }, # ... 其他车轮配置 ] # 创建车辆 vehicle = physics_plugin.create_vehicle(chassis_body, wheel_configs) # 控制车辆 vehicle.set_steering(0.5) # 转向 vehicle.set_engine_force(1.0) # 加油 vehicle.set_brake_force(0.3) # 刹车 ``` ### 5. 创建粒子系统 ```python # 创建粒子系统 particle_system = physics_plugin.create_particle_system(max_particles=500) # 设置发射器属性 particle_system.set_emitter_properties( position=Point3(0, 0, 5), velocity=Vec3(0, 0, 10), spread=0.5 ) # 创建爆炸效果 particle_system.create_explosion( position=Point3(0, 0, 0), particle_count=100, explosion_force=50.0 ) ``` ### 6. 主循环更新 ```python def update(task): dt = globalClock.getDt() physics_plugin.update(dt) # 更新车辆 for vehicle in physics_plugin.vehicles: vehicle.update(dt) return task.cont taskMgr.add(update, "physics_update") ``` ## 高级功能 ### 材质系统 ```python # 使用预定义材质 concrete_material = physics_plugin.get_predefined_material('concrete') # 创建自定义材质 custom_material = physics_plugin.create_custom_material( 'my_material', { 'friction': 0.8, 'restitution': 0.2, 'density': 2000.0, 'thermal_conductivity': 2.0, 'color': Vec4(0.8, 0.6, 0.4, 1.0) } ) # 设置材质交互 custom_material.set_interaction_coefficient('metal', 1.2) # 更新材质状态 custom_material.update_state( temperature=50.0, wear=0.1, stress=100.0 ) ``` ### 调试可视化 ```python # 启用调试可视化 physics_plugin.enable_debug_visualization(True) # 设置调试选项 physics_plugin.set_debug_options( show_constraints=True, show_aabbs=True, show_velocities=True, show_forces=True ) # 性能分析 profiler = physics_plugin.profiler performance_report = profiler.get_performance_report() print(f"平均FPS: {performance_report['average_fps']}") ``` ### 性能监控 ```python # 获取性能统计 stats = physics_plugin.get_performance_stats() print(f"平均更新时间: {stats['avg_update_time']}") print(f"刚体数量: {stats['objects']['rigid_bodies']}") # 获取详细性能分析 analysis = physics_plugin.profiler.get_performance_analysis() print(f"性能等级: {analysis['performance_grade']}") print(f"瓶颈: {analysis['bottlenecks']}") print(f"建议: {analysis['recommendations']}") ``` ## 配置文件 插件支持通过JSON配置文件进行配置: ```json { "physics": { "gravity": [0, 0, -9.81], "time_step": 0.016667, "solver_iterations": 10, "solver_tolerance": 0.001 }, "materials": { "concrete": { "friction": 0.7, "restitution": 0.1, "density": 2400.0 } }, "vehicle": { "max_engine_force": 3000.0, "max_brake_force": 100.0, "max_steering": 0.7854 } } ``` ## API参考 ### RigidBodyPhysicsPlugin类 #### 构造函数 ```python RigidBodyPhysicsPlugin(world_node=None, config_file=None) ``` #### 主要方法 - `create_rigid_body(node_path, shape_type, mass, body_type, material)`: 创建刚体 - `create_constraint(constraint_type, body_a, body_b, **kwargs)`: 创建约束 - `create_vehicle(chassis_body, wheel_configurations)`: 创建车辆 - `create_particle_system(max_particles)`: 创建粒子系统 - `update(dt)`: 更新物理系统 - `ray_test(from_pos, to_pos)`: 射线检测 - `get_performance_stats()`: 获取性能统计 - `enable_debug_visualization(enabled)`: 启用调试可视化 - `set_debug_options(**kwargs)`: 设置调试选项 - `get_predefined_material(material_name)`: 获取预定义材质 - `create_custom_material(name, properties)`: 创建自定义材质 - `set_gravity(gravity)`: 设置重力 - `set_time_step(time_step, max_substeps)`: 设置时间步长 - `get_collision_groups()`: 获取碰撞组工具 - `save_config(config_file)`: 保存配置 - `load_config(config_file)`: 加载配置 - `clear_all()`: 清除所有物理对象 - `destroy()`: 销毁物理插件 ### RigidBody类 #### 主要方法 - `set_friction(friction, static_friction, dynamic_friction)`: 设置摩擦系数 - `set_restitution(restitution)`: 设置恢复系数 - `set_damping(linear_damping, angular_damping)`: 设置阻尼 - `set_factors(linear_factor, angular_factor)`: 设置线性和角因子 - `set_activation_state(active, always_active)`: 设置激活状态 - `set_sleeping_thresholds(linear_threshold, angular_threshold)`: 设置休眠阈值 - `set_ccd_parameters(motion_threshold, swept_sphere_radius)`: 设置CCD参数 - `apply_force(force, position, duration)`: 应用力 - `apply_torque(torque, duration)`: 应用扭矩 - `apply_impulse(impulse, position, duration)`: 应用冲量 - `apply_torque_impulse(torque_impulse)`: 应用扭矩冲量 - `get_linear_velocity()`: 获取线性速度 - `set_linear_velocity(velocity)`: 设置线性速度 - `get_angular_velocity()`: 获取角速度 - `set_angular_velocity(velocity)`: 设置角速度 - `get_position()`: 获取位置 - `set_position(position)`: 设置位置 - `get_rotation()`: 获取旋转 - `set_rotation(rotation)`: 设置旋转 - `sync_visual_node()`: 同步物理节点和可视化节点 - `get_mass()`: 获取质量 - `set_mass(mass)`: 设置质量 - `get_kinetic_energy()`: 计算动能 - `get_potential_energy(gravity)`: 计算势能 - `get_total_energy(gravity)`: 计算总能量 - `set_custom_data(key, value)`: 设置自定义数据 - `get_custom_data(key, default)`: 获取自定义数据 - `destroy()`: 销毁刚体 ### PhysicsMaterial类 #### 主要方法 - `set_property(property_name, value)`: 设置材质属性 - `get_property(property_name)`: 获取材质属性 - `set_friction(friction, static_friction, dynamic_friction)`: 设置摩擦系数 - `set_restitution(restitution)`: 设置恢复系数 - `set_density(density)`: 设置密度 - `set_color(color)`: 设置颜色 - `set_thermal_properties(conductivity, specific_heat, expansion)`: 设置热力学属性 - `set_electrical_properties(conductivity, dielectric, permeability)`: 设置电学属性 - `set_fluid_properties(viscosity, surface_tension, compressibility)`: 设置流体属性 - `set_visual_properties(roughness, metallic, specular, emissive)`: 设置视觉属性 - `set_environmental_properties(weather_resistance, corrosion_rate, aging_rate)`: 设置环境属性 - `set_special_properties(flammability, toxicity, radioactivity)`: 设置特殊属性 - `update_state(temperature, humidity, wear, contamination, stress, fatigue)`: 更新材质状态 - `get_effective_friction(other_material, velocity)`: 获取有效摩擦系数 - `get_effective_restitution(other_material, impact_velocity)`: 获取有效恢复系数 - `set_interaction_coefficient(other_material_name, coefficient)`: 设置交互系数 - `apply_to_rigid_body(rigid_body)`: 应用到刚体 - `to_dict()`: 转换为字典 - `from_dict(data)`: 从字典创建 - `save_to_file(filepath)`: 保存到文件 - `load_from_file(filepath)`: 从文件加载 ### ConstraintManager类 #### 支持的约束类型 - `CONSTRAINT_POINT2POINT`: 点对点约束 - `CONSTRAINT_HINGE`: 铰链约束 - `CONSTRAINT_SLIDER`: 滑动约束 - `CONSTRAINT_CONETWIST`: 锥形扭转约束 - `CONSTRAINT_6DOF`: 6自由度约束 - `CONSTRAINT_6DOF_SPRING`: 6自由度弹簧约束 - `CONSTRAINT_GEAR`: 齿轮约束 - `CONSTRAINT_FIXED`: 固定约束 #### 主要方法 - `create_point2point_constraint(body_a, body_b, pivot_a, pivot_b, ...)`: 创建点对点约束 - `create_hinge_constraint(body_a, body_b, pivot_a, pivot_b, axis_a, axis_b, ...)`: 创建铰链约束 - `create_slider_constraint(body_a, body_b, frame_a, frame_b, ...)`: 创建滑动约束 - `create_cone_twist_constraint(body_a, body_b, frame_a, frame_b, ...)`: 创建锥形扭转约束 - `create_6dof_constraint(body_a, body_b, frame_a, frame_b, ...)`: 创建6自由度约束 - `create_6dof_spring_constraint(body_a, body_b, frame_a, frame_b, ...)`: 创建6自由度弹簧约束 - `create_gear_constraint(body_a, body_b, axis_a, axis_b, ratio)`: 创建齿轮约束 - `create_fixed_constraint(body_a, body_b, frame_a, frame_b, ...)`: 创建固定约束 - `set_motor(constraint, axis, target_velocity, max_impulse)`: 设置马达 - `disable_motor(constraint)`: 禁用马达 - `set_spring(constraint, axis, stiffness, damping, equilibrium)`: 设置弹簧 - `disable_spring(constraint, axis)`: 禁用弹簧 - `set_limit(constraint, axis, lower_limit, upper_limit)`: 设置限制 - `add_constraint_to_group(constraint, group_name)`: 添加到组 - `remove_constraint_from_group(constraint, group_name)`: 从组移除 - `add_constraint_tag(constraint, tag)`: 添加标签 - `remove_constraint_tag(constraint, tag)`: 移除标签 - `get_constraints_by_tag(tag)`: 根据标签获取约束 - `get_constraints_by_group(group_name)`: 根据组获取约束 - `get_constraint_state(constraint)`: 获取约束状态 - `get_constraint_statistics()`: 获取约束统计 ### VehicleSystem类 #### 主要方法 - `add_wheel(...)`: 添加车轮 - `set_steering(steering)`: 设置转向 - `set_engine_force(force)`: 设置引擎力 - `set_brake_force(force)`: 设置刹车力 - `set_handbrake_force(force)`: 设置手刹力 - `shift_up()`: 升档 - `shift_down()`: 降档 - `set_gear(gear)`: 设置档位 - `update(dt)`: 更新车辆 - `get_current_speed_km_hour()`: 获取当前速度(km/h) - `get_wheel_info(wheel_index)`: 获取车轮信息 - `get_vehicle_state()`: 获取车辆状态 - `get_engine_torque()`: 获取发动机扭矩 - `get_engine_power()`: 获取发动机功率 - `apply_damage(component, amount)`: 应用损伤 - `repair_component(component, amount)`: 修复组件 - `refuel(amount)`: 加油 - `get_performance_stats()`: 获取性能统计 - `enable_anti_lock_brake(enabled)`: 启用ABS - `enable_traction_control(enabled)`: 启用牵引力控制 - `enable_stability_control(enabled)`: 启用车身稳定控制 - `destroy()`: 销毁车辆 ### ParticleSystem类 #### 主要方法 - `set_emitter_properties(...)`: 设置发射器属性 - `set_particle_properties(...)`: 设置粒子属性 - `set_physics_properties(...)`: 设置物理属性 - `set_collision_properties(...)`: 设置碰撞属性 - `set_environmental_effects(...)`: 设置环境影响 - `set_special_effects(...)`: 设置特殊效果 - `set_lifetime_behaviors(...)`: 设置生命周期行为 - `set_sub_emitter(...)`: 设置子发射器 - `set_performance_options(...)`: 设置性能选项 - `set_emission_rate(rate)`: 设置发射速率 - `set_emission_burst(count, interval)`: 设置爆发发射 - `emit_particle(position, velocity, lifetime, color)`: 发射粒子 - `update(dt)`: 更新粒子系统 - `get_particle_count()`: 获取粒子数量 - `get_statistics()`: 获取统计信息 - `clear_particles()`: 清除粒子 - `pause(paused)`: 暂停/恢复 - `set_time_scale(scale)`: 设置时间缩放 - `create_explosion(position, particle_count, explosion_force, ...)`: 创建爆炸 - `create_fire_effect(position, particle_count, rise_speed, ...)`: 创建火焰 - `destroy()`: 销毁粒子系统 ### PhysicsWorld类 #### 主要方法 - `set_gravity(gravity)`: 设置重力 - `set_time_step(time_step, max_substeps)`: 设置时间步长 - `set_solver_parameters(iterations, tolerance)`: 设置求解器参数 - `set_split_impulse(enable, penetration_threshold)`: 设置分离冲量 - `set_ccd_parameters(threshold, radius)`: 设置CCD参数 - `enable_multithreading(enable, thread_count)`: 启用多线程 - `setup_spatial_partitioning(partition_size)`: 设置空间分区 - `update(dt)`: 更新物理世界 - `add_rigid_body(rigid_body)`: 添加刚体 - `remove_rigid_body(rigid_body)`: 移除刚体 - `add_constraint(constraint)`: 添加约束 - `remove_constraint(constraint)`: 移除约束 - `add_vehicle(vehicle)`: 添加车辆 - `remove_vehicle(vehicle)`: 移除车辆 - `add_particle_system(particle_system)`: 添加粒子系统 - `remove_particle_system(particle_system)`: 移除粒子系统 - `ray_test(from_pos, to_pos)`: 射线检测 - `ray_test_all(from_pos, to_pos)`: 射线检测(所有结果) - `get_performance_stats()`: 获取性能统计 - `pause(paused)`: 暂停/恢复 - `set_time_scale(scale)`: 设置时间缩放 - `clear()`: 清除所有对象 - `reset()`: 重置物理世界 ### PhysicsDebug类 #### 主要方法 - `enable_debug(enabled)`: 启用/禁用调试 - `set_debug_options(...)`: 设置调试选项 - `update_debug_visualization()`: 更新调试可视化 - `add_contact_point(position, normal, impulse)`: 添加接触点 - `add_collision_event(body_a, body_b, contact_points)`: 添加碰撞事件 - `set_line_thickness(thickness)`: 设置线条粗细 - `set_axis_length(length)`: 设置坐标轴长度 - `set_velocity_scale(scale)`: 设置速度缩放 - `set_force_scale(scale)`: 设置力缩放 - `set_contact_point_size(size)`: 设置接触点大小 - `set_normal_scale(scale)`: 设置法线缩放 - `enable_debug_text(enabled)`: 启用/禁用调试文本 - `enable_stats_display(enabled)`: 启用/禁用统计显示 - `set_debug_update_frequency(frequency)`: 设置调试更新频率 - `hide_debug_visualization()`: 隐藏调试可视化 - `show_debug_visualization()`: 显示调试可视化 - `destroy()`: 销毁调试工具 ### PhysicsProfiler类 #### 主要方法 - `record_frame()`: 记录帧数据 - `get_average_update_time()`: 获取平均更新时间 - `get_max_update_time()`: 获取最大更新时间 - `get_min_update_time()`: 获取最小更新时间 - `get_average_fps()`: 获取平均FPS - `get_object_counts()`: 获取对象数量 - `get_average_object_counts()`: 获取平均对象数量 - `get_performance_report()`: 获取性能报告 - `get_performance_analysis()`: 获取性能分析 - `reset_statistics()`: 重置统计 - `export_statistics(filepath)`: 导出统计 - `destroy()`: 销毁分析器 ## 性能优化建议 1. **合理设置时间步长**: 过小的时间步长会影响性能,建议在1/60秒左右 2. **控制刚体数量**: 过多的刚体会影响性能,考虑使用休眠机制和剔除 3. **使用适当的碰撞形状**: 复杂形状比简单形状消耗更多资源,优先使用基本形状 4. **启用休眠机制**: 让静止的物体进入休眠状态以节省计算资源 5. **使用连续碰撞检测**: 对于高速运动的物体启用CCD以避免穿透 6. **合理设置求解器参数**: 迭代次数和容差影响精度和性能的平衡 7. **启用调试可视化仅在开发时**: 调试可视化会消耗额外资源 8. **及时销毁不需要的对象**: 避免内存泄漏 9. **使用对象池**: 对于频繁创建销毁的对象使用对象池 10. **空间分区**: 对于大型场景使用空间分区优化碰撞检测 ## 故障排除 ### 常见问题 1. **刚体穿透**: - 检查时间步长是否过小,增加求解器迭代次数 - 对高速物体启用连续碰撞检测(CCD) - 调整碰撞形状边界 2. **性能问题**: - 减少刚体和约束数量 - 优化碰撞形状复杂度 - 启用休眠机制 - 使用空间分区 - 调整求解器参数 3. **约束不稳定**: - 检查约束参数,适当调整限制范围 - 增加求解器迭代次数 - 调整约束的破裂阈值 4. **车辆控制不自然**: - 调整悬挂参数 - 调整轮胎摩擦系数 - 调整发动机扭矩曲线 - 启用或调整ABS、TC等辅助系统 5. **粒子效果不理想**: - 调整发射器参数 - 调整粒子生命周期参数 - 调整物理属性(重力、阻力等) - 调整环境影响参数 ### 联系支持 如有问题,请联系插件开发者或查看相关文档。