"""
Qt Legacy GLMesh Molecular Viewer for PDB Files
This example demonstrates how to:
1. Load PDB files using the PDBLoader
2. Extract C-alpha atoms (CA) from the structure
3. Convert them to PicoGL MeshData format
4. Display them using LegacyGLMesh for rendering
5. Provide interactive controls for rotation and zoom
"""
from __future__ import annotations
import sys
from pathlib import Path
from molib.gl.mesh.atom.sphere import AtomSpheresMesh, make_chain_color_fn
from picogl.backend.gl.api.clear import gl_clear, gl_clear_rgba_color
from picogl.backend.gl.api.enable import gl_enable_capability_list
from picogl.backend.gl.api.legacy.matrix import gl_matrix_mode_context
from picogl.backend.gl.capability import GLPipelineCapability
from picogl.backend.gl.enums import GLBitMask
from picogl.backend.gl.enums.legacy.scale import gl_load_identity
from picogl.backend.gl.legacy.lighting import GLFixedFunctionLightingModel
from picogl.backend.gl.legacy.view import CameraPerspective, LegacyGLViewTransform
from picogl.backend.glu.perspective import glu_perspective
from picogl.core.polygon.mode import gl_set_line_mode, gl_set_polygon_mode
from picogl.core.rgbcolor import RGBAColor
from picogl.core.viewport import GLViewport
from picogl.ui.backend.qt.legacy.window import LegacyQtObjectWindow
from picoui.dimensions import Dimensions, Point, WindowGeometry
from picoui.helpers import create_layout_with_items, create_widget_with_layout
from picoui.helpers.layout import create_splitter_with_items, create_widget_layout
from picoui.specs.widgets import ButtonSpec, LabelSpec
from picoui.widget.helper import create_button_from_spec, create_label_from_spec
from PySide6.QtCore import Qt, QTimer
from PySide6.QtOpenGLWidgets import QOpenGLWidget
from PySide6.QtWidgets import (
QApplication,
QLabel,
QMessageBox,
QPushButton,
QSplitter,
QVBoxLayout,
QWidget,
)
[docs]
_EXAMPLES_PATH = Path(__file__).resolve().parent.parent
[docs]
_EXAMPLES_DIR = str(_EXAMPLES_PATH)
if _EXAMPLES_DIR not in sys.path:
sys.path.insert(0, _EXAMPLES_DIR)
from picogl.examples.utils.pdb_loader import PDBLoader # noqa: E402
[docs]
class QtLegacyGLMeshMolecularViewer(QOpenGLWidget):
"""Qt OpenGL widget for displaying molecular structures using LegacyGLMesh."""
def __init__(self, pdb_path: str, parent: QWidget | None = None):
super().__init__(parent)
[docs]
self._initialized = False
[docs]
self.pdb_path = pdb_path
[docs]
self.calpha_positions = None
[docs]
self.last_mouse_pos = None
[docs]
self.mouse_pressed = False
[docs]
self.wireframe_mode = False
[docs]
self.lighting_enabled = False
[docs]
self.bond_radius = 0.06
[docs]
self.bond_segments = 12
# Set up view
[docs]
self.light = GLFixedFunctionLightingModel()
[docs]
self.viewport = GLViewport(0, 0, self.width(), self.height())
self._load_pdb_structure()
@property
[docs]
def zoom(self):
return self.transform.zoom.value
@zoom.setter
def zoom(self, value):
self.transform.zoom.value = value
self.update()
@property
[docs]
def rotation_x(self):
return self.transform.rotation.x
@rotation_x.setter
def rotation_x(self, value):
self.transform.rotation.x = value
self.update()
@property
[docs]
def rotation_y(self):
return self.transform.rotation.y
@rotation_y.setter
def rotation_y(self, value):
self.transform.rotation.y = value
self.update()
@property
[docs]
def translation_x(self):
return self.transform.translation.x
@translation_x.setter
def translation_x(self, value):
self.transform.translation.x = value
self.update()
@property
[docs]
def translation_y(self):
return self.transform.translation.y
@translation_y.setter
def translation_y(self, value):
self.transform.translation.y = value
self.update()
[docs]
def initializeGL(self):
"""Initialize OpenGL settings via PicoGL wrappers."""
self.enable_depth_test()
self.light.enable()
self.light.setup_color_materials()
self.setup_background()
self._create_mesh_data()
self._initialized = True
QTimer.singleShot(100, self._enable_controls)
[docs]
def enable_depth_test(self):
"""enable depth test"""
gl_enable_capability_list([GLPipelineCapability.DEPTH_TEST])
[docs]
def setup_background(self):
"""setup background"""
gl_clear_rgba_color(RGBAColor.BLACK)
[docs]
def resizeGL(self, w: int, h: int):
"""Handle window resize."""
self.viewport.update(0, 0, w, h)
with gl_matrix_mode_context():
glu_perspective(
CameraPerspective.fovy,
w / max(h, 1),
CameraPerspective.near,
CameraPerspective.far,
)
[docs]
def paintGL(self):
"""Main rendering function."""
self.setup_view()
self._apply_lighting()
self.apply_zoom(value=-5.0)
self.transform.rotation.apply()
self.transform.zoom.rescale()
self._render_molecular_structure()
[docs]
def setup_view(self):
"""setup view"""
gl_clear(GLBitMask.COLOR_BUFFER | GLBitMask.DEPTH_BUFFER)
gl_load_identity()
[docs]
def apply_zoom(self, value: float = 1.0):
"""apply zoom"""
self._apply_zoom_with_translation(self.transform.translation, value=value)
[docs]
def _apply_zoom_with_translation(self, translation, value: float = 0.01):
"""apply zoom with translation"""
self.transform.zoom.apply_translation_and_zoom(translation, value)
[docs]
def _apply_lighting(self) -> None:
"""Enable or disable fixed-function lighting for this frame."""
if self.lighting_enabled:
self.light.apply()
return
self.light.disable()
[docs]
def _load_pdb_structure(self):
"""Load PDB structure and extract C-alpha atoms."""
print(f"Loading PDB structure from: {self.pdb_path}")
try:
self.pdb_loader = PDBLoader(self.pdb_path)
structure = self.pdb_loader.structure
self.calpha_atoms = structure.calpha_atoms
self.calpha_bonds = structure.calpha_bonds
print(structure.report)
except Exception as e:
print(f"Error loading PDB file: {e}")
QMessageBox.critical(None, "Error", f"Failed to load PDB file: {e}")
[docs]
def _create_mesh_data(self):
"""Create molecular meshes and upload legacy GPU buffers."""
if self._initialized:
return
chain_ids = [atom.chain_id for atom in self.calpha_atoms]
color_fn = make_chain_color_fn(chain_ids)
from molib.gl.mesh.bond.cylinder import BondCylindersMesh
if self.calpha_atoms:
self.atoms_mesh = AtomSpheresMesh(self.calpha_atoms, color_fn=color_fn)
self.atoms_mesh.to_legacy_glmesh(upload=True)
if self.calpha_bonds:
index_by_id = {id(atom): i for i, atom in enumerate(self.calpha_atoms)}
indices = [
[index_by_id[id(atom1)], index_by_id[id(atom2)]]
for atom1, atom2 in self.calpha_bonds
]
self.bonds_mesh = BondCylindersMesh(
self.calpha_atoms,
indices=indices,
color_fn=color_fn,
color_bonds=True,
radius=self.bond_radius,
segments=self.bond_segments,
)
self.bonds_mesh.to_legacy_glmesh(upload=True)
[docs]
def _render_molecular_structure(self):
"""Render the molecular structure using molecular mesh adapters."""
if self.atoms_mesh is None and self.bonds_mesh is None:
return
if self.wireframe_mode:
gl_set_polygon_mode()
else:
gl_set_line_mode()
if self.atoms_mesh is not None:
self.atoms_mesh.draw_legacy()
if self.bonds_mesh is not None:
self.bonds_mesh.draw_legacy()
[docs]
def _enable_controls(self):
"""Enable control buttons by finding the main window."""
widget = self.parent()
while widget is not None:
if hasattr(widget, "lighting_button"):
widget.lighting_button.setEnabled(True)
print("Controls enabled")
break
widget = widget.parent()
[docs]
def mousePressEvent(self, event):
"""Handle mouse press for rotation."""
if event.button() == Qt.LeftButton:
self.mouse_pressed = True
self.last_mouse_pos = event.position().toPoint()
[docs]
def mouseMoveEvent(self, event):
"""Handle mouse movement for rotation."""
if self.mouse_pressed and self.last_mouse_pos:
current_pos = event.position().toPoint()
dx = current_pos.x() - self.last_mouse_pos.x()
dy = current_pos.y() - self.last_mouse_pos.y()
self.transform.rotation.y += dx * 0.5
self.transform.rotation.x += dy * 0.5
self.last_mouse_pos = current_pos
self.update()
[docs]
def mouseReleaseEvent(self, event):
"""Handle mouse release."""
if event.button() == Qt.LeftButton:
self.mouse_pressed = False
[docs]
def wheelEvent(self, event):
"""Handle mouse wheel for zooming."""
delta = event.angleDelta().y()
zoom_factor = 1.1 if delta > 0 else 0.9
self.transform.zoom.value *= zoom_factor
self.transform.zoom.value = max(0.01, min(30.0, self.zoom))
self.update()
[docs]
def keyPressEvent(self, event):
"""Handle keyboard input."""
if event.key() == Qt.Key_R:
self.transform.rotation.x = 0.0
self.transform.rotation.y = 0.0
self.transform.zoom.value = 1.0
self.transform.translation.x = 0.0
self.transform.translation.y = 0.0
self.update()
elif event.key() == Qt.Key_W:
self.wireframe_mode = not self.wireframe_mode
print(f"Wireframe mode: {'ON' if self.wireframe_mode else 'OFF'}")
self.update()
elif (
event.key() == Qt.Key_L
or event.text().lower() == "l"
or event.key() == Qt.Key_T
or event.text().lower() == "t"
):
self.lighting_enabled = not self.lighting_enabled
print(f"Lighting: {'ON' if self.lighting_enabled else 'OFF'}")
self.update()
elif event.key() == Qt.Key_Escape:
self.close()
[docs]
class LegacyGLMeshMolecularViewerWindow(LegacyQtObjectWindow):
"""Main window for the LegacyGLMesh molecular viewer."""
[docs]
window_geometry = WindowGeometry(
position=Point(x=100, y=100),
dimensions=Dimensions(width=1200, height=800),
)
def __init__(self, object_file_path: str = None):
[docs]
self._pdb_path = object_file_path
super().__init__(parent=None)
[docs]
self.object_file_path = object_file_path
[docs]
def ui_init(self):
"""Override ui_init to delay layout creation until we have the PDB path."""
central_widget = QWidget()
self.setCentralWidget(central_widget)
self.layout = QVBoxLayout(central_widget)
self.set_layout(self.layout)
[docs]
def init_ui(self):
"""Initialize the user interface."""
self.setWindowTitle(
"Qt Legacy GLMesh Molecular Viewer - 2VUG C-alpha (Chain A: Green, Chain B: Blue)"
)
self.setGeometry(*window_geometry.to_tuple())
[docs]
def set_layout(self, layout: QLayout | None):
"""Build the window layout and GL widget."""
pdb_path = getattr(self, "_pdb_path", None) or self.object_file_path
self.label_specs = self._build_label_specs()
self.button_specs = self.build_button_specs()
self.gl_widget = QtLegacyGLMeshMolecularViewer(pdb_path)
splitter = self.create_splitter()
layout.addWidget(splitter)
[docs]
def create_splitter(self) -> QSplitter:
splitter_items = self.create_splitter_items()
splitter = create_splitter_with_items(items=splitter_items, sizes=[200, 800])
return splitter
[docs]
def create_splitter_items(self) -> list[QWidget]:
info_label = create_label_from_spec(self.label_specs["info_label_spec"])
instructions_label = create_label_from_spec(
self.label_specs["instructions_spec"]
)
lower_layout = create_widget_layout(self.gl_widget)
controls_layout_items = self.create_controls_layout_items()
controls_layout = create_layout_with_items(
controls_layout_items, start_stretch=False, end_stretch=True
)
upper_layout = create_layout_with_items(
[info_label, controls_layout, instructions_label],
start_stretch=False,
end_stretch=True,
vertical=False,
)
upper_widget = create_widget_with_layout(upper_layout)
lower_widget = create_widget_with_layout(lower_layout)
splitter_items = [upper_widget, lower_widget]
return splitter_items
[docs]
def create_controls_layout_items(self) -> list[QPushButton]:
reset_button = create_button_from_spec(self.button_specs["reset_button"])
info_button = create_button_from_spec(self.button_specs["info_button"])
self.lighting_button = create_button_from_spec(
self.button_specs["lighting_button"]
)
controls_layout_items = [reset_button, info_button, self.lighting_button]
return controls_layout_items
[docs]
def _build_label_specs(self) -> dict[str, LabelSpec]:
instructions_text = "Controls:\n"
"• Left mouse: Rotate\n"
"• Mouse wheel: Zoom\n"
"• R key: Reset view\n"
"• W key: Toggle wireframe/filled\n"
"• L/T key: Toggle lighting\n"
"• ESC: Exit\n"
"• Chain A: Green, Chain B: Blue\n"
"• Using LegacyGLMesh for rendering"
instructions_style = (
"color: black; font-size: 12px; padding: 10px; background-color: #f0f0f0;"
)
return {
"info_label_spec": LabelSpec(
label="PDB Structure - C-alpha Atoms (Chain A: Green, Chain B: Blue)",
style="font-size: 14px; font-weight: bold; padding: 10px;",
),
"instructions_spec": LabelSpec(
style=instructions_style, label=instructions_text
),
}
[docs]
def create_instructions_label(self) -> QLabel:
instructions_text = "Controls:\n"
"• Left mouse: Rotate\n"
"• Mouse wheel: Zoom\n"
"• R key: Reset view\n"
"• W key: Toggle wireframe/filled\n"
"• L/T key: Toggle lighting\n"
"• ESC: Exit\n"
"• Chain A: Green, Chain B: Blue\n"
"• Using LegacyGLMesh for rendering"
instructions_style = (
"color: black; font-size: 12px; padding: 10px; background-color: #f0f0f0;"
)
instructions_label = create_label_from_spec(
LabelSpec(style=instructions_style, label=instructions_text)
)
return instructions_label
[docs]
def reset_view(self):
"""Reset the view to default."""
if self.gl_widget is None:
print("OpenGL widget not yet initialized")
return
self.gl_widget.rotation_x = 0.0
self.gl_widget.rotation_y = 0.0
self.gl_widget.zoom = 1.0
self.gl_widget.translation_x = 0.0
self.gl_widget.translation_y = 0.0
self.gl_widget.update()
[docs]
def toggle_lighting(self):
"""Toggle lighting on/off."""
if self.gl_widget is None:
print("OpenGL widget not yet initialized")
return
self.gl_widget.lighting_enabled = not self.gl_widget.lighting_enabled
status = "ON" if self.gl_widget.lighting_enabled else "OFF"
print(f"Lighting: {status}")
self.lighting_button.setText(f"Lighting: {status}")
self.gl_widget.update()
[docs]
def enable_controls(self):
"""Enable control buttons once OpenGL widget is ready."""
if hasattr(self, "lighting_button"):
self.lighting_button.setEnabled(True)
print("Controls enabled")
[docs]
def show_info(self):
"""Show structure information."""
if self.gl_widget.pdb_loader:
structure = self.gl_widget.pdb_loader.structure
info_text = f"""
Structure Information:
Title: {structure.title}
Total atoms: {len(structure.atoms)}
C-alpha atoms: {len(self.gl_widget.calpha_atoms)}
Chains: {structure.chains}
Residues: {len(structure.residues)}
C-alpha bonds: {len(self.gl_widget.calpha_bonds)}
Rendering:
Mode: {'Wireframe' if self.gl_widget.wireframe_mode else 'Filled'}
Using: LegacyGLMesh
"""
QMessageBox.information(self, "Structure Information", info_text)
else:
QMessageBox.warning(self, "No Data", "No PDB structure loaded.")
[docs]
def main():
"""Main function to run the molecular viewer."""
app = QApplication(sys.argv)
pdb_path = Path(_EXAMPLES_DIR) / "data" / "2VUG.pdb"
pdb_path = pdb_path.absolute()
print(pdb_path)
if not pdb_path.exists():
print(f"Error: PDB file not found at {pdb_path}")
return 1
window = LegacyGLMeshMolecularViewerWindow(object_file_path=str(pdb_path))
window.show()
return app.exec()
if __name__ == "__main__":
sys.exit(main())