python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
# 创建立方体顶点
def create_cube(center=(0, 0, 0), size=1):
half = size / 2
vertices = np.array([
[center[0]-half, center[1]-half, center[2]-half], # 0 左前下
[center[0]+half, center[1]-half, center[2]-half], # 1 右前下
[center[0]+half, center[1]+half, center[2]-half], # 2 右后下
[center[0]-half, center[1]+half, center[2]-half], # 3 左后下
[center[0]-half, center[1]-half, center[2]+half], # 4 左前上
[center[0]+half, center[1]-half, center[2]+half], # 5 右前上
[center[0]+half, center[1]+half, center[2]+half], # 6 右后上
[center[0]-half, center[1]+half, center[2]+half] # 7 左后上
])
return vertices
# 定义立方体面
def get_faces(vertices):
faces = [
[vertices[0], vertices[1], vertices[5], vertices[4]], # 前面
[vertices[1], vertices[2], vertices[6], vertices[5]], # 右面
[vertices[2], vertices[3], vertices[7], vertices[6]], # 后面
[vertices[3], vertices[0], vertices[4], vertices[7]], # 左面
[vertices[4], vertices[5], vertices[6], vertices[7]], # 上面
[vertices[0], vertices[3], vertices[2], vertices[1]] # 下面
]
return np.array(faces)
# 计算面法向量
def calculate_normal(face):
v1 = face[1] - face[0]
v2 = face[2] - face[0]
normal = np.cross(v1, v2)
return normal / np.linalg.norm(normal)
# 计算光照强度
def calculate_lighting(normal, light_direction):
intensity = np.dot(normal, light_direction)
return max(0, min(1, (intensity + 1) / 2)) # 映射到0-1范围
# 设置光照参数
light_direction = np.array([1, 1, 1]) # 光照方向
light_direction = light_direction / np.linalg.norm(light_direction) # 归一化
base_color = np.array([0.1, 0.5, 0.9]) # 基础颜色 (蓝色)
# 创建立方体
cube_vertices = create_cube(center=(0, 0, 0), size=2)
faces = get_faces(cube_vertices)
# 创建图形
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
# 设置坐标轴范围
ax.set_xlim([-2, 2])
ax.set_ylim([-2, 2])
ax.set_zlim([-2, 2])
# 设置坐标轴标签
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('带光照效果的3D立方体 (可拖拽旋转)')
# 绘制立方体每个面
for face in faces:
normal = calculate_normal(face)
light_intensity = calculate_lighting(normal, light_direction)
# 根据光照调整颜色
face_color = base_color * light_intensity
face_color = np.clip(face_color, 0, 1) # 确保颜色值在0-1范围内
# 创建多边形面
poly = Poly3DCollection([face], alpha=0.8)
poly.set_facecolor(face_color)
poly.set_edgecolor('k') # 设置边框为黑色
poly.set_linewidth(1.5) # 设置边框线宽
ax.add_collection3d(poly)
# 设置视角
ax.view_init(elev=30, azim=45) # 初始视角
# 显示图形
plt.tight_layout()
plt.show()