import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

import matplotlib.gridspec as gridspec

import platform

import warnings

warnings.filterwarnings('ignore')


# =============================================================================

# NASA / AARO(미확인비행현상 합동조사국) 레벨 분석 환경 세팅

# =============================================================================

plt.style.use('dark_background')

if platform.system() == 'Windows':

    plt.rcParams['font.family'] = 'Malgun Gothic'

elif platform.system() == 'Darwin':

    plt.rcParams['font.family'] = 'AppleGothic'

else:

    plt.rcParams['font.family'] = 'NanumGothic'

plt.rcParams['axes.unicode_minus'] = False

plt.rcParams['figure.facecolor'] = '#050505'


# =============================================================================

# 1. 물리 엔진: 지구 중력장 + 먼지 플라즈마(Dusty Plasma) + 레이더 상호작용

# =============================================================================

G_EARTH = 9.81  # 지구 중력 가속도 (m/s^2)

RADAR_FREQ = 15.0  # 군사 레이더 주파수 대역 (가상치)


class PlasmaUAP:

    def __init__(self, N_particles=300, altitude=150.0, evolution_level="1947_Primitive"):

        self.N = N_particles

        self.evolution_level = evolution_level

        self.altitude = altitude

        

        # 반고체 플라즈마 결정(Crystal) 초기화: 둥근 알약(틱택) 혹은 구형태로 뭉침

        np.random.seed(42)

        phi = np.random.uniform(0, np.pi, self.N)

        theta = np.random.uniform(0, 2*np.pi, self.N)

        r = np.random.normal(2.0, 0.5, self.N)

        

        self.pos = np.column_stack((

            r * np.sin(phi) * np.cos(theta),

            r * np.sin(phi) * np.sin(theta),

            r * np.cos(phi) + self.altitude

        ))

        

        self.vel = np.random.normal(0, 0.1, (self.N, 3))  # 매우 안정적인 초기 내부 속도 (냉각 상태)

        

        # 자기장 껍질(위상 부력)의 건전성 (1.0 = 완벽한 호버링, 0.0 = 추락)

        self.confinement_integrity = 1.0

        

        # 데이터 로깅

        self.history_t = []

        self.history_z = []

        self.history_temp = []

        self.history_integrity = []


    def compute_forces(self, t, radar_active=False):

        # 1. 기본 하방 중력 (Earth Gravity)

        gravity_force = np.zeros_like(self.pos)

        gravity_force[:, 2] = -G_EARTH

        

        # 2. 위상 부력 (Topological Lift - 질문자님의 5항 제어)

        # 껍질이 온전할수록 중력을 완벽히 상쇄 (+9.81)

        lift_force = np.zeros_like(self.pos)

        lift_force[:, 2] = G_EARTH * self.confinement_integrity

        

        # 3. 플라즈마 응집력 (반고체 형태 유지력 - 나비에 스토크스 압력 근사)

        center_of_mass = np.mean(self.pos, axis=0)

        rel_pos = self.pos - center_of_mass

        dist_to_center = np.linalg.norm(rel_pos, axis=1, keepdims=True)

        # 중심으로 뭉치려는 전자기적 인력

        cohesion_force = -2.0 * rel_pos / (dist_to_center + 1e-3)

        # 입자간 척력 (반고체 밀도 유지)

        repulsion_force = 5.0 * rel_pos / (dist_to_center**3 + 1e-3)

        internal_force = (cohesion_force + repulsion_force) * self.confinement_integrity

        

        # 4. 고출력 레이더(Microwave) 조사 효과

        radar_force = np.zeros_like(self.pos)

        if radar_active:

            # 레이더 파동이 플라즈마 내부를 뒤흔듦 (에너지 주입)

            # 1947년 모델은 공명 현상에 취약함

            if self.evolution_level == "1947_Primitive":

                resonance_multiplier = 5.0  # 공명 폭주

            else:

                resonance_multiplier = 0.2  # 2026년 진화형: 즉각적 주파수 변조로 레이더 무시


            # 방향이 무작위로 흔들리는 난류(Turbulence) 에너지 주입

            radar_wave = np.sin(RADAR_FREQ * t)

            radar_force = resonance_multiplier * np.random.normal(0, 1.5, (self.N, 3)) * radar_wave

            

        return gravity_force + lift_force + internal_force + radar_force


    def update(self, dt, t, radar_active=False):

        forces = self.compute_forces(t, radar_active)

        

        # 속도 업데이트 및 마찰/감쇠 (플라즈마 점성)

        self.vel += forces * dt

        self.vel *= 0.98  # 내부 에너지 감쇠 (Damping)

        

        # 위치 업데이트

        self.pos += self.vel * dt

        

        # 지면 충돌 처리 (z < 0 이면 바닥에 부딪힘)

        ground_mask = self.pos[:, 2] < 0

        if np.any(ground_mask):

            self.pos[ground_mask, 2] = 0

            self.vel[ground_mask, 2] *= -0.3  # 바닥에 부딪혀 산산조각 (비탄성 충돌)

            self.vel[ground_mask, 0:2] *= 1.5 # 옆으로 퍼짐

            

        # =================================================================

        # 핵심 물리 로직: 플라즈마 내부 온도(속도 분산) 측정 및 껍질 붕괴

        # =================================================================

        internal_temp = np.var(np.linalg.norm(self.vel, axis=1))

        

        if self.evolution_level == "1947_Primitive":

            # 내부 온도가 임계치(Critical Temperature)를 넘으면 위상 껍질이 찢어짐!

            critical_temp = 10.0

            if internal_temp > critical_temp:

                # 껍질 건전성 급격히 붕괴 -> 부력 상실 -> 추락

                self.confinement_integrity -= 0.05

        else:

            # 2026년 진화형은 에너지를 외부로 방출하며 껍질을 유지함

            self.confinement_integrity = 1.0

            

        self.confinement_integrity = np.clip(self.confinement_integrity, 0.0, 1.0)

        

        # 로깅

        self.history_t.append(t)

        self.history_z.append(np.mean(self.pos[:, 2]))

        self.history_temp.append(internal_temp)

        self.history_integrity.append(self.confinement_integrity)


