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
|
import enum
import importlib
from OpenGL import GL
from OpenGL.GL import shaders
import numpy as np
from ...Qt import QtGui, QT_LIB
from ... import functions as fn
from ..GLGraphicsItem import GLGraphicsItem
if QT_LIB in ["PyQt5", "PySide2"]:
QtOpenGL = QtGui
else:
QtOpenGL = importlib.import_module(f"{QT_LIB}.QtOpenGL")
__all__ = ['GLLinePlotItem']
class DirtyFlag(enum.Flag):
POSITION = enum.auto()
COLOR = enum.auto()
class GLLinePlotItem(GLGraphicsItem):
"""Draws line plots in 3D."""
_shaderProgram = None
def __init__(self, parentItem=None, **kwds):
"""All keyword arguments are passed to setData()"""
super().__init__()
glopts = kwds.pop('glOptions', 'additive')
self.setGLOptions(glopts)
self.pos = None
self.mode = 'line_strip'
self.width = 1.
self.color = (1.0,1.0,1.0,1.0)
self.antialias = False
self.m_vbo_position = QtOpenGL.QOpenGLBuffer(QtOpenGL.QOpenGLBuffer.Type.VertexBuffer)
self.m_vbo_color = QtOpenGL.QOpenGLBuffer(QtOpenGL.QOpenGLBuffer.Type.VertexBuffer)
self.dirty_bits = DirtyFlag(0)
self.setParentItem(parentItem)
self.setData(**kwds)
def setData(self, **kwds):
"""
Update the data displayed by this item. All arguments are optional;
for example it is allowed to update vertex positions while leaving
colors unchanged, etc.
==================== ==================================================
**Arguments:**
------------------------------------------------------------------------
pos (N,3) array of floats specifying point locations.
color (N,4) array of floats (0.0-1.0) or
tuple of floats specifying
a single color for the entire item.
width float specifying line width
antialias enables smooth line drawing
mode 'lines': Each pair of vertexes draws a single line
segment.
'line_strip': All vertexes are drawn as a
continuous set of line segments.
==================== ==================================================
"""
args = ['pos', 'color', 'width', 'mode', 'antialias']
for k in kwds.keys():
if k not in args:
raise Exception('Invalid keyword argument: %s (allowed arguments are %s)' % (k, str(args)))
if 'pos' in kwds:
pos = kwds.pop('pos')
self.pos = np.ascontiguousarray(pos, dtype=np.float32)
self.dirty_bits |= DirtyFlag.POSITION
if 'color' in kwds:
color = kwds.pop('color')
if isinstance(color, np.ndarray):
color = np.ascontiguousarray(color, dtype=np.float32)
self.dirty_bits |= DirtyFlag.COLOR
if isinstance(color, str):
color = fn.mkColor(color)
if isinstance(color, QtGui.QColor):
color = color.getRgbF()
self.color = color
for k, v in kwds.items():
setattr(self, k, v)
if self.mode not in ['line_strip', 'lines']:
raise ValueError("Unknown line mode '%s'. (must be 'lines' or 'line_strip')" % self.mode)
self.update()
def upload_vbo(self, vbo, arr):
if arr is None:
vbo.destroy()
return
if not vbo.isCreated():
vbo.create()
vbo.bind()
if vbo.size() != arr.nbytes:
vbo.allocate(arr, arr.nbytes)
else:
vbo.write(0, arr, arr.nbytes)
vbo.release()
@staticmethod
def getShaderProgram():
klass = GLLinePlotItem
if klass._shaderProgram is not None:
return klass._shaderProgram
ctx = QtGui.QOpenGLContext.currentContext()
fmt = ctx.format()
if ctx.isOpenGLES():
if fmt.version() >= (3, 0):
glsl_version = "#version 300 es\n"
sources = SHADER_CORE
else:
glsl_version = ""
sources = SHADER_LEGACY
else:
if fmt.version() >= (3, 1):
glsl_version = "#version 140\n"
sources = SHADER_CORE
else:
glsl_version = ""
sources = SHADER_LEGACY
compiled = [shaders.compileShader([glsl_version, v], k) for k, v in sources.items()]
program = shaders.compileProgram(*compiled)
# bind generic vertex attrib 0 to "a_position" so that
# vertex attrib 0 definitely gets enabled later.
GL.glBindAttribLocation(program, 0, "a_position")
GL.glBindAttribLocation(program, 1, "a_color")
GL.glLinkProgram(program)
klass._shaderProgram = program
return program
def paint(self):
if self.pos is None:
return
self.setupGLState()
mat_mvp = self.mvpMatrix()
mat_mvp = np.array(mat_mvp.data(), dtype=np.float32)
context = QtGui.QOpenGLContext.currentContext()
if DirtyFlag.POSITION in self.dirty_bits:
self.upload_vbo(self.m_vbo_position, self.pos)
if DirtyFlag.COLOR in self.dirty_bits:
self.upload_vbo(self.m_vbo_color, self.color)
self.dirty_bits = DirtyFlag(0)
program = self.getShaderProgram()
enabled_locs = []
loc = 0
self.m_vbo_position.bind()
GL.glVertexAttribPointer(loc, 3, GL.GL_FLOAT, False, 0, None)
self.m_vbo_position.release()
enabled_locs.append(loc)
loc = 1
if isinstance(self.color, np.ndarray):
self.m_vbo_color.bind()
GL.glVertexAttribPointer(loc, 4, GL.GL_FLOAT, False, 0, None)
self.m_vbo_color.release()
enabled_locs.append(loc)
else:
GL.glVertexAttrib4f(loc, *self.color)
enable_aa = self.antialias and not context.isOpenGLES()
if enable_aa:
GL.glEnable(GL.GL_LINE_SMOOTH)
GL.glEnable(GL.GL_BLEND)
GL.glBlendFuncSeparate(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA,
GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA)
GL.glHint(GL.GL_LINE_SMOOTH_HINT, GL.GL_NICEST)
sfmt = context.format()
core_forward_compatible = (
sfmt.profile() == sfmt.OpenGLContextProfile.CoreProfile
and not sfmt.testOption(sfmt.FormatOption.DeprecatedFunctions)
)
if not core_forward_compatible:
# Core Forward Compatible profiles will return error for
# any width that is not 1.0
GL.glLineWidth(self.width)
for loc in enabled_locs:
GL.glEnableVertexAttribArray(loc)
with program:
loc = GL.glGetUniformLocation(program, "u_mvp")
GL.glUniformMatrix4fv(loc, 1, False, mat_mvp)
if self.mode == 'line_strip':
GL.glDrawArrays(GL.GL_LINE_STRIP, 0, len(self.pos))
elif self.mode == 'lines':
GL.glDrawArrays(GL.GL_LINES, 0, len(self.pos))
for loc in enabled_locs:
GL.glDisableVertexAttribArray(loc)
if enable_aa:
GL.glDisable(GL.GL_LINE_SMOOTH)
GL.glDisable(GL.GL_BLEND)
GL.glLineWidth(1.0)
SHADER_LEGACY = {
GL.GL_VERTEX_SHADER : """
uniform mat4 u_mvp;
attribute vec4 a_position;
attribute vec4 a_color;
varying vec4 v_color;
void main() {
v_color = a_color;
gl_Position = u_mvp * a_position;
}
""",
GL.GL_FRAGMENT_SHADER : """
#ifdef GL_ES
precision mediump float;
#endif
varying vec4 v_color;
void main() {
gl_FragColor = v_color;
}
""",
}
SHADER_CORE = {
GL.GL_VERTEX_SHADER : """
uniform mat4 u_mvp;
in vec4 a_position;
in vec4 a_color;
out vec4 v_color;
void main() {
v_color = a_color;
gl_Position = u_mvp * a_position;
}
""",
GL.GL_FRAGMENT_SHADER : """
#ifdef GL_ES
precision mediump float;
#endif
in vec4 v_color;
out vec4 fragColor;
void main() {
fragColor = v_color;
}
""",
}
|