Ejemplo n.º 1
0
    def initialize(self):
        # Bring used components
        self.registerVtkWebProtocol(vtk_protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(vtk_protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(
            vtk_override_protocols.vtkWebPublishImageDelivery(decode=False))

        # Custom API
        self.registerVtkWebProtocol(VtkCone())

        # tell the C++ web app to use no encoding.
        # ParaViewWebPublishImageDelivery must be set to decode=False to match.
        self.getApplication().SetImageEncoding(0)

        # Update authentication key to use
        self.updateSecret(_Server.authKey)

        if not _Server.view:
            renderer = vtk.vtkRenderer()
            renderWindow = vtk.vtkRenderWindow()
            renderWindow.AddRenderer(renderer)

            renderWindowInteractor = vtk.vtkRenderWindowInteractor()
            renderWindowInteractor.SetRenderWindow(renderWindow)
            renderWindowInteractor.GetInteractorStyle(
            ).SetCurrentStyleToTrackballCamera()
            renderWindowInteractor.EnableRenderOff()
            self.getApplication().GetObjectIdMap().SetActiveObject(
                "VIEW", renderWindow)
Ejemplo n.º 2
0
    def initialize(self):
        print "initialize"
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor
        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebFileBrowser('.', '.'))
        # Create default pipeline (Only once for all the session)
        # Update authentication key to use
        self.updateSecret(_WebCone.authKey)

        if not _WebCone.view:
            # # VTK specific code
            # renderer = vtk.vtkRenderer()
            # renderWindow = vtk.vtkRenderWindow()
            # renderWindow.AddRenderer(renderer)
            # renderWindowInteractor = vtk.vtkRenderWindowInteractor()
            # renderWindowInteractor.SetRenderWindow(renderWindow)
            # renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera()
            # cone = vtk.vtkConeSource()
            # mapper = vtk.vtkPolyDataMapper()
            # actor = vtk.vtkActor()
            # mapper.SetInputConnection(cone.GetOutputPort())
            # actor.SetMapper(mapper)
            # renderer.AddActor(actor)
            # renderer.ResetCamera()
            # renderWindow.Render()

            # VCS specific code
            import vcs, cdms2, sys
            x = vcs.init(bg=1)
            f = cdms2.open(vcs.sample_data + "/geos5-sample.nc")
            v = f["uwnd"]
            dv3d = vcs.get3d_scalar()
            dv3d.ToggleClipping = (40, 360, -28, 90)
            dv3d.YSlider = (0.0, vcs.off)
            dv3d.XSlider = (180.0, vcs.on)
            dv3d.ZSlider = (0.0, vcs.on)
            dv3d.ToggleVolumePlot = vcs.on
            dv3d.ToggleSurfacePlot = vcs.on
            dv3d.IsosurfaceValue = 31.0
            dv3d.ScaleOpacity = [0.0, 1.0]
            dv3d.BasemapOpacity = 0.5
            dv3d.Camera = {
                'Position': (-161, -171, 279),
                'ViewUp': (.29, 0.67, 0.68),
                'FocalPoint': (146.7, 8.5, -28.6)
            }
            dv3d.VerticalScaling = 5.0
            dv3d.ScaleColormap = [-46.0, 48.0]
            dv3d.ScaleTransferFunction = [12.0, 77.0]

            x.plot(v, dv3d)
            renderWindow = x.backend.renWin
            # VTK Web application specific
            _WebCone.view = renderWindow
            self.getApplication().GetObjectIdMap().SetActiveObject(
                "VIEW", renderWindow)
Ejemplo n.º 3
0
    def initialize(self):
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Create default pipeline (Only once for all the session)
        if not _WebCone.view:
            # VTK specific code
            renderer = vtk.vtkRenderer()
            renderWindow = vtk.vtkRenderWindow()
            renderWindow.AddRenderer(renderer)

            renderWindowInteractor = vtk.vtkRenderWindowInteractor()
            renderWindowInteractor.SetRenderWindow(renderWindow)
            renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera()

            cone = vtk.vtkConeSource()
            mapper = vtk.vtkPolyDataMapper()
            actor = vtk.vtkActor()

            mapper.SetInputConnection(cone.GetOutputPort())
            actor.SetMapper(mapper)

            renderer.AddActor(actor)
            renderer.ResetCamera()
            renderWindow.Render()

            # VTK Web application specific
            _WebCone.view = renderWindow
            self.Application.GetObjectIdMap().SetActiveObject("VIEW", renderWindow)
Ejemplo n.º 4
0
    def initialize(self):
        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())

        # Update authentication key to use
        self.updateSecret(_WebMolecule.authKey)

        # Create default pipeline (Only once for all the session)
        if not self.view:
            self.reader = vtk.vtkCMLMoleculeReader()
            #self.reader.SetFileName('/home/cjh/work/VTKData/Data/porphyrin.cml')
            self.mapper = vtk.vtkMoleculeMapper()
            self.mapper.SetInputConnection(self.reader.GetOutputPort())
            self.mapper.UseBallAndStickSettings()

            self.actor = vtk.vtkActor()
            self.actor.SetMapper(self.mapper)

            self.renderer = vtk.vtkRenderer()
            self.window = vtk.vtkRenderWindow()
            self.window.AddRenderer(self.renderer)

            interactor = vtk.vtkRenderWindowInteractor()
            interactor.SetRenderWindow(self.window)
            interactor.GetInteractorStyle().SetCurrentStyleToTrackballCamera()

            self.renderer.AddActor(self.actor)
            self.renderer.SetBackground(1, 1, 1)

            # VTK Web application specific
            _WebMolecule.view = self.window
            self.Application.GetObjectIdMap().SetActiveObject(
                "VIEW", self.window)
Ejemplo n.º 5
0
    def initialize(self):
        print "initialize"
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor
        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebFileBrowser('.', '.'))
        # Create default pipeline (Only once for all the session)
        # Update authentication key to use
        self.updateSecret(_WebCone.authKey)
        
        if not _WebCone.view:
            # # VTK specific code
            # renderer = vtk.vtkRenderer()
            # renderWindow = vtk.vtkRenderWindow()
            # renderWindow.AddRenderer(renderer)
            # renderWindowInteractor = vtk.vtkRenderWindowInteractor()
            # renderWindowInteractor.SetRenderWindow(renderWindow)
            # renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera()
            # cone = vtk.vtkConeSource()
            # mapper = vtk.vtkPolyDataMapper()
            # actor = vtk.vtkActor()
            # mapper.SetInputConnection(cone.GetOutputPort())
            # actor.SetMapper(mapper)
            # renderer.AddActor(actor)
            # renderer.ResetCamera()
            # renderWindow.Render()

            # VCS specific code
            import vcs, cdms2, sys
            x = vcs.init(bg=1)
            f = cdms2.open( vcs.sample_data+"/geos5-sample.nc" )
            v = f["uwnd"]
            dv3d = vcs.get3d_scalar()
            dv3d.ToggleClipping = ( 40, 360, -28, 90 )
            dv3d.YSlider = ( 0.0, vcs.off)
            dv3d.XSlider = ( 180.0, vcs.on )
            dv3d.ZSlider = ( 0.0, vcs.on )
            dv3d.ToggleVolumePlot = vcs.on
            dv3d.ToggleSurfacePlot = vcs.on
            dv3d.IsosurfaceValue = 31.0
            dv3d.ScaleOpacity = [0.0, 1.0]
            dv3d.BasemapOpacity = 0.5
            dv3d.Camera={ 'Position': (-161, -171, 279),
                          'ViewUp': (.29, 0.67, 0.68),
                          'FocalPoint': (146.7, 8.5, -28.6)  }
            dv3d.VerticalScaling = 5.0
            dv3d.ScaleColormap = [ -46.0, 48.0 ]
            dv3d.ScaleTransferFunction =  [ 12.0, 77.0 ]

            x.plot( v, dv3d )
            renderWindow = x.backend.renWin
            # VTK Web application specific
            _WebCone.view = renderWindow
            self.getApplication().GetObjectIdMap().SetActiveObject("VIEW", renderWindow)
Ejemplo n.º 6
0
    def initialize(self):
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebFileBrowser(self.rootDir, 'Home'))
        self.registerVtkWebProtocol(FileLoader(self.rootDir))
        self.registerVtkWebProtocol(Visualizer())

        # Update authentication key to use
        self.updateSecret(_VCSTestServer.authKey)
    def initialize(self):
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Update authentication key to use
        self.updateSecret(_PhylogeneticTree.authKey)

        # Create default pipeline (Only once for all the session)
        if not _PhylogeneticTree.view:
            # read in  a tree
            treeReader = vtk.vtkNewickTreeReader()
            treeReader.SetFileName(_PhylogeneticTree.treeFilePath)
            treeReader.Update()
            reader = treeReader.GetOutput()

            # read in  a table
            tableReader = vtk.vtkDelimitedTextReader()
            tableReader.SetFileName(_PhylogeneticTree.csvFilePath)
            tableReader.SetHaveHeaders(True)
            tableReader.DetectNumericColumnsOn()
            tableReader.Update()
            table = tableReader.GetOutput()

            # play with the heatmap vis
            treeHeatmapItem = vtk.vtkTreeHeatmapItem()
            treeHeatmapItem.SetTree(reader)
            treeHeatmapItem.SetTable(table)

            # setup the window
            view = vtk.vtkContextView()
            view.GetRenderer().SetBackground(1, 1, 1)
            view.GetRenderWindow().SetSize(800, 600)

            iren = view.GetInteractor()
            iren.SetRenderWindow(view.GetRenderWindow())

            transformItem = vtk.vtkContextTransform()
            transformItem.AddItem(treeHeatmapItem)
            transformItem.SetInteractive(1)

            view.GetScene().AddItem(transformItem)
            view.GetRenderWindow().SetMultiSamples(0)

            iren.Initialize()
            view.GetRenderWindow().Render()

            # VTK Web application specific
            _PhylogeneticTree.view = view.GetRenderWindow()
            self.Application.GetObjectIdMap().SetActiveObject(
                "VIEW", view.GetRenderWindow())