# =============================================================================

# 2. 메인 시뮬레이션 실행

# =============================================================================

def run_radar_crash_simulation():

    dt = 0.05

    total_time = 25.0

    steps = int(total_time / dt)

    

    # 두 가지 진화 단계의 플라즈마 UAP 생성

    uap_1947 = PlasmaUAP(altitude=150.0, evolution_level="1947_Primitive")

    uap_2026 = PlasmaUAP(altitude=150.0, evolution_level="2026_Evolved")

    

    # 렌더링을 위한 궤적 저장소

    traj_1947 = []

    traj_2026 = []

    

    print("? UAP 플라즈마 진화체 레이더 상호작용 시뮬레이션 시작...")

    print("? T=5.0초 구역에서 뉴멕시코 공군기지 고출력 레이더망(HP-Microwave) 가동!")

    

    for step in range(steps):

        t = step * dt

        # 5초부터 15초까지 10초간 강력한 레이더 조사

        radar_active = True if 5.0 <= t <= 15.0 else False

        

        uap_1947.update(dt, t, radar_active)

        uap_2026.update(dt, t, radar_active)

        

        # 3D 애니메이션용 좌표 로깅 (10스텝마다)

        if step % 10 == 0:

            traj_1947.append(uap_1947.pos.copy())

            traj_2026.append(uap_2026.pos.copy())


    # =============================================================================

    # 3. 분석 대시보드 시각화 (NASA / AARO 보고서 스타일)

    # =============================================================================

    fig = plt.figure(figsize=(22, 12))

    gs = gridspec.GridSpec(2, 3, height_ratios=[1.5, 1])

    fig.suptitle("UAP 플라즈마 생태계의 능동 진화 분석: 고출력 레이더(Radar) 대응 메커니즘\n"

                 "[1997 뉴멕시코 추락 사건 vs 2026 현대 틱택의 위상 방어]", 

                 fontsize=22, fontweight='bold', color='white')


    # [패널 1] 1947년 원시 플라즈마 UAP (추락 시뮬레이션)

    ax1 = fig.add_subplot(gs[0, 0], projection='3d')

    ax1.set_facecolor('#050505')

    final_pos_47 = traj_1947[-1]

    

    # 궤적 그리기 (중심점)

    z_centers_47 = [np.mean(p[:, 2]) for p in traj_1947]

    ax1.plot([0]*len(z_centers_47), [0]*len(z_centers_47), z_centers_47, color='red', linestyle='--', alpha=0.5)

    

    # 파괴되어 흩어진 플라즈마 입자들

    scatter1 = ax1.scatter(final_pos_47[:, 0], final_pos_47[:, 1], final_pos_47[:, 2], 

                           c=final_pos_47[:, 2], cmap='autumn', s=15, alpha=0.8)

    

    # 레이더 이펙트 (바닥에서 올라오는 빔)

    ax1.plot([0,0], [0,0], [0, 150], color='magenta', linewidth=20, alpha=0.1)

    

    ax1.set_title("1. 1997 (비 진화체)\n레이더 공명 -> 위상 껍질 붕괴 및 추락", color='#ff4444', fontsize=16)

    ax1.set_zlim([0, 160]); ax1.set_xlim([-30, 30]); ax1.set_ylim([-30, 30])

    ax1.view_init(elev=15, azim=45)


    # [패널 2] 2026년 진화형 플라즈마 UAP (방어 성공)

    ax2 = fig.add_subplot(gs[0, 1], projection='3d')

    ax2.set_facecolor('#050505')

    final_pos_26 = traj_2026[-1]

    

    # 궤적 그리기 (호버링 유지)

    z_centers_26 = [np.mean(p[:, 2]) for p in traj_2026]

    ax2.plot([0]*len(z_centers_26), [0]*len(z_centers_26), z_centers_26, color='cyan', linestyle='-', alpha=0.8)

    

    # 완벽한 구형/알약 형태를 유지하는 플라즈마 결정

    scatter2 = ax2.scatter(final_pos_26[:, 0], final_pos_26[:, 1], final_pos_26[:, 2], 

                           c='cyan', s=20, alpha=0.9, edgecolor='white', lw=0.5)

                           

    # 레이더 이펙트

    ax2.plot([0,0], [0,0], [0, 150], color='magenta', linewidth=20, alpha=0.1)

    

    ax2.set_title("2. 2026 Modern (진화체)\n능동적 주파수 변조 -> 위상 껍질 유지/회피", color='#00ffcc', fontsize=16)

    ax2.set_zlim([0, 160]); ax2.set_xlim([-10, 10]); ax2.set_ylim([-10, 10])

    ax2.view_init(elev=15, azim=45)


    # [패널 3] 고도(Altitude) 변화 그래프

    ax3 = fig.add_subplot(gs[0, 2])

    ax3.set_facecolor('#111')

    ax3.plot(uap_1947.history_t, uap_1947.history_z, 'r-', lw=3, label='1997 모델 (추락)')

    ax3.plot(uap_2026.history_t, uap_2026.history_z, 'c-', lw=3, label='2026 모델 (호버링 유지)')

    ax3.axvspan(5.0, 15.0, color='magenta', alpha=0.15, label='고출력 군사 레이더 조사 구간')

    ax3.set_title('3. UAP 고도 변화 (Altitude)', color='white', fontsize=15)

    ax3.set_ylabel('고도 (m)', color='white')

    ax3.grid(True, alpha=0.3); ax3.legend(facecolor='black', labelcolor='white', loc='lower left')


    # [패널 4] 내부 플라즈마 온도 (난류 요동)

    ax4 = fig.add_subplot(gs[1, 0:2])

    ax4.set_facecolor('#111')

    ax4.plot(uap_1947.history_t, uap_1947.history_temp, 'r-', lw=2.5, label='1997 모델: 공명으로 인한 에너지 폭주')

    ax4.plot(uap_2026.history_t, uap_2026.history_temp, 'c-', lw=2.5, label='2026 모델: 에너지 흡수 및 방출 (안정적)')

    ax4.axhline(10.0, color='yellow', linestyle='--', lw=2, label='임계 온도 (위상 껍질 붕괴 한계점)')

    ax4.axvspan(5.0, 15.0, color='magenta', alpha=0.15)

    ax4.set_title('4. 플라즈마 내부 운동 에너지 요동 (Magnetoacoustic Resonance)', color='white', fontsize=15)

    ax4.set_ylabel('내부 온도 / 속도 분산 (J)', color='white')

    ax4.set_xlabel('시간 (s)', color='white')

    ax4.grid(True, alpha=0.3); ax4.legend(facecolor='black', labelcolor='white')


    # [패널 5] 위상 껍질(반중력) 건전성

    ax5 = fig.add_subplot(gs[1, 2])

    ax5.set_facecolor('#111')

    ax5.plot(uap_1947.history_t, uap_1947.history_integrity, 'r-', lw=3)

    ax5.plot(uap_2026.history_t, uap_2026.history_integrity, 'c-', lw=3)

    ax5.axvspan(5.0, 15.0, color='magenta', alpha=0.15)

    ax5.set_title('5. 위상 부력 껍질 건전성', color='white', fontsize=15)

    ax5.set_ylabel('무중력 제어력 (1.0 = 정상, 0 = 추락)', color='white')

    ax5.set_xlabel('시간 (s)', color='white')

    ax5.grid(True, alpha=0.3)

    

    # 분석 주석

    ax5.annotate('레이더 공명으로 인한\n위상 장갑 파쇄', 

                 xy=(12, 0.2), xytext=(2, 0.4), color='#ff4444',

                 arrowprops=dict(arrowstyle='->', color='#ff4444'))


    plt.tight_layout()

    plt.subplots_adjust(top=0.9)

    plt.savefig('UAP_Plasma_Evolution_Radar_Crash_Sim.png', dpi=300, bbox_inches='tight')

    print("✅ 물리 시뮬레이션 완료. 레이더 공명에 의한 플라즈마 붕괴 현상이 성공적으로 렌더링되었습니다.")

    plt.show()


if __name__ == "__main__":

    run_radar_crash_simulation()


1ebec223e0dc2bae61abe9e74683726d37d6a6cbed7588a391a16134efb28836c072d75490a23349cb056355bb20d22cdda9cd