"""
物理材质系统模块
负责物理材质的定义和管理
"""

from panda3d.core import Vec3, Vec4
import json
import math
import time
from collections import defaultdict


class PhysicsMaterial:
    """
    物理材质类
    定义物体的物理表面属性
    """
    
    # 预定义材质类型
    TYPE_DEFAULT = 'default'
    TYPE_METAL = 'metal'
    TYPE_WOOD = 'wood'
    TYPE_CONCRETE = 'concrete'
    TYPE_RUBBER = 'rubber'
    TYPE_ICE = 'ice'
    TYPE_SAND = 'sand'
    TYPE_WATER = 'water'
    TYPE_GLASS = 'glass'
    TYPE_FLESH = 'flesh'
    TYPE_PLASTIC = 'plastic'
    TYPE_CLOTH = 'cloth'
    TYPE_LEATHER = 'leather'
    TYPE_STONE = 'stone'
    TYPE_SNOW = 'snow'
    TYPE_MUD = 'mud'
    
    def __init__(self, name, properties=None, material_type=TYPE_DEFAULT):
        """
        初始化物理材质
        
        Args:
            name (str): 材质名称
            properties (dict): 材质属性字典
            material_type (str): 材质类型
        """
        self.name = name
        self.material_type = material_type
        self.creation_time = time.time()
        
        # 默认材质属性
        self.properties = {
            # 基础物理属性
            'friction': 0.5,              # 摩擦系数
            'restitution': 0.1,           # 恢复系数（弹性）
            'rolling_friction': 0.1,      # 滚动摩擦
            'spinning_friction': 0.1,     # 自旋摩擦
            'static_friction': 0.6,       # 静摩擦
            'dynamic_friction': 0.4,      # 动摩擦
            
            # 高级物理属性
            'anisotropic_friction': Vec3(1, 1, 1),  # 各向异性摩擦
            'contact_cfm': 0.0,           # 接触约束力混合参数
            'contact_erp': 0.2,           # 接触误差减少参数
            'contact_threshold': 1e30,    # 接触处理阈值
            'stiffness': 1000000.0,       # 刚度
            'damping': 1.0,               # 阻尼
            'density': 1000.0,            # 密度（kg/m³）
            
            # 热力学属性
            'thermal_conductivity': 1.0,  # 热导率
            'specific_heat': 1000.0,      # 比热容
            'temperature': 20.0,          # 温度（摄氏度）
            'melting_point': 1000.0,      # 熔点
            'thermal_expansion': 0.0001,  # 热膨胀系数
            'heat_generation': 0.0,       # 热量生成率
            
            # 电学属性
            'electrical_conductivity': 0.0,  # 电导率
            'dielectric_constant': 1.0,      # 介电常数
            'magnetic_permeability': 1.0,    # 磁导率
            'charge_accumulation': 0.0,      # 电荷积累
            
            # 流体属性
            'viscosity': 0.001,           # 粘度
            'surface_tension': 0.072,     # 表面张力
            'compressibility': 0.0,       # 压缩性
            'buoyancy': 1.0,              # 浮力系数
            
            # 视觉属性
            'color': Vec4(0.5, 0.5, 0.5, 1.0),  # 显示颜色
            'surface_velocity': Vec3(0, 0, 0),   # 表面速度
            'roughness': 0.5,             # 粗糙度
            'metallic': 0.0,              # 金属度
            'specular': 0.5,              # 镜面反射
            'emissive': Vec3(0, 0, 0),    # 自发光
            'transparency': 0.0,          # 透明度
            
            # 环境属性
            'weather_resistance': 1.0,    # 耐候性
            'corrosion_rate': 0.0,        # 腐蚀率
            'aging_rate': 0.0,            # 老化率
            'uv_resistance': 1.0,         # 紫外线抗性
            
            # 特殊属性
            'flammability': 0.0,          # 易燃性
            'toxicity': 0.0,              # 毒性
            'radioactivity': 0.0,         # 放射性
            'explosiveness': 0.0,         # 爆炸性
            'flammability_threshold': 100.0,  # 燃烧阈值
        }
        
        # 材质状态
        self.state = {
            'temperature': 20.0,          # 当前温度
            'humidity': 50.0,             # 湿度
            'wear': 0.0,                  # 磨损度
            'contamination': 0.0,         # 污染度
            'stress': 0.0,                # 应力
            'fatigue': 0.0,               # 疲劳度
            'charge': 0.0,                # 电荷
            'wetness': 0.0,               # 湿润度
            'dirtiness': 0.0,             # 脏污度
        }
        
        # 材质交互矩阵（与其他材质的交互系数）
        self.interaction_matrix = defaultdict(lambda: 1.0)
        
        # 材质历史记录
        self.history = {
            'temperature_history': [],    # 温度历史
            'wear_history': [],           # 磨损历史
            'stress_history': [],         # 应力历史
            'aging_history': [],          # 老化历史
            'fatigue_history': [],        # 疲劳历史
            'chemical_history': [],       # 化学反应历史
        }
        
        # 应用自定义属性
        if properties:
            self.properties.update(properties)
            
        # 根据材质类型设置默认属性
        self._set_defaults_by_type()
        
        print(f"物理材质创建完成: {name} ({material_type})")
        
    def _set_defaults_by_type(self):
        """
        根据材质类型设置默认属性
        """
        if self.material_type == self.TYPE_METAL:
            self.properties.update({
                'friction': 0.3,
                'restitution': 0.4,
                'density': 7800.0,
                'color': Vec4(0.7, 0.7, 0.8, 1.0),
                'thermal_conductivity': 80.0,
                'electrical_conductivity': 1e7,
                'roughness': 0.3,
                'metallic': 1.0,
                'specular': 0.9,
                'corrosion_rate': 0.1,
            })
        elif self.material_type == self.TYPE_WOOD:
            self.properties.update({
                'friction': 0.4,
                'restitution': 0.2,
                'density': 700.0,
                'color': Vec4(0.8, 0.6, 0.4, 1.0),
                'thermal_conductivity': 0.1,
                'flammability': 0.8,
                'roughness': 0.7,
                'aging_rate': 0.05,
            })
        elif self.material_type == self.TYPE_CONCRETE:
            self.properties.update({
                'friction': 0.7,
                'restitution': 0.1,
                'density': 2400.0,
                'color': Vec4(0.6, 0.6, 0.6, 1.0),
                'roughness': 0.9,
                'weather_resistance': 0.9,
            })
        elif self.material_type == self.TYPE_RUBBER:
            self.properties.update({
                'friction': 0.9,
                'restitution': 0.8,
                'density': 1200.0,
                'color': Vec4(0.2, 0.2, 0.2, 1.0),
                'roughness': 0.8,
                'specular': 0.1,
                'elasticity': 0.9,
            })
        elif self.material_type == self.TYPE_ICE:
            self.properties.update({
                'friction': 0.03,
                'restitution': 0.1,
                'density': 917.0,
                'color': Vec4(0.8, 0.9, 1.0, 0.8),
                'thermal_conductivity': 2.2,
                'roughness': 0.1,
                'specular': 0.9,
                'melting_point': 0.0,
            })
        elif self.material_type == self.TYPE_SAND:
            self.properties.update({
                'friction': 0.6,
                'restitution': 0.05,
                'density': 1600.0,
                'color': Vec4(0.9, 0.8, 0.6, 1.0),
                'roughness': 0.9,
                'flowability': 0.8,
            })
        elif self.material_type == self.TYPE_WATER:
            self.properties.update({
                'friction': 0.1,
                'restitution': 0.0,
                'density': 1000.0,
                'color': Vec4(0.0, 0.5, 1.0, 0.7),
                'viscosity': 0.001,
                'surface_tension': 0.072,
                'buoyancy': 1.0,
                'transparency': 0.8,
            })
        elif self.material_type == self.TYPE_GLASS:
            self.properties.update({
                'friction': 0.2,
                'restitution': 0.9,
                'density': 2500.0,
                'color': Vec4(0.8, 0.9, 1.0, 0.3),
                'roughness': 0.1,
                'specular': 0.95,
                'transparency': 0.9,
                'fragility': 0.8,
            })
        elif self.material_type == self.TYPE_FLESH:
            self.properties.update({
                'friction': 0.8,
                'restitution': 0.1,
                'density': 1060.0,
                'color': Vec4(0.9, 0.7, 0.7, 1.0),
                'roughness': 0.6,
                'toxicity': 0.1,
                'elasticity': 0.3,
            })
        elif self.material_type == self.TYPE_PLASTIC:
            self.properties.update({
                'friction': 0.4,
                'restitution': 0.3,
                'density': 1200.0,
                'color': Vec4(0.9, 0.9, 0.9, 1.0),
                'roughness': 0.5,
                'specular': 0.6,
                'flammability': 0.3,
                'elasticity': 0.5,
            })
        elif self.material_type == self.TYPE_CLOTH:
            self.properties.update({
                'friction': 0.6,
                'restitution': 0.1,
                'density': 500.0,
                'color': Vec4(0.8, 0.8, 0.8, 1.0),
                'roughness': 0.8,
                'flexibility': 0.9,
                'breathability': 0.7,
            })
        elif self.material_type == self.TYPE_LEATHER:
            self.properties.update({
                'friction': 0.5,
                'restitution': 0.2,
                'density': 900.0,
                'color': Vec4(0.5, 0.3, 0.2, 1.0),
                'roughness': 0.6,
                'durability': 0.8,
                'water_resistance': 0.6,
            })
        elif self.material_type == self.TYPE_STONE:
            self.properties.update({
                'friction': 0.7,
                'restitution': 0.1,
                'density': 2600.0,
                'color': Vec4(0.7, 0.7, 0.7, 1.0),
                'roughness': 0.8,
                'hardness': 0.9,
                'weather_resistance': 0.95,
            })
        elif self.material_type == self.TYPE_SNOW:
            self.properties.update({
                'friction': 0.2,
                'restitution': 0.05,
                'density': 100.0,
                'color': Vec4(1.0, 1.0, 1.0, 0.9),
                'roughness': 0.3,
                'melting_point': 0.0,
                'compressibility': 0.5,
            })
        elif self.material_type == self.TYPE_MUD:
            self.properties.update({
                'friction': 0.8,
                'restitution': 0.01,
                'density': 1300.0,
                'color': Vec4(0.4, 0.3, 0.2, 1.0),
                'roughness': 0.9,
                'stickiness': 0.7,
                'viscosity': 0.1,
            })
            
    def set_property(self, property_name, value):
        """
        设置材质属性
        
        Args:
            property_name (str): 属性名称
            value: 属性值
        """
        if property_name in self.properties:
            self.properties[property_name] = value
        else:
            raise ValueError(f"未知的材质属性: {property_name}")
            
    def get_property(self, property_name):
        """
        获取材质属性
        
        Args:
            property_name (str): 属性名称
            
        Returns:
            属性值
        """
        if property_name in self.properties:
            return self.properties[property_name]
        else:
            raise ValueError(f"未知的材质属性: {property_name}")
            
    def set_friction(self, friction, static_friction=None, dynamic_friction=None):
        """
        设置摩擦系数
        
        Args:
            friction (float): 摩擦系数
            static_friction (float): 静摩擦系数（可选）
            dynamic_friction (float): 动摩擦系数（可选）
        """
        self.properties['friction'] = friction
        if static_friction is not None:
            self.properties['static_friction'] = static_friction
        if dynamic_friction is not None:
            self.properties['dynamic_friction'] = dynamic_friction
            
    def set_restitution(self, restitution):
        """
        设置恢复系数
        
        Args:
            restitution (float): 恢复系数
        """
        self.properties['restitution'] = restitution
        
    def set_density(self, density):
        """
        设置密度
        
        Args:
            density (float): 密度（kg/m³）
        """
        self.properties['density'] = density
        
    def set_color(self, color):
        """
        设置显示颜色
        
        Args:
            color (Vec4): RGBA颜色值
        """
        self.properties['color'] = color
        
    def set_thermal_properties(self, conductivity=None, specific_heat=None, 
                              expansion=None, heat_generation=None):
        """
        设置热力学属性
        
        Args:
            conductivity (float): 热导率
            specific_heat (float): 比热容
            expansion (float): 热膨胀系数
            heat_generation (float): 热量生成率
        """
        if conductivity is not None:
            self.properties['thermal_conductivity'] = conductivity
        if specific_heat is not None:
            self.properties['specific_heat'] = specific_heat
        if expansion is not None:
            self.properties['thermal_expansion'] = expansion
        if heat_generation is not None:
            self.properties['heat_generation'] = heat_generation
            
    def set_electrical_properties(self, conductivity=None, dielectric=None, 
                                 permeability=None, charge_accumulation=None):
        """
        设置电学属性
        
        Args:
            conductivity (float): 电导率
            dielectric (float): 介电常数
            permeability (float): 磁导率
            charge_accumulation (float): 电荷积累
        """
        if conductivity is not None:
            self.properties['electrical_conductivity'] = conductivity
        if dielectric is not None:
            self.properties['dielectric_constant'] = dielectric
        if permeability is not None:
            self.properties['magnetic_permeability'] = permeability
        if charge_accumulation is not None:
            self.properties['charge_accumulation'] = charge_accumulation
            
    def set_fluid_properties(self, viscosity=None, surface_tension=None, 
                            compressibility=None, buoyancy=None):
        """
        设置流体属性
        
        Args:
            viscosity (float): 粘度
            surface_tension (float): 表面张力
            compressibility (float): 压缩性
            buoyancy (float): 浮力系数
        """
        if viscosity is not None:
            self.properties['viscosity'] = viscosity
        if surface_tension is not None:
            self.properties['surface_tension'] = surface_tension
        if compressibility is not None:
            self.properties['compressibility'] = compressibility
        if buoyancy is not None:
            self.properties['buoyancy'] = buoyancy
            
    def set_visual_properties(self, roughness=None, metallic=None, specular=None,
                             emissive=None, transparency=None):
        """
        设置视觉属性
        
        Args:
            roughness (float): 粗糙度
            metallic (float): 金属度
            specular (float): 镜面反射
            emissive (Vec3): 自发光
            transparency (float): 透明度
        """
        if roughness is not None:
            self.properties['roughness'] = roughness
        if metallic is not None:
            self.properties['metallic'] = metallic
        if specular is not None:
            self.properties['specular'] = specular
        if emissive is not None:
            self.properties['emissive'] = emissive
        if transparency is not None:
            self.properties['transparency'] = transparency
            
    def set_environmental_properties(self, weather_resistance=None, 
                                   corrosion_rate=None, aging_rate=None,
                                   uv_resistance=None):
        """
        设置环境属性
        
        Args:
            weather_resistance (float): 耐候性
            corrosion_rate (float): 腐蚀率
            aging_rate (float): 老化率
            uv_resistance (float): 紫外线抗性
        """
        if weather_resistance is not None:
            self.properties['weather_resistance'] = weather_resistance
        if corrosion_rate is not None:
            self.properties['corrosion_rate'] = corrosion_rate
        if aging_rate is not None:
            self.properties['aging_rate'] = aging_rate
        if uv_resistance is not None:
            self.properties['uv_resistance'] = uv_resistance
            
    def set_special_properties(self, flammability=None, toxicity=None, 
                              radioactivity=None, explosiveness=None,
                              flammability_threshold=None):
        """
        设置特殊属性
        
        Args:
            flammability (float): 易燃性
            toxicity (float): 毒性
            radioactivity (float): 放射性
            explosiveness (float): 爆炸性
            flammability_threshold (float): 燃烧阈值
        """
        if flammability is not None:
            self.properties['flammability'] = flammability
        if toxicity is not None:
            self.properties['toxicity'] = toxicity
        if radioactivity is not None:
            self.properties['radioactivity'] = radioactivity
        if explosiveness is not None:
            self.properties['explosiveness'] = explosiveness
        if flammability_threshold is not None:
            self.properties['flammability_threshold'] = flammability_threshold
            
    def update_state(self, temperature=None, humidity=None, wear=None,
                    contamination=None, stress=None, fatigue=None,
                    charge=None, wetness=None, dirtiness=None):
        """
        更新材质状态
        
        Args:
            temperature (float): 温度
            humidity (float): 湿度
            wear (float): 磨损度
            contamination (float): 污染度
            stress (float): 应力
            fatigue (float): 疲劳度
            charge (float): 电荷
            wetness (float): 湿润度
            dirtiness (float): 脏污度
        """
        current_time = time.time()
        
        if temperature is not None:
            self.state['temperature'] = temperature
            self.history['temperature_history'].append((temperature, current_time))
            # 保持历史记录在合理范围内
            if len(self.history['temperature_history']) > 100:
                self.history['temperature_history'].pop(0)
                
        if humidity is not None:
            self.state['humidity'] = humidity
            
        if wear is not None:
            self.state['wear'] = max(0.0, min(1.0, wear))
            self.history['wear_history'].append((wear, current_time))
            if len(self.history['wear_history']) > 100:
                self.history['wear_history'].pop(0)
                
        if contamination is not None:
            self.state['contamination'] = max(0.0, min(1.0, contamination))
            
        if stress is not None:
            self.state['stress'] = max(0.0, stress)
            self.history['stress_history'].append((stress, current_time))
            if len(self.history['stress_history']) > 100:
                self.history['stress_history'].pop(0)
                
        if fatigue is not None:
            self.state['fatigue'] = max(0.0, min(1.0, fatigue))
            
        if charge is not None:
            self.state['charge'] = charge
            
        if wetness is not None:
            self.state['wetness'] = max(0.0, min(1.0, wetness))
            
        if dirtiness is not None:
            self.state['dirtiness'] = max(0.0, min(1.0, dirtiness))
            
    def get_effective_friction(self, other_material=None, velocity=None, normal_force=None, surface_area=None):
        """
        获取有效摩擦系数（考虑状态和交互）
        
        Args:
            other_material (PhysicsMaterial): 另一个材质
            velocity (Vec3): 相对速度
            normal_force (float): 法向力
            surface_area (float): 接触面积
            
        Returns:
            float: 有效摩擦系数
        """
        base_friction = self.properties['friction']
        
        # 考虑磨损影响
        wear_factor = 1.0 - self.state['wear'] * 0.3
        
        # 考虑污染影响
        contamination_factor = 1.0 - self.state['contamination'] * 0.2
        
        # 考虑湿润度影响
        wetness_factor = 1.0 - self.state['wetness'] * 0.5
        
        # 考虑脏污度影响
        dirtiness_factor = 1.0 - self.state['dirtiness'] * 0.1
        
        # 考虑速度影响（高速时摩擦减小）
        velocity_factor = 1.0
        if velocity:
            speed = velocity.length()
            if speed > 1.0:
                velocity_factor = max(0.5, 1.0 - speed * 0.01)
                
        # 考虑法向力影响（压力影响摩擦）
        pressure_factor = 1.0
        if normal_force and surface_area and surface_area > 0:
            pressure = normal_force / surface_area
            # 压力增加会略微增加摩擦
            pressure_factor = 1.0 + min(0.2, pressure * 0.0001)
                
        # 考虑温度影响
        temperature = self.state['temperature']
        temperature_factor = 1.0
        # 高温可能降低摩擦（简化模型）
        if temperature > 100:
            temperature_factor = max(0.7, 1.0 - (temperature - 100) * 0.001)
                
        # 考虑材质交互
        interaction_factor = 1.0
        if other_material:
            interaction_key = other_material.name
            interaction_factor = self.interaction_matrix[interaction_key]
            
        effective_friction = base_friction * wear_factor * contamination_factor * wetness_factor * dirtiness_factor * velocity_factor * pressure_factor * temperature_factor * interaction_factor
        return max(0.0, effective_friction)
        
    def get_dynamic_friction(self, other_material=None, velocity=None, normal_force=None, surface_area=None):
        """
        获取动态摩擦系数（考虑滑动状态）
        
        Args:
            other_material (PhysicsMaterial): 另一个材质
            velocity (Vec3): 相对速度
            normal_force (float): 法向力
            surface_area (float): 接触面积
            
        Returns:
            float: 动态摩擦系数
        """
        # 静摩擦系数
        static_friction = self.properties.get('static_friction', self.properties['friction'] * 1.2)
        
        # 动摩擦系数
        dynamic_friction = self.properties.get('dynamic_friction', self.properties['friction'])
        
        # 速度影响（滑动时摩擦略有不同）
        speed_effect = 1.0
        if velocity:
            speed = velocity.length()
            # 低速时接近静摩擦，高速时接近动摩擦
            if speed < 0.1:
                speed_effect = static_friction / dynamic_friction if dynamic_friction > 0 else 1.0
            elif speed < 1.0:
                # 插值
                t = speed / 0.1
                speed_effect = static_friction / dynamic_friction * (1 - t) + t if dynamic_friction > 0 else 1.0
                
        # 使用有效摩擦系数作为基础
        effective_friction = self.get_effective_friction(other_material, velocity, normal_force, surface_area)
        
        # 应用速度效应
        return effective_friction * speed_effect
        
    def get_effective_restitution(self, other_material=None, impact_velocity=None, temperature=None):
        """
        获取有效恢复系数（考虑状态和交互）
        
        Args:
            other_material (PhysicsMaterial): 另一个材质
            impact_velocity (float): 撞击速度
            temperature (float): 温度（可选，使用当前温度）
            
        Returns:
            float: 有效恢复系数
        """
        base_restitution = self.properties['restitution']
        
        # 考虑疲劳影响
        fatigue_factor = 1.0 - self.state['fatigue'] * 0.5
        
        # 考虑应力影响
        stress_factor = 1.0 - min(1.0, self.state['stress'] / 1000.0) * 0.3
        
        # 考虑撞击速度影响（高速时弹性减小）
        velocity_factor = 1.0
        if impact_velocity and impact_velocity > 5.0:
            velocity_factor = max(0.3, 1.0 - (impact_velocity - 5.0) * 0.05)
            
        # 考虑温度影响
        temp = temperature if temperature is not None else self.state['temperature']
        temperature_factor = 1.0
        # 高温可能降低弹性（简化模型）
        if temp > 100:
            temperature_factor = max(0.5, 1.0 - (temp - 100) * 0.002)
        # 低温可能增加脆性（降低弹性）
        elif temp < 0:
            temperature_factor = max(0.3, 1.0 + temp * 0.005)
            
        # 考虑老化影响
        aging_factor = 1.0 - self.state['wear'] * 0.4  # 老化降低弹性
        
        # 考虑材质交互
        interaction_factor = 1.0
        if other_material:
            interaction_key = other_material.name
            interaction_factor = self.interaction_matrix[interaction_key]
            
        effective_restitution = base_restitution * fatigue_factor * stress_factor * velocity_factor * temperature_factor * aging_factor * interaction_factor
        return max(0.0, min(1.0, effective_restitution))
        
    def get_energy_absorption(self, impact_energy, contact_area):
        """
        计算材质的能量吸收特性
        
        Args:
            impact_energy (float): 撞击能量
            contact_area (float): 接触面积
            
        Returns:
            dict: 能量吸收结果
        """
        # 材质的阻尼属性
        damping = self.properties.get('damping', 0.1)
        
        # 能量吸收（部分能量转化为热量和形变）
        absorbed_energy = impact_energy * damping
        reflected_energy = impact_energy - absorbed_energy
        
        # 计算温升
        specific_heat = self.properties.get('specific_heat', 1000.0)
        mass = self.properties.get('density', 1000.0) * contact_area * 0.01  # 简化质量计算
        temperature_rise = absorbed_energy / (mass * specific_heat) if mass * specific_heat > 0 else 0
        
        # 更新温度状态
        self.update_state(temperature=self.state['temperature'] + temperature_rise)
        
        # 计算应力增加
        stress_increase = absorbed_energy * 0.01 / contact_area if contact_area > 0 else 0
        self.update_state(stress=max(0.0, self.state['stress'] + stress_increase))
        
        # 计算疲劳增加
        fatigue_increase = absorbed_energy * 0.001 / contact_area if contact_area > 0 else 0
        self.update_state(fatigue=min(1.0, self.state['fatigue'] + fatigue_increase))
        
        return {
            'absorbed_energy': absorbed_energy,
            'reflected_energy': reflected_energy,
            'temperature_rise': temperature_rise,
            'stress_increase': stress_increase,
            'fatigue_increase': fatigue_increase
        }
        
    def set_interaction_coefficient(self, other_material_name, coefficient):
        """
        设置与其他材质的交互系数
        
        Args:
            other_material_name (str): 其他材质名称
            coefficient (float): 交互系数
        """
        self.interaction_matrix[other_material_name] = coefficient
        
    def get_interaction_coefficient(self, other_material_name):
        """
        获取与其他材质的交互系数
        
        Args:
            other_material_name (str): 其他材质名称
            
        Returns:
            float: 交互系数
        """
        return self.interaction_matrix[other_material_name]
        
    def apply_to_rigid_body(self, rigid_body):
        """
        应用材质属性到刚体
        
        Args:
            rigid_body (RigidBody): 刚体对象
        """
        # 应用摩擦属性
        effective_friction = self.get_effective_friction()
        rigid_body.set_friction(effective_friction)
        rigid_body.bullet_body.setAnisotropicFriction(self.properties['anisotropic_friction'])
        rigid_body.bullet_body.setContactProcessingThreshold(self.properties['contact_threshold'])
        
        # 应用恢复系数
        effective_restitution = self.get_effective_restitution()
        rigid_body.set_restitution(effective_restitution)
        
        # 应用CFM和ERP参数
        rigid_body.bullet_body.setContactCfm(self.properties['contact_cfm'])
        rigid_body.bullet_body.setContactErp(self.properties['contact_erp'])
        
        # 设置自定义数据
        rigid_body.set_custom_data('material_name', self.name)
        rigid_body.set_custom_data('material_type', self.material_type)
        
    def calculate_thermal_effect(self, time_delta, environment_temp=20.0, heat_sources=None):
        """
        计算热效应
        
        Args:
            time_delta (float): 时间增量
            environment_temp (float): 环境温度
            heat_sources (list): 热源列表 [{'position': Point3, 'temperature': float, 'radius': float}]
            
        Returns:
            float: 温度变化
        """
        current_temp = self.state['temperature']
        conductivity = self.properties['thermal_conductivity']
        specific_heat = self.properties['specific_heat']
        heat_generation = self.properties.get('heat_generation', 0.0)
        thermal_expansion = self.properties.get('thermal_expansion', 0.0)
        
        # 基础热传导计算
        temp_difference = environment_temp - current_temp
        heat_transfer = temp_difference * conductivity * time_delta
        
        # 内部热量生成
        internal_heat = heat_generation * time_delta
        
        # 外部热源影响
        external_heat = 0.0
        if heat_sources:
            for source in heat_sources:
                # 简化的热源影响计算
                source_temp = source.get('temperature', 0.0)
                source_radius = source.get('radius', 1.0)
                distance_factor = max(0.1, source_radius)  # 简化距离影响
                external_heat += (source_temp - current_temp) * 0.1 / distance_factor * time_delta
        
        # 温度变化 = (热传导 + 内部热量 + 外部热源) / (质量 * 比热容)
        # 这里假设单位质量为1kg
        temp_change = (heat_transfer + internal_heat + external_heat) / specific_heat if specific_heat > 0 else 0
        
        # 考虑相变（简化实现）
        melting_point = self.properties.get('melting_point', 1000.0)
        if current_temp < melting_point <= current_temp + temp_change:
            # 材质开始熔化，吸收潜热
            latent_heat = self.properties.get('latent_heat_of_fusion', 0.0)
            if latent_heat > 0:
                temp_change *= 0.1  # 熔化过程中温度变化减缓
                
        return temp_change
        
    def calculate_thermal_expansion(self, temperature_change):
        """
        计算热膨胀效应
        
        Args:
            temperature_change (float): 温度变化
            
        Returns:
            float: 尺寸变化因子
        """
        thermal_expansion = self.properties.get('thermal_expansion', 0.0)
        return 1.0 + thermal_expansion * temperature_change
        
    def calculate_environmental_effects(self, time_delta, weather_conditions=None):
        """
        计算环境效应对材质的影响
        
        Args:
            time_delta (float): 时间增量
            weather_conditions (dict): 天气条件 {'rain': float, 'wind': float, 'humidity': float, 'uv': float}
            
        Returns:
            dict: 环境效应结果
        """
        if weather_conditions is None:
            weather_conditions = {'rain': 0.0, 'wind': 0.0, 'humidity': 0.5, 'uv': 0.0}
            
        # 获取材质属性
        weather_resistance = self.properties.get('weather_resistance', 1.0)
        corrosion_rate = self.properties.get('corrosion_rate', 0.0)
        uv_resistance = self.properties.get('uv_resistance', 1.0)
        aging_rate = self.properties.get('aging_rate', 0.0)
        
        # 雨水影响
        rain_intensity = weather_conditions.get('rain', 0.0)
        wetness_increase = rain_intensity * (1.0 - weather_resistance) * time_delta
        self.update_state(wetness=min(1.0, self.state['wetness'] + wetness_increase))
        
        # 湿度影响
        humidity = weather_conditions.get('humidity', 0.5)
        humidity_effect = (humidity - 0.5) * 0.1 * time_delta
        self.update_state(humidity=max(0.0, min(100.0, self.state['humidity'] + humidity_effect)))
        
        # 腐蚀影响
        corrosion_increase = rain_intensity * corrosion_rate * (1.0 - weather_resistance) * time_delta
        self.update_state(contamination=min(1.0, self.state['contamination'] + corrosion_increase))
        
        # UV老化影响
        uv_intensity = weather_conditions.get('uv', 0.0)
        uv_damage = uv_intensity * aging_rate * (1.0 - uv_resistance) * time_delta
        self.update_state(wear=min(1.0, self.state['wear'] + uv_damage))
        
        # 风力影响（清洁效果）
        wind_speed = weather_conditions.get('wind', 0.0)
        dirt_removal = wind_speed * 0.01 * time_delta
        self.update_state(dirtiness=max(0.0, self.state['dirtiness'] - dirt_removal))
        
        return {
            'wetness_change': wetness_increase,
            'humidity_change': humidity_effect,
            'corrosion_change': corrosion_increase,
            'uv_damage': uv_damage,
            'dirt_removal': dirt_removal
        }
        
    def simulate_aging(self, time_delta, environmental_factors=None):
        """
        模拟材质老化过程
        
        Args:
            time_delta (float): 时间增量
            environmental_factors (dict): 环境因素
            
        Returns:
            dict: 老化效应
        """
        if environmental_factors is None:
            environmental_factors = {}
            
        aging_rate = self.properties.get('aging_rate', 0.0)
        weather_resistance = self.properties.get('weather_resistance', 1.0)
        
        # 基础老化
        base_aging = aging_rate * time_delta
        
        # 环境加速老化
        environmental_aging = 0.0
        for factor, intensity in environmental_factors.items():
            if factor == 'temperature':
                # 高温加速老化
                if intensity > 50:  # 超过50度
                    environmental_aging += (intensity - 50) * 0.001 * time_delta
            elif factor == 'humidity':
                # 高湿影响
                if intensity > 0.8:  # 湿度超过80%
                    environmental_aging += (intensity - 0.8) * 0.1 * time_delta
            elif factor == 'chemical_exposure':
                # 化学暴露
                environmental_aging += intensity * 0.05 * time_delta
                
        # 总老化效应
        total_aging = base_aging + environmental_aging
        
        # 应用老化效应到材质属性
        current_wear = self.state['wear']
        new_wear = min(1.0, current_wear + total_aging)
        self.update_state(wear=new_wear)
        
        # 老化对物理属性的影响
        aging_factor = new_wear  # 简化处理，磨损程度等于老化程度
        
        # 老化对摩擦系数的影响
        friction_change = aging_factor * 0.1  # 老化增加摩擦变化
        
        # 老化对弹性的影响
        restitution_degradation = aging_factor * 0.2  # 老化降低弹性
        
        # 更新老化历史
        current_time = time.time()
        self.history['aging_history'].append((total_aging, current_time))
        if len(self.history['aging_history']) > 100:
            self.history['aging_history'].pop(0)
        
        return {
            'aging_amount': total_aging,
            'friction_change': friction_change,
            'restitution_degradation': restitution_degradation,
            'new_wear_level': new_wear
        }
        
    def get_aging_stats(self):
        """
        获取老化统计数据
        
        Returns:
            dict: 老化统计数据
        """
        if not self.history['aging_history']:
            return {'total_aging': 0.0, 'average_aging_rate': 0.0}
            
        total_aging = sum([aging for aging, _ in self.history['aging_history']])
        avg_aging_rate = total_aging / len(self.history['aging_history'])
        
        return {
            'total_aging': total_aging,
            'average_aging_rate': avg_aging_rate,
            'current_wear_level': self.state['wear']
        }
        
    def calculate_wear_rate(self, relative_velocity, normal_force, time_delta):
        """
        计算磨损率
        
        Args:
            relative_velocity (Vec3): 相对速度
            normal_force (float): 法向力
            time_delta (float): 时间增量
            
        Returns:
            float: 磨损率
        """
        speed = relative_velocity.length()
        pressure = normal_force  # 简化处理
        
        # 磨损率 = k * 压力 * 速度 * 时间
        wear_constant = 1e-6  # 磨损常数
        wear_rate = wear_constant * pressure * speed * time_delta
        
        # 考虑材质硬度影响
        hardness = self.properties.get('hardness', 1.0)
        wear_rate *= (1.0 - hardness * 0.5)
        
        # 考虑环境因素
        wetness_factor = 1.0 + self.state['wetness'] * 0.2  # 湿润可能增加磨损
        wear_rate *= wetness_factor
        
        return wear_rate
        
    def calculate_fatigue_accumulation(self, stress_amplitude, cycles, material_properties=None):
        """
        计算疲劳累积（基于Palmgren-Miner线性累积损伤法则）
        
        Args:
            stress_amplitude (float): 应力幅值
            cycles (int): 循环次数
            material_properties (dict): 材料特性参数
            
        Returns:
            float: 疲劳损伤累积
        """
        if material_properties is None:
            material_properties = {}
            
        # 材料的疲劳参数
        fatigue_strength_coefficient = material_properties.get('fatigue_strength_coefficient', 
                                                              self.properties.get('fatigue_strength_coefficient', 1000.0))
        fatigue_strength_exponent = material_properties.get('fatigue_strength_exponent', 
                                                           self.properties.get('fatigue_strength_exponent', -0.1))
        fatigue_ductility_coefficient = material_properties.get('fatigue_ductility_coefficient', 
                                                               self.properties.get('fatigue_ductility_coefficient', 1.0))
        fatigue_ductility_exponent = material_properties.get('fatigue_ductility_exponent', 
                                                            self.properties.get('fatigue_ductility_exponent', -0.6))
        
        # 计算疲劳寿命（N）
        # 简化的疲劳寿命计算模型
        if stress_amplitude > 0:
            # 基于应力幅值的疲劳寿命估算
            N = (fatigue_strength_coefficient / stress_amplitude) ** (1 / abs(fatigue_strength_exponent))
        else:
            N = 1e10  # 极大值表示几乎不会疲劳
            
        # Palmgren-Miner线性累积损伤法则
        # D = Σ(ni/Ni) ，其中D为累积损伤，ni为实际循环次数，Ni为对应应力下的疲劳寿命
        damage_per_cycle = 1.0 / N if N > 0 else 0
        total_damage = damage_per_cycle * cycles
        
        # 更新疲劳状态
        current_fatigue = self.state['fatigue']
        new_fatigue = min(1.0, current_fatigue + total_damage)
        self.update_state(fatigue=new_fatigue)
        
        # 记录疲劳历史
        current_time = time.time()
        self.history['fatigue_history'].append((total_damage, current_time))
        if len(self.history['fatigue_history']) > 100:
            self.history['fatigue_history'].pop(0)
        
        return {
            'damage_per_cycle': damage_per_cycle,
            'total_damage': total_damage,
            'fatigue_life_cycles': N,
            'new_fatigue_level': new_fatigue
        }
        
    def get_fatigue_stats(self):
        """
        获取疲劳统计数据
        
        Returns:
            dict: 疲劳统计数据
        """
        if not self.history['fatigue_history']:
            return {'total_fatigue_damage': 0.0, 'average_fatigue_rate': 0.0}
            
        total_damage = sum([damage for damage, _ in self.history['fatigue_history']])
        avg_fatigue_rate = total_damage / len(self.history['fatigue_history'])
        
        return {
            'total_fatigue_damage': total_damage,
            'average_fatigue_rate': avg_fatigue_rate,
            'current_fatigue_level': self.state['fatigue']
        }
        
    def calculate_electrical_effect(self, time_delta):
        """
        计算电学效应
        
        Args:
            time_delta (float): 时间增量
            
        Returns:
            float: 电荷变化
        """
        conductivity = self.properties['electrical_conductivity']
        charge_accumulation = self.properties.get('charge_accumulation', 0.0)
        
        # 电荷变化 = 积累率 * 时间 - 传导率 * 当前电荷 * 时间
        charge_change = charge_accumulation * time_delta
        if self.state['charge'] != 0 and conductivity > 0:
            charge_change -= conductivity * self.state['charge'] * time_delta
            
        return charge_change
        
    def calculate_fluid_dynamics(self, fluid_velocity, fluid_density, time_delta):
        """
        计算流体动力学效应
        
        Args:
            fluid_velocity (Vec3): 流体速度
            fluid_density (float): 流体密度
            time_delta (float): 时间增量
            
        Returns:
            dict: 流体动力学结果
        """
        # 材质属性
        drag_coefficient = self.properties.get('drag_coefficient', 0.5)
        lift_coefficient = self.properties.get('lift_coefficient', 0.1)
        surface_area = self.properties.get('surface_area', 1.0)
        
        # 相对速度
        relative_velocity = fluid_velocity  # 简化处理，假设材质相对静止
        speed = relative_velocity.length()
        
        # 阻力计算 (D = 0.5 * ρ * v² * Cd * A)
        drag_force = 0.5 * fluid_density * speed * speed * drag_coefficient * surface_area if speed > 0 else 0.0
        
        # 升力计算 (L = 0.5 * ρ * v² * Cl * A)
        # 简化处理，假设升力方向为垂直于流体流动方向
        lift_force = 0.5 * fluid_density * speed * speed * lift_coefficient * surface_area if speed > 0 else 0.0
        
        # 浮力计算
        material_volume = self.properties.get('density', 1000.0) / fluid_density  # 简化体积计算
        buoyancy_force = fluid_density * 9.81 * material_volume
        
        # 更新湿润状态（与流体接触）
        wetness_increase = min(1.0, speed * 0.001 * time_delta)
        self.update_state(wetness=min(1.0, self.state['wetness'] + wetness_increase))
        
        return {
            'drag_force': drag_force,
            'lift_force': lift_force,
            'buoyancy_force': buoyancy_force,
            'wetness_increase': wetness_increase
        }
        
    def calculate_chemical_reaction(self, chemical_composition, temperature=None, time_delta=1.0):
        """
        计算化学反应效应
        
        Args:
            chemical_composition (dict): 化学成分 {'acid': float, 'base': float, 'oxidizer': float}
            temperature (float): 温度（可选，使用当前温度）
            time_delta (float): 时间增量
            
        Returns:
            dict: 化学反应结果
        """
        temp = temperature if temperature is not None else self.state['temperature']
        
        # 材质抗性
        chemical_resistance = self.properties.get('chemical_resistance', 1.0)
        
        # 各类化学物质的影响
        acid_concentration = chemical_composition.get('acid', 0.0)
        base_concentration = chemical_composition.get('base', 0.0)
        oxidizer_concentration = chemical_composition.get('oxidizer', 0.0)
        
        # 腐蚀速率计算
        corrosion_rate = self.properties.get('corrosion_rate', 0.0)
        
        # 酸腐蚀
        acid_damage = acid_concentration * (1.0 - chemical_resistance) * corrosion_rate * time_delta
        # 碱腐蚀
        base_damage = base_concentration * (1.0 - chemical_resistance) * corrosion_rate * 0.5 * time_delta
        # 氧化
        oxidation_damage = oxidizer_concentration * (1.0 - chemical_resistance) * 0.1 * time_delta
        
        # 温度加速效应
        temperature_factor = 1.0
        if temp > 25:  # 室温以上
            temperature_factor = 1.0 + (temp - 25) * 0.02  # 每度增加2%反应速率
            
        total_damage = (acid_damage + base_damage + oxidation_damage) * temperature_factor
        
        # 更新污染状态
        contamination_increase = min(1.0, total_damage * 0.1)
        self.update_state(contamination=min(1.0, self.state['contamination'] + contamination_increase))
        
        # 更新磨损状态
        wear_increase = min(1.0, total_damage)
        self.update_state(wear=min(1.0, self.state['wear'] + wear_increase))
        
        # 记录化学反应历史
        current_time = time.time()
        self.history['chemical_history'].append((total_damage, current_time))
        if len(self.history['chemical_history']) > 100:
            self.history['chemical_history'].pop(0)
        
        return {
            'acid_damage': acid_damage * temperature_factor,
            'base_damage': base_damage * temperature_factor,
            'oxidation_damage': oxidation_damage * temperature_factor,
            'total_damage': total_damage,
            'contamination_increase': contamination_increase,
            'wear_increase': wear_increase
        }
        
    def get_chemical_stats(self):
        """
        获取化学反应统计数据
        
        Returns:
            dict: 化学反应统计数据
        """
        if not self.history['chemical_history']:
            return {'total_chemical_damage': 0.0, 'average_chemical_rate': 0.0}
            
        total_damage = sum([damage for damage, _ in self.history['chemical_history']])
        avg_chemical_rate = total_damage / len(self.history['chemical_history'])
        
        return {
            'total_chemical_damage': total_damage,
            'average_chemical_rate': avg_chemical_rate,
            'current_contamination_level': self.state['contamination']
        }
        
    def check_failure_criteria(self, stress_tensor, strain_tensor=None):
        """
        检查材质失效准则
        
        Args:
            stress_tensor (list): 应力张量 [σxx, σyy, σzz, σxy, σyz, σzx]
            strain_tensor (list): 应变张量 [εxx, εyy, εzz, εxy, εyz, εzx]（可选）
            
        Returns:
            dict: 失效分析结果
        """
        # 材质强度参数
        tensile_strength = self.properties.get('tensile_strength', 1000.0)
        compressive_strength = self.properties.get('compressive_strength', 1000.0)
        shear_strength = self.properties.get('shear_strength', 500.0)
        fatigue_limit = self.properties.get('fatigue_limit', 200.0)
        
        # 提取应力分量
        sigma_xx, sigma_yy, sigma_zz = stress_tensor[0], stress_tensor[1], stress_tensor[2]
        sigma_xy, sigma_yz, sigma_zx = stress_tensor[3], stress_tensor[4], stress_tensor[5]
        
        # 计算主应力
        # 简化处理，只计算最大主应力
        max_principal_stress = max(sigma_xx, sigma_yy, sigma_zz)
        min_principal_stress = min(sigma_xx, sigma_yy, sigma_zz)
        
        # 计算等效应力（von Mises应力）
        deviatoric_stress = [
            sigma_xx - (sigma_xx + sigma_yy + sigma_zz) / 3,
            sigma_yy - (sigma_xx + sigma_yy + sigma_zz) / 3,
            sigma_zz - (sigma_xx + sigma_yy + sigma_zz) / 3,
            sigma_xy, sigma_yz, sigma_zx
        ]
        
        von_mises_stress = math.sqrt(
            0.5 * (
                deviatoric_stress[0]**2 + deviatoric_stress[1]**2 + deviatoric_stress[2]**2 +
                2 * (deviatoric_stress[3]**2 + deviatoric_stress[4]**2 + deviatoric_stress[5]**2)
            )
        )
        
        # 检查各种失效准则
        failures = {}
        
        # 1. 最大拉应力准则
        if max_principal_stress > tensile_strength:
            failures['tensile_failure'] = {
                'safety_factor': tensile_strength / max_principal_stress if max_principal_stress > 0 else 0,
                'excess_stress': max_principal_stress - tensile_strength
            }
            
        # 2. 最大压应力准则
        if min_principal_stress < -compressive_strength:
            failures['compressive_failure'] = {
                'safety_factor': compressive_strength / abs(min_principal_stress) if min_principal_stress < 0 else 0,
                'excess_stress': abs(min_principal_stress) - compressive_strength
            }
            
        # 3. 最大剪应力准则（Tresca准则）
        max_shear_stress = (max_principal_stress - min_principal_stress) / 2
        if max_shear_stress > shear_strength:
            failures['shear_failure'] = {
                'safety_factor': shear_strength / max_shear_stress if max_shear_stress > 0 else 0,
                'excess_stress': max_shear_stress - shear_strength
            }
            
        # 4. von Mises失效准则
        if von_mises_stress > tensile_strength:  # 简化处理，使用拉伸强度作为屈服强度
            failures['von_mises_failure'] = {
                'safety_factor': tensile_strength / von_mises_stress if von_mises_stress > 0 else 0,
                'excess_stress': von_mises_stress - tensile_strength
            }
            
        # 5. 疲劳失效准则
        current_fatigue = self.state['fatigue']
        if current_fatigue > 0.9:  # 疲劳度超过90%时可能发生疲劳失效
            fatigue_damage = current_fatigue * fatigue_limit
            if von_mises_stress > fatigue_limit:
                failures['fatigue_failure'] = {
                    'safety_factor': fatigue_limit / von_mises_stress if von_mises_stress > 0 else 0,
                    'fatigue_level': current_fatigue
                }
                
        # 6. 蠕变失效准则（高温下）
        temperature = self.state['temperature']
        if temperature > 0.5 * self.properties.get('melting_point', 1000.0):  # 超过熔点的一半
            creep_threshold = tensile_strength * 0.1  # 蠕变阈值
            if von_mises_stress > creep_threshold:
                failures['creep_failure'] = {
                    'temperature_factor': temperature / self.properties.get('melting_point', 1000.0),
                    'stress_ratio': von_mises_stress / creep_threshold
                }
                
        # 更新应力历史
        current_time = time.time()
        self.history['stress_history'].append((von_mises_stress, current_time))
        if len(self.history['stress_history']) > 100:
            self.history['stress_history'].pop(0)
            
        # 更新应力状态
        self.update_state(stress=max(von_mises_stress, self.state['stress']))
        
        return {
            'principal_stresses': [max_principal_stress, min_principal_stress],
            'von_mises_stress': von_mises_stress,
            'failures': failures,
            'safety_margins': self._calculate_safety_margins(
                max_principal_stress, min_principal_stress, von_mises_stress,
                tensile_strength, compressive_strength, shear_strength
            )
        }
        
    def _calculate_safety_margins(self, max_stress, min_stress, von_mises_stress,
                                 tensile_strength, compressive_strength, shear_strength):
        """
        计算安全裕度
        
        Args:
            max_stress (float): 最大主应力
            min_stress (float): 最小主应力
            von_mises_stress (float): von Mises应力
            tensile_strength (float): 抗拉强度
            compressive_strength (float): 抗压强度
            shear_strength (float): 抗剪强度
            
        Returns:
            dict: 安全裕度
        """
        safety_margins = {}
        
        # 拉伸安全裕度
        if max_stress > 0:
            safety_margins['tensile'] = tensile_strength / max_stress if max_stress > 0 else float('inf')
        else:
            safety_margins['tensile'] = float('inf')
            
        # 压缩安全裕度
        if min_stress < 0:
            safety_margins['compressive'] = compressive_strength / abs(min_stress) if min_stress < 0 else float('inf')
        else:
            safety_margins['compressive'] = float('inf')
            
        # 剪切安全裕度
        max_shear = (max_stress - min_stress) / 2
        safety_margins['shear'] = shear_strength / max_shear if max_shear > 0 else float('inf')
        
        # von Mises安全裕度
        safety_margins['von_mises'] = tensile_strength / von_mises_stress if von_mises_stress > 0 else float('inf')
        
        return safety_margins
        
    def simulate_fracture(self, impact_energy, impact_location):
        """
        模拟材质断裂
        
        Args:
            impact_energy (float): 撞击能量
            impact_location (Point3): 撞击位置
            
        Returns:
            dict: 断裂模拟结果
        """
        # 材质韧性参数
        fracture_toughness = self.properties.get('fracture_toughness', 50.0)
        toughness = self.properties.get('toughness', 0.1)
        
        # 计算断裂概率
        # 基于能量密度和材质韧性
        critical_energy = fracture_toughness * 100  # 简化的临界能量
        energy_density = impact_energy / (self.properties.get('density', 1000.0) * 0.001)  # 简化的能量密度
        
        fracture_probability = 1.0 - math.exp(-energy_density / critical_energy)
        
        # 考虑材质韧性降低断裂概率
        fracture_probability *= (1.0 - toughness)
        
        # 考虑已有损伤状态
        current_wear = self.state['wear']
        current_fatigue = self.state['fatigue']
        fracture_probability *= (1.0 + current_wear * 0.5 + current_fatigue * 0.3)
        
        # 确定是否发生断裂
        import random
        fracture_occurred = random.random() < min(1.0, fracture_probability)
        
        if fracture_occurred:
            # 计算断裂严重程度
            severity = min(1.0, energy_density / critical_energy)
            
            # 更新材质状态
            self.update_state(
                wear=min(1.0, self.state['wear'] + severity * 0.3),
                stress=max(0.0, self.state['stress'] - severity * 100),  # 断裂释放应力
                fatigue=min(1.0, self.state['fatigue'] + severity * 0.2)
            )
            
            # 记录断裂事件
            current_time = time.time()
            fracture_event = {
                'time': current_time,
                'energy': impact_energy,
                'location': impact_location,
                'severity': severity,
                'probability': fracture_probability
            }
            
            if 'fracture_history' not in self.history:
                self.history['fracture_history'] = []
                
            self.history['fracture_history'].append(fracture_event)
            if len(self.history['fracture_history']) > 50:
                self.history['fracture_history'].pop(0)
                
            return {
                'fracture_occurred': True,
                'severity': severity,
                'probability': fracture_probability,
                'critical_energy': critical_energy,
                'energy_density': energy_density,
                'fracture_event': fracture_event
            }
        else:
            return {
                'fracture_occurred': False,
                'probability': fracture_probability,
                'critical_energy': critical_energy,
                'energy_density': energy_density
            }
            
    def get_structural_integrity(self):
        """
        获取结构完整性评估
        
        Returns:
            dict: 结构完整性评估结果
        """
        # 综合评估各种损伤因素
        wear_factor = 1.0 - self.state['wear']
        fatigue_factor = 1.0 - self.state['fatigue']
        contamination_factor = 1.0 - self.state['contamination'] * 0.5
        stress_factor = max(0.1, 1.0 - self.state['stress'] / 10000.0)  # 假设10000为临界应力
        
        # 结构完整性 = 各因素加权平均
        integrity = (
            wear_factor * 0.3 +
            fatigue_factor * 0.3 +
            contamination_factor * 0.2 +
            stress_factor * 0.2
        )
        
        # 确保完整性在合理范围内
        integrity = max(0.0, min(1.0, integrity))
        
        # 评估等级
        if integrity > 0.9:
            integrity_level = "Excellent"
        elif integrity > 0.7:
            integrity_level = "Good"
        elif integrity > 0.5:
            integrity_level = "Fair"
        elif integrity > 0.3:
            integrity_level = "Poor"
        else:
            integrity_level = "Critical"
            
        return {
            'integrity': integrity,
            'integrity_level': integrity_level,
            'factors': {
                'wear_factor': wear_factor,
                'fatigue_factor': fatigue_factor,
                'contamination_factor': contamination_factor,
                'stress_factor': stress_factor
            },
            'recommendations': self._generate_maintenance_recommendations(integrity)
        }
        
    def _generate_maintenance_recommendations(self, integrity):
        """
        生成维护建议
        
        Args:
            integrity (float): 结构完整性
            
        Returns:
            list: 维护建议列表
        """
        recommendations = []
        
        if integrity < 0.3:
            recommendations.append("URGENT: Immediate replacement required")
        elif integrity < 0.5:
            recommendations.append("Replace as soon as possible")
        elif integrity < 0.7:
            recommendations.append("Schedule inspection and maintenance")
            
        # 基于具体因素的建议
        if self.state['wear'] > 0.7:
            recommendations.append("High wear detected - consider replacement")
        if self.state['fatigue'] > 0.8:
            recommendations.append("High fatigue level - reduce load or replace")
        if self.state['contamination'] > 0.6:
            recommendations.append("High contamination - cleaning recommended")
        if self.state['stress'] > 5000:  # 假设5000为高应力阈值
            recommendations.append("High stress levels detected - check loading conditions")
            
        return recommendations
        
    def get_history_stats(self):
        """
        获取历史统计数据
        
        Returns:
            dict: 历史统计数据
        """
        stats = {}
        
        # 温度统计
        if self.history['temperature_history']:
            temps = [temp for temp, _ in self.history['temperature_history']]
            stats['temperature'] = {
                'min': min(temps),
                'max': max(temps),
                'avg': sum(temps) / len(temps)
            }
            
        # 磨损统计
        if self.history['wear_history']:
            wears = [wear for wear, _ in self.history['wear_history']]
            stats['wear'] = {
                'min': min(wears),
                'max': max(wears),
                'avg': sum(wears) / len(wears)
            }
            
        # 应力统计
        if self.history['stress_history']:
            stresses = [stress for stress, _ in self.history['stress_history']]
            stats['stress'] = {
                'min': min(stresses),
                'max': max(stresses),
                'avg': sum(stresses) / len(stresses)
            }
            
        return stats
        
    def to_dict(self):
        """
        将材质转换为字典格式
        
        Returns:
            dict: 材质属性字典
        """
        # 转换不可序列化的对象
        props = self.properties.copy()
        if isinstance(props['anisotropic_friction'], Vec3):
            props['anisotropic_friction'] = [
                props['anisotropic_friction'].getX(),
                props['anisotropic_friction'].getY(),
                props['anisotropic_friction'].getZ()
            ]
        if isinstance(props['color'], Vec4):
            props['color'] = [
                props['color'].getX(),
                props['color'].getY(),
                props['color'].getZ(),
                props['color'].getW()
            ]
        if isinstance(props['surface_velocity'], Vec3):
            props['surface_velocity'] = [
                props['surface_velocity'].getX(),
                props['surface_velocity'].getY(),
                props['surface_velocity'].getZ()
            ]
        if isinstance(props['emissive'], Vec3):
            props['emissive'] = [
                props['emissive'].getX(),
                props['emissive'].getY(),
                props['emissive'].getZ()
            ]
            
        # 转换交互矩阵
        interaction_matrix = {}
        for key, value in self.interaction_matrix.items():
            interaction_matrix[key] = value
            
        # 转换历史记录
        history = {}
        for key, value in self.history.items():
            history[key] = [(v, t) for v, t in value]
            
        return {
            'name': self.name,
            'material_type': self.material_type,
            'properties': props,
            'state': self.state.copy(),
            'interaction_matrix': interaction_matrix,
            'history': history,
            'creation_time': self.creation_time
        }
        
    @classmethod
    def from_dict(cls, data):
        """
        从字典创建材质对象
        
        Args:
            data (dict): 材质数据字典
            
        Returns:
            PhysicsMaterial: 材质对象
        """
        # 转换序列化数据回对象
        properties = data.get('properties', {}).copy()
        if 'anisotropic_friction' in properties and isinstance(properties['anisotropic_friction'], list):
            properties['anisotropic_friction'] = Vec3(*properties['anisotropic_friction'])
        if 'color' in properties and isinstance(properties['color'], list):
            properties['color'] = Vec4(*properties['color'])
        if 'surface_velocity' in properties and isinstance(properties['surface_velocity'], list):
            properties['surface_velocity'] = Vec3(*properties['surface_velocity'])
        if 'emissive' in properties and isinstance(properties['emissive'], list):
            properties['emissive'] = Vec3(*properties['emissive'])
            
        material = cls(data['name'], properties, data.get('material_type', cls.TYPE_DEFAULT))
        material.state = data.get('state', material.state)
        material.creation_time = data.get('creation_time', time.time())
        
        # 恢复交互矩阵
        interaction_matrix = data.get('interaction_matrix', {})
        for key, value in interaction_matrix.items():
            material.interaction_matrix[key] = value
            
        # 恢复历史记录
        history = data.get('history', {})
        for key, value in history.items():
            if key in material.history:
                material.history[key] = [(v, t) for v, t in value]
            
        return material
        
    def save_to_file(self, filepath):
        """
        保存材质到文件
        
        Args:
            filepath (str): 文件路径
        """
        data = self.to_dict()
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=2, ensure_ascii=False)
            
    @classmethod
    def load_from_file(cls, filepath):
        """
        从文件加载材质
        
        Args:
            filepath (str): 文件路径
            
        Returns:
            PhysicsMaterial: 材质对象
        """
        with open(filepath, 'r', encoding='utf-8') as f:
            data = json.load(f)
        return cls.from_dict(data)
        
    def __str__(self):
        """
        字符串表示
        """
        return f"PhysicsMaterial('{self.name}', type={self.material_type}, friction={self.properties['friction']}, restitution={self.properties['restitution']})"
        
    def __repr__(self):
        """
        详细字符串表示
        """
        return self.__str__()


