import numpy as np
import matplotlib.pyplot as plt
import math
from matplotlib.colors import LinearSegmentedColormap
import warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)

# ===================== 全局参数 =====================
W, H = 1600, 1200
MAX_ITER = 700
ESCAPE = 256
# 曼德博视口
x_min, x_max = -2.3, 0.9
y_min, y_max = -1.3, 1.3

# 自定义8阶高精细渐变色彩
color_list = [
    (0.00, (0.00, 0.00, 0.02)),
    (0.10, (0.03, 0.01, 0.25)),
    (0.22, (0.12, 0.00, 0.70)),
    (0.35, (0.90, 0.10, 0.30)),
    (0.48, (1.00, 0.65, 0.10)),
    (0.62, (0.10, 0.95, 0.65)),
    (0.80, (0.00, 0.50, 1.00)),
    (1.00, (0.98, 0.99, 1.00))
]
cmap = LinearSegmentedColormap.from_list("ultra_chaos", color_list, N=3000)

# ===================== 1. 生成复数网格，计算曼德博分形层 =====================
xs = np.linspace(x_min, x_max, W)
ys = np.linspace(y_min, y_max, H)
X, Y = np.meshgrid(xs, ys)
c = X + 1j * Y
z = np.zeros_like(c)

smooth_buf = np.zeros((H, W), dtype=np.float64)
wave_texture = np.zeros((H, W), dtype=np.float64)
mask = np.ones((H, W), dtype=bool)

for step in range(MAX_ITER):
    # 仅更新未逃逸点，防止数值溢出
    z[mask] = z[mask] ** 2 + c[mask]
    valid_z = z[mask]
    perturb = 0.0018 * np.sin(valid_z * 3.8)
    z[mask] += perturb

    abs_z = np.abs(z)
    escape_flag = abs_z > ESCAPE
    new_esc = mask & escape_flag

    if np.any(new_esc):
        log_v = np.log(abs_z[new_esc])
        smooth_buf[new_esc] = step + 1 - np.log2(log_v)
        ang = np.angle(z[new_esc])
        wave_texture[new_esc] += np.sin(ang * 14) * 0.18

    mask[escape_flag] = False
    if not np.any(mask):
        break

# 内核星云纹理
inner = mask
r_inner = np.sqrt(X[inner] ** 2 + Y[inner] ** 2)
smooth_buf[inner] = np.sin(r_inner * 32) * 0.42 + 0.58

# ===================== 2. 柏林噪声 肌理层 =====================
def noise_2d(x, y, freq, octave):
    total = 0.0
    amp = 1.0
    f = freq
    for _ in range(octave):
        total += amp * np.sin(x * f) * np.cos(y * f)
        f *= 2.2
        amp *= 0.48
    return total / octave

noise_layer = noise_2d(X, Y, 12, 6)

# ===================== 3. 径向暗角+中心光晕光影层 =====================
cx = (x_min + x_max) / 2
cy = (y_min + y_max) / 2
dist_center = np.sqrt((X - cx) ** 2 + (Y - cy) ** 2)
max_dist = np.max(dist_center)
vignette = 1 - (dist_center / max_dist) * 0.4
glow = np.exp(-dist_center * 1.8) * 0.25

# ===================== 4. 多层图层混合 =====================
base = smooth_buf + wave_texture + noise_layer * 0.22
base = base * vignette + glow
# 归一化到0~1
img_data = (base - np.min(base)) / (np.max(base) - np.min(base))

# ===================== 5. 递归L分形树绘制叠加图层 =====================
def draw_tree(ax, x0, y0, len_, angle, depth, max_d):
    if depth > max_d or len_ < 0.003:
        return
    rad = math.radians(angle)
    x1 = x0 + len_ * math.cos(rad)
    y1 = y0 + len_ * math.sin(rad)
    ax.plot([x0, x1], [y0, y1], color=(0.9, 0.95, 1, 0.6), linewidth=0.45)
    # 左右分支递归
    draw_tree(ax, x1, y1, len_ * 0.72, angle - 26, depth + 1, max_d)
    draw_tree(ax, x1, y1, len_ * 0.72, angle + 26, depth + 1, max_d)

# ===================== 输出渲染画布 =====================
fig, ax = plt.subplots(figsize=(16, 12), dpi=120)
ax.imshow(img_data, cmap=cmap, extent=[x_min, x_max, y_min, y_max], origin="lower")
# 在中心绘制多层递归分形树
draw_tree(ax, cx, y_min + 0.18, 0.48, 90, 0, 12)
ax.set_axis_off()
plt.tight_layout()
plt.savefig("ultimate_complex_art.png", bbox_inches="tight", pad_inches=0)
plt.show()
print("极致多层复合复杂图形渲染完成！文件：ultimate_complex_art.png")