Ejemplo n.º 8
0
    def initialize(self):
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Update authentication key to use
        self.updateSecret(_PhylogeneticTree.authKey)

        # Create default pipeline (Only once for all the session)
        if not _PhylogeneticTree.view:
            # read in  a tree
            treeReader = vtk.vtkNewickTreeReader()
            treeReader.SetFileName(_PhylogeneticTree.treeFilePath)
            treeReader.Update()
            reader = treeReader.GetOutput()

            # read in  a table
            tableReader = vtk.vtkDelimitedTextReader()
            tableReader.SetFileName(_PhylogeneticTree.csvFilePath)
            tableReader.SetHaveHeaders(True)
            tableReader.DetectNumericColumnsOn()
            tableReader.Update()
            table = tableReader.GetOutput()

            # play with the heatmap vis
            treeHeatmapItem = vtk.vtkTreeHeatmapItem()
            treeHeatmapItem.SetTree(reader);
            treeHeatmapItem.SetTable(table);

            # setup the window
            view = vtk.vtkContextView()
            view.GetRenderer().SetBackground(1,1,1)
            view.GetRenderWindow().SetSize(800,600)

            iren = view.GetInteractor()
            iren.SetRenderWindow(view.GetRenderWindow())

            transformItem = vtk.vtkContextTransform()
            transformItem.AddItem(treeHeatmapItem)
            transformItem.SetInteractive(1)

            view.GetScene().AddItem(transformItem)
            view.GetRenderWindow().SetMultiSamples(0)

            iren.Initialize()
            view.GetRenderWindow().Render()

            # VTK Web application specific
            _PhylogeneticTree.view = view.GetRenderWindow()
            self.Application.GetObjectIdMap().SetActiveObject("VIEW", view.GetRenderWindow())
Ejemplo n.º 9
0
    def initialize(self):
        # Bring used components
        self.registerVtkWebProtocol(vtk_protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(vtk_protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(vtkWebPublishImageDelivery(decode=False))

        # Custom API
        self.registerVtkWebProtocol(MouseWheel())

        # tell the C++ web app to use no encoding.
        # ParaViewWebPublishImageDelivery must be set to decode=False to match.
        self.getApplication().SetImageEncoding(0)

        # Update authentication key to use
        self.updateSecret(_Server.authKey)

        if not _Server.view:
            scene = window.Scene()
            scene.background((1, 1, 1))

            if os.path.isfile(_Server.centersToLoad):
                with open(_Server.centersToLoad) as f:
                    f_dict = json.loads(f.read())
                centers = np.array(f_dict["centers"])
                n_points = len(centers)
                colors = np.array(f_dict["colors"])
                directions = np.random.rand(n_points, 3)
            else:
                n_points = 10000
                translate = 100
                centers = translate * np.random.rand(n_points,
                                                     3) - translate / 2
                colors = 255 * np.random.rand(n_points, 3)

                directions = np.random.rand(n_points, 3)
            # scales = np.random.rand(n_points, 3)

            prim_type = ['sphere', 'ellipsoid', 'torus']
            primitive = [random.choice(prim_type) for _ in range(n_points)]

            sdf_actor = actor.sdf(centers, directions, colors, primitive)
            scene.add(sdf_actor)
            scene.add(actor.axes())

            showm = window.ShowManager(scene)

            renderWindow = showm.window
            showm.iren.EnableRenderOff()

            self.getApplication().GetObjectIdMap().SetActiveObject(
                "VIEW", renderWindow)
Ejemplo n.º 10
0
        def initialize(self):
            # Bring used components
            self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
            self.registerVtkWebProtocol(protocols.vtkWebViewPort())
            self.registerVtkWebProtocol(
                protocols.vtkWebViewPortImageDelivery())
            self.registerVtkWebProtocol(
                protocols.vtkWebViewPortGeometryDelivery())

            # Update authentication key to use
            self.updateSecret(VTKWebApp.authKey)

            if "initialize" in self.app.__dict__:
                self.app.initialize(self, VTKWebApp, self.args)
Ejemplo n.º 11
0
        def initialize(self):
            # Bring used components
            self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
            self.registerVtkWebProtocol(protocols.vtkWebViewPort())
            self.registerVtkWebProtocol(
                protocols.vtkWebViewPortImageDelivery())
            self.registerVtkWebProtocol(
                protocols.vtkWebViewPortGeometryDelivery())

            # Update authentication key to use
            self.updateSecret(VTKWebApp.authKey)

            if "initialize" in self.app.__dict__:
                self.app.initialize(self, VTKWebApp, self.args)
Ejemplo n.º 12
0
    def initialize(self):
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())

        # Update authentication key to use
        self.updateSecret(_WebGraph.authKey)

        # Create default pipeline (Only once for all the sessions)
        if not _WebGraph.view:
            # Generate Random graph
            random = vtkRandomGraphSource()
            random.SetNumberOfVertices(_WebGraph.vertices)
            random.SetNumberOfEdges(_WebGraph.edges)
            random.SetStartWithTree(True)
            random.Update()
            graphData = random.GetOutput()

            # Create view
            view = vtkGraphLayoutView()
            view.AddRepresentationFromInput(graphData)

            # Customize Rendering
            view.SetVertexLabelArrayName("vertex id")
            view.SetVertexLabelVisibility(True)
            view.SetVertexColorArrayName("vertex id")
            view.SetColorVertices(True)
            view.SetScalingArrayName("vertex id")
            view.ScaledGlyphsOn()
            view.HideVertexLabelsOnInteractionOn()
            view.SetEdgeColorArrayName("edge id")
            view.SetColorEdges(True)

            view.SetLayoutStrategyToSpanTree()

            # Set trackball interaction style
            style = vtkInteractorStyleTrackballCamera()
            view.GetRenderWindow().GetInteractor().SetInteractorStyle(style)

            # VTK Web application specific
            _WebGraph.view = view
            view.ResetCamera()
            view.Render()
            self.Application.GetObjectIdMap().SetActiveObject(
                "VIEW", view.GetRenderWindow())
Ejemplo n.º 13
0
    def initialize(self):
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())

        # Update authentication key to use
        self.updateSecret(_WebGraph.authKey)

        # Create default pipeline (Only once for all the sessions)
        if not _WebGraph.view:
            # Generate Random graph
            random = vtkRandomGraphSource()
            random.SetNumberOfVertices(_WebGraph.vertices)
            random.SetNumberOfEdges(_WebGraph.edges)
            random.SetStartWithTree(True)
            random.Update()
            graphData = random.GetOutput()

            # Create view
            view = vtkGraphLayoutView()
            view.AddRepresentationFromInput(graphData)

            # Customize Rendering
            view.SetVertexLabelArrayName("vertex id")
            view.SetVertexLabelVisibility(True)
            view.SetVertexColorArrayName("vertex id")
            view.SetColorVertices(True)
            view.SetScalingArrayName("vertex id")
            view.ScaledGlyphsOn()
            view.HideVertexLabelsOnInteractionOn()
            view.SetEdgeColorArrayName("edge id")
            view.SetColorEdges(True)

            view.SetLayoutStrategyToSpanTree()

            # Set trackball interaction style
            style = vtkInteractorStyleTrackballCamera()
            view.GetRenderWindow().GetInteractor().SetInteractorStyle(style)

            # VTK Web application specific
            _WebGraph.view = view
            view.ResetCamera()
            view.Render()
            self.Application.GetObjectIdMap().SetActiveObject("VIEW", view.GetRenderWindow())
Ejemplo n.º 14
0
    def initialize(self):
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(
            protocols.vtkWebPublishImageDelivery(decode=False))
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Update authentication key to use
        self.updateSecret(_WebCone.authKey)

        # tell the C++ web app to use no encoding.
        # ParaViewWebPublishImageDelivery must be set to decode=False to match.
        self.getApplication().SetImageEncoding(0)

        # Create default pipeline (Only once for all the session)
        if not _WebCone.view:
            # VTK specific code
            renderer = vtk.vtkRenderer()
            renderWindow = vtk.vtkRenderWindow()
            renderWindow.AddRenderer(renderer)
            # renderWindow.SetOffScreenRendering(1)

            renderWindowInteractor = vtk.vtkRenderWindowInteractor()
            renderWindowInteractor.SetRenderWindow(renderWindow)
            renderWindowInteractor.GetInteractorStyle(
            ).SetCurrentStyleToTrackballCamera()

            cone = vtk.vtkConeSource()
            mapper = vtk.vtkPolyDataMapper()
            actor = vtk.vtkActor()

            mapper.SetInputConnection(cone.GetOutputPort())
            actor.SetMapper(mapper)

            renderer.AddActor(actor)
            renderer.ResetCamera()

            renderWindow.Render()

            # VTK Web application specific
            _WebCone.view = renderWindow
            self.getApplication().GetObjectIdMap().SetActiveObject(
                "VIEW", renderWindow)
