示例#1
0
    def InitRenderPasses(self):
        """Initiate and add realism passes to renderer"""
        cameraP = vtk.vtkCameraPass()
        opaque = vtk.vtkOpaquePass()
        peeling = vtk.vtkDepthPeelingPass()
        peeling.SetMaximumNumberOfPeels(1000)
        peeling.SetOcclusionRatio(0.1)

        translucent = vtk.vtkTranslucentPass()
        peeling.SetTranslucentPass(translucent)

        volume = vtk.vtkVolumetricPass()
        overlay = vtk.vtkOverlayPass()

        lights = vtk.vtkLightsPass()
        opaqueSequence = vtk.vtkSequencePass()

        passes2 = vtk.vtkRenderPassCollection()
        passes2.AddItem(lights)
        passes2.AddItem(opaque)
        opaqueSequence.SetPasses(passes2)

        opaqueCameraPass = vtk.vtkCameraPass()
        opaqueCameraPass.SetDelegatePass(opaqueSequence)

        shadowsBaker = vtk.vtkShadowMapBakerPass()
        shadowsBaker.SetOpaqueSequence(opaqueCameraPass)
        shadowsBaker.SetResolution(SHADOW_RENDER_RES)

        shadows = vtk.vtkShadowMapPass()
        shadows.SetShadowMapBakerPass(shadowsBaker)
        shadows.SetOpaqueSequence(opaqueSequence)

        seq = vtk.vtkSequencePass()
        passes = vtk.vtkRenderPassCollection()
        passes.AddItem(shadowsBaker)
        passes.AddItem(shadows)
        passes.AddItem(lights)
        passes.AddItem(peeling)
        passes.AddItem(volume)
        passes.AddItem(overlay)
        seq.SetPasses(passes)
        cameraP.SetDelegatePass(seq)

        self.renderer.SetPass(cameraP)
示例#2
0
    def __init__(self, Skeleton, Scene, Animator, idx):
        """
            Skeleton will be a list
        """
        self.ren = vtk.vtkRenderer()
        self.renWin = vtk.vtkRenderWindow()
        self.renWin.AddRenderer(self.ren)
        self.iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.renWin)
        self.style = vtk.vtkInteractorStyleTrackballCamera()
        self.iren.SetInteractorStyle(self.style)
        self.ren.GradientBackgroundOn()
        self.ren.SetBackground(0, 0, 0)
        self.ren.SetBackground2(0, 0, 0)
        self.renWin.SetSize(800, 800)
        self.animator = Animator

        for i in range(len(Skeleton)):
            self.addSkeleton(Skeleton[i])

        self.addScene(Scene)

        self.cameraP = vtk.vtkCameraPass()
        self.lights = vtk.vtkLightsPass()
        self.shadowsBaker = vtk.vtkShadowMapBakerPass()
        self.shadowsBaker.SetResolution(4096)

        self.shadows = vtk.vtkShadowMapPass()
        self.shadows.SetShadowMapBakerPass(self.shadowsBaker)

        self.seq = vtk.vtkSequencePass()
        self.passes = vtk.vtkRenderPassCollection()
        self.passes.AddItem(self.shadowsBaker)
        self.passes.AddItem(self.shadows)
        self.passes.AddItem(self.lights)
        self.seq.SetPasses(self.passes)
        self.cameraP.SetDelegatePass(self.seq)

        self.ren.SetPass(self.cameraP)
        self.iren.Initialize()
        self.ren.ResetCamera()
        self.ren.GetActiveCamera().ParallelProjectionOff()
        self.ren.GetActiveCamera().Azimuth(180)
        self.ren.GetActiveCamera().Pitch(1)
        self.ren.GetActiveCamera().Elevation(20)
        self.ren.GetActiveCamera().SetViewAngle(55)
        self.renWin.Render()

        self.idx = idx
        self.frame_time = 33  # 8
        self.iren.AddObserver("KeyPressEvent", self.keyPress)
        self.iren.AddObserver('TimerEvent', Animator.animate)
        self.timerId = self.iren.CreateRepeatingTimer(self.frame_time)
        self.iren.Start()
        print(self.idx)
