forked from openPSTD/openPSTD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Viewer2D.py
694 lines (526 loc) · 22.6 KB
/
Viewer2D.py
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
########################################################################
# #
# This file is part of openPSTD. #
# #
# openPSTD is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# openPSTD is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with openPSTD. If not, see <http://www.gnu.org/licenses/>. #
# #
########################################################################
__author__ = 'michiel'
import sys
import abc
import copy
import math
from PySide import QtCore, QtGui, QtOpenGL
from vispy import gloo
import OpenGL.GL as gl
import numpy as np
from colors import activeColorScheme as colorScheme
#from model import Model
import InteractiveView
from transforms2D import Matrix
import MouseHandlers
try:
# noinspection PyUnresolvedReferences
from OpenGL import GL
except ImportError:
app = QtGui.QApplication(sys.argv)
# noinspection PyTypeChecker
QtGui.QMessageBox.critical(None, "OpenPSTD",
"PyOpenGL must be installed to run this application.",
QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default,
QtGui.QMessageBox.NoButton)
sys.exit(1)
class Viewer2D(QtOpenGL.QGLWidget):
def __init__(self, parent=None):
QtOpenGL.QGLWidget.__init__(self, parent)
self.setMouseTracking(True)
self.viewPort = [640, 480]
self.layers = {
"simulation": SimulationLayer(),
"Scene": SceneLayer(),
"Debug": DebugLayer(),
"Interactive": InteractiveView.InteractiveViewLayer(),
"Grid": GridLayer()
}
[v.set_viewer_2d(self) for k, v in self.layers.items()]
self.mouseHandler = MouseHandlers.MouseStrategyConsole()
""":type: MouseHandlers.MouseStrategy"""
self._view_matrix = Matrix()
self.scene_min_max = MinMaxLayer([-1, -1], [1, 1])
def minimumSizeHint(self):
return QtCore.QSize(50, 50)
def sizeHint(self):
return QtCore.QSize(400, 400)
def initializeGL(self):
gl.glEnable(gl.GL_BLEND)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
[v.initialize_gl() for k, v in self.layers.items()]
def paintGL(self):
gl.glClearColor(1,1,1,1)
gl.glClear(gl.GL_COLOR_BUFFER_BIT)
[v.paint_gl_visibility_check() for k, v in self.layers.items()]
def resizeGL(self, width, height):
view = self.get_view_matrix()
view = view*Matrix.scale(self.viewPort[0]/width, self.viewPort[1]/height)
self.set_view_matrix(view)
gl.glViewport(0, 0, width, height)
self.viewPort = [width, height]
def mousePressEvent(self, event):
self.mouseHandler.mousePressEvent(event)
def mouseMoveEvent(self, event):
self.mouseHandler.mouseMoveEvent(event)
def wheelEvent(self, event):
self.mouseHandler.wheelEvent(event)
def mouseReleaseEvent(self, event):
self.mouseHandler.mouseReleaseEvent(event)
def update_scene(self, model):
"""
Updates all the layers with new information in the model
:type model: Model
:param model: the current model
"""
[v.update_scene(model) for k, v in self.layers.items()]
self.scene_min_max = MinMaxLayer.combineList([v.get_min_max() for k, v in self.layers.items()])
self.update()
def set_view_matrix(self, matrix: Matrix):
"""
Replaces the current matrix with a new matrix.
:param matrix: the matrix that has to replace the current matrix
"""
self._view_matrix = matrix
[v.update_view_matrix(self._view_matrix.M) for k, v in self.layers.items()]
def get_view_matrix(self) -> Matrix:
"""
Returns the current matrix.
:rtype : Matrix
:return: The current matrix.
"""
return self._view_matrix
def read_shader(filename: str) -> str:
"""
Read file into a stream for reading a shader
:rtype : str
:param filename: a filename of the shader
:return: the contents of that file
"""
with open(filename, "r") as file:
return file.read()
class MinMaxLayer(object):
def __init__(self, pos_min: list=None, pos_max: list=None):
"""
Creates an info object that can be used to calculate the minimum and maximum of an layer
:param pos_min: the minimum of the layer, defaults to positive infinity
:param pos_max: the maximum of the layer, defaults to negative infinity
"""
if pos_min is not None:
self.pos_min = pos_min
else:
self.pos_min = [float("inf"), float("inf")]
if pos_min is not None:
self.pos_max = pos_max
else:
self.pos_max = [-float("inf"), -float("inf")]
def min(self, *values: list, dimension: int=-1):
"""
Calculates the min of 2 dimensional points or in a certain dimension
:type values: list[list[float]]
:type dimension: int
:param values: the 2 dimensional points or single scaler values
:param dimension: if 2 dimensional points are given, then this should be -1, else it should specify the
dimension in which it should minimize the values.
"""
if dimension == -1:
for d in range(2):
self.min([v[d] for v in values], dimension=d)
else:
values2 = list(*values)
values2.append(self.pos_min[dimension])
self.pos_min[dimension] = min(*values2)
def max(self, *values: list, dimension: int=-1):
"""
Calculates the max of 2 dimensional points or in a certain dimension
:type values: list[list[float]]
:param values: the 2 dimensional points or single scaler values
:param dimension: if 2 dimensional points are given, then this should be -1, else it should specify the
dimension in which it should maximize the values.
"""
if dimension == -1:
for d in range(2):
self.max([v[d] for v in values], dimension=d)
else:
values2 = list(*values)
values2.append(self.pos_max[dimension])
self.pos_max[dimension] = max(*values2)
def combine(self, other):
"""
The combine method combines 2 different min and max of layers together
:rtype : MinMaxLayer
:param other: the other layers information
:return: a new object with layer information
"""
result = MinMaxLayer()
if other is not None:
result.pos_max[0] = max(self.pos_max[0], other.pos_max[0])
result.pos_max[1] = max(self.pos_max[1], other.pos_max[1])
result.pos_min[0] = min(self.pos_min[0], other.pos_min[0])
result.pos_min[1] = min(self.pos_min[1], other.pos_min[1])
else:
result.pos_max[0] = self.pos_max[0]
result.pos_max[1] = self.pos_max[1]
result.pos_min[0] = self.pos_min[0]
result.pos_min[1] = self.pos_min[1]
return result
@staticmethod
def combineList(l: list):
"""
Combines a list of MinMaxLayer to generate a complete info for multiple layers, None elements are ignored.
:rtype : MinMaxLayer
:param l: list of MinMaxLayer
:return: The resulting minimum and maximum
"""
total = MinMaxLayer([float("inf"), float("inf")], [-float("inf"), -float("inf")])
for info in l:
if info is not None:
total = total.combine(info)
return total
class Layer:
__metaclass__ = abc.ABCMeta
def __init__(self):
self.visible = True
self.viewer_2d = None
""":type: Viewer2D"""
self.view_matrix = np.eye(3,dtype=np.float32)
def set_viewer_2d(self, viewer_2d):
self.viewer_2d = viewer_2d
def set_visible(self, value):
"""
set's the visibility property
:type value: bool
:param value: the new value
"""
self.visible = value
def get_visible(self):
"""
returns the value of the visibility property
:return: true if the layer is visible
:rtype: bool
"""
return self.visible
def initialize_gl(self):
"""
Initilizes everything from GL, like loading shaders and creating buffers
"""
pass
def paint_gl_visibility_check(self):
"""
Checks if this layer is visible, if so calls the paint_gl method
"""
if self.visible:
self.paint_gl()
def paint_gl(self):
"""
Does the draw actions, these methods can't be big
"""
pass
def update_scene(self, model):
"""
Updates all the scene information
:param model: the model where the scene has to be based on
"""
pass
def get_min_max(self) -> MinMaxLayer:
"""
Returns the min and max of the layer, with this information the view whole scene is created. If this layer
should not be accounted for, then return None.
:rtype : MinMaxLayer
:return: the min and maximum of the layer.
"""
return None
def update_view_matrix(self, matrix: Matrix):
"""
Changes the matrix for this layer.
:type matrix: Matrix
:param matrix: The new matrix
"""
self.view_matrix = matrix
class SimulationLayer(Layer):
def __init__(self):
super(SimulationLayer, self).__init__()
self.program = None
self.renderInfo = {}
self.scene_min_max = MinMaxLayer([0, 0], [0, 0])
def initialize_gl(self):
vertex_code = read_shader("GPU\Simulation2D.vert")
fragment_code = read_shader("GPU\Simulation2D.frag")
self._create_colormap()
# Build program & data
# ----------------------------------------
self.program = gloo.Program(vertex_code, fragment_code, count=4)
self.program['u_view'] = np.eye(3,dtype=np.float32)
self.program['vmin'] = 0.00
self.program['vmax'] = 0.10
self.program['colormap'] = self.colormap
def paint_gl(self):
for domain, info in self.renderInfo.items():
self.program['a_color'] = info['colors']
self.program['a_position'] = info['position']
self.program['a_texcoord'] = info['texcoord']
self.program['image'] = info['texture']
self.program.draw('triangle_strip')
def update_scene(self, model):
scene_min_max = MinMaxLayer()
for id in model.Simulation.get_list_domain_ids():
if model.Simulation.frame_exists(id, model.visible_frame):
data = model.Simulation.read_frame(id, model.visible_frame)
domain = data['scene_desc']
x = 0
y = 1
tl = [domain['topleft'][x], domain['topleft'][y]]
tr = [domain['topleft'][x]+domain['size'][x], domain['topleft'][y]]
bl = [domain['topleft'][x], domain['topleft'][y]+domain['size'][y]]
br = [domain['topleft'][x]+domain['size'][x], domain['topleft'][y]+domain['size'][y]]
scene_min_max.max(tl, tr, bl, br)
scene_min_max.min(tl, tr, bl, br)
if id in self.renderInfo:
self._update_texture(data['data'], self.renderInfo[id]['texture'])
else:
self.renderInfo[id] = \
{
'texture': self._load_texture(data['data']),
'position': gloo.VertexBuffer(np.array([tl, tr, bl, br], np.float32)),
'texcoord': gloo.VertexBuffer(np.array([(0, 0), (0, +1), (+1, 0), (+1, +1)], np.float32)),
'colors': gloo.VertexBuffer(np.array([[0, 1, 0], [0, 0, 1], [0, 1, 1], [1, 0, 1]], np.float32))
}
for key in copy.copy(self.renderInfo):
if not model.Simulation.frame_exists(key, model.visible_frame):
del self.renderInfo[key]
self.scene_min_max = scene_min_max
def get_min_max(self):
return self.scene_min_max
def update_view_matrix(self, matrix):
self.program['u_view'] = matrix
def _load_texture(self, data):
T = gloo.Texture2D(data=data, store=True, copy=False)
T.interpolation = 'linear'
return T
def _update_texture(self, data, T):
T[:] = data[:]
def _create_colormap(self):
gradient = colorScheme.editorDomainSignalColorGradient()
colormap = gradient.create_color_map(0, 0.10, 512)
colormap2 = [colormap]
T = gloo.Texture2D(data=colormap2, store=True, copy=False)
T.interpolation = 'linear'
self.colormap = T
class SceneLayer(Layer):
def __init__(self):
super(SceneLayer, self).__init__()
self.program = None
self.renderInfo = {}
self.scene_min_max = MinMaxLayer([0, 0], [0, 0])
def initialize_gl(self):
vertex_code = read_shader("GPU\Scene2D.vert")
fragment_code = read_shader("GPU\Scene2D.frag")
self._create_colormap()
self.vPosition = gloo.VertexBuffer(np.array([[0, 0], [0, 0]], np.float32))
self.vValues = gloo.VertexBuffer(np.array([[0], [0]], np.float32))
# Build program & data
# ----------------------------------------
self.program = gloo.Program(vertex_code, fragment_code, count=4)
self.program['u_view'] = np.eye(3,dtype=np.float32)
self.program['vmin'] = 0.00
self.program['vmax'] = 1.00
self.program['colormap'] = self.colormap
self.program['a_position'] = self.vPosition
self.program['a_value'] = self.vValues
def paint_gl(self):
gl.glLineWidth(5.0)
self.program.draw(gl.GL_LINES)
def update_scene(self, model):
horizontalEdges = []
verticalEdges = []
horizontalvalues = []
verticalvalues = []
edges = []
values = []
scene_min_max = MinMaxLayer()
# region reading domains
for domain in model.SceneDesc['domains']:
x = 0
y = 1
tl = [domain['topleft'][x], domain['topleft'][y]]
tr = [domain['topleft'][x]+domain['size'][x], domain['topleft'][y]]
bl = [domain['topleft'][x], domain['topleft'][y]+domain['size'][y]]
br = [domain['topleft'][x]+domain['size'][x], domain['topleft'][y]+domain['size'][y]]
scene_min_max.max(tl, tr, bl, br)
scene_min_max.min(tl, tr, bl, br)
horizontalvalues.append([domain['edges']['t']['a']])
horizontalEdges.append(tl)
horizontalvalues.append([domain['edges']['t']['a']])
horizontalEdges.append(tr)
verticalvalues.append([domain['edges']['r']['a']])
verticalEdges.append(tr)
verticalvalues.append([domain['edges']['r']['a']])
verticalEdges.append(br)
horizontalvalues.append([domain['edges']['b']['a']])
horizontalEdges.append(br)
horizontalvalues.append([domain['edges']['b']['a']])
horizontalEdges.append(bl)
verticalvalues.append([domain['edges']['l']['a']])
verticalEdges.append(bl)
verticalvalues.append([domain['edges']['l']['a']])
verticalEdges.append(tl)
# endregion
edges.extend(verticalEdges)
edges.extend(horizontalEdges)
values.extend(verticalvalues)
values.extend(horizontalvalues)
self.vPosition.set_data(np.array(edges, np.float32))
self.vValues.set_data(np.array(values, np.float32))
self.scene_min_max = scene_min_max
def get_min_max(self):
return self.scene_min_max
def update_view_matrix(self, matrix):
self.program['u_view'] = matrix
def _create_colormap(self):
gradient = colorScheme.editorLineAbsoptionColorGradient()
colormap = gradient.create_color_map(0.0, 1.0, 512)
colormap2 = [colormap]
T = gloo.Texture2D(data=colormap2, store=True, copy=False)
T.interpolation = 'linear'
self.colormap = T
class GridLayer(Layer):
def __init__(self):
super(GridLayer, self).__init__()
self.program = None
self.renderInfo = {}
self.scene_min_max = {max: [0, 0], min: [0, 0]}
def initialize_gl(self):
vertex_code = read_shader("GPU\Debug2D.vert")
fragment_code = read_shader("GPU\Debug2D.frag")
self.vPosition = gloo.VertexBuffer(np.array([[0, 0], [5, 0]], np.float32))
self.vColors = gloo.VertexBuffer(np.array(
[
(0.5, 0.5, 0.5, 0.5),
(0.5, 0.5, 0.5, 0.5)], np.float32))
# Build program & data
# ----------------------------------------
self.program = gloo.Program(vertex_code, fragment_code, count=4)
self.program['u_view'] = np.eye(3, dtype=np.float32)
self.program['a_position'] = self.vPosition
self.program['a_color'] = self.vColors
def paint_gl(self):
gl.glLineWidth(1.0)
self.program.draw('lines')
def update_scene(self, model):
"""
:type model: m.Model
"""
grid_spacing = model.SceneDesc["grid_spacing"]
coordCalc = CoordinateCalculator(self.viewer_2d)
tl = coordCalc.screen_to_world([-1, -1])
br = coordCalc.screen_to_world([1, 1])
tl[0] = math.floor(tl[0]/grid_spacing)
tl[1] = math.ceil(tl[1]/grid_spacing)
br[0] = math.ceil(br[0]/grid_spacing)
br[1] = math.floor(br[1]/grid_spacing)
vertical_lines = abs(int(br[0])-int(tl[0]))
horizontal_lines = abs(int(br[1])-int(tl[1]))
lines = vertical_lines+horizontal_lines
tl[0] = tl[0]*grid_spacing
tl[1] = tl[1]*grid_spacing
br[0] = br[0]*grid_spacing
br[1] = br[1]*grid_spacing
positions = [x for x in range(lines)]
positions[0:vertical_lines] = [[(tl[0]+x*grid_spacing, tl[1]), (tl[0]+x*grid_spacing, br[1])] for x in range(vertical_lines)]
positions[vertical_lines:vertical_lines+horizontal_lines] = [[(tl[0], tl[1]-x*grid_spacing), (br[0], tl[1]-x*grid_spacing)] for x in range(horizontal_lines)]
positions = np.array(positions, np.float32).flatten().reshape((lines*2, 2))
colors = np.array([(0.5, 0.5, 0.5, 0.5) for _ in range(len(positions))], np.float32)
self.vPosition.set_data(positions)
self.vColors.set_data(colors)
def update_view_matrix(self, matrix):
self.program['u_view'] = matrix
class DebugLayer(Layer):
def __init__(self):
super(DebugLayer, self).__init__()
self.program = None
def initialize_gl(self):
vertex_code = read_shader("GPU\Debug2D.vert")
fragment_code = read_shader("GPU\Debug2D.frag")
self.vPosition = gloo.VertexBuffer(np.array([[0, 0], [0, 0], [0, 0], [0, 0]], np.float32))
self.vColors = gloo.VertexBuffer(np.array([[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]], np.float32))
# Build program & data
# ----------------------------------------
self.program = gloo.Program(vertex_code, fragment_code, count=4)
self.program['u_view'] = np.eye(3,dtype=np.float32)
self.program['a_position'] = self.vPosition
self.program['a_color'] = self.vColors
def paint_gl(self):
self.program.draw(gl.GL_TRIANGLE_STRIP)
def update_scene(self, model):
if 'viewer' not in model.debug_data:
return
self.vPosition.set_data(np.array(model.debug_data['viewer']['positions'], np.float32))
self.vColors.set_data(np.array(model.debug_data['viewer']['Colors'], np.float32))
def get_min_max(self):
return None
def update_view_matrix(self, matrix):
self.program['u_view'] = matrix
class CoordinateCalculator:
def __init__(self, viewer: Viewer2D):
"""
Creates a coordinate calculator, that can calculates coordinates
:type viewer: Viewer2D
:param viewer: the viewer where the coordinates are based on
"""
self._viewer = viewer
def window_to_screen(self, pos: list) -> list:
"""
Calculates from window space to screen space.
Window space is from [0, 0] to [width, height] of the gl view.
Screen space is from [-1, -1] to [1, 1].
:rtype : list[float]
:type pos: list[float]
:param pos: the window space coordinates
:return: the screen space coordinates
"""
w = self._viewer.width()
h = self._viewer.height()
pos2 = [pos[0], pos[1]]
pos3 = [pos2[0] / w, pos2[1] / h]
pos4 = [pos3[0] * 2, pos3[1] * 2]
pos5 = [pos4[0] - 1, pos4[1] - 1]
pos6 = np.array([pos5[0], -pos5[1]])
return pos6
def screen_to_world(self, pos: list) -> list:
"""
Calculates from screen space to world space.
Screen space is from [-1, -1] to [1, 1].
world space are the coordinates from within the scene, that is rendered
:rtype : list[float]
:param pos: the screen space coordinates
:return: the world space coordinates
"""
world_pos = self._viewer.get_view_matrix().invMultipleVector(pos)
return world_pos
def window_to_world(self, pos: list) -> list:
"""
Calculates from screen space to world space.
Window space is from [0, 0] to [width, height] of the gl view.
world space are the coordinates from within the scene, that is rendered
:rtype : list[float]
:param pos: the window space coordinates
:return: the world space coordinates
"""
return self.screen_to_world(self.window_to_screen(pos))