def _shader_from_file(self, fname_vert, fname_frag): shader = QOpenGLShaderProgram() shader.addShaderFromSourceFile(QOpenGLShader.Vertex, fname_vert) shader.addShaderFromSourceFile(QOpenGLShader.Fragment, fname_frag) shader.link() shader.bind() logger.debug("GLSL program log:%s", shader.log()) return shader
class TriangleUnderlayRenderer(QObject): def __init__(self, parent=None): super(TriangleUnderlayRenderer, self).__init__(parent) self._shader_program = None self._viewport_size = QSize() self._window = None @pyqtSlot() def paint(self): # TODO test on Ubuntu # for Darwin, it's a must gl = self._window.openglContext().versionFunctions() if self._shader_program is None: self._shader_program = QOpenGLShaderProgram() self._shader_program.addShaderFromSourceFile( QOpenGLShader.Vertex, 'shaders/OpenGL_2_1/vertex.glsl') self._shader_program.addShaderFromSourceFile( QOpenGLShader.Fragment, 'shaders/OpenGL_2_1/fragment.glsl') self._shader_program.bindAttributeLocation('position', 0) self._shader_program.bindAttributeLocation('color', 1) self._shader_program.link() self._shader_program.bind() self._shader_program.enableAttributeArray(0) self._shader_program.enableAttributeArray(1) self._shader_program.setAttributeArray(0, positions) self._shader_program.setAttributeArray(1, colors) gl.glViewport(0, 0, self._viewport_size.width(), self._viewport_size.height()) gl.glClearColor(0.5, 0.5, 0.5, 1) gl.glDisable(gl.GL_DEPTH_TEST) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3) self._shader_program.disableAttributeArray(0) self._shader_program.disableAttributeArray(1) self._shader_program.release() # Restore the OpenGL state for QtQuick rendering self._window.resetOpenGLState() self._window.update() def set_viewport_size(self, size): self._viewport_size = size def set_window(self, window): self._window = window
def init_shaders(self): program = QOpenGLShaderProgram(self) if not program.addShaderFromSourceFile(QOpenGLShader.Vertex, get_resources_path("shader.vert")): return None if not program.addShaderFromSourceFile(QOpenGLShader.Fragment, get_resources_path("shader.frag")): return None if not program.link(): return None if not program.bind(): return None return program
def init_shaders(self): program = QOpenGLShaderProgram(self) if not program.addShaderFromSourceFile( QOpenGLShader.Vertex, get_resources_path("shader.vert")): return None if not program.addShaderFromSourceFile( QOpenGLShader.Fragment, get_resources_path("shader.frag")): return None if not program.link(): return None if not program.bind(): return None return program
class ModelRenderer(QObject): """ The ModelRenderer wraps an opengl context so you can draw models to it. Currently supports blockmodels. You need: an opengl surface, an opengl context and a workspace instance. """ def __init__(self, workspace, surface: QSurface): super().__init__() self.surf = surface prof = QOpenGLVersionProfile() prof.setVersion(2, 0) self.vao = GL.glGenVertexArrays(1) self.vbo, self.vbo2 = GL.glGenBuffers(2) self.texture = -1 self.current_model: BlockModel = None self.workspace = workspace self.array1, array2 = None, None self.shader = QOpenGLShaderProgram() self.shader.addShaderFromSourceFile(QOpenGLShader.Vertex, "shader/block.vertex.glsl") self.shader.addShaderFromSourceFile(QOpenGLShader.Fragment, "shader/block.fragment.glsl") self.shader.link() self.proj_mat = glm.perspective( 1.57, self.surf.size().width() / self.surf.size().height(), 0.1, 100) self.texture = GL.glGenTextures(1) def set_workspace(self, workspace): self.workspace = workspace def setup_data_for_block_model(self, model: BlockModel): """ Setup the vbo & texture for a block model todo: optimize for repeats You probably should call render after using this function :param model: the blockmodel to setup for """ self.current_model = model print(self.workspace) atlas = model.create_model_atlas(self.workspace) GL.glBindTexture(GL.GL_TEXTURE_2D, self.texture) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, atlas.size[0], atlas.size[1], 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, atlas.data) verts, uvs = model.compile_to_vertex_list(atlas) verts = list(map(lambda x: list(x), verts)) uvs = list(map(lambda x: list(x), uvs)) GL.glBindVertexArray(self.vao) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.vbo) self.array1 = np.array(verts, dtype=np.float32).ravel() self.array2 = np.array(uvs, dtype=np.float32).ravel() GL.glBufferData(GL.GL_ARRAY_BUFFER, self.array1.size * 4, self.array1, GL.GL_DYNAMIC_DRAW) GL.glEnableVertexAttribArray(0) GL.glEnableVertexAttribArray(1) GL.glVertexAttribPointer(0, 4, GL.GL_FLOAT, GL.GL_FALSE, 0, ctypes.c_void_p(0)) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.vbo2) GL.glBufferData(GL.GL_ARRAY_BUFFER, self.array1.size * 4, self.array2, GL.GL_DYNAMIC_DRAW) GL.glVertexAttribPointer(1, 2, GL.GL_FLOAT, GL.GL_FALSE, 0, ctypes.c_void_p(0)) GL.glBindVertexArray(0) self.array_size = len(verts) self.array = verts def _plumb_shader_for(self, proj_view: glm.mat4, model_transform): self.shader.bind() GL.glUniformMatrix4fv(1, 1, GL.GL_FALSE, glm.value_ptr(proj_view)) GL.glUniformMatrix4fv(0, 1, GL.GL_FALSE, glm.value_ptr(model_transform)) print(model_transform * self.array[0]) GL.glBindTexture(GL.GL_TEXTURE_2D, self.texture) def draw_loaded_model(self, view_matrix, transform_name, proj=None): """ Draw the loaded model with transforms and view :param proj: projection matrix for doing ortho :param view_matrix: View matrix (y should be up) :param transform_name: Transform name in model """ if self.current_model is None: raise ValueError("No model is loaded!") if proj is None: proj = self.proj_mat print(self.current_model.transforms[transform_name]) self._plumb_shader_for(proj * view_matrix, self.current_model.transforms[transform_name]) GL.glBindVertexArray(self.vao) GL.glEnable(GL.GL_DEPTH_TEST) GL.glDrawArrays(GL.GL_TRIANGLES, 0, len(self.array)) def resize(self, width, height): """ Resize the modelRenderer to acommodate for differing aspect ratios """ self.proj_mat = glm.perspective(1.57, width / height, 0.1, 100)
class QtGL2Material(Material): def __init__(self, renderer): super().__init__() self._gl = renderer._gl self._shader_program = None self._uniform_indices = {} self._attribute_indices = {} self._uniform_values = {} self._bound = False self._textures = {} def loadVertexShader(self, file): if not self._shader_program: self._shader_program = QOpenGLShaderProgram() self._shader_program.addShaderFromSourceFile(QOpenGLShader.Vertex, file) def loadFragmentShader(self, file): if not self._shader_program: self._shader_program = QOpenGLShaderProgram() self._shader_program.addShaderFromSourceFile(QOpenGLShader.Fragment, file) def build(self): if not self._shader_program: Logger.log("e", "No shader sources loaded") return self._shader_program.link() def setUniformValue(self, name, value, **kwargs): if not self._shader_program: return cache = True if "cache" in kwargs: cache = kwargs["cache"] if name not in self._uniform_indices: self._uniform_indices[name] = self._shader_program.uniformLocation(name) uniform = self._uniform_indices[name] if uniform == -1: return if cache: self._uniform_values[uniform] = value if self._bound: self._setUniformValueDirect(uniform, value) def setUniformTexture(self, name, file): if not self._shader_program: return if name not in self._uniform_indices: self._uniform_indices[name] = self._shader_program.uniformLocation(name) index = self._uniform_indices[name] texture = QOpenGLTexture(QImage(file).mirrored()) texture.setMinMagFilters(QOpenGLTexture.Linear, QOpenGLTexture.Linear) self._textures[index] = texture self._uniform_values[index] = 1 if self._bound: texture = self._textures[index] texture.bind() self._setUniformValueDirect(index, texture.textureId()) def enableAttribute(self, name, type, offset, stride = 0): if not self._shader_program: return self.bind() if name not in self._attribute_indices: self._attribute_indices[name] = self._shader_program.attributeLocation(name) attribute = self._attribute_indices[name] if attribute == -1: return if type is "int": self._shader_program.setAttributeBuffer(attribute, self._gl.GL_INT, offset, 1, stride) elif type is "float": self._shader_program.setAttributeBuffer(attribute, self._gl.GL_FLOAT, offset, 1, stride) elif type is "vector2f": self._shader_program.setAttributeBuffer(attribute, self._gl.GL_FLOAT, offset, 2, stride) elif type is "vector3f": self._shader_program.setAttributeBuffer(attribute, self._gl.GL_FLOAT, offset, 3, stride) elif type is "vector4f": self._shader_program.setAttributeBuffer(attribute, self._gl.GL_FLOAT, offset, 4, stride) self._shader_program.enableAttributeArray(attribute) def disableAttribute(self, name): if not self._shader_program: return if name not in self._attribute_indices: return self._shader_program.disableAttributeArray(self._attribute_indices[name]) def bind(self): if not self._shader_program or not self._shader_program.isLinked(): return if self._bound: return self._bound = True self._shader_program.bind() for uniform in self._uniform_values: if uniform in self._textures: texture = self._textures[uniform] texture.bind() self._setUniformValueDirect(uniform, 0) else: self._setUniformValueDirect(uniform, self._uniform_values[uniform]) def release(self): if not self._shader_program or not self._bound: return for texture in self._textures.values(): texture.release() self._bound = False self._shader_program.release() def _matrixToQMatrix4x4(self, m): return QMatrix4x4(m.at(0,0), m.at(0, 1), m.at(0, 2), m.at(0, 3), m.at(1,0), m.at(1, 1), m.at(1, 2), m.at(1, 3), m.at(2,0), m.at(2, 1), m.at(2, 2), m.at(2, 3), m.at(3,0), m.at(3, 1), m.at(3, 2), m.at(3, 3)) def _setUniformValueDirect(self, uniform, value): if type(value) is Vector: self._shader_program.setUniformValue(uniform, QVector3D(value.x, value.y, value.z)) elif type(value) is Matrix: self._shader_program.setUniformValue(uniform, self._matrixToQMatrix4x4(value)) elif type(value) is Color: self._shader_program.setUniformValue(uniform, QColor(value.r * 255, value.g * 255, value.b * 255, value.a * 255)) elif type(value) is list and len(value) is 2: self._shader_program.setUniformValue(uniform, QVector2D(value[0], value[1])) elif type(value) is list and len(value) is 3: self._shader_program.setUniformValue(uniform, QVector3D(value[0], value[1], value[2])) elif type(value) is list and len(value) is 4: self._shader_program.setUniformValue(uniform, QVector4D(value[0], value[1], value[2], value[3])) else: self._shader_program.setUniformValue(uniform, value)
class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, processor, df, parent=None): super().__init__(parent) self.parent = parent self.processor = processor # Data self.df = df # UI self.setupUi(self) self.setupControls() self.keyPressEvent = self.keyPressed self.mouseMoveEvent = self.mouseMoved # Control & Display self.mouse_grabbed = False self.camera_pos = QVector3D(0.5, 0.5, -2) # Start camera position self.center = QVector3D(0.5, 0, 0.5) # Center of object self.rot_center = QVector3D(0.5, 0.5, 0.5) # Center of rotation self.camera_rot = QVector3D(0, 0, 1) # Camera rotation self.scale_vec = QVector3D(1, 1, 1) # Object scale self.real_prop = processor.get_real_scaling() # val to lat self.light_pos = QVector3D(self.xLightSpinBox.value(), self.yLightSpinBox.value(), self.zLightSpinBox.value()) self.ambient = self.ambientSlider.value() / 100 self.diffuse = self.diffuseSlider.value() / 100 self.alpha = self.alphaSlider.value() / 100 # Transparency # Drawing self.normals = [] self.colors = [] self.coords_array = [] # !> len(self.normals) == len(self.colors) == len(self.coords_array) self.update_light = False # Update for light is needed self.update_buffer = False # Update for whole buffer is needed self.show_grid = self.gridCheckBox.isChecked() self.show_contour = self.contourCheckBox.isChecked() self.contour_levels = self.contourLevelSpinBox.value() self.show_light_lines = True self.grid_freq = 10 self.grid_color = QVector4D(1, 1, 1, 1) self.contour_color = QVector4D(1, 1, 1, 1) self.light_line_color = QVector4D(1, 0.6, 0, 1) self.prepareScene() self.updateUi() self.shaders = QOpenGLShaderProgram() self.openGLWidget.initializeGL = self.initializeGL self.openGLWidget.paintGL = self.paintGL def updateUi(self): """Set up custom widgets & positions""" self.splitDockWidget(self.displayDockWidget, self.elevationDockWidget, Qt.Vertical) self.splitDockWidget(self.elevationDockWidget, self.displayDockWidget, Qt.Vertical) self.tabifyDockWidget(self.elevationDockWidget, self.minimapDockWidget) self.tabifyDockWidget(self.displayDockWidget, self.lightDockWidget) self.tabifyDockWidget(self.projDockWidget, self.additionalDockWidget) self.tabifyDockWidget(self.elevationDockWidget, self.cameraDockWidget) self.lightDockWidget.raise_() self.additionalDockWidget.raise_() self.elevationDockWidget.raise_() self.elevationWidget = ElevationGraphWidget( self.processor.min_val, self.processor.max_val, self.processor.denormalizeValue(self.camera_pos.y()), width=240, height=100) self.minimapWidget = MinimapGraphWidget(self.processor, self.camera_pos, self.camera_rot, width=240, height=100) self.elevationWidgetLayout.addWidget(self.elevationWidget) self.minimapLayout.addWidget(self.minimapWidget) self.mapDockWidgetControls() self.actionOpenAnother.triggered.connect(self.onOpenAnother) def onOpenAnother(self): """Open another GeoTIFF file""" self.parent.show() self.hide() self.deleteLater() def mapDockWidgetControls(self): """Show/hide dockwidgets via corresponding actions""" self.dock_widgets = [ self.lightDockWidget, self.cameraDockWidget, self.additionalDockWidget, self.minimapDockWidget, self.displayDockWidget, self.projDockWidget, self.elevationDockWidget ] self.dock_actions = [ self.actionShowLightSourceDW, self.actionShowCameraDW, self.actionShowAdditionalDW, self.actionShowMinimapDW, self.actionShowDisplayDW, self.actionShowProjectionDW, self.actionShowElevationDW ] for dock_widget, action in zip(self.dock_widgets, self.dock_actions): def wrapper(action): def dock_widget_close_event(event): action.setChecked(False) event.accept() return dock_widget_close_event dock_widget.closeEvent = wrapper(action) action.triggered.connect(dock_widget.setVisible) # ==================== PREPARATION ==================== def prepareScene(self): """Prepare the data for bufferization""" self.coords_array = [] self.colors = [] self.normals = [] polygons, normals, colors = self.getMapPolygons() self.map_data = self.preparePolygons(polygons, normals, colors) # self.normal_data = self.prepareNormalLines(polygons, normals, colors) polygons, normals, colors = self.getLightSourceCoords() self.light_data = self.preparePolygons(polygons, normals, colors) if self.show_light_lines: lines, line_colors = self.getLightLines() self.light_lines_data = self.prepareLines(lines, line_colors) if self.show_grid: lines, line_colors = self.getGrid() self.grid_data = self.prepareLines(lines, line_colors) if self.show_contour: self.contour_data = self.getContour() # POLYGONS def getLightSourceCoords(self): polygons = np.array([((0, 0, 0), (0, 1, 0), (1, 1, 0), (1, 0, 0)), ((0, 0, 1), (0, 1, 1), (1, 1, 1), (1, 0, 1)), ((0, 0, 0), (0, 0, 1), (1, 0, 1), (1, 0, 0)), ((0, 1, 0), (0, 1, 1), (1, 1, 1), (1, 1, 0)), ((0, 0, 0), (0, 0, 1), (0, 1, 1), (0, 1, 0)), ((1, 0, 0), (1, 0, 1), (1, 1, 1), (1, 1, 0))]) normals = [(0, 0, -1), (0, 0, 1), (0, -1, 0), (0, 1, 0), (-1, 0, 0), (1, 0, 0)] normals_vec = [] [[ normals_vec.append(QVector3D(*normals[i])) for _ in range(len(polygons[i])) ] for i in range(len(polygons))] center = np.array( (self.light_pos.x(), self.light_pos.y(), self.light_pos.z())) delta = np.array((0.5, 0.5, 0.5)) polygons = [[(p - delta) * 0.05 + center for p in side] for side in polygons] colors = [] [ colors.append(QVector4D(1, 153 / 255, 0, 1) * self.diffuse) for _ in range(len(normals_vec)) ] return polygons, normals_vec, colors def getMapPolygons(self): polygons, normals, colors = [], [], [] for polygon, normal in self.processor.polygon_generator(self.df): polygons.append(self.swapPoints(polygon)) [ normals.append(QVector3D(*self.swapPoint(*normal))) for _ in polygon ] [colors.append(self.getColorByValue(val)) for x, y, val in polygon] return polygons, normals, colors def getColorByValue(self, value): """Get QVector4D-color from green (value == 0) to red (value == 1) :param value: 0 - 1 """ hue = 120 * (1 - value) / 360 color = QColor.fromHslF(hue, 1, 0.5) color_vec = QVector4D(color.redF(), color.greenF(), color.blueF(), 0.5) return color_vec def swapPoint(self, lon, lat, value): return lon, value, lat def swapPoints(self, polygon): return [(lon, value, lat) for lon, lat, value in polygon] def prepareNormalLines(self, polygons, normals, colors): """Normal lines for each polygon. Debug only """ norm_i = 0 start = len(self.coords_array) for polygon in polygons: point = polygon[0] normal = normals[norm_i] # color = colors[norm_i] color = QVector4D(1, 1, 1, 1) point_2 = QVector3D(*point) + normal * 0.04 point_2 = (point_2.x(), point_2.y(), point_2.z()) self.prepareLine((point, point_2), [color] * 2) norm_i += len(polygon) end = len(self.coords_array) return start, end def preparePolygons(self, polygons, normals, colors, start_index=None): """Prepare polygons for bufferization :param polygons: a list like [(p11, p12, ...), (p21, p22, ...)] :param normals: normals with number of normals equal to points :param colors: colors for each point :param start_index: if None, start at the end of each array. Otherwise, overwrite """ assert len(normals) == len(colors) coords_array = [] [[coords_array.append(list(p)) for p in polygon] for polygon in polygons] start = len(self.coords_array) if start_index is None: self.coords_array += coords_array self.normals += normals self.colors += colors else: for i, j in enumerate( range(start_index, start_index + len(coords_array))): self.coords_array[j] = coords_array[i] self.normals[j] = normals[i] self.colors[j] = colors[i] end = len(self.coords_array) return start, end # LINES def getGrid(self): assert self.processor.min_lat != self.processor.max_lat \ and self.processor.min_val != self.processor.max_val value = self.processor.min_val - \ (self.processor.max_val - self.processor.min_val) * 0.1 lines = [] for lat in np.linspace(self.processor.min_lat, self.processor.max_lat, self.grid_freq): line = ((self.processor.min_lon, lat, value), (self.processor.max_lon, lat, value)) lines.append(line) for lon in np.linspace(self.processor.min_lon, self.processor.max_lon, self.grid_freq): line = ((lon, self.processor.min_lat, value), (lon, self.processor.max_lat, value)) lines.append(line) # lines.append(((self.min_lon, self.min_lat, self.min_val), # (self.min_lon, self.min_lat, self.max_val))) lines = [ self.swapPoints(self.processor.normalizePoints(line)) for line in lines ] line_colors = [(self.grid_color, self.grid_color) for _ in lines] return lines, line_colors def getContour(self): lev_lines = self.processor.get_contour(levels=self.contour_levels) contour = [] for level, line in lev_lines: line = [(self.processor.normalizeLon(lon), self.processor.normalizeValue(level + 10), self.processor.normalizeLat(lat)) for lon, lat in line] colors = [self.contour_color] * len(line) contour.append(self.prepareLine(line, colors)) return contour def getLightLines(self): if self.processor.max_val == self.processor.min_val: v = 0 else: v = self.processor.normalizeValue( self.processor.min_val - (self.processor.max_val - self.processor.min_val) * 0.1) lines = (((self.light_pos.x(), v, -100), (self.light_pos.x(), v, 100)), ((-100, v, self.light_pos.z()), (100, v, self.light_pos.z())), ((self.light_pos.x(), v, self.light_pos.z()), (self.light_pos.x(), self.light_pos.y(), self.light_pos.z()))) line_colors = [(self.light_line_color, self.light_line_color) for _ in lines] return lines, line_colors def prepareLines(self, lines, line_colors, start_index=None): """Prepare lines for bufferization :param lines: list like one for polygons :param line_colors: list of colors of each line :param start_index: start index """ assert len(lines) == len(line_colors) if start_index is None: data = [None] * len(lines) else: data = [] sum_len = 0 for line in lines: data.append(start_index + sum_len) sum_len += len(line) result = [ self.prepareLine(line, colors, datum) for line, colors, datum in zip(lines, line_colors, data) ] return result[0][0], result[-1][1] def prepareLine(self, line, colors, start_index=None): assert len(line) == len(colors) if start_index is None: start = len(self.coords_array) self.coords_array += line self.colors += colors self.normals += [QVector3D(0, 1, 0)] * len(line) end = len(self.coords_array) else: start = start_index for i, j in enumerate(range(start_index, start_index + len(line))): self.coords_array[j] = line[i] self.colors[j] = colors[i] end = start_index + len(line) return start, end # ==================== SCENE PREPARATION ==================== def initializeGL(self): GL.glClearColor(0.1, 0.1, 0.1, 1.0) GL.glEnableClientState(GL.GL_VERTEX_ARRAY) self.setUpShaders() self.initVertexArrays() def setUpShaders(self): self.shaders.addShaderFromSourceFile( QOpenGLShader.Vertex, resource_path('shaders/shader.vert')) self.shaders.addShaderFromSourceFile( QOpenGLShader.Fragment, resource_path('shaders/shader.frag')) self.shaders.link() self.shaders.bind() def initVertexArrays(self): """Init buffers""" assert len(self.coords_array) == len(self.colors) == len(self.normals) GL.glVertexPointer(3, GL.GL_FLOAT, 0, self.coords_array) self.shaders.setAttributeArray("v_color", self.colors) self.shaders.enableAttributeArray("v_color") self.shaders.setAttributeArray("v_normal", self.normals) self.shaders.enableAttributeArray("v_normal") # ==================== UPDATING STUFF ==================== def updateGL(func): def wrapper(self, *args, **kwargs): res = func(self, *args, **kwargs) self.openGLWidget.update() return res return wrapper def updateCameraInfo(func): """A decorator to update camera widgets after excution """ def wrapper(self, *args, **kwargs): res = func(self, *args, **kwargs) coef = 1 if not self.realPropCheckBox.isChecked() \ else self.real_prop self.elevationWidget.updatePos( self.processor.denormalizeValue(self.camera_pos.y() / (self.scale_vec.y()) * coef)) self.minimapWidget.updateCameraInfo( self.camera_pos * self.scale_vec, self.camera_rot) return res return wrapper def updateLightData(self): """Update parts of buffer used to display the light source""" polygons, normals, colors = self.getLightSourceCoords() self.preparePolygons(polygons, normals, colors, self.light_data[0]) lines, colors = self.getLightLines() self.prepareLines(lines, colors, self.light_lines_data[0]) GL.glVertexPointer(3, GL.GL_FLOAT, 0, self.coords_array) self.update_light = False def updateBuffer(self): """Update the whole buffer""" self.prepareScene() self.initVertexArrays() self.update_buffer = False # ==================== ACTUAL DRAWING ==================== def paintGL(self): self.loadScene() if self.update_light: self.updateLightData() if self.update_buffer: self.updateBuffer() self.updateMatrices() self.updateParams() self.drawScene() def loadScene(self): width, height = self.openGLWidget.width(), self.openGLWidget.height() view = max(width, height) GL.glViewport(int((width - view) / 2), int((height - view) / 2), view, view) GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL) GL.glEnable(GL.GL_BLEND) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) GL.glEnable(GL.GL_DEPTH_TEST) GL.glDepthFunc(GL.GL_LEQUAL) def updateMatrices(self): """Update projection matrices""" proj = QMatrix4x4() coef = 0.01 center_x = 0 center_y = 0 projection = (-1 * coef + center_x, 1 * coef + center_x, -1 * coef + center_y, 1 * coef + center_y, 2.8 * coef, 20) if self.perspectiveRadioButton.isChecked(): proj.frustum(*projection) else: proj.ortho(*projection) modelview = QMatrix4x4() modelview.lookAt(self.camera_pos, self.camera_pos + self.camera_rot, QVector3D(0, 1, 0)) self.shaders.setUniformValue("ModelViewMatrix", modelview) self.shaders.setUniformValue("MVP", proj * modelview) def updateParams(self): """Update light, alpha and scaling parameters""" self.shaders.setUniformValue("LightPos", self.light_pos) self.shaders.setUniformValue("ambientStrength", self.ambient) self.shaders.setUniformValue("diffuseStrength", self.diffuse) self.shaders.setUniformValue("alpha", self.alpha) self.shaders.setUniformValue("center", self.center) self.shaders.setUniformValue("scale", self.scale_vec) def drawScene(self): """Paint all the prepared data""" GL.glClear(GL.GL_COLOR_BUFFER_BIT) self.shaders.setUniformValue('scaleEnabled', False) self.shaders.setUniformValue('phongModel', False) self.drawPreparedPolygons(*self.light_data) if self.show_light_lines: self.drawPreparedLines(*self.light_lines_data) self.shaders.setUniformValue('scaleEnabled', True) if self.show_grid: self.drawPreparedLines(*self.grid_data) # self.drawPreparedLines(*self.normal_data) self.shaders.setUniformValue('phongModel', True) self.drawPreparedPolygons(*self.map_data) if self.show_contour: self.shaders.setUniformValue('phongModel', False) self.drawPreparedLineStrips(self.contour_data) def drawPreparedPolygons(self, start, end): for i in range(start, end, 4): GL.glDrawArrays(GL.GL_POLYGON, i, 4) def drawPreparedLines(self, start, end): GL.glDrawArrays(GL.GL_LINES, start, end - start) def drawPreparedLineStrips(self, arr): for start, end in arr: GL.glDrawArrays(GL.GL_LINE_STRIP, start, end - start) # ==================== CONTROLS ==================== def setupControls(self): """Connect controls to this class' methods""" # Camera self.moveCameraUp.clicked.connect(lambda: self.moveCamera(az=1)) self.moveCameraDown.clicked.connect(lambda: self.moveCamera(az=-1)) self.moveCameraLeft.clicked.connect(lambda: self.moveCamera(pol=1)) self.moveCameraRight.clicked.connect(lambda: self.moveCamera(pol=-1)) self.moveCameraForward.clicked.connect(lambda: self.moveCamera(z=-1)) self.moveCameraBackward.clicked.connect(lambda: self.moveCamera(z=1)) # Scaling self.xScaleSpinBox.valueChanged.connect(lambda x: self.scaleView(x=x)) self.yScaleSpinBox.valueChanged.connect(lambda y: self.scaleView(y=y)) self.zScaleSpinBox.valueChanged.connect(lambda z: self.scaleView(z=z)) self.realPropCheckBox.stateChanged.connect( lambda: self.scaleView(y=self.yScaleSpinBox.value())) # Light self.ambientSlider.valueChanged.connect( lambda ambient: self.setLight(ambient=ambient / 100)) self.diffuseSlider.valueChanged.connect( lambda diffuse: self.setLight(diffuse=diffuse / 100)) self.xLightSpinBox.valueChanged.connect(lambda x: self.setLight(x=x)) self.yLightSpinBox.valueChanged.connect(lambda y: self.setLight(y=y)) self.zLightSpinBox.valueChanged.connect(lambda z: self.setLight(z=z)) # Display self.gridCheckBox.toggled.connect(lambda g: self.setGrid(show=g)) self.contourCheckBox.toggled.connect(lambda c: self.setContour(show=c)) self.contourLevelSpinBox.valueChanged.connect( lambda l: self.setContour(levels=l)) # Misc self.alphaSlider.valueChanged.connect( lambda alpha: self.setDisplay(alpha / 100)) self.actionGrabKeyboard.toggled.connect(self.toggleGrabKeyboard) self.actionGrabMouse.toggled.connect(self.toggleGrabMouse) self.orhogonalRadioButton.clicked.connect(self.openGLWidget.update) self.perspectiveRadioButton.clicked.connect(self.openGLWidget.update) self.openGLWidget.mousePressEvent \ = lambda event: self.actionGrabMouse.setChecked(True) def keyPressed(self, event): key = event.key() camera_dict = { Qt.Key_W: { 'z': 1 }, Qt.Key_S: { 'z': -1 }, Qt.Key_A: { 'x': -1 }, Qt.Key_D: { 'x': 1 }, Qt.Key_Z: { 'y': 1 }, Qt.Key_X: { 'y': -1 }, Qt.Key_Up: { 'az': 1 }, Qt.Key_Down: { 'az': -1 }, Qt.Key_Left: { 'pol': 1 }, Qt.Key_Right: { 'pol': -1 } } self.moveCamera(**camera_dict.get(key, {})) if key == Qt.Key_Escape: self.actionGrabMouse.setChecked(False) self.actionGrabKeyboard.setChecked(False) def mouseMoved(self, event): az_sensivity = 0.03 pol_sensivity = 0.03 if self.mouse_grabbed: delta = event.globalPos() - self.mouse_center QCursor.setPos(self.mouse_center) if event.buttons() == Qt.RightButton: self.moveCameraAroundCenter(az=delta.y() * az_sensivity, pol=delta.x() * pol_sensivity) else: self.moveCamera(az=delta.y() * az_sensivity, pol=delta.x() * pol_sensivity) else: super().mouseMoveEvent(event) def getRotVec(self): rot_matr = QMatrix4x4() rot_matr.rotate(-90, 0, 1, 0) rot_vec = QVector3D(self.camera_rot) rot_vec.setY(0) rot_vec = rot_matr * rot_vec return rot_vec @updateGL @updateCameraInfo def moveCamera(self, az=0, pol=0, x=0, y=0, z=0): move_coef = 0.1 rot_coef = 2 rot_vec = self.getRotVec() if az != 0 or pol != 0: rot_matr = QMatrix4x4() rot_matr.rotate(rot_coef * az, rot_vec) rot_matr.rotate(rot_coef * pol, 0, 1, 0) self.camera_rot = rot_matr * self.camera_rot if z: self.camera_pos += move_coef * self.camera_rot * z if x: self.camera_pos += rot_vec * move_coef * x if y: self.camera_pos.setY(self.camera_pos.y() + y * move_coef) @updateGL @updateCameraInfo def moveCameraAroundCenter(self, az=0, pol=0): rot_coef = 4 rot_vec = self.getRotVec() rot_matr = QMatrix4x4() rot_matr.rotate(rot_coef * az, rot_vec) rot_matr.rotate(rot_coef * pol, 0, 1, 0) rot_center = self.rot_center * self.scale_vec self.camera_pos -= rot_center self.camera_pos = rot_matr * self.camera_pos self.camera_pos += rot_center self.camera_rot = -self.camera_pos + rot_center @updateGL @updateCameraInfo def scaleView(self, x=None, y=None, z=None): if x: self.scale_vec.setX(x) if y: if self.realPropCheckBox.isChecked(): self.scale_vec.setY(y * self.real_prop) else: self.scale_vec.setY(y) if z: self.scale_vec.setZ(z) @updateGL def setLight(self, x=None, y=None, z=None, ambient=None, diffuse=None): if x: self.light_pos.setX(x) if y: self.light_pos.setY(y) if z: self.light_pos.setZ(z) if ambient: self.ambient = ambient if diffuse: self.diffuse = diffuse self.update_light = True @updateGL def setDisplay(self, alpha=None, invisible=None): if invisible: self.invisible = invisible if alpha: self.alpha = alpha @updateGL def setGrid(self, show): self.show_grid = show self.update_buffer = True @updateGL def setContour(self, show=None, levels=None): if show is not None: self.show_contour = show self.update_buffer = True if levels is not None: self.contour_levels = levels if self.show_contour: self.update_buffer = True def toggleGrabKeyboard(self, grab: bool): if grab: self.grabKeyboard() else: self.releaseKeyboard() def toggleGrabMouse(self, grab: bool): self.actionGrabKeyboard.setChecked(grab) self.mouse_grabbed = grab if grab: self.setCursor(Qt.BlankCursor) self.mouse_center = self.getMouseCenter() QCursor.setPos(self.mouse_center) self.setMouseTracking(True) self.grabMouse() else: self.setCursor(Qt.ArrowCursor) self.setMouseTracking(False) self.releaseMouse() def getMouseCenter(self): w, h = self.openGLWidget.width(), self.openGLWidget.height() local_center = QPoint(w / 2, h / 2) global_center = self.mapToGlobal(self.openGLWidget.pos()) \ + local_center return global_center
class TriangleUnderlayRenderer(QObject): def __init__(self, parent=None): super(TriangleUnderlayRenderer, self).__init__(parent) self._shader_program = None self._viewport_size = QSize() self._window = None self._camera = Camera() self._perspective_projection_matrix = perspective_projection( 45.0, 4.0 / 3.0, 0.001, 100.0) self._orthographic_projection_matrix = orthographic_projection( 640.0, 480.0, 0.001, 100.0) self._model_matrix = np.identity(4) self._projection_type = 0 self._projection_matrix = self._perspective_projection_matrix self._theta = 0.0 def set_theta(self, theta): self._theta = theta # around y axis def build_rotation_matrix(self): m = np.identity(4) m[0][0] = np.cos(np.radians(self._theta)) m[0][2] = np.sin(np.radians(self._theta)) m[2][0] = -np.sin(np.radians(self._theta)) m[2][2] = np.cos(np.radians(self._theta)) return m @pyqtSlot(int) def setProjectionType(self, t): if t != self._projection_type: self._projection_type = t @pyqtSlot() def paint(self): # for Darwin, it's a must if pf.uname().system == 'Darwin': global GL GL = self._window.openglContext().versionFunctions() w = self._viewport_size.width() h = self._viewport_size.height() GL.glViewport(0, 0, int(w), int(h)) if self._shader_program is None: self._shader_program = QOpenGLShaderProgram() self._shader_program.addShaderFromSourceFile( QOpenGLShader.Vertex, 'shaders/OpenGL_2_1/vertex.glsl') self._shader_program.addShaderFromSourceFile( QOpenGLShader.Fragment, 'shaders/OpenGL_2_1/fragment.glsl') self._shader_program.bindAttributeLocation('position', 0) self._shader_program.bindAttributeLocation('color', 1) self._shader_program.link() self._shader_program.bind() self._shader_program.enableAttributeArray(0) self._shader_program.enableAttributeArray(1) self._shader_program.setAttributeArray(0, positions) self._shader_program.setAttributeArray(1, colors) if self._projection_type == 0: self._projection_matrix = self._perspective_projection_matrix elif self._projection_type == 1: self._projection_matrix = self._orthographic_projection_matrix self._model_matrix = self.build_rotation_matrix() self._shader_program.setUniformValue( 'model_matrix', QMatrix4x4(self._model_matrix.flatten().tolist())) self._shader_program.setUniformValue( 'view_matrix', QMatrix4x4(self._camera.get_view_matrix().flatten().tolist())) self._shader_program.setUniformValue( 'projection_matrix', QMatrix4x4(self._projection_matrix.flatten().tolist())) GL.glClearColor(0.2, 0.2, 0.2, 1) GL.glEnable(GL.GL_DEPTH_TEST) GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3) self._shader_program.disableAttributeArray(0) self._shader_program.disableAttributeArray(1) self._shader_program.release() # Restore the OpenGL state for QtQuick rendering self._window.resetOpenGLState() self._window.update() def set_viewport_size(self, size): self._viewport_size = size def set_window(self, window): self._window = window def set_projection_matrix(self): # Need to be set every time we change the size of the window self._perspective_projection_matrix = perspective_projection( 45.0, self._viewport_size.width() / self._viewport_size.height(), 0.001, 100.0) self._orthographic_projection_matrix = orthographic_projection( self._viewport_size.width(), self._viewport_size.height(), 0.001, 100.0)
class ModelUnderlayRenderer(QObject): def __init__(self, parent=None): super(ModelUnderlayRenderer, self).__init__(parent) self._cube_shader = None self._sphere_shader = None self._viewport_size = QSize() self._window = None self._camera = Camera() self._perspective_projection_matrix = None self._orthographic_projection_matrix = None self._model_matrix = np.identity(4) self._projection_type = 0 self._projection_matrix = perspective_projection( 45.0, 640.0 / 480.0, 0.001, 1000.0) self._index_buffer = -1 # keep track of the objects in the scene self._cube_model = Cube() self._sphere_model = Sphere() self._models = dict() self._models[self._cube_model] = [] self._models[self._sphere_model] = [] @pyqtSlot() def paint(self): # for Darwin, it's a must if pf.uname().system == 'Darwin': global GL GL = self._window.openglContext().versionFunctions() w = self._viewport_size.width() h = self._viewport_size.height() GL.glViewport(0, 0, int(w), int(h)) GL.glClearColor(0.1, 0.1, 0.1, 1) GL.glEnable(GL.GL_DEPTH_TEST) GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glClear(GL.GL_DEPTH_BUFFER_BIT) # # vertices_block = np.vstack((self._cube_model.vertices, self._sphere_model.vertices)) # colors_block = np.vstack((self._cube_model.colors, self._sphere_model)) # # if len(self._objects) > 1: # for v in self._vertices[1:]: # vertices_block = np.vstack((vertices_block, v)) # for idx, c in enumerate(self._colors[1:]): # if not c: # c = [[0.6, 0.6, 0.7] for i in range(len(self._vertices[idx]))] # colors_block = np.vstack((colors_block, c)) # for i in self._indices[1:]: # indices_block = np.hstack((indices_block, i)) view_matrix = np.identity(4) view_matrix[2][3] = -30 if self._cube_shader is None: self._cube_shader = QOpenGLShaderProgram() self._cube_shader.addShaderFromSourceFile( QOpenGLShader.Vertex, 'shaders/OpenGL_2_1/vertex.glsl') self._cube_shader.addShaderFromSourceFile( QOpenGLShader.Fragment, 'shaders/OpenGL_2_1/fragment.glsl') self._cube_shader.bindAttributeLocation('position', 0) self._cube_shader.bindAttributeLocation('color', 1) self._cube_shader.link() self._cube_shader.bind() self._cube_shader.enableAttributeArray(0) self._cube_shader.enableAttributeArray(1) self._cube_shader.setAttributeArray(0, self._cube_model.vertices.tolist()) self._cube_shader.setAttributeArray(1, self._cube_model.colors.tolist()) # view_matrix = self._camera.get_view_matrix() self._cube_shader.setUniformValue( 'view_matrix', QMatrix4x4(view_matrix.flatten().tolist()).transposed()) self._cube_shader.setUniformValue( 'projection_matrix', QMatrix4x4( self._projection_matrix.flatten().tolist()).transposed()) if self._cube_model in self._models.keys(): for entity in self._models[self._cube_model]: m = create_transformation_matrix(entity.position, entity.rotation, entity.scale) self._cube_shader.setUniformValue( 'model_matrix', QMatrix4x4(m.flatten().tolist())) GL.glDrawElements(GL.GL_TRIANGLES, len(self._cube_model.indices), GL.GL_UNSIGNED_INT, self._cube_model.indices.tolist()) self._cube_shader.disableAttributeArray(0) self._cube_shader.disableAttributeArray(1) self._cube_shader.release() if self._sphere_shader is None: self._sphere_shader = QOpenGLShaderProgram() self._sphere_shader.addShaderFromSourceFile( QOpenGLShader.Vertex, 'shaders/OpenGL_2_1/vertex.glsl') self._sphere_shader.addShaderFromSourceFile( QOpenGLShader.Fragment, 'shaders/OpenGL_2_1/fragment.glsl') self._sphere_shader.bindAttributeLocation('position', 0) self._sphere_shader.bindAttributeLocation('color', 1) self._sphere_shader.link() self._sphere_shader.bind() self._sphere_shader.enableAttributeArray(0) self._sphere_shader.enableAttributeArray(1) self._sphere_shader.setAttributeArray( 0, self._sphere_model.vertices.tolist()) self._sphere_shader.setAttributeArray( 1, self._sphere_model.colors.tolist()) self._sphere_shader.setUniformValue( 'view_matrix', QMatrix4x4(view_matrix.flatten().tolist()).transposed()) self._sphere_shader.setUniformValue( 'projection_matrix', QMatrix4x4( self._projection_matrix.flatten().tolist()).transposed()) if self._sphere_model in self._models.keys(): for entity in self._models[self._sphere_model]: m = create_transformation_matrix(entity.position, entity.rotation, entity.scale) self._cube_shader.setUniformValue( 'model_matrix', QMatrix4x4(m.flatten().tolist())) GL.glDrawElements(GL.GL_TRIANGLES, len(self._sphere_model.indices), GL.GL_UNSIGNED_INT, self._sphere_model.indices.tolist()) self._sphere_shader.disableAttributeArray(0) self._sphere_shader.disableAttributeArray(1) self._sphere_shader.release() # def build_rotation_matrix (t): # m = np.identity(4) # m[0][0] = np.cos(np.radians(t)) # m[0][2] = np.sin(np.radians(t)) # m[2][0] = -np.sin(np.radians(t)) # m[2][2] = np.cos(np.radians(t)) # return m # # global theta # theta += 1 # self._model_matrix = build_rotation_matrix(theta) # self._model_matrix[2][3] = -3 # Restore the OpenGL state for QtQuick rendering self._window.resetOpenGLState() self._window.update() def set_viewport_size(self, size): self._viewport_size = size def set_window(self, window): self._window = window def set_projection_matrix(self): # Need to be set every time we change the size of the window self._projection_matrix = perspective_projection( 45.0, self._window.width() / self._window.height(), 0.001, 1000.0) def move_model(self, val): self._model_matrix[2][3] += val def move_camera(self): pass def add_geometry(self, geo_enum): if geo_enum == 0: self._models[self._cube_model].append( Entity( self._cube_model, np.array([ random.uniform(-3.0, 3.0), random.uniform(-3.0, 3.0), random.uniform(-20.0, -10.0) ]), np.array([ random.uniform(-45.0, 45.0), random.uniform(-45.0, 45.0), random.uniform(-45.0, 45.0) ]), np.array([1.0, 1.0, 1.0]))) elif geo_enum == 1: self._models[self._sphere_model].append( Entity( self._sphere_model, np.array([ random.uniform(-3.0, 3.0), random.uniform(-3.0, 3.0), random.uniform(-20.0, -10.0) ]), np.array([ random.uniform(-30.0, 30.0), random.uniform(-30.0, 30.0), random.uniform(-30.0, 30.0) ]), np.array([1.0, 1.0, 1.0]))) else: return def delete_geometry(self, geo_enum): if geo_enum == 0: if self._models[self._cube_model]: self._models[self._cube_model].pop() elif geo_enum == 1: if self._models[self._sphere_model]: self._models[self._sphere_model].pop() def change_random_cube_color(self): tmp = self._models[self._cube_model] self._models.pop(self._cube_model) self._cube_model = Cube() self._models[self._cube_model] = tmp def change_random_sphere_color(self): tmp = self._models[self._sphere_model] self._models.pop(self._sphere_model) self._sphere_model = Sphere() self._models[self._sphere_model] = tmp
class QtGL2Material(Material): def __init__(self, renderer): super().__init__() self._gl = renderer._gl self._shader_program = None self._uniform_indices = {} self._attribute_indices = {} self._uniform_values = {} self._bound = False self._textures = {} self._disable_textures = Application.getInstance( ).getCommandLineOption("disable-textures", False) def loadVertexShader(self, file): if not self._shader_program: self._shader_program = QOpenGLShaderProgram() self._shader_program.addShaderFromSourceFile(QOpenGLShader.Vertex, file) def loadFragmentShader(self, file): if not self._shader_program: self._shader_program = QOpenGLShaderProgram() self._shader_program.addShaderFromSourceFile(QOpenGLShader.Fragment, file) def build(self): if not self._shader_program: Logger.log("e", "No shader sources loaded") return self._shader_program.link() def setUniformValue(self, name, value, **kwargs): if not self._shader_program: return cache = True if "cache" in kwargs: cache = kwargs["cache"] if name not in self._uniform_indices: self._uniform_indices[name] = self._shader_program.uniformLocation( name) uniform = self._uniform_indices[name] if uniform == -1: return if cache: self._uniform_values[uniform] = value if self._bound: self._setUniformValueDirect(uniform, value) def setUniformTexture(self, name, file): if not self._shader_program or self._disable_textures: return if name not in self._uniform_indices: self._uniform_indices[name] = self._shader_program.uniformLocation( name) index = self._uniform_indices[name] texture = QOpenGLTexture(QImage(file).mirrored()) texture.setMinMagFilters(QOpenGLTexture.Linear, QOpenGLTexture.Linear) self._textures[index] = texture self._uniform_values[index] = 1 if self._bound: texture = self._textures[index] texture.bind() self._setUniformValueDirect(index, texture.textureId()) def enableAttribute(self, name, type, offset, stride=0): if not self._shader_program: return self.bind() if name not in self._attribute_indices: self._attribute_indices[ name] = self._shader_program.attributeLocation(name) attribute = self._attribute_indices[name] if attribute == -1: return if type is "int": self._shader_program.setAttributeBuffer(attribute, self._gl.GL_INT, offset, 1, stride) elif type is "float": self._shader_program.setAttributeBuffer(attribute, self._gl.GL_FLOAT, offset, 1, stride) elif type is "vector2f": self._shader_program.setAttributeBuffer(attribute, self._gl.GL_FLOAT, offset, 2, stride) elif type is "vector3f": self._shader_program.setAttributeBuffer(attribute, self._gl.GL_FLOAT, offset, 3, stride) elif type is "vector4f": self._shader_program.setAttributeBuffer(attribute, self._gl.GL_FLOAT, offset, 4, stride) self._shader_program.enableAttributeArray(attribute) def disableAttribute(self, name): if not self._shader_program: return if name not in self._attribute_indices: return self._shader_program.disableAttributeArray( self._attribute_indices[name]) def bind(self): if not self._shader_program or not self._shader_program.isLinked(): return if self._bound: return self._bound = True self._shader_program.bind() for uniform in self._uniform_values: if uniform in self._textures: texture = self._textures[uniform] texture.bind() self._setUniformValueDirect(uniform, 0) else: self._setUniformValueDirect(uniform, self._uniform_values[uniform]) def release(self): if not self._shader_program or not self._bound: return for texture in self._textures.values(): texture.release() self._bound = False self._shader_program.release() def _matrixToQMatrix4x4(self, m): return QMatrix4x4(m.at(0, 0), m.at(0, 1), m.at(0, 2), m.at(0, 3), m.at(1, 0), m.at(1, 1), m.at(1, 2), m.at(1, 3), m.at(2, 0), m.at(2, 1), m.at(2, 2), m.at(2, 3), m.at(3, 0), m.at(3, 1), m.at(3, 2), m.at(3, 3)) def _setUniformValueDirect(self, uniform, value): if type(value) is Vector: self._shader_program.setUniformValue( uniform, QVector3D(value.x, value.y, value.z)) elif type(value) is Matrix: self._shader_program.setUniformValue( uniform, self._matrixToQMatrix4x4(value)) elif type(value) is Color: self._shader_program.setUniformValue( uniform, QColor(value.r * 255, value.g * 255, value.b * 255, value.a * 255)) elif type(value) is list and len(value) is 2: self._shader_program.setUniformValue(uniform, QVector2D(value[0], value[1])) elif type(value) is list and len(value) is 3: self._shader_program.setUniformValue( uniform, QVector3D(value[0], value[1], value[2])) elif type(value) is list and len(value) is 4: self._shader_program.setUniformValue( uniform, QVector4D(value[0], value[1], value[2], value[3])) else: self._shader_program.setUniformValue(uniform, value)
class MyGLWindow(QGLWidget): def __init__(self, obj_num, camera_dist=60): super(MyGLWindow, self).__init__() self.obj_num = obj_num self.objs = [] for i in range(obj_num): self.objs.append(None) self.shaderProgram = None self.is_rotate = False self.is_pan = False self.pan_param = 0.1 self.rotate_param = 0.5 self.camera = MyCamera(camera_dist) def paintGL(self): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self.shaderProgram.bind() p_matrix = QMatrix4x4() p_matrix.perspective(60.0, 1.33, 0.1, 1000) self.shaderProgram.setUniformValue(self.p_matrix_id, p_matrix) self.shaderProgram.setUniformValue(self.main_light_dir, QVector4D(0, 1.0, -1.0, 0.0)) self.shaderProgram.setUniformValue(self.sub_light_dir, QVector4D(0, 1.0, 1.0, 0.0)) self.shaderProgram.setUniformValue(self.back_light_dir, QVector4D(0, -1.0, 0.0, 0.0)) self.shaderProgram.setUniformValue(self.ambient_id, QVector4D(0.15, 0.15, 0.15, 0.0)) self.shaderProgram.setUniformValue(self.diffuse_id, QVector4D(1.0, 1.0, 1.0, 1.0)) mv_matrix = self.camera.getMatrix() self.shaderProgram.setUniformValue(self.mv_matrix_id, mv_matrix) viewport_width = self.width() / self.obj_num for i in range(self.obj_num): glViewport(int(i * viewport_width), 0, int(viewport_width), self.height()) if self.objs[i] is not None: self.objs[i].render() self.shaderProgram.release() def initializeGL(self): glClearColor(0.95, 0.95, 0.95, 1.0) glClearDepth(1.0) glEnable(GL_DEPTH_TEST) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60.0, 1.33, 0.1, 1000) self.shaderProgram = QOpenGLShaderProgram() print("Initialize vertex shader: ", self.shaderProgram.addShaderFromSourceFile(QOpenGLShader.Vertex, "shader.vert")) print("Initialize fragment shader: ", self.shaderProgram.addShaderFromSourceFile(QOpenGLShader.Fragment, "shader.frag")) self.shaderProgram.link() self.p_matrix_id = self.shaderProgram.uniformLocation("um4p") self.mv_matrix_id = self.shaderProgram.uniformLocation("um4mv") self.main_light_dir = self.shaderProgram.uniformLocation("main_light_dir") self.sub_light_dir = self.shaderProgram.uniformLocation("sub_light_dir") self.back_light_dir = self.shaderProgram.uniformLocation("back_light_dir") self.ambient_id = self.shaderProgram.uniformLocation("ambient") self.diffuse_id = self.shaderProgram.uniformLocation("diffuse") self.pos_id = self.shaderProgram.attributeLocation("pos") self.normal_id = self.shaderProgram.attributeLocation("normal") def mousePressEvent(self, event): if event.button() == 2: self.is_rotate = True elif event.button() == 4: self.is_pan = True self.lastPos = event.pos() def mouseMoveEvent(self, event): dx = event.x() - self.lastPos.x() dy = event.y() - self.lastPos.y() if self.is_rotate: self.camera.rotate(dy * self.rotate_param, -dx * self.rotate_param) elif self.is_pan: self.camera.pan(dx * self.pan_param, dy * self.pan_param) self.lastPos = event.pos() self.repaint() def mouseReleaseEvent(self, event): self.is_rotate = False self.is_pan = False def setObj(self, idx, vertices, faces, normals=None, focus=False): self.shaderProgram.bind() if self.objs[idx] is None: self.objs[idx] = MyMeshObj(vertices, faces, normals) self.objs[idx].buildRenderingBuffer(self.pos_id, self.normal_id) else: self.objs[idx].updateMesh(vertices, faces) self.objs[idx].updateRenderingBuffer(self.pos_id, self.normal_id) self.shaderProgram.release() if focus: self.camera.focus(self.objs[idx])
class AkiraRenderWindow(OpenGLWindow): def __init__(self): super(AkiraRenderWindow, self).__init__() self.m_program = 0 self.m_frame = 0.0 self.m_vertex = 0 self.m_vertices = [] self.m_color = 0 self.m_colors = [] self.m_offset = 0 self.m_offsets = 0 self.m_vao = None def initialize(self): self.create_shader() self.create_vao() def create_shader(self): self.m_program = QOpenGLShaderProgram(self) self.m_program.addShaderFromSourceFile(QOpenGLShader.Vertex, "shaders/chapter2.vs.glsl") self.m_program.addShaderFromSourceFile(QOpenGLShader.Fragment, "shaders/chapter2.fs.glsl") self.m_program.link() self.m_vertex = self.m_program.attributeLocation("m_vertex") self.m_offset = self.m_program.attributeLocation("m_offset") self.m_color = self.m_program.attributeLocation("m_color") return self def create_vao(self): vertex_array_object = GL.glGenVertexArrays(1) GL.glBindVertexArray(vertex_array_object) vertex_buffer = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vertex_buffer) #using PyQt shader program instead GL.glEnableVertexAttribArray(self.m_vertex) GL.glEnableVertexAttribArray(self.m_color) self.m_vao = vertex_array_object return self def render(self): ratio = int(self.devicePixelRatio().real) GL.glViewport(0, 0, self.width()*ratio, self.height()*ratio) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) self.m_offsets = QVector4D(sin(self.m_frame/20)*0.5, cos(self.m_frame/20)*0.5, 0.0, 0.0) self.m_vertices = [(0.25, -0.25, 0, 1.0), (-0.25, -0.25, 0, 1.0), (0.25, 0.25, 0, 1.0)] self.m_colors = [(0.0, 0.0, 1.0, 1.0), (1.0, 0.0, 0.0, 1.0), (0.0, 1.0, 0.0, 1.0)] self.m_program.setAttributeValue(self.m_offset, self.m_offsets) self.m_program.setAttributeArray(self.m_vertex, self.m_vertices) self.m_program.setAttributeArray(self.m_color, self.m_colors) self.m_program.bind() GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3) self.m_program.release() self.m_frame += 1
class ShaderWindow(OpenGLWindow): def __init__(self): super(ShaderWindow, self).__init__() self.m_program = 0 self.m_vao = None self.m_model_matrix = QMatrix4x4() self.m_view_matrix = QMatrix4x4() self.m_projection_matrix = QMatrix4x4() @property def m_mvp_matrix(self): return self.m_projection_matrix * self.m_view_matrix * self.m_model_matrix def initialize_data(self): pass def initialize(self): self.initialize_data() self.create_shader() self.bind_attribute_localtion() self.create_vao() self.enableVAA() def bind_attribute_localtion(self): pass def create_shader(self): self.m_program = QOpenGLShaderProgram(self) for k, v in self.shader_files.items(): self.m_program.addShaderFromSourceFile(k, v) self.m_program.link() def create_vao(self): vertex_array_object = GL.glGenVertexArrays(1) GL.glBindVertexArray(vertex_array_object) vertex_buffer = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vertex_buffer) def enableVAA(self): pass def render(self): pass def keyPressEvent(self, event): key = event.key() if key == Qt.Key_Up: self.m_model_matrix.rotate(2.0, 1.0, 0.0, 0.0) elif key == Qt.Key_Down: self.m_model_matrix.rotate(-2.0, 1.0, 0.0, 0.0) elif key == Qt.Key_Left: self.m_model_matrix.rotate(2.0, 0.0, 1.0, 0.0) elif key == Qt.Key_Right: self.m_model_matrix.rotate(-2.0, 0.0, 1.0, 0.0) else: pass