import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D


#始点の初期値
elev = 5.90
azim = -67.55

axis_font_size = 24
draw_lattice_vectors = False


def lattice_vectors(a, b, c, alpha, beta, gamma):
    alpha_r, beta_r, gamma_r = np.radians([alpha, beta, gamma])
    va = np.array([a, 0, 0])
    vb = np.array([b * np.cos(gamma_r), b * np.sin(gamma_r), 0])
    cx = c * np.cos(beta_r)
    cy = c * (np.cos(alpha_r) - np.cos(beta_r) * np.cos(gamma_r)) / np.sin(gamma_r)
    cz = np.sqrt(c**2 - cx**2 - cy**2)
    vc = np.array([cx, cy, cz])
    return va, vb, vc

def set_equal_aspect(ax, points):
    # 全軸の範囲を揃える
    xlim = [np.min(points[:,0]), np.max(points[:,0])]
    ylim = [np.min(points[:,1]), np.max(points[:,1])]
    zlim = [np.min(points[:,2]), np.max(points[:,2])]
    max_range = max(
        xlim[1] - xlim[0],
        ylim[1] - ylim[0],
        zlim[1] - zlim[0]
    ) / 2

    mid_x = np.mean(xlim)
    mid_y = np.mean(ylim)
    mid_z = np.mean(zlim)

    ax.set_xlim(mid_x - max_range, mid_x + max_range)
    ax.set_ylim(mid_y - max_range, mid_y + max_range)
    ax.set_zlim(mid_z - max_range, mid_z + max_range)
    ax.set_box_aspect([1,1,1])

def draw_cell(ax, va, vb, vc, origin, linewidth=0.5):
    # 8頂点
    p0 = origin
    p1 = origin + va
    p2 = origin + vb
    p3 = origin + vc
    p4 = origin + va + vb
    p5 = origin + va + vc
    p6 = origin + vb + vc
    p7 = origin + va + vb + vc
    verts = [p0, p1, p2, p3, p4, p5, p6, p7]

    # 辺の描画
    edges = [
        (0,1), (0,2), (0,3),
        (1,4), (1,5),
        (2,4), (2,6),
        (3,5), (3,6),
        (4,7), (5,7), (6,7)
    ]
    for i,j in edges:
        ax.plot(*zip(verts[i], verts[j]), color='black', linewidth=linewidth)


def draw_supercell(a, b, c, alpha, beta, gamma, nx=3, ny=3, nz=3):
    va, vb, vc = lattice_vectors(a, b, c, alpha, beta, gamma)
    fig = plt.figure(figsize=(8,6))
    ax = fig.add_subplot(111, projection='3d')
    ax.view_init(elev=elev, azim=azim)
    def on_draw(event):
        elev = ax.elev
        azim = ax.azim
        print(f"elev: {elev:.2f}, azim: {azim:.2f}")
    fig.canvas.mpl_connect('draw_event', on_draw)

    # 全セルの描画（細い黒線）
    for i in range(nx):
        for j in range(ny):
            for k in range(nz):
                offset = i * va + j * vb + k * vc
                draw_cell(ax, va, vb, vc, offset, linewidth=0.5)

    # 原点セルの強調（太い黒線）
    draw_cell(ax, va, vb, vc, np.array([0,0,0]), linewidth=2)

    # 基本ベクトルの描画
    if draw_lattice_vectors:
        for vec, label in zip([va, vb, vc], ['a', 'b', 'c']):
            ax.quiver(0, 0, 0, *vec, color='blue', linewidth=2, arrow_length_ratio=0.1)
            ax.text(*vec * 1.05, label, fontsize=axis_font_size, color='blue')

    # 軸・背景の削除
    ax.set_xticks([]); ax.set_yticks([]); ax.set_zticks([])
    ax.set_xticklabels([]); ax.set_yticklabels([]); ax.set_zticklabels([])
    ax.set_xlabel(''); ax.set_ylabel(''); ax.set_zlabel('')
    ax.grid(False)
    ax.xaxis.pane.set_visible(False)
    ax.yaxis.pane.set_visible(False)
    ax.zaxis.pane.set_visible(False)
    ax.xaxis.line.set_color((0,0,0,0))
    ax.yaxis.line.set_color((0,0,0,0))
    ax.zaxis.line.set_color((0,0,0,0))
    ax.set_facecolor((1,1,1,0))

    # アスペクト比固定
    all_points = []
    for i in range(nx+1):
        for j in range(ny+1):
            for k in range(nz+1):
                all_points.append(i*va + j*vb + k*vc)
    all_points = np.array(all_points)
# 格子点の描画（黒い小さな●）
    ax.scatter(all_points[:,0], all_points[:,1], all_points[:,2], color='black', s=20)
    set_equal_aspect(ax, all_points)

    plt.tight_layout()
    plt.savefig("unit_cells.png", dpi=300, bbox_inches='tight', transparent=True)
    plt.show()


draw_supercell(a=5.0, b=5.5, c=4.5, alpha=80, beta=70, gamma=100) 
