def __init__(self, parent): super(DefaultEnvMap, self).__init__(parent) envmap_root = assetsUrl() + "/envmaps/pink_sunrise" envmap_name = "pink_sunrise" + ("_16f" if platform.system() == "Darwin" else "") self.tli = Qt3DRender.QTextureLoader(self) self.tli.setSource(envmap_root + "/" + envmap_name + "_irradiance.dds") self.tli.setMinificationFilter( Qt3DRender.QAbstractTexture.LinearMipMapLinear) self.tli.setMagnificationFilter(Qt3DRender.QAbstractTexture.Linear) self.tli.wrapMode().setX(Qt3DRender.QTextureWrapMode.ClampToEdge) self.tli.wrapMode().setY(Qt3DRender.QTextureWrapMode.ClampToEdge) self.tli.setGenerateMipMaps(0) self.setIrradiance(self.tli) self.tls = Qt3DRender.QTextureLoader(self) self.tls.setSource(envmap_root + "/" + envmap_name + "_specular.dds") self.tls.setMinificationFilter( Qt3DRender.QAbstractTexture.LinearMipMapLinear) self.tls.setMagnificationFilter(Qt3DRender.QAbstractTexture.Linear) self.tls.wrapMode().setX(Qt3DRender.QTextureWrapMode.ClampToEdge) self.tls.wrapMode().setY(Qt3DRender.QTextureWrapMode.ClampToEdge) self.tls.setGenerateMipMaps(0) self.setSpecular(self.tls)
def __init__(self, parent, size = QSize(500,500) ): super().__init__(parent) self.size = size self.output = Qt3DRender.QRenderTargetOutput( self ) self.output.setAttachmentPoint( Qt3DRender.QRenderTargetOutput.Color0 ) self.texture = Qt3DRender.QTexture2D(self.output) self.texture.setSize(size.width(), size.height()) self.texture.setFormat(Qt3DRender.QAbstractTexture.RGB8_UNorm) self.texture.setMinificationFilter(Qt3DRender.QAbstractTexture.Linear) self.texture.setMagnificationFilter(Qt3DRender.QAbstractTexture.Linear) self.output.setTexture(self.texture) self.addOutput(self.output) self.depthTexOutput = Qt3DRender.QRenderTargetOutput( self ) self.depthTexOutput.setAttachmentPoint( Qt3DRender.QRenderTargetOutput.Depth ) self.depthTex = Qt3DRender.QTexture2D(self.depthTexOutput ) self.depthTex.setSize( size.width(), size.height() ) self.depthTex.setFormat( Qt3DRender.QAbstractTexture.D32F ) self.depthTex.setMinificationFilter(Qt3DRender.QAbstractTexture.Linear) self.depthTex.setMagnificationFilter(Qt3DRender.QAbstractTexture.Linear) self.depthTex.setComparisonFunction(Qt3DRender.QAbstractTexture.CompareLessEqual) self.depthTex.setComparisonMode(Qt3DRender.QAbstractTexture.CompareRefToTexture) self.depthTexOutput.setTexture( self.depthTex) self.addOutput( self.depthTexOutput )
def create_layers(self): """ Assigns the gnomon view and component view to different cameras and viewports. Controls the buffer behaviour of the different viewports so that the depth buffer behaves in such a way that the gnomon is always in front. """ # Set up view surface selector for filtering surface_selector = Qt3DRender.QRenderSurfaceSelector(self.root_entity) surface_selector.setSurface(self.view) main_camera = self.view.camera() viewport = Qt3DRender.QViewport(surface_selector) self.view.setActiveFrameGraph(surface_selector) # Filters out just the instrument for the main camera to see component_clear_buffers = self.create_camera_filter( viewport, self.combined_component_axes_entity, main_camera) # Have the component buffer take on the default behaviour component_clear_buffers.setBuffers(Qt3DRender.QClearBuffers.AllBuffers) # Set the background color of the main scene component_clear_buffers.setClearColor(QColor("lightgrey")) # Create a viewport for gnomon in small section of the screen self.gnomon_viewport = Qt3DRender.QViewport(surface_selector) self.update_gnomon_size() # Filter out the gnomon for just the gnomon camera to see gnomon_camera = self.gnomon.get_gnomon_camera() gnomon_clear_buffers = self.create_camera_filter( self.gnomon_viewport, self.gnomon_root_entity, gnomon_camera) # Make the gnomon appear in front of everything else gnomon_clear_buffers.setBuffers(Qt3DRender.QClearBuffers.DepthBuffer) self.gnomon.update_gnomon()
def __init__(self, vertex_data: QtCore.QByteArray, parent=None): """ Geometry for depicting a line. Used for axes placed in the origin of the instrument view. :param vertex_data: A byte array containing the coordinates for the start and end points of the line. :param parent: The object parent. """ Qt3DRender.QGeometry.__init__(self, parent) # Create a position buffer and give it the vertex data self.position_buffer = Qt3DRender.QBuffer(self) self.position_buffer.setUsage(Qt3DRender.QBuffer.StaticDraw) self.position_buffer.setData(vertex_data) # Configure a position attribute and configure it to represent a set of coordinates self.position_attribute = Qt3DRender.QAttribute(self) self.position_attribute.setAttributeType( Qt3DRender.QAttribute.VertexAttribute) self.position_attribute.setVertexBaseType(Qt3DRender.QAttribute.Float) self.position_attribute.setVertexSize(3) self.position_attribute.setName( Qt3DRender.QAttribute.defaultPositionAttributeName()) self.position_attribute.setBuffer(self.position_buffer) # Set the number of points contained in the attribute # This must be two for the start and end of the line self.position_attribute.setCount(2) self.addAttribute(self.position_attribute)
def __init__(self, parent, bildfile, transform=None): super().__init__(parent) # Draw the arrow bodies as cylinders too cylinderlist = bildfile.cylinders + list( bildfile.cylindersFromArrows()) num_cylinders = len(cylinderlist) if num_cylinders == 0: return total_vertices = 2 * num_cylinders vertex_basetype = geom.basetypes.Float if (total_vertices < 30000): index_basetype = geom.basetypes.UnsignedShort else: index_basetype = geom.basetypes.UnsignedInt vertex_nparr = np.zeros( [total_vertices, 7], dtype=geom.basetype_numpy_codes[vertex_basetype]) for idx, (color, x1, y1, z1, x2, y2, z2, r) in enumerate(cylinderlist): if color is None: color = QColor('white') vertex_nparr[2 * idx, :] = x1, y1, z1, r, color.redF( ), color.greenF(), color.blueF() vertex_nparr[2 * idx + 1, :] = x2, y2, z2, r, color.redF( ), color.greenF(), color.blueF() if (transform): vertex_nparr[:, 0:3] = transform(vertex_nparr[:, 0:3]) # Transform radii by the equivalent scaling factor (assume it's equal in all dimensions) scale = transform(np.ones((1, 3)))[0, 0] vertex_nparr[:, 3] *= scale self.geometry = Qt3DRender.QGeometry(self) position_attrname = Qt3DRender.QAttribute.defaultPositionAttributeName( ) radius_attrname = 'radius' color_attrname = Qt3DRender.QAttribute.defaultColorAttributeName() attrspecs = [ geom.AttrSpec(position_attrname, column=0, numcols=3), geom.AttrSpec(radius_attrname, column=3, numcols=1), geom.AttrSpec(color_attrname, column=4, numcols=3) ] self.vtx_attrs = geom.buildVertexAttrs(self, vertex_nparr, attrspecs) for va in self.vtx_attrs: self.geometry.addAttribute(va) # Create qt3d index buffer index_nparr = np.arange( len(vertex_nparr), dtype=geom.basetype_numpy_codes[index_basetype]) self.indexAttr = geom.buildIndexAttr(self, index_nparr) self.geometry.addAttribute(self.indexAttr) self.renderer = Qt3DRender.QGeometryRenderer(parent) self.renderer.setGeometry(self.geometry) self.renderer.setPrimitiveType(Qt3DRender.QGeometryRenderer.Lines) self.addComponent(self.renderer)
def createScene(self): wd = os.path.dirname(os.path.abspath(__file__)) # Root entity self.rootEntity = Kuesa.SceneEntity() self.rootEntity.loadingDone.connect(self.onLoadingDone) self.gltfImporter = Kuesa.GLTF2Importer(self.rootEntity) self.gltfImporter.setSceneEntity(self.rootEntity) self.gltfImporter.setSource("file://" + wd + "/../assets/models/car/DodgeViper-draco.gltf") self.el = Qt3DRender.QEnvironmentLight(self.rootEntity) self.tli = Qt3DRender.QTextureLoader(self.rootEntity) self.tli.setSource("file://" + wd + "/../assets/envmaps/pink_sunrise/pink_sunrise" + ("_16f" if platform.system() == "Darwin" else "") + "_irradiance.dds") self.tli.setMinificationFilter(Qt3DRender.QAbstractTexture.LinearMipMapLinear) self.tli.setMagnificationFilter(Qt3DRender.QAbstractTexture.Linear) self.tli.wrapMode().setX(Qt3DRender.QTextureWrapMode.ClampToEdge) self.tli.wrapMode().setY(Qt3DRender.QTextureWrapMode.ClampToEdge) self.tli.setGenerateMipMaps(0) self.el.setIrradiance(self.tli) self.tls = Qt3DRender.QTextureLoader(self.rootEntity) self.tls.setSource("file://" + wd + "/../assets/envmaps/pink_sunrise/pink_sunrise" + ("_16f" if platform.system() == "Darwin" else "") + "_specular.dds") self.tls.setMinificationFilter(Qt3DRender.QAbstractTexture.LinearMipMapLinear) self.tls.setMagnificationFilter(Qt3DRender.QAbstractTexture.Linear) self.tls.wrapMode().setX(Qt3DRender.QTextureWrapMode.ClampToEdge) self.tls.wrapMode().setY(Qt3DRender.QTextureWrapMode.ClampToEdge) self.tls.setGenerateMipMaps(0) self.el.setSpecular(self.tls) self.rootEntity.addComponent(self.el)
def buildVertexAttrs(parent, array, attrspecs): # Measure the input array rows = len(array) columns = len(array[0]) basetype = basetype_numpy_codes_reverse[array.dtype.type] basetype_width = basetype_widths[basetype] row_width = columns * basetype_width #print(columns, rows, basetype, basetype_width, row_width) # Convert input to a qt buffer rawstring = array.tobytes() byte_array = QByteArray(rawstring) qbuffer = Qt3DRender.QBuffer(parent) qbuffer.setData(byte_array) attrs = list() for asp in attrspecs: attr = Qt3DRender.QAttribute(parent) attr.setName(asp.name) attr.setVertexBaseType(basetype) attr.setVertexSize(asp.numcols) attr.setAttributeType(Qt3DRender.QAttribute.VertexAttribute) attr.setBuffer(qbuffer) attr.setByteStride(row_width) attr.setByteOffset(asp.column * basetype_width) attr.setCount(rows) attrs.append(attr) return attrs
def set_texture(self, img_path: Path) -> None: # This is from https://stackoverflow.com/q/49887994/2826337 # and from https://forum.qt.io/topic/106370/qdiffusespecularmaterial-diffuse-texture/4 # noqa: E501 loader = Qt3DRender.QTextureLoader(self.entity) img_url = QUrl.fromLocalFile(str(img_path.resolve())) loader.setSource(img_url) self.material.setDiffuse(loader)
def createScene(self): self.rootEntity = Qt3DCore.QEntity() self.scannerEntity = Qt3DCore.QEntity(self.rootEntity) # QSceneLoader loads materials from scanner.mtl referenced in scanner.obj self.scanner = Qt3DRender.QSceneLoader(self.scannerEntity) self.scanner.setSource(QUrl.fromLocalFile("scanner.obj")) self.scannerEntity.addComponent(self.scanner) self.addTransform()
def buildIndexAttr(parent, array): basetype = basetype_numpy_codes_reverse[array.dtype.type] basetype_width = basetype_widths[basetype] basetype_width = array.itemsize rawstring = array.tobytes() byte_array = QByteArray(rawstring) qbuffer = Qt3DRender.QBuffer(parent) qbuffer.setData(byte_array) attr = Qt3DRender.QAttribute(parent) attr.setVertexBaseType(basetype) attr.setAttributeType(Qt3DRender.QAttribute.IndexAttribute) attr.setBuffer(qbuffer) attr.setCount(array.size) return attr
def create_camera_filter( viewport: Qt3DRender.QViewport, visible_entity: Qt3DCore.QEntity, camera_to_filter: Qt3DRender.QCamera, ) -> Qt3DRender.QClearBuffers: """ Filter the objects that are visible to a camera. :param viewport: The viewport that the camera is using. :param visible_entity: Only children of this entity will be visible to the camera. :param camera_to_filter: The camera to apply the filter to. :return: The clear buffers """ layer_filter = Qt3DRender.QLayerFilter(viewport) layer = Qt3DRender.QLayer(visible_entity) visible_entity.addComponent(layer) layer.setRecursive(True) layer_filter.addLayer(layer) camera_selector = Qt3DRender.QCameraSelector(layer_filter) camera_selector.setCamera(camera_to_filter) clear_buffers = Qt3DRender.QClearBuffers(camera_selector) return clear_buffers
def __init__(self, parent, vtx1, vtx2, color): super().__init__(parent) total_vertices = 2 vertex_basetype = geom.basetypes.Float index_basetype = geom.basetypes.UnsignedShort vertex_nparr = np.zeros( [total_vertices, 7], dtype=geom.basetype_numpy_codes[vertex_basetype]) vertex_nparr[0, :] = *vtx1[:], *color[:] vertex_nparr[1, :] = *vtx2[:], *color[:] self.geometry = Qt3DRender.QGeometry(self) position_attrname = Qt3DRender.QAttribute.defaultPositionAttributeName( ) color_attrname = Qt3DRender.QAttribute.defaultColorAttributeName() attrspecs = [ geom.AttrSpec(position_attrname, column=0, numcols=3), geom.AttrSpec(color_attrname, column=3, numcols=3) ] self.vtx_attrs = geom.buildVertexAttrs(self, vertex_nparr, attrspecs) for va in self.vtx_attrs: self.geometry.addAttribute(va) # Create qt3d index buffer index_nparr = np.arange( 2, dtype=geom.basetype_numpy_codes[index_basetype]) self.indexAttr = geom.buildIndexAttr(self, index_nparr) self.geometry.addAttribute(self.indexAttr) self.renderer = Qt3DRender.QGeometryRenderer(parent) self.renderer.setGeometry(self.geometry) self.renderer.setPrimitiveType(Qt3DRender.QGeometryRenderer.Lines) self.addComponent(self.renderer)
def _athenaMaterial( self, qmlfile, vert_shader, frag_shader, geom_shader=None ): material = self._qmlLoad( qmlfile ) shader_path = Path(ATHENA_SRC_DIR) / 'shaders' vert_shader = shader_path / vert_shader frag_shader = shader_path / frag_shader if( geom_shader ): geom_shader = shader_path / geom_shader def loadShader( s ): return Qt3DRender.QShaderProgram.loadSource( s.as_uri() ) shader = Qt3DRender.QShaderProgram(material) shader.setVertexShaderCode( loadShader( vert_shader ) ) if( geom_shader): shader.setGeometryShaderCode( loadShader( geom_shader ) ) shader.setFragmentShaderCode( loadShader( frag_shader ) ) for rpass in material.effect().techniques()[0].renderPasses(): rpass.setShaderProgram( shader ) return material
def importerLoaded(self, status): if status != Kuesa.GLTF2Importer.Status.Ready: return parent = self.rootEntity.entity("KuesaEntity_0") parent.setObjectName("KuesaEntity_0") orig_entity = self.rootEntity.entity("KuesaEntity_2").childNodes()[1] orig_geometry = orig_entity.childNodes()[0] orig_material = orig_entity.childNodes()[1] orig_entity.removeComponent(orig_material) new_material = Kuesa.UnlitMaterial(orig_material.parent()) # Materials need both an effect and material properties. # First create the Effect new_effect = Kuesa.UnlitEffect(new_material) new_effect.setBaseColorMapEnabled(False) new_effect.setUsingColorAttribute(True) new_effect.setDoubleSided(True) new_effect.setUseSkinning(False) new_effect.setOpaque(True) new_effect.setAlphaCutoffEnabled(True) new_material.setEffect(new_effect) # Then the properties new_props = Kuesa.UnlitProperties(new_material) new_props.setBaseColorUsesTexCoord1(True) new_props.setBaseColorFactor("white") # Load a texture new_tex = Qt3DRender.QTextureLoader(self.rootEntity) new_tex.setSource(assetsUrl() + "/models/car/KDAB.png") new_tex.setMinificationFilter( Qt3DRender.QAbstractTexture.LinearMipMapLinear) new_tex.setMagnificationFilter(Qt3DRender.QAbstractTexture.Linear) new_tex.wrapMode().setX(Qt3DRender.QTextureWrapMode.Repeat) new_tex.wrapMode().setY(Qt3DRender.QTextureWrapMode.Repeat) new_tex.setGenerateMipMaps(1) new_props.setBaseColorMap(new_tex) new_material.setUnlitProperties(new_props) orig_entity.addComponent(new_material)
def create_attribute(self, buffer_values, name): SIZE_OF_FLOAT_IN_STRUCT = 4 POINTS_IN_VECTOR = 3 buffer = Qt3DRender.QBuffer(self) buffer.setData(convert_to_bytes(buffer_values)) attribute = self.q_attribute(self) attribute.setAttributeType(self.q_attribute.VertexAttribute) attribute.setBuffer(buffer) attribute.setDataSize(POINTS_IN_VECTOR) attribute.setByteOffset(0) attribute.setByteStride(POINTS_IN_VECTOR * SIZE_OF_FLOAT_IN_STRUCT) attribute.setCount(len(buffer_values)) attribute.setName(name) return attribute
def __init__(self, view: Qt3DExtras.Qt3DWindow) -> None: """ Initialize a new instance. Args: view: where to render the planetary sphere. """ self.root_entity = Qt3DCore.QEntity() ce = self.camera_entity = view.camera() ce.lens().setPerspectiveProjection(45.0, 1.0, 0.1, 1000.0) ce.setPosition(V3(0, 8, 8)) ce.setUpVector(V3(0, 1, 0)) ce.setViewCenter(V3(0, 0, 0)) self.light = Qt3DCore.QEntity(self.root_entity) self.point_light = Qt3DRender.QPointLight(self.light) self.point_light.setColor("white") self.point_light.setIntensity(1.0) self.light.addComponent(self.point_light) # Move the light to the camera's position - on-camera 'flash'! t = self.light_transform = Qt3DCore.QTransform(self.light) t.setTranslation(ce.position()) self.light.addComponent(t) self.mesh = Qt3DExtras.QSphereMesh() self.mesh.setRings(30) self.mesh.setSlices(30) self.mesh.setRadius(2) t = self.transform = Qt3DCore.QTransform() t.setScale(1.3) t.setTranslation(V3(0.0, 0.0, 0.0)) m = self.material = Qt3DExtras.QDiffuseSpecularMaterial() m.setAmbient(QColor(200, 200, 255)) m.setShininess(20.0) self.entity = Qt3DCore.QEntity(self.root_entity) self.entity.addComponent(self.mesh) self.entity.addComponent(self.material) self.entity.addComponent(self.transform) view.setRootEntity(self.root_entity) self.entity.setEnabled(True)
def create_gnomon_camera(self, main_camera): """ Creates a camera for observing the gnomon. Borrows some settings from the main camera. :param main_camera: The main camera that views the instrument components. :return: The gnomon camera. """ aspect = 1 near_plane = 0.1 # Set far plane so that the camera can see the gnomon even when it is turned "behind" it and the cylinders are # facing away from the camera. far_plane = 25 gnomon_camera = Qt3DRender.QCamera() gnomon_camera.setParent(self.gnomon_root_entity) gnomon_camera.setProjectionType(main_camera.projectionType()) gnomon_camera.lens().setPerspectiveProjection( main_camera.fieldOfView(), aspect, near_plane, far_plane) gnomon_camera.setUpVector(main_camera.upVector()) gnomon_camera.setViewCenter(QVector3D(0, 0, 0)) return gnomon_camera
def __init__(self, component_root_entity: Qt3DCore.QEntity, line_length: float): """ Class for housing the objects that create the axes in the instrument view. :param component_root_entity: The root entity for the instrument view components. :param line_length: The length of the line in the axes. """ vertices = [0 for _ in range(3)] for i, color in enumerate( [AxisColors.X.value, AxisColors.Y.value, AxisColors.Z.value] ): mesh = Qt3DRender.QGeometryRenderer(component_root_entity) line_vertices = vertices[:] line_vertices[i] = line_length geometry = LineGeometry( QtCore.QByteArray(self.create_data_array(line_vertices)), component_root_entity, ) self.set_mesh_properties(mesh, geometry) material = create_material(color, color, component_root_entity) create_qentity([mesh, material], component_root_entity)
def __init__(self, window): self.window = window self.offscreenSurface = QOffscreenSurface() sformat = QSurfaceFormat.defaultFormat() sformat.setDepthBufferSize(32) self.offscreenSurface.setFormat( sformat ) self.offscreenSurface.create() self.overlayCamera = Qt3DRender.QCamera() self.overlayCamera.setViewCenter( vec3d() ) self.overlayCamera.setPosition( vec3d( 0, 0, -1 ) ) self.overlayCamera.setUpVector( vec3d( 0, 1, 0 ) ) self.overlayCamera.lens().setOrthographicProjection( -1, 1, -1, 1, -1, 1 ) # Framegraph root #1 -- onscreen rendering self.surfaceSelector = Qt3DRender.QRenderSurfaceSelector() self.surfaceSelector.setSurface(window) self.root = self.surfaceSelector # Framgraph root #2 -- Used for offscreen renders, not in the graph by default # During screenshots, offscreenSurfaceSelector becomes the root # and the branch roots will become a child of renderTargetSelector self.offscreenSurfaceSelector = Qt3DRender.QRenderSurfaceSelector() self.offscreenSurfaceSelector.setSurface(self.offscreenSurface) self.renderTargetSelector = Qt3DRender.QRenderTargetSelector(self.offscreenSurfaceSelector) self.targetTexture = OffscreenRenderTarget(self.renderTargetSelector) self.renderTargetSelector.setTarget(self.targetTexture) self.noDraw2 = Qt3DRender.QNoDraw(self.renderTargetSelector) # Branch 1: clear buffers self.clearBuffers = Qt3DRender.QClearBuffers(self.surfaceSelector) self.clearBuffers.setBuffers(Qt3DRender.QClearBuffers.ColorDepthBuffer) self.clearBuffers.setClearColor(Qt.white) self.noDraw = Qt3DRender.QNoDraw(self.clearBuffers) # Branch 2: main drawing branches using the Athena camera self.cameraSelector = Qt3DRender.QCameraSelector(self.surfaceSelector) self.cameraSelector.setCamera(window.camera()) # Branch 2A: solid objects self.viewport = Qt3DRender.QViewport(self.cameraSelector) self.viewport.setNormalizedRect(QRectF(0, 0, 1.0, 1.0)) self.qfilt = Qt3DRender.QTechniqueFilter(self.viewport) self.solidPassFilter = Qt3DRender.QFilterKey(self.qfilt) self.solidPassFilter.setName('pass') self.solidPassFilter.setValue('solid') self.qfilt.addMatch(self.solidPassFilter) # Branch 2B: transparent objects self.viewport2 = Qt3DRender.QViewport(self.cameraSelector) self.viewport2.setNormalizedRect(QRectF(0, 0, 1.0, 1.0)) self.qfilt2 = Qt3DRender.QTechniqueFilter(self.viewport2) self.transPassFilter = Qt3DRender.QFilterKey(self.qfilt2) self.transPassFilter.setName('pass') self.transPassFilter.setValue('transp') self.qfilt2.addMatch(self.transPassFilter) # Branch 3: 2D screen overlays self.cameraSelector2 = Qt3DRender.QCameraSelector(self.surfaceSelector) self.cameraSelector2.setCamera(self.overlayCamera) self.viewport3 = Qt3DRender.QViewport(self.cameraSelector2) self.viewport3.setNormalizedRect(QRectF(0, 0, 1.0, 1.0)) self.qfilt3 = Qt3DRender.QTechniqueFilter(self.viewport3) self.overlayPassFilter = Qt3DRender.QFilterKey(self.viewport3) self.overlayPassFilter.setName('pass') self.overlayPassFilter.setValue('overlay') self.qfilt3.addMatch(self.overlayPassFilter) # Branch 4: render capture branch for taking screenshots self.renderCapture = Qt3DRender.QRenderCapture(self.surfaceSelector) self.noDraw3 = Qt3DRender.QNoDraw(self.renderCapture) # Branch roots are the bits that need reparenting when switching between # offscreen and onscreen rendering self.branchRoots = [ self.clearBuffers, self.cameraSelector, self.cameraSelector2, self.renderCapture ]
def __init__(self, parent=None): super().__init__(parent) self.rnd_lat = random.randrange(5200,5300) / 100.0 self.rnd_hdg = random.randrange(-300,300) / 100.0 self.rnd_dec = random.randrange(-50,50) / 10.0 print(self.rnd_lat, self.rnd_hdg, self.rnd_dec) self.view = Qt3DExtras.Qt3DWindow() self.view.defaultFrameGraph().setClearColor(QtGui.QColor("#4d4d4f")) self.container = QtWidgets.QWidget.createWindowContainer(self.view) self.vLayout = QtWidgets.QVBoxLayout(self) self.vLayout.addWidget(self.container, 1) self.input_aspect = Qt3DInput.QInputAspect() self.view.registerAspect(self.input_aspect) self.rootEntity = Qt3DCore.QEntity() self.view.setRootEntity(self.rootEntity) ### cameraEntity = self.view.camera() cameraEntity.lens().setPerspectiveProjection(5.0, 16.0 / 9.0, 10, 100000.0) cameraEntity.setPosition(QtGui.QVector3D(0, 1000, 50000)) cameraEntity.setUpVector(QtGui.QVector3D(0, 1, 0)) cameraEntity.setViewCenter(QtGui.QVector3D(0, 1000, 0)) self.camController = Qt3DExtras.QOrbitCameraController(self.rootEntity) self.camController.setCamera(cameraEntity) ### self.lightEntity = Qt3DCore.QEntity(self.rootEntity) self.light = Qt3DRender.QPointLight(self.lightEntity) self.light.setColor("white") self.light.setIntensity(1) self.lightTransform = Qt3DCore.QTransform(self.lightEntity) self.lightTransform.setTranslation(cameraEntity.position()) self.lightEntity.addComponent(self.light) self.lightEntity.addComponent(self.lightTransform) ### sky # self.skyMesh = Qt3DExtras.QSphereMesh(radius=5000, rings=94, slices=48) # self.skyMaterial = Qt3DExtras.QPhongMaterial(diffuse=QtGui.QColor("#ff0000")) # self.skyEntity = Qt3DCore.QEntity(self.rootEntity) # self.skyEntity.addComponent(self.skyMesh) # self.skyEntity.addComponent(self.skyMaterial) ### hdg, x right, y up # Cylinder cog = (0,0,0) long direction = y self.hdgMesh = Qt3DExtras.QCylinderMesh(length=1200.0, radius=100.0, rings=100, slices=20) rotation = QtGui.QQuaternion.fromAxisAndAngle(QtGui.QVector3D(0.0, 0.0, 1.0), 15.0) translation = QtGui.QVector3D(0.0, 600.0, 0.0) self.hdgTransform = Qt3DCore.QTransform(translation=translation, rotation=rotation) self.hdgMaterial = Qt3DExtras.QPhongMaterial(diffuse=QtGui.QColor("#ff0000")) self.hdgEntity = Qt3DCore.QEntity(self.rootEntity) self.hdgEntity.addComponent(self.hdgMesh) self.hdgEntity.addComponent(self.hdgMaterial) self.hdgEntity.addComponent(self.hdgTransform) ### lat x up, y left self.latMesh = Qt3DExtras.QCylinderMesh(length=200.0, radius=100.0, rings=100, slices=20) rotation = QtGui.QQuaternion.fromAxisAndAngle(QtGui.QVector3D(0.0, 0.0, 1.0), 90.0) translation = QtGui.QVector3D(0.0, 700.0, 0.0) self.latTransform = Qt3DCore.QTransform(rotation=rotation, translation=translation) self.latMaterial = Qt3DExtras.QPhongMaterial(diffuse=QtGui.QColor("#00ff00")) self.latEntity = Qt3DCore.QEntity(self.hdgEntity) self.latEntity.addComponent(self.latMesh) self.latEntity.addComponent(self.latMaterial) self.latEntity.addComponent(self.latTransform) ### ra x up, y left self.raMesh = Qt3DExtras.QCylinderMesh(length=500.0, radius=100.0, rings=100, slices=20) rotation1 = QtGui.QQuaternion.fromAxisAndAngle(QtGui.QVector3D(0.0, 0.0, -1.0), 90) rotation2 = QtGui.QQuaternion.fromAxisAndAngle(QtGui.QVector3D(-1.0, 0.0, 0.0), 90) rotation = rotation1 * rotation2 translation = QtGui.QVector3D(200.0, 0.0, 0.0) self.raTransform = Qt3DCore.QTransform(rotation=rotation, translation=translation) self.raMaterial = Qt3DExtras.QPhongMaterial(diffuse=QtGui.QColor("#beb32b")) self.raEntity = Qt3DCore.QEntity(self.latEntity) self.raEntity.addComponent(self.raMesh) self.raEntity.addComponent(self.raMaterial) self.raEntity.addComponent(self.raTransform) ### dec self.decMesh = Qt3DExtras.QCylinderMesh(length=500.0, radius=100.0, rings=100, slices=20) rotation = QtGui.QQuaternion.fromAxisAndAngle(QtGui.QVector3D(1.0, 0.0, 0.0), 90.0) translation = QtGui.QVector3D(0.0, 350.0, 0.0) self.decTransform = Qt3DCore.QTransform(rotation=rotation, translation=translation) self.decMaterial = Qt3DExtras.QPhongMaterial(diffuse=QtGui.QColor("#0000ff")) self.decEntity = Qt3DCore.QEntity(self.raEntity) self.decEntity.addComponent(self.decMesh) self.decEntity.addComponent(self.decMaterial) self.decEntity.addComponent(self.decTransform) ### tube self.tubeMesh = Qt3DExtras.QCylinderMesh(length=1200.0, radius=100.0, rings=100, slices=20) rotation = QtGui.QQuaternion.fromAxisAndAngle(QtGui.QVector3D(-1.0, 0.0, 0.0), 90.0) translation = QtGui.QVector3D(0.0, 350.0, 100.0) self.tubeTransform = Qt3DCore.QTransform(rotation=rotation, translation=translation) self.tubeMaterial = Qt3DExtras.QPhongMaterial(diffuse=QtGui.QColor("#ffffff")) self.tubeEntity = Qt3DCore.QEntity(self.decEntity) self.tubeEntity.addComponent(self.tubeMesh) self.tubeEntity.addComponent(self.tubeMaterial) self.tubeEntity.addComponent(self.tubeTransform) self.ocuMesh = Qt3DExtras.QCylinderMesh(length=100.0, radius=50.0, rings=100, slices=20) translation = QtGui.QVector3D(0.0, -650.0, 0.0) self.ocuTransform = Qt3DCore.QTransform(translation=translation) self.ocuMaterial = Qt3DExtras.QPhongMaterial(diffuse=QtGui.QColor("#ffffff")) self.ocuEntity = Qt3DCore.QEntity(self.tubeEntity) self.ocuEntity.addComponent(self.ocuMesh) self.ocuEntity.addComponent(self.ocuMaterial) self.ocuEntity.addComponent(self.ocuTransform) self.fakeMesh = Qt3DExtras.QCuboidMesh(xExtent=500, yExtent=500, zExtent=500) translation = QtGui.QVector3D(-1000.0, 0, 0.0) self.fakeTransform = Qt3DCore.QTransform(translation=translation) self.fakeMaterial = Qt3DExtras.QPhongMaterial(diffuse=QtGui.QColor("#ffffff")) self.fakeEntity = Qt3DCore.QEntity(self.rootEntity) self.fakeEntity.addComponent(self.fakeMesh) self.fakeEntity.addComponent(self.fakeMaterial) self.fakeEntity.addComponent(self.fakeTransform) self._heading = 0 self._latitude = 45 self._ra = 0 self._dec = 90
def __init__(self, args, parent=None): super().__init__(parent) ############################################################################## # UI初期化処理 self.ui = MainWindowUi.loader(os.path.join(os.getcwd(), 'ui/main.ui')) self.setWindowTitle('self.viewer test') self.setCentralWidget(self.ui.widgets) self.view = Qt3DExtras.Qt3DWindow() self.view.defaultFrameGraph().setClearColor(QtGui.QColor(0, 0, 0)) self.container = QWidget.createWindowContainer(self.view) screen_size = self.view.screen().size() self.ui.viewer.addWidget(self.container) self.container.setMinimumSize(QtCore.QSize(400, 600)) self.container.setMaximumSize(screen_size) # QSize screenSize = self.view -> screen() -> size(); # container -> setMinimumSize(QSize(200, 100)); # container -> setMaximumSize(screenSize); # vLayout -> setAlignment(Qt: : AlignTop); # hLayout -> addWidget(container, 1); # hLayout -> addLayout(vLayout); # input_aspect = Qt3DInput.QInputAspect() # self.view.registerAspect(input_aspect) # root entity self.root_entity: Qt3DCore.QEntity = Qt3DCore.QEntity() # draw grid and axis """ self.x_axis: Qt3DRender.QGeometry = Qt3DRender.QGeometry(self.root_entity) x_axis_pos: QtCore.QByteArray = QtCore.QByteArray() x_axis_pos.append(0) x_axis_pos.append(0) x_axis_pos.append(0) x_axis_pos.append(10) x_axis_pos.append(0) x_axis_pos.append(0) x_axis_buf: Qt3DRender.QBuffer = Qt3DRender.QBuffer(self.x_axis) x_axis_buf.setData(x_axis_pos) x_axis_attr: Qt3DRender.QAttribute = Qt3DRender.QAttribute(self.x_axis) x_axis_attr.setVertexBaseType(Qt3DRender.QAttribute.Float) x_axis_attr.setVertexSize(3) x_axis_attr.setAttributeType(Qt3DRender.QAttribute.VertexAttribute) x_axis_attr.setBuffer(x_axis_buf) x_axis_attr.setByteStride(3) x_axis_attr.setCount(2) self.x_axis.addAttribute(x_axis_attr) """ test_mtl = Qt3DExtras.QTextureMaterial(self.root_entity) self.test = Qt3DCore.QEntity(self.root_entity) self.test_mesh: Qt3DExtras.QTorusMesh = Qt3DExtras.QTorusMesh() self.test_mesh.setRadius(5) self.test_mesh.setMinorRadius(1) self.test_mesh.setRings(100) self.test_mesh.setSlices(20) self.test_tr = Qt3DCore.QTransform() self.test_tr.setTranslation(QtGui.QVector3D(0, 0, 0)) # test_tr.setScale3D() self.test.addComponent(self.test_mesh) self.test.addComponent(self.test_tr) self.test.addComponent(self.test_mtl) # camera entity camera_entity: Qt3DRender.QCamera = self.view.camera() camera_entity.lens().setPerspectiveProjection(45.0, 16.0 / 9.0, 0.1, 1000.0) camera_entity.setPosition(QtGui.QVector3D(0, 0, 20.0)) camera_entity.setUpVector(QtGui.QVector3D(0, 1, 0)) camera_entity.setViewCenter(QtGui.QVector3D(0, 0, 0)) light_entity = Qt3DCore.QEntity(self.root_entity) light = Qt3DRender.QPointLight(light_entity) light.setColor("white") light.setIntensity(1) light_entity.addComponent(light) light_transform = Qt3DCore.QTransform(light_entity) light_transform.setTranslation(camera_entity.position()) light_entity.addComponent(light_transform) # for camera controls cam_controller = Qt3DExtras.QFirstPersonCameraController(self.root_entity) cam_controller.setCamera(camera_entity) # set root object of the scene self.view.setRootEntity(self.root_entity)
def init( self ): param = Qt3DRender.QParameter( self.rootEntity ) param.setName( key ) param.setValue( value ) setattr( self, attr_name, param )