示例#3
0
def main():
    fn = get_program_parameters()
    if fn:
        polyData = ReadPolyData(fn)
    else:
        # Use a sphere
        source = vtk.vtkSphereSource()
        source.SetThetaResolution(100)
        source.SetPhiResolution(100)
        source.Update()
        polyData = source.GetOutput()

    colors = vtk.vtkNamedColors()
    colors.SetColor('HighNoonSun', [255, 255, 251, 255])  # Color temp. 5400°K
    colors.SetColor('100W Tungsten',
                    [255, 214, 170, 255])  # Color temp. 2850°K

    renderer = vtk.vtkRenderer()
    renderer.SetBackground(colors.GetColor3d('Silver'))

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetSize(640, 480)
    renderWindow.AddRenderer(renderer)

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    light1 = vtk.vtkLight()
    light1.SetFocalPoint(0, 0, 0)
    light1.SetPosition(0, 1, 0.2)
    light1.SetColor(colors.GetColor3d('HighNoonSun'))
    light1.SetIntensity(0.3)
    renderer.AddLight(light1)

    light2 = vtk.vtkLight()
    light2.SetFocalPoint(0, 0, 0)
    light2.SetPosition(1.0, 1.0, 1.0)
    light2.SetColor(colors.GetColor3d('100W Tungsten'))
    light2.SetIntensity(0.8)
    renderer.AddLight(light2)

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(polyData)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetAmbientColor(colors.GetColor3d('SaddleBrown'))
    actor.GetProperty().SetDiffuseColor(colors.GetColor3d('Sienna'))
    actor.GetProperty().SetSpecularColor(colors.GetColor3d('White'))
    actor.GetProperty().SetSpecular(0.51)
    actor.GetProperty().SetDiffuse(0.7)
    actor.GetProperty().SetAmbient(0.7)
    actor.GetProperty().SetSpecularPower(30.0)
    actor.GetProperty().SetOpacity(1.0)
    renderer.AddActor(actor)

    # Add a plane
    bounds = polyData.GetBounds()

    rnge = [0] * 3
    rnge[0] = bounds[1] - bounds[0]
    rnge[1] = bounds[3] - bounds[2]
    rnge[2] = bounds[5] - bounds[4]
    print("range: ", ', '.join(["{0:0.6f}".format(i) for i in rnge]))
    expand = 1.0
    THICKNESS = rnge[2] * 0.1
    plane = vtk.vtkCubeSource()
    plane.SetCenter((bounds[1] + bounds[0]) / 2.0, bounds[2] + THICKNESS / 2.0,
                    (bounds[5] + bounds[4]) / 2.0)
    plane.SetXLength(bounds[1] - bounds[0] + (rnge[0] * expand))
    plane.SetYLength(THICKNESS)
    plane.SetZLength(bounds[5] - bounds[4] + (rnge[2] * expand))

    planeMapper = vtk.vtkPolyDataMapper()
    planeMapper.SetInputConnection(plane.GetOutputPort())

    planeActor = vtk.vtkActor()
    planeActor.SetMapper(planeMapper)
    renderer.AddActor(planeActor)

    renderWindow.SetMultiSamples(0)

    shadows = vtk.vtkShadowMapPass()

    seq = vtk.vtkSequencePass()

    passes = vtk.vtkRenderPassCollection()
    passes.AddItem(shadows.GetShadowMapBakerPass())
    passes.AddItem(shadows)
    seq.SetPasses(passes)

    cameraP = vtk.vtkCameraPass()
    cameraP.SetDelegatePass(seq)

    # Tell the renderer to use our render pass pipeline
    glrenderer = renderer
    glrenderer.SetPass(cameraP)

    renderer.GetActiveCamera().SetPosition(-0.2, 0.2, 1)
    renderer.GetActiveCamera().SetFocalPoint(0, 0, 0)
    renderer.GetActiveCamera().SetViewUp(0, 1, 0)
    renderer.GetActiveCamera().OrthogonalizeViewUp()
    renderer.ResetCamera()
    renderer.GetActiveCamera().Dolly(2.25)
    renderer.ResetCameraClippingRange()
    renderWindow.SetWindowName('Shadows')
    renderWindow.Render()

    interactor.Start()
