# -*- coding: utf-8 -*-
"""
Created on Fri Sep  5 17:19:22 2025

@author: AKourgli
"""

# em_propagation_3d.py
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D    # nécessaire pour 3D
import matplotlib.animation as animation

# ---------- Paramètres physiques (modifiables) ----------
c = 3e8           # m/s
f = 1e9           # Hz (1 GHz)
lam = c / f
omega = 2 * np.pi * f
k = 2 * np.pi / lam

E0 = 10.0
H0 = E0 / 377.0   # impédance du vide   



# ---------- Discrétisation spatiale & temporelle ----------
num_wavelengths = 3        # afficher 2 λ le long de z
Nz = 50                    # nombre de points le long de z
z = np.linspace(0, num_wavelengths * lam, Nz)

frames_per_cycle = 30
fps = 20
dt = (1.0 / f) / frames_per_cycle
total_frames = frames_per_cycle * 3  # 3 cycles animés

# ---------- Figure 3D ----------
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

def setup_axes():
    ax.set_xlim(0, num_wavelengths * lam)
    ax.set_ylim(-1.2 * E0, 1.2 * E0)
    ax.set_zlim(-1.2 * H0, 1.2 * H0)
    ax.set_xlabel("z (m) — propagation")
    ax.set_ylabel("E (V/m) — direction x")
    ax.set_zlabel("H (A/m) — direction y")
    ax.set_title("Propagation d'une onde EM plane : E (rouge), H (bleu), k (vert)")
    ax.grid(True)

def animate(frame):
    ax.cla()
    setup_axes()
    t = frame * dt
    Ez = E0 * np.cos(k * z - omega * t)   # valeurs des extrémités de E
    Hz = H0 * np.cos(k * z - omega * t)   # valeurs des extrémités de H

    # Points le long de z
    X = z

    # ---- Tracé des courbes reliant les extrémités ----
    # Courbe pour E (rouge)
    ax.plot(X, Ez, np.zeros_like(z), 'r-', linewidth=2, label="E (x)")
    # Courbe pour H (bleu)
    ax.plot(X, np.zeros_like(z), Hz, 'b-', linewidth=2, label="H (y)")

    # ---- Option : tracer aussi les segments "barres" (facultatif)
    for i in range(len(z)):
        ax.plot([X[i], X[i]], [0, Ez[i]], [0, 0], 'r-', alpha=0.3)
        ax.plot([X[i], X[i]], [0, 0], [0, Hz[i]], 'b-', alpha=0.3)

    # Vecteur k (vert, direction de propagation)
    ax.plot([0, num_wavelengths * lam * 1], [0, 0], [0, 0], 'g-', linewidth=3, label="k")

    if frame == 0:
        ax.legend()

    return []


# Lancer l'animation
ani = animation.FuncAnimation(fig, animate, frames=total_frames, interval=1000//fps, blit=False)
plt.show()