# 预定义常用材质
MATERIALS = {
    'concrete': PhysicsMaterial('concrete', material_type=PhysicsMaterial.TYPE_CONCRETE, properties={
        'friction': 0.7,
        'restitution': 0.1,
        'density': 2400.0,
        'color': Vec4(0.6, 0.6, 0.6, 1.0),
        'roughness': 0.9,
        'weather_resistance': 0.9,
        'compressive_strength': 20000.0,
        'tensile_strength': 2000.0,
        'shear_strength': 1000.0,
        'thermal_conductivity': 1.0,
        'specific_heat': 880.0,
        'thermal_expansion': 0.00001,
        'fatigue_strength_coefficient': 8000.0,
        'fatigue_strength_exponent': -0.1,
    }),
    'wood': PhysicsMaterial('wood', material_type=PhysicsMaterial.TYPE_WOOD, properties={
        'friction': 0.4,
        'restitution': 0.2,
        'density': 700.0,
        'color': Vec4(0.8, 0.6, 0.4, 1.0),
        'thermal_conductivity': 0.1,
        'flammability': 0.8,
        'roughness': 0.7,
        'aging_rate': 0.05,
        'tensile_strength': 1000.0,
        'compressive_strength': 5000.0,
        'shear_strength': 800.0,
        'specific_heat': 1700.0,
        'thermal_expansion': 0.000005,
        'hardness': 0.6,
        'chemical_resistance': 0.7,
    }),
    'metal': PhysicsMaterial('metal', material_type=PhysicsMaterial.TYPE_METAL, properties={
        'friction': 0.3,
        'restitution': 0.4,
        'density': 7800.0,
        'color': Vec4(0.7, 0.7, 0.8, 1.0),
        'thermal_conductivity': 80.0,
        'electrical_conductivity': 1e7,
        'roughness': 0.3,
        'metallic': 1.0,
        'specular': 0.9,
        'corrosion_rate': 0.1,
        'tensile_strength': 40000.0,
        'compressive_strength': 40000.0,
        'shear_strength': 20000.0,
        'specific_heat': 490.0,
        'thermal_expansion': 0.000012,
        'fatigue_limit': 20000.0,
        'fracture_toughness': 100.0,
        'hardness': 0.9,
    }),
    'rubber': PhysicsMaterial('rubber', material_type=PhysicsMaterial.TYPE_RUBBER, properties={
        'friction': 0.9,
        'restitution': 0.8,
        'density': 1200.0,
        'color': Vec4(0.2, 0.2, 0.2, 1.0),
        'roughness': 0.8,
        'specular': 0.1,
        'elasticity': 0.9,
        'tensile_strength': 500.0,
        'compressive_strength': 1000.0,
        'shear_strength': 300.0,
        'specific_heat': 1500.0,
        'thermal_conductivity': 0.2,
        'damping': 0.3,
        'toughness': 0.2,
    }),
    'ice': PhysicsMaterial('ice', material_type=PhysicsMaterial.TYPE_ICE, properties={
        'friction': 0.03,
        'restitution': 0.1,
        'density': 917.0,
        'color': Vec4(0.8, 0.9, 1.0, 0.8),
        'thermal_conductivity': 2.2,
        'roughness': 0.1,
        'specular': 0.9,
        'melting_point': 0.0,
        'compressive_strength': 500.0,
        'tensile_strength': 100.0,
        'specific_heat': 2100.0,
        'thermal_expansion': 0.00005,
    }),
    'sand': PhysicsMaterial('sand', material_type=PhysicsMaterial.TYPE_SAND, properties={
        'friction': 0.6,
        'restitution': 0.05,
        'density': 1600.0,
        'color': Vec4(0.9, 0.8, 0.6, 1.0),
        'roughness': 0.9,
        'flowability': 0.8,
        'compressive_strength': 100.0,
        'tensile_strength': 10.0,
        'specific_heat': 830.0,
        'thermal_conductivity': 0.25,
    }),
    'water': PhysicsMaterial('water', material_type=PhysicsMaterial.TYPE_WATER, properties={
        'friction': 0.1,
        'restitution': 0.0,
        'density': 1000.0,
        'color': Vec4(0.0, 0.5, 1.0, 0.7),
        'viscosity': 0.001,
        'surface_tension': 0.072,
        'buoyancy': 1.0,
        'transparency': 0.8,
        'compressive_strength': 2000000.0,  # 水几乎不可压缩
        'specific_heat': 4186.0,
        'thermal_conductivity': 0.6,
    }),
    'glass': PhysicsMaterial('glass', material_type=PhysicsMaterial.TYPE_GLASS, properties={
        'friction': 0.2,
        'restitution': 0.9,
        'density': 2500.0,
        'color': Vec4(0.8, 0.9, 1.0, 0.3),
        'roughness': 0.1,
        'specular': 0.95,
        'transparency': 0.9,
        'fragility': 0.8,
        'tensile_strength': 7000.0,
        'compressive_strength': 10000.0,
        'shear_strength': 3000.0,
        'specific_heat': 840.0,
        'thermal_conductivity': 1.0,
        'fracture_toughness': 20.0,
    }),
    'flesh': PhysicsMaterial('flesh', material_type=PhysicsMaterial.TYPE_FLESH, properties={
        'friction': 0.8,
        'restitution': 0.1,
        'density': 1060.0,
        'color': Vec4(0.9, 0.7, 0.7, 1.0),
        'roughness': 0.6,
        'toxicity': 0.1,
        'elasticity': 0.3,
        'tensile_strength': 50.0,
        'compressive_strength': 200.0,
        'shear_strength': 30.0,
        'specific_heat': 3500.0,
        'thermal_conductivity': 0.3,
        'damping': 0.2,
    }),
    'plastic': PhysicsMaterial('plastic', material_type=PhysicsMaterial.TYPE_PLASTIC, properties={
        'friction': 0.4,
        'restitution': 0.3,
        'density': 1200.0,
        'color': Vec4(0.9, 0.9, 0.9, 1.0),
        'roughness': 0.5,
        'specular': 0.6,
        'flammability': 0.3,
        'elasticity': 0.5,
        'tensile_strength': 5000.0,
        'compressive_strength': 8000.0,
        'shear_strength': 3000.0,
        'specific_heat': 1300.0,
        'thermal_conductivity': 0.2,
        'chemical_resistance': 0.8,
    }),
    'cloth': PhysicsMaterial('cloth', material_type=PhysicsMaterial.TYPE_CLOTH, properties={
        'friction': 0.6,
        'restitution': 0.1,
        'density': 500.0,
        'color': Vec4(0.8, 0.8, 0.8, 1.0),
        'roughness': 0.8,
        'flexibility': 0.9,
        'breathability': 0.7,
        'tensile_strength': 200.0,
        'specific_heat': 1200.0,
        'thermal_conductivity': 0.05,
        'damping': 0.1,
    }),
    'leather': PhysicsMaterial('leather', material_type=PhysicsMaterial.TYPE_LEATHER, properties={
        'friction': 0.5,
        'restitution': 0.2,
        'density': 900.0,
        'color': Vec4(0.5, 0.3, 0.2, 1.0),
        'roughness': 0.6,
        'durability': 0.8,
        'water_resistance': 0.6,
        'tensile_strength': 800.0,
        'specific_heat': 1500.0,
        'thermal_conductivity': 0.15,
        'aging_rate': 0.02,
    }),
    'stone': PhysicsMaterial('stone', material_type=PhysicsMaterial.TYPE_STONE, properties={
        'friction': 0.7,
        'restitution': 0.1,
        'density': 2600.0,
        'color': Vec4(0.7, 0.7, 0.7, 1.0),
        'roughness': 0.8,
        'hardness': 0.9,
        'weather_resistance': 0.95,
        'tensile_strength': 3000.0,
        'compressive_strength': 20000.0,
        'shear_strength': 1000.0,
        'specific_heat': 800.0,
        'thermal_conductivity': 2.0,
    }),
    'snow': PhysicsMaterial('snow', material_type=PhysicsMaterial.TYPE_SNOW, properties={
        'friction': 0.2,
        'restitution': 0.05,
        'density': 100.0,
        'color': Vec4(1.0, 1.0, 1.0, 0.9),
        'roughness': 0.3,
        'melting_point': 0.0,
        'compressibility': 0.5,
        'tensile_strength': 50.0,
        'specific_heat': 2100.0,
        'thermal_conductivity': 0.3,
    }),
    'mud': PhysicsMaterial('mud', material_type=PhysicsMaterial.TYPE_MUD, properties={
        'friction': 0.8,
        'restitution': 0.01,
        'density': 1300.0,
        'color': Vec4(0.4, 0.3, 0.2, 1.0),
        'roughness': 0.9,
        'stickiness': 0.7,
        'viscosity': 0.1,
        'tensile_strength': 20.0,
        'specific_heat': 1800.0,
        'thermal_conductivity': 0.8,
    }),
}


# 材质交互预设
MATERIAL_INTERACTIONS = {
    ('metal', 'metal'): 1.2,
    ('metal', 'wood'): 0.8,
    ('metal', 'concrete'): 0.9,
    ('metal', 'rubber'): 1.1,
    ('wood', 'wood'): 1.0,
    ('wood', 'concrete'): 0.7,
    ('concrete', 'concrete'): 1.0,
    ('rubber', 'rubber'): 1.3,
    ('ice', 'ice'): 0.1,
    ('ice', 'metal'): 0.15,
    ('sand', 'sand'): 0.9,
    ('water', 'metal'): 0.1,
    ('water', 'wood'): 0.2,
    ('glass', 'glass'): 0.95,
    ('plastic', 'plastic'): 0.6,
    ('cloth', 'cloth'): 0.8,
    ('leather', 'leather'): 0.7,
    ('stone', 'stone'): 0.85,
    ('snow', 'snow'): 0.3,
    ('mud', 'mud'): 0.4,
}