示例#4
0
def main(args):
    parser = argparse.ArgumentParser(
        description=
        'Render a DSM from a DTM and polygons representing buildings.')
    parser.add_argument("--input_vtp_path",
                        type=str,
                        help="Input buildings polygonal file (.vtp)")
    parser.add_argument(
        "--input_obj_paths",
        nargs="*",
        help="List of input building (.obj) file paths.  "
        "Building object files start "
        "with a digit, road object files start with \"Road\". "
        "All obj files start with comments specifying the offsets "
        "that are added the coordinats. There are three comment lines, "
        "one for each coordinate: \"#c offset: value\" where c is x, y and z.")
    parser.add_argument("input_dtm", help="Input digital terain model (DTM)")
    parser.add_argument("output_dsm",
                        help="Output digital surface model (DSM)")
    parser.add_argument("--render_png",
                        action="store_true",
                        help="Do not save the DSM, render into a PNG instead.")
    parser.add_argument(
        "--render_cls",
        action="store_true",
        help="Render a buildings mask: render buildings label (6), "
        "background (2) and no DTM.")
    parser.add_argument("--buildings_only",
                        action="store_true",
                        help="Do not use the DTM, use only the buildings.")
    parser.add_argument("--debug",
                        action="store_true",
                        help="Save intermediate results")
    args = parser.parse_args(args)

    # open the DTM
    dtm = gdal.Open(args.input_dtm, gdal.GA_ReadOnly)
    if not dtm:
        raise RuntimeError("Error: Failed to open DTM {}".format(
            args.input_dtm))

    dtmDriver = dtm.GetDriver()
    dtmDriverMetadata = dtmDriver.GetMetadata()
    dsm = None
    dtmBounds = [0.0, 0.0, 0.0, 0.0]
    if dtmDriverMetadata.get(gdal.DCAP_CREATE) == "YES":
        print("Create destination image "
              "size:({}, {}) ...".format(dtm.RasterXSize, dtm.RasterYSize))
        # georeference information
        projection = dtm.GetProjection()
        transform = dtm.GetGeoTransform()
        gcpProjection = dtm.GetGCPProjection()
        gcps = dtm.GetGCPs()
        options = ["COMPRESS=DEFLATE"]
        # ensure that space will be reserved for geographic corner coordinates
        # (in DMS) to be set later
        if (dtmDriver.ShortName == "NITF" and not projection):
            options.append("ICORDS=G")
        if args.render_cls:
            eType = gdal.GDT_Byte
        else:
            eType = gdal.GDT_Float32
        dsm = dtmDriver.Create(args.output_dsm,
                               xsize=dtm.RasterXSize,
                               ysize=dtm.RasterYSize,
                               bands=1,
                               eType=eType,
                               options=options)
        if (projection):
            # georeference through affine geotransform
            dsm.SetProjection(projection)
            dsm.SetGeoTransform(transform)
        else:
            # georeference through GCPs
            dsm.SetGCPs(gcps, gcpProjection)
            gdal.GCPsToGeoTransform(gcps, transform)
        corners = [[0, 0], [0, dtm.RasterYSize],
                   [dtm.RasterXSize, dtm.RasterYSize], [dtm.RasterXSize, 0]]
        geoCorners = numpy.zeros((4, 2))
        for i, corner in enumerate(corners):
            geoCorners[i] = [
                transform[0] + corner[0] * transform[1] +
                corner[1] * transform[2], transform[3] +
                corner[0] * transform[4] + corner[1] * transform[5]
            ]
        dtmBounds[0] = numpy.min(geoCorners[:, 0])
        dtmBounds[1] = numpy.max(geoCorners[:, 0])
        dtmBounds[2] = numpy.min(geoCorners[:, 1])
        dtmBounds[3] = numpy.max(geoCorners[:, 1])

        if args.render_cls:
            # label for no building
            dtmRaster = numpy.full([dtm.RasterYSize, dtm.RasterXSize], 2)
            nodata = 0
        else:
            print("Reading the DTM {} size: ({}, {})\n"
                  "\tbounds: ({}, {}), ({}, {})...".format(
                      args.input_dtm, dtm.RasterXSize, dtm.RasterYSize,
                      dtmBounds[0], dtmBounds[1], dtmBounds[2], dtmBounds[3]))
            dtmRaster = dtm.GetRasterBand(1).ReadAsArray()
            nodata = dtm.GetRasterBand(1).GetNoDataValue()
        print("Nodata: {}".format(nodata))
    else:
        raise RuntimeError(
            "Driver {} does not supports Create().".format(dtmDriver))

    # read the buildings polydata, set Z as a scalar and project to XY plane
    print("Reading the buildings ...")
    # labels for buildings and elevated roads
    labels = [6, 17]
    if (args.input_vtp_path and os.path.isfile(args.input_vtp_path)):
        polyReader = vtk.vtkXMLPolyDataReader()
        polyReader.SetFileName(args.input_vtp_path)
        polyReader.Update()
        polyVtkList = [polyReader.GetOutput()]
    elif (args.input_obj_paths):
        # buildings start with numbers
        # optional elevated roads start with Road*.obj
        bldg_re = re.compile(".*/?[0-9][^/]*\\.obj")
        bldg_files = [f for f in args.input_obj_paths if bldg_re.match(f)]
        print(bldg_files)
        road_re = re.compile(".*/?Road[^/]*\\.obj")
        road_files = [f for f in args.input_obj_paths if road_re.match(f)]
        files = [bldg_files, road_files]
        files = [x for x in files if x]
        print(road_files)
        if len(files) >= 2:
            print("Found {} buildings and {} roads".format(
                len(files[0]), len(files[1])))
        elif len(files) == 1:
            print("Found {} buildings".format(len(files[0])))
        else:
            raise RuntimeError("No OBJ files found in {}".format(
                args.input_obj_paths))
        polyVtkList = []
        for category in range(len(files)):
            append = vtk.vtkAppendPolyData()
            for i, fileName in enumerate(files[category]):
                offset = [0.0, 0.0, 0.0]
                gdal_utils.read_offset(fileName, offset)
                print("Offset: {}".format(offset))
                transform = vtk.vtkTransform()
                transform.Translate(offset[0], offset[1], offset[2])

                objReader = vtk.vtkOBJReader()
                objReader.SetFileName(fileName)
                transformFilter = vtk.vtkTransformFilter()
                transformFilter.SetTransform(transform)
                transformFilter.SetInputConnection(objReader.GetOutputPort())
                append.AddInputConnection(transformFilter.GetOutputPort())
            append.Update()
            polyVtkList.append(append.GetOutput())
    else:
        raise RuntimeError(
            "Must provide either --input_vtp_path, or --input_obj_paths")

    arrayName = "Elevation"
    append = vtk.vtkAppendPolyData()
    for category in range(len(polyVtkList)):
        poly = dsa.WrapDataObject(polyVtkList[category])
        polyElevation = poly.Points[:, 2]
        if args.render_cls:
            # label for buildings
            polyElevation[:] = labels[category]
        polyElevationVtk = numpy_support.numpy_to_vtk(polyElevation)
        polyElevationVtk.SetName(arrayName)
        poly.PointData.SetScalars(polyElevationVtk)
        append.AddInputDataObject(polyVtkList[category])
    append.Update()

    # Create the RenderWindow, Renderer
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.OffScreenRenderingOn()
    renWin.SetSize(dtm.RasterXSize, dtm.RasterYSize)
    renWin.SetMultiSamples(0)
    renWin.AddRenderer(ren)

    # show the buildings
    trisBuildingsFilter = vtk.vtkTriangleFilter()
    trisBuildingsFilter.SetInputDataObject(append.GetOutput())
    trisBuildingsFilter.Update()

    p2cBuildings = vtk.vtkPointDataToCellData()
    p2cBuildings.SetInputConnection(trisBuildingsFilter.GetOutputPort())
    p2cBuildings.PassPointDataOn()
    p2cBuildings.Update()
    buildingsScalarRange = p2cBuildings.GetOutput().GetCellData().GetScalars(
    ).GetRange()

    if (args.debug):
        polyWriter = vtk.vtkXMLPolyDataWriter()
        polyWriter.SetFileName("p2c.vtp")
        polyWriter.SetInputConnection(p2cBuildings.GetOutputPort())
        polyWriter.Write()

    buildingsMapper = vtk.vtkPolyDataMapper()
    buildingsMapper.SetInputDataObject(p2cBuildings.GetOutput())

    buildingsActor = vtk.vtkActor()
    buildingsActor.SetMapper(buildingsMapper)
    ren.AddActor(buildingsActor)

    if (args.render_png):
        print("Render into a PNG ...")
        # Show the terrain.
        print("Converting the DTM into a surface ...")
        # read the DTM as a VTK object
        dtmReader = vtk.vtkGDALRasterReader()
        dtmReader.SetFileName(args.input_dtm)
        dtmReader.Update()
        dtmVtk = dtmReader.GetOutput()

        # Convert the terrain into a polydata.
        surface = vtk.vtkImageDataGeometryFilter()
        surface.SetInputDataObject(dtmVtk)

        # Make sure the polygons are planar, so need to use triangles.
        tris = vtk.vtkTriangleFilter()
        tris.SetInputConnection(surface.GetOutputPort())

        # Warp the surface by scalar values
        warp = vtk.vtkWarpScalar()
        warp.SetInputConnection(tris.GetOutputPort())
        warp.SetScaleFactor(1)
        warp.UseNormalOn()
        warp.SetNormal(0, 0, 1)
        warp.Update()
        dsmScalarRange = warp.GetOutput().GetPointData().GetScalars().GetRange(
        )

        dtmMapper = vtk.vtkPolyDataMapper()
        dtmMapper.SetInputConnection(warp.GetOutputPort())
        dtmActor = vtk.vtkActor()
        dtmActor.SetMapper(dtmMapper)
        ren.AddActor(dtmActor)

        ren.ResetCamera()
        camera = ren.GetActiveCamera()
        camera.ParallelProjectionOn()
        camera.SetParallelScale((dtmBounds[3] - dtmBounds[2]) / 2)

        if (args.buildings_only):
            scalarRange = buildingsScalarRange
        else:
            scalarRange = [
                min(dsmScalarRange[0], buildingsScalarRange[0]),
                max(dsmScalarRange[1], buildingsScalarRange[1])
            ]
        lut = vtk.vtkColorTransferFunction()
        lut.AddRGBPoint(scalarRange[0], 0.23, 0.30, 0.75)
        lut.AddRGBPoint((scalarRange[0] + scalarRange[1]) / 2, 0.86, 0.86,
                        0.86)
        lut.AddRGBPoint(scalarRange[1], 0.70, 0.02, 0.15)

        dtmMapper.SetLookupTable(lut)
        dtmMapper.SetColorModeToMapScalars()
        buildingsMapper.SetLookupTable(lut)
        if (args.buildings_only):
            ren.RemoveActor(dtmActor)

        renWin.Render()
        windowToImageFilter = vtk.vtkWindowToImageFilter()
        windowToImageFilter.SetInput(renWin)
        windowToImageFilter.SetInputBufferTypeToRGBA()
        windowToImageFilter.ReadFrontBufferOff()
        windowToImageFilter.Update()

        writerPng = vtk.vtkPNGWriter()
        writerPng.SetFileName(args.output_dsm + ".png")
        writerPng.SetInputConnection(windowToImageFilter.GetOutputPort())
        writerPng.Write()
    else:
        print("Render into a floating point buffer ...")

        ren.ResetCamera()
        camera = ren.GetActiveCamera()
        camera.ParallelProjectionOn()
        camera.SetParallelScale((dtmBounds[3] - dtmBounds[2]) / 2)
        distance = camera.GetDistance()
        focalPoint = [(dtmBounds[0] + dtmBounds[1]) * 0.5,
                      (dtmBounds[3] + dtmBounds[2]) * 0.5,
                      (buildingsScalarRange[0] + buildingsScalarRange[1]) * 0.5
                      ]
        position = [focalPoint[0], focalPoint[1], focalPoint[2] + distance]
        camera.SetFocalPoint(focalPoint)
        camera.SetPosition(position)

        valuePass = vtk.vtkValuePass()
        valuePass.SetRenderingMode(vtk.vtkValuePass.FLOATING_POINT)
        # use the default scalar for point data
        valuePass.SetInputComponentToProcess(0)
        valuePass.SetInputArrayToProcess(
            vtk.VTK_SCALAR_MODE_USE_POINT_FIELD_DATA, arrayName)
        passes = vtk.vtkRenderPassCollection()
        passes.AddItem(valuePass)
        sequence = vtk.vtkSequencePass()
        sequence.SetPasses(passes)
        cameraPass = vtk.vtkCameraPass()
        cameraPass.SetDelegatePass(sequence)
        ren.SetPass(cameraPass)
        # We have to render the points first, otherwise we get a segfault.
        renWin.Render()
        valuePass.SetInputArrayToProcess(
            vtk.VTK_SCALAR_MODE_USE_CELL_FIELD_DATA, arrayName)
        renWin.Render()
        elevationFlatVtk = valuePass.GetFloatImageDataArray(ren)
        valuePass.ReleaseGraphicsResources(renWin)

        print("Writing the DSM ...")
        elevationFlat = numpy_support.vtk_to_numpy(elevationFlatVtk)
        # VTK X,Y corresponds to numpy cols,rows. VTK stores arrays
        # in Fortran order.
        elevationTranspose = numpy.reshape(elevationFlat,
                                           [dtm.RasterXSize, dtm.RasterYSize],
                                           "F")
        # changes from cols, rows to rows,cols.
        elevation = numpy.transpose(elevationTranspose)
        # numpy rows increase as you go down, Y for VTK images increases as you go up
        elevation = numpy.flip(elevation, 0)
        if args.buildings_only:
            dsmElevation = elevation
        else:
            # elevation has nans in places other than buildings
            dsmElevation = numpy.fmax(dtmRaster, elevation)
        dsm.GetRasterBand(1).WriteArray(dsmElevation)
        if nodata:
            dsm.GetRasterBand(1).SetNoDataValue(nodata)