Ejemplo n.º 15
0
    def initializeProtocols(self):
        if "geode_default" not in GeodeServerProtocol.modules:
            GeodeServerProtocol.modules.append("geode_default")
        # Bring used components
        self.registerVtkWebProtocol(vtk_protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(vtk_protocols.vtkWebViewPort())
        delivery = vtk_protocols.vtkWebPublishImageDelivery(decode=False)
        delivery.deltaStaleTimeBeforeRender = 0.001
        self.registerVtkWebProtocol(delivery)

        # tell the C++ web app to use no encoding. ParaViewWebPublishImageDelivery must be set to decode=False to match.
        self.getApplication().SetImageEncoding(0)

        print(GeodeServerProtocol.modules)
        for module_name in GeodeServerProtocol.modules:
            module = import_module(module_name.strip() + "_protocols")
            for module_protocol in module.protocols:
                self.registerVtkWebProtocol(module_protocol())
Ejemplo n.º 16
0
    def initialize(self):
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Create default pipeline (Only once for all the session)
        if not _WebCone.view:
            # VTK specific code
            renderer = vtk.vtkRenderer()
            renderWindow = vtk.vtkRenderWindow()
            renderWindow.AddRenderer(renderer)

            renderWindowInteractor = vtk.vtkRenderWindowInteractor()
            renderWindowInteractor.SetRenderWindow(renderWindow)
            renderWindowInteractor.GetInteractorStyle(
            ).SetCurrentStyleToTrackballCamera()

            cone = vtk.vtkConeSource()
            mapper = vtk.vtkPolyDataMapper()
            actor = vtk.vtkActor()

            mapper.SetInputConnection(cone.GetOutputPort())
            actor.SetMapper(mapper)

            renderer.AddActor(actor)
            renderer.ResetCamera()
            renderWindow.Render()

            # VTK Web application specific
            _WebCone.view = renderWindow
            self.Application.GetObjectIdMap().SetActiveObject(
                "VIEW", renderWindow)
Ejemplo n.º 17
0
    def initialize(self):
        # Bring used components
        self.registerVtkWebProtocol(vtk_protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(vtk_protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(
            vtk_override_protocols.vtkWebPublishImageDelivery(decode=False))

        # Custom API
        self.registerVtkWebProtocol(VtkCone())

        # tell the C++ web app to use no encoding.
        # ParaViewWebPublishImageDelivery must be set to decode=False to match.
        self.getApplication().SetImageEncoding(0)

        # Update authentication key to use
        self.updateSecret(_Server.authKey)

        if not _Server.view:

            # Create the renderer, the render window, and the interactor. The renderer
            # draws into the render window, the interactor enables mouse- and
            # keyboard-based interaction with the scene.
            ren = vtk.vtkRenderer()
            renWin = vtk.vtkRenderWindow()
            renWin.AddRenderer(ren)
            iren = vtk.vtkRenderWindowInteractor()
            iren.SetRenderWindow(renWin)
            interactorStyle = vtk.vtkInteractorStyleImage()
            iren.SetInteractorStyle(interactorStyle)

            cred = credentials()

            mydb = mysql.connector.connect(host="localhost",
                                           user=cred[0],
                                           password=cred[1],
                                           database="iqweb")

            mycursor = mydb.cursor()
            sql = "SELECT path FROM image WHERE seriesuid = %s"
            params = (self.uid, )
            mycursor.execute(sql, params)

            files = mycursor.fetchall()
            fileset = vtk.vtkStringArray()
            for file in files:
                fileset.InsertNextValue(file[0])

            sorter = vtk.vtkDICOMFileSorter()
            sorter.SetInputFileNames(fileset)
            sorter.Update()

            sortedFiles = vtk.vtkStringArray()
            sortedFiles = sorter.GetFileNamesForSeries(0)

            reader = vtk.vtkDICOMReader()
            reader.SetFileNames(sortedFiles)
            reader.Update()

            # Calculate the center of the volume
            reader.Update()
            (xMin, xMax, yMin, yMax, zMin,
             zMax) = reader.GetExecutive().GetWholeExtent(
                 reader.GetOutputInformation(0))
            (xSpacing, ySpacing, zSpacing) = reader.GetOutput().GetSpacing()
            (x0, y0, z0) = reader.GetOutput().GetOrigin()

            center = [
                x0 + xSpacing * 0.5 * (xMin + xMax),
                y0 + ySpacing * 0.5 * (yMin + yMax),
                z0 + zSpacing * 0.5 * (zMin + zMax)
            ]

            # Matrices for axial, coronal, sagittal, oblique view orientations
            axial = vtk.vtkMatrix4x4()
            axial.DeepCopy((1, 0, 0, center[0], 0, 1, 0, center[1], 0, 0, 1,
                            center[2], 0, 0, 0, 1))

            coronal = vtk.vtkMatrix4x4()
            coronal.DeepCopy((1, 0, 0, center[0], 0, 0, 1, center[1], 0, -1, 0,
                              center[2], 0, 0, 0, 1))

            sagittal = vtk.vtkMatrix4x4()
            sagittal.DeepCopy((0, 0, -1, center[0], 1, 0, 0, center[1], 0, -1,
                               0, center[2], 0, 0, 0, 1))

            # Extract a slice in the desired orientation
            reslice = vtk.vtkImageReslice()
            reslice.SetInputConnection(reader.GetOutputPort())
            reslice.SetOutputDimensionality(2)
            reslice.SetResliceAxes(axial)
            if self.orientation == "coronal":
                reslice.SetResliceAxes(coronal)
            if self.orientation == "sagittal":
                reslice.SetResliceAxes(sagittal)
            reslice.SetInterpolationModeToLinear()

            meta = reader.GetMetaData()

            level = meta.Get(vtk.vtkDICOMTag(
                0x0028, 0x1050)).AsUTF8String().split("\\")[0]
            window = meta.Get(vtk.vtkDICOMTag(
                0x0028, 0x1051)).AsUTF8String().split("\\")[0]

            range1 = int(level) - int(window) / 2
            range2 = int(level) + int(window) / 2

            # Create a greyscale lookup table
            table = vtk.vtkLookupTable()
            table.SetRange(range1, range2)  # image intensity range
            table.SetValueRange(0.0, 1.0)  # from black to white
            table.SetSaturationRange(0.0, 0.0)  # no color saturation
            table.SetRampToLinear()
            table.Build()

            # Map the image through the lookup table
            color = vtk.vtkImageMapToColors()
            color.SetLookupTable(table)
            color.SetInputConnection(reslice.GetOutputPort())

            # Display the image
            actor = vtk.vtkImageActor()
            actor.GetMapper().SetInputConnection(color.GetOutputPort())

            ren.AddActor(actor)

            # Create callbacks for slicing the image
            actions = {}
            actions["Slicing"] = 0

            def ButtonCallback(obj, event):
                if event == "LeftButtonPressEvent":
                    actions["Slicing"] = 1
                else:
                    actions["Slicing"] = 0

            def MouseMoveCallback(obj, event):
                (lastX, lastY) = iren.GetLastEventPosition()
                (mouseX, mouseY) = iren.GetEventPosition()
                if actions["Slicing"] == 1:
                    deltaY = mouseY - lastY
                    reslice.Update()
                    sliceSpacing = reslice.GetOutput().GetSpacing()[2]
                    matrix = reslice.GetResliceAxes()
                    # move the center point that we are slicing through
                    center = matrix.MultiplyPoint(
                        (0, 0, sliceSpacing * deltaY, 1))
                    matrix.SetElement(0, 3, center[0])
                    matrix.SetElement(1, 3, center[1])
                    matrix.SetElement(2, 3, center[2])
                    window.Render()
                else:
                    interactorStyle.OnMouseMove()

            interactorStyle.AddObserver("MouseMoveEvent", MouseMoveCallback)
            interactorStyle.AddObserver("LeftButtonPressEvent", ButtonCallback)
            interactorStyle.AddObserver("LeftButtonReleaseEvent",
                                        ButtonCallback)

            renWin.Render()

            # vtkweb
            self.getApplication().GetObjectIdMap().SetActiveObject(
                "VIEW", renWin)
Ejemplo n.º 18
0
    def initialize(self):
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(
            protocols.vtkWebPublishImageDelivery(decode=False))
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Update authentication key to use
        self.updateSecret(_WebCone.authKey)

        # tell the C++ web app to use no encoding.
        # ParaViewWebPublishImageDelivery must be set to decode=False to match.
        self.getApplication().SetImageEncoding(0)

        # Create default pipeline (Only once for all the session)
        if not _WebCone.view:
            # VTK specific code
            renderer = vtk.vtkRenderer()
            renderWindow = vtk.vtkRenderWindow()
            renderWindow.AddRenderer(renderer)

            renderWindowInteractor = vtk.vtkRenderWindowInteractor()
            renderWindowInteractor.SetRenderWindow(renderWindow)
            renderWindowInteractor.GetInteractorStyle(
            ).SetCurrentStyleToTrackballCamera()

            # cone = vtk.vtkConeSource()
            # mapper = vtk.vtkPolyDataMapper()
            # actor = vtk.vtkActor()

            # mapper.SetInputConnection(cone.GetOutputPort())
            # actor.SetMapper(mapper)

            # renderer.AddActor(actor)

            # load nrrd
            reader = vtk.vtkNrrdReader()
            reader.SetFileName('C:\\Users\\Mat\\Desktop\\tardiva3.0.nrrd')
            reader.Update()

            # The volume will be displayed by ray-cast alpha compositing.
            # A ray-cast mapper is needed to do the ray-casting.
            # volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
            volume_mapper = vtk.vtkSmartVolumeMapper()
            volume_mapper.SetInputConnection(reader.GetOutputPort())
            volume_mapper.SetSampleDistance(0.5)

            # The color transfer function maps voxel intensities to colors.
            # It is modality-specific, and often anatomy-specific as well.
            # The goal is to one color for flesh (between 500 and 1000)
            # and another color for bone (1150 and over).
            volume_color = vtk.vtkColorTransferFunction()
            volume_color.AddRGBPoint(0, 0.2, 0.2, 0.7)
            volume_color.AddRGBPoint(500, 240.0 / 255.0, 184.0 / 255.0,
                                     160.0 / 255.0)
            volume_color.AddRGBPoint(1000, 240.0 / 255.0, 184.0 / 255.0,
                                     160.0 / 255.0)
            volume_color.AddRGBPoint(1150, 1.0, 1.0, 240.0 / 255.0)  # Ivory

            # The opacity transfer function is used to control the opacity
            # of different tissue types.
            volume_scalar_opacity = vtk.vtkPiecewiseFunction()
            volume_scalar_opacity.AddPoint(0, 0.00)
            volume_scalar_opacity.AddPoint(500, 0.15)
            volume_scalar_opacity.AddPoint(1000, 0.15)
            volume_scalar_opacity.AddPoint(1150, 0.85)

            # The gradient opacity function is used to decrease the opacity
            # in the 'flat' regions of the volume while maintaining the opacity
            # at the boundaries between tissue types.  The gradient is measured
            # as the amount by which the intensity changes over unit distance.
            # For most medical data, the unit distance is 1mm.
            volume_gradient_opacity = vtk.vtkPiecewiseFunction()
            volume_gradient_opacity.AddPoint(0, 0.0)
            volume_gradient_opacity.AddPoint(90, 0.5)
            volume_gradient_opacity.AddPoint(100, 1.0)

            # The VolumeProperty attaches the color and opacity functions to the
            # volume, and sets other volume properties.  The interpolation should
            # be set to linear to do a high-quality rendering.  The ShadeOn option
            # turns on directional lighting, which will usually enhance the
            # appearance of the volume and make it look more '3D'.  However,
            # the quality of the shading depends on how accurately the gradient
            # of the volume can be calculated, and for noisy data the gradient
            # estimation will be very poor.  The impact of the shading can be
            # decreased by increasing the Ambient coefficient while decreasing
            # the Diffuse and Specular coefficient.  To increase the impact
            # of shading, decrease the Ambient and increase the Diffuse and Specular.
            volume_property = vtk.vtkVolumeProperty()
            volume_property.SetColor(volume_color)
            volume_property.SetScalarOpacity(volume_scalar_opacity)
            volume_property.SetGradientOpacity(volume_gradient_opacity)
            volume_property.SetInterpolationTypeToLinear()
            volume_property.ShadeOn()
            volume_property.SetAmbient(0.4)
            volume_property.SetDiffuse(0.6)
            volume_property.SetSpecular(0.2)

            # The vtkVolume is a vtkProp3D (like a vtkActor) and controls the position
            # and orientation of the volume in world coordinates.
            volumeActor = vtk.vtkVolume()
            volumeActor.SetMapper(volume_mapper)
            volumeActor.SetProperty(volume_property)

            # Finally, add the volume to the renderer
            renderer.AddActor(volumeActor)

            ##########################
            # renderer.AddActor(actor)

            # render
            renderer.ResetCamera()
            renderWindow.Render()

            # VTK Web application specific
            _WebCone.view = renderWindow
            self.getApplication().GetObjectIdMap().SetActiveObject(
                "VIEW", renderWindow)
Ejemplo n.º 19
0
    def initialize(self):
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Update authentication key to use
        self.updateSecret(_WebCone.authKey)

        # Create default pipeline (Only once for all the session)
        if not _WebCone.view:

            def GetDiagonalFromBounds(bounds):
                box = vtk.vtkBoundingBox(bounds)
                box.SetBounds(bounds)
                distance = box.GetDiagonalLength()
                return distance
                
            def setupCamera( renWin, ren, width, height ):
                print("setting up camera")
                renWin.SetSize( width, height )
                camera = ren.GetActiveCamera()
                cameraDistance = 10
                sliceHalfThickness = 1
                xFocal = ( width - 1 ) / 2.0
                yFocal = ( height - 1 ) / 2.0
                #camera.SetFocalPoint( xFocal, yFocal, 0.0 )
                camera.SetPosition( xFocal, yFocal, cameraDistance )
                camera.SetViewUp( 0, 1, 0 )
                camera.SetClippingRange( cameraDistance - sliceHalfThickness, cameraDistance + sliceHalfThickness )
                #camera.SetParallelScale( ( height - 1 ) / 2.0 )
                camera.ParallelProjectionOn()

            try:
                # Create the renderer, the render window, and the interactor. The renderer
                # draws into the render window, the interactor enables mouse- and
                # keyboard-based interaction with the scene.
                ren = vtk.vtkRenderer()
                renWin = vtk.vtkRenderWindow()
                renWin.AddRenderer(ren)
                iren = vtk.vtkRenderWindowInteractor()
                iren.SetRenderWindow(renWin)
                interactorStyle = vtk.vtkInteractorStyleImage()
                iren.SetInteractorStyle(interactorStyle)
                
                cred = credentials()

                mydb = mysql.connector.connect(
                  host="localhost",
                  user=cred[0],
                  password=cred[1],
                  database="iqweb"
                )

                mycursor = mydb.cursor()
                sql = "SELECT path FROM image WHERE seriesuid = %s"
                params = (self.uid,)
                mycursor.execute(sql, params)

                files = mycursor.fetchall()
                fileset = vtk.vtkStringArray()
                for file in files:
                    fileset.InsertNextValue(file[0])

                sorter = vtk.vtkDICOMFileSorter()
                sorter.SetInputFileNames(fileset)
                sorter.Update()

                sortedFiles = vtk.vtkStringArray()
                sortedFiles = sorter.GetFileNamesForSeries(0)

                reader = vtk.vtkDICOMReader()
                reader.SetFileNames(sortedFiles);
                reader.Update()

                # Calculate the center of the volume
                reader.Update()
                (xMin, xMax, yMin, yMax, zMin, zMax) = reader.GetExecutive().GetWholeExtent(reader.GetOutputInformation(0))
                (xSpacing, ySpacing, zSpacing) = reader.GetOutput().GetSpacing()
                (x0, y0, z0) = reader.GetOutput().GetOrigin()
                
                origin = [x0, y0, z0]
                spacing = [xSpacing, ySpacing, zSpacing]
                extent = [xMin, xMax, yMin, yMax, zMin, zMax]
                bounds = [ extent[0]/spacing[0], extent[1]/spacing[0], extent[2]/spacing[1], extent[3]/spacing[1], extent[4]/spacing[2], extent[5]/spacing[2] ] 
                diagonal = GetDiagonalFromBounds(bounds)
                originOut = [diagonal * spacing[0]/2, -diagonal * spacing[1]/2]


                center = [x0 + xSpacing * 0.5 * (xMin + xMax),
                          y0 + ySpacing * 0.5 * (yMin + yMax),
                          z0 + zSpacing * 0.5 * (zMin + zMax)]

                # Matrices for axial, coronal, sagittal, oblique view orientations
                axial = vtk.vtkMatrix4x4()
                axial.DeepCopy((1, 0, 0, center[0],
                                0, 1, 0, center[1],
                                0, 0, 1, center[2],
                                0, 0, 0, 1))

                coronal = vtk.vtkMatrix4x4()
                coronal.DeepCopy((1, 0, 0, center[0],
                                  0, 0, 1, center[1],
                                  0,-1, 0, center[2],
                                  0, 0, 0, 1))

                sagittal = vtk.vtkMatrix4x4()
                sagittal.DeepCopy((0, 0,-1, center[0],
                                   1, 0, 0, center[1],
                                   0,-1, 0, center[2],
                                   0, 0, 0, 1))

                # Extract a slice in the desired orientation
                reslice = vtk.vtkImageReslice()
                reslice.SetInputConnection(reader.GetOutputPort())
                reslice.SetOutputDimensionality(2)
                #reslice.SetOutputOrigin(origin)
                reslice.SetResliceAxes(axial)
                if self.orientation == "coronal":
                    reslice.SetResliceAxes(coronal)
                if self.orientation == "sagittal":
                    reslice.SetResliceAxes(sagittal)
                reslice.SetInterpolationModeToLinear()

                meta = reader.GetMetaData();

                level = meta.Get(vtk.vtkDICOMTag(0x0028,0x1050)).AsUTF8String().split("\\")[0]
                window = meta.Get(vtk.vtkDICOMTag(0x0028,0x1051)).AsUTF8String().split("\\")[0]

                range1 = int(level) - int(window)/2
                range2 = int(level) + int(window)/2

                # Create a greyscale lookup table
                table = vtk.vtkLookupTable()
                table.SetRange(range1, range2) # image intensity range
                table.SetValueRange(0.0, 1.0) # from black to white
                table.SetSaturationRange(0.0, 0.0) # no color saturation
                table.SetRampToLinear()
                table.Build()

                # Map the image through the lookup table
                color = vtk.vtkImageMapToColors()
                color.SetLookupTable(table)
                color.SetInputConnection(reslice.GetOutputPort())

                # Display the image
                actor = vtk.vtkImageActor()
                actor.GetMapper().SetInputConnection(color.GetOutputPort())

                ren.AddActor(actor)


                # Create callbacks for slicing the image
                actions = {}
                actions["Slicing"] = 0

                def ButtonCallback(obj, event):
                    if event == "LeftButtonPressEvent":
                        actions["Slicing"] = 1
                    else:
                        actions["Slicing"] = 0

                def MouseMoveCallback(obj, event):
                    (lastX, lastY) = iren.GetLastEventPosition()
                    (mouseX, mouseY) = iren.GetEventPosition()
                    if actions["Slicing"] == 1:
                        deltaY = mouseY - lastY
                        reslice.Update()
                        sliceSpacing = reslice.GetOutput().GetSpacing()[2]
                        matrix = reslice.GetResliceAxes()
                        # move the center point that we are slicing through
                        center = matrix.MultiplyPoint((0, 0, sliceSpacing*deltaY, 1))
                        matrix.SetElement(0, 3, center[0])
                        matrix.SetElement(1, 3, center[1])
                        matrix.SetElement(2, 3, center[2])
                        window.Render()
                    else:
                        interactorStyle.OnMouseMove()


                interactorStyle.AddObserver("MouseMoveEvent", MouseMoveCallback)
                interactorStyle.AddObserver("LeftButtonPressEvent", ButtonCallback)
                interactorStyle.AddObserver("LeftButtonReleaseEvent", ButtonCallback)

        
                xc = origin[0] + 0.5*(extent[0] + extent[1])*spacing[0]
                yc = origin[1] + 0.5*(extent[2] + extent[3])*spacing[1]
                xd = (extent[1] - extent[0] + 1)*spacing[0]
                yd = (extent[3] - extent[2] + 1)*spacing[1]
                
                
               
                ren.ResetCamera()
                camera = ren.GetActiveCamera()
                camera.Zoom(1.4)
                #d = camera.GetDistance()
                #camera.SetParallelScale(0.5 * yd)
                #camera.SetFocalPoint(xc, yc, 0.0)
                #camera.SetPosition(xc, yc, d)
                
                #setupCamera(renWin, ren, 320, 240)
                renWin.Render()
                
                # vtkweb
                self.getApplication().GetObjectIdMap().SetActiveObject("VIEW", renWin)
            except:
                print("Unexpected error:", sys.exc_info()[0])
                exit()
Ejemplo n.º 20
0
    def initialize(self):
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Update authentication key to use
        self.updateSecret(_WebCone.authKey)

        # Create default pipeline (Only once for all the session)
        if not _WebCone.view:

            try:
                # Create the renderer, the render window, and the interactor. The renderer
                # draws into the render window, the interactor enables mouse- and
                # keyboard-based interaction with the scene.
                ren = vtk.vtkRenderer()
                renWin = vtk.vtkRenderWindow()
                renWin.AddRenderer(ren)
                iren = vtk.vtkRenderWindowInteractor()
                iren.SetRenderWindow(renWin)
                iren.GetInteractorStyle().SetCurrentStyleToTrackballCamera()

                cred = credentials()

                mydb = mysql.connector.connect(host="localhost",
                                               user=cred[0],
                                               password=cred[1],
                                               database="iqweb")

                mycursor = mydb.cursor()
                sql = "SELECT path FROM image WHERE seriesuid = %s"
                params = (self.uid, )
                mycursor.execute(sql, params)

                files = mycursor.fetchall()
                fileset = vtk.vtkStringArray()
                for file in files:
                    fileset.InsertNextValue(file[0])

                sorter = vtk.vtkDICOMFileSorter()
                sorter.SetInputFileNames(fileset)
                sorter.Update()

                sortedFiles = vtk.vtkStringArray()
                sortedFiles = sorter.GetFileNamesForSeries(0)

                reader = vtk.vtkDICOMReader()
                reader.AutoRescaleOff()  #only because our preset is shifted
                reader.SetFileNames(sortedFiles)
                reader.Update()

                # The volume will be displayed by ray-cast alpha compositing.
                # A ray-cast mapper is needed to do the ray-casting, and a
                # compositing function is needed to do the compositing along the ray.
                volumeMapper = vtk.vtkGPUVolumeRayCastMapper()
                volumeMapper.SetInputConnection(reader.GetOutputPort())
                volumeMapper.SetBlendModeToComposite()
                volumeMapper.AutoAdjustSampleDistancesOff()
                volumeMapper.UseJitteringOn()

                # The color transfer function maps voxel intensities to colors.
                # It is modality-specific, and often anatomy-specific as well.
                # The goal is to one color for flesh (between 500 and 1000)
                # and another color for bone (1150 and over).
                volumeColor = vtk.vtkColorTransferFunction()
                volumeColor.AddRGBPoint(1024, 0.53125, 0.171875, 0.0507813)
                volumeColor.AddRGBPoint(1031, 0.488281, 0.148438, 0.0351563)
                volumeColor.AddRGBPoint(1000, 0.589844, 0.0257813, 0.0148438)
                volumeColor.AddRGBPoint(1170, 0.589844, 0.0257813, 0.0148438)
                volumeColor.AddRGBPoint(1181, 0.957031, 0.996094, 0.878906)
                volumeColor.AddRGBPoint(2024, 0.976563, 0.996094, 0.929688)
                volumeColor.AddRGBPoint(3014, 0.488281, 0.488281, 0.488281)

                # The opacity transfer function is used to control the opacity
                # of different tissue types.
                volumeScalarOpacity = vtk.vtkPiecewiseFunction()
                #volumeScalarOpacity.AddPoint(0,    0.00)
                #volumeScalarOpacity.AddPoint(500,  0.15)
                #volumeScalarOpacity.AddPoint(1000, 0.15)
                #volumeScalarOpacity.AddPoint(1150, 0.85)

                volumeScalarOpacity.AddPoint(1131, 0)
                volumeScalarOpacity.AddPoint(1463, 1)
                volumeScalarOpacity.AddPoint(3135, 1)

                # The gradient opacity function is used to decrease the opacity
                # in the "flat" regions of the volume while maintaining the opacity
                # at the boundaries between tissue types.  The gradient is measured
                # as the amount by which the intensity changes over unit distance.
                # For most medical data, the unit distance is 1mm.
                volumeGradientOpacity = vtk.vtkPiecewiseFunction()
                volumeGradientOpacity.AddPoint(0, 0.0)
                volumeGradientOpacity.AddPoint(90, 0.9)
                volumeGradientOpacity.AddPoint(100, 1.0)

                # The VolumeProperty attaches the color and opacity functions to the
                # volume, and sets other volume properties.  The interpolation should
                # be set to linear to do a high-quality rendering.  The ShadeOn option
                # turns on directional lighting, which will usually enhance the
                # appearance of the volume and make it look more "3D".  However,
                # the quality of the shading depends on how accurately the gradient
                # of the volume can be calculated, and for noisy data the gradient
                # estimation will be very poor.  The impact of the shading can be
                # decreased by increasing the Ambient coefficient while decreasing
                # the Diffuse and Specular coefficient.  To increase the impact
                # of shading, decrease the Ambient and increase the Diffuse and Specular.
                volumeProperty = vtk.vtkVolumeProperty()
                volumeProperty.SetColor(volumeColor)
                volumeProperty.SetScalarOpacity(volumeScalarOpacity)
                volumeProperty.SetGradientOpacity(volumeGradientOpacity)
                volumeProperty.SetInterpolationTypeToLinear()
                volumeProperty.ShadeOn()
                volumeProperty.SetAmbient(0.4)  # 0.1
                volumeProperty.SetDiffuse(0.5)  # 0.9
                volumeProperty.SetSpecular(0.2)  # 0.2
                volumeProperty.SetSpecularPower(10)

                # The vtkVolume is a vtkProp3D (like a vtkActor) and controls the position
                # and orientation of the volume in world coordinates.
                volume = vtk.vtkVolume()
                volume.SetMapper(volumeMapper)
                volume.SetProperty(volumeProperty)

                # Finally, add the volume to the renderer
                ren.AddViewProp(volume)

                # Set up an initial view of the volume.  The focal point will be the
                # center of the volume, and the camera position will be 400mm to the
                # patient's left (which is our right).
                camera = ren.GetActiveCamera()
                c = volume.GetCenter()
                camera.SetFocalPoint(c[0], c[1], c[2])
                camera.SetPosition(c[0] + 400, c[1], c[2])
                camera.SetViewUp(0, 0, -1)

                # Increase the size of the render window
                #renWin.SetSize(640, 480)
                #renWin.SetSize(432, 336)
                renWin.SetSize(320, 240)

                # Interact with the data.
                #iren.Initialize()
                renWin.Render()

                # vtkweb
                self.getApplication().GetObjectIdMap().SetActiveObject(
                    "VIEW", renWin)
            except:
                print("Unexpected error:", sys.exc_info()[0])
Ejemplo n.º 21
0
    def initialize(self):
        # Bring used components
        self.registerVtkWebProtocol(vtk_protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(vtk_protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(
            vtk_override_protocols.vtkWebPublishImageDelivery(decode=False))

        # Custom API
        self.registerVtkWebProtocol(VtkCone())

        # tell the C++ web app to use no encoding.
        # ParaViewWebPublishImageDelivery must be set to decode=False to match.
        self.getApplication().SetImageEncoding(0)

        # Update authentication key to use
        self.updateSecret(_Server.authKey)

        if not _Server.view:

            # draw the borders of a renderer's viewport
            def ViewportBorder(renderer, color, last):
                # points start at upper right and proceed anti-clockwise
                points = vtk.vtkPoints()
                points.SetNumberOfPoints(4)
                points.InsertPoint(0, 1, 1, 0)
                points.InsertPoint(1, 0, 1, 0)
                points.InsertPoint(2, 0, 0, 0)
                points.InsertPoint(3, 1, 0, 0)

                # create cells, and lines
                cells = vtk.vtkCellArray()
                cells.Initialize()

                lines = vtk.vtkPolyLine()

                # only draw last line if this is the last viewport
                # this prevents double vertical lines at right border
                # if different colors are used for each border, then do
                # not specify last
                if (last):
                    lines.GetPointIds().SetNumberOfIds(5)
                else:
                    lines.GetPointIds().SetNumberOfIds(4)

                for i in range(0, 4):
                    lines.GetPointIds().SetId(i, i)

                if (last):
                    lines.GetPointIds().SetId(4, 0)

                cells.InsertNextCell(lines)

                # now make tge polydata and display it
                poly = vtk.vtkPolyData()
                poly.Initialize()
                poly.SetPoints(points)
                poly.SetLines(cells)

                # use normalized viewport coordinates since
                # they are independent of window size
                coordinate = vtk.vtkCoordinate()
                coordinate.SetCoordinateSystemToNormalizedViewport()

                mapper = vtk.vtkPolyDataMapper2D()
                mapper.SetInputData(poly)
                mapper.SetTransformCoordinate(coordinate)

                actor = vtk.vtkActor2D()
                actor.SetMapper(mapper)
                actor.GetProperty().SetColor(color)
                actor.GetProperty().SetLineWidth(2.0)

                renderer.AddViewProp(actor)

            def getViewport(viewNr):
                if viewNr == 0:
                    return [0.0, 0.5, 0.5, 1.0]
                elif viewNr == 1:
                    return [0.5, 0.5, 1.0, 1.0]
                elif viewNr == 2:
                    return [0.0, 0.0, 0.5, 0.5]
                elif viewNr == 3:
                    return [0.5, 0.0, 1.0, 0.5]
                else:
                    logging.warning('invalid view nr {}'.format(viewNr))
                    return [0.0, 0.0, 1.0, 1.0]

            def doVolumeRendering(renWin, reader, viewNr):
                # The volume will be displayed by ray-cast alpha compositing.
                # A ray-cast mapper is needed to do the ray-casting, and a
                # compositing function is needed to do the compositing along the ray.
                volumeMapper = vtk.vtkGPUVolumeRayCastMapper()
                volumeMapper.SetInputConnection(reader.GetOutputPort())
                volumeMapper.SetBlendModeToComposite()
                volumeMapper.AutoAdjustSampleDistancesOff()
                volumeMapper.UseJitteringOn()

                offset = -1024

                # The color transfer function maps voxel intensities to colors.
                # It is modality-specific, and often anatomy-specific as well.
                # The goal is to one color for flesh (between 500 and 1000)
                # and another color for bone (1150 and over).
                volumeColor = vtk.vtkColorTransferFunction()
                volumeColor.AddRGBPoint(1024 + offset, 0.53125, 0.171875,
                                        0.0507813)
                volumeColor.AddRGBPoint(1031 + offset, 0.488281, 0.148438,
                                        0.0351563)
                volumeColor.AddRGBPoint(1000 + offset, 0.589844, 0.0257813,
                                        0.0148438)
                volumeColor.AddRGBPoint(1170 + offset, 0.589844, 0.0257813,
                                        0.0148438)
                volumeColor.AddRGBPoint(1181 + offset, 0.957031, 0.996094,
                                        0.878906)
                volumeColor.AddRGBPoint(2024 + offset, 0.976563, 0.996094,
                                        0.929688)
                volumeColor.AddRGBPoint(3014 + offset, 0.488281, 0.488281,
                                        0.488281)

                # The opacity transfer function is used to control the opacity
                # of different tissue types.
                volumeScalarOpacity = vtk.vtkPiecewiseFunction()
                #volumeScalarOpacity.AddPoint(0,    0.00)
                #volumeScalarOpacity.AddPoint(500,  0.15)
                #volumeScalarOpacity.AddPoint(1000, 0.15)
                #volumeScalarOpacity.AddPoint(1150, 0.85)

                volumeScalarOpacity.AddPoint(1131 + offset, 0)
                volumeScalarOpacity.AddPoint(1463 + offset, 1)
                volumeScalarOpacity.AddPoint(3135 + offset, 1)

                # The gradient opacity function is used to decrease the opacity
                # in the "flat" regions of the volume while maintaining the opacity
                # at the boundaries between tissue types.  The gradient is measured
                # as the amount by which the intensity changes over unit distance.
                # For most medical data, the unit distance is 1mm.
                volumeGradientOpacity = vtk.vtkPiecewiseFunction()
                volumeGradientOpacity.AddPoint(0, 0.0)
                volumeGradientOpacity.AddPoint(90, 0.9)
                volumeGradientOpacity.AddPoint(100, 1.0)

                # The VolumeProperty attaches the color and opacity functions to the
                # volume, and sets other volume properties.  The interpolation should
                # be set to linear to do a high-quality rendering.  The ShadeOn option
                # turns on directional lighting, which will usually enhance the
                # appearance of the volume and make it look more "3D".  However,
                # the quality of the shading depends on how accurately the gradient
                # of the volume can be calculated, and for noisy data the gradient
                # estimation will be very poor.  The impact of the shading can be
                # decreased by increasing the Ambient coefficient while decreasing
                # the Diffuse and Specular coefficient.  To increase the impact
                # of shading, decrease the Ambient and increase the Diffuse and Specular.
                volumeProperty = vtk.vtkVolumeProperty()
                volumeProperty.SetColor(volumeColor)
                volumeProperty.SetScalarOpacity(volumeScalarOpacity)
                volumeProperty.SetGradientOpacity(volumeGradientOpacity)
                volumeProperty.SetInterpolationTypeToLinear()
                volumeProperty.ShadeOn()
                volumeProperty.SetAmbient(0.4)  # 0.1
                volumeProperty.SetDiffuse(0.5)  # 0.9
                volumeProperty.SetSpecular(0.2)  # 0.2
                volumeProperty.SetSpecularPower(10)

                # The vtkVolume is a vtkProp3D (like a vtkActor) and controls the position
                # and orientation of the volume in world coordinates.
                volume = vtk.vtkVolume()
                volume.SetMapper(volumeMapper)
                volume.SetProperty(volumeProperty)

                ren = vtk.vtkRenderer()
                ren.SetBackground(0.0, 0.0, 0.0)
                ren.SetViewport(*getViewport(viewNr))
                renWin.AddRenderer(ren)

                # Finally, add the volume to the renderer
                ren.AddViewProp(volume)

                # Set up an initial view of the volume.  The focal point will be the
                # center of the volume, and the camera position will be 400mm to the
                # patient's left (which is our right).
                camera = ren.GetActiveCamera()
                c = volume.GetCenter()
                camera.SetFocalPoint(c[0], c[1], c[2])
                camera.SetPosition(c[0] + 400, c[1], c[2])
                camera.SetViewUp(0, 0, -1)
                ViewportBorder(ren, [1, 1, 1], True)

                ren.ResetCamera()

            def doReslice(renWin, reader, viewNr, orientation, level, window):

                # Calculate the center of the volume
                reader.Update()
                (xMin, xMax, yMin, yMax, zMin,
                 zMax) = reader.GetExecutive().GetWholeExtent(
                     reader.GetOutputInformation(0))
                (xSpacing, ySpacing,
                 zSpacing) = reader.GetOutput().GetSpacing()
                (x0, y0, z0) = reader.GetOutput().GetOrigin()

                center = [
                    x0 + xSpacing * 0.5 * (xMin + xMax),
                    y0 + ySpacing * 0.5 * (yMin + yMax),
                    z0 + zSpacing * 0.5 * (zMin + zMax)
                ]

                # Matrices for axial, coronal, sagittal, oblique view orientations
                axial = vtk.vtkMatrix4x4()
                axial.DeepCopy((1, 0, 0, center[0], 0, 1, 0, center[1], 0, 0,
                                1, center[2], 0, 0, 0, 1))

                coronal = vtk.vtkMatrix4x4()
                coronal.DeepCopy((1, 0, 0, center[0], 0, 0, 1, center[1], 0,
                                  -1, 0, center[2], 0, 0, 0, 1))

                sagittal = vtk.vtkMatrix4x4()
                sagittal.DeepCopy((0, 0, -1, center[0], 1, 0, 0, center[1], 0,
                                   -1, 0, center[2], 0, 0, 0, 1))

                # Extract a slice in the desired orientation
                reslice = vtk.vtkImageReslice()
                reslice.SetInputConnection(reader.GetOutputPort())
                reslice.SetOutputDimensionality(2)
                reslice.SetResliceAxes(axial)
                if orientation == "coronal":
                    reslice.SetResliceAxes(coronal)
                if orientation == "sagittal":
                    reslice.SetResliceAxes(sagittal)
                reslice.SetInterpolationModeToLinear()

                range1 = int(level) - int(window) / 2
                range2 = int(level) + int(window) / 2

                # Create a greyscale lookup table
                table = vtk.vtkLookupTable()
                table.SetRange(range1, range2)  # image intensity range
                table.SetValueRange(0.0, 1.0)  # from black to white
                table.SetSaturationRange(0.0, 0.0)  # no color saturation
                table.SetRampToLinear()
                table.Build()

                # Map the image through the lookup table
                color = vtk.vtkImageMapToColors()
                color.SetLookupTable(table)
                color.SetInputConnection(reslice.GetOutputPort())

                # Display the image
                actor = vtk.vtkImageActor()
                actor.GetMapper().SetInputConnection(color.GetOutputPort())

                cornerAnnotation = vtk.vtkCornerAnnotation()
                cornerAnnotation.SetLinearFontScaleFactor(1)
                cornerAnnotation.SetNonlinearFontScaleFactor(1)
                cornerAnnotation.SetMinimumFontSize(12)
                cornerAnnotation.SetMaximumFontSize(20)
                cornerAnnotation.SetText(0, "lower left")
                cornerAnnotation.SetText(1, "lower right")
                cornerAnnotation.SetText(2, "upper left")
                cornerAnnotation.SetText(3, "upper right")
                cornerAnnotation.GetTextProperty().SetColor(1, 1, 1)

                ren = vtk.vtkRenderer()
                ren.SetBackground(0.0, 0.0, 0.0)
                ren.AddActor(actor)
                #ren.AddViewProp( cornerAnnotation )
                ren.SetViewport(*getViewport(viewNr))
                renWin.AddRenderer(ren)
                ren.ResetCamera()

                camera = ren.GetActiveCamera()
                camera.Zoom(1.4)

                ViewportBorder(ren, [1, 1, 1], False)

                return reslice

            # Create the renderer, the render window, and the interactor. The renderer
            # draws into the render window, the interactor enables mouse- and
            # keyboard-based interaction with the scene.

            renWin = vtk.vtkRenderWindow()
            iren = vtk.vtkRenderWindowInteractor()
            iren.SetRenderWindow(renWin)
            interactorStyleImage = vtk.vtkInteractorStyleImage()
            interactorStyleTrackball = vtk.vtkInteractorStyleTrackballCamera()
            interactorStyleTrackball.SetMotionFactor(
                20
            )  # 10 is default, we need twice the speed to compensate the smaller viewport
            iren.SetInteractorStyle(interactorStyleImage)

            cred = credentials()

            mydb = mysql.connector.connect(host="localhost",
                                           user=cred[0],
                                           password=cred[1],
                                           database="iqweb")

            mycursor = mydb.cursor()
            sql = "SELECT path FROM image WHERE seriesuid = %s"
            params = (self.uid, )
            mycursor.execute(sql, params)

            files = mycursor.fetchall()
            fileset = vtk.vtkStringArray()
            for file in files:
                fileset.InsertNextValue(file[0])

            sorter = vtk.vtkDICOMFileSorter()
            sorter.SetInputFileNames(fileset)
            sorter.Update()

            sortedFiles = vtk.vtkStringArray()
            sortedFiles = sorter.GetFileNamesForSeries(0)

            reader = vtk.vtkDICOMReader()
            reader.SetFileNames(sortedFiles)
            reader.Update()

            meta = reader.GetMetaData()

            level = meta.Get(vtk.vtkDICOMTag(
                0x0028, 0x1050)).AsUTF8String().split("\\")[0]
            window = meta.Get(vtk.vtkDICOMTag(
                0x0028, 0x1051)).AsUTF8String().split("\\")[0]

            resliceList = []

            resliceList.append(
                doReslice(renWin, reader, 0, 'axial', level, window))

            resliceList.append(
                doReslice(renWin, reader, 1, 'coronal', level, window))

            resliceList.append(
                doReslice(renWin, reader, 2, 'sagittal', level, window))

            doVolumeRendering(renWin, reader, 3)

            # Create callbacks for slicing the image
            actions = {}
            actions["Slicing"] = 0
            actions["ViewNr"] = 0

            def GetViewNrOnMousePosition(iren):
                (mouseX, mouseY) = iren.GetEventPosition()
                (sizeX, sizeY) = iren.GetSize()
                ratioX = mouseX / sizeX
                ratioY = mouseY / sizeY
                if (ratioX < 0.5 and ratioY < 0.5):
                    return 2
                elif (ratioX > 0.5 and ratioY < 0.5):
                    return 3
                elif (ratioX < 0.5 and ratioY > 0.5):
                    return 0
                else:
                    return 1

            def ButtonCallback(obj, event):
                actions["ViewNr"] = GetViewNrOnMousePosition(iren)
                if (actions["ViewNr"] >= 0 and actions["ViewNr"] <= 2):
                    iren.SetInteractorStyle(interactorStyleImage)
                else:
                    iren.SetInteractorStyle(interactorStyleTrackball)

                if event == "LeftButtonPressEvent":
                    actions["Slicing"] = 1
                    iren.GetInteractorStyle().OnLeftButtonDown()
                else:
                    actions["Slicing"] = 0
                    iren.GetInteractorStyle().OnLeftButtonUp()

            def MouseMoveCallback(obj, event):
                (lastX, lastY) = iren.GetLastEventPosition()
                (mouseX, mouseY) = iren.GetEventPosition()
                if actions["Slicing"] == 1 and actions[
                        "ViewNr"] >= 0 and actions["ViewNr"] <= 2:
                    deltaY = mouseY - lastY
                    reslice = resliceList[actions["ViewNr"]]
                    reslice.Update()
                    sliceSpacing = reslice.GetOutput().GetSpacing()[2]
                    matrix = reslice.GetResliceAxes()
                    # move the center point that we are slicing through
                    center = matrix.MultiplyPoint(
                        (0, 0, sliceSpacing * deltaY, 1))
                    matrix.SetElement(0, 3, center[0])
                    matrix.SetElement(1, 3, center[1])
                    matrix.SetElement(2, 3, center[2])
                    renWin.Render()
                else:
                    currentViewNr = GetViewNrOnMousePosition(iren)
                    if (currentViewNr == 3):
                        iren.GetInteractorStyle().OnMouseMove()

            interactorStyleTrackball.AddObserver("MouseMoveEvent",
                                                 MouseMoveCallback)
            interactorStyleTrackball.AddObserver("LeftButtonPressEvent",
                                                 ButtonCallback)
            interactorStyleTrackball.AddObserver("LeftButtonReleaseEvent",
                                                 ButtonCallback)

            interactorStyleImage.AddObserver("MouseMoveEvent",
                                             MouseMoveCallback)
            interactorStyleImage.AddObserver("LeftButtonPressEvent",
                                             ButtonCallback)
            interactorStyleImage.AddObserver("LeftButtonReleaseEvent",
                                             ButtonCallback)

            renWin.Render()

            # vtkweb
            self.getApplication().GetObjectIdMap().SetActiveObject(
                "VIEW", renWin)
Ejemplo n.º 22
0
    def initialize(self):
        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        # Image delivery
        # 1. Original method where the client ask for each image individually
        #self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        # 2. Improvement on the initial protocol to allow images to be pushed
        # from the server without any client request (i.e.: animation, LOD, …)
        self.registerVtkWebProtocol(
            protocols.vtkWebPublishImageDelivery(decode=False))
        # Protocol for sending geometry for the vtk.js synchronized render
        # window
        # For local rendering using vtk.js
        #self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())
        #self.registerVtkWebProtocol(protocols.vtkWebLocalRendering())

        # Custom API
        self.registerVtkWebProtocol(FuryProtocol())

        # Tell the C++ web app to use no encoding.
        # ParaViewWebPublishImageDelivery must be set to decode=False to match.
        # RAW instead of base64
        self.getApplication().SetImageEncoding(0)

        # Update authentication key to use
        self.updateSecret(_WebSpheres.authKey)

        # Create default pipeline (Only once for all the session)
        if not _WebSpheres.view:
            # FURY specific code
            scene = window.Scene()
            scene.background((1, 1, 1))

            n_points = 10000
            translate = 100
            centers = translate * np.random.rand(n_points, 3) - translate / 2
            colors = 255 * np.random.rand(n_points, 3)
            radius = np.random.rand(n_points)
            fake_sphere = \
                """
                float len = length(point);
                float radius = 1.;
                if(len > radius)
                    {discard;}

                vec3 normalizedPoint = normalize(vec3(point.xy, sqrt(1. - len)));
                vec3 direction = normalize(vec3(1., 1., 1.));
                float df_1 = max(0, dot(direction, normalizedPoint));
                float sf_1 = pow(df_1, 24);
                fragOutput0 = vec4(max(df_1 * color, sf_1 * vec3(1)), 1);
                """
            spheres_actor = actor.billboard(centers,
                                            colors=colors,
                                            scales=radius,
                                            fs_impl=fake_sphere)

            scene.add(spheres_actor)
            scene.add(actor.axes())

            showm = window.ShowManager(scene)
            # For debugging purposes
            #showm.render()

            ren_win = showm.window

            ren_win_interactor = vtk.vtkRenderWindowInteractor()
            ren_win_interactor.SetRenderWindow(ren_win)
            ren_win_interactor.GetInteractorStyle().\
                SetCurrentStyleToTrackballCamera()
            ren_win_interactor.EnableRenderOff()

            # VTK Web application specific
            _WebSpheres.view = ren_win
            self.getApplication().GetObjectIdMap().SetActiveObject(
                'VIEW', ren_win)
Ejemplo n.º 23
0
    def initialize(self):
        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Update authentication key to use
        self.updateSecret(_WebSpheres.authKey)

        # Create default pipeline (Only once for all the session)
        if not _WebSpheres.view:
            # FURY specific code
            scene = window.Scene()
            scene.background((1, 1, 1))

            n_points = 1000000
            translate = 100
            colors = 255 * np.random.rand(n_points, 3)
            centers = translate * np.random.rand(n_points, 3) - translate / 2
            radius = np.random.rand(n_points) / 10

            polydata = vtk.vtkPolyData()

            verts = np.array([[0.0, 0.0, 0.0], [0.0, 1.0, 0.0],
                              [1.0, 1.0, 0.0], [1.0, 0.0, 0.0]])
            verts -= np.array([0.5, 0.5, 0])

            big_verts = np.tile(verts, (centers.shape[0], 1))
            big_cents = np.repeat(centers, verts.shape[0], axis=0)

            big_verts += big_cents

            # print(big_verts)

            big_scales = np.repeat(radius, verts.shape[0], axis=0)

            # print(big_scales)

            big_verts *= big_scales[:, np.newaxis]

            # print(big_verts)

            tris = np.array([[0, 1, 2], [2, 3, 0]], dtype='i8')

            big_tris = np.tile(tris, (centers.shape[0], 1))
            shifts = np.repeat(
                np.arange(0, centers.shape[0] * verts.shape[0],
                          verts.shape[0]), tris.shape[0])

            big_tris += shifts[:, np.newaxis]

            # print(big_tris)

            big_cols = np.repeat(colors, verts.shape[0], axis=0)

            # print(big_cols)

            big_centers = np.repeat(centers, verts.shape[0], axis=0)

            # print(big_centers)

            big_centers *= big_scales[:, np.newaxis]

            # print(big_centers)

            set_polydata_vertices(polydata, big_verts)
            set_polydata_triangles(polydata, big_tris)
            set_polydata_colors(polydata, big_cols)

            vtk_centers = numpy_to_vtk(big_centers, deep=True)
            vtk_centers.SetNumberOfComponents(3)
            vtk_centers.SetName("center")
            polydata.GetPointData().AddArray(vtk_centers)

            canvas_actor = get_actor_from_polydata(polydata)
            canvas_actor.GetProperty().BackfaceCullingOff()

            mapper = canvas_actor.GetMapper()

            mapper.MapDataArrayToVertexAttribute(
                "center", "center", vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS,
                -1)

            vtk_major_version = vtk.vtkVersion.GetVTKMajorVersion()
            vtk_minor_version = vtk.vtkVersion.GetVTKMinorVersion()
            if vtk_major_version > 8 or (vtk_major_version == 8
                                         and vtk_minor_version >= 90):
                mapper = canvas_actor.GetShaderProperty()

            mapper.AddShaderReplacement(
                vtk.vtkShader.Vertex, "//VTK::ValuePass::Dec", True, """
                //VTK::ValuePass::Dec
                in vec3 center;

                out vec3 centeredVertexMC;
                """, False)

            mapper.AddShaderReplacement(
                vtk.vtkShader.Vertex, "//VTK::ValuePass::Impl", True, """
                //VTK::ValuePass::Impl
                centeredVertexMC = vertexMC.xyz - center;
                float scalingFactor = 1. / abs(centeredVertexMC.x);
                centeredVertexMC *= scalingFactor;

                vec3 cameraRight = vec3(MCVCMatrix[0][0], MCVCMatrix[1][0],
                                        MCVCMatrix[2][0]);
                vec3 cameraUp = vec3(MCVCMatrix[0][1], MCVCMatrix[1][1],
                                     MCVCMatrix[2][1]);
                vec2 squareVertices = vec2(.5, -.5);
                vec3 vertexPosition = center + cameraRight * squareVertices.x *
                                      vertexMC.x + cameraUp * squareVertices.y *
                                      vertexMC.y;
                gl_Position = MCDCMatrix * vec4(vertexPosition, 1.);
                gl_Position /= gl_Position.w;
                """, False)

            mapper.AddShaderReplacement(
                vtk.vtkShader.Fragment, "//VTK::ValuePass::Dec", True, """
                //VTK::ValuePass::Dec
                in vec3 centeredVertexMC;
                """, False)

            mapper.AddShaderReplacement(
                vtk.vtkShader.Fragment, "//VTK::Light::Impl", True, """
                // Renaming variables passed from the Vertex Shader
                vec3 color = vertexColorVSOutput.rgb;
                vec3 point = centeredVertexMC;
                float len = length(point);
                // VTK Fake Spheres
                float radius = 1.;
                if(len > radius)
                  discard;
                vec3 normalizedPoint = normalize(vec3(point.xy, sqrt(1. - len)));
                vec3 direction = normalize(vec3(1., -1., 1.));
                float df = max(0, dot(direction, normalizedPoint));
                float sf = pow(df, 24);
                fragOutput0 = vec4(max(df * color, sf * vec3(1)), 1);
                """, False)

            scene.add(canvas_actor)
            #scene.add(actor.axes())

            showm = window.ShowManager(scene)

            renderWindow = showm.window

            # VTK Web application specific
            _WebSpheres.view = renderWindow
            self.getApplication().GetObjectIdMap().\
                SetActiveObject('VIEW', renderWindow)
Ejemplo n.º 24
0
    def initialize(self):
        print(sys.version)
        global renderer, renderWindow, renderWindowInteractor  #, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        # self.registerVtkWebProtocol(protocols.vtkWebPublishImageDelivery(decode=False))
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Update authentication key to use
        self.updateSecret(_WebCone.authKey)

        # tell the C++ web app to use no encoding. vtkWebPublishImageDelivery must be set to decode=False to match.
        # self.getApplication().SetImageEncoding(0)

        # Create default pipeline (Only once for all the session)
        if not _WebCone.view:
            TEST_HORIZON = False

            if not TEST_HORIZON:
                showm = window.ShowManager()
                showm.initialize()

                slider_demo = self.build_slider_demo()
                brain_demo = self.build_brain_demo(showm)
                bundle_demo = self.build_bundle_demo()
                surface_demo = self.build_surface_demo(showm)

                examples = [slider_demo, brain_demo]
                examples_names = [name for name, act in examples]

                listbox = ui.ListBox2D(values=examples_names,
                                       position=(10, 300),
                                       size=(300, 80),
                                       multiselection=False)

                def hide_all_examples():
                    for _, l_act in examples:
                        for element in l_act:
                            if hasattr(element, 'add_to_scene'):
                                element.set_visibility(False)
                            else:
                                element.SetVisibility(False)

                def display_element():
                    hide_all_examples()
                    example = examples[examples_names.index(
                        listbox.selected[0])]
                    for element in example[1]:
                        if hasattr(element, 'add_to_scene'):
                            element.set_visibility(True)
                        else:
                            element.SetVisibility(True)

                listbox.on_change = display_element
                listbox.panel.color = (1.0, 1.0, 1.0)
                listbox.panel.opacity = 0.3
                hide_all_examples()
                showm.scene.add(listbox)
                for _, l_act in examples:
                    for element in l_act:
                        showm.scene.add(element)

                # VTK specific code
                renderer = showm.scene
                renderWindow = showm.window
                renderWindowInteractor = showm.iren

            else:
                affine = np.diag([2., 1, 1, 1]).astype('f8')
                data = 255 * np.random.rand(150, 150, 150)
                images = [(data, affine)]
                from dipy.segment.tests.test_bundles import f1
                streamlines = f1.copy()
                tractograms = [streamlines]

                Horizon(tractograms,
                        images=images,
                        cluster=True,
                        cluster_thr=5,
                        random_colors=False,
                        length_lt=np.inf,
                        length_gt=0,
                        clusters_lt=np.inf,
                        clusters_gt=0,
                        world_coords=True)

            def calc_suare(numbers, showm):
                print("Calculate square numbers")
                for n in numbers:
                    time.sleep(1)
                    print("square:", n * n)
                    showm.scene.GetActiveCamera().Azimuth(10)
                    # showm.render()
                    # view = self.getApplication().GetObjectIdMap().GetActiveObject("VIEW")

            # arr = np.random.rand(100)
            # t1 = threading.Thread(target=calc_suare, args=(arr, showm))
            # t1.start()
            print("Auth-key {}".format(_WebCone.authKey))
            print('Initialization  --- OK')
            print('Starting FURY SERVER')
            # VTK Web application specific
            _WebCone.view = renderWindow
            self.getApplication().GetObjectIdMap().SetActiveObject(
                "VIEW", renderWindow)