ball-demo.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. import pygame
  2. import math
  3. import time
  4. import os
  5. try:
  6. import pyperclip
  7. clipboard_available = True
  8. except ImportError:
  9. clipboard_available = False
  10. print("警告: pyperclip 模块未安装,剪贴板功能不可用。请运行 'pip install pyperclip' 安装。")
  11. from pygame.locals import *
  12. from OpenGL.GL import *
  13. from OpenGL.GLU import *
  14. from OpenGL.GLUT import *
  15. # 初始化字体
  16. pygame.font.init()
  17. # 使用默认字体,增大字体大小
  18. font = pygame.font.Font(None, 24)
  19. # 初始化 GLUT
  20. glutInit()
  21. # 模拟模式开关(True: 使用模拟数据,False: 扫描真实目录)
  22. # USE_MOCK_DATA = True
  23. USE_MOCK_DATA = False
  24. # 初始化 Pygame
  25. pygame.init()
  26. # 获取屏幕尺寸
  27. info = pygame.display.Info()
  28. screen_width = info.current_w
  29. screen_height = info.current_h
  30. # 设置窗口大小(高度为屏幕高度的80%,保持原始宽高比)
  31. height = int(screen_height * 0.8)
  32. width = int(height * (800 / 600)) # 保持原始宽高比 800:600
  33. display = pygame.display.set_mode((width, height), DOUBLEBUF | OPENGL)
  34. pygame.display.set_caption('3D Yellow Ball')
  35. # 启用深度测试
  36. glEnable(GL_DEPTH_TEST)
  37. # 设置背景色
  38. glClearColor(0.1, 0.1, 0.1, 1.0)
  39. # 禁用混合,确保完全不透明
  40. glDisable(GL_BLEND)
  41. # 设置光照
  42. glEnable(GL_LIGHTING)
  43. glEnable(GL_LIGHT0)
  44. # 设置光源位置
  45. light_position = [2.0, 2.0, 2.0, 1.0] # 点光源
  46. glLightfv(GL_LIGHT0, GL_POSITION, light_position)
  47. # 设置光源颜色
  48. light_ambient = [0.3, 0.3, 0.3, 1.0]
  49. light_diffuse = [1.0, 1.0, 1.0, 1.0]
  50. light_specular = [1.0, 1.0, 1.0, 1.0]
  51. glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient)
  52. glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse)
  53. glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular)
  54. # 设置投影矩阵(透视投影)
  55. glMatrixMode(GL_PROJECTION)
  56. glLoadIdentity()
  57. gluPerspective(45, (width/height), 0.1, 50.0)
  58. # 设置模型视图矩阵
  59. glMatrixMode(GL_MODELVIEW)
  60. glLoadIdentity()
  61. # 移动相机(现在在主循环中每帧设置)
  62. # glTranslatef(0.0, 0.0, -5)
  63. def generate_mock_tree():
  64. # 生成模拟目录树数据
  65. nodes = [
  66. ("root", True, -1, 0, "/mock/root"),
  67. ("dir1", True, 0, 1, "/mock/root/dir1"),
  68. ("dir2", True, 0, 1, "/mock/root/dir2"),
  69. ("file1.txt", False, 0, 1, "/mock/root/file1.txt"),
  70. ("file2.py", False, 0, 1, "/mock/root/file2.py"),
  71. ("subdir1", True, 1, 2, "/mock/root/dir1/subdir1"),
  72. ("file3.js", False, 1, 2, "/mock/root/dir1/file3.js"),
  73. ("file4.md", False, 2, 2, "/mock/root/dir2/file4.md"),
  74. ]
  75. edges = [
  76. (0, 1), (0, 2), (0, 3), (0, 4),
  77. (1, 5), (1, 6),
  78. (2, 7),
  79. ]
  80. # 构建子节点列表
  81. children = [[] for _ in range(len(nodes))]
  82. for parent_id, child_id in edges:
  83. children[parent_id].append(child_id)
  84. # 计算节点位置(使用原有算法)
  85. positions = []
  86. for i in range(len(nodes)):
  87. positions.append([0.0, 0.0, 0.0])
  88. # 计算最大深度
  89. max_depth_found = 0
  90. for node in nodes:
  91. max_depth_found = max(max_depth_found, node[3])
  92. # 递归计算位置函数
  93. def calculate_positions(node_id, start_angle, end_angle, depth):
  94. if depth > max_depth_found:
  95. return
  96. if node_id == 0: # 根节点
  97. positions[node_id] = [0.0, max_depth_found * 0.4, 0.0]
  98. else:
  99. parent_id = nodes[node_id][2]
  100. if parent_id >= 0:
  101. child_index = children[parent_id].index(node_id)
  102. num_siblings = len(children[parent_id])
  103. angle = start_angle + (end_angle - start_angle) * (child_index / max(num_siblings, 1))
  104. radius = 0.75 * (0.75 ** depth)
  105. px, py, pz = positions[parent_id]
  106. x = px + radius * math.cos(angle)
  107. y = py - 0.65
  108. z = pz + radius * math.sin(angle)
  109. positions[node_id] = [x, y, z]
  110. node_children = children[node_id]
  111. if node_children:
  112. angle_range = math.pi * 1.5
  113. angle_start = -angle_range / 2
  114. angle_step = angle_range / len(node_children)
  115. for i, child_id in enumerate(node_children):
  116. child_angle_start = angle_start + i * angle_step
  117. child_angle_end = angle_start + (i + 1) * angle_step
  118. calculate_positions(child_id, child_angle_start, child_angle_end, depth + 1)
  119. calculate_positions(0, -math.pi, math.pi, 0)
  120. return nodes, edges, positions, children
  121. def build_directory_tree(root_path, max_depth=3, max_children_per_node=30):
  122. # 如果启用模拟模式,返回模拟数据
  123. if USE_MOCK_DATA:
  124. return generate_mock_tree()
  125. # 递归扫描目录树
  126. nodes = [] # 每个节点: (name, is_dir, parent_id, depth)
  127. edges = [] # (parent_id, child_id)
  128. # 递归扫描函数
  129. def scan_directory(current_path, parent_id, depth):
  130. if depth >= max_depth:
  131. return
  132. try:
  133. entries = os.listdir(current_path)
  134. except Exception:
  135. return # 忽略所有访问错误
  136. # 过滤掉一些不需要的目录
  137. filtered_entries = []
  138. for entry in entries:
  139. # 过滤常见的版本控制和IDE目录
  140. if entry in ['.git', '.vscode', '.idea', 'node_modules', '__pycache__']:
  141. continue
  142. filtered_entries.append(entry)
  143. # 限制每个节点的最大子项数量
  144. filtered_entries = filtered_entries[:max_children_per_node]
  145. # 当前目录的节点ID:根节点为0,其他目录为parent_id
  146. current_node_id = 0 if parent_id == -1 else parent_id
  147. for entry in filtered_entries:
  148. entry_path = os.path.join(current_path, entry)
  149. is_dir = os.path.isdir(entry_path)
  150. # 添加子节点
  151. child_id = len(nodes)
  152. nodes.append((entry, is_dir, current_node_id, depth + 1, entry_path))
  153. edges.append((current_node_id, child_id))
  154. # 如果是目录,递归扫描
  155. if is_dir:
  156. scan_directory(entry_path, child_id, depth + 1)
  157. # 添加根节点
  158. root_name = os.path.basename(root_path.rstrip('\\'))
  159. nodes.append((root_name, True, -1, 0, root_path))
  160. # 从根节点开始递归扫描
  161. scan_directory(root_path, -1, 0)
  162. # 计算节点位置
  163. positions = []
  164. for i in range(len(nodes)):
  165. positions.append([0.0, 0.0, 0.0]) # 初始位置
  166. # 构建子节点列表
  167. children = [[] for _ in range(len(nodes))]
  168. for edge in edges:
  169. parent_id, child_id = edge
  170. children[parent_id].append(child_id)
  171. # 计算最大深度
  172. max_depth_found = 0
  173. for node in nodes:
  174. max_depth_found = max(max_depth_found, node[3])
  175. # 递归计算位置
  176. def calculate_positions(node_id, start_angle, end_angle, depth):
  177. if depth > max_depth_found:
  178. return
  179. # 计算当前节点位置
  180. if node_id == 0: # 根节点
  181. positions[node_id] = [0.0, max_depth_found * 0.4, 0.0] # 顶部,高度减半
  182. else:
  183. parent_id = nodes[node_id][2]
  184. if parent_id >= 0:
  185. # 子节点围绕父节点在圆上分布
  186. child_index = children[parent_id].index(node_id)
  187. num_siblings = len(children[parent_id])
  188. # 计算角度(在父节点周围的圆上)
  189. angle = start_angle + (end_angle - start_angle) * (child_index / max(num_siblings, 1))
  190. # 半径随深度减小
  191. radius = 0.75 * (0.75 ** depth) # 深度越大,半径越小,基础半径减半
  192. # 计算位置
  193. px, py, pz = positions[parent_id]
  194. x = px + radius * math.cos(angle)
  195. y = py - 0.65 # 每层向下移动,垂直距离减半
  196. z = pz + radius * math.sin(angle)
  197. positions[node_id] = [x, y, z]
  198. # 为子节点递归计算位置
  199. node_children = children[node_id]
  200. if node_children:
  201. # 计算子节点的角度范围
  202. angle_range = math.pi * 1.5 # 270度范围
  203. angle_start = -angle_range / 2
  204. angle_step = angle_range / len(node_children)
  205. for i, child_id in enumerate(node_children):
  206. child_angle_start = angle_start + i * angle_step
  207. child_angle_end = angle_start + (i + 1) * angle_step
  208. calculate_positions(child_id, child_angle_start, child_angle_end, depth + 1)
  209. # 从根节点开始计算位置
  210. calculate_positions(0, -math.pi, math.pi, 0)
  211. return nodes, edges, positions, children
  212. # 构建目录树(使用当前目录)
  213. # root_path = "."
  214. root_path = "E:\\agricultural_research_platform"
  215. tree_nodes, tree_edges, node_positions, tree_children = build_directory_tree(root_path)
  216. def draw_text(x, y, z, text):
  217. """在3D空间中绘制文本"""
  218. glDisable(GL_LIGHTING)
  219. glColor3f(1.0, 1.0, 1.0) # 白色文本
  220. # 保存当前矩阵
  221. glPushMatrix()
  222. # 移动到指定位置
  223. glTranslatef(x, y, z)
  224. # 旋转文本,使其面向相机
  225. glRotatef(rotation_angle, 0.0, 1.0, 0.0)
  226. # 缩小文本,使其适合3D空间
  227. scale = 0.001
  228. glScalef(scale, scale, scale)
  229. # 计算文本宽度,以便居中显示
  230. text_width = 0
  231. for char in text:
  232. text_width += glutBitmapWidth(GLUT_BITMAP_HELVETICA_12, ord(char))
  233. # 设置文本位置,使其居中
  234. glRasterPos2f(-text_width / 2, 0)
  235. # 绘制文本
  236. for char in text:
  237. glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, ord(char))
  238. # 恢复矩阵
  239. glPopMatrix()
  240. glEnable(GL_LIGHTING)
  241. # 初始化选中节点(根节点)
  242. selected_node_index = 0
  243. # 剪贴板相关变量
  244. clipboard_content = ""
  245. clipboard_check_time = 0
  246. blinking_nodes = set()
  247. file_content_cache = {}
  248. blink_start_time = pygame.time.get_ticks()
  249. # 旋转控制变量
  250. rotation_angle = 0.0
  251. # 相机控制变量
  252. camera_z = -5 # 相机的 Z 轴位置,初始值为 -5
  253. # 主循环
  254. running = True
  255. while running:
  256. # 获取当前时间(用于闪烁效果)
  257. current_time = pygame.time.get_ticks()
  258. # 更新旋转角度(每20秒旋转一圈)
  259. rotation_angle = (current_time * 0.018) % 360.0
  260. # 检查剪贴板内容是否变化(如果剪贴板功能可用)
  261. if clipboard_available:
  262. if current_time - clipboard_check_time > 1000: # 每秒检查一次
  263. clipboard_check_time = current_time
  264. try:
  265. new_clipboard_content = pyperclip.paste()
  266. if new_clipboard_content != clipboard_content:
  267. clipboard_content = new_clipboard_content
  268. # 剪贴板内容变化,重新检查所有文件节点
  269. blinking_nodes.clear()
  270. if clipboard_content.strip(): # 剪贴板非空
  271. for i, (name, is_dir, parent_id, depth, full_path) in enumerate(tree_nodes):
  272. if not is_dir: # 文件节点
  273. # 检查文件内容是否包含剪贴板文本
  274. try:
  275. # 从缓存读取或加载文件内容
  276. if i not in file_content_cache:
  277. with open(full_path, 'r', encoding='utf-8', errors='ignore') as f:
  278. file_content_cache[i] = f.read()
  279. file_content = file_content_cache[i]
  280. if clipboard_content in file_content:
  281. blinking_nodes.add(i)
  282. except Exception as e:
  283. pass # 忽略读取错误
  284. except Exception as e:
  285. pass # 忽略剪贴板访问错误
  286. # 处理事件
  287. for event in pygame.event.get():
  288. if event.type == pygame.QUIT:
  289. running = False
  290. elif event.type == pygame.KEYDOWN:
  291. # 获取当前节点信息
  292. current_node = tree_nodes[selected_node_index]
  293. current_parent_id = current_node[2]
  294. current_depth = current_node[3]
  295. if event.key == pygame.K_UP: # 上键:移动到父节点
  296. if current_parent_id >= 0: # 有父节点
  297. selected_node_index = current_parent_id
  298. elif event.key == pygame.K_DOWN: # 下键:移动到第一个子节点
  299. if tree_children[selected_node_index]: # 有子节点
  300. selected_node_index = tree_children[selected_node_index][0]
  301. elif event.key == pygame.K_LEFT: # 左键:移动到前一个兄弟节点
  302. if current_parent_id >= 0: # 有父节点
  303. siblings = tree_children[current_parent_id]
  304. if len(siblings) > 1:
  305. current_index_in_siblings = siblings.index(selected_node_index)
  306. # 移动到前一个兄弟,如果当前是第一个则移动到最后一个
  307. new_index = (current_index_in_siblings - 1) % len(siblings)
  308. selected_node_index = siblings[new_index]
  309. elif event.key == pygame.K_RIGHT: # 右键:移动到后一个兄弟节点
  310. if current_parent_id >= 0: # 有父节点
  311. siblings = tree_children[current_parent_id]
  312. if len(siblings) > 1:
  313. current_index_in_siblings = siblings.index(selected_node_index)
  314. # 移动到后一个兄弟,如果当前是最后一个则移动到第一个
  315. new_index = (current_index_in_siblings + 1) % len(siblings)
  316. selected_node_index = siblings[new_index]
  317. elif event.type == pygame.MOUSEBUTTONDOWN:
  318. if event.button == 4: # 鼠标滚轮向上滚动,放大
  319. camera_z += 0.5 # 相机向Z轴正方向移动,放大视图
  320. elif event.button == 5: # 鼠标滚轮向下滚动,缩小
  321. camera_z -= 0.5 # 相机向Z轴负方向移动,缩小视图
  322. # 限制相机的Z轴范围,防止过度放大或缩小
  323. camera_z = max(-10, min(-2, camera_z))
  324. # 清除屏幕
  325. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
  326. # 重置模型视图矩阵并设置相机位置
  327. glLoadIdentity()
  328. glTranslatef(0.0, 0.0, camera_z) # 相机位置,可通过鼠标滚轮调整
  329. glRotatef(rotation_angle, 0.0, 1.0, 0.0) # 绕竖直中线/Y轴旋转
  330. # 目录树可视化
  331. ball_radius = 0.0667 # 节点球的半径(默认大小)
  332. # 绘制所有连线(目录树边)
  333. glDisable(GL_LIGHTING) # 禁用光照以使用纯色
  334. glColor3f(1.0, 1.0, 1.0) # 白色连线
  335. glLineWidth(2.0)
  336. glBegin(GL_LINES)
  337. for edge in tree_edges:
  338. node1_idx, node2_idx = edge
  339. x1, y1, z1 = node_positions[node1_idx]
  340. x2, y2, z2 = node_positions[node2_idx]
  341. glVertex3f(x1, y1, z1)
  342. glVertex3f(x2, y2, z2)
  343. glEnd()
  344. glEnable(GL_LIGHTING) # 重新启用光照
  345. # 绘制所有节点球(根据类型使用不同颜色)
  346. for i, (name, is_dir, parent_id, depth, full_path) in enumerate(tree_nodes):
  347. x, y, z = node_positions[i]
  348. # 根据节点类型设置材质颜色(选中节点显示为红色)
  349. if i in blinking_nodes: # 闪烁节点
  350. # 计算闪烁因子(正弦波,周期约2秒)
  351. blink_factor = (math.sin((current_time - blink_start_time) * 0.005) + 1) * 0.5
  352. # 基础颜色 #c31c1f
  353. base_r, base_g, base_b = 0.7647, 0.1098, 0.1216
  354. # 亮度在0.7到1.0之间变化
  355. brightness = 0.7 + 0.3 * blink_factor
  356. color = [base_r * brightness, base_g * brightness, base_b * brightness, 1.0]
  357. ambient = [base_r * 0.5, base_g * 0.5, base_b * 0.5, 1.0]
  358. specular = [base_r * 0.8, base_g * 0.8, base_b * 0.8, 1.0]
  359. elif i == selected_node_index: # 选中节点
  360. color = [1.0, 0.0, 0.0, 1.0] # 红色
  361. ambient = [0.5, 0.0, 0.0, 1.0]
  362. specular = [0.8, 0.3, 0.3, 1.0]
  363. elif i == 0: # 根节点
  364. color = [1.0, 1.0, 0.0, 1.0] # 黄色
  365. ambient = [0.5, 0.5, 0.0, 1.0]
  366. specular = [0.8, 0.8, 0.4, 1.0]
  367. elif is_dir: # 目录
  368. color = [0.2902, 0.5961, 0.3098, 1.0] # #4a984f
  369. ambient = [0.2, 0.4, 0.2, 1.0]
  370. specular = [0.4, 0.8, 0.4, 1.0]
  371. else: # 文件
  372. color = [0.7059, 0.7176, 0.2549, 1.0] # #b4b741
  373. ambient = [0.4, 0.4, 0.15, 1.0]
  374. specular = [0.8, 0.8, 0.4, 1.0]
  375. shininess = [30.0]
  376. glMaterialfv(GL_FRONT, GL_AMBIENT, ambient)
  377. glMaterialfv(GL_FRONT, GL_DIFFUSE, color)
  378. glMaterialfv(GL_FRONT, GL_SPECULAR, specular)
  379. glMaterialfv(GL_FRONT, GL_SHININESS, shininess)
  380. glPushMatrix()
  381. glTranslatef(x, y, z)
  382. quad = gluNewQuadric()
  383. gluQuadricNormals(quad, GLU_SMOOTH)
  384. # 根据深度和节点类型调整球体大小:深度越大,球体越小;文件节点的半径缩小为原来的1/3,文件夹节点的半径缩小为原来的1/2
  385. if is_dir:
  386. current_radius = (ball_radius / 2) * (0.85 ** depth) # 文件夹节点的半径缩小为原来的1/2
  387. else:
  388. current_radius = (ball_radius / 3) * (0.85 ** depth) # 文件节点的半径缩小为原来的1/3
  389. gluSphere(quad, current_radius, 32, 32)
  390. gluDeleteQuadric(quad)
  391. glPopMatrix()
  392. # 绘制文件名
  393. draw_text(x, y + current_radius + 0.05, z, name)
  394. # 交换缓冲区
  395. pygame.display.flip()
  396. # 控制帧率
  397. pygame.time.wait(10)
  398. # 退出 Pygame
  399. pygame.quit()