molforge-studio 7.4.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. main.py +71 -0
  2. molforge/__init__.py +19 -0
  3. molforge/ai/__init__.py +15 -0
  4. molforge/ai/deepseek_harness.py +185 -0
  5. molforge/ai/mcp/desktop_client.py +38 -0
  6. molforge/ai/mcp/desktop_service.py +121 -0
  7. molforge/ai/mcp/mcp_server.py +780 -0
  8. molforge/ai/mcp_bridge.py +945 -0
  9. molforge/ai/observation.py +152 -0
  10. molforge/ai/tools.py +455 -0
  11. molforge/application/__init__.py +22 -0
  12. molforge/application/ai/__init__.py +1 -0
  13. molforge/application/ai/deepseek_client.py +293 -0
  14. molforge/application/ai/observation.py +161 -0
  15. molforge/application/ai/tools.py +200 -0
  16. molforge/application/ai_proposals.py +166 -0
  17. molforge/application/bio_selection.py +143 -0
  18. molforge/application/builtin_commands.py +1445 -0
  19. molforge/application/calculators/__init__.py +10 -0
  20. molforge/application/calculators/base.py +143 -0
  21. molforge/application/calculators/calchem_engine.py +67 -0
  22. molforge/application/calculators/calchem_subprocess_worker.py +109 -0
  23. molforge/application/calculators/gaussian_engine.py +59 -0
  24. molforge/application/calculators/gaussian_job_spec.py +240 -0
  25. molforge/application/calculators/orca_engine.py +92 -0
  26. molforge/application/calculators/qc_input_generator.py +300 -0
  27. molforge/application/calculators/registry.py +29 -0
  28. molforge/application/calculators/rest_engine.py +262 -0
  29. molforge/application/command_bus.py +139 -0
  30. molforge/application/commands.py +55 -0
  31. molforge/application/conformers.py +143 -0
  32. molforge/application/document_session.py +156 -0
  33. molforge/application/events.py +74 -0
  34. molforge/application/fragment_catalog.py +422 -0
  35. molforge/application/fragment_commands.py +268 -0
  36. molforge/application/geometry_commands.py +84 -0
  37. molforge/application/history.py +105 -0
  38. molforge/application/internal_coordinates.py +293 -0
  39. molforge/application/invalidation.py +1174 -0
  40. molforge/application/jobs.py +185 -0
  41. molforge/application/measurement.py +167 -0
  42. molforge/application/measurement_targets.py +264 -0
  43. molforge/application/modeling_commands.py +61 -0
  44. molforge/application/plugins.py +197 -0
  45. molforge/application/ports/editor2d.py +85 -0
  46. molforge/application/reaction.py +75 -0
  47. molforge/application/selection.py +164 -0
  48. molforge/application/selection_commands.py +31 -0
  49. molforge/application/trajectory.py +120 -0
  50. molforge/application/trajectory_analysis.py +231 -0
  51. molforge/application/workspace_registry.py +226 -0
  52. molforge/core/__init__.py +12 -0
  53. molforge/core/conformer.py +45 -0
  54. molforge/core/molecule.py +150 -0
  55. molforge/core/orbital.py +33 -0
  56. molforge/core/properties.py +43 -0
  57. molforge/domain/__init__.py +12 -0
  58. molforge/domain/biomolecule.py +99 -0
  59. molforge/domain/chemical_summary.py +129 -0
  60. molforge/domain/chemistry.py +13 -0
  61. molforge/domain/coordinate_store.py +164 -0
  62. molforge/domain/coordination.py +133 -0
  63. molforge/domain/custom_fragments.py +255 -0
  64. molforge/domain/document.py +469 -0
  65. molforge/domain/element_reference.json +598 -0
  66. molforge/domain/elements.py +188 -0
  67. molforge/domain/ids.py +58 -0
  68. molforge/domain/massive_system.py +246 -0
  69. molforge/domain/periodic.py +116 -0
  70. molforge/domain/provenance.py +115 -0
  71. molforge/domain/topology.py +364 -0
  72. molforge/infrastructure/__init__.py +23 -0
  73. molforge/infrastructure/hpc/cluster_config.py +122 -0
  74. molforge/infrastructure/hpc/remote_executor.py +212 -0
  75. molforge/infrastructure/hpc/slurm_generator.py +93 -0
  76. molforge/io/__init__.py +35 -0
  77. molforge/io/calchem_bridge.py +407 -0
  78. molforge/io/calculators.py +893 -0
  79. molforge/io/cclib_adapter.py +422 -0
  80. molforge/io/conformers.py +183 -0
  81. molforge/io/cube_reader.py +215 -0
  82. molforge/io/custom_fragments.py +79 -0
  83. molforge/io/format_matrix.py +157 -0
  84. molforge/io/gemmi_adapter.py +150 -0
  85. molforge/io/history_skill.py +46 -0
  86. molforge/io/mdanalysis_adapter.py +155 -0
  87. molforge/io/mforge_storage.py +261 -0
  88. molforge/io/multiwfn_driver.py +614 -0
  89. molforge/io/openbabel_adapter.py +265 -0
  90. molforge/io/openbabel_handler.py +33 -0
  91. molforge/io/rdkit_adapter.py +1865 -0
  92. molforge/io/readers/__init__.py +10 -0
  93. molforge/io/readers/cube_reader.py +71 -0
  94. molforge/io/readers/gjf_reader.py +110 -0
  95. molforge/io/readers/glog_reader.py +45 -0
  96. molforge/io/readers/mol2_reader.py +36 -0
  97. molforge/io/readers/mol_reader.py +56 -0
  98. molforge/io/readers/pdb_reader.py +39 -0
  99. molforge/io/readers/smi_reader.py +40 -0
  100. molforge/io/readers/xyz_reader.py +47 -0
  101. molforge/io/registry.py +128 -0
  102. molforge/io/writers/__init__.py +7 -0
  103. molforge/io/writers/gjf_writer.py +68 -0
  104. molforge/io/writers/pdb_writer.py +37 -0
  105. molforge/io/writers/png_writer.py +31 -0
  106. molforge/io/writers/svg_writer.py +111 -0
  107. molforge/io/writers/xyz_writer.py +39 -0
  108. molforge/rendering/__init__.py +21 -0
  109. molforge/rendering/benchmark.py +121 -0
  110. molforge/rendering/bridge.py +60 -0
  111. molforge/rendering/contracts.py +119 -0
  112. molforge/rendering/glyph_scene.py +279 -0
  113. molforge/rendering/ketcher_bridge.py +131 -0
  114. molforge/rendering/ketcher_id_mapping.py +110 -0
  115. molforge/rendering/materials.py +127 -0
  116. molforge/rendering/molstar_backend.py +245 -0
  117. molforge/rendering/native_labels.py +134 -0
  118. molforge/rendering/orbitals.py +139 -0
  119. molforge/rendering/vtk_backend.py +2294 -0
  120. molforge/runtime.py +29 -0
  121. molforge/server/__init__.py +1 -0
  122. molforge/server/api_bridge.py +947 -0
  123. molforge/ui/__init__.py +1 -0
  124. molforge/ui/assets/caffeine_2d.svg +150 -0
  125. molforge/ui/assets/caffeine_3d_preview.svg +209 -0
  126. molforge/ui/assets/caffeine_preview.json +302 -0
  127. molforge/ui/assets/icons/atom.svg +1 -0
  128. molforge/ui/assets/icons/bond.svg +1 -0
  129. molforge/ui/assets/icons/cleanup.svg +1 -0
  130. molforge/ui/assets/icons/export.svg +1 -0
  131. molforge/ui/assets/icons/fragments.svg +1 -0
  132. molforge/ui/assets/icons/history.svg +1 -0
  133. molforge/ui/assets/icons/jobs.svg +1 -0
  134. molforge/ui/assets/icons/measure.svg +1 -0
  135. molforge/ui/assets/icons/molecules.svg +1 -0
  136. molforge/ui/assets/icons/overview.svg +1 -0
  137. molforge/ui/assets/icons/ring.svg +1 -0
  138. molforge/ui/assets/icons/search.svg +1 -0
  139. molforge/ui/assets/icons/select.svg +1 -0
  140. molforge/ui/assets/icons/settings.svg +1 -0
  141. molforge/ui/assets/icons/templates.svg +1 -0
  142. molforge/ui/assets/molforge_logo.ico +0 -0
  143. molforge/ui/assets/molforge_logo.png +0 -0
  144. molforge/ui/atom_labels.py +92 -0
  145. molforge/ui/bio_structure_dialog.py +57 -0
  146. molforge/ui/conformer_dialog.py +151 -0
  147. molforge/ui/dialogs/__init__.py +2 -0
  148. molforge/ui/dialogs/aim_qtaim_dialog.py +533 -0
  149. molforge/ui/dialogs/calchem_orbitals_dialog.py +287 -0
  150. molforge/ui/dialogs/element_fragments.py +130 -0
  151. molforge/ui/dialogs/gaussian_calculation_setup.py +308 -0
  152. molforge/ui/dialogs/hpc_job_dialog.py +427 -0
  153. molforge/ui/dialogs/vibrational_spectrum_dialog.py +381 -0
  154. molforge/ui/editor2d_widget.py +1803 -0
  155. molforge/ui/element_picker.py +218 -0
  156. molforge/ui/gmv_window_manager.py +65 -0
  157. molforge/ui/gromacs_job_dialog.py +47 -0
  158. molforge/ui/hotkeys.py +107 -0
  159. molforge/ui/i18n.py +237 -0
  160. molforge/ui/live_llm_dialog.py +135 -0
  161. molforge/ui/llm_config_dialog.py +103 -0
  162. molforge/ui/modeling_actions.py +176 -0
  163. molforge/ui/molstar_widget.py +98 -0
  164. molforge/ui/molstar_window.py +85 -0
  165. molforge/ui/panels.py +2966 -0
  166. molforge/ui/qc_result_dialog.py +1924 -0
  167. molforge/ui/render3d_widget.py +1579 -0
  168. molforge/ui/scrolling.py +52 -0
  169. molforge/ui/settings_panel.py +330 -0
  170. molforge/ui/shells/__init__.py +4 -0
  171. molforge/ui/shells/base_shell.py +72 -0
  172. molforge/ui/shells/document_tabs.py +715 -0
  173. molforge/ui/shells/studio_2d.py +339 -0
  174. molforge/ui/shells/studio_3d.py +401 -0
  175. molforge/ui/shells/studio_split.py +370 -0
  176. molforge/ui/shells/workflow_inputs.py +698 -0
  177. molforge/ui/theme.py +719 -0
  178. molforge/ui/trajectory_window.py +333 -0
  179. molforge/ui/views.py +892 -0
  180. molforge/ui/vtk_multiview_widget.py +141 -0
  181. molforge/ui/welcome_window.py +223 -0
  182. molforge/ui/window.py +3320 -0
  183. molforge/workflows/__init__.py +25 -0
  184. molforge/workflows/assets/OSC_MD_workflows/templates/01-MD/delete_solvent.py +216 -0
  185. molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms.py +60 -0
  186. molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms_example.py +22 -0
  187. molforge/workflows/assets/OSC_MD_workflows/templates/03-/342/225/244/320/225/342/225/250/342/226/221/342/225/250/320/246/342/225/244/320/227/342/225/250/342/225/226/342/225/250/342/224/220/342/225/244/320/225/342/225/250/320/247/342/225/250/342/226/221/342/225/244/320/224/321/202/320/245/320/254/342/225/250/320/265/analysis_mol.py +244 -0
  188. molforge/workflows/assets/OSC_MD_workflows/templates/04-/342/225/244/320/224/321/202/320/245/320/241/342/225/250/320/254/342/225/244/320/227/321/202/320/245/320/247/321/202/320/244/320/264/342/225/244/320/225/342/225/250/342/224/220/342/225/250/320/246/342/225/244/320/225/321/202/320/245/320/241/342/225/250/342/225/242/rms_roughness.py +33 -0
  189. molforge/workflows/assets/OSC_MD_workflows/templates/04-/342/225/244/320/224/321/202/320/245/320/241/342/225/250/320/254/342/225/244/320/227/321/202/320/245/320/247/321/202/320/244/320/264/342/225/244/320/225/342/225/250/342/224/220/342/225/250/320/246/342/225/244/320/225/321/202/320/245/320/241/342/225/250/342/225/242/xpm_2.py +117 -0
  190. molforge/workflows/assets/OSC_MD_workflows/templates/09-/342/225/244/320/231/342/225/250/320/240/342/225/250/320/277/342/225/244/320/227/342/225/250/320/256/342/225/250/320/247/marcus_rate.py +60 -0
  191. molforge/workflows/assets/esp-surface-analysis/scripts/compute_descriptors.py +134 -0
  192. molforge/workflows/assets/esp-surface-analysis/scripts/parse_surfanalysis.py +58 -0
  193. molforge/workflows/assets/esp-surface-analysis/scripts/plot_esp_hist.py +115 -0
  194. molforge/workflows/assets/homo-lumo-plot/extract_orb_energy.py +57 -0
  195. molforge/workflows/assets/homo-lumo-plot/make_level_plot.py +76 -0
  196. molforge/workflows/assets/homo-lumo-plot/run_pipeline.py +84 -0
  197. molforge/workflows/assets/osc-energy-level-diagram/scripts/extract_levels.py +60 -0
  198. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_editable_pptx.py +122 -0
  199. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_energy_table.py +66 -0
  200. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_level_lines_diagram.py +148 -0
  201. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_rectangle_diagram.py +148 -0
  202. molforge/workflows/assets/osc-energy-level-diagram/scripts/verify_from_log.py +45 -0
  203. molforge/workflows/dipole_analysis.py +32 -0
  204. molforge/workflows/esp_surface.py +36 -0
  205. molforge/workflows/gromacs_submit.py +167 -0
  206. molforge/workflows/homo_lumo_plot.py +59 -0
  207. molforge/workflows/igmh_interaction.py +111 -0
  208. molforge/workflows/md_rdf_analysis.py +134 -0
  209. molforge/workflows/md_studio.py +255 -0
  210. molforge/workflows/osc_energy_diagram.py +24 -0
  211. molforge/workflows/planarity_analysis.py +66 -0
  212. molforge/workflows/reorganization_energy.py +166 -0
  213. molforge/workflows/scientific_workflows.py +650 -0
  214. molforge_studio-7.4.3.dist-info/METADATA +215 -0
  215. molforge_studio-7.4.3.dist-info/RECORD +219 -0
  216. molforge_studio-7.4.3.dist-info/WHEEL +5 -0
  217. molforge_studio-7.4.3.dist-info/entry_points.txt +3 -0
  218. molforge_studio-7.4.3.dist-info/licenses/LICENSE +93 -0
  219. molforge_studio-7.4.3.dist-info/top_level.txt +2 -0
