Metadata-Version: 2.4
Name: unit-cell-gui
Version: 0.2.5
Summary: PySide6 widget for rendering caller-supplied unit-cell scenes
Author-email: Mikhail Mirushchenko <miruschenko98@gmail.com>
License-Expression: MIT
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: X11 Applications :: Qt
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: PySide6-Essentials<7,>=6.8
Requires-Dist: PyOpenGL<4,>=3.1.7
Dynamic: license-file

# unit-cell-gui

`unit-cell-gui` is a reusable PySide6 widget that draws complete unit-cell
scenes supplied by another program. It does not read CIF files, expand
symmetry, resolve atomic positions, infer bonds, construct polyhedra or
calculate diffraction.

The caller supplies ready Cartesian coordinates and presentation data:

- atoms and their styled occupancy components;
- bond indices;
- unit-cell vertices and edges;
- three basis vectors;
- optional polyhedron vertices, polygon faces and centres.

The package owns only display behaviour: camera projection, OpenGL depth buffering,
left-button rotation, right-button panning, wheel zoom, occupancy sectors,
colour and black-and-white drawing, and polyhedron hatching. Quadrilateral
hatching uses one intact polygon with `2x + 1` full parallel strokes. Hatch
directions on farther faces are refolded through real shared edges.

<table>
  <tr>
    <td align="center" width="50%">
      <img src="https://raw.githubusercontent.com/ofussr/unit-cell-gui/main/docs/images/color-view.png" alt="Color view" width="100%">
      <br>
      <sub>Color view</sub>
    </td>
    <td align="center" width="50%">
      <img src="https://raw.githubusercontent.com/ofussr/unit-cell-gui/main/docs/images/hatched-view.png" alt="Hatched view" width="100%">
      <br>
      <sub>Hatched view</sub>
    </td>
  </tr>
</table>

## Installation

```bash
python -m pip install unit-cell-gui
```

Python 3.10 or newer, NumPy, PySide6 Essentials and PyOpenGL are required. The renderer requests an OpenGL 3.3 core-profile context.

Import `UnitCellViewer` or `CrystalCanvas` before constructing `QApplication`.
This lets the package establish one shared OpenGL format for every viewer and
keeps top-level Qt composition stable across screen and DPI changes. The basic
example below already uses this order.

## Basic use

```python
import numpy as np
from PySide6.QtWidgets import QApplication
from unit_cell_gui import Atom, AtomComponent, DisplayOptions, Scene, UnitCellViewer

silicon = AtomComponent(
    key="Si:Si1", label="Si1", element="Si",
    occupancy=1.0, colour="#f0c8a0", radius=0.30,
)
scene = Scene(
    atoms=(Atom("Si:Si1", "Si1", (silicon,)),),
    atom_centers=np.array([[0.0, 0.0, 0.0]]),
    bonds=np.empty((0, 2), dtype=int),
    cell_vertices=np.array([
        [x, y, z]
        for x in (-1.0, 1.0)
        for y in (-1.0, 1.0)
        for z in (-1.0, 1.0)
    ]),
    cell_edges=np.array([
        [0, 1], [0, 2], [0, 4], [1, 3], [1, 5], [2, 3],
        [2, 6], [3, 7], [4, 5], [4, 6], [5, 7], [6, 7],
    ]),
    basis_vectors=np.eye(3),
    base_radius=2.0,
)

app = QApplication([])
viewer = UnitCellViewer()
viewer.set_scene(scene)
viewer.set_display_options(DisplayOptions(show_polyhedra=False))
viewer.show()
app.exec()
```

`Scene` copies its arrays and makes them read-only. Later changes in the caller
therefore cannot alter an already submitted scene.

## Orientation synchronization

`orientation` is a 3 by 3 world-to-camera matrix. For column vectors the
camera coordinate is `orientation @ world`; the renderer's row arrays use the
equivalent `world @ orientation.T`.

Matrices must be finite and float32-representable, remain invertible after
float32 rounding, and have condition number below 1e6. Their inverse and
conservative generated/transformed geometry bounds must also fit float32.
Reflections and general well-conditioned invertible matrices remain accepted;
SO(3) orthogonality is not required. Invalid input leaves the previous state
unchanged and does not emit a signal.

Programmatic changes are silent by default:

```python
viewer.set_orientation(matrix, emit=False)
```

Interactive rotation emits the complete new matrix through
`orientation_changed`. Connect that signal to a pole figure or another view,
then send changes from the other view back with silent `set_orientation` calls.
This supports bidirectional synchronization without a signal loop.

```python
viewer.orientation_changed.connect(update_other_view)
other_view.orientation_changed.connect(
    lambda matrix: viewer.set_orientation(matrix, emit=False)
)
```