示例#5
0
    def __init__(self, render_window_interactor, widget,config=None):

        # render_window_interactor.Initialize()
        # render_window_interactor.Start()
        self.configure(config)
        self.iren = render_window_interactor
        self.ren_win = render_window_interactor.GetRenderWindow()
        self.ren = vtk.vtkRenderer()
        self.ren.GradientBackgroundOn()
        self.ren.SetBackground2(self.BACKGROUND2)
        self.ren.SetBackground(self.BACKGROUND1)
        self.ren.SetUseDepthPeeling(1)
        self.ren_win.SetMultiSamples(0)
        self.ren_win.AlphaBitPlanesOn()
        self.ren.SetOcclusionRatio(0.1)
        self.ren_win.AddRenderer(self.ren)

        self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())

        self.light = vtk.vtkLight()
        self.ren.AddLight(self.light)
        self.light.SetLightTypeToSceneLight()
        self.light.SetPositional(0)


        self.light2 = vtk.vtkLight()
        self.ren.AddLight(self.light2)
        self.light2.SetLightTypeToSceneLight()
        self.light2.SetPositional(0)

        self.light3 = vtk.vtkLight()
        self.ren.AddLight(self.light3)
        self.light3.SetLightTypeToSceneLight()
        self.light3.SetPositional(0)

        self.picker = vtk.vtkCellPicker()
        self.picker.SetTolerance(0.0005)
        self.iren.SetPicker(self.picker)

        self.experiment = None
        self.__cylinder_actors = {}
        self.__line_actors = {}
        self.__cone_actors = {}
        self.__cone_sources = {}
        self.__error_triple = None
        self.__temp_sample = None
        self.__highlighted_actors = []

        #orientation axes
        axes_actor = vtk.vtkAnnotatedCubeActor()
        axes_actor.SetXPlusFaceText("R")
        axes_actor.SetXMinusFaceText("L")
        axes_actor.SetYPlusFaceText("P")
        axes_actor.SetYMinusFaceText("I ")
        axes_actor.SetZPlusFaceText("B")
        axes_actor.SetZMinusFaceText("F")

        axes_actor.GetTextEdgesProperty().SetColor(1, 1, 1)
        axes_actor.GetTextEdgesProperty().SetLineWidth(2)
        axes_actor.GetCubeProperty().SetColor(0.3, 0.3, 0.3)
        axes_actor.SetTextEdgesVisibility(1)
        axes_actor.SetFaceTextVisibility(0)

        axes_actor.SetZFaceTextRotation(90)
        axes_actor.SetXFaceTextRotation(-90)

        axes = vtk.vtkOrientationMarkerWidget()
        axes.SetOrientationMarker(axes_actor)
        axes.SetViewport(0.01, 0.01, 0.2, 0.2)

        self.axes = axes
        self.axes_actor = axes_actor


        self.axes.SetInteractor(self.iren)
        self.axes.EnabledOn()
        self.axes.InteractiveOff()

        self.__widget = widget

        if self.SHADOWS:
            opaque_sequence = vtk.vtkSequencePass()
            passes2 = vtk.vtkRenderPassCollection()
            opaque = vtk.vtkOpaquePass()
            lights = vtk.vtkLightsPass()
            peeling = vtk.vtkDepthPeelingPass()
            translucent = vtk.vtkTranslucentPass()
            peeling.SetTranslucentPass(translucent)
            passes2.AddItem(lights)
            passes2.AddItem(opaque)
            opaque_sequence.SetPasses(passes2)

            opaque_camera_pass = vtk.vtkCameraPass()
            opaque_camera_pass.SetDelegatePass(opaque_sequence)

            shadow_baker = vtk.vtkShadowMapBakerPass()
            shadow_baker.SetOpaquePass(opaque_camera_pass)

            shadow_baker.SetResolution(2**12)
            shadow_baker.SetPolygonOffsetFactor(3.1)
            shadow_baker.SetPolygonOffsetUnits(10.0)

            shadows = vtk.vtkShadowMapPass()
            shadows.SetShadowMapBakerPass(shadow_baker)

            shadows.SetOpaquePass(opaque_sequence)

            seq = vtk.vtkSequencePass()
            passes = vtk.vtkRenderPassCollection()
            seq.SetPasses(passes)
            passes.AddItem(shadow_baker)
            passes.AddItem(shadows)

            passes.AddItem(lights)
            passes.AddItem(peeling)
            passes.AddItem(vtk.vtkVolumetricPass())

            cameraP = vtk.vtkCameraPass()
            cameraP.SetDelegatePass(seq)
            self.ren.SetPass(cameraP)