@@ -0,0 +1,2294 @@
1
+ """
2
+ rendering/vtk_backend.py - 逐原子 Glyph + 逐键变径 Tube 零崩溃 3D 渲染引擎 (MolForge v4)
3
+ ========================================================================================
4
+ 彻底解决 P0 核心诉求(告别 vtkMoleculeMapper 黑盒):
5
+ 1. 逐原子独立渲染 (`self._atom_actor` = `vtkGlyph3DMapper` + `vtkPolyData`):
6
+ - 每个原子拥有独立的半径标量 (`atom_radius` = `vdw * mode_scale * global_atom_scale * atom.scale`)
7
+ - 每个原子拥有独立的 RGB 颜色 (`atom_color` = `atom.color` 优先,否则读取当前配色方案 `COLOR_SCHEMES`)
8
+ - 右侧「选中原子大小」滑块只改选中原子的 `atom.scale`;「全局原子大小」滑块管整体缩放,二者完美共存!
9
+ 2. 逐键独立粗细与半键双色/自定义键色渲染 (`self._bond_actor` = `vtkTubeFilter` + `SetVaryRadiusToVaryRadiusByAbsoluteScalar`):
10
+ - 每条化学键(含单键、双键双圆柱、三键三圆柱、芳香键)拆分为中心对称半键段写入常驻 `self._bond_polydata`
11
+ - 每个顶点写入独立半径标量 (`bond_radius` = `base_r * global_bond_scale * bond.width_scale * multi_factor`)
12
+ - 每个顶点写入独立 RGB 颜色 (`bond_color` = 若设置了 `bond.color` 则整键使用该颜色;否则两端半键自动继承两端原子的实时颜色!)
13
+ - 右侧「选中键粗细」滑块只改选中键的 `bond.width_scale`;「全局键粗细」滑块管整体缩放!
14
+ 3. 常驻 Actor 架构(生命周期内零 `RemoveActor` / 零 C++ 析构崩溃):
15
+ - `_atom_actor`、`_bond_actor`、`_highlight_actor`、`_highlight_bond_actor`、`_rubberband_actor`、`_measure_actor`
16
+ 在首次初始化时只 `AddActor` 一次,交互全过程仅原地修改 `vtkPoints` / `vtkFloatArray` / `vtkUnsignedCharArray`!
17
+ 4. 100% 纯 NumPy 相机透视投影与射线拾取(感知每个原子的独立缩放半径与每条键的独立粗细)。
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from typing import Callable, Any, Sequence
23
+ import math
24
+ import numpy as np
25
+
26
+ try:
27
+ import vtk
28
+ from vtk.util import numpy_support as _vtk_numpy_support
29
+ except ImportError: # pragma: no cover
30
+ vtk = None
31
+ _vtk_numpy_support = None
32
+
33
+ from .contracts import Renderer3D, RenderSnapshot, RepresentationMode
34
+ from .materials import MaterialPreset, ScientificPreset, StudioPreset, AnalysisPreset
35
+ from ..domain.ids import AtomId, BondId
36
+
37
+ from ..domain.elements import ELEMENTS
38
+ VDW_RADII = {z: e.vdw_radius for z, e in ELEMENTS.items()}
39
+ DEFAULT_VDW = 1.65
40
+
41
+ # 多套专业配色方案(支持状态栏/View 菜单一键切换)
42
+ STUDIO_CPK_COLORS: dict[int, tuple[float, float, float]] = {
43
+ 1: (0.95, 0.97, 0.99), # H 瓷白
44
+ 5: (0.96, 0.68, 0.50), # B 暖杏
45
+ 6: (0.52, 0.61, 0.70), # C 钛灰蓝
46
+ 7: (0.32, 0.62, 0.98), # N 宝石蓝
47
+ 8: (0.96, 0.36, 0.38), # O 珊瑚红
48
+ 9: (0.36, 0.88, 0.58), # F 翡翠绿
49
+ 14: (0.82, 0.72, 0.56), # Si 香槟金
50
+ 15: (0.98, 0.62, 0.26), # P 琥珀橙
51
+ 16: (0.96, 0.82, 0.28), # S 明黄
52
+ 17: (0.30, 0.84, 0.52), # Cl 鲜绿
53
+ 34: (0.98, 0.58, 0.16), # Se 橙金
54
+ 35: (0.68, 0.28, 0.22), # Br 深红棕
55
+ 50: (0.50, 0.62, 0.62), # Sn 青灰
56
+ 53: (0.58, 0.24, 0.68), # I 紫罗兰
57
+ }
58
+
59
+ GAUSSVIEW_COLORS: dict[int, tuple[float, float, float]] = {
60
+ 1: (0.90, 0.90, 0.90),
61
+ 6: (0.45, 0.45, 0.45),
62
+ 7: (0.20, 0.35, 0.95),
63
+ 8: (0.95, 0.15, 0.15),
64
+ 9: (0.45, 0.90, 0.45),
65
+ 14: (0.78, 0.68, 0.52),
66
+ 15: (1.00, 0.55, 0.00),
67
+ 16: (0.95, 0.85, 0.15),
68
+ 17: (0.15, 0.90, 0.15),
69
+ 34: (0.95, 0.55, 0.10),
70
+ 35: (0.60, 0.15, 0.15),
71
+ 53: (0.55, 0.10, 0.65),
72
+ }
73
+
74
+ JMOL_COLORS: dict[int, tuple[float, float, float]] = {
75
+ 1: (1.00, 1.00, 1.00),
76
+ 6: (0.56, 0.56, 0.56),
77
+ 7: (0.19, 0.31, 0.97),
78
+ 8: (1.00, 0.05, 0.05),
79
+ 9: (0.56, 0.88, 0.31),
80
+ 14: (0.94, 0.78, 0.63),
81
+ 15: (1.00, 0.50, 0.00),
82
+ 16: (1.00, 1.00, 0.19),
83
+ 17: (0.12, 0.94, 0.12),
84
+ 34: (1.00, 0.63, 0.00),
85
+ 35: (0.65, 0.16, 0.16),
86
+ 53: (0.58, 0.00, 0.58),
87
+ }
88
+
89
+ CARBON_CYAN_COLORS: dict[int, tuple[float, float, float]] = {
90
+ **STUDIO_CPK_COLORS,
91
+ 6: (0.25, 0.82, 0.75), # PyMOL 风格青色碳骨架
92
+ }
93
+
94
+ COLOR_SCHEMES: dict[str, dict[int, tuple[float, float, float]]] = {
95
+ "Default Scheme": STUDIO_CPK_COLORS,
96
+ "Studio CPK": STUDIO_CPK_COLORS,
97
+ "GaussView Classic": GAUSSVIEW_COLORS,
98
+ "Jmol Standard": JMOL_COLORS,
99
+ "Carbon Cyan (PyMOL)": CARBON_CYAN_COLORS,
100
+ }
101
+
102
+ PRESETS: dict[str, MaterialPreset] = {
103
+ "Scientific": ScientificPreset,
104
+ "Studio": StudioPreset,
105
+ "Analysis": AnalysisPreset,
106
+ }
107
+
108
+
109
+ def ray_sphere_intersect(
110
+ ray_origin: np.ndarray,
111
+ ray_dir: np.ndarray,
112
+ centers: np.ndarray,
113
+ radii: np.ndarray,
114
+ ) -> tuple[int, float]:
115
+ """纯数学 3D 射线与一组球体求交,返回 (best_atom_index, best_t)。"""
116
+ if centers is None or len(centers) == 0:
117
+ return -1, float("inf")
118
+
119
+ d = np.asarray(ray_dir, dtype=np.float64)
120
+ d_norm = np.linalg.norm(d)
121
+ if d_norm < 1e-12:
122
+ return -1, float("inf")
123
+ d = d / d_norm
124
+
125
+ oc = np.asarray(centers, dtype=np.float64) - np.asarray(ray_origin, dtype=np.float64)
126
+ t_ca = oc @ d
127
+ oc_norm2 = np.einsum("ij,ij->i", oc, oc)
128
+ d2 = oc_norm2 - t_ca * t_ca
129
+ r2 = np.asarray(radii, dtype=np.float64) ** 2
130
+
131
+ hit_mask = (t_ca > 0.0) & (d2 <= r2)
132
+ if not np.any(hit_mask):
133
+ return -1, float("inf")
134
+
135
+ hit_indices = np.where(hit_mask)[0]
136
+ t_hc = np.sqrt(np.maximum(0.0, r2[hit_indices] - d2[hit_indices]))
137
+ t_hit = t_ca[hit_indices] - t_hc
138
+
139
+ best_local = int(np.argmin(t_hit))
140
+ return int(hit_indices[best_local]), float(t_hit[best_local])
141
+
142
+
143
+ def ray_segment_closest(
144
+ ray_origin: np.ndarray,
145
+ ray_dir: np.ndarray,
146
+ p1: np.ndarray,
147
+ p2: np.ndarray,
148
+ ) -> tuple[float, float]:
149
+ """计算 3D 射线与线段 p1->p2 之间的最短距离及射线参数 t。"""
150
+ u = np.asarray(ray_dir, dtype=np.float64)
151
+ u = u / (np.linalg.norm(u) + 1e-12)
152
+ v = np.asarray(p2, dtype=np.float64) - np.asarray(p1, dtype=np.float64)
153
+ w = np.asarray(ray_origin, dtype=np.float64) - np.asarray(p1, dtype=np.float64)
154
+
155
+ a = float(np.dot(u, u))
156
+ b = float(np.dot(u, v))
157
+ c = float(np.dot(v, v))
158
+ d = float(np.dot(u, w))
159
+ e = float(np.dot(v, w))
160
+ denom = a * c - b * b
161
+
162
+ if denom < 1e-9:
163
+ tc = 0.5
164
+ else:
165
+ tc = (a * e - b * d) / denom
166
+
167
+ tc = max(0.15, min(0.85, tc))
168
+ sc = max(0.0, -d + b * tc)
169
+ closest_on_ray = ray_origin + sc * u
170
+ closest_on_seg = p1 + tc * v
171
+ dist = float(np.linalg.norm(closest_on_ray - closest_on_seg))
172
+ return dist, float(sc)
173
+
174
+
175
+ def compute_camera_basis(
176
+ cam_pos: np.ndarray,
177
+ cam_focal: np.ndarray,
178
+ cam_up: np.ndarray,
179
+ view_angle_deg: float,
180
+ width: float,
181
+ height: float,
182
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, float, float]:
183
+ """纯 NumPy 计算透视相机的正交基向量 (eye, forward, right, up, tx, ty)。"""
184
+ eye = np.asarray(cam_pos, dtype=np.float64)
185
+ focal = np.asarray(cam_focal, dtype=np.float64)
186
+ up_raw = np.asarray(cam_up, dtype=np.float64)
187
+
188
+ forward = focal - eye
189
+ f_norm = float(np.linalg.norm(forward))
190
+ forward = forward / (f_norm if f_norm > 1e-12 else 1.0)
191
+
192
+ right = np.cross(forward, up_raw)
193
+ r_norm = float(np.linalg.norm(right))
194
+ if r_norm < 1e-9:
195
+ fallback_up = np.array([0.0, 1.0, 0.0]) if abs(forward[1]) < 0.9 else np.array([1.0, 0.0, 0.0])
196
+ right = np.cross(forward, fallback_up)
197
+ r_norm = float(np.linalg.norm(right))
198
+ right = right / (r_norm if r_norm > 1e-12 else 1.0)
199
+
200
+ true_up = np.cross(right, forward)
201
+ true_up = true_up / (float(np.linalg.norm(true_up)) + 1e-12)
202
+
203
+ fov_rad = math.radians(max(5.0, min(150.0, float(view_angle_deg))))
204
+ ty = math.tan(fov_rad * 0.5)
205
+ aspect = max(1.0, float(width)) / max(1.0, float(height))
206
+ tx = ty * aspect
207
+ return eye, forward, right, true_up, tx, ty
208
+
209
+
210
+ class VtkRendererBackend(Renderer3D):
211
+ """
212
+ MolForge v4 逐原子 Glyph + 逐键变径 Tube 零崩溃 VTK 3D 渲染后端。
213
+ """
214
+
215
+ BASE_BALL_SCALE = 0.25
216
+ BASE_CPK_SCALE = 1.0
217
+ BASE_STICK_RADIUS = 0.165
218
+ BASE_LINE_ATOM_SCALE = 0.04
219
+ BASE_BOND_RADIUS = 0.088
220
+ BASE_STICK_BOND_RADIUS = 0.165
221
+ BASE_LINE_BOND_RADIUS = 0.032
222
+
223
+ def __init__(self, pick_tolerance: float = 0.48) -> None:
224
+ self._viewer = None
225
+ self._mode = RepresentationMode.BALL_AND_STICK
226
+
227
+ # 双向映射:idx <-> AtomId
228
+ self._atom_ids: list[AtomId] = []
229
+ self._id_to_idx: dict[AtomId, int] = {}
230
+ self._bond_ids: list[BondId] = []
231
+ self._bonds: list[tuple[int, int, int]] = []
232
+ self._n_atoms = 0
233
+ self._coordinates: np.ndarray | None = None
234
+ self._atomic_numbers: np.ndarray | None = None
235
+
236
+ # 逐原子与逐键独立属性缓存(支持每个原子/每条键独立大小与颜色!)
237
+ self._per_atom_scales: np.ndarray = np.ones(0, dtype=np.float32)
238
+ self._per_atom_colors: dict[int, tuple[float, float, float]] = {}
239
+ self._per_bond_scales: np.ndarray = np.ones(0, dtype=np.float32)
240
+ self._per_bond_colors: dict[int, tuple[float, float, float]] = {}
241
+
242
+ # 全局缩放与配色方案
243
+ self._atom_opacities = np.ones(0)
244
+ self._atom_glows = {}
245
+ self._glow_layers = []
246
+ self._atom_scale = 1.0
247
+ self._bond_scale = 1.0
248
+ self._color_scheme = "Default Scheme"
249
+
250
+ # 视图显示开关(对应 View 菜单)
251
+ self.show_hydrogens: bool = True
252
+ self.show_bonds: bool = True
253
+ self.label_scope = "all"
254
+ self._native_labels = None
255
+ self.show_labels: bool = False
256
+ self.show_symbols: bool = False
257
+ self.show_axes: bool = True
258
+
259
+ # 选中集合
260
+ self._selected: set[AtomId] = set()
261
+ self._selected_bonds: set[BondId] = set()
262
+ self._pick_tolerance = pick_tolerance
263
+
264
+ # 常驻 VTK 对象(整个生命周期只 AddActor 一次,绝不 RemoveActor!)
265
+ self._scene_initialized = False
266
+
267
+ # 1. 逐原子 Glyph 常驻管线
268
+ self._atom_sphere = None
269
+ self._atom_points = None
270
+ self._atom_radii = None
271
+ self._atom_colors = None
272
+ self._atom_polydata = None
273
+ self._atom_glyph_mapper = None
274
+ self._atom_gpu_sphere_mapper = None
275
+ self._atom_actor = None
276
+ self._actor = None # 兼容引用指向 self._atom_actor
277
+
278
+ # 2. 逐键变径/变色 Tube 常驻管线 + 超大体系 GPU GLSL Stick 管线
279
+ self._bond_points = None
280
+ self._bond_lines = None
281
+ self._bond_radii = None
282
+ self._bond_colors = None
283
+ self._bond_polydata = None
284
+ self._bond_stick_polydata = None
285
+ self._bond_tube_filter = None
286
+ self._bond_mapper = None
287
+ self._bond_gpu_stick_mapper = None
288
+ self._bond_actor = None
289
+ self._gpu_summary_cache: str | None = None
290
+ self._massive_vert_count: int = -1
291
+
292
+ # 3. 常驻选中原子光晕 Glyph Actor
293
+ self._highlight_points = None
294
+ self._highlight_radii = None
295
+ self._highlight_colors = None
296
+ self._highlight_polydata = None
297
+ self._highlight_mapper = None
298
+ self._highlight_actor = None
299
+
300
+ # 4. 常驻选中化学键高亮 Tube Actor
301
+ self._hl_bond_points = None
302
+ self._hl_bond_lines = None
303
+ self._hl_bond_radii = None
304
+ self._hl_bond_polydata = None
305
+ self._hl_bond_tube = None
306
+ self._hl_bond_actor = None
307
+
308
+ # 5. 常驻 3D 橡皮筋建键预览圆柱 Actor & 测量标尺线 Actor
309
+ self._rubberband_line = None
310
+ self._rubberband_actor = None
311
+ self._measure_points = None
312
+ self._measure_lines = None
313
+ self._measure_polydata = None
314
+ self._measure_actor = None
315
+ self._measure_chain: list[AtomId] | None = None
316
+
317
+ # 可选晶胞线框(12 条边,只在存在有效 CRYST1 时显示)
318
+ self._cell_matrix = None
319
+ self._cell_origin = np.zeros(3, dtype=np.float64)
320
+ self._cell_actor = None
321
+ self._cell_points = None
322
+ self._cell_polydata = None
323
+
324
+ # 6. 常驻 3D 文字标签 Actor (vtkLabeledDataMapper / 2D overlay)
325
+ self._label_points = None
326
+ self._label_strings = None
327
+ self._label_polydata = None
328
+ self._label_actor = None
329
+
330
+ # 可选附加层(表面/轨道/体渲染)
331
+ self._surface_actor = None
332
+ self._orbital_actors: list = []
333
+ self._volume_actors: list = []
334
+ self._qtaim_actors: list = []
335
+
336
+ # 交互状态与防重入节流标记
337
+ self.current_tool: str = "选择"
338
+ self.current_element: int = 6
339
+ self._on_selection_changed: Callable[[set[AtomId]], None] | None = None
340
+ self._render_pending = False
341
+ self._in_render = False
342
+ self._camera_state: dict | None = None
343
+
344
+ def attach(self, viewer) -> None:
345
+ self._viewer = viewer
346
+
347
+ # ---------- 初始化常驻 VTK 场景(整个生命周期只执行一次 AddActor) ----------
348
+
349
+ def _ensure_scene_initialized(self) -> None:
350
+ if self._scene_initialized or self._viewer is None or vtk is None:
351
+ return
352
+
353
+ ren = self._viewer.renderer
354
+ self._viewer.set_background(
355
+ color=[0.067, 0.114, 0.173], # #111D2C
356
+ top=[0.145, 0.227, 0.314], # #253A50
357
+ )
358
+ try:
359
+ self._viewer.enable_anti_aliasing("fxaa")
360
+ except Exception:
361
+ pass
362
+
363
+ # 1. 配置三点式 Studio 灯光
364
+ try:
365
+ ren.RemoveAllLights()
366
+ key_light = vtk.vtkLight()
367
+ key_light.SetLightTypeToCameraLight()
368
+ key_light.SetPosition(1.8, 2.2, 2.5)
369
+ key_light.SetColor(1.0, 0.98, 0.95)
370
+ key_light.SetIntensity(0.95)
371
+ ren.AddLight(key_light)
372
+
373
+ fill_light = vtk.vtkLight()
374
+ fill_light.SetLightTypeToCameraLight()
375
+ fill_light.SetPosition(-2.0, -1.2, 1.8)
376
+ fill_light.SetColor(0.78, 0.88, 1.0)
377
+ fill_light.SetIntensity(0.45)
378
+ ren.AddLight(fill_light)
379
+
380
+ rim_light = vtk.vtkLight()
381
+ rim_light.SetLightTypeToCameraLight()
382
+ rim_light.SetPosition(0.0, 2.5, -2.0)
383
+ rim_light.SetColor(0.85, 0.95, 1.0)
384
+ rim_light.SetIntensity(0.28)
385
+ ren.AddLight(rim_light)
386
+ except Exception:
387
+ pass
388
+
389
+ # 1.5 角落 XYZ 坐标轴指示器(GaussView 风格)
390
+ try:
391
+ axes_actor = vtk.vtkAxesActor()
392
+ axes_actor.SetTotalLength(2.0, 2.0, 2.0)
393
+ axes_actor.SetShaftTypeToCylinder()
394
+ axes_actor.SetXAxisLabelText("X")
395
+ axes_actor.SetYAxisLabelText("Y")
396
+ axes_actor.SetZAxisLabelText("Z")
397
+ axes_actor.GetXAxisCaptionActor2D().GetCaptionTextProperty().SetColor(1, 0, 0)
398
+ axes_actor.GetXAxisCaptionActor2D().GetCaptionTextProperty().SetFontSize(16)
399
+ axes_actor.GetYAxisCaptionActor2D().GetCaptionTextProperty().SetColor(0, 1, 0)
400
+ axes_actor.GetYAxisCaptionActor2D().GetCaptionTextProperty().SetFontSize(16)
401
+ axes_actor.GetZAxisCaptionActor2D().GetCaptionTextProperty().SetColor(0, 0.5, 1)
402
+ axes_actor.GetZAxisCaptionActor2D().GetCaptionTextProperty().SetFontSize(16)
403
+ vtk_iren = (
404
+ getattr(getattr(self._viewer, "iren", None), "interactor", None)
405
+ or getattr(getattr(self._viewer, "interactor", None), "_Iren", None)
406
+ or (self._viewer.render_window.GetInteractor() if hasattr(self._viewer, "render_window") and self._viewer.render_window else None)
407
+ )
408
+ self._axes_actor_3d = axes_actor
409
+ if vtk_iren is not None:
410
+ self._axes_marker = vtk.vtkOrientationMarkerWidget()
411
+ self._axes_marker.SetOrientationMarker(axes_actor)
412
+ self._axes_marker.SetInteractor(vtk_iren)
413
+ self._axes_marker.SetViewport(0.0, 0.0, 0.22, 0.22)
414
+ self._axes_marker.SetEnabled(1 if self.show_axes else 0)
415
+ self._axes_marker.InteractiveOff()
416
+ else:
417
+ self._axes_marker = None
418
+ if hasattr(self._viewer, "add_axes"):
419
+ self._viewer.add_axes(interactive=False)
420
+ # Only the corner marker is shown; origin axes obscure molecular geometry.
421
+ self._origin_axes_actor = None
422
+ except Exception:
423
+ self._axes_marker = None
424
+ try:
425
+ if hasattr(self._viewer, "add_axes"):
426
+ self._viewer.add_axes(interactive=False)
427
+ except Exception:
428
+ pass
429
+
430
+ # 2. 常驻逐原子 Sphere Glyph Actor(支持每个原子独立半径 + 独立 RGB 颜色!)
431
+ self._atom_points = vtk.vtkPoints()
432
+ self._atom_radii = vtk.vtkFloatArray()
433
+ self._atom_radii.SetName("atom_radius")
434
+ self._atom_colors = vtk.vtkUnsignedCharArray()
435
+ self._atom_colors.SetName("atom_color")
436
+ self._atom_colors.SetNumberOfComponents(4)
437
+
438
+ self._atom_polydata = vtk.vtkPolyData()
439
+ self._atom_polydata.SetPoints(self._atom_points)
440
+ self._atom_polydata.GetPointData().SetScalars(self._atom_radii)
441
+ self._atom_polydata.GetPointData().AddArray(self._atom_colors)
442
+
443
+ atom_sphere = vtk.vtkSphereSource()
444
+ atom_sphere.SetRadius(1.0)
445
+ atom_sphere.SetThetaResolution(24)
446
+ atom_sphere.SetPhiResolution(24)
447
+ self._atom_sphere = atom_sphere
448
+
449
+ self._atom_glyph_mapper = vtk.vtkGlyph3DMapper()
450
+ self._atom_glyph_mapper.SetSourceConnection(atom_sphere.GetOutputPort())
451
+ self._atom_glyph_mapper.SetInputData(self._atom_polydata)
452
+ self._atom_glyph_mapper.SetScaleArray("atom_radius")
453
+ self._atom_glyph_mapper.SetScaleModeToScaleByMagnitude()
454
+ self._atom_glyph_mapper.ScalingOn()
455
+ self._atom_glyph_mapper.SetScalarModeToUsePointFieldData()
456
+ self._atom_glyph_mapper.SelectColorArray("atom_color")
457
+ self._atom_glyph_mapper.SetColorModeToDirectScalars()
458
+ self._atom_glyph_mapper.ScalarVisibilityOn()
459
+
460
+ if hasattr(vtk, "vtkOpenGLSphereMapper"):
461
+ self._atom_gpu_sphere_mapper = vtk.vtkOpenGLSphereMapper()
462
+ self._atom_gpu_sphere_mapper.SetInputData(self._atom_polydata)
463
+ self._atom_gpu_sphere_mapper.SetScaleArray("atom_radius")
464
+ self._atom_gpu_sphere_mapper.SetScalarModeToUsePointFieldData()
465
+ self._atom_gpu_sphere_mapper.SelectColorArray("atom_color")
466
+ self._atom_gpu_sphere_mapper.SetColorModeToDirectScalars()
467
+ self._atom_gpu_sphere_mapper.ScalarVisibilityOn()
468
+
469
+ self._atom_actor = vtk.vtkActor()
470
+ self._atom_actor.SetMapper(self._atom_glyph_mapper)
471
+ ap = self._atom_actor.GetProperty()
472
+ ap.SetInterpolationToPhong()
473
+ ap.SetAmbient(0.28)
474
+ ap.SetDiffuse(0.74)
475
+ ap.SetSpecular(0.50)
476
+ ap.SetSpecularPower(44.0)
477
+ ren.AddActor(self._atom_actor)
478
+ # A shared Gaussian-splat layer gives smooth colored light, not physical luminescence.
479
+ self._glow_layers = []
480
+ for radius_factor, alpha_factor in ((1.15,.65),):
481
+ poly = vtk.vtkPolyData()
482
+ poly.SetPoints(self._atom_points)
483
+ radii = vtk.vtkFloatArray(); radii.SetName("glow_radius")
484
+ colors = vtk.vtkUnsignedCharArray(); colors.SetName("glow_color"); colors.SetNumberOfComponents(4)
485
+ poly.GetPointData().AddArray(radii); poly.GetPointData().AddArray(colors)
486
+ mapper = vtk.vtkPointGaussianMapper()
487
+ mapper.SetInputData(poly)
488
+ mapper.SetScaleArray("glow_radius"); mapper.SetScaleFactor(1.); mapper.EmissiveOn()
489
+ mapper.SetScalarModeToUsePointFieldData(); mapper.SelectColorArray("glow_color"); mapper.SetColorModeToDirectScalars()
490
+ actor = vtk.vtkActor(); actor.SetMapper(mapper); actor.PickableOff()
491
+ actor.GetProperty().SetAmbient(1.); actor.GetProperty().SetDiffuse(0.); actor.GetProperty().SetSpecular(0.)
492
+ ren.AddActor(actor)
493
+ self._glow_layers.append((poly,radii,colors,actor,radius_factor,alpha_factor))
494
+ self._actor = self._atom_actor
495
+
496
+ # 3. 常驻逐键变径/变色 Tube Actor(支持每条键独立粗细 + 半键双色或独立键色!)
497
+ self._bond_points = vtk.vtkPoints()
498
+ self._bond_lines = vtk.vtkCellArray()
499
+ self._bond_radii = vtk.vtkFloatArray()
500
+ self._bond_radii.SetName("bond_radius")
501
+ self._bond_colors = vtk.vtkUnsignedCharArray()
502
+ self._bond_colors.SetName("bond_color")
503
+ self._bond_colors.SetNumberOfComponents(4)
504
+
505
+ self._bond_polydata = vtk.vtkPolyData()
506
+ self._bond_polydata.SetPoints(self._bond_points)
507
+ self._bond_polydata.SetLines(self._bond_lines)
508
+ self._bond_polydata.GetPointData().SetScalars(self._bond_radii)
509
+ self._bond_polydata.GetPointData().AddArray(self._bond_colors)
510
+
511
+ self._bond_tube_filter = vtk.vtkTubeFilter()
512
+ self._bond_tube_filter.SetInputData(self._bond_polydata)
513
+ self._bond_tube_filter.SetVaryRadiusToVaryRadiusByAbsoluteScalar()
514
+ self._bond_tube_filter.SetNumberOfSides(18)
515
+ self._bond_tube_filter.SetCapping(True)
516
+
517
+ self._bond_mapper = vtk.vtkPolyDataMapper()
518
+ self._bond_mapper.SetInputConnection(self._bond_tube_filter.GetOutputPort())
519
+ self._bond_mapper.SetScalarModeToUsePointFieldData()
520
+ self._bond_mapper.SelectColorArray("bond_color")
521
+ self._bond_mapper.SetColorModeToDirectScalars()
522
+ self._bond_mapper.ScalarVisibilityOn()
523
+
524
+ self._bond_stick_polydata = vtk.vtkPolyData()
525
+ if hasattr(vtk, "vtkOpenGLStickMapper"):
526
+ self._bond_gpu_stick_mapper = vtk.vtkOpenGLStickMapper()
527
+ self._bond_gpu_stick_mapper.SetInputData(self._bond_stick_polydata)
528
+ self._bond_gpu_stick_mapper.SetOrientationArray("bond_ori")
529
+ self._bond_gpu_stick_mapper.SetScaleArray("bond_scale")
530
+ self._bond_gpu_stick_mapper.SetScalarModeToUsePointFieldData()
531
+ self._bond_gpu_stick_mapper.SelectColorArray("bond_color")
532
+ self._bond_gpu_stick_mapper.SetColorModeToDirectScalars()
533
+ self._bond_gpu_stick_mapper.ScalarVisibilityOn()
534
+
535
+ self._bond_actor = vtk.vtkActor()
536
+ self._bond_actor.SetMapper(self._bond_mapper)
537
+ bp = self._bond_actor.GetProperty()
538
+ bp.SetInterpolationToPhong()
539
+ bp.SetAmbient(0.28)
540
+ bp.SetDiffuse(0.74)
541
+ bp.SetSpecular(0.45)
542
+ bp.SetSpecularPower(38.0)
543
+ ren.AddActor(self._bond_actor)
544
+
545
+ # 4. 常驻选中原子高亮光晕 Actor
546
+ self._highlight_points = vtk.vtkPoints()
547
+ self._highlight_radii = vtk.vtkFloatArray()
548
+ self._highlight_radii.SetName("halo_scale")
549
+ self._highlight_polydata = vtk.vtkPolyData()
550
+ self._highlight_polydata.SetPoints(self._highlight_points)
551
+ self._highlight_polydata.GetPointData().SetScalars(self._highlight_radii)
552
+
553
+ halo_sphere = vtk.vtkSphereSource()
554
+ halo_sphere.SetRadius(1.0)
555
+ halo_sphere.SetThetaResolution(24)
556
+ halo_sphere.SetPhiResolution(24)
557
+
558
+ self._highlight_mapper = vtk.vtkGlyph3DMapper()
559
+ self._highlight_mapper.SetSourceConnection(halo_sphere.GetOutputPort())
560
+ self._highlight_mapper.SetInputData(self._highlight_polydata)
561
+ self._highlight_mapper.SetScaleArray("halo_scale")
562
+ self._highlight_mapper.SetScaleModeToScaleByMagnitude()
563
+ self._highlight_mapper.ScalingOn()
564
+ self._highlight_mapper.ScalarVisibilityOff()
565
+
566
+ self._highlight_actor = vtk.vtkActor()
567
+ self._highlight_actor.SetMapper(self._highlight_mapper)
568
+ hp = self._highlight_actor.GetProperty()
569
+ hp.SetColor(0.40, 0.87, 0.79) # #66DEC9 青翠光环
570
+ hp.SetOpacity(0.34)
571
+ hp.SetAmbient(0.80)
572
+ self._highlight_actor.SetPickable(False)
573
+ self._highlight_actor.VisibilityOff()
574
+ ren.AddActor(self._highlight_actor)
575
+
576
+ # 5. 常驻选中化学键高亮光环 Actor
577
+ self._hl_bond_points = vtk.vtkPoints()
578
+ self._hl_bond_lines = vtk.vtkCellArray()
579
+ self._hl_bond_radii = vtk.vtkFloatArray()
580
+ self._hl_bond_radii.SetName("hl_bond_r")
581
+ self._hl_bond_polydata = vtk.vtkPolyData()
582
+ self._hl_bond_polydata.SetPoints(self._hl_bond_points)
583
+ self._hl_bond_polydata.SetLines(self._hl_bond_lines)
584
+ self._hl_bond_polydata.GetPointData().SetScalars(self._hl_bond_radii)
585
+
586
+ self._hl_bond_tube = vtk.vtkTubeFilter()
587
+ self._hl_bond_tube.SetInputData(self._hl_bond_polydata)
588
+ self._hl_bond_tube.SetVaryRadiusToVaryRadiusByAbsoluteScalar()
589
+ self._hl_bond_tube.SetNumberOfSides(16)
590
+
591
+ hl_b_mapper = vtk.vtkPolyDataMapper()
592
+ hl_b_mapper.SetInputConnection(self._hl_bond_tube.GetOutputPort())
593
+ hl_b_mapper.ScalarVisibilityOff()
594
+
595
+ self._hl_bond_actor = vtk.vtkActor()
596
+ self._hl_bond_actor.SetMapper(hl_b_mapper)
597
+ hbp = self._hl_bond_actor.GetProperty()
598
+ hbp.SetColor(0.40, 0.87, 0.79)
599
+ hbp.SetOpacity(0.40)
600
+ hbp.SetAmbient(0.80)
601
+ self._hl_bond_actor.SetPickable(False)
602
+ self._hl_bond_actor.VisibilityOff()
603
+ ren.AddActor(self._hl_bond_actor)
604
+
605
+ # 6. 常驻 3D 橡皮筋建键预览圆柱 Actor
606
+ self._rubberband_line = vtk.vtkLineSource()
607
+ self._rubberband_line.SetPoint1(0.0, 0.0, 0.0)
608
+ self._rubberband_line.SetPoint2(1.0, 0.0, 0.0)
609
+ rb_tube = vtk.vtkTubeFilter()
610
+ rb_tube.SetInputConnection(self._rubberband_line.GetOutputPort())
611
+ rb_tube.SetRadius(0.075)
612
+ rb_tube.SetNumberOfSides(16)
613
+ rb_mapper = vtk.vtkPolyDataMapper()
614
+ rb_mapper.SetInputConnection(rb_tube.GetOutputPort())
615
+ self._rubberband_actor = vtk.vtkActor()
616
+ self._rubberband_actor.SetMapper(rb_mapper)
617
+ rbp = self._rubberband_actor.GetProperty()
618
+ rbp.SetColor(0.40, 0.87, 0.79)
619
+ rbp.SetOpacity(0.82)
620
+ rbp.SetAmbient(0.75)
621
+ self._rubberband_actor.SetPickable(False)
622
+ self._rubberband_actor.VisibilityOff()
623
+ ren.AddActor(self._rubberband_actor)
624
+
625
+ # 7. 常驻 3D 测量连线 Actor
626
+ self._measure_points = vtk.vtkPoints()
627
+ self._measure_lines = vtk.vtkCellArray()
628
+ self._measure_polydata = vtk.vtkPolyData()
629
+ self._measure_polydata.SetPoints(self._measure_points)
630
+ self._measure_polydata.SetLines(self._measure_lines)
631
+ m_tube = vtk.vtkTubeFilter()
632
+ m_tube.SetInputData(self._measure_polydata)
633
+ m_tube.SetRadius(0.032)
634
+ m_tube.SetNumberOfSides(10)
635
+ m_mapper = vtk.vtkPolyDataMapper()
636
+ m_mapper.SetInputConnection(m_tube.GetOutputPort())
637
+ self._measure_actor = vtk.vtkActor()
638
+ self._measure_actor.SetMapper(m_mapper)
639
+ mp = self._measure_actor.GetProperty()
640
+ mp.SetColor(1.0, 0.84, 0.35)
641
+ mp.SetOpacity(0.88)
642
+ mp.SetAmbient(0.8)
643
+ self._measure_actor.SetPickable(False)
644
+ self._measure_actor.VisibilityOff()
645
+ ren.AddActor(self._measure_actor)
646
+
647
+ from .native_labels import NativeAtomLabels
648
+ self._native_labels = NativeAtomLabels(self,ren)
649
+ self._label_actor = self._native_labels.actor
650
+ self._label_points = self._native_labels.points
651
+ self._label_strings = self._native_labels.strings
652
+ self._label_polydata = self._native_labels.data
653
+
654
+ self._scene_initialized = True
655
+
656
+ # ---------- 计算单个原子的实际显示半径与 RGB 颜色 ----------
657
+
658
+ def get_gpu_summary(self) -> str:
659
+ """查询当前 OpenGL/GPU 硬件渲染器摘要并缓存。"""
660
+ if self._gpu_summary_cache is not None:
661
+ return self._gpu_summary_cache
662
+ if self._viewer is None:
663
+ return ""
664
+ try:
665
+ import os
666
+ if os.environ.get("QT_QPA_PLATFORM", "").lower() == "offscreen":
667
+ return ""
668
+ rw = getattr(self._viewer, "render_window", None) or getattr(self._viewer, "ren_win", None)
669
+ if rw is None:
670
+ return ""
671
+ if hasattr(rw, "GetNeverRendered") and rw.GetNeverRendered():
672
+ return ""
673
+ caps = rw.ReportCapabilities() or ""
674
+ renderer_name = ""
675
+ for line in caps.splitlines():
676
+ if "OpenGL renderer string:" in line:
677
+ renderer_name = line.split(":", 1)[1].strip()
678
+ break
679
+ if renderer_name:
680
+ renderer_name = renderer_name.split("/")[0].strip()
681
+ self._gpu_summary_cache = f"GPU: {renderer_name}"
682
+ return self._gpu_summary_cache
683
+ except Exception:
684
+ pass
685
+ return ""
686
+
687
+ def _base_mode_atom_factor(self) -> float:
688
+ if self._mode in (RepresentationMode.CPK, RepresentationMode.SPACE_FILL):
689
+ return self.BASE_CPK_SCALE
690
+ if self._mode == RepresentationMode.LINE:
691
+ return self.BASE_LINE_ATOM_SCALE
692
+ return self.BASE_BALL_SCALE
693
+
694
+ def get_effective_atom_radius(self, idx: int) -> float:
695
+ """返回第 idx 个原子的真实 3D 球体渲染半径(融合元素 VdW + 模式 + 全局缩放 + 单原子缩放)。"""
696
+ if self._atomic_numbers is None or not (0 <= idx < self._n_atoms):
697
+ return 0.40
698
+ z = int(self._atomic_numbers[idx])
699
+ if not self.show_hydrogens and z == 1:
700
+ return 0.0
701
+ ind_scale = float(self._per_atom_scales[idx]) if idx < len(self._per_atom_scales) else 1.0
702
+ if self._mode == RepresentationMode.STICK:
703
+ return float(self.BASE_STICK_RADIUS * self._bond_scale * ind_scale)
704
+ vdw = VDW_RADII.get(z, DEFAULT_VDW)
705
+ return float(vdw * self._base_mode_atom_factor() * self._atom_scale * ind_scale)
706
+
707
+ def get_effective_atom_color(self, idx: int) -> tuple[float, float, float]:
708
+ """返回第 idx 个原子的真实 RGB 颜色(优先读取 atom.color,否则读取当前配色方案)。"""
709
+ if idx in self._per_atom_colors and self._per_atom_colors[idx] is not None:
710
+ c = self._per_atom_colors[idx]
711
+ return (float(c[0]), float(c[1]), float(c[2]))
712
+ z = int(self._atomic_numbers[idx]) if (self._atomic_numbers is not None and 0 <= idx < self._n_atoms) else 6
713
+ scheme_map = COLOR_SCHEMES.get(self._color_scheme, STUDIO_CPK_COLORS)
714
+ if z in scheme_map:
715
+ return scheme_map[z]
716
+ from ..domain.elements import get_element
717
+ elem = get_element(z)
718
+ return elem.cpk_color if elem else (0.55, 0.62, 0.70)
719
+
720
+ def get_effective_bond_radius(self, b_idx: int) -> float:
721
+ """返回第 b_idx 条键的真实 3D 圆柱半径(融合全局键粗细 + 单键独立粗细)。"""
722
+ if self._mode == RepresentationMode.STICK:
723
+ base_r = self.BASE_STICK_BOND_RADIUS
724
+ elif self._mode == RepresentationMode.LINE:
725
+ base_r = self.BASE_LINE_BOND_RADIUS
726
+ else:
727
+ base_r = self.BASE_BOND_RADIUS
728
+ ind_w = float(self._per_bond_scales[b_idx]) if b_idx < len(self._per_bond_scales) else 1.0
729
+ return float(base_r * self._bond_scale * ind_w)
730
+
731
+ # ---------- 原地重建逐原子 Glyph 与逐键变径 Tube(零 RemoveActor / 零崩溃!) ----------
732
+
733
+ def _build_lut_tables(self) -> tuple[np.ndarray, np.ndarray]:
734
+ """构建长度为 120 的颜色查找表 (RGBA uint8) 与 VdW 半径表 (float32)。"""
735
+ color_lut = np.full((120, 4), [140, 158, 178, 255], dtype=np.uint8)
736
+ vdw_lut = np.full(120, float(DEFAULT_VDW), dtype=np.float32)
737
+ for z, elem in ELEMENTS.items():
738
+ if 0 <= z < 120:
739
+ c = elem.cpk_color
740
+ color_lut[z, :3] = [int(round(c[0] * 255)), int(round(c[1] * 255)), int(round(c[2] * 255))]
741
+ vdw_lut[z] = float(elem.vdw_radius)
742
+ scheme_map = COLOR_SCHEMES.get(self._color_scheme, STUDIO_CPK_COLORS)
743
+ for z, c in scheme_map.items():
744
+ if 0 <= z < 120:
745
+ color_lut[z, :3] = [int(round(c[0] * 255)), int(round(c[1] * 255)), int(round(c[2] * 255))]
746
+ return color_lut, vdw_lut
747
+
748
+ def _rebuild_massive_gpu(self, n: int) -> None:
749
+ """超大体系(>2000 原子/键)全矢量化 NumPy + GPU GLSL Impostor 极速渲染管线。"""
750
+ color_lut, vdw_lut = self._build_lut_tables()
751
+ z_raw = np.asarray(self._atomic_numbers[:n], dtype=np.int32)
752
+ z_clip = np.clip(z_raw, 0, 119)
753
+ atom_rgba = color_lut[z_clip].copy()
754
+ for idx, col in self._per_atom_colors.items():
755
+ if col is not None and 0 <= idx < n:
756
+ atom_rgba[idx, 0] = max(0, min(255, int(round(col[0] * 255.0))))
757
+ atom_rgba[idx, 1] = max(0, min(255, int(round(col[1] * 255.0))))
758
+ atom_rgba[idx, 2] = max(0, min(255, int(round(col[2] * 255.0))))
759
+ op = np.clip(np.asarray(self._atom_opacities[:n], dtype=np.float32), 0.0, 1.0)
760
+ if len(op) == n:
761
+ atom_rgba[:, 3] = np.round(255.0 * op).astype(np.uint8)
762
+
763
+ ind_sc = (
764
+ self._per_atom_scales[:n].astype(np.float32)
765
+ if len(self._per_atom_scales) >= n
766
+ else np.ones(n, dtype=np.float32)
767
+ )
768
+ if self._mode == RepresentationMode.LINE:
769
+ atom_radii_np = np.zeros(n, dtype=np.float32)
770
+ elif self._mode == RepresentationMode.STICK:
771
+ atom_radii_np = np.float32(self.BASE_STICK_RADIUS * self._bond_scale) * ind_sc
772
+ else:
773
+ atom_radii_np = vdw_lut[z_clip] * np.float32(self._base_mode_atom_factor() * self._atom_scale) * ind_sc
774
+ if not self.show_hydrogens:
775
+ atom_radii_np[z_raw == 1] = 0.0
776
+
777
+ coords_f32 = np.ascontiguousarray(self._coordinates[:n], dtype=np.float32)
778
+ self._atom_points.SetData(_vtk_numpy_support.numpy_to_vtk(coords_f32, deep=1))
779
+ r_vtk = _vtk_numpy_support.numpy_to_vtk(np.ascontiguousarray(atom_radii_np, dtype=np.float32), deep=1)
780
+ r_vtk.SetName("atom_radius")
781
+ c_vtk = _vtk_numpy_support.numpy_to_vtk(np.ascontiguousarray(atom_rgba, dtype=np.uint8), deep=1)
782
+ c_vtk.SetName("atom_color")
783
+ self._atom_radii = r_vtk
784
+ self._atom_colors = c_vtk
785
+ pd = self._atom_polydata.GetPointData()
786
+ pd.SetScalars(r_vtk)
787
+ pd.AddArray(c_vtk)
788
+ if self._massive_vert_count != n:
789
+ ca = vtk.vtkCellArray()
790
+ ca.SetData(
791
+ _vtk_numpy_support.numpy_to_vtk(np.arange(n + 1, dtype=np.int64), deep=1),
792
+ _vtk_numpy_support.numpy_to_vtk(np.arange(n, dtype=np.int64), deep=1),
793
+ )
794
+ self._atom_polydata.SetVerts(ca)
795
+ self._massive_vert_count = n
796
+ self._atom_points.Modified()
797
+ self._atom_polydata.Modified()
798
+
799
+ if self._atom_actor is not None:
800
+ if self._mode == RepresentationMode.LINE:
801
+ self._atom_actor.VisibilityOff()
802
+ else:
803
+ mapper = self._atom_gpu_sphere_mapper or self._atom_glyph_mapper
804
+ if self._atom_actor.GetMapper() is not mapper:
805
+ self._atom_actor.SetMapper(mapper)
806
+ self._atom_actor.VisibilityOn()
807
+
808
+ show_b = self.show_bonds and (self._mode not in (RepresentationMode.CPK, RepresentationMode.SPACE_FILL))
809
+ if not (show_b and self._bonds):
810
+ if self._bond_actor is not None:
811
+ self._bond_actor.VisibilityOff()
812
+ return
813
+
814
+ b_arr = np.asarray(self._bonds, dtype=np.int64)
815
+ bi_raw = b_arr[:, 0]
816
+ bj_raw = b_arr[:, 1]
817
+ mask = (bi_raw >= 0) & (bi_raw < n) & (bj_raw >= 0) & (bj_raw < n) & (bi_raw != bj_raw)
818
+ if not self.show_hydrogens:
819
+ mask &= (z_raw[np.clip(bi_raw, 0, n - 1)] != 1) & (z_raw[np.clip(bj_raw, 0, n - 1)] != 1)
820
+ valid_idx = np.flatnonzero(mask)
821
+ if len(valid_idx) == 0:
822
+ self._bond_actor.VisibilityOff()
823
+ return
824
+
825
+ bi = bi_raw[valid_idx]
826
+ bj = bj_raw[valid_idx]
827
+ p1 = coords_f32[bi]
828
+ p2 = coords_f32[bj]
829
+ d = p2 - p1
830
+ lens = np.linalg.norm(d, axis=1)
831
+ len_mask = lens > 1e-4
832
+ valid_idx = valid_idx[len_mask]
833
+ nb = len(valid_idx)
834
+ if nb == 0:
835
+ self._bond_actor.VisibilityOff()
836
+ return
837
+
838
+ bi = bi[len_mask]
839
+ bj = bj[len_mask]
840
+ p1 = p1[len_mask]
841
+ p2 = p2[len_mask]
842
+ d = d[len_mask]
843
+ lens = lens[len_mask]
844
+
845
+ c1 = atom_rgba[bi].copy()
846
+ c2 = atom_rgba[bj].copy()
847
+ a_pair = np.maximum(atom_rgba[bi, 3], atom_rgba[bj, 3])
848
+ c1[:, 3] = a_pair
849
+ c2[:, 3] = a_pair
850
+ if self._per_bond_colors:
851
+ idx_to_pos = {int(b_i): pos for pos, b_i in enumerate(valid_idx)}
852
+ for b_idx, bc in self._per_bond_colors.items():
853
+ pos = idx_to_pos.get(int(b_idx))
854
+ if pos is not None and bc is not None:
855
+ rgb = (
856
+ max(0, min(255, int(round(bc[0] * 255.0)))),
857
+ max(0, min(255, int(round(bc[1] * 255.0)))),
858
+ max(0, min(255, int(round(bc[2] * 255.0)))),
859
+ )
860
+ c1[pos, :3] = rgb
861
+ c2[pos, :3] = rgb
862
+
863
+ if self._mode == RepresentationMode.LINE or self._bond_gpu_stick_mapper is None:
864
+ pts = np.empty((2 * nb, 3), dtype=np.float32)
865
+ pts[0::2] = p1
866
+ pts[1::2] = p2
867
+ cols = np.empty((2 * nb, 4), dtype=np.uint8)
868
+ cols[0::2] = c1
869
+ cols[1::2] = c2
870
+ self._bond_points.SetData(_vtk_numpy_support.numpy_to_vtk(pts, deep=1))
871
+ b_col_vtk = _vtk_numpy_support.numpy_to_vtk(cols, deep=1)
872
+ b_col_vtk.SetName("bond_color")
873
+ b_rad_vtk = _vtk_numpy_support.numpy_to_vtk(np.full(2 * nb, 0.04, dtype=np.float32), deep=1)
874
+ b_rad_vtk.SetName("bond_radius")
875
+ self._bond_colors = b_col_vtk
876
+ self._bond_radii = b_rad_vtk
877
+ bpd = self._bond_polydata.GetPointData()
878
+ bpd.SetScalars(b_rad_vtk)
879
+ bpd.AddArray(b_col_vtk)
880
+ self._bond_lines.SetData(
881
+ _vtk_numpy_support.numpy_to_vtk(np.arange(0, 2 * nb + 1, 2, dtype=np.int64), deep=1),
882
+ _vtk_numpy_support.numpy_to_vtk(np.arange(2 * nb, dtype=np.int64), deep=1),
883
+ )
884
+ if self._bond_mapper.GetInputConnection(0, 0) is not None:
885
+ self._bond_mapper.SetInputConnection(None)
886
+ self._bond_mapper.SetInputData(self._bond_polydata)
887
+ if self._bond_actor.GetMapper() is not self._bond_mapper:
888
+ self._bond_actor.SetMapper(self._bond_mapper)
889
+ self._bond_actor.GetProperty().SetLineWidth(4.5 if self._mode == RepresentationMode.STICK else 1.25)
890
+ self._bond_points.Modified()
891
+ self._bond_lines.Modified()
892
+ self._bond_polydata.Modified()
893
+ self._bond_actor.VisibilityOn()
894
+ else:
895
+ u = d / lens[:, None]
896
+ mid = 0.5 * (p1 + p2)
897
+ centers = np.ascontiguousarray(np.vstack([0.5 * (p1 + mid), 0.5 * (mid + p2)]), dtype=np.float32)
898
+ ori = np.ascontiguousarray(np.vstack([u, u]), dtype=np.float32)
899
+ hl = (0.5 * lens).astype(np.float32)
900
+ base_r = self.BASE_STICK_BOND_RADIUS if self._mode == RepresentationMode.STICK else self.BASE_BOND_RADIUS
901
+ b_ind = (
902
+ self._per_bond_scales[valid_idx].astype(np.float32)
903
+ if len(self._per_bond_scales) >= len(self._bonds)
904
+ else np.ones(nb, dtype=np.float32)
905
+ )
906
+ r_half = np.float32(base_r * self._bond_scale) * np.concatenate([b_ind, b_ind]).astype(np.float32)
907
+ sc_arr = np.ascontiguousarray(np.column_stack([np.concatenate([hl, hl]), r_half, r_half]), dtype=np.float32)
908
+ b_cols = np.ascontiguousarray(np.vstack([c1, c2]), dtype=np.uint8)
909
+ st_pts = vtk.vtkPoints()
910
+ st_pts.SetData(_vtk_numpy_support.numpy_to_vtk(centers, deep=1))
911
+ st_ca = vtk.vtkCellArray()
912
+ st_ca.SetData(
913
+ _vtk_numpy_support.numpy_to_vtk(np.arange(2 * nb + 1, dtype=np.int64), deep=1),
914
+ _vtk_numpy_support.numpy_to_vtk(np.arange(2 * nb, dtype=np.int64), deep=1),
915
+ )
916
+ self._bond_stick_polydata.SetPoints(st_pts)
917
+ self._bond_stick_polydata.SetVerts(st_ca)
918
+ ori_v = _vtk_numpy_support.numpy_to_vtk(ori, deep=1)
919
+ ori_v.SetName("bond_ori")
920
+ sc_v = _vtk_numpy_support.numpy_to_vtk(sc_arr, deep=1)
921
+ sc_v.SetName("bond_scale")
922
+ col_v = _vtk_numpy_support.numpy_to_vtk(b_cols, deep=1)
923
+ col_v.SetName("bond_color")
924
+ st_pd = self._bond_stick_polydata.GetPointData()
925
+ st_pd.AddArray(ori_v)
926
+ st_pd.AddArray(sc_v)
927
+ st_pd.AddArray(col_v)
928
+ self._bond_stick_polydata.Modified()
929
+ if self._bond_actor.GetMapper() is not self._bond_gpu_stick_mapper:
930
+ self._bond_actor.SetMapper(self._bond_gpu_stick_mapper)
931
+ self._bond_actor.VisibilityOn()
932
+
933
+ def _rebuild_vtk_molecule_in_place(self) -> None:
934
+ """
935
+ 原地更新常驻 `_atom_polydata` 与 `_bond_polydata`:
936
+ - 每个原子写入独立半径与独立 RGB 颜色
937
+ - 每条化学键写入独立半径与独立 RGB 颜色(或两端原子半键双色)
938
+ - 小分子走 18/24 面高清 Cylinder/Sphere;>2000 原子/键自动切换 GPU GLSL Impostor 零拷贝极速管线
939
+ """
940
+ if self._viewer is None or vtk is None:
941
+ return
942
+ self._ensure_scene_initialized()
943
+ if self._atom_points is None or self._bond_points is None:
944
+ return
945
+
946
+ if self._coordinates is None or self._atomic_numbers is None or self._n_atoms == 0:
947
+ self._atom_points.Reset()
948
+ self._bond_points.Reset()
949
+ self._bond_lines.Reset()
950
+ self._atom_polydata.Modified()
951
+ self._bond_polydata.Modified()
952
+ if self._atom_actor is not None:
953
+ self._atom_actor.VisibilityOff()
954
+ if self._bond_actor is not None:
955
+ self._bond_actor.VisibilityOff()
956
+ self._update_glow_layers()
957
+ self._update_labels_in_place()
958
+ return
959
+
960
+ n = min(self._n_atoms, len(self._coordinates), len(self._atomic_numbers))
961
+ is_massive = (n > 2000 or len(self._bonds) > 2000)
962
+ if is_massive and _vtk_numpy_support is not None and self._atom_gpu_sphere_mapper is not None:
963
+ self._rebuild_massive_gpu(n)
964
+ self._update_glow_layers()
965
+ self._update_labels_in_place()
966
+ return
967
+
968
+ # 从超大体系切回经典小分子时,恢复 Glyph3DMapper 与 TubeFilter 原生可增删对象
969
+ if self._massive_vert_count != -1 or not isinstance(self._atom_radii, vtk.vtkFloatArray):
970
+ self._atom_polydata.SetVerts(None)
971
+ self._massive_vert_count = -1
972
+ self._atom_points = vtk.vtkPoints()
973
+ self._atom_radii = vtk.vtkFloatArray()
974
+ self._atom_radii.SetName("atom_radius")
975
+ self._atom_colors = vtk.vtkUnsignedCharArray()
976
+ self._atom_colors.SetName("atom_color")
977
+ self._atom_colors.SetNumberOfComponents(4)
978
+ self._atom_polydata.SetPoints(self._atom_points)
979
+ self._atom_polydata.GetPointData().SetScalars(self._atom_radii)
980
+ self._atom_polydata.GetPointData().AddArray(self._atom_colors)
981
+ for poly, _r, _c, _a, _f, _af in self._glow_layers:
982
+ poly.SetPoints(self._atom_points)
983
+ if not isinstance(self._bond_radii, vtk.vtkFloatArray):
984
+ self._bond_points = vtk.vtkPoints()
985
+ self._bond_lines = vtk.vtkCellArray()
986
+ self._bond_radii = vtk.vtkFloatArray()
987
+ self._bond_radii.SetName("bond_radius")
988
+ self._bond_colors = vtk.vtkUnsignedCharArray()
989
+ self._bond_colors.SetName("bond_color")
990
+ self._bond_colors.SetNumberOfComponents(4)
991
+ self._bond_polydata.SetPoints(self._bond_points)
992
+ self._bond_polydata.SetLines(self._bond_lines)
993
+ self._bond_polydata.GetPointData().SetScalars(self._bond_radii)
994
+ self._bond_polydata.GetPointData().AddArray(self._bond_colors)
995
+
996
+ if self._atom_actor is not None and self._atom_actor.GetMapper() is not self._atom_glyph_mapper:
997
+ self._atom_actor.SetMapper(self._atom_glyph_mapper)
998
+ if self._bond_actor is not None and self._bond_actor.GetMapper() is not self._bond_mapper:
999
+ self._bond_actor.SetMapper(self._bond_mapper)
1000
+
1001
+ self._atom_points.Reset()
1002
+ self._atom_radii.Reset()
1003
+ self._atom_radii.SetName("atom_radius")
1004
+ self._atom_colors.Reset()
1005
+ self._atom_colors.SetName("atom_color")
1006
+ self._atom_colors.SetNumberOfComponents(4)
1007
+
1008
+ self._bond_points.Reset()
1009
+ self._bond_lines.Reset()
1010
+ self._bond_radii.Reset()
1011
+ self._bond_radii.SetName("bond_radius")
1012
+ self._bond_colors.Reset()
1013
+ self._bond_colors.SetName("bond_color")
1014
+ self._bond_colors.SetNumberOfComponents(4)
1015
+
1016
+ # 动态调节原子球多边形细分精度(小分子高保真 24x24;超大体系/动力学盒子 8x8 或 6x6,减少 96.5% 多边形开销与显存压力!)
1017
+ if self._atom_sphere is not None:
1018
+ if n > 50000:
1019
+ self._atom_sphere.SetThetaResolution(6)
1020
+ self._atom_sphere.SetPhiResolution(6)
1021
+ elif n > 2000:
1022
+ self._atom_sphere.SetThetaResolution(8)
1023
+ self._atom_sphere.SetPhiResolution(8)
1024
+ else:
1025
+ self._atom_sphere.SetThetaResolution(24)
1026
+ self._atom_sphere.SetPhiResolution(24)
1027
+
1028
+ atom_rgb_cache: list[tuple[int, int, int]] = []
1029
+
1030
+ # 1. 写入全部原子球顶点、逐原子半径、逐原子 RGB
1031
+ for i in range(n):
1032
+ x, y, z = self._coordinates[i]
1033
+ r_val = self.get_effective_atom_radius(i)
1034
+ cr, cg, cb = self.get_effective_atom_color(i)
1035
+ rgb_u8 = (
1036
+ max(0, min(255, int(round(cr * 255.0)))),
1037
+ max(0, min(255, int(round(cg * 255.0)))),
1038
+ max(0, min(255, int(round(cb * 255.0)))),
1039
+ )
1040
+ atom_rgb_cache.append(rgb_u8)
1041
+ self._atom_points.InsertNextPoint(float(x), float(y), float(z))
1042
+ self._atom_radii.InsertNextValue(float(r_val))
1043
+ alpha = int(round(255 * self._atom_opacities[i])) if i < len(self._atom_opacities) else 255
1044
+ self._atom_colors.InsertNextTuple4(*rgb_u8,alpha)
1045
+
1046
+ self._atom_points.Modified()
1047
+ self._atom_radii.Modified()
1048
+ self._atom_colors.Modified()
1049
+ self._atom_polydata.Modified()
1050
+ if self._atom_glyph_mapper is not None:
1051
+ self._atom_glyph_mapper.Modified()
1052
+ if self._atom_actor is not None:
1053
+ self._atom_actor.VisibilityOn()
1054
+
1055
+ # 2. 写入全部化学键(CPK 空间填充模式下或关闭显示键时隐藏键圆柱)
1056
+ show_b = self.show_bonds and (self._mode not in (RepresentationMode.CPK, RepresentationMode.SPACE_FILL))
1057
+ if show_b and self._bonds:
1058
+ pt_cursor = 0
1059
+ if is_massive:
1060
+ # 宏观超大体系 / 动力学盒子:断开 CPU TubeFilter 管道,直连 GPU 硬件管线渲染线条!
1061
+ # 显存直接执行硬件着色,免除 1000 万个 CPU 多边形与数 GB 内存暴涨!
1062
+ if self._bond_mapper.GetInputConnection(0, 0) is not None:
1063
+ self._bond_mapper.SetInputConnection(None)
1064
+ self._bond_mapper.SetInputData(self._bond_polydata)
1065
+ self._bond_actor.GetProperty().SetLineWidth(1.8)
1066
+
1067
+ for b_idx, (i, j, order) in enumerate(self._bonds):
1068
+ if not (0 <= i < n and 0 <= j < n) or i == j:
1069
+ continue
1070
+ if not self.show_hydrogens and (int(self._atomic_numbers[i]) == 1 or int(self._atomic_numbers[j]) == 1):
1071
+ continue
1072
+ p1 = self._coordinates[i]
1073
+ p2 = self._coordinates[j]
1074
+ c1 = atom_rgb_cache[i]
1075
+ c2 = atom_rgb_cache[j]
1076
+ self._bond_points.InsertNextPoint(float(p1[0]), float(p1[1]), float(p1[2]))
1077
+ self._bond_points.InsertNextPoint(float(p2[0]), float(p2[1]), float(p2[2]))
1078
+ self._bond_radii.InsertNextValue(0.05)
1079
+ self._bond_radii.InsertNextValue(0.05)
1080
+ self._bond_colors.InsertNextTuple4(c1[0], c1[1], c1[2], 255)
1081
+ self._bond_colors.InsertNextTuple4(c2[0], c2[1], c2[2], 255)
1082
+ self._bond_lines.InsertNextCell(2)
1083
+ self._bond_lines.InsertCellPoint(pt_cursor)
1084
+ self._bond_lines.InsertCellPoint(pt_cursor + 1)
1085
+ pt_cursor += 2
1086
+ else:
1087
+ # 经典小分子:连接高品质 18 面圆柱 TubeFilter
1088
+ if self._bond_mapper.GetInputConnection(0, 0) is None:
1089
+ self._bond_mapper.SetInputConnection(self._bond_tube_filter.GetOutputPort())
1090
+
1091
+ def _add_tube_segment(p_start: np.ndarray, p_end: np.ndarray, rad: float, rgb_tuple: tuple[int, int, int]):
1092
+ nonlocal pt_cursor
1093
+ self._bond_points.InsertNextPoint(float(p_start[0]), float(p_start[1]), float(p_start[2]))
1094
+ self._bond_points.InsertNextPoint(float(p_end[0]), float(p_end[1]), float(p_end[2]))
1095
+ self._bond_radii.InsertNextValue(float(rad))
1096
+ self._bond_radii.InsertNextValue(float(rad))
1097
+ self._bond_colors.InsertNextTuple4(*rgb_tuple)
1098
+ self._bond_colors.InsertNextTuple4(*rgb_tuple)
1099
+ self._bond_lines.InsertNextCell(2)
1100
+ self._bond_lines.InsertCellPoint(pt_cursor)
1101
+ self._bond_lines.InsertCellPoint(pt_cursor + 1)
1102
+ pt_cursor += 2
1103
+
1104
+ for b_idx, (i, j, order) in enumerate(self._bonds):
1105
+ if not (0 <= i < n and 0 <= j < n) or i == j:
1106
+ continue
1107
+ if not self.show_hydrogens and (int(self._atomic_numbers[i]) == 1 or int(self._atomic_numbers[j]) == 1):
1108
+ continue
1109
+
1110
+ p1 = self._coordinates[i].astype(np.float64)
1111
+ p2 = self._coordinates[j].astype(np.float64)
1112
+ vec = p2 - p1
1113
+ length = float(np.linalg.norm(vec))
1114
+ if length < 1e-4:
1115
+ continue
1116
+
1117
+ r_bond = self.get_effective_bond_radius(b_idx)
1118
+ if b_idx in self._per_bond_colors and self._per_bond_colors[b_idx] is not None:
1119
+ bc = self._per_bond_colors[b_idx]
1120
+ c1_u8 = (
1121
+ max(0, min(255, int(round(bc[0] * 255.0)))),
1122
+ max(0, min(255, int(round(bc[1] * 255.0)))),
1123
+ max(0, min(255, int(round(bc[2] * 255.0)))),
1124
+ )
1125
+ c2_u8 = c1_u8
1126
+ else:
1127
+ c1_u8 = atom_rgb_cache[i]
1128
+ c2_u8 = atom_rgb_cache[j]
1129
+
1130
+ # A bond fades with the less transparent endpoint, keeping boundary bonds legible.
1131
+ alpha = int(round(255 * max(self._atom_opacities[i], self._atom_opacities[j])))
1132
+ c1_u8 = tuple(c1_u8) + (alpha,)
1133
+ c2_u8 = tuple(c2_u8) + (alpha,)
1134
+ vis_order = 2 if int(order) == 4 else max(1, min(3, int(order)))
1135
+ if vis_order == 1 or self._mode == RepresentationMode.LINE:
1136
+ mid = 0.5 * (p1 + p2)
1137
+ _add_tube_segment(p1, mid, r_bond, c1_u8)
1138
+ _add_tube_segment(mid, p2, r_bond, c2_u8)
1139
+ else:
1140
+ # 计算垂直于键方向的偏移向量(用于双键/三键平行多圆柱)
1141
+ u = vec / length
1142
+ ref = np.array([0.0, 0.0, 1.0]) if abs(u[2]) < 0.85 else np.array([0.0, 1.0, 0.0])
1143
+ perp = np.cross(u, ref)
1144
+ perp /= (float(np.linalg.norm(perp)) + 1e-12)
1145
+
1146
+ if vis_order == 2:
1147
+ sub_r = r_bond * 0.62
1148
+ sep = r_bond * 1.15
1149
+ for sign in (-1.0, 1.0):
1150
+ off = perp * (sign * sep)
1151
+ pa, pb = p1 + off, p2 + off
1152
+ mid = 0.5 * (pa + pb)
1153
+ _add_tube_segment(pa, mid, sub_r, c1_u8)
1154
+ _add_tube_segment(mid, pb, sub_r, c2_u8)
1155
+ else:
1156
+ sub_r = r_bond * 0.52
1157
+ sep = r_bond * 1.35
1158
+ for mult in (-1.0, 0.0, 1.0):
1159
+ off = perp * (mult * sep)
1160
+ pa, pb = p1 + off, p2 + off
1161
+ mid = 0.5 * (pa + pb)
1162
+ _add_tube_segment(pa, mid, sub_r, c1_u8)
1163
+ _add_tube_segment(mid, pb, sub_r, c2_u8)
1164
+
1165
+ self._bond_points.Modified()
1166
+ self._bond_lines.Modified()
1167
+ self._bond_radii.Modified()
1168
+ self._bond_colors.Modified()
1169
+ self._bond_polydata.Modified()
1170
+ if self._bond_tube_filter is not None:
1171
+ self._bond_tube_filter.Modified()
1172
+ if self._bond_actor is not None:
1173
+ self._bond_actor.SetVisibility(pt_cursor > 0)
1174
+ else:
1175
+ if self._bond_actor is not None:
1176
+ self._bond_actor.VisibilityOff()
1177
+
1178
+ self._update_glow_layers()
1179
+ self._update_labels_in_place()
1180
+
1181
+ def _update_glow_layers(self):
1182
+ if self._n_atoms > 2000:
1183
+ for poly, radii, colors, actor, factor, alpha_factor in self._glow_layers:
1184
+ actor.SetVisibility(False)
1185
+ return
1186
+ for poly, radii, colors, actor, factor, alpha_factor in self._glow_layers:
1187
+ radii.Reset(); colors.Reset(); colors.SetNumberOfComponents(4)
1188
+ visible = False
1189
+ for i in range(self._n_atoms):
1190
+ rgb_strength = self._atom_glows.get(i, (0.3,0.8,1.,0.))
1191
+ strength = float(rgb_strength[3])
1192
+ opacity = self._atom_opacities[i] if i < len(self._atom_opacities) else 1.
1193
+ radius = self.get_effective_atom_radius(i)
1194
+ radii.InsertNextValue(radius*factor if strength>0 else 0.)
1195
+ colors.InsertNextTuple4(*(int(255*max(0.,min(1.,float(c)))) for c in rgb_strength[:3]),int(255*alpha_factor*strength*opacity))
1196
+ visible = visible or (strength>0 and opacity>0 and radius>0)
1197
+ radii.Modified(); colors.Modified(); poly.Modified(); actor.SetVisibility(visible)
1198
+
1199
+ def _update_labels_in_place(self) -> None:
1200
+ if self._n_atoms > 2000 and self.label_scope != "selected":
1201
+ if self._native_labels is not None:
1202
+ self._native_labels.actor.VisibilityOff()
1203
+ return
1204
+ if self._native_labels is not None:
1205
+ self._native_labels.update()
1206
+
1207
+ # ---------- 场景快照渲染 ----------
1208
+
1209
+ def set_snapshot(self, snapshot: RenderSnapshot, reset_cam: bool = True) -> None:
1210
+ """设置渲染快照并原地更新逐原子/逐键常驻 VTK 对象。"""
1211
+ previous_n_atoms = int(getattr(self, "_n_atoms", 0))
1212
+ fit_initial_small_system = 0 < snapshot.num_atoms <= 3 and snapshot.num_atoms != previous_n_atoms
1213
+ self._atom_ids = list(snapshot.atom_ids)
1214
+ self._id_to_idx = {aid: i for i, aid in enumerate(self._atom_ids)}
1215
+ self._bonds = list(snapshot.bonds)
1216
+ self._bond_ids = list(snapshot.bond_ids) if snapshot.bond_ids is not None else []
1217
+ self._n_atoms = snapshot.num_atoms
1218
+ self._coordinates = snapshot.coordinates.copy().astype(np.float32) if len(snapshot.coordinates) > 0 else np.zeros((0, 3), dtype=np.float32)
1219
+ self._atomic_numbers = snapshot.atomic_numbers.copy()
1220
+ self._cell_matrix = None if snapshot.cell_matrix is None else np.asarray(snapshot.cell_matrix, dtype=np.float64).copy()
1221
+ cell_origin = getattr(snapshot, "cell_origin", None)
1222
+ self._cell_origin = np.zeros(3, dtype=np.float64) if cell_origin is None else np.asarray(cell_origin, dtype=np.float64).reshape(3).copy()
1223
+
1224
+ values = snapshot.atom_opacities
1225
+ self._atom_opacities = np.ones(self._n_atoms) if values is None else np.clip(np.asarray(values,dtype=float),0.,1.)
1226
+ self._atom_glows = dict(snapshot.atom_glows or {})
1227
+
1228
+ # 解析逐原子独立缩放比例
1229
+ self._per_atom_scales = np.ones(self._n_atoms, dtype=np.float32)
1230
+ if snapshot.atom_scales is not None:
1231
+ if isinstance(snapshot.atom_scales, dict):
1232
+ for k, v in snapshot.atom_scales.items():
1233
+ idx = self._id_to_idx.get(k, k if isinstance(k, int) else -1)
1234
+ if 0 <= idx < self._n_atoms:
1235
+ self._per_atom_scales[idx] = float(v)
1236
+ else:
1237
+ arr = np.asarray(snapshot.atom_scales, dtype=np.float32)
1238
+ m = min(self._n_atoms, len(arr))
1239
+ self._per_atom_scales[:m] = arr[:m]
1240
+
1241
+ # 解析逐原子自定义颜色
1242
+ self._per_atom_colors = {}
1243
+ if snapshot.atom_colors:
1244
+ for k, col in snapshot.atom_colors.items():
1245
+ if col is None:
1246
+ continue
1247
+ idx = self._id_to_idx.get(k, k if isinstance(k, int) else -1)
1248
+ if 0 <= idx < self._n_atoms:
1249
+ self._per_atom_colors[idx] = (float(col[0]), float(col[1]), float(col[2]))
1250
+
1251
+ # 解析逐键独立粗细比例
1252
+ n_bonds = len(self._bonds)
1253
+ self._per_bond_scales = np.ones(n_bonds, dtype=np.float32)
1254
+ if snapshot.bond_scales is not None:
1255
+ if isinstance(snapshot.bond_scales, dict):
1256
+ bid_to_bidx = {bid: idx for idx, bid in enumerate(self._bond_ids)}
1257
+ for k, v in snapshot.bond_scales.items():
1258
+ b_idx = bid_to_bidx.get(k, k if isinstance(k, int) else -1)
1259
+ if 0 <= b_idx < n_bonds:
1260
+ self._per_bond_scales[b_idx] = float(v)
1261
+ else:
1262
+ arr = np.asarray(snapshot.bond_scales, dtype=np.float32)
1263
+ m = min(n_bonds, len(arr))
1264
+ self._per_bond_scales[:m] = arr[:m]
1265
+
1266
+ # 解析逐键自定义颜色
1267
+ self._per_bond_colors = {}
1268
+ if snapshot.bond_colors:
1269
+ bid_to_bidx = {bid: idx for idx, bid in enumerate(self._bond_ids)}
1270
+ for k, col in snapshot.bond_colors.items():
1271
+ if col is None:
1272
+ continue
1273
+ b_idx = bid_to_bidx.get(k, k if isinstance(k, int) else -1)
1274
+ if 0 <= b_idx < n_bonds:
1275
+ self._per_bond_colors[b_idx] = (float(col[0]), float(col[1]), float(col[2]))
1276
+
1277
+ self.show_hydrogens = bool(snapshot.show_hydrogens)
1278
+ self.show_bonds = bool(snapshot.show_bonds)
1279
+ self.show_labels = bool(snapshot.show_labels)
1280
+ self.show_symbols = bool(snapshot.show_symbols)
1281
+ self.show_axes = bool(snapshot.show_axes)
1282
+ if getattr(self, "_axes_marker", None) is not None:
1283
+ try:
1284
+ self._axes_marker.SetEnabled(1 if self.show_axes else 0)
1285
+ except Exception:
1286
+ pass
1287
+ if getattr(self, "_origin_axes_actor", None) is not None:
1288
+ try:
1289
+ self._origin_axes_actor.SetVisibility(1 if self.show_axes else 0)
1290
+ except Exception:
1291
+ pass
1292
+ if snapshot.color_scheme:
1293
+ self._color_scheme = snapshot.color_scheme
1294
+
1295
+ if snapshot.selected_atoms is not None:
1296
+ self._selected = {a for a in snapshot.selected_atoms if a in self._id_to_idx}
1297
+ if snapshot.selected_bonds is not None:
1298
+ self._selected_bonds = set(snapshot.selected_bonds)
1299
+ self._measure_chain = list(snapshot.measure_chain) if getattr(snapshot, "measure_chain", None) else None
1300
+
1301
+ if self._viewer is None or vtk is None:
1302
+ return
1303
+
1304
+ self._ensure_scene_initialized()
1305
+ self.clear_rubberband()
1306
+ self._rebuild_vtk_molecule_in_place()
1307
+ self._apply_mode()
1308
+ self._update_highlights_in_place()
1309
+ self._update_unit_cell()
1310
+
1311
+ if reset_cam or not self._camera_state or fit_initial_small_system:
1312
+ self.reset_camera()
1313
+ else:
1314
+ self.render()
1315
+
1316
+ def _update_unit_cell(self) -> None:
1317
+ """Create/update the persistent 12-edge crystallographic cell actor."""
1318
+ if self._viewer is None or vtk is None:
1319
+ return
1320
+ if self._cell_matrix is None:
1321
+ if self._cell_actor is not None:
1322
+ self._cell_actor.VisibilityOff()
1323
+ return
1324
+ matrix = np.asarray(self._cell_matrix, dtype=np.float64)
1325
+ if matrix.shape != (3, 3) or not np.all(np.isfinite(matrix)):
1326
+ if self._cell_actor is not None:
1327
+ self._cell_actor.VisibilityOff()
1328
+ return
1329
+ from itertools import product
1330
+ corners = (np.asarray(list(product((0.0, 1.0), repeat=3))) @ matrix) + self._cell_origin
1331
+ edges = (
1332
+ (0, 1), (0, 2), (0, 4), (1, 3), (1, 5), (2, 3),
1333
+ (2, 6), (3, 7), (4, 5), (4, 6), (5, 7), (6, 7),
1334
+ )
1335
+ if self._cell_actor is None:
1336
+ self._cell_points = vtk.vtkPoints()
1337
+ lines = vtk.vtkCellArray()
1338
+ for begin, end in edges:
1339
+ line = vtk.vtkLine()
1340
+ line.GetPointIds().SetId(0, begin)
1341
+ line.GetPointIds().SetId(1, end)
1342
+ lines.InsertNextCell(line)
1343
+ self._cell_polydata = vtk.vtkPolyData()
1344
+ self._cell_polydata.SetPoints(self._cell_points)
1345
+ self._cell_polydata.SetLines(lines)
1346
+ mapper = vtk.vtkPolyDataMapper()
1347
+ mapper.SetInputData(self._cell_polydata)
1348
+ self._cell_actor = vtk.vtkActor()
1349
+ self._cell_actor.SetMapper(mapper)
1350
+ self._cell_actor.GetProperty().SetColor(0.30, 0.85, 0.95)
1351
+ self._cell_actor.GetProperty().SetOpacity(0.75)
1352
+ self._cell_actor.GetProperty().SetLineWidth(1.5)
1353
+ self._viewer.renderer.AddActor(self._cell_actor)
1354
+ self._cell_points.Reset()
1355
+ for point in corners:
1356
+ self._cell_points.InsertNextPoint(float(point[0]), float(point[1]), float(point[2]))
1357
+ self._cell_points.Modified()
1358
+ self._cell_polydata.Modified()
1359
+ self._cell_actor.VisibilityOn()
1360
+
1361
+ def _apply_mode(self) -> None:
1362
+ if self._surface_actor is not None and self._viewer is not None:
1363
+ self._surface_actor.VisibilityOff()
1364
+
1365
+ self._rebuild_vtk_molecule_in_place()
1366
+ if self._mode == RepresentationMode.SURFACE:
1367
+ self._build_surface()
1368
+
1369
+ # ---------- 实时逐原子 / 逐键样式更新接口(无需重建快照,毫秒级立即生效!) ----------
1370
+
1371
+ def set_single_atom_scale(self, atom_id: AtomId, scale: float) -> None:
1372
+ """单独修改某个原子的球体缩放比例并立即刷新 3D。"""
1373
+ idx = self._id_to_idx.get(atom_id)
1374
+ if idx is None or not (0 <= idx < len(self._per_atom_scales)):
1375
+ return
1376
+ self._per_atom_scales[idx] = max(0.20, min(3.50, float(scale)))
1377
+ self._rebuild_vtk_molecule_in_place()
1378
+ self._update_highlights_in_place()
1379
+ self.render()
1380
+
1381
+ def set_single_atom_color(self, atom_id: AtomId, color: tuple[float, float, float] | None) -> None:
1382
+ """单独修改某个原子的 RGB 颜色并立即刷新 3D。"""
1383
+ idx = self._id_to_idx.get(atom_id)
1384
+ if idx is None:
1385
+ return
1386
+ if color is None:
1387
+ self._per_atom_colors.pop(idx, None)
1388
+ else:
1389
+ self._per_atom_colors[idx] = (float(color[0]), float(color[1]), float(color[2]))
1390
+ self._rebuild_vtk_molecule_in_place()
1391
+ self.render()
1392
+
1393
+ def set_single_bond_scale(self, b_idx: int, scale: float) -> None:
1394
+ """单独修改某条化学键的粗细比例并立即刷新 3D。"""
1395
+ if not (0 <= b_idx < len(self._per_bond_scales)):
1396
+ return
1397
+ self._per_bond_scales[b_idx] = max(0.20, min(3.50, float(scale)))
1398
+ self._rebuild_vtk_molecule_in_place()
1399
+ self._update_highlights_in_place()
1400
+ self.render()
1401
+
1402
+ def set_single_bond_color(self, b_idx: int, color: tuple[float, float, float] | None) -> None:
1403
+ """单独修改某条化学键的 RGB 颜色并立即刷新 3D。"""
1404
+ if color is None:
1405
+ self._per_bond_colors.pop(b_idx, None)
1406
+ else:
1407
+ self._per_bond_colors[b_idx] = (float(color[0]), float(color[1]), float(color[2]))
1408
+ self._rebuild_vtk_molecule_in_place()
1409
+ self.render()
1410
+
1411
+ def set_color_scheme(self, scheme_name: str) -> None:
1412
+ """切换全局默认配色方案(未设自定义颜色的原子自动跟随切换)。"""
1413
+ if scheme_name in COLOR_SCHEMES:
1414
+ self._color_scheme = scheme_name
1415
+ self._rebuild_vtk_molecule_in_place()
1416
+ self.render()
1417
+
1418
+ def set_view_options(
1419
+ self,
1420
+ show_hydrogens: bool | None = None,
1421
+ show_bonds: bool | None = None,
1422
+ show_labels: bool | None = None,
1423
+ show_symbols: bool | None = None,
1424
+ show_axes: bool | None = None,
1425
+ ) -> None:
1426
+ if show_hydrogens is not None:
1427
+ self.show_hydrogens = bool(show_hydrogens)
1428
+ if show_bonds is not None:
1429
+ self.show_bonds = bool(show_bonds)
1430
+ if show_labels is not None:
1431
+ self.show_labels = bool(show_labels)
1432
+ if show_symbols is not None:
1433
+ self.show_symbols = bool(show_symbols)
1434
+ if show_axes is not None:
1435
+ self.show_axes = bool(show_axes)
1436
+ if self._viewer is not None:
1437
+ try:
1438
+ marker = getattr(self, "_axes_marker", None)
1439
+ if marker is not None:
1440
+ marker.SetEnabled(1 if self.show_axes else 0)
1441
+ elif self.show_axes:
1442
+ self._viewer.show_axes()
1443
+ else:
1444
+ self._viewer.hide_axes()
1445
+ except Exception:
1446
+ pass
1447
+ self._rebuild_vtk_molecule_in_place()
1448
+ self._update_highlights_in_place()
1449
+ self.render()
1450
+
1451
+ # ---------- 100% 纯 NumPy 相机读取与拾取(感知每个原子的独立缩放半径!) ----------
1452
+
1453
+ def _get_camera_params(self) -> tuple[np.ndarray, np.ndarray, np.ndarray, float]:
1454
+ if self._viewer is not None:
1455
+ try:
1456
+ cam = self._viewer.renderer.GetActiveCamera()
1457
+ return (
1458
+ np.array(cam.GetPosition(), dtype=np.float64),
1459
+ np.array(cam.GetFocalPoint(), dtype=np.float64),
1460
+ np.array(cam.GetViewUp(), dtype=np.float64),
1461
+ float(cam.GetViewAngle()),
1462
+ )
1463
+ except Exception:
1464
+ pass
1465
+ return (
1466
+ np.array([0.0, 0.0, 15.0], dtype=np.float64),
1467
+ np.zeros(3, dtype=np.float64),
1468
+ np.array([0.0, 1.0, 0.0], dtype=np.float64),
1469
+ 30.0,
1470
+ )
1471
+
1472
+ def _screen_to_ray_numpy(self, lx: float, ly: float, widget_w: int, widget_h: int) -> tuple[np.ndarray, np.ndarray]:
1473
+ w = max(1.0, float(widget_w))
1474
+ h = max(1.0, float(widget_h))
1475
+ cam_pos, cam_focal, cam_up, fov_y = self._get_camera_params()
1476
+ eye, forward, right, true_up, tx, ty = compute_camera_basis(
1477
+ cam_pos, cam_focal, cam_up, fov_y, w, h
1478
+ )
1479
+ nx = (2.0 * float(lx) / w) - 1.0
1480
+ ny = 1.0 - (2.0 * float(ly) / h)
1481
+ ray_dir = forward + (nx * tx) * right + (ny * ty) * true_up
1482
+ ray_dir /= (float(np.linalg.norm(ray_dir)) + 1e-12)
1483
+ return eye, ray_dir
1484
+
1485
+ def _project_points_to_qt_numpy(
1486
+ self, pts: np.ndarray, widget_w: int, widget_h: int
1487
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, float]:
1488
+ w = max(1.0, float(widget_w))
1489
+ h = max(1.0, float(widget_h))
1490
+ cam_pos, cam_focal, cam_up, fov_y = self._get_camera_params()
1491
+ eye, forward, right, true_up, tx, ty = compute_camera_basis(
1492
+ cam_pos, cam_focal, cam_up, fov_y, w, h
1493
+ )
1494
+ rel = np.asarray(pts, dtype=np.float64) - eye
1495
+ z_cam = np.maximum(0.1, rel @ forward)
1496
+ nx = (rel @ right) / (z_cam * tx)
1497
+ ny = (rel @ true_up) / (z_cam * ty)
1498
+ sx = 0.5 * w * (1.0 + nx)
1499
+ sy = 0.5 * h * (1.0 - ny)
1500
+ return sx, sy, z_cam, ty
1501
+
1502
+ def pick_atom_id_at_qt(self, lx: float, ly: float, widget_w: int, widget_h: int) -> AtomId | None:
1503
+ """100% 纯 NumPy 拾取原子(自动使用每个原子真实的独立缩放半径 get_effective_atom_radius)。"""
1504
+ if self._coordinates is None or self._n_atoms == 0 or len(self._atom_ids) == 0:
1505
+ return None
1506
+
1507
+ n = min(self._n_atoms, len(self._atom_ids), len(self._coordinates))
1508
+ coords = self._coordinates[:n]
1509
+ eye, ray_dir = self._screen_to_ray_numpy(lx, ly, widget_w, widget_h)
1510
+
1511
+ radii = np.array([
1512
+ (0.0 if (not self.show_hydrogens and int(self._atomic_numbers[i]) == 1) else max(0.38, self.get_effective_atom_radius(i) * 1.25))
1513
+ for i in range(n)
1514
+ ], dtype=np.float64)
1515
+
1516
+ hit_idx, _ = ray_sphere_intersect(eye, ray_dir, coords, radii)
1517
+ if 0 <= hit_idx < n and radii[hit_idx] > 0.0:
1518
+ return self._atom_ids[hit_idx]
1519
+
1520
+ sx, sy, z_cam, ty = self._project_points_to_qt_numpy(coords, widget_w, widget_h)
1521
+ dists_px = np.hypot(sx - float(lx), sy - float(ly))
1522
+ proj_r_px = np.where(
1523
+ radii > 0.0,
1524
+ np.maximum(18.0, (radii / (z_cam * ty)) * (0.5 * max(1.0, float(widget_h)))),
1525
+ -1.0,
1526
+ )
1527
+
1528
+ hits = np.where(dists_px <= proj_r_px)[0]
1529
+ if len(hits) > 0:
1530
+ order = sorted(hits, key=lambda idx: (round(float(z_cam[idx]), 2), float(dists_px[idx])))
1531
+ return self._atom_ids[int(order[0])]
1532
+
1533
+ return None
1534
+
1535
+ def pick_bond_idx_at_qt(self, lx: float, ly: float, widget_w: int, widget_h: int) -> int:
1536
+ """100% 纯 NumPy 拾取 3D 化学键(感知每条键的独立粗细)。"""
1537
+ if not self.show_bonds or self._coordinates is None or not self._bonds or self._n_atoms == 0:
1538
+ return -1
1539
+
1540
+ eye, ray_dir = self._screen_to_ray_numpy(lx, ly, widget_w, widget_h)
1541
+ best_bond = -1
1542
+ best_t = float("inf")
1543
+
1544
+ for b_idx, (i, j, _order) in enumerate(self._bonds):
1545
+ if 0 <= i < self._n_atoms and 0 <= j < self._n_atoms:
1546
+ if not self.show_hydrogens and (int(self._atomic_numbers[i]) == 1 or int(self._atomic_numbers[j]) == 1):
1547
+ continue
1548
+ tol_3d = max(0.25, self.get_effective_bond_radius(b_idx) * 3.0)
1549
+ dist, t_val = ray_segment_closest(
1550
+ eye, ray_dir, self._coordinates[i], self._coordinates[j]
1551
+ )
1552
+ if dist <= tol_3d and t_val < best_t:
1553
+ best_t = t_val
1554
+ best_bond = b_idx
1555
+
1556
+ if best_bond >= 0:
1557
+ return best_bond
1558
+
1559
+ sx, sy, z_cam, _ = self._project_points_to_qt_numpy(self._coordinates, widget_w, widget_h)
1560
+ best_d_px = 10.0
1561
+ for b_idx, (i, j, _order) in enumerate(self._bonds):
1562
+ if 0 <= i < self._n_atoms and 0 <= j < self._n_atoms:
1563
+ if not self.show_hydrogens and (int(self._atomic_numbers[i]) == 1 or int(self._atomic_numbers[j]) == 1):
1564
+ continue
1565
+ x1, y1 = float(sx[i]), float(sy[i])
1566
+ x2, y2 = float(sx[j]), float(sy[j])
1567
+ dx, dy = x2 - x1, y2 - y1
1568
+ l2 = dx * dx + dy * dy
1569
+ if l2 < 1e-4:
1570
+ continue
1571
+ t = max(0.18, min(0.82, ((lx - x1) * dx + (ly - y1) * dy) / l2))
1572
+ d_px = math.hypot(lx - (x1 + t * dx), ly - (y1 + t * dy))
1573
+ if d_px < best_d_px:
1574
+ best_d_px = d_px
1575
+ best_bond = b_idx
1576
+
1577
+ return best_bond
1578
+
1579
+ def unproject_qt_to_world(
1580
+ self, lx: float, ly: float, widget_w: int, widget_h: int, ref_point: np.ndarray | None = None
1581
+ ) -> np.ndarray:
1582
+ if ref_point is not None:
1583
+ center = np.asarray(ref_point, dtype=np.float64)
1584
+ elif self._coordinates is not None and len(self._coordinates) > 0:
1585
+ center = self._coordinates.mean(axis=0).astype(np.float64)
1586
+ else:
1587
+ center = np.zeros(3, dtype=np.float64)
1588
+
1589
+ eye, ray_dir = self._screen_to_ray_numpy(lx, ly, widget_w, widget_h)
1590
+ cam_pos, cam_focal, _, _ = self._get_camera_params()
1591
+ view_dir = cam_focal - cam_pos
1592
+ norm_v = float(np.linalg.norm(view_dir))
1593
+ view_dir = view_dir / (norm_v if norm_v > 1e-9 else 1.0)
1594
+
1595
+ denom = float(np.dot(ray_dir, view_dir))
1596
+ if abs(denom) < 1e-6:
1597
+ return center.astype(np.float32)
1598
+ t = float(np.dot(center - eye, view_dir)) / denom
1599
+ return (eye + t * ray_dir).astype(np.float32)
1600
+
1601
+ # ---------- 60 FPS 单原子实时拖拽(原子与所有相连化学键同步跟随!) ----------
1602
+
1603
+ def update_single_atom_coord(self, atom_id: AtomId, new_pos: np.ndarray) -> None:
1604
+ if self._coordinates is None or atom_id not in self._id_to_idx:
1605
+ return
1606
+ idx = self._id_to_idx[atom_id]
1607
+ if not (0 <= idx < self._n_atoms):
1608
+ return
1609
+ self._coordinates[idx] = np.asarray(new_pos, dtype=np.float32)
1610
+ self._rebuild_vtk_molecule_in_place()
1611
+ self._update_highlights_in_place()
1612
+ self.render()
1613
+
1614
+ def update_multi_atoms_coords(self, pos_map: dict[AtomId, np.ndarray]) -> None:
1615
+ """
1616
+ 实时批量更新多个选中原子的 3D 坐标及其关联化学键几何(用于框选/套索多原子拖拽平移,60fps 零卡顿)。
1617
+ """
1618
+ if self._coordinates is None or not pos_map:
1619
+ return
1620
+ updated_any = False
1621
+ for aid, new_pos in pos_map.items():
1622
+ idx = self._id_to_idx.get(aid)
1623
+ if idx is not None and 0 <= idx < self._n_atoms:
1624
+ self._coordinates[idx] = np.asarray(new_pos, dtype=np.float64)
1625
+ updated_any = True
1626
+ if not updated_any:
1627
+ return
1628
+ self._rebuild_vtk_molecule_in_place()
1629
+ self._update_highlights_in_place()
1630
+ self._update_labels_in_place()
1631
+ self.render()
1632
+
1633
+ def begin_interactive_lod(self) -> None:
1634
+ """
1635
+ P0-2 3D 旋转/缩放防卡顿加速:
1636
+ 交互开始时临时关闭高开销 FXAA,并对 >100 原子的大体系自动降低球体/圆柱细分面数。
1637
+ """
1638
+ if getattr(self, "_in_interactive_lod", False):
1639
+ return
1640
+ self._in_interactive_lod = True
1641
+ if self._viewer is None:
1642
+ return
1643
+ try:
1644
+ ren = getattr(self._viewer, "renderer", None)
1645
+ if ren is not None and hasattr(ren, "SetUseFXAA"):
1646
+ ren.SetUseFXAA(False)
1647
+ if self._n_atoms > 80:
1648
+ sphere = getattr(self, "_atom_sphere", None) or getattr(self, "_sphere_source", None)
1649
+ if sphere is not None:
1650
+ sphere.SetThetaResolution(8)
1651
+ sphere.SetPhiResolution(8)
1652
+ if getattr(self, "_bond_tube_filter", None) is not None:
1653
+ self._bond_tube_filter.SetNumberOfSides(6)
1654
+ except Exception:
1655
+ pass
1656
+
1657
+ def end_interactive_lod(self) -> None:
1658
+ """交互静止后恢复全分辨率球棍细分与 FXAA 抗锯齿。"""
1659
+ if not getattr(self, "_in_interactive_lod", False):
1660
+ return
1661
+ self._in_interactive_lod = False
1662
+ if self._viewer is None:
1663
+ return
1664
+ try:
1665
+ ren = getattr(self._viewer, "renderer", None)
1666
+ if ren is not None and hasattr(ren, "SetUseFXAA"):
1667
+ ren.SetUseFXAA(True)
1668
+ res = 16 if self._n_atoms > 500 else 28
1669
+ sides = 10 if self._n_atoms > 500 else 18
1670
+ sphere = getattr(self, "_atom_sphere", None) or getattr(self, "_sphere_source", None)
1671
+ if sphere is not None:
1672
+ sphere.SetThetaResolution(res)
1673
+ sphere.SetPhiResolution(res)
1674
+ if getattr(self, "_bond_tube_filter", None) is not None:
1675
+ self._bond_tube_filter.SetNumberOfSides(sides)
1676
+ self.render()
1677
+
1678
+ except Exception:
1679
+ pass
1680
+
1681
+ def zoom_camera(self, factor: float = 1.2) -> None:
1682
+ """通过按钮精确放大 (factor > 1) 或缩小 (factor < 1) 3D 相机视角。"""
1683
+ if self._viewer is None:
1684
+ return
1685
+ try:
1686
+ cam = getattr(self._viewer, "camera", None)
1687
+ if cam is None and hasattr(self._viewer, "renderer"):
1688
+ cam = self._viewer.renderer.GetActiveCamera()
1689
+ if cam is not None and hasattr(cam, "Zoom"):
1690
+ cam.Zoom(float(factor))
1691
+ if hasattr(self._viewer, "renderer"):
1692
+ self._viewer.renderer.ResetCameraClippingRange()
1693
+ self.render()
1694
+ except Exception:
1695
+ pass
1696
+
1697
+ def update_coordinates(self, coordinates: np.ndarray) -> None:
1698
+ coords = np.asarray(coordinates, dtype=np.float32)
1699
+ self._coordinates = coords.copy()
1700
+ self._rebuild_vtk_molecule_in_place()
1701
+ self._update_highlights_in_place()
1702
+ self.render()
1703
+
1704
+ # ---------- 原地更新高亮与橡皮筋(零 RemoveActor / 零 AddActor) ----------
1705
+
1706
+ def update_rubberband_3d(self, p1: np.ndarray, p2: np.ndarray) -> None:
1707
+ self._ensure_scene_initialized()
1708
+ if self._rubberband_line is None or self._rubberband_actor is None:
1709
+ return
1710
+ self._rubberband_line.SetPoint1(float(p1[0]), float(p1[1]), float(p1[2]))
1711
+ self._rubberband_line.SetPoint2(float(p2[0]), float(p2[1]), float(p2[2]))
1712
+ self._rubberband_line.Modified()
1713
+ self._rubberband_actor.VisibilityOn()
1714
+ self.render()
1715
+
1716
+ def clear_rubberband(self) -> None:
1717
+ if self._rubberband_actor is not None:
1718
+ self._rubberband_actor.VisibilityOff()
1719
+
1720
+ def _resolve_topological_chain(self, indices: list[int]) -> list[int]:
1721
+ """在 2~4 个原子构成的导出子图中,根据化学键拓扑恢复连通的测量链,杜绝无序 set 导致拉出空间斜穿连线。"""
1722
+ n = len(indices)
1723
+ if n <= 2:
1724
+ return list(indices)
1725
+
1726
+ idx_set = set(indices)
1727
+ adj: dict[int, list[int]] = {i: [] for i in indices}
1728
+ for u, v, _ in self._bonds:
1729
+ if u in idx_set and v in idx_set:
1730
+ adj[u].append(v)
1731
+ adj[v].append(u)
1732
+
1733
+ if n == 3:
1734
+ deg2 = [u for u in indices if len(adj[u]) == 2]
1735
+ if len(deg2) == 1:
1736
+ mid = deg2[0]
1737
+ ends = [u for u in indices if u != mid]
1738
+ return [ends[0], mid, ends[1]]
1739
+ return list(indices)
1740
+
1741
+ if n == 4:
1742
+ import itertools
1743
+ for perm in itertools.permutations(indices, 4):
1744
+ if (
1745
+ perm[1] in adj[perm[0]]
1746
+ and perm[2] in adj[perm[1]]
1747
+ and perm[3] in adj[perm[2]]
1748
+ ):
1749
+ return list(perm)
1750
+ return list(indices)
1751
+
1752
+ return list(indices)
1753
+
1754
+ def _update_highlights_in_place(self) -> None:
1755
+ """原地修改选中原子光晕与选中化学键光环(读取真实的逐原子半径与逐键粗细)。"""
1756
+ self._ensure_scene_initialized()
1757
+ if (
1758
+ self._highlight_points is None
1759
+ or self._highlight_radii is None
1760
+ or self._highlight_polydata is None
1761
+ or self._highlight_actor is None
1762
+ or self._coordinates is None
1763
+ ):
1764
+ return
1765
+
1766
+ self._highlight_points.Reset()
1767
+ self._highlight_radii.Reset()
1768
+ self._highlight_radii.SetName("halo_scale")
1769
+
1770
+ selected_indices: list[int] = []
1771
+ for atom_id in self._selected:
1772
+ idx = self._id_to_idx.get(atom_id)
1773
+ if idx is None or not (0 <= idx < self._n_atoms):
1774
+ continue
1775
+ r_eff = self.get_effective_atom_radius(idx)
1776
+ if r_eff <= 0.0:
1777
+ continue
1778
+ selected_indices.append(idx)
1779
+ pos = self._coordinates[idx]
1780
+ halo_r = max(0.32, r_eff * 1.28)
1781
+ self._highlight_points.InsertNextPoint(float(pos[0]), float(pos[1]), float(pos[2]))
1782
+ self._highlight_radii.InsertNextValue(float(halo_r))
1783
+
1784
+ self._highlight_points.Modified()
1785
+ self._highlight_radii.Modified()
1786
+ self._highlight_polydata.Modified()
1787
+ self._highlight_actor.SetVisibility(bool(selected_indices))
1788
+
1789
+ # 原地更新选中化学键高亮套管
1790
+ if self._hl_bond_points is not None and self._hl_bond_lines is not None and self._hl_bond_actor is not None:
1791
+ self._hl_bond_points.Reset()
1792
+ self._hl_bond_lines.Reset()
1793
+ self._hl_bond_radii.Reset()
1794
+ self._hl_bond_radii.SetName("hl_bond_r")
1795
+ hl_b_cnt = 0
1796
+ if self._selected_bonds and self._bond_ids:
1797
+ bid_to_bidx = {bid: i for i, bid in enumerate(self._bond_ids)}
1798
+ for bid in self._selected_bonds:
1799
+ b_idx = bid_to_bidx.get(bid, -1)
1800
+ if 0 <= b_idx < len(self._bonds):
1801
+ i, j, _ = self._bonds[b_idx]
1802
+ if 0 <= i < self._n_atoms and 0 <= j < self._n_atoms:
1803
+ p1, p2 = self._coordinates[i], self._coordinates[j]
1804
+ r_hl = self.get_effective_bond_radius(b_idx) * 1.65
1805
+ self._hl_bond_points.InsertNextPoint(float(p1[0]), float(p1[1]), float(p1[2]))
1806
+ self._hl_bond_points.InsertNextPoint(float(p2[0]), float(p2[1]), float(p2[2]))
1807
+ self._hl_bond_radii.InsertNextValue(float(r_hl))
1808
+ self._hl_bond_radii.InsertNextValue(float(r_hl))
1809
+ self._hl_bond_lines.InsertNextCell(2)
1810
+ self._hl_bond_lines.InsertCellPoint(hl_b_cnt * 2)
1811
+ self._hl_bond_lines.InsertCellPoint(hl_b_cnt * 2 + 1)
1812
+ hl_b_cnt += 1
1813
+ self._hl_bond_points.Modified()
1814
+ self._hl_bond_lines.Modified()
1815
+ self._hl_bond_radii.Modified()
1816
+ self._hl_bond_polydata.Modified()
1817
+ self._hl_bond_actor.SetVisibility(hl_b_cnt > 0)
1818
+
1819
+ # 原地更新 2~4 个选中原子之间的测量连线
1820
+ if self._measure_points is not None and self._measure_lines is not None and self._measure_actor is not None:
1821
+ self._measure_points.Reset()
1822
+ self._measure_lines.Reset()
1823
+ chain_indices: list[int] = []
1824
+ if self._measure_chain:
1825
+ valid_chain = True
1826
+ for aid in self._measure_chain:
1827
+ idx = self._id_to_idx.get(aid)
1828
+ if idx is not None and 0 <= idx < self._n_atoms:
1829
+ chain_indices.append(idx)
1830
+ else:
1831
+ valid_chain = False
1832
+ break
1833
+ if not valid_chain:
1834
+ chain_indices.clear()
1835
+
1836
+ if not chain_indices and 2 <= len(selected_indices) <= 4:
1837
+ chain_indices = self._resolve_topological_chain(selected_indices)
1838
+
1839
+ if 2 <= len(chain_indices) <= 4:
1840
+ for idx in chain_indices:
1841
+ p = self._coordinates[idx]
1842
+ self._measure_points.InsertNextPoint(float(p[0]), float(p[1]), float(p[2]))
1843
+ for k in range(len(chain_indices) - 1):
1844
+ self._measure_lines.InsertNextCell(2)
1845
+ self._measure_lines.InsertCellPoint(k)
1846
+ self._measure_lines.InsertCellPoint(k + 1)
1847
+ self._measure_points.Modified()
1848
+ self._measure_lines.Modified()
1849
+ self._measure_polydata.Modified()
1850
+ self._measure_actor.VisibilityOn()
1851
+ else:
1852
+ self._measure_actor.VisibilityOff()
1853
+
1854
+ # ---------- 安全防重入渲染与相机控制 ----------
1855
+
1856
+ def render(self) -> None:
1857
+ if self._viewer is None or self._render_pending or self._in_render:
1858
+ return
1859
+ self._render_pending = True
1860
+ from PyQt6.QtCore import QTimer
1861
+ QTimer.singleShot(0, self._do_safe_render)
1862
+
1863
+ def _do_safe_render(self) -> None:
1864
+ self._render_pending = False
1865
+ if self._viewer is None or self._in_render:
1866
+ return
1867
+ self._in_render = True
1868
+ try:
1869
+ self._viewer.render()
1870
+ self.save_camera_state()
1871
+ except Exception:
1872
+ pass
1873
+ finally:
1874
+ self._in_render = False
1875
+
1876
+ def reset_camera(self) -> None:
1877
+ if self._viewer is None:
1878
+ return
1879
+ try:
1880
+ ren = self._viewer.renderer
1881
+ cam = ren.GetActiveCamera()
1882
+ coords = self._coordinates.astype(np.float64) if self._coordinates is not None else np.zeros((0, 3))
1883
+ center = coords.mean(axis=0) if len(coords) else np.zeros(3, dtype=np.float64)
1884
+ centered = coords - center if len(coords) else coords
1885
+ normal = np.array([0.0, 0.0, 1.0])
1886
+ up_vec = np.array([0.0, 1.0, 0.0])
1887
+ span = 4.5
1888
+ if len(coords) >= 3:
1889
+ _, _, vh = np.linalg.svd(centered, full_matrices=False)
1890
+ normal = vh[2] if len(vh) >= 3 else normal
1891
+ up_vec = vh[1] if len(vh) >= 2 else up_vec
1892
+ if normal[2] < 0:
1893
+ normal = -normal
1894
+ if up_vec[1] < 0:
1895
+ up_vec = -up_vec
1896
+ span = max(span, float(np.linalg.norm(centered, axis=1).max()) * 2.4)
1897
+ elif len(coords) == 2:
1898
+ bond = coords[1] - coords[0]
1899
+ bond_length = float(np.linalg.norm(bond))
1900
+ if bond_length > 1e-8 and abs(float(np.dot(bond / bond_length, normal))) > 0.95:
1901
+ normal = np.array([1.0, 0.0, 0.0])
1902
+ span = max(span, bond_length * 2.4)
1903
+ if self._cell_matrix is not None:
1904
+ from itertools import product
1905
+ corners = (np.asarray(list(product((0.0, 1.0), repeat=3))) @ self._cell_matrix) + self._cell_origin
1906
+ span = max(span, float(np.linalg.norm(corners - center, axis=1).max()) * 2.4)
1907
+ dist = span / math.tan(math.radians(15.0))
1908
+ cam.SetFocalPoint(float(center[0]), float(center[1]), float(center[2]))
1909
+ pos = center + normal * dist
1910
+ cam.SetPosition(float(pos[0]), float(pos[1]), float(pos[2]))
1911
+ cam.SetViewUp(float(up_vec[0]), float(up_vec[1]), float(up_vec[2]))
1912
+ ren.ResetCameraClippingRange()
1913
+ self.save_camera_state()
1914
+ self.render()
1915
+ except Exception:
1916
+ pass
1917
+
1918
+ def set_view_direction(self, direction: str) -> None:
1919
+ """设置固定视图方向:front(沿-Z看)/side(沿-X看)/top(沿+Y看)/iso(等轴测)。"""
1920
+ if self._viewer is None or self._coordinates is None:
1921
+ return
1922
+ try:
1923
+ ren = self._viewer.renderer
1924
+ cam = ren.GetActiveCamera()
1925
+ coords = self._coordinates.astype(np.float64)
1926
+ center = coords.mean(axis=0)
1927
+ span = max(4.5, float(np.linalg.norm(coords - center, axis=1).max()) * 2.0)
1928
+ dist = span / math.tan(math.radians(15.0))
1929
+
1930
+ directions = {
1931
+ "front": {"pos": np.array([0.0, 0.0, -1.0]), "up": np.array([0.0, 1.0, 0.0])},
1932
+ "side": {"pos": np.array([-1.0, 0.0, 0.0]), "up": np.array([0.0, 1.0, 0.0])},
1933
+ "top": {"pos": np.array([0.0, 1.0, 0.0]), "up": np.array([0.0, 0.0, -1.0])},
1934
+ "iso": {"pos": np.array([1.0, 1.0, 1.0]), "up": np.array([0.0, 1.0, 0.0])},
1935
+ }
1936
+ d = directions.get(direction, directions["front"])
1937
+ cam.SetFocalPoint(float(center[0]), float(center[1]), float(center[2]))
1938
+ pos = center + d["pos"] * dist
1939
+ cam.SetPosition(float(pos[0]), float(pos[1]), float(pos[2]))
1940
+ cam.SetViewUp(float(d["up"][0]), float(d["up"][1]), float(d["up"][2]))
1941
+ ren.ResetCameraClippingRange()
1942
+ self.save_camera_state()
1943
+ self.render()
1944
+ except Exception:
1945
+ pass
1946
+
1947
+ def save_camera_state(self) -> dict:
1948
+ if self._viewer is None:
1949
+ return {}
1950
+ try:
1951
+ camera = self._viewer.camera
1952
+ self._camera_state = {
1953
+ "position": tuple(camera.position),
1954
+ "focal_point": tuple(camera.focal_point),
1955
+ "up": tuple(camera.up),
1956
+ "view_angle": float(camera.view_angle),
1957
+ }
1958
+ except Exception:
1959
+ pass
1960
+ return self._camera_state or {}
1961
+
1962
+ def restore_camera_state(self, state: dict | None = None) -> None:
1963
+ if self._viewer is None:
1964
+ return
1965
+ state = state or self._camera_state
1966
+ if not state:
1967
+ return
1968
+ try:
1969
+ camera = self._viewer.camera
1970
+ if "position" in state:
1971
+ camera.position = state["position"]
1972
+ if "focal_point" in state:
1973
+ camera.focal_point = state["focal_point"]
1974
+ if "up" in state:
1975
+ camera.up = state["up"]
1976
+ if "view_angle" in state:
1977
+ camera.view_angle = state["view_angle"]
1978
+ self._viewer.renderer.ResetCameraClippingRange()
1979
+ except Exception:
1980
+ pass
1981
+
1982
+ def set_mode(self, mode: RepresentationMode) -> None:
1983
+ self._mode = mode
1984
+ self._apply_mode()
1985
+ self.render()
1986
+
1987
+ def set_selection(
1988
+ self,
1989
+ selected: set[AtomId],
1990
+ selected_bonds: set[BondId] | None = None,
1991
+ measure_chain: Sequence[AtomId] | None = None,
1992
+ ) -> None:
1993
+ self._selected = {a for a in selected if a in self._id_to_idx}
1994
+ if selected_bonds is not None:
1995
+ self._selected_bonds = set(selected_bonds)
1996
+ if measure_chain is not None:
1997
+ self._measure_chain = list(measure_chain)
1998
+ elif not self._selected:
1999
+ self._measure_chain = None
2000
+ self._update_highlights_in_place()
2001
+ self.render()
2002
+
2003
+ def set_on_selection_changed(self, callback: Callable[[set[AtomId]], None]) -> None:
2004
+ self._on_selection_changed = callback
2005
+
2006
+ def export_image(self, path: str, width: int = 1920, height: int = 1080) -> None:
2007
+ if self._viewer:
2008
+ self._viewer.screenshot(path, transparent_background=False)
2009
+
2010
+ def set_material_preset(self, preset_name: str) -> None:
2011
+ preset = PRESETS.get(preset_name, StudioPreset)
2012
+ if self._viewer is None:
2013
+ return
2014
+ self._viewer.set_background(
2015
+ color=list(preset.background_bottom),
2016
+ top=list(preset.background_top),
2017
+ )
2018
+ for act in (self._atom_actor, self._bond_actor):
2019
+ if act is not None:
2020
+ prop = act.GetProperty()
2021
+ prop.SetInterpolationToPhong()
2022
+ prop.SetSpecular(max(0.15, 1.0 - preset.roughness))
2023
+ prop.SetSpecularPower(max(15.0, (1.0 - preset.roughness) * 60.0))
2024
+ self.render()
2025
+
2026
+ def set_roughness(self, value: float) -> None:
2027
+ v = max(0.05, min(0.95, float(value)))
2028
+ for act in (self._atom_actor, self._bond_actor):
2029
+ if act is not None:
2030
+ act.GetProperty().SetSpecular(max(0.1, 1.0 - v))
2031
+ act.GetProperty().SetSpecularPower(max(10.0, (1.0 - v) * 65.0))
2032
+ self.render()
2033
+
2034
+ def set_metallic(self, value: float) -> None:
2035
+ v = max(0.0, min(1.0, float(value)))
2036
+ for act in (self._atom_actor, self._bond_actor):
2037
+ if act is not None:
2038
+ act.GetProperty().SetAmbient(0.22 + 0.28 * v)
2039
+ self.render()
2040
+
2041
+ def set_atom_scale(self, scale: float) -> None:
2042
+ """设置全局原子缩放比例(保留每个原子的独立 _per_atom_scales 相对比例)。"""
2043
+ self._atom_scale = max(0.30, min(2.60, float(scale)))
2044
+ self._rebuild_vtk_molecule_in_place()
2045
+ self._update_highlights_in_place()
2046
+ self.render()
2047
+
2048
+ def set_bond_scale(self, scale: float) -> None:
2049
+ """设置全局化学键粗细比例(保留每条键的独立 _per_bond_scales 相对比例)。"""
2050
+ self._bond_scale = max(0.30, min(2.60, float(scale)))
2051
+ self._rebuild_vtk_molecule_in_place()
2052
+ self._update_highlights_in_place()
2053
+ self.render()
2054
+
2055
+ def set_background_color(self, r: float, g: float, b: float) -> None:
2056
+ if self._viewer is None:
2057
+ return
2058
+ self._viewer.set_background(color=[float(r), float(g), float(b)])
2059
+ self.render()
2060
+
2061
+ # ---------- 轨道 / 体数据 / 表面 ----------
2062
+
2063
+ def clear_orbital(self):
2064
+ if self._viewer is None:
2065
+ return
2066
+ for a in self._orbital_actors:
2067
+ a.VisibilityOff()
2068
+ self._orbital_actors = []
2069
+ self.render()
2070
+
2071
+ def set_orbital(self, cube, isovalue=0.05, opacity=0.68,
2072
+ pos_color=(0.22, 0.64, 1.0), neg_color=(1.0, 0.44, 0.24)):
2073
+ import pyvista as pv
2074
+ if self._viewer is None:
2075
+ return
2076
+ self.clear_orbital()
2077
+ nx, ny, nz = cube.dims
2078
+ sp = float(np.linalg.norm(cube.axes[0]))
2079
+ grid = pv.ImageData(dimensions=(nx, ny, nz), spacing=(1, 1, 1), origin=(0, 0, 0))
2080
+ grid.point_data["orb"] = np.ascontiguousarray(cube.values.flatten(order="F"))
2081
+ origin = np.asarray(cube.origin, dtype=float)
2082
+ for iso, color in ((abs(isovalue), pos_color), (-abs(isovalue), neg_color)):
2083
+ try:
2084
+ surf = grid.contour([iso], scalars="orb", method="flying_edges")
2085
+ if surf.n_points == 0:
2086
+ continue
2087
+ surf.points = surf.points * sp + origin
2088
+ act = self._viewer.add_mesh(
2089
+ surf, color=color, opacity=opacity, smooth_shading=True,
2090
+ specular=0.45, specular_power=32)
2091
+ self._orbital_actors.append(act)
2092
+ except Exception as e:
2093
+ print("[orbital] 等值面失败:", e)
2094
+
2095
+ def clear_volume(self):
2096
+ if self._viewer is None:
2097
+ return
2098
+ for a in self._volume_actors:
2099
+ a.VisibilityOff()
2100
+ self._volume_actors = []
2101
+ self.render()
2102
+
2103
+ @staticmethod
2104
+ def _is_orthogonal(axes, tol=1e-4) -> bool:
2105
+ off = axes - np.diag(np.diag(axes))
2106
+ return bool(np.all(np.abs(off) < tol))
2107
+
2108
+ def _downsample(self, cube, max_voxels: int):
2109
+ total = int(np.prod(cube.dims))
2110
+ if total <= max_voxels:
2111
+ return cube.values, cube.dims, 1
2112
+ step = max(1, int(np.ceil((total / max_voxels) ** (1 / 3))))
2113
+ vals = cube.values[::step, ::step, ::step]
2114
+ return vals, vals.shape, step
2115
+
2116
+ def set_volume(self, cube, max_voxels: int = 2_000_000, cmap: str = "turbo"):
2117
+ import pyvista as pv
2118
+ if self._viewer is None:
2119
+ return
2120
+ self.clear_volume()
2121
+ vals, dims, step = self._downsample(cube, max_voxels)
2122
+ axes = cube.axes * step
2123
+ origin = np.asarray(cube.origin, dtype=float)
2124
+ if self._is_orthogonal(axes):
2125
+ spacing = tuple(float(np.abs(axes[i, i])) for i in range(3))
2126
+ grid = pv.ImageData(dimensions=dims, spacing=spacing, origin=origin)
2127
+ else:
2128
+ nx, ny, nz = dims
2129
+ ix, iy, iz = np.meshgrid(np.arange(nx), np.arange(ny), np.arange(nz), indexing="ij")
2130
+ pts = (origin + ix.reshape(-1, 1) * axes[0]
2131
+ + iy.reshape(-1, 1) * axes[1]
2132
+ + iz.reshape(-1, 1) * axes[2])
2133
+ grid = pv.StructuredGrid()
2134
+ grid.points = pts
2135
+ grid.dimensions = dims
2136
+ grid.point_data["scalar"] = np.ascontiguousarray(vals.flatten(order="F"))
2137
+ act = self._viewer.add_volume(grid, cmap=cmap, opacity="linear", shade=False, show_scalar_bar=True)
2138
+ self._volume_actors.append(act)
2139
+
2140
+ def set_slice(self, cube, axis: int = 2, fraction: float = 0.5, cmap: str = "turbo"):
2141
+ import pyvista as pv
2142
+ if self._viewer is None:
2143
+ return
2144
+ self.clear_volume()
2145
+ nx, ny, nz = cube.dims
2146
+ idx = int(np.clip(fraction, 0, 1) * (cube.dims[axis] - 1))
2147
+ if axis == 0:
2148
+ plane_vals = cube.values[idx, :, :]
2149
+ a, b = np.meshgrid(np.arange(ny), np.arange(nz), indexing="ij")
2150
+ keys = np.stack([np.full_like(a, idx), a, b], axis=-1).reshape(-1, 3)
2151
+ dims2 = (ny, nz)
2152
+ elif axis == 1:
2153
+ plane_vals = cube.values[:, idx, :]
2154
+ a, b = np.meshgrid(np.arange(nx), np.arange(nz), indexing="ij")
2155
+ keys = np.stack([a, np.full_like(a, idx), b], axis=-1).reshape(-1, 3)
2156
+ dims2 = (nx, nz)
2157
+ else:
2158
+ plane_vals = cube.values[:, :, idx]
2159
+ a, b = np.meshgrid(np.arange(nx), np.arange(ny), indexing="ij")
2160
+ keys = np.stack([a, b, np.full_like(a, idx)], axis=-1).reshape(-1, 3)
2161
+ dims2 = (nx, ny)
2162
+ pts = (cube.origin + keys[:, 0:1] * cube.axes[0]
2163
+ + keys[:, 1:2] * cube.axes[1] + keys[:, 2:3] * cube.axes[2])
2164
+ grid = pv.StructuredGrid()
2165
+ grid.points = pts
2166
+ grid.dimensions = (dims2[0], dims2[1], 1)
2167
+ grid.point_data["scalar"] = plane_vals.flatten()
2168
+ act = self._viewer.add_mesh(grid, scalars="scalar", cmap=cmap, show_scalar_bar=True)
2169
+ self._volume_actors.append(act)
2170
+
2171
+ def _build_surface(self) -> None:
2172
+ if self._coordinates is None or self._atomic_numbers is None or self._viewer is None or vtk is None:
2173
+ return
2174
+ coords = self._coordinates
2175
+ n = self._n_atoms
2176
+ if n == 0 or n > 1500:
2177
+ return
2178
+ implicit_balls = vtk.vtkImplicitBoolean()
2179
+ implicit_balls.SetOperationTypeToUnion()
2180
+ for i in range(n):
2181
+ r = VDW_RADII.get(int(self._atomic_numbers[i]), DEFAULT_VDW)
2182
+ sphere = vtk.vtkSphere()
2183
+ sphere.SetRadius(r)
2184
+ sphere.SetCenter(float(coords[i, 0]), float(coords[i, 1]), float(coords[i, 2]))
2185
+ implicit_balls.AddFunction(sphere)
2186
+ min_b = coords.min(axis=0) - 1.8
2187
+ max_b = coords.max(axis=0) + 1.8
2188
+ spacing = 0.18
2189
+ sample = vtk.vtkSampleFunction()
2190
+ sample.SetImplicitFunction(implicit_balls)
2191
+ sample.SetSampleDimensions(
2192
+ max(12, int((max_b[0] - min_b[0]) / spacing)),
2193
+ max(12, int((max_b[1] - min_b[1]) / spacing)),
2194
+ max(12, int((max_b[2] - min_b[2]) / spacing)),
2195
+ )
2196
+ sample.SetModelBounds(min_b[0], max_b[0], min_b[1], max_b[1], min_b[2], max_b[2])
2197
+ sample.ComputeNormalsOn()
2198
+ flying_edges = vtk.vtkFlyingEdges3D()
2199
+ flying_edges.SetInputConnection(sample.GetOutputPort())
2200
+ flying_edges.SetValue(0, 0.0)
2201
+ smoother = vtk.vtkWindowedSincPolyDataFilter()
2202
+ smoother.SetInputConnection(flying_edges.GetOutputPort())
2203
+ smoother.SetNumberOfIterations(18)
2204
+ smoother.SetPassBand(0.08)
2205
+ smoother.NonManifoldSmoothingOn()
2206
+ smoother.NormalizeCoordinatesOn()
2207
+
2208
+ if self._surface_actor is None:
2209
+ mapper = vtk.vtkPolyDataMapper()
2210
+ mapper.SetInputConnection(smoother.GetOutputPort())
2211
+ mapper.ScalarVisibilityOff()
2212
+ actor = vtk.vtkActor()
2213
+ actor.SetMapper(mapper)
2214
+ actor.GetProperty().SetColor(0.38, 0.82, 0.88)
2215
+ actor.GetProperty().SetOpacity(0.26)
2216
+ actor.GetProperty().SetInterpolationToPhong()
2217
+ actor.GetProperty().SetSpecular(0.5)
2218
+ actor.GetProperty().SetSpecularPower(45.0)
2219
+ actor.GetProperty().SetFrontfaceCulling(False)
2220
+ actor.GetProperty().SetBackfaceCulling(False)
2221
+ actor.SetPickable(False)
2222
+ self._viewer.renderer.AddActor(actor)
2223
+ self._surface_actor = actor
2224
+ else:
2225
+ self._surface_actor.GetMapper().SetInputConnection(smoother.GetOutputPort())
2226
+ self._surface_actor.VisibilityOn()
2227
+
2228
+
2229
+ # 兼容别名
2230
+ def clear_qtaim(self):
2231
+ """清除当前视口中显示的所有 QTAIM 临界点与键径。"""
2232
+ if self._viewer is None:
2233
+ return
2234
+ for a in self._qtaim_actors:
2235
+ try:
2236
+ a.VisibilityOff()
2237
+ except Exception:
2238
+ pass
2239
+ self._qtaim_actors = []
2240
+ self.render()
2241
+
2242
+ def set_qtaim(self, critical_points, bond_paths=None, bcp_radius: float = 0.14, path_radius: float = 0.035):
2243
+ """在 3D 视口中叠合渲染 QTAIM 拓扑临界点与梯度键径。"""
2244
+ import pyvista as pv
2245
+ if self._viewer is None:
2246
+ return
2247
+ self.clear_qtaim()
2248
+
2249
+ # 1. 临界点 (BCP: 琥珀金; RCP: 青色; CCP: 紫罗兰)
2250
+ for cp in critical_points:
2251
+ pos = getattr(cp, "coords_angstrom", None)
2252
+ if pos is None:
2253
+ continue
2254
+ cp_type = getattr(cp, "cp_type", "")
2255
+ if cp_type == "(3,-1)":
2256
+ color = (1.0, 0.65, 0.15)
2257
+ r = bcp_radius
2258
+ elif cp_type == "(3,+1)":
2259
+ color = (0.15, 0.85, 0.85)
2260
+ r = bcp_radius * 1.15
2261
+ elif cp_type == "(3,+3)":
2262
+ color = (0.85, 0.25, 0.85)
2263
+ r = bcp_radius * 1.25
2264
+ else:
2265
+ continue
2266
+
2267
+ sphere = pv.Sphere(radius=r, center=pos)
2268
+ act = self._viewer.add_mesh(
2269
+ sphere, color=color, smooth_shading=True,
2270
+ specular=0.5, specular_power=24
2271
+ )
2272
+ self._qtaim_actors.append(act)
2273
+
2274
+ # 2. 键径 (Bond paths)
2275
+ if bond_paths:
2276
+ for path in bond_paths:
2277
+ pts = getattr(path, "points_angstrom", None)
2278
+ if pts is not None and len(pts) >= 2:
2279
+ try:
2280
+ line = pv.lines_from_points(pts)
2281
+ tube = line.tube(radius=path_radius)
2282
+ act = self._viewer.add_mesh(
2283
+ tube, color=(0.95, 0.85, 0.35), smooth_shading=True,
2284
+ specular=0.4, specular_power=20
2285
+ )
2286
+ self._qtaim_actors.append(act)
2287
+ except Exception:
2288
+ pass
2289
+
2290
+ self.render()
2291
+
2292
+
2293
+ # 兼容别名
2294
+ VTKMoleculeBackend = VtkRendererBackend