Set `rotation_enabled=False` when an application temporarily forbids left-button
rotation. Panning and zoom remain available. Polyhedra are hidden by default
and must be enabled with `show_polyhedra=True`.

Per-position colours, visibility and opaque-polyhedron selections are replaced
atomically with `viewer.set_style_overrides(StyleOverrides(...))`. The widget
copies these mappings, so the host can keep its own independent UI state.

## Atom instancing

Atoms share one indexed sphere mesh with the same 16-by-24 tessellation as
previous releases. An OpenGL instance buffer stores each visible atom's
Cartesian centre, radius, eight RGB occupancy colours and cumulative occupancy
thresholds once, instead of repeating them for every triangle vertex. The atom
layer uses one `glDrawElementsInstanced` call.

The base sphere and its indices occupy 18,792 bytes per viewer; instance records
add 144 bytes per visible atom. For 1,000 atoms, these buffers total 162,792
bytes, compared with 328,320,000 bytes for the previous expanded atom buffer.
This comparison excludes bonds, outlines, polyhedra and Qt/driver overhead.
The number of sphere triangles is unchanged, so this is primarily a reduction
in geometry preparation and buffer storage, not a frame-rate guarantee.

OpenGL 3.3 core remains sufficient: the renderer uses 13 vertex attribute
locations, within the guaranteed minimum of 16. No C++ extension, new package
dependency or host-application API change is required.

## Visibility and rendering caches

Both global and per-site polyhedron visibility filter already prepared geometry
at draw time. Faces, edges and atom/face intersection contours remain in GPU
buffers when a site is hidden or shown. This avoids rebuilding the full
polyhedron layer for each individual visibility change.

Engraving hatching is cached per polyhedron. Its density still follows the
depth range of the visible polyhedra: hiding the nearest or farthest object can
change other objects' effective division counts. Only affected hatch buffers
are updated. Rotation, zoom, panning and window-size changes keep the original
view-dependent hatching behaviour. CPU density variants are bounded and are
discarded when the view or scene changes.

Intersection contours and hatching are prepared when their layers are first
needed. The initial preparation still has a cost; subsequent site visibility
changes reuse the prepared data.


## Renderer compatibility

`UnitCellViewer` and the legacy alias `CrystalCanvas` now use the OpenGL
renderer internally. Existing construction, scene submission, display-option,
style-override, orientation-synchronization and interaction calls remain the
same. `OpenGLUnitCellViewer` remains available as an explicit name and refers
to the same renderer class.

## Used in

`unit-cell-gui` is used as the crystal-structure viewer in [XRD Combine](https://github.com/ofussr/XRD-Combine), where it is integrated with CIF processing, diffraction tools, and synchronized crystallographic views.

## How to cite

If you use `unit-cell-gui` in academic work, please cite the Zenodo record:

[![DOI](https://img.shields.io/badge/DOI-10.5281%2Fzenodo.22714946-blue.svg)](https://doi.org/10.5281/zenodo.22714946)

You can also use the metadata provided in [`CITATION.cff`](CITATION.cff).

## Shared GPU geometry (0.2.4)

Atoms, camera-facing outlines, coloured bonds, polyhedron fill triangles,
physical edges and engraving bonds use shared meshes and instance records.
Camera changes keep geometry resident; depth-sorted edges update compact
index lists. Large arrays are split at the driver's texture-buffer limit.
Sphere tessellation remains 720 triangles per atom; no LOD is applied.

Hatching uses intact polygons and the existing stroke algorithm. In coloured mode, atom/face
intersection curves use the corresponding face colour, including polyhedron
colour overrides. Engraving keeps black intersection ink.

## External partial updates (0.2.4)

```python
viewer.update_scene(
    atom_positions={17: (x, y, z)},
    atom_visibility={42: False},
    polyhedra={3: updated_polyhedron},
    polyhedron_opacities={3: 0.35},
)
```

Original scene indices stay stable; positions are absolute Cartesian XYZ.
Packets are validated atomically, copied and uploaded on the next paint.
Only changed atoms, their existing adjacent bonds and affected polyhedra are
updated; dependent sections and hatching refresh as needed.

`set_atom_positions`, `set_atom_visibility` and `update_polyhedra` provide
individual setters. `reset_scene_updates()` restores input geometry and local
visibility while preserving camera and host styles. Effective-state getters
are `get_atom_positions()`, `get_atom_visibility()` and `get_polyhedra()`.

`viewer.scene` remains the original object; `set_scene()` clears the overrides.
Call updates on the GUI thread. The host supplies updated polyhedra and bond
topology; neither is inferred automatically. Local visibility respects host
component/external-atom switches. A changed state draws a new frame without
requiring a complete scene rebuild.

See [the API contract](docs/partial-updates.md),
[the external-control example](examples/partial_updates.py), and
[changes since 0.2.3](RELEASE_NOTES_0.2.4.md).

## Transparency and opacity control (0.2.5)

Transparent faces and physical edges share a global back-to-front order computed
from depth over projected overlap. The default renderer draws directly into Qt's
MSAA framebuffer without depth peeling or whole-window supersampling. Opaque
atoms, bonds and faces write depth before transparent surfaces. The host supplies
planar convex faces without physical intersections or cyclic visibility. Shared
boundaries are supported; dense overlap can still produce quadratic graph memory.

External opacity updates reuse resident geometry:

```python
viewer.set_polyhedron_opacities({3: 0.35, 7: 1.0})
viewer.update_scene(atom_positions={17: (x, y, z)},
                    polyhedron_opacities={3: 0.5})
viewer.set_polyhedron_opacities({3: None})
values = viewer.get_polyhedron_opacities()
```

Use original scene indices and GUI-thread calls. Zero hides an object; one makes
it opaque; None restores its default. Invalid packets are rejected atomically.
Fill/edges change together and explicit opacity fades contacts. A separate table
normally uploads four bytes per changed object. Positive fractional values are
stored in engraving, whose displayed fills remain opaque; zero hides the object.
See the [complete contract](docs/partial-updates.md).

## Optional WBOIT modes

**Shift + right mouse button** opens two independent checkboxes:

| Setting | Behavior |
| --- | --- |
| Weighted Blended OIT when rotate | Approximate during rotation, exact after release/external inactivity |
| Weighted Blended OIT always | Approximate also at rest and after mouse release; takes priority |

Both default to false, apply to one widget, are not saved to disk, and are
ignored by engraving. Ordinary right-button dragging still pans. The existing
external API controls both:

```python
viewer.set_display_options(weighted_blended_oit=True)  # permanent
viewer.set_display_options(weighted_blended_oit=False) # leave permanent mode
viewer.set_display_options(weighted_blended_oit_when_rotate=True)
# Both off: use sorted transparency throughout.
viewer.set_display_options(weighted_blended_oit=False,
                           weighted_blended_oit_when_rotate=False)
```

The checkboxes retain their independent values. Disabling permanent mode restores
the rotation-only preference. With rotation-only enabled, external set_orientation
series request an exact frame after 150 ms without an effective change. Repeating
the same orientation does not restart the timer. Mouse-held rotation stays fast
until release/interruption. Permanent mode does not start an idle-to-exact timer.
Neither quality changes nor timer completion emit extra orientation signals;
emit=False keeps its meaning. Pan/zoom alone do not start rotation-only WBOIT.

WBOIT uses two GL 3.3 accumulation passes and per-sample composition with shared
owned MSAA depth. It skips exact sorting and reuses resident meshes. Edge
coverage participates in alpha; opaque edges are handled separately and
contours/contacts are depth-tested beneath transparency. The approximation can
change hues/edge emphasis. Permanent mode intentionally retains it after stopping.
Small scenes may be slower with WBOIT enabled.

Resources are lazy and reused. Additional attachments cost approximately
20 bytes × physical width × physical height × actual samples: 23.4 MiB at
640 × 480 × 4, or 158.2 MiB at 1920 × 1080 × 4. DPR 2 multiplies this by four.
Qt/geometry/driver padding is additional. Exceeding the 256 MiB per-widget budget
or GPU limits uses exact fallback without silently lowering MSAA. Allocation or
pass failures appear in the menu and weighted_oit_error, separately from the
main opengl_error; retry is permitted after context restoration or close/show.
Scene clear/cleanup releases attachments. The historical
transparency_supersampling=1/2 field remains an inert compatibility option.

## Preparation and robustness (0.2.5)

World geometry, topology/material keys and normals are prepared once for camera
updates. Projected bounds prune sort candidates. Refittable spatial indices and
cached face frames reduce contact/local-update work. Opacity-only state is lazy;
host polyhedron style refreshes stay local. The legend uses cached visible
components. GPU ranges and derived geometry are validated, integer indices are
strict, unstable orientations are rejected atomically and huge finite occupancy
weights are normalized safely. Scene clear releases scene storage, shader-failure
cleanup is transactional, and ordinary close/show restores GPU resources.

See [release notes relative to GitHub 0.2.4](RELEASE_NOTES_0.2.5.md),
[transparency details](docs/hybrid-transparency.md),
[external-control example](examples/partial_updates.py), and
[validation commands](validation/README.md). Existing host calls/dependencies and
all 0.2.4 instancing/hatching features remain supported.