示例#6
0
#from https://discourse.vtk.org/t/enabling-self-occlusion-shadows-wrt-image-based-skybox-lighting/4358/2
# passes = vtk.vtkRenderPassCollection()
# passes.AddItem(vtk.vtkRenderStepsPass())
# seq = vtk.vtkSequencePass()
# seq.SetPasses(passes)
# ssao=vtk.vtkSSAOPass()
# ssao.SetDelegatePass(seq)
# ssao.SetRadius(0.035)
# ssao.SetKernelSize(128)
# ssao.BlurOff() # do not blur occlusion
# renderer.SetPass(ssao)



# #set tonemapping https://gitlab.kitware.com/vtk/vtk/-/blob/master/Rendering/OpenGL2/Testing/Cxx/TestToneMappingPass.cxx
cameraP=vtk.vtkCameraPass()
seq=vtk.vtkSequencePass()
opaque=vtk.vtkOpaquePass()
lights=vtk.vtkLightsPass()

passes=vtk.vtkRenderPassCollection()
passes.AddItem(lights)
passes.AddItem(opaque)
seq.SetPasses(passes)

#shadows  https://gitlab.kitware.com/vtk/vtk/-/blob/master/Rendering/OpenGL2/Testing/Cxx/TestShadowMapPass.cxx
shadows=vtk.vtkShadowMapPass()
shadows.GetShadowMapBakerPass().SetResolution(1024)
# to cancel self->shadowing
# shadows.GetShadowMapBakerPass().SetPolygonOffsetFactor(3.1)
# shadows.GetShadowMapBakerPass().SetPolygonOffsetUnits(10.0)
示例#7
0
def main():
    interactor = vtk.vtkRenderWindowInteractor()

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetSize(400, 400)
    renderWindow.SetMultiSamples(0)

    renderWindow.SetAlphaBitPlanes(1)
    interactor.SetRenderWindow(renderWindow)

    renderer = vtk.vtkOpenGLRenderer()
    renderWindow.AddRenderer(renderer)
    renderWindow.SetSize(640, 480)

    rectangleSource = vtk.vtkPlaneSource()
    rectangleSource.SetOrigin(-5.0, 0.0, 5.0)
    rectangleSource.SetPoint1(5.0, 0.0, 5.0)
    rectangleSource.SetPoint2(-5.0, 0.0, -5.0)
    rectangleSource.SetResolution(100, 100)

    rectangleMapper = vtk.vtkPolyDataMapper()
    rectangleMapper.SetInputConnection(rectangleSource.GetOutputPort())

    rectangleMapper.SetScalarVisibility(0)

    shadows = vtk.vtkShadowMapPass()

    seq = vtk.vtkSequencePass()

    passes = vtk.vtkRenderPassCollection()
    passes.AddItem(shadows.GetShadowMapBakerPass())
    passes.AddItem(shadows)
    seq.SetPasses(passes)

    cameraP = vtk.vtkCameraPass()
    cameraP.SetDelegatePass(seq)

    # tell the renderer to use our render pass pipeline
    glrenderer = renderer
    glrenderer.SetPass(cameraP)

    colors = vtk.vtkNamedColors()
    boxColor = colors.GetColor3d("Tomato")
    rectangleColor = colors.GetColor3d("Beige")
    coneColor = colors.GetColor3d("Peacock")
    sphereColor = colors.GetColor3d("Banana")

    rectangleActor = vtk.vtkActor()
    rectangleActor.SetMapper(rectangleMapper)
    rectangleActor.VisibilityOn()
    rectangleActor.GetProperty().SetColor(rectangleColor)

    boxSource = vtk.vtkCubeSource()
    boxSource.SetXLength(2.0)

    boxNormals = vtk.vtkPolyDataNormals()
    boxNormals.SetInputConnection(boxSource.GetOutputPort())
    boxNormals.ComputePointNormalsOff()
    boxNormals.ComputeCellNormalsOn()
    boxNormals.Update()
    boxNormals.GetOutput().GetPointData().SetNormals(None)

    boxMapper = vtk.vtkPolyDataMapper()
    boxMapper.SetInputConnection(boxNormals.GetOutputPort())
    boxMapper.ScalarVisibilityOff()

    boxActor = vtk.vtkActor()
    boxActor.SetMapper(boxMapper)
    boxActor.VisibilityOn()
    boxActor.SetPosition(-2.0, 2.0, 0.0)
    boxActor.GetProperty().SetColor(boxColor)

    coneSource = vtk.vtkConeSource()
    coneSource.SetResolution(24)
    coneSource.SetDirection(1.0, 1.0, 1.0)

    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInputConnection(coneSource.GetOutputPort())
    coneMapper.SetScalarVisibility(0)

    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)
    coneActor.VisibilityOn()
    coneActor.SetPosition(0.0, 1.0, 1.0)
    coneActor.GetProperty().SetColor(coneColor)

    sphereSource = vtk.vtkSphereSource()
    sphereSource.SetThetaResolution(32)
    sphereSource.SetPhiResolution(32)

    sphereMapper = vtk.vtkPolyDataMapper()
    sphereMapper.SetInputConnection(sphereSource.GetOutputPort())
    sphereMapper.ScalarVisibilityOff()

    sphereActor = vtk.vtkActor()
    sphereActor.SetMapper(sphereMapper)

    sphereActor.VisibilityOn()
    sphereActor.SetPosition(2.0, 2.0, -1.0)
    sphereActor.GetProperty().SetColor(sphereColor)

    renderer.AddViewProp(rectangleActor)
    renderer.AddViewProp(boxActor)
    renderer.AddViewProp(coneActor)
    renderer.AddViewProp(sphereActor)

    # Spotlights.

    # lighting the box.
    l1 = vtk.vtkLight()
    l1.SetPosition(-4.0, 4.0, -1.0)
    l1.SetFocalPoint(boxActor.GetPosition())
    l1.SetColor(1.0, 1.0, 1.0)
    l1.PositionalOn()
    renderer.AddLight(l1)
    l1.SwitchOn()

    # lighting the sphere
    l2 = vtk.vtkLight()
    l2.SetPosition(4.0, 5.0, 1.0)
    l2.SetFocalPoint(sphereActor.GetPosition())
    l2.SetColor(1.0, 0.0, 1.0)
    l2.PositionalOn()
    renderer.AddLight(l2)
    l2.SwitchOn()

    # For each spotlight, add a light frustum wireframe representation and a cone
    # wireframe representation, colored with the light color.
    angle = l1.GetConeAngle()
    if l1.LightTypeIsSceneLight() and l1.GetPositional(
    ) and angle < 180.0:  # spotlight
        la = vtk.vtkLightActor()
        la.SetLight(l1)
        renderer.AddViewProp(la)
    angle = l2.GetConeAngle()
    if l2.LightTypeIsSceneLight() and l2.GetPositional(
    ) and angle < 180.0:  # spotlight
        la = vtk.vtkLightActor()
        la.SetLight(l2)
        renderer.AddViewProp(la)

    renderer.SetBackground2(colors.GetColor3d("Silver"))
    renderer.SetBackground(colors.GetColor3d("LightGrey"))
    renderer.SetGradientBackground(True)

    renderWindow.Render()
    renderWindow.SetWindowName('ShadowsLightsDemo')

    renderer.ResetCamera()

    camera = renderer.GetActiveCamera()
    camera.Azimuth(40.0)
    camera.Elevation(10.0)

    renderWindow.Render()

    interactor.Start()
renderWindow   .SetMultiSamples(0)
renderWindow.SetAlphaBitPlanes(1)
interactor.SetRenderWindow(renderWindow)

renderer = vtk.vtkRenderer()

renderWindow.AddRenderer(renderer)

supported = vtk.vtkFrameBufferObject.IsSupported(renderWindow)

if (not supported):
    print "returning"
    time.sleep(5)


cameraP = vtk.vtkCameraPass()
opaque = vtk.vtkOpaquePass()

peeling = vtk.vtkDepthPeelingPass()
peeling.SetMaximumNumberOfPeels(200)
peeling.SetOcclusionRatio(0.1)


translucent = vtk.vtkTranslucentPass()
peeling.SetTranslucentPass(translucent)


volume = vtk.vtkVolumetricPass()
overlay = vtk.vtkOverlayPass()
lights = vtk.vtkLightsPass()
opaqueSequence = vtk.vtkSequencePass()
renderWindow   .SetMultiSamples(0)
renderWindow.SetAlphaBitPlanes(1)
interactor.SetRenderWindow(renderWindow)

renderer = vtk.vtkRenderer()

renderWindow.AddRenderer(renderer)

supported = vtk.vtkFrameBufferObject.IsSupported(renderWindow)

if (not supported):
    print "returning"
    time.sleep(5)


cameraP = vtk.vtkCameraPass()
opaque = vtk.vtkOpaquePass()

peeling = vtk.vtkDepthPeelingPass()
peeling.SetMaximumNumberOfPeels(200)
peeling.SetOcclusionRatio(0.1)


translucent = vtk.vtkTranslucentPass()
peeling.SetTranslucentPass(translucent)


volume = vtk.vtkVolumetricPass()
overlay = vtk.vtkOverlayPass()
lights = vtk.vtkLightsPass()
opaqueSequence = vtk.vtkSequencePass()
    def __init__(self):
       
        self.renderer = vtk.vtkRenderer()
        self.renderer.GradientBackgroundOn()

        self.ren_win = ren_win = vtk.vtkRenderWindow()
        
        ren_win.SetSize(512,512) 
        ren_win.SetMultiSamples(0)
        ren_win.SetAlphaBitPlanes(1)
        ren_win.SetOffScreenRendering(1) #default 1

        iren = self.iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(ren_win)
        ren_win.AddRenderer(self.renderer)
       
        camera_pass = vtk.vtkCameraPass()
        opaque = vtk.vtkOpaquePass()

        peeling=vtk.vtkDepthPeelingPass()
        peeling.SetMaximumNumberOfPeels(200)
        peeling.SetOcclusionRatio(0.1)

        translucent=vtk.vtkTranslucentPass()
        peeling.SetTranslucentPass(translucent)

        volume=vtk.vtkVolumetricPass()
        overlay=vtk.vtkOverlayPass()
        lights=vtk.vtkLightsPass()
        opaque_sequence=vtk.vtkSequencePass()

        passes2=vtk.vtkRenderPassCollection()
        passes2.AddItem(lights)
        passes2.AddItem(opaque)

        opaque_sequence.SetPasses(passes2)
        opaque_camera_pass=vtk.vtkCameraPass()
        opaque_camera_pass.SetDelegatePass(opaque_sequence)

        shadows_baker=vtk.vtkShadowMapBakerPass()
        shadows_baker.SetOpaquePass(opaque_camera_pass)
        shadows_baker.SetResolution(1024)

        #To cancel self-shadowing.
        shadows_baker.SetPolygonOffsetFactor(3.1)
        shadows_baker.SetPolygonOffsetUnits(10.0)

        shadows=vtk.vtkShadowMapPass()
        shadows.SetShadowMapBakerPass(shadows_baker)
        shadows.SetOpaquePass(opaque_sequence)

        seq=vtk.vtkSequencePass()
        passes=vtk.vtkRenderPassCollection()
        passes.AddItem(shadows_baker)
        passes.AddItem(shadows)
        passes.AddItem(lights)
        passes.AddItem(peeling)
        passes.AddItem(volume)
        passes.AddItem(overlay)

        seq.SetPasses(passes)
        camera_pass.SetDelegatePass(seq)
        self.renderer.SetPass(camera_pass)