File: OSMesaGLBackend.py

package info (click to toggle)
pymca 5.8.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 44,392 kB
  • sloc: python: 155,456; ansic: 15,843; makefile: 116; sh: 73; xml: 55
file content (266 lines) | stat: -rw-r--r-- 9,190 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# /*#########################################################################
#
# The PyMca X-Ray Fluorescence Toolkit
#
# Copyright (c) 2004-2015 European Synchrotron Radiation Facility
#
# This file is part of the PyMca X-ray Fluorescence Toolkit developed at
# the ESRF by the Software group.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/
__author__ = "T. Vincent - ESRF Data Analysis"
__contact__ = "thomas.vincent@esrf.fr"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
__doc__ = """
Experimental Off-Screen Mesa/Qt OpenGL backend.

This backend is based on the OSMesa software backend (http://www.mesa3d.org/).
It can be used when OpenGL is not available.
It depends on libOSMesa, PyOpenGL (tested with v3.1.1) and Qt.

Information on how to compile libOSMesa can be found here:

- http://www.mesa3d.org/osmesa.html
- http://www.paraview.org/Wiki/ParaView/ParaView_And_Mesa_3D

The --enable-texture-float flag is required to support float32 textures.

The environment variable PYOPENGL_PLATFORM MUST be set to osmesa before
the first import of PyOpenGL.
This module adds it to the environment variables, but in case another module
imports PyOpenGL before, PYOPENGL_PLATFORM must already be set at that time
(e.g., from the shell).
"""


# import ######################################################################

import numpy as np

# PyOpenGL
# Tells PyOpenGL to use libOSMesa
# This only works if PyOpenGL has not yet been imported
import os
os.environ['PYOPENGL_PLATFORM'] = 'osmesa'

# Test PyOpenGL version
import OpenGL
if OpenGL.version.__version__ < '3.1.0':
    raise ImportError(
        "PyOpenGL version >= 3.1.0 is required for OS Mesa backend.")
try:
    from OpenGL.raw.osmesa import mesa
except:
    raise RuntimeError(
        """PyOpenGL is not set to use OSMesa.
         Add PYOPENGL_PLATFORM=osmesa to the environment variables.""")

from .GLSupport import gl
from .GLSupport import setGLContextGetter

# Qt
try:
    from PyMca5.PyMcaGui.PyMcaQt import pyqtSignal, QCursor, QSize, Qt, QLabel
    from PyMca5.PyMcaGui.PyMcaQt import QPixmap, QImage
except ImportError:
    try:
        from PyQt4.QtCore import pyqtSignal, QSize, Qt
        from PyQt4.QtGui import QLabel, QPixmap, QImage
        from PyQt4.Qt import QCursor
    except ImportError:
        from PyQt5.QtCore import pyqtSignal, QSize, Qt
        from PyQt5.QtGui import QLabel, QPixmap
        from PyQt5.Qt import QCursor

from ._OpenGLPlotCanvas import OpenGLPlotCanvas
from ._OpenGLPlotCanvas import CURSOR_DEFAULT, CURSOR_POINTING, \
    CURSOR_SIZE_HOR, CURSOR_SIZE_VER, CURSOR_SIZE_ALL


# OS Mesa #####################################################################

class OSMesaGLBackend(QLabel, OpenGLPlotCanvas):
    _signalRedisplay = pyqtSignal()  # PyQt binds it to instances

    _currentContext = None

    def __init__(self, parent=None, **kw):
        # Qt init
        QLabel.__init__(self, parent)
        self._signalRedisplay.connect(self.update)

        self.setAutoFillBackground(False)
        self.setMouseTracking(True)

        # OS Mesa init
        self.__dirtyPixmap = True
        self.__context = mesa.OSMesaCreateContext(mesa.OSMESA_BGRA, None)
        assert self.__context != 0

        # OpenGL Plot backend init
        OpenGLPlotCanvas.__init__(self, parent, **kw)

    def __del__(self):
        mesa.OSMesaDestroyContext(self.__context)

    @classmethod
    def getCurrentContext(cls):
        """Returns the current OSMesa GL context."""
        return cls._currentContext

    def makeCurrent(self):
        """Set the current OSMesa GL context to this instance.
        There is one context per OSMesaGLBackend instance.
        """
        OSMesaGLBackend._currentContext = self

    def postRedisplay(self):
        self.__dirtyPixmap = True
        self._signalRedisplay.emit()

    # Paint #
    def paintEvent(self, event):
        # Only refresh content when paint comes from backend
        if self.__dirtyPixmap:
            self.__dirtyPixmap = False

            height, width = self.__pixmap.shape[0:2]
            assert width == self.size().width()
            assert height == self.size().height()
            errCode = mesa.OSMesaMakeCurrent(self.__context,
                                             self.__pixmap,
                                             gl.GL_UNSIGNED_BYTE,
                                             width,
                                             height)
            assert errCode == gl.GL_TRUE

            self.makeCurrent()
            self.paintGL()
            gl.glFinish()

            image = QImage(self.__pixmap.data, width, height,
                           QImage.Format_ARGB32)
            self.setPixmap(QPixmap.fromImage(image))
        QLabel.paintEvent(self, event)

    def resizeEvent(self, event):
        width, height = self.size().width(), self.size().height()

        # Update underlying pixmap
        self.__dirtyPixmap = True
        self.__pixmap = np.empty((height, width, 4), dtype=np.uint8)
        errCode = mesa.OSMesaMakeCurrent(self.__context,
                                         self.__pixmap,
                                         gl.GL_UNSIGNED_BYTE,
                                         width,
                                         height)
        assert errCode == gl.GL_TRUE
        mesa.OSMesaPixelStore(mesa.OSMESA_Y_UP, 0)

        self.makeCurrent()
        gl.testGL()
        self.initializeGL()
        self.resizeGL(width, height)

        QLabel.resizeEvent(self, event)

    # Mouse events #
    _MOUSE_BTNS = {1: 'left', 2: 'right', 4: 'middle'}

    def sizeHint(self):
        return QSize(8 * 80, 6 * 80)  # Mimic MatplotlibBackend

    def mousePressEvent(self, event):
        xPixel, yPixel = event.x(), event.y()
        btn = self._MOUSE_BTNS[event.button()]
        self.onMousePress(xPixel, yPixel, btn)
        event.accept()

    def mouseMoveEvent(self, event):
        xPixel, yPixel = event.x(), event.y()
        self.onMouseMove(xPixel, yPixel)
        event.accept()

    def mouseReleaseEvent(self, event):
        xPixel, yPixel = event.x(), event.y()
        btn = self._MOUSE_BTNS[event.button()]
        self.onMouseRelease(xPixel, yPixel, btn)
        event.accept()

    def wheelEvent(self, event):
        xPixel, yPixel = event.x(), event.y()
        angleInDegrees = event.delta() / 8.
        self.onMouseWheel(xPixel, yPixel, angleInDegrees)
        event.accept()

    _CURSORS = {
        CURSOR_DEFAULT: Qt.ArrowCursor,
        CURSOR_POINTING: Qt.PointingHandCursor,
        CURSOR_SIZE_HOR: Qt.SizeHorCursor,
        CURSOR_SIZE_VER: Qt.SizeVerCursor,
        CURSOR_SIZE_ALL: Qt.SizeAllCursor,
    }

    def setCursor(self, cursor=CURSOR_DEFAULT):
        cursor = self._CURSORS[cursor]
        QLabel.setCursor(self, QCursor(cursor))

    # Widget handle

    def getWidgetHandle(self):
        return self

# Init GL context getter
setGLContextGetter(OSMesaGLBackend.getCurrentContext)
# OSMesaGetCurrentContext does not return the same object for the context.
# setGLContextGetter(mesa.OSMesaGetCurrentContext)


# main ########################################################################

if __name__ == "__main__":
    import sys
    try:
        from PyQt4.QtGui import QApplication
    except ImportError:
        from PyQt5.QtWidgets import QApplication

    from PyMca5.PyMcaGraph.Plot import Plot

    app = QApplication([])
    w = Plot(None, backend=OSMesaGLBackend)

    size = 1024
    data = np.arange(float(size)*size, dtype=np.uint16)
    data.shape = size, size

    colormap = {'name': 'gray', 'normalization': 'linear',
                'autoscale': True, 'vmin': 0.0, 'vmax': 1.0,
                'colors': 256}
    w.addImage(data, legend="image 1",
               xScale=(25, 1.0), yScale=(-1000, 1.0),
               replot=False, colormap=colormap)
    w.insertXMarker(512, 'testX', 'markerX', color='pink',
                    selectable=False, draggable=True)

    w.getWidgetHandle().show()
    sys.exit(app.exec())