. This replaces the
          ``'ipyvtklink'`` backend with better performance.
          Supports the most VTK features, but suffers from minor lag due
          to remote rendering. Requires that a virtual framebuffer be set
          up when displaying on a headless server. Must have at least ``trame``
          and ``jupyter-server-proxy`` installed for cloud/remote Jupyter
          instances. This mode is also aliased by ``'trame'``.

        * ``'trame'``: The full Trame-based backend that combines both
          ``'server'`` and ``'client'`` into one backend. This requires a
          virtual frame buffer.

        * ``'none'`` : Do not display any plots within jupyterlab,
          instead display using dedicated VTK render windows.  This
          will generate nothing on headless servers even with a
          virtual framebuffer.

    Examples
    --------
    Enable the pythreejs backend.

    >>> import pyvista as pv
    >>> pv.set_jupyter_backend('pythreejs')  # doctest:+SKIP

    Enable the ipygany backend.

    >>> import pyvista as pv
    >>> pv.set_jupyter_backend('ipygany')  # doctest:+SKIP

    Enable the panel backend.

    >>> pv.set_jupyter_backend('panel')  # doctest:+SKIP

    Enable the ipyvtklink backend.

    >>> pv.set_jupyter_backend('ipyvtklink')  # doctest:+SKIP

    Enable the trame Trame backend.

    >>> pv.set_jupyter_backend('trame')  # doctest:+SKIP

    Just show static images.

    >>> pv.set_jupyter_backend('static')  # doctest:+SKIP

    Disable all plotting within JupyterLab and display using a
    standard desktop VTK render window.

    >>> pv.set_jupyter_backend(None)  # doctest:+SKIP

    """
    pyvista.global_theme._jupyter_backend = _validate_jupyter_backend(backend)
    if backend in ['server', 'client', 'trame']:
        # Launch the trame server
        from pyvista.trame.jupyter import elegantly_launch

        elegantly_launch(pyvista.global_theme.trame.jupyter_server_name)


# pyvista/jupyter/notebook.py

"""
Support dynamic or static jupyter notebook plotting.

Includes:

* ``ipyvtklink``
* ``panel``
* ``pythreejs``
* ``ipygany``
* ``client``
* ``server``

"""
import os
import warnings

import numpy as np

from pyvista import _vtk
from pyvista.utilities.misc import PyVistaDeprecationWarning

PANEL_EXTENSION_SET = [False]


def handle_plotter(plotter, backend=None, screenshot=None, **kwargs):
    """Show the ``pyvista`` plot in a jupyter environment.

    Returns
    -------
    IPython Widget
        IPython widget or image.

    """
    if screenshot is False:
        screenshot = None

    try:
        if backend == 'pythreejs':
            return show_pythreejs(plotter, **kwargs)
        if backend == 'ipyvtklink':
            warnings.warn(
                '`ipyvtklink` backend is deprecated and has been replaced by the `trame` backend.',
                PyVistaDeprecationWarning,
            )
            return show_ipyvtk(plotter)
        if backend == 'panel':
            return show_panel(plotter)
        if backend == 'ipygany':
            from pyvista.jupyter.pv_ipygany import show_ipygany

            return show_ipygany(plotter, **kwargs)
        if backend in ['server', 'client', 'trame']:
            from pyvista.trame.jupyter import show_trame

            return show_trame(plotter, mode=backend, **kwargs)

    except ImportError as e:
        warnings.warn(
            f'Failed to use notebook backend: \n\n{e}\n\nFalling back to a static output.'
        )

    return show_static_image(plotter, screenshot)


def show_static_image(plotter, screenshot):
    """Display a static image to be displayed within a jupyter notebook."""
    import PIL.Image

    if plotter.last_image is None:
        # Must render here, otherwise plotter will segfault.
        plotter.render()
        plotter.last_image = plotter.screenshot(screenshot, return_img=True)
    image = PIL.Image.fromarray(plotter.last_image)

    # Simply display the result: either ipyvtklink object or image display
    return image


def show_ipyvtk(plotter):
    """Display an interactive viewer widget using ``ipyvtklink``."""
    if any('SPYDER' in name for name in os.environ):
        warnings.warn(
            '``ipyvtklink`` backend is incompatible with Spyder.\n'
            'Use notebook=False for interactive '
            'plotting within spyder or disable it globally with:\n'
            'pyvista.set_jupyter_backend(None)'
        )

    try:
        from ipyvtklink.viewer import ViewInteractiveWidget
    except ImportError:  # pragma: no cover
        raise ImportError(
            'Please install `ipyvtklink` to use this feature: '
            'https://github.com/Kitware/ipyvtklink'
        )

    # Have to leave the Plotter open for the widget to use
    disp = ViewInteractiveWidget(
        plotter.render_window,
        on_close=plotter.close,
        transparent_background=plotter.image_transparent_background,
    )

    for renderer in plotter.renderers:
        renderer.AddObserver(_vtk.vtkCommand.ModifiedEvent, lambda *args: disp.update_canvas())

    return disp


def show_panel(plotter):
    """Take the active renderer or renderers from a plotter and show them using ``panel``."""
    try:
        import panel as pn
    except ImportError:  # pragma: no cover
        raise ImportError('Install ``panel`` to use this feature')

    # check if panel extension has been set
    if not PANEL_EXTENSION_SET[0]:
        pn.extension('vtk')
        PANEL_EXTENSION_SET[0] = True

    # only set window size if explicitly set within the plotter
    sizing = {}
    if not plotter._window_size_unset:
        width, height = plotter.window_size
        sizing = {'width': width, 'height': height}

    axes_enabled = plotter.renderer.axes_enabled
    pan = pn.panel(
        plotter.render_window,
        sizing_mode='stretch_width',
        orientation_widget=axes_enabled,
        enable_keybindings=False,
        **sizing,
    )

    # if plotter.renderer.axes_enabled:
    # pan.axes = build_panel_axes()

    if plotter.renderer.cube_axes_actor is not None:
        pan.axes = build_panel_bounds(plotter.renderer.cube_axes_actor)

    return pan


def build_panel_bounds(actor):
    """Build a panel bounds actor using the plotter cube_axes_actor."""
    bounds = {}

    n_ticks = 5
    if actor.GetXAxisVisibility():
        xmin, xmax = actor.GetXRange()
        bounds['xticker'] = {'ticks': np.linspace(xmin, xmax, n_ticks)}

    if actor.GetYAxisVisibility():
        ymin, ymax = actor.GetYRange()
        bounds['yticker'] = {'ticks': np.linspace(ymin, ymax, n_ticks)}

    if actor.GetZAxisVisibility():
        zmin, zmax = actor.GetZRange()
        bounds['zticker'] = {'ticks': np.linspace(zmin, zmax, n_ticks)}

    bounds['origin'] = [xmin, ymin, zmin]
    bounds['grid_opacity'] = 0.5
    bounds['show_grid'] = True
    bounds['digits'] = 3
    bounds['fontsize'] = actor.GetLabelTextProperty(0).GetFontSize()

    return bounds


def show_pythreejs(plotter, **kwargs):
    """Show a pyvista plotting scene using pythreejs."""
    from .pv_pythreejs import convert_plotter

    renderer = convert_plotter(plotter)
    return renderer


# pyvista/jupyter/pv_ipygany.py

"""Support for the ipygany plotter."""

from array import array
import warnings

import numpy as np

# not to be imported at the init level
try:
    import ipygany
except ImportError:  # pragma: no cover
    raise ImportError('Install ``ipygany`` to use this feature.')

try:
    from ipywidgets import HTML, AppLayout, Dropdown, VBox, jslink
except ImportError:  # pragma: no cover
    raise ImportError('Install ``ipywidgets`` to use this feature.')


from ipygany import IsoColor, PointCloud, PolyMesh, Scene
from ipygany.colormaps import colormaps
from ipygany.ipygany import _grid_data_to_data_widget
from ipygany.vtk_loader import get_ugrid_data

import pyvista as pv


def pyvista_polydata_to_polymesh(obj):
    """Import a mesh from ``pyvista`` or ``vtk``.

    Copies over the active scalars and only the active scalars.

    Parameters
    ----------
    obj : pyvista compatible object
        Any object compatible with pyvista.  Includes most ``vtk``
        objects.

    Returns
    -------
    PolyMesh
        ``ipygany.PolyMesh`` object.
    """
    # attempt to wrap non-pyvista objects
    if not pv.is_pyvista_dataset(obj):  # pragma: no cover
        mesh = pv.wrap(obj)
        if not pv.is_pyvista_dataset(mesh):
            raise TypeError(f'Object type ({type(mesh)}) cannot be converted to a pyvista dataset')
    else:
        mesh = obj

    # PolyMesh requires vertices and triangles, so we need to
    # convert the mesh to an all triangle polydata
    if not isinstance(obj, pv.PolyData):
        # unlikely case that mesh does not have extract_surface
        if not hasattr(mesh, 'extract_surface'):  # pragma: no cover
            mesh = mesh.cast_to_unstructured_grid()
        surf = mesh.extract_surface()
    else:
        surf = mesh

    # convert to an all-triangular surface
    if surf.is_all_triangles:
        trimesh = surf
    else:
        trimesh = surf.triangulate()

    # finally, pass the triangle vertices to PolyMesh
    triangle_indices = trimesh.faces.reshape(-1, 4)[:, 1:]

    if not triangle_indices.size:
        warnings.warn('Unable to convert mesh to triangular PolyMesh')

    # only copy active scalars
    data = []
    if trimesh.active_scalars is not None:
        arr = array('f', trimesh.active_scalars)
        components = [ipygany.Component('X1', arr)]
        data = [ipygany.Data(trimesh.active_scalars_name, components)]

    # convert to float32 for speed.  Also, ints are not supported for plotting
    points = trimesh.points.astype(np.float32, copy=False)

    # for speed, only convert the active scalars later
    return PolyMesh(vertices=points, triangle_indices=triangle_indices, data=data)


def pyvista_object_to_pointcloud(pv_object):
    """Convert any pyvista object into a ``ipygany.PointCloud``."""
    pc = PointCloud(
        vertices=pv_object.points, data=_grid_data_to_data_widget(get_ugrid_data(pv_object))
    )
    return pc


def check_colormap(cmap):
    """Attempt to convert a colormap to ``ipygany``."""
    if cmap not in colormaps:
        # attempt to matplotlib cmaps to ipygany
        if cmap.capitalize() in colormaps:
            cmap = cmap.capitalize()

    if cmap not in colormaps:
        allowed = ', '.join([f"'{clmp}'" for clmp in colormaps.keys()])
        raise ValueError(
            f'``cmap`` "{cmap}" is not supported by ``ipygany``\n'
            'Pick from one of the following:\n' + allowed
        )
    return cmap


def ipygany_block_from_actor(actor):
    """Convert a vtk actor to a ipygany Block."""
    mapper = actor.GetMapper()
    if mapper is None:
        return
    dataset = pv.wrap(mapper.GetInputAsDataSet())

    prop = actor.GetProperty()
    rep_type = prop.GetRepresentationAsString()

    # check if missing faces as a polydata
    if rep_type != 'Points' and isinstance(dataset, pv.PolyData):
        if not dataset.faces.size and dataset.n_points:
            rep_type = 'Points'

    if rep_type == 'Points':
        pmesh = pyvista_object_to_pointcloud(dataset)
    elif rep_type == 'Wireframe':
        warnings.warn('Wireframe style is not supported in ipygany')
        return
    else:
        pmesh = pyvista_polydata_to_polymesh(dataset)
    pmesh.default_color = pv.Color(prop.GetColor()).hex_rgb

    # determine if there are active scalars
    valid_mode = mapper.GetScalarModeAsString() in ['UsePointData', 'UseCellData']
    if valid_mode:
        # verify dataset is in pmesh
        names = [dataset.name for dataset in pmesh.data]
        if dataset.active_scalars_name in names:
            mn, mx = mapper.GetScalarRange()
            cmesh = IsoColor(pmesh, input=dataset.active_scalars_name, min=mn, max=mx)
            if hasattr(mapper, 'cmap'):
                cmap = check_colormap(mapper.cmap)
                cmesh.colormap = colormaps[cmap]
            return cmesh

    return pmesh


def ipygany_camera_from_plotter(plotter):
    """Return an ipygany camera dict from a ``pyvista.Plotter`` object."""
    position, target, up = plotter.camera_position
    # TODO: camera position appears twice as far within ipygany, adjust:

    position = np.array(position, copy=True)
    position -= (position - np.array(target)) / 2

    return {'position': position.tolist(), 'target': target, 'up': up}


def show_ipygany(plotter, height=None, width=None):
    """Show an ipygany scene."""
    # convert each mesh in the plotter to an ipygany scene
    actors = plotter.renderer._actors
    meshes = []
    for actor in actors.values():
        ipygany_obj = ipygany_block_from_actor(actor)
        if ipygany_obj is not None:
            meshes.append(ipygany_obj)

    bc_color = plotter.background_color.hex_rgb
    scene = Scene(meshes, background_color=bc_color, camera=ipygany_camera_from_plotter(plotter))

    # optionally size of the plotter
    if height is not None:
        scene.layout.height = f'{height}'
    if width is not None:
        scene.layout.width = f'{width}'

    cbar = None
    if len(plotter.scalar_bars):
        for mesh in meshes:
            if isinstance(mesh, ipygany.IsoColor):
                cbar = ipygany.ColorBar(mesh)
                colored_mesh = mesh
                break

    if cbar is not None:
        # Colormap choice widget
        options = list(colormaps.items())
        colormap_dd = Dropdown(options=options, description='Colormap:')
        jslink((colored_mesh, 'colormap'), (colormap_dd, 'index'))

        # sensible colorbar maximum width, or else it looks bad when
        # window is large.
        cbar.layout.max_width = '500px'
        cbar.layout.min_height = '50px'  # stop from getting squished
        # cbar.layout.height = '20%'  # stop from getting squished
        # cbar.layout.max_height = ''

        # Create a slider that will dynamically change the boundaries of the colormap
        # colormap_slider_range = FloatRangeSlider(value=[height_min, height_max],
        #                                          min=height_min, max=height_max,
        #                                          step=(height_max - height_min) / 100.)

        # jslink((colored_mesh, 'range'), (colormap_slider_range, 'value'))

        # create app
        title = HTML(value=f'<h3>{list(plotter.scalar_bars.keys())[0]}</h3>')
        legend = VBox((title, colormap_dd, cbar))
        scene = AppLayout(center=scene, footer=legend, pane_heights=[0, 0, '150px'])

    return scene


# pyvista/jupyter/pv_pythreejs.py

"""Serialize a pyvista plotter to a pythreejs scene."""

import warnings

import numpy as np

try:
    import pythreejs as tjs
except ImportError:  # pragma: no cover
    raise ImportError('Please install pythreejs to use this feature')

from ipywidgets import GridspecLayout

import pyvista as pv


def segment_poly_cells(mesh):
    """Segment lines from a mesh into line segments."""
    if not pv.is_pyvista_dataset(mesh):  # pragma: no cover
        mesh = pv.wrap(mesh)
    polylines = []
    offset = 0
    cc = mesh.lines  # fetch up front
    ncc = len(cc)
    while offset < ncc:
        nn = cc[offset]
        polylines.append(cc[offset + 1 : offset + 1 + nn])
        offset += nn + 1

    lines = []
    for poly in polylines:
        lines.append(np.column_stack((poly[:-1], poly[1:])))
    return np.vstack(lines)


def buffer_normals(trimesh):
    """Extract surface normals and return a buffer attribute."""
    if 'Normals' in trimesh.point_data:
        normals = trimesh.point_data['Normals']
    else:
        normals = trimesh.point_normals
    normals = normals.astype(np.float32, copy=False)
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", message="Given trait value dtype")
        return tjs.BufferAttribute(array=normals)


def get_coloring(mapper, dataset):
    """Return the three.js coloring type for a given actor.

    Returns
    -------
    str
        Either ``'NoColors'``, ``'VertexColors'``, or ``'FaceColors'``.

    """
    coloring = 'NoColors'
    if mapper.scalar_map_mode == 'point':
        scalars = dataset.point_data.active_scalars
        if scalars is not None:
            coloring = 'VertexColors'
    elif mapper.scalar_map_mode == 'cell':
        scalars = dataset.cell_data.active_scalars
        if scalars is not None:
            coloring = 'FaceColors'
    return coloring


def extract_surface_mesh(obj):
    """Extract a surface mesh from a pyvista or vtk dataset.

    Parameters
    ----------
    obj : pyvista compatible object
        Any object compatible with pyvista.  Includes most ``vtk``
        objects.

    Returns
    -------
    pyvista.PolyData
        Surface mesh

    """
    # attempt to wrap non-pyvista objects
    if not pv.is_pyvista_dataset(obj):  # pragma: no cover
        mesh = pv.wrap(obj)
        if not pv.is_pyvista_dataset(mesh):
            raise TypeError(f'Object type ({type(mesh)}) cannot be converted to a pyvista dataset')
    else:
        mesh = obj

    if not isinstance(obj, pv.PolyData):
        # unlikely case that mesh does not have extract_surface
        if not hasattr(mesh, 'extract_surface'):  # pragma: no cover
            mesh = mesh.cast_to_unstructured_grid()
        return mesh.extract_surface()

    return mesh


def map_scalars(lookup_table, scalars):
    """Map scalars to a RGB array.

    Parameters
    ----------
    lookup_table : vtk.vtkLookupTable
        Color lookup table.
    scalars : vtk array, numpy.ndarray, or pyvista.pyvista_ndarray
        Scalars to map.

    Returns
    -------
    pyvista.pyvista_ndarray
        Array of mapped scalars.

    """
    if isinstance(scalars, np.ndarray):
        if hasattr(scalars, 'VTKObject') and scalars.VTKObject is not None:
            scalars = scalars.VTKObject
        else:
            scalars = pv._vtk.numpy_to_vtk(scalars)
    return pv.wrap(lookup_table.MapScalars(scalars, 0, 0))[:, :3] / 255


def array_to_float_buffer(points):
    """Convert a numpy array to a pythreejs compatible point buffer."""
    # create buffered points
    points = points.astype(np.float32, copy=False)

    # ignore invalid warning.  BufferAttribute type is None and is
    # improperly recognized as float64.  Same for the rest
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", message="Given trait value dtype")
        position = tjs.BufferAttribute(array=points, normalized=False)
    return position


def cast_to_min_size(ind, max_index):
    """Return a buffered attribute of the minimum index size."""
    ind = ind.ravel()
    if max_index < np.iinfo(np.uint16).max:
        ind = ind.astype(np.uint16, copy=False)
    elif max_index < np.iinfo(np.uint32).max:
        ind = ind.astype(np.uint32, copy=False)
    else:
        raise ValueError(
            f'pythreejs does not support a maximum index more than {np.iinfo(np.uint32).max}'
        )
    return tjs.BufferAttribute(array=ind, normalized=False)


def to_surf_mesh(
    surf,
    texture,
    prop,
    scalar_mode,
    color_mode,
    lookup_table,
    coloring,
    add_attr=None,
    color=None,
    opacity=None,
):
    """Convert a pyvista surface to a buffer geometry.

    General Notes
    -------------

    * THREE.BufferGeometry expects position and index attributes
      representing a triangulated mesh points and face indices or just
      a position array representing individual faces of a mesh.
    * The normals attribute is needed for physically based rendering,
      but not for the other mesh types.
    * Colors must be a RGB array with one value per point.

    Shading Notes
    -------------
    To match VTK, the following materials are used to match VTK's shading:

    * MeshPhysicalMaterial when physically based rendering is enabled
    * MeshPhongMaterial when physically based rendering is disabled,
      but lighting is enabled.
    * MeshBasicMaterial when lighting is disabled.

    """
    # allow override of property opacity
    opacity = prop.GetOpacity() if opacity is None else opacity

    if add_attr is None:
        add_attr = {}
    # convert to an all-triangular surface
    if surf.is_all_triangles:
        trimesh = surf
    else:
        trimesh = surf.triangulate()

    position = array_to_float_buffer(trimesh.points)

    # convert to minimum index type
    face_ind = trimesh.faces.reshape(-1, 4)[:, 1:]
    index = cast_to_min_size(face_ind, trimesh.n_points)
    attr = {
        'position': position,
        'index': index,
    }

    if prop.GetInterpolation():  # something other than flat shading
        attr['normal'] = buffer_normals(trimesh)

    # extract point/cell scalars for coloring
    colors = None
    if scalar_mode == 'UsePointData':
        colors = map_scalars(lookup_table, trimesh.point_data.active_scalars)
    elif scalar_mode == 'UseCellData':
        # special handling for RGBA
        if color_mode == 2:
            scalars = trimesh.cell_data.active_scalars.repeat(3, axis=0)
            scalars = scalars.astype(np.float32, copy=False)
            colors = scalars[:, :3] / 255  # ignore alpha
        else:
            # must repeat for each triangle
            scalars = trimesh.cell_data.active_scalars.repeat(3)
            colors = map_scalars(lookup_table, scalars)

        position = array_to_float_buffer(trimesh.points[face_ind])
        attr = {'position': position}

    # add colors to the buffer geometry attributes
    if colors is not None:
        attr['color'] = array_to_float_buffer(colors)

    # texture coordinates
    t_coords = trimesh.active_t_coords
    if t_coords is not None:
        attr['uv'] = array_to_float_buffer(t_coords)

    # TODO: Convert PBR textures
    # base_color_texture = prop.GetTexture("albedoTex")
    # orm_texture = prop.GetTexture("materialTex")
    # anisotropy_texture = prop.GetTexture("anisotropyTex")
    # normal_texture = prop.GetTexture("normalTex")
    # emissive_texture = prop.GetTexture("emissiveTex")
    # coatnormal_texture = prop.GetTexture("coatNormalTex")
    if prop.GetNumberOfTextures():  # pragma: no cover
        warnings.warn('pythreejs converter does not support PBR textures (yet).')

    # create base buffer geometry
    surf_geo = tjs.BufferGeometry(attributes=attr)

    # add texture to the surface buffer if available
    tjs_texture = None
    if texture is not None:
        wrapped_tex = pv.wrap(texture.GetInput())
        data = wrapped_tex.active_scalars
        dim = (wrapped_tex.dimensions[0], wrapped_tex.dimensions[1], data.shape[1])
        data = data.reshape(dim)
        # fmt = "RGBFormat" if data.shape[1] == 3 else "RGBAFormat"

        # Create data texture and catch invalid warning
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", message="Given trait value dtype")
            tjs_texture = tjs.DataTexture(data=data, format="RGBFormat", type="UnsignedByteType")

    # these attributes are always used regardless of the material
    shared_attr = {
        'vertexColors': coloring,
        'wireframe': prop.GetRepresentation() == 1,
        'opacity': opacity,
        'wireframeLinewidth': prop.GetLineWidth(),
        # 'side': 'DoubleSide'  # enabling seems to mess with textures
    }

    if colors is None:
        if color is None:
            shared_attr['color'] = pv.Color(prop.GetColor()).hex_rgb
        else:
            shared_attr['color'] = pv.Color(color).hex_rgb

    if tjs_texture is not None:
        shared_attr['map'] = tjs_texture
    else:
        if prop.GetBackfaceCulling():
            shared_attr['side'] = 'FrontSide'
        elif prop.GetFrontfaceCulling():
            shared_attr['side'] = 'BackSide'
        else:
            shared_attr['side'] = 'DoubleSide'

    if opacity < 1.0:
        shared_attr['transparent'] = True

    if prop.GetInterpolation() == 3:  # using physically based rendering
        material = tjs.MeshPhysicalMaterial(
            flatShading=False,
            roughness=prop.GetRoughness(),
            metalness=prop.GetMetallic(),
            reflectivity=0,
            **shared_attr,
            **add_attr,
        )
    elif prop.GetLighting():
        # specular disabled to fix lighting issues
        material = tjs.MeshPhongMaterial(
            shininess=0,
            flatShading=prop.GetInterpolation() == 0,
            specular='#000000',
            reflectivity=0,
            **shared_attr,
            **add_attr,
        )
    else:  # no lighting
        material = tjs.MeshBasicMaterial(**shared_attr, **add_attr)

    return tjs.Mesh(geometry=surf_geo, material=material)


def to_edge_mesh(
    surf,
    prop,
    coloring,
    scalar_mode,
    lookup_table,
    use_edge_coloring=True,
    use_lines=False,
    color=None,
    opacity=None,
):
    """Convert a pyvista surface to a three.js edge mesh."""
    # extract all edges from the surface.  Should not use triangular
    # mesh here as mesh may contain more than triangular faces
    if use_lines:
        edges_mesh = surf
        edges = segment_poly_cells(surf)
    else:
        edges_mesh = surf.extract_all_edges()
        edges = edges_mesh.lines.reshape(-1, 3)[:, 1:]

    attr = {
        'position': array_to_float_buffer(edges_mesh.points),
        'index': cast_to_min_size(edges, surf.n_points),
    }

    # add in colors
    if coloring != 'NoColors' and not use_edge_coloring:
        if scalar_mode == 'UsePointData':
            edge_scalars = edges_mesh.point_data.active_scalars
            edge_colors = map_scalars(lookup_table, edge_scalars)
            attr['color'] = array_to_float_buffer(edge_colors)

    edge_geo = tjs.BufferGeometry(attributes=attr)

    mesh_attr = {}
    if coloring != 'NoColors':
        mesh_attr['vertexColors'] = coloring

    if use_edge_coloring:
        edge_color = prop.GetEdgeColor()
    elif color is not None:
        edge_color = color
    else:
        edge_color = prop.GetColor()

    opacity = prop.GetOpacity() if opacity is None else opacity
    edge_mat = tjs.LineBasicMaterial(
        color=pv.Color(edge_color).hex_rgb,
        linewidth=prop.GetLineWidth(),
        opacity=opacity,
        side='FrontSide',
        **mesh_attr,
    )
    return tjs.LineSegments(edge_geo, edge_mat)


def to_tjs_points(dataset, prop, coloring, lookup_table, color=None, opacity=None):
    """Extract the points from a dataset and return a buffered geometry."""
    attr = {
        'position': array_to_float_buffer(dataset.points),
    }

    if coloring == 'VertexColors':
        colors = map_scalars(lookup_table, dataset.point_data.active_scalars)
        attr['color'] = array_to_float_buffer(colors)

    geo = tjs.BufferGeometry(attributes=attr)

    color = pv.Color(prop.GetColor()).hex_rgb if color is None else color
    opacity = prop.GetOpacity() if opacity is None else opacity
    m_attr = {
        'color': color,
        'size': prop.GetPointSize() / 100,
        'vertexColors': coloring,
        'opacity': opacity,
        'transparent': opacity < 1.0,
    }

    point_mat = tjs.PointsMaterial(**m_attr)
    return tjs.Points(geo, point_mat)


def pvcamera_to_threejs_camera(pv_camera, lights, aspect):
    """Return an ipygany camera dict from a ``pyvista.Plotter`` object."""
    # scene will be centered at focal_point, so adjust the position
    position = np.array(pv_camera.position) - np.array(pv_camera.focal_point)
    far = np.linalg.norm(position) * 100000

    return tjs.PerspectiveCamera(
        up=pv_camera.up,
        children=lights,
        position=position.tolist(),
        fov=pv_camera.view_angle,
        aspect=aspect,
        far=far,
        near=0.01,
    )


def pvlight_to_threejs_light(pvlight):
    """Convert a pyvista headlight into a three.js directional light."""
    if pvlight.is_camera_light or pvlight.is_headlight:
        # extend the position of the light to make "near infinite"
        position = np.array(pvlight.position) * 100000
        return tjs.DirectionalLight(
            color=pvlight.diffuse_color.linear_to_srgb().hex_rgb,
            position=position.tolist(),
            intensity=pvlight.intensity,
        )


def extract_lights_from_renderer(renderer):
    """Extract and convert all pyvista lights to pythreejs compatible lights."""
    return [pvlight_to_threejs_light(pvlight) for pvlight in renderer.lights]


def dataset_to_mesh(
    dataset,
    prop,
    texture,
    focal_point,
    coloring,
    scalar_mode,
    color_mode,
    lookup_table,
    color=None,
    opacity=None,
):
    """Convert a VTK dataset to a threejs mesh or meshes."""
    has_faces = True
    if hasattr(dataset, 'faces'):
        has_faces = np.any(dataset.faces)

    rep_type = prop.GetRepresentationAsString()

    # PolyData vertices should always be rendered
    has_verts = False
    if isinstance(dataset, pv.PolyData):
        has_verts = dataset.verts.any()

    meshes = []
    if rep_type == 'Surface' and has_faces:
        surf = extract_surface_mesh(dataset)
        add_attr = {}
        if prop.GetEdgeVisibility():
            # must offset polygons to have mesh render property with lines
            add_attr = {'polygonOffset': True, 'polygonOffsetFactor': 1, 'polygonOffsetUnits': 1}

            meshes.append(
                to_edge_mesh(
                    surf,
                    prop,
                    coloring,
                    scalar_mode,
                    lookup_table,
                    use_edge_coloring=True,
                    color=color,
                    opacity=opacity,
                )
            )

        meshes.append(
            to_surf_mesh(
                surf,
                texture,
                prop,
                scalar_mode,
                color_mode,
                lookup_table,
                coloring,
                add_attr,
                color=color,
                opacity=opacity,
            )
        )

    elif rep_type == 'Points':
        meshes.append(
            to_tjs_points(dataset, prop, coloring, lookup_table, color=color, opacity=opacity)
        )

    if has_verts:
        # extract just vertices
        poly_points = dataset.extract_cells(dataset.verts[1::2])
        meshes.append(
            to_tjs_points(poly_points, prop, coloring, lookup_table, color=color, opacity=opacity)
        )

    if rep_type not in ['Surface', 'Points']:
        if has_faces:
            surf = extract_surface_mesh(dataset)
            mesh = to_edge_mesh(
                surf,
                prop,
                coloring,
                scalar_mode,
                lookup_table,
                use_edge_coloring=False,
                color=color,
                opacity=opacity,
            )
            meshes.append(mesh)
        elif np.any(dataset.lines):
            mesh = to_edge_mesh(
                dataset,
                prop,
                coloring,
                scalar_mode,
                lookup_table,
                use_edge_coloring=False,
                use_lines=True,
            )
            meshes.append(mesh)
        else:  # pragma: no cover
            warnings.warn(f'Empty or unsupported dataset {type(dataset)}.')

    # the camera in three.js has no concept of a "focal point".  In
    # three.js, the scene is always centered at the origin, which
    # serves as the focal point of the camera.  Therefore, we need to
    # shift the entire scene by the focal point of the pyvista camera
    for mesh in meshes:
        mesh.position = -focal_point[0], -focal_point[1], -focal_point[2]

    return meshes


def meshes_from_actors(actors, focal_point):
    """Convert VTK actors to threejs meshes.

    Parameters
    ----------
    actors : list[vtk.vtkActor]
        List of VTK actors.

    focal_point : sequence
        Length three sequence representing the focal point of the camera.

    Returns
    -------
    list
        List of :class:`pythreejs.Mesh`.

    """
    meshes = []
    for actor in actors:
        mapper = actor.GetMapper()
        if mapper is None:
            continue

        # ignore any mappers whose inputs are not datasets
        if isinstance(mapper, pv.CompositePolyDataMapper):
            prop = actor.GetProperty()
            block_attrs = mapper.block_attr
            for i, dataset in enumerate(mapper.dataset):
                # individual block opacity might be different
                block_attr = block_attrs[i + 1]
                mesh = dataset_to_mesh(
                    dataset,
                    prop,
                    None,
                    focal_point,
                    get_coloring(mapper, dataset),
                    mapper.GetScalarModeAsString(),
                    mapper.GetColorMode(),
                    mapper.GetLookupTable(),
                    color=block_attr.color,
                    opacity=block_attr.opacity,
                )
                meshes.extend(mesh)
        elif not hasattr(mapper, 'GetInputAsDataSet'):
            continue
        else:
            dataset = pv.wrap(mapper.GetInputAsDataSet())
            mesh = dataset_to_mesh(
                dataset,
                actor.GetProperty(),
                actor.GetTexture(),
                focal_point,
                get_coloring(mapper, dataset),
                mapper.GetScalarModeAsString(),
                mapper.GetColorMode(),
                mapper.GetLookupTable(),
            )
            meshes.extend(mesh)

    return meshes


def convert_renderer(pv_renderer):
    """Convert a pyvista renderer to a pythreejs widget."""
    # verify plotter hasn't been closed

    width, height = pv_renderer.width, pv_renderer.height
    pv_camera = pv_renderer.camera
    children = meshes_from_actors(pv_renderer.actors.values(), pv_camera.focal_point)

    lights = extract_lights_from_renderer(pv_renderer)
    aspect = width / height
    camera = pvcamera_to_threejs_camera(pv_camera, lights, aspect)

    children.append(camera)

    if pv_renderer.axes_enabled:
        children.append(tjs.AxesHelper(0.1))

    scene = tjs.Scene(children=children, background=pv_renderer.background_color.hex_rgb)

    # replace inf with a real value here due to changes in
    # ipywidges==6.4.0 see
    # https://github.com/ipython/ipykernel/issues/771
    inf = 1e20
    orbit_controls = tjs.OrbitControls(
        controlling=camera,
        maxAzimuthAngle=inf,
        maxDistance=inf,
        maxZoom=inf,
        minAzimuthAngle=-inf,
    )

    renderer = tjs.Renderer(
        camera=camera,
        scene=scene,
        alpha=True,
        clearOpacity=0,
        controls=[orbit_controls],
        width=width,
        height=height,
        antialias=pv_renderer.GetUseFXAA(),
    )

    if pv_renderer.has_border:
        bdr_color = pv_renderer.border_color.hex_rgb
        renderer.layout.border = f'solid {pv_renderer.border_width}px {bdr_color}'

    # for now, we can't dynamically size the render windows.  If
    # unset, the renderer widget will attempt to resize and the
    # threejs renderer will not resize.
    # renderer.layout.width = f'{width}px'
    # renderer.layout.height = f'{height}px'
    return renderer


def convert_plotter(pl):
    """Convert a pyvista plotter to a pythreejs widget."""
    if pl.render_window is None:
        raise AttributeError(
            'This plotter is closed and unable to export to html.\n'
            'Please run this before showing or closing the plotter.'
        )

    if len(pl.renderers) == 1:
        # return HBox(children=(convert_renderer(pl.renderers[0]),))
        return convert_renderer(pl.renderers[0])

    # otherwise, determine if we can use a grid layout
    if len(pl.shape) == 2:
        n_row = pl.shape[0]
        n_col = pl.shape[1]
        grid = GridspecLayout(int(n_row), int(n_col))
        width, height = 0, 0
        for i in range(n_row):
            for j in range(n_col):
                pv_ren = pl.renderers[j + n_row * i]
                if j == 0:
                    height += pv_ren.height + pv_ren.border_width * 2
                if i == 0:
                    width += pv_ren.width + pv_ren.border_width * 2
                grid[i, j] = convert_renderer(pv_ren)

        # check for linked cameras
        cameras = [ren.camera for ren in pl.renderers]
        for cc, camera_a in enumerate(cameras):
            for dd, camera_b in enumerate(cameras[cc + 1 :], start=cc + 1):
                if camera_a is camera_b:
                    # flatten indices
                    ii_source, jj_source = divmod(cc, n_col)
                    ii_target, jj_target = divmod(dd, n_col)
                    # Must link camera and controls
                    grid[ii_target, jj_target].camera = grid[ii_source, jj_source].camera
                    grid[ii_target, jj_target].controls = grid[ii_source, jj_source].controls

        # this is important to ignore when building the gallery
        if not pv.BUILDING_GALLERY:
            grid.layout.width = f'{width}px'
            grid.layout.height = f'{height+4}px'

        return grid

    raise RuntimeError(
        'Unsupported plotter shape.  The ``pythreejs`` backend only '
        'supports single or regular grids of plots'
    )


# pyvista/plotting/__init__.py

"""Plotting routines."""

from pyvista import MAX_N_COLOR_BARS
from .charts import Chart, Chart2D, ChartMPL, ChartBox, ChartPie
from .colors import (
    Color,
    ColorLike,
    color_char_to_word,
    get_cmap_safe,
    hexcolors,
    PARAVIEW_BACKGROUND,
)
from .composite_mapper import CompositeAttributes, BlockAttributes, CompositePolyDataMapper
from .export_vtkjs import export_plotter_vtkjs, get_vtkjs_url
from .helpers import plot, plot_arrows, plot_compare_four
from .plotting import BasePlotter, Plotter, close_all
from ._property import Property
from .renderer import CameraPosition, Renderer, scale_point
from .tools import (
    check_matplotlib_vtk_compatibility,
    check_math_text_support,
    create_axes_marker,
    create_axes_orientation_box,
    opacity_transfer_function,
    FONTS,
    system_supports_plotting,
    parse_font_family,
)
from .widgets import WidgetHelper
from .lights import Light
from .camera import Camera
from .axes import Axes
from .axes_actor import AxesActor
from .actor import Actor
from .actor_properties import ActorProperties
from .mapper import DataSetMapper, _BaseMapper
from .lookup_table import LookupTable
from .cube_axes_actor import CubeAxesActor


class QtDeprecationError(Exception):
    """Depreciation Error for features that moved to `pyvistaqt`."""

    message = """`{}` has moved to pyvistaqt.
    You can install this from PyPI with: `pip install pyvistaqt`
    Then import it via: `from pyvistaqt import {}`
    `{}` is no longer accessible by `pyvista.{}`
    See https://github.com/pyvista/pyvistaqt
"""

    def __init__(self, feature_name):
        """Empty init."""
        Exception.__init__(self, self.message.format(*[feature_name] * 4))


class BackgroundPlotter:
    """This class has been moved to pyvistaqt."""

    def __init__(self, *args, **kwargs):
        """Empty init."""
        raise QtDeprecationError('BackgroundPlotter')


class QtInteractor:
    """This class has been moved to pyvistaqt."""

    def __init__(self, *args, **kwargs):
        """Empty init."""
        raise QtDeprecationError('QtInteractor')


# pyvista/plotting/_plotting.py

"""These are private methods we keep out of plotting.py to simplify the module."""
import warnings

import numpy as np

import pyvista
from pyvista.utilities import assert_empty_kwargs, get_array

from ..utilities.misc import PyVistaDeprecationWarning
from .colors import Color
from .opts import InterpolationType
from .tools import opacity_transfer_function

USE_SCALAR_BAR_ARGS = """
"stitle" is a deprecated keyword argument and will be removed in a future
release.

Use ``scalar_bar_args`` instead.  For example:

scalar_bar_args={'title': 'Scalar Bar Title'}
"""


def prepare_smooth_shading(mesh, scalars, texture, split_sharp_edges, feature_angle, preference):
    """Prepare a dataset for smooth shading.

    VTK requires datasets with Phong shading to have active normals.
    This requires extracting the external surfaces from non-polydata
    datasets and computing the point normals.

    Parameters
    ----------
    mesh : pyvista.DataSet
        Dataset to prepare smooth shading for.

    scalars : sequence
        Sequence of scalars.

    texture : vtk.vtkTexture or np.ndarray or bool, optional
        A texture to apply to the mesh.

    split_sharp_edges : bool
        Split sharp edges exceeding 30 degrees when plotting with
        smooth shading.  Control the angle with the optional
        keyword argument ``feature_angle``.  By default this is
        ``False``.  Note that enabling this will create a copy of
        the input mesh within the plotter.  See
        :ref:`shading_example`.

    feature_angle : float
        Angle to consider an edge a sharp edge.

    preference : str
        If the number of points is identical to the number of cells.
        Either ``'point'`` or ``'cell'``.

    Returns
    -------
    pyvista.PolyData
        Always a surface as we need to compute point normals.

    """
    is_polydata = isinstance(mesh, pyvista.PolyData)
    indices_array = None

    has_scalars = scalars is not None
    use_points = False
    if has_scalars:
        if not isinstance(scalars, np.ndarray):
            scalars = np.array(scalars)
        if scalars.shape[0] == mesh.n_points and scalars.shape[0] == mesh.n_cells:
            use_points = preference == 'point'
        else:
            use_points = scalars.shape[0] == mesh.n_points

    # extract surface if not already a surface
    if not is_polydata:
        mesh = mesh.extract_surface(
            pass_pointid=use_points or texture is not None,
            pass_cellid=not use_points,
        )
        if use_points:
            indices_array = 'vtkOriginalPointIds'
        else:
            indices_array = 'vtkOriginalCellIds'

    if split_sharp_edges:
        mesh = mesh.compute_normals(
            cell_normals=False,
            split_vertices=True,
            feature_angle=feature_angle,
        )
        if is_polydata:
            if has_scalars and use_points:
                # we must track the original IDs with our own array from compute_normals
                indices_array = 'pyvistaOriginalPointIds'
    else:
        # consider checking if mesh contains active normals
        # if mesh.point_data.active_normals is None:
        mesh.compute_normals(cell_normals=False, inplace=True)

    if has_scalars and indices_array is not None:
        ind = mesh[indices_array]
        scalars = np.asarray(scalars)[ind]

    return mesh, scalars


def process_opacity(mesh, opacity, preference, n_colors, scalars, use_transparency):
    """Process opacity.

    This function accepts an opacity string or array and always
    returns an array that can be applied to a dataset for plotting.

    Parameters
    ----------
    mesh : pyvista.DataSet
        Dataset to process the opacity for.

    opacity : str, sequence
        String or array.  If string, can be a ``str`` name of a
        predefined mapping such as ``'linear'``, ``'geom'``,
        ``'sigmoid'``, ``'sigmoid3-10'``, or the key of a cell or
        point data array.

    preference : str
        When ``mesh.n_points == mesh.n_cells``, this parameter
        sets how the scalars will be mapped to the mesh. If
        ``'point'``, causes the scalars will be associated with
        the mesh points.  Can be either ``'point'`` or
        ``'cell'``.

    n_colors : int
        Number of colors to use when displaying the opacity.

    scalars : numpy.ndarray
        Dataset scalars.

    use_transparency : bool
        Invert the opacity mappings and make the values correspond
        to transparency.

    Returns
    -------
    custom_opac : bool
        If using custom opacity.

    opacity : numpy.ndarray
        Array containing the opacity.

    """
    custom_opac = False
    if isinstance(opacity, str):
        try:
            # Get array from mesh
            opacity = get_array(mesh, opacity, preference=preference, err=True)
            if np.any(opacity > 1):
                warnings.warn("Opacity scalars contain values over 1")
            if np.any(opacity < 0):
                warnings.warn("Opacity scalars contain values less than 0")
            custom_opac = True
        except KeyError:
            # Or get opacity transfer function (e.g. "linear")
            opacity = opacity_transfer_function(opacity, n_colors)
        else:
            if scalars.shape[0] != opacity.shape[0]:
                raise ValueError(
                    "Opacity array and scalars array must have the same number of elements."
                )
    elif isinstance(opacity, (np.ndarray, list, tuple)):
        opacity = np.asanyarray(opacity)
        if opacity.shape[0] in [mesh.n_cells, mesh.n_points]:
            # User could pass an array of opacities for every point/cell
            custom_opac = True
        else:
            opacity = opacity_transfer_function(opacity, n_colors)

    if use_transparency:
        if np.max(opacity) <= 1.0:
            opacity = 1 - opacity
        elif isinstance(opacity, np.ndarray):
            opacity = 255 - opacity

    return custom_opac, opacity


def _common_arg_parser(
    dataset,
    theme,
    n_colors,
    scalar_bar_args,
    split_sharp_edges,
    show_scalar_bar,
    render_points_as_spheres,
    smooth_shading,
    pbr,
    clim,
    cmap,
    culling,
    name,
    nan_color,
    nan_opacity,
    color,
    texture,
    rgb,
    style,
    **kwargs,
):
    """Parse arguments in common between add_volume, composite, and mesh."""
    # supported aliases
    clim = kwargs.pop('rng', clim)
    cmap = kwargs.pop('colormap', cmap)
    culling = kwargs.pop("backface_culling", culling)
    rgb = kwargs.pop('rgba', rgb)
    vertex_color = kwargs.pop('vertex_color', theme.edge_color)
    vertex_style = kwargs.pop('vertex_style', 'points')
    vertex_opacity = kwargs.pop('vertex_opacity', 1.0)

    # Support aliases for 'back', 'front', or 'none'. Consider deprecating
    if culling is False:
        culling = 'none'
    elif culling in ['b', 'backface', True]:
        culling = 'back'
    elif culling in ['f', 'frontface']:
        culling = 'front'

    if show_scalar_bar is None:
        # use theme unless plotting RGB
        _default = theme.show_scalar_bar or scalar_bar_args
        show_scalar_bar = False if rgb else _default
    # Avoid mutating input
    if scalar_bar_args is None:
        scalar_bar_args = {'n_colors': n_colors}
    else:
        scalar_bar_args = scalar_bar_args.copy()

    # theme based parameters
    if split_sharp_edges is None:
        split_sharp_edges = theme.split_sharp_edges
    feature_angle = kwargs.pop('feature_angle', theme.sharp_edges_feature_angle)
    if render_points_as_spheres is None:
        if style == 'points_gaussian':
            render_points_as_spheres = False
        else:
            render_points_as_spheres = theme.render_points_as_spheres

    if smooth_shading is None:
        if pbr:
            smooth_shading = True
        else:
            smooth_shading = theme.smooth_shading

    if name is None:
        name = f'{type(dataset).__name__}({dataset.memory_address})'
        remove_existing_actor = False
    else:
        # check if this actor already exists
        remove_existing_actor = True

    nan_color = Color(nan_color, opacity=nan_opacity, default_color=theme.nan_color)

    if color is True:
        color = theme.color

    if texture is False:
        texture = None

    # allow directly specifying interpolation (potential future feature)
    if 'interpolation' in kwargs:
        interpolation = kwargs.pop('interpolation')  # pragma: no cover:
    elif pbr:
        interpolation = InterpolationType.PBR
    elif smooth_shading:
        interpolation = InterpolationType.PHONG
    else:
        interpolation = theme.lighting_params.interpolation

    # account for legacy behavior
    if 'stitle' in kwargs:  # pragma: no cover
        # Deprecated on v0.37.0, estimated removal on v0.40.0
        warnings.warn(USE_SCALAR_BAR_ARGS, PyVistaDeprecationWarning)
        scalar_bar_args.setdefault('title', kwargs.pop('stitle'))

    if "scalar" in kwargs:
        raise TypeError(
            "`scalar` is an invalid keyword argument. Perhaps you mean `scalars` with an s?"
        )

    assert_empty_kwargs(**kwargs)
    return (
        scalar_bar_args,
        split_sharp_edges,
        show_scalar_bar,
        feature_angle,
        render_points_as_spheres,
        smooth_shading,
        clim,
        cmap,
        culling,
        name,
        nan_color,
        color,
        texture,
        rgb,
        interpolation,
        remove_existing_actor,
        vertex_color,
        vertex_style,
        vertex_opacity,
    )


# pyvista/plotting/_property.py

"""This module contains the Property class."""
from typing import Union

import pyvista as pv
from pyvista import _vtk
from pyvista.plotting.opts import InterpolationType
from pyvista.utilities.misc import _check_range, no_new_attr

from .colors import Color


@no_new_attr
class Property(_vtk.vtkProperty):
    """Wrap vtkProperty and expose it pythonically.

    This class is used to set the property of actors.

    Parameters
    ----------
    theme : pyvista.themes.DefaultTheme, optional
        Plot-specific theme.

    interpolation : str, default: :attr:`pyvista.themes._LightingConfig.interpolation`
        Set the method of shading. One of the following:

        * ``'Physically based rendering'`` - Physically based rendering.
        * ``'pbr'`` - Alias for Physically based rendering.
        * ``'Phong'`` - Phong shading.
        * ``'Gouraud'`` - Gouraud shading.
        * ``'Flat'`` - Flat Shading.

        This parameter is case insensitive.

    color : ColorLike, default: :attr:`pyvista.themes.DefaultTheme.color`
        Used to make the entire mesh have a single solid color.
        Either a string, RGB list, or hex color string.  For example:
        ``color='white'``, ``color='w'``, ``color=[1.0, 1.0, 1.0]``, or
        ``color='#FFFFFF'``. Color will be overridden if scalars are
        specified.

    style : str, default: 'surface'
        Visualization style of the mesh.  One of the following:
        ``style='surface'``, ``style='wireframe'``, ``style='points'``.
        Note that ``'wireframe'`` only shows a wireframe of the outer
        geometry.

    metallic : float, default: :attr:`pyvista.themes._LightingConfig.metallic`
        Usually this value is either 0 or 1 for a real material but any
        value in between is valid. This parameter is only used by PBR
        interpolation.

    roughness : float, default: :attr:`pyvista.themes._LightingConfig.roughness`
        This value has to be between 0 (glossy) and 1 (rough). A glossy
        material has reflections and a high specular part. This parameter
        is only used by PBR interpolation.

    point_size : float, default: :attr:`pyvista.themes.DefaultTheme.point_size`
        Size of the points represented by this property.

    opacity : float, default: :attr:`pyvista.themes.DefaultTheme.opacity`
        Opacity of the mesh. A single float value that will be applied globally
        opacity of the mesh and uniformly applied everywhere - should be
        between 0 and 1.

    ambient : float, default: :attr:`pyvista.themes._LightingConfig.ambient`
        When lighting is enabled, this is the amount of light in the range
        of 0 to 1 that reaches the actor when not directed at the light
        source emitted from the viewer.

    diffuse : float, default: :attr:`pyvista.themes._LightingConfig.diffuse`
        The diffuse lighting coefficient.

    specular : float, default: :attr:`pyvista.themes._LightingConfig.specular`
        The specular lighting coefficient.

    specular_power : float, default: :attr:`pyvista.themes._LightingConfig.specular_power`
        The specular power. Must be between 0.0 and 128.0.

    show_edges : bool, default: :attr:`pyvista.themes.DefaultTheme.show_edges`
        Shows the edges.  Does not apply to a wireframe representation.

    edge_color : ColorLike, default: :attr:`pyvista.themes.DefaultTheme.edge_color`
        The solid color to give the edges when ``show_edges=True``.
        Either a string, RGB list, or hex color string.

    render_points_as_spheres : bool, default: :attr:`pyvista.themes.DefaultTheme.render_points_as_spheres`
        Render points as spheres rather than dots.

    render_lines_as_tubes : bool, default: :attr:`pyvista.themes.DefaultTheme.render_lines_as_tubes`
        Show lines as thick tubes rather than flat lines.  Control
        the width with ``line_width``.

    lighting : bool, default: :attr:`pyvista.themes.DefaultTheme.lighting`
        Enable or disable view direction lighting.

    line_width : float, default: :attr:`pyvista.themes.DefaultTheme.line_width`
        Thickness of lines.  Only valid for wireframe and surface
        representations.

    culling : str | bool, optional
        Does not render faces that are culled. This can be helpful for
        dense surface meshes, especially when edges are visible, but can
        cause flat meshes to be partially displayed. Defaults to
        ``'none'``. One of the following:

        * ``"back"`` - Enable backface culling
        * ``"front"`` - Enable frontface culling
        * ``'none'`` - Disable both backface and frontface culling

    Examples
    --------
    Create a :class:`pyvista.Actor` and assign properties to it.

    >>> import pyvista as pv
    >>> actor = pv.Actor()
    >>> actor.prop = pv.Property(
    ...     color='r',
    ...     show_edges=True,
    ...     interpolation='Physically based rendering',
    ...     metallic=0.5,
    ...     roughness=0.1,
    ... )

    Visualize how the property would look when applied to a mesh.

    >>> actor.prop.plot()

    Set custom properties not directly available in
    :func:`pyvista.Plotter.add_mesh`. Here, we set diffuse, ambient, and
    specular power and colors.

    >>> pl = pv.Plotter()
    >>> actor = pl.add_mesh(pv.Sphere())
    >>> prop = actor.prop
    >>> prop.diffuse = 0.6
    >>> prop.diffuse_color = 'w'
    >>> prop.ambient = 0.3
    >>> prop.ambient_color = 'r'
    >>> prop.specular = 0.5
    >>> prop.specular_color = 'b'
    >>> pl.show()

    """

    _theme = None
    _color_set = None

    def __init__(
        self,
        theme=None,
        interpolation=None,
        color=None,
        style='surface',
        metallic=None,
        roughness=None,
        point_size=None,
        opacity=None,
        ambient=None,
        diffuse=None,
        specular=None,
        specular_power=None,
        show_edges=None,
        edge_color=None,
        render_points_as_spheres=None,
        render_lines_as_tubes=None,
        lighting=None,
        line_width=None,
        culling=None,
    ):
        """Initialize this property."""
        self._theme = pv.themes.DefaultTheme()
        if theme is None:
            # copy global theme to ensure local property theme is fixed
            # after creation.
            self._theme.load_theme(pv.global_theme)
        else:
            self._theme.load_theme(theme)

        if interpolation is None:
            interpolation = self._theme.lighting_params.interpolation
        self.interpolation = interpolation

        self.color = color

        if style is not None:
            self.style = style

        if self.interpolation == InterpolationType.PBR:
            if metallic is None:
                metallic = self._theme.lighting_params.metallic
            self.metallic = metallic
            if roughness is None:
                roughness = self._theme.lighting_params.roughness
            self.roughness = roughness

        if point_size is None:
            point_size = self._theme.point_size
        self.point_size = point_size
        if opacity is None:
            opacity = self._theme.opacity
        self.opacity = opacity
        if ambient is None:
            ambient = self._theme.lighting_params.ambient
        self.ambient = ambient
        if diffuse is None:
            diffuse = self._theme.lighting_params.diffuse
        self.diffuse = diffuse
        if specular is None:
            specular = self._theme.lighting_params.specular
        self.specular = specular
        if specular_power is None:
            specular_power = self._theme.lighting_params.specular_power
        self.specular_power = specular_power

        if show_edges is None:
            self.show_edges = self._theme.show_edges
        else:
            self.show_edges = show_edges

        self.edge_color = edge_color
        if render_points_as_spheres is None:
            render_points_as_spheres = self._theme.render_points_as_spheres
        self.render_points_as_spheres = render_points_as_spheres
        if render_lines_as_tubes is None:
            render_lines_as_tubes = self._theme.render_lines_as_tubes
        self.render_lines_as_tubes = render_lines_as_tubes
        self.lighting = lighting
        if line_width is None:
            line_width = self._theme.line_width
        self.line_width = line_width
        if culling is not None:
            self.culling = culling

    @property
    def style(self) -> str:
        """Return or set Visualization style of the mesh.

        One of the following (case insensitive):

        * ``'surface'``
        * ``'wireframe'``
        * ``'points'``

        Examples
        --------
        Set the representation style to ``'Wireframe'``

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.style = 'wireframe'
        >>> prop.style
        'Wireframe'

        Visualize default surface representation style.

        >>> prop.style = 'surface'
        >>> prop.plot()

        Visualize wireframe representation style.

        >>> prop.style = 'wireframe'
        >>> prop.plot()

        Visualize points representation style.

        >>> prop.style = 'points'
        >>> prop.point_size = 5.0
        >>> prop.plot()
        """
        return self.GetRepresentationAsString()

    @style.setter
    def style(self, new_style: str):
        new_style = new_style.lower()

        if new_style == 'wireframe':
            self.SetRepresentationToWireframe()
            if not self._color_set:
                self.color = self._theme.outline_color  # type: ignore
        elif new_style == 'points':
            self.SetRepresentationToPoints()
        elif new_style == 'surface':
            self.SetRepresentationToSurface()
        else:
            raise ValueError(
                f'Invalid style "{new_style}".  Must be one of the following:\n'
                '\t"surface"\n'
                '\t"wireframe"\n'
                '\t"points"\n'
            )

    @property
    def color(self) -> Color:
        """Return or set the color of this property.

        Either a string, RGB list, or hex color string.  For example:
        ``color='white'``, ``color='w'``, ``color=[1.0, 1.0, 1.0]``, or
        ``color='#FFFFFF'``. Color will be overridden if scalars are
        specified.

        Examples
        --------
        Set the color to blue.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.color = 'b'
        >>> prop.color
        Color(name='blue', hex='#0000ffff', opacity=255)

        Visualize setting the property to blue.

        >>> prop.color = 'b'
        >>> prop.plot()

        Visualize setting the color using an RGB value.

        >>> prop.color = (0.5, 0.5, 0.1)
        >>> prop.plot()

        """
        return Color(self.GetColor())

    @color.setter
    def color(self, value):
        self._color_set = value is not None
        rgb_color = Color(value, default_color=self._theme.color)
        self.SetColor(rgb_color.float_rgb)

    @property
    def edge_color(self) -> Color:
        """Return or set the edge color of this property.

        The solid color to give the edges when ``show_edges=True``.
        Either a string, RGB list, or hex color string.

        Examples
        --------
        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.edge_color = 'red'
        >>> prop.edge_color
        Color(name='red', hex='#ff0000ff', opacity=255)

        Visualize red edges. Set the edge's visibility to ``True`` so we can see
        them.

        >>> prop.show_edges = True
        >>> prop.edge_color = 'red'
        >>> prop.plot()

        """
        return Color(self.GetEdgeColor())

    @edge_color.setter
    def edge_color(self, value):
        rgb_color = Color(value, default_color=self._theme.edge_color)
        self.SetEdgeColor(rgb_color.float_rgb)

    @property
    def opacity(self) -> float:
        """Return or set the opacity of this property.

        Opacity of the mesh. A single float value that will be applied globally
        opacity of the mesh and uniformly applied everywhere. Between 0 and 1.

        Examples
        --------
        Set opacity to ``0.5``.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.opacity = 0.5
        >>> prop.opacity
        0.5

        Visualize default opacity of ``1.0``.

        >>> prop.opacity = 1.0
        >>> prop.plot()

        Visualize opacity of ``0.75``.

        >>> prop.opacity = 0.75
        >>> prop.plot()

        Visualize opacity of ``0.25``.

        >>> prop.opacity = 0.25
        >>> prop.plot()


        """
        return self.GetOpacity()

    @opacity.setter
    def opacity(self, value: float):
        _check_range(value, (0, 1), 'opacity')
        self.SetOpacity(value)

    @property
    def show_edges(self) -> bool:
        """Return or set the visibility of edges.

        Shows or hides the edges.  Does not apply to a wireframe
        representation.

        Examples
        --------
        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.show_edges = True
        >>> prop.show_edges
        True

        Visualize default edge visibility of ``False``.

        >>> prop.show_edges = False
        >>> prop.plot()

        Visualize edge visibility of ``True``.

        >>> prop.show_edges = True
        >>> prop.plot()

        """
        return bool(self.GetEdgeVisibility())

    @show_edges.setter
    def show_edges(self, value: bool):
        self.SetEdgeVisibility(value)

    @property
    def lighting(self) -> bool:
        """Return or set view direction lighting.

        Examples
        --------
        Disable lighting.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.lighting = False
        >>> prop.lighting
        False

        Visualize it.

        >>> prop.plot()

        """
        return self.GetLighting()

    @lighting.setter
    def lighting(self, value: bool):
        if value is None:
            value = self._theme.lighting
        self.SetLighting(value)

    @property
    def ambient(self) -> float:
        """Return or set ambient.

        Default :attr:`pyvista.themes._LightingConfig.ambient`.

        When lighting is enabled, this is the amount of light in the range
        of 0 to 1 that reaches the actor when not directed at the light
        source emitted from the viewer.

        Examples
        --------
        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.ambient = 0.2
        >>> prop.ambient
        0.2

        Visualize default ambient light.

        >>> prop.ambient = 0.0
        >>> prop.plot()

        Visualize ambient at ``0.5``.

        >>> prop.ambient = 0.5
        >>> prop.plot()

        Visualize ambient at ``1.0``.

        >>> prop.ambient = 1.0
        >>> prop.plot()

        """
        return self.GetAmbient()

    @ambient.setter
    def ambient(self, value: float):
        _check_range(value, (0, 1), 'ambient')
        self.SetAmbient(value)

    @property
    def diffuse(self) -> float:
        """Return or set the diffuse lighting coefficient.

        Default :attr:`pyvista.themes._LightingConfig.diffuse`.

        This is the scattering of light by reflection or
        transmission. Diffuse reflection results when light strikes an
        irregular surface such as a frosted window or the surface of a
        frosted or coated light bulb. Must be between 0 and 1.

        Examples
        --------
        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.diffuse = 0.2
        >>> prop.diffuse
        0.2

        Visualize default diffuse light.

        >>> prop.diffuse = 1.0
        >>> prop.plot()

        Visualize diffuse at ``0.5``.

        >>> prop.diffuse = 0.5
        >>> prop.plot()

        Visualize diffuse at ``0.0``.

        >>> prop.diffuse = 0.0
        >>> prop.plot()

        """
        return self.GetDiffuse()

    @diffuse.setter
    def diffuse(self, value: float):
        _check_range(value, (0, 1), 'diffuse')
        self.SetDiffuse(value)

    @property
    def specular(self) -> float:
        """Return or set specular.

        Default :attr:`pyvista.themes._LightingConfig.specular`.

        Specular lighting simulates the bright spot of a light that appears
        on shiny objects. Must be between 0 and 1.

        Examples
        --------
        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.specular = 0.2
        >>> prop.specular
        0.2

        Visualize default specular light.

        >>> prop.specular = 0.0
        >>> prop.plot()

        Visualize specular at ``0.5``.

        >>> prop.specular = 0.5
        >>> prop.plot()

        Visualize specular at ``1.0``.

        >>> prop.specular = 1.0
        >>> prop.plot()

        """
        return self.GetSpecular()

    @specular.setter
    def specular(self, value: float):
        _check_range(value, (0, 1), 'specular')
        self.SetSpecular(value)

    @property
    def specular_power(self) -> float:
        """Return or set specular power.

        Default :attr:`pyvista.themes._LightingConfig.specular_power`.

        The specular power. Must be between 0.0 and 128.0.

        Examples
        --------
        Set specular power to 5.0

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.specular = 0.1  # enable specular
        >>> prop.specular_power = 5.0
        >>> prop.specular_power
        5.0

        Visualize default specular power.

        >>> prop.specular_power = 1.0
        >>> prop.plot()

        Visualize specular power at ``0.1``.

        >>> prop.specular_power = 0.1
        >>> prop.plot()

        Visualize specular power at ``5.0``.

        >>> prop.specular_power = 5.0
        >>> prop.plot()

        Visualize specular power at ``128.0``.

        >>> prop.specular_power = 128.0
        >>> prop.plot()

        """
        return self.GetSpecularPower()

    @specular_power.setter
    def specular_power(self, value: float):
        _check_range(value, (0, 128), 'specular_power')
        self.SetSpecularPower(value)

    @property
    def metallic(self) -> float:
        """Return or set metallic.

        Default :attr:`pyvista.themes._LightingConfig.metallic`.

        This requires that the interpolation be set to ``'Physically based
        rendering'``. Must be between 0 and 1.

        Examples
        --------
        Set metallic to 0.1

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> # requires physically based rendering
        >>> prop.interpolation = 'pbr'
        >>> prop.metallic = 0.1
        >>> prop.metallic
        0.1

        Visualize default metallic.

        >>> prop.metallic = 0.0
        >>> prop.plot()

        Visualize metallic at ``0.5``.

        >>> prop.metallic = 0.5
        >>> prop.plot()

        Visualize metallic at ``1.0``.

        >>> prop.metallic = 1.0
        >>> prop.plot()

        """
        return self.GetMetallic()

    @metallic.setter
    def metallic(self, value: float):
        _check_range(value, (0, 1), 'metallic')
        self.SetMetallic(value)

    @property
    def roughness(self) -> float:
        """Return or set roughness.

        Default :attr:`pyvista.themes._LightingConfig.roughness`.

        This requires that the interpolation be set to ``'Physically based
        rendering'``. Must be between 0 and 1.

        Examples
        --------
        Set roughness to 0.1

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> # requires physically based rendering
        >>> prop.interpolation = 'pbr'
        >>> prop.metallic = 0.5  # helps to visualize metallic
        >>> prop.roughness = 0.1
        >>> prop.roughness
        0.1

        Visualize default roughness with metallic of ``0.5``.

        >>> prop.roughness = 0.5
        >>> prop.plot()

        Visualize roughness at ``0.0`` with metallic of ``0.5``.

        >>> prop.roughness = 0.0
        >>> prop.plot()

        Visualize roughness at ``1.0`` with metallic of ``0.5``.

        >>> prop.roughness = 1.0
        >>> prop.plot()

        """
        return self.GetRoughness()

    @roughness.setter
    def roughness(self, value: bool):
        _check_range(value, (0, 1), 'roughness')
        self.SetRoughness(value)

    @property
    def interpolation(self) -> InterpolationType:
        """Return or set the method of shading.

        Defaults to :attr:`pyvista.themes._LightingConfig.interpolation`.

        One of the following options.

        * ``'Physically based rendering'`` - Physically based rendering.
        * ``'pbr'`` - Alias for Physically based rendering.
        * ``'Phong'`` - Phong shading.
        * ``'Gouraud'`` - Gouraud shading.
        * ``'Flat'`` - Flat Shading.

        This parameter is case insensitive.

        Examples
        --------
        Set interpolation to physically based rendering.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.interpolation = 'pbr'
        >>> prop.interpolation
        <InterpolationType.PBR: 3>

        Visualize default flat shading.

        >>> prop.interpolation = 'Flat'
        >>> prop.plot()

        Visualize gouraud shading.

        >>> prop.interpolation = 'Gouraud'
        >>> prop.plot()

        Visualize phong shading.

        >>> prop.interpolation = 'Phong'
        >>> prop.plot()

        Visualize physically based rendering.

        >>> prop.interpolation = 'Physically based rendering'
        >>> prop.plot()

        """
        return InterpolationType.from_any(self.GetInterpolation())

    @interpolation.setter
    def interpolation(self, value: Union[str, int, InterpolationType]):
        value = InterpolationType.from_any(value).value
        if value == InterpolationType.PBR:
            self.SetInterpolationToPBR()
        else:
            self.SetInterpolation(value)

    @property
    def render_points_as_spheres(self) -> bool:
        """Return or set rendering points as spheres.

        Defaults to :attr:`pyvista.themes.DefaultTheme.render_points_as_spheres`.

        Requires representation style be set to ``'points'``.

        Examples
        --------
        Enable rendering points as spheres.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.style = 'points'
        >>> prop.point_size = 20
        >>> prop.render_points_as_spheres = True
        >>> prop.render_points_as_spheres
        True

        Visualize default point rendering.

        >>> prop.render_points_as_spheres = False
        >>> prop.plot()

        Visualize rendering points as spheres.

        >>> prop.render_points_as_spheres = True
        >>> prop.plot()

        """
        return self.GetRenderPointsAsSpheres()

    @render_points_as_spheres.setter
    def render_points_as_spheres(self, value: bool):
        self.SetRenderPointsAsSpheres(value)

    @property
    def render_lines_as_tubes(self) -> bool:
        """Return or set rendering lines as tubes.

        Defaults to :attr:`pyvista.themes.DefaultTheme.render_lines_as_tubes`.

        Requires representation style be set to ``'wireframe'``.

        Examples
        --------
        Enable rendering lines as tubes.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.style = 'wireframe'
        >>> prop.line_width = 10
        >>> prop.render_lines_as_tubes = True
        >>> prop.render_lines_as_tubes
        True

        Visualize default line rendering.

        >>> prop.render_lines_as_tubes = False
        >>> prop.plot()

        Visualize rendering lines as tubes

        >>> prop.render_lines_as_tubes = True
        >>> prop.plot()

        """
        return self.GetRenderLinesAsTubes()

    @render_lines_as_tubes.setter
    def render_lines_as_tubes(self, value: bool):
        self.SetRenderLinesAsTubes(value)

    @property
    def line_width(self) -> float:
        """Return or set the line width.

        Defaults to :attr:`pyvista.themes.DefaultTheme.line_width`.

        Examples
        --------
        Change the line width to ``10``.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.line_width = 10
        >>> prop.line_width
        10.0

        Visualize the default line width.

        >>> prop.line_width = 1.0
        >>> prop.show_edges = True
        >>> prop.plot()

        Visualize with a line width of 5.0

        >>> prop.line_width = 5.0
        >>> prop.plot()

        """
        return self.GetLineWidth()

    @line_width.setter
    def line_width(self, value: bool):
        self.SetLineWidth(value)

    @property
    def point_size(self):
        """Return or set the point size.

        Defaults to :attr:`pyvista.themes.DefaultTheme.point_size`.

        Examples
        --------
        Change the point size to ``10.0``.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.point_size = 10
        >>> prop.point_size
        10.0

        Visualize a point size of ``5.0``.

        >>> prop.point_size = 5.0
        >>> prop.style = 'points'
        >>> prop.plot()

        Visualize the a point size of ``10.0``.

        >>> prop.point_size = 10.0
        >>> prop.plot()

        """
        return self.GetPointSize()

    @point_size.setter
    def point_size(self, new_size):
        self.SetPointSize(new_size)

    @property
    def culling(self) -> str:
        """Return or set face culling.

        Does not render faces that are culled. This can be helpful for dense
        surface meshes, especially when edges are visible, but can cause flat
        meshes to be partially displayed. Defaults to ``'none'``. One of the
        following:

        * ``"back"`` - Enable backface culling
        * ``"front"`` - Enable frontface culling
        * ``'none'`` - Disable both backface and frontface culling

        Examples
        --------
        Enable back face culling

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.culling = 'back'
        >>> prop.culling
        'back'

        Plot default culling.

        >>> prop.culling = 'none'
        >>> prop.plot()

        Plot backface culling. This looks the same as the default culling
        ``'none'`` because the forward facing faces are already obscuring the
        back faces.

        >>> prop.culling = 'back'
        >>> prop.plot()

        Plot frontface culling. Here, the forward facing faces are hidden
        entirely.

        >>> prop.culling = 'front'
        >>> prop.plot()

        """
        if self.GetBackfaceCulling():
            return 'back'
        elif self.GetFrontfaceCulling():
            return 'front'
        return 'none'

    @culling.setter
    def culling(self, value):
        if isinstance(value, str):
            value = value.lower()

        if value == 'back':
            try:
                self.BackfaceCullingOn()
                self.FrontfaceCullingOff()
            except AttributeError:  # pragma: no cover
                pass
        elif value == 'front':
            try:
                self.FrontfaceCullingOn()
                self.BackfaceCullingOff()
            except AttributeError:  # pragma: no cover
                pass
        elif value == 'none':
            self.FrontfaceCullingOff()
            self.BackfaceCullingOff()
        else:
            raise ValueError(
                f'Invalid culling "{value}". Should be either:\n' '"back", "front", or "None"'
            )

    @property
    def ambient_color(self) -> Color:
        """Return or set the ambient color of this property.

        Either a string, RGB list, or hex color string.  For example:
        ``color='white'``, ``color='w'``, ``color=[1.0, 1.0, 1.0]``, or
        ``color='#FFFFFF'``. Color will be overridden if scalars are
        specified.

        Examples
        --------
        Set the ambient color to blue.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.ambient_color = 'b'
        >>> prop.ambient_color
        Color(name='blue', hex='#0000ffff', opacity=255)

        Visualize setting the ambient color to blue with ``ambient = 0.1``

        >>> prop.ambient = 0.1
        >>> prop.ambient_color = 'b'
        >>> prop.plot()

        """
        return Color(self.GetAmbientColor())

    @ambient_color.setter
    def ambient_color(self, value):
        self.SetAmbientColor(Color(value).float_rgb)

    @property
    def specular_color(self) -> Color:
        """Return or set the specular color of this property.

        Either a string, RGB list, or hex color string.  For example:
        ``color='white'``, ``color='w'``, ``color=[1.0, 1.0, 1.0]``, or
        ``color='#FFFFFF'``.

        Examples
        --------
        Set the specular color to blue.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.specular_color = 'b'
        >>> prop.specular_color
        Color(name='blue', hex='#0000ffff', opacity=255)

        Visualize setting the specular color to blue with ``specular = 0.2``

        >>> prop.specular = 0.2
        >>> prop.specular_color = 'r'
        >>> prop.plot()

        """
        return Color(self.GetSpecularColor())

    @specular_color.setter
    def specular_color(self, value):
        self.SetSpecularColor(Color(value).float_rgb)

    @property
    def diffuse_color(self) -> Color:
        """Return or set the diffuse color of this property.

        Either a string, RGB list, or hex color string.  For example:
        ``color='white'``, ``color='w'``, ``color=[1.0, 1.0, 1.0]``, or
        ``color='#FFFFFF'``.

        Examples
        --------
        Set the diffuse color to blue.

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop.diffuse_color = 'b'
        >>> prop.diffuse_color
        Color(name='blue', hex='#0000ffff', opacity=255)

        Visualize setting the diffuse color to white with ``diffuse = 0.5``

        >>> prop.diffuse = 0.5
        >>> prop.diffuse_color = 'w'
        >>> prop.plot()

        """
        return Color(self.GetDiffuseColor())

    @diffuse_color.setter
    def diffuse_color(self, value):
        self.SetDiffuseColor(Color(value).float_rgb)

    @property
    def anisotropy(self):
        """Return or set the anisotropy coefficient.

        This value controls the anisotropy of the material (0.0 means
        isotropic). This requires physically based rendering.

        For further details see `PBR Journey Part 2 : Anisotropy model with VTK
        <https://www.kitware.com/pbr-journey-part-2-anisotropy-model-with-vtk/>`_

        Notes
        -----
        This attribute requires VTK v9.1.0 or newer.

        Examples
        --------
        Set anisotropy to 0.1

        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> # requires physically based rendering
        >>> prop.interpolation = 'pbr'
        >>> prop.anisotropy
        0.1

        """
        if not hasattr(self, 'GetAnisotropy'):  # pragma: no cover
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError('Anisotropy requires VTK v9.1.0 or newer.')
        return self.GetAnisotropy()

    @anisotropy.setter
    def anisotropy(self, value: float):
        if not hasattr(self, 'SetAnisotropy'):  # pragma: no cover
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError('Anisotropy requires VTK v9.1.0 or newer.')
        _check_range(value, (0, 1), 'anisotropy')
        self.SetAnisotropy(value)

    def plot(self, **kwargs) -> None:
        """Plot this property on the Stanford Bunny.

        This is useful for visualizing how this property would be applied to an
        actor.

        Parameters
        ----------
        **kwargs : dict, optional
            Keyword arguments for :class:`pyvista.Plotter`.

        Examples
        --------
        >>> import pyvista as pv
        >>> prop = pv.Property(
        ...     show_edges=True,
        ...     color='brown',
        ...     edge_color='blue',
        ...     line_width=4,
        ...     specular=1.0,
        ... )
        >>> prop.plot()

        """
        from pyvista import examples  # avoid circular import

        before_close_callback = kwargs.pop('before_close_callback', None)

        pl = pv.Plotter(**kwargs)
        actor = pl.add_mesh(examples.download_bunny_coarse())
        actor.SetProperty(self)

        if self.interpolation == 'Physically based rendering':
            cubemap = examples.download_sky_box_cube_map()
            pl.set_environment_texture(cubemap)

        pl.camera_position = 'xy'
        pl.show(before_close_callback=before_close_callback)

    def copy(self) -> 'Property':
        """Create a deep copy of this property.

        Returns
        -------
        pyvista.Property
            Deep copy of this property.

        Examples
        --------
        >>> import pyvista as pv
        >>> prop = pv.Property()
        >>> prop_copy = prop.copy()

        """
        new_prop = Property()
        new_prop.DeepCopy(self)
        return new_prop

    def __repr__(self):
        """Representation of this property."""
        from pyvista.core.errors import VTKVersionError

        props = [
            f'{type(self).__name__} ({hex(id(self))})',
        ]

        for attr in dir(self):
            if not attr.startswith('_') and attr[0].islower():
                name = ' '.join(attr.split('_')).capitalize() + ':'
                try:
                    value = getattr(self, attr)
                except VTKVersionError:  # pragma:no cover
                    continue
                if callable(value):
                    continue
                if isinstance(value, str):
                    value = f'"{value}"'
                props.append(f'  {name:28s} {value}')

        return '\n'.join(props)


# pyvista/plotting/actor.py

"""Wrap vtkActor module."""

from typing import Optional, Union

import numpy as np

import pyvista as pv
from pyvista import _vtk
from pyvista.utilities.misc import no_new_attr

from ._property import Property
from .mapper import _BaseMapper
from .prop3d import Prop3D


@no_new_attr
class Actor(Prop3D, _vtk.vtkActor):
    """Wrap vtkActor.

    This class represents the geometry & properties in a rendered
    scene. Normally, a :class:`pyvista.Actor` is constructed from
    :func:`pyvista.Plotter.add_mesh`, but there may be times when it is more
    convenient to construct an actor directly from a
    :class:`pyvista.DataSetMapper`.

    Parameters
    ----------
    mapper : pyvista.DataSetMapper, optional
        DataSetMapper.

    prop : pyvista.Property, optional
        Property of the actor.

    name : str, optional
        The name of this actor used when tracking on a plotter.

    Examples
    --------
    Create an actor without using :class:`pyvista.Plotter`.

    >>> import pyvista as pv
    >>> mesh = pv.Sphere()
    >>> mapper = pv.DataSetMapper(mesh)
    >>> actor = pv.Actor(mapper=mapper)
    >>> actor
    Actor (...)
      Center:                     (0.0, 0.0, 0.0)
      Pickable:                   True
      Position:                   (0.0, 0.0, 0.0)
      Scale:                      (1.0, 1.0, 1.0)
      Visible:                    True
      X Bounds                    -4.993E-01, 4.993E-01
      Y Bounds                    -4.965E-01, 4.965E-01
      Z Bounds                    -5.000E-01, 5.000E-01
      User matrix:                Unset
      Has mapper:                 True
    ...

    Change the actor properties and plot the actor.

    >>> import pyvista as pv
    >>> mesh = pv.Sphere()
    >>> mapper = pv.DataSetMapper(mesh)
    >>> actor = pv.Actor(mapper=mapper)
    >>> actor.prop.color = 'blue'
    >>> actor.plot()

    Create an actor using the :class:`pyvista.Plotter` and then change the
    visibility of the actor.

    >>> import pyvista as pv
    >>> pl = pv.Plotter()
    >>> mesh = pv.Sphere()
    >>> actor = pl.add_mesh(mesh)
    >>> actor.visibility = False
    >>> actor.visibility
    False

    """

    _new_attr_exceptions = ['_name']

    def __init__(self, mapper=None, prop=None, name=None):
        """Initialize actor."""
        super().__init__()
        if mapper is not None:
            self.mapper = mapper
        if prop is None:
            self.prop = Property()
        self._name = name

    @property
    def name(self) -> str:
        """Get or set the unique name identifier used by PyVista."""
        if self._name is None:
            self._name = f'{type(self).__name__}({self.memory_address})'
        return self._name

    @name.setter
    def name(self, value: str):
        if not value:
            raise ValueError('Name must be truthy.')
        self._name = value

    @property
    def mapper(self) -> _BaseMapper:
        """Return or set the mapper of the actor.

        Examples
        --------
        Create an actor and assign a mapper to it.

        >>> import pyvista as pv
        >>> dataset = pv.Sphere()
        >>> actor = pv.Actor()
        >>> actor.mapper = pv.DataSetMapper(dataset)
        >>> actor.mapper
        DataSetMapper (...)
          Scalar visibility:           True
          Scalar range:                (0.0, 1.0)
          Interpolate before mapping:  True
          Scalar map mode:             default
          Color mode:                  direct
        <BLANKLINE>
        Attached dataset:
        PolyData (...)
          N Cells:    1680
          N Points:   842
          N Strips:   0
          X Bounds:   -4.993e-01, 4.993e-01
          Y Bounds:   -4.965e-01, 4.965e-01
          Z Bounds:   -5.000e-01, 5.000e-01
          N Arrays:   1

        """
        return self.GetMapper()

    @mapper.setter
    def mapper(self, obj):
        return self.SetMapper(obj)

    @property
    def prop(self):
        """Return or set the property of this actor.

        Examples
        --------
        Modify the properties of an actor after adding a dataset to the plotter.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(pv.Sphere())
        >>> prop = actor.prop
        >>> prop.diffuse = 0.6
        >>> pl.show()

        """
        return self.GetProperty()

    @prop.setter
    def prop(self, obj: Property):
        self.SetProperty(obj)

    @property
    def texture(self):
        """Return or set the actor texture.

        Notes
        -----
        The mapper dataset must have texture coordinates for the texture to be
        used.

        Examples
        --------
        Create an actor and add a texture to it. Note how the
        :class:`pyvista.PolyData` has texture coordinates by default.

        >>> import pyvista as pv
        >>> from pyvista import examples
        >>> plane = pv.Plane()
        >>> plane.active_t_coords is not None
        True
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(plane)
        >>> actor.texture = examples.download_masonry_texture()
        >>> actor.texture
        Texture (...)
          Components:   3
          Cube Map:     False
          Dimensions:   256, 256

        """
        return self.GetTexture()

    @texture.setter
    def texture(self, obj):
        self.SetTexture(obj)

    @property
    def memory_address(self):
        """Return the memory address of this actor."""
        return self.GetAddressAsString("")

    @property
    def pickable(self) -> bool:
        """Return or set actor pickability.

        Examples
        --------
        Create an actor using the :class:`pyvista.Plotter` and then make the
        actor unpickable.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(pv.Sphere())
        >>> actor.pickable = False
        >>> actor.pickable
        False

        """
        return bool(self.GetPickable())

    @pickable.setter
    def pickable(self, value):
        return self.SetPickable(value)

    @property
    def visibility(self) -> bool:
        """Return or set actor visibility.

        Examples
        --------
        Create an actor using the :class:`pyvista.Plotter` and then change the
        visibility of the actor.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(pv.Sphere())
        >>> actor.visibility = False
        >>> actor.visibility
        False

        """
        return bool(self.GetVisibility())

    @visibility.setter
    def visibility(self, value: bool):
        return self.SetVisibility(value)

    def plot(self, **kwargs):
        """Plot just the actor.

        This may be useful when interrogating or debugging individual actors.

        Parameters
        ----------
        **kwargs : dict, optional
            Optional keyword arguments passed to :func:`pyvista.Plotter.show`.

        Examples
        --------
        Create an actor without the :class:`pyvista.Plotter`, change its
        properties, and plot it.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere()
        >>> mapper = pv.DataSetMapper(mesh)
        >>> actor = pv.Actor(mapper=mapper)
        >>> actor.prop.color = 'red'
        >>> actor.prop.show_edges = True
        >>> actor.plot()

        """
        pl = pv.Plotter()
        pl.add_actor(self)
        pl.show(**kwargs)

    def copy(self, deep=True) -> 'Actor':
        """Create a copy of this actor.

        Parameters
        ----------
        deep : bool, default: True
            Create a shallow or deep copy of the actor. A deep copy will have a
            new property and mapper, while a shallow copy will use the mapper
            and property of this actor.

        Returns
        -------
        pyvista.Actor
            Deep or shallow copy of this actor.

        Examples
        --------
        Create an actor of a cube by adding it to a :class:`pyvista.Plotter`
        and then copy the actor, change the properties, and add it back to the
        :class:`pyvista.Plotter`.

        >>> import pyvista as pv
        >>> mesh = pv.Cube()
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(mesh, color='b')
        >>> new_actor = actor.copy()
        >>> new_actor.prop.style = 'wireframe'
        >>> new_actor.prop.line_width = 5
        >>> new_actor.prop.color = 'r'
        >>> new_actor.prop.lighting = False
        >>> _ = pl.add_actor(new_actor)
        >>> pl.show()

        """
        new_actor = Actor()
        if deep:
            new_actor.mapper = self.mapper.copy()
            new_actor.prop = self.prop.copy()
        else:
            new_actor.ShallowCopy(self)
        return new_actor

    def __repr__(self):
        """Representation of the actor."""
        mat_info = 'Unset' if self.user_matrix is None else 'Set'
        bnd = self.bounds
        attr = [
            f'{type(self).__name__} ({hex(id(self))})',
            f'  Center:                     {self.center}',
            f'  Pickable:                   {self.pickable}',
            f'  Position:                   {self.position}',
            f'  Scale:                      {self.scale}',
            f'  Visible:                    {self.visibility}',
            f'  X Bounds                    {bnd[0]:.3E}, {bnd[1]:.3E}',
            f'  Y Bounds                    {bnd[2]:.3E}, {bnd[3]:.3E}',
            f'  Z Bounds                    {bnd[4]:.3E}, {bnd[5]:.3E}',
            f'  User matrix:                {mat_info}',
            f'  Has mapper:                 {self.mapper is not None}',
            '',
            repr(self.prop),
        ]
        if self.mapper is not None:
            attr.append('')
            attr.append(repr(self.mapper))
        return '\n'.join(attr)

    @property
    def user_matrix(self) -> Optional[np.ndarray]:
        """Return or set the orientation matrix.

        Examples
        --------
        Apply a 4x4 translation to a wireframe actor. This 4x4 transformation
        is effectively translates the actor by one unit in the Z direction,
        rotates the actor about the Z axis by approximately 45 degrees, and
        shrinks the actor by a factor of 0.5.

        >>> import numpy as np
        >>> import pyvista as pv
        >>> mesh = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, color="b")
        >>> actor = pl.add_mesh(
        ...     mesh,
        ...     color="r",
        ...     style="wireframe",
        ...     line_width=5,
        ...     lighting=False,
        ... )
        >>> arr = np.array(
        ...     [
        ...         [0.707, -0.707, 0, 0],
        ...         [0.707, 0.707, 0, 0],
        ...         [0, 0, 1, 1.500001],
        ...         [0, 0, 0, 2],
        ...     ]
        ... )
        >>> actor.user_matrix = arr
        >>> pl.show_axes()
        >>> pl.show()

        """
        mat = self.GetUserMatrix()
        if mat is not None:
            mat = pv.array_from_vtkmatrix(mat)
        return mat

    @user_matrix.setter
    def user_matrix(self, value: Union[pv._vtk.vtkMatrix4x4, np.ndarray]):
        if isinstance(value, np.ndarray):
            value = pv.vtkmatrix_from_array(value)
        self.SetUserMatrix(value)

    @property
    def backface_prop(self) -> Optional['pv.Property']:
        """Return or set the backface property.

        By default this property matches the frontface property
        :attr:`Actor.prop`. Once accessed or modified, this backface
        property becomes independent of the frontface property. In
        order to restore the fallback to frontface property, assign
        ``None`` to the property.

        Returns
        -------
        pyvista.Property
            The object describing backfaces.

        Examples
        --------
        Clip a sphere by a plane and color the inside of the clipped sphere
        light blue using the ``backface_prop``.

        >>> import numpy as np
        >>> import pyvista as pv
        >>> plane = pv.Plane(i_size=1.5, j_size=1.5)
        >>> mesh = pv.Sphere().clip_surface(plane, invert=False)
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(mesh, smooth_shading=True)
        >>> actor.backface_prop.color = 'lightblue'
        >>> _ = pl.add_mesh(
        ...     plane,
        ...     opacity=0.25,
        ...     show_edges=True,
        ...     color='grey',
        ...     lighting=False,
        ... )
        >>> pl.show()

        """
        if self.GetBackfaceProperty() is None:
            self.SetBackfaceProperty(self.prop.copy())
        return self.GetBackfaceProperty()

    @backface_prop.setter
    def backface_prop(self, value: 'pv.Property'):
        self.SetBackfaceProperty(value)


# pyvista/plotting/actor_properties.py

"""Module containing pyvista implementation of vtkProperty."""
import pyvista as pv
from pyvista.plotting.opts import InterpolationType, RepresentationType


class ActorProperties:
    """Properties wrapper for ``vtkProperty``.

    Contains the surface properties of the object.

    Parameters
    ----------
    properties : pv._vtk.vtkProperty
        VTK properties of the current object.

    Examples
    --------
    Access the properties of the z axis shaft.

    >>> import pyvista as pv

    >>> axes = pv.Axes()
    >>> z_axes_prop = axes.axes_actor.z_axis_shaft_properties
    >>> z_axes_prop.color = (1, 1, 0)
    >>> z_axes_prop.opacity = 0.5
    >>> axes.axes_actor.shaft_type = axes.axes_actor.ShaftType.CYLINDER

    >>> pl = pv.Plotter()
    >>> _ = pl.add_actor(axes.axes_actor)
    >>> _ = pl.add_mesh(pv.Sphere())
    >>> pl.show()

    """

    def __init__(self, properties: pv._vtk.vtkProperty) -> None:
        super().__init__()
        self.properties = properties

    @property
    def color(self):
        """Return or set the color of the actor."""
        return self.properties.GetColor()

    @color.setter
    def color(self, color: tuple):
        self.properties.SetColor(color[0], color[1], color[2])

    @property
    def metallic(self):
        """Return or set the metallic coefficient of the surface."""
        return self.properties.GetMetallic()

    @metallic.setter
    def metallic(self, value: float):
        self.properties.SetMetallic(value)

    @property
    def roughness(self):
        """Return or set the roughness of the surface."""
        return self.properties.GetRoughness()

    @roughness.setter
    def roughness(self, value: float):
        self.properties.SetRoughness(value)

    @property
    def anisotropy(self):
        """Return or set the anisotropy coefficient."""
        return self.properties.GetAnisotropy()

    @anisotropy.setter
    def anisotropy(self, value: float):
        self.properties.SetAnisotropy(value)

    @property
    def anisotropy_rotation(self):
        """Return or set the anisotropy rotation coefficient."""
        return self.properties.GetAnisotropyRotation()

    @anisotropy_rotation.setter
    def anisotropy_rotation(self, value: float):
        self.properties.SetAnisotropyRotation(value)

    @property
    def lighting(self):
        """Return or set the lighting activation flag."""
        return self.properties.GetLighting()

    @lighting.setter
    def lighting(self, flag: bool):
        self.properties.SetLighting(flag)

    @property
    def interpolation_model(self):
        """Return or set the interpolation model.

        Can be any of the options in :class:`pyvista.plotting.opts.InterpolationType` enum.
        """
        return InterpolationType.from_any(self.properties.GetInterpolation())

    @interpolation_model.setter
    def interpolation_model(self, model: InterpolationType):
        self.properties.SetInterpolation(model.value)

    @property
    def index_of_refraction(self):
        """Return or set the Index Of Refraction of the base layer."""
        return self.properties.GetBaseIOR()

    @index_of_refraction.setter
    def index_of_refraction(self, value: float):
        self.properties.SetBaseIOR(value)

    @property
    def opacity(self):
        """Return or set the opacity of the actor."""
        return self.properties.GetOpacity()

    @opacity.setter
    def opacity(self, value: float):
        self.properties.SetOpacity(value)

    @property
    def shading(self):
        """Return or set the flag to activate the shading."""
        return self.properties.GetShading()

    @shading.setter
    def shading(self, is_active: bool):
        self.properties.SetShading(is_active)

    @property
    def representation(self) -> RepresentationType:
        """Return or set the representation of the actor.

        Can be any of the options in :class:`pyvista.plotting.opts.RepresentationType` enum.
        """
        return RepresentationType.from_any(self.properties.GetRepresentation())

    @representation.setter
    def representation(self, value: RepresentationType):
        self.properties.SetRepresentation(RepresentationType.from_any(value).value)


# pyvista/plotting/axes.py

"""Module containing pyvista implementation of vtkAxes."""
from pyvista import _vtk

from .actor import Actor
from .axes_actor import AxesActor


class Axes(_vtk.vtkAxes):
    """PyVista wrapper for the VTK Axes class.

    Parameters
    ----------
    show_actor : bool, optional
        Hide or show the actor of these axes.  Default ``False``.

    actor_scale : float, optional
        Scale the size of the axes actor.  Default ``1``.

    line_width : float, optional
        Width of the axes lines.  Default ``1``.

    symmetric : bool, optional
        If true, the axis continue to negative values.

    Examples
    --------
    Create an instance of axes at the pyvista module level.

    >>> import pyvista
    >>> axes = pyvista.Axes()

    """

    def __init__(self, show_actor=False, actor_scale=1, line_width=1.0, symmetric=False):
        """Initialize a new axes descriptor."""
        super().__init__()
        self.SetSymmetric(symmetric)
        # Add the axes mapper
        self.mapper = _vtk.vtkPolyDataMapper()
        self.mapper.SetInputConnection(self.GetOutputPort())
        # Add the axes actor
        self.actor = Actor(mapper=self.mapper)
        self.axes_actor = AxesActor()
        self.actor.visibility = show_actor
        self.actor.scale = actor_scale
        self.actor.prop.line_width = line_width

    @property
    def origin(self):
        """Origin of the axes in world coordinates.

        Examples
        --------
        >>> import pyvista
        >>> axes = pyvista.Axes()
        >>> axes.origin
        (0.0, 0.0, 0.0)

        Set the origin of the camera.

        >>> axes.origin = (2.0, 1.0, 1.0)
        >>> axes.origin
        (2.0, 1.0, 1.0)

        """
        return self.GetOrigin()

    @origin.setter
    def origin(self, value):
        """Set the origin of the camera."""
        self.SetOrigin(value)

    def show_actor(self):
        """Show an actor of axes.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.show_actor()
        """
        self.actor.visibility = True

    def hide_actor(self):
        """Hide an actor of axes.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.hide_actor()
        """
        self.actor.visibility = False

    def show_symmetric(self):
        """Show symmetric of axes.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.show_symmetric()
        """
        self.SymmetricOn()

    def hide_symmetric(self):
        """Hide symmetric of axes.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.hide_symmetric()
        """
        self.SymmetricOff()

    def __del__(self):
        """Clean the attributes of the class."""
        self.axes_actor = None
        self.actor = None
        self.mapper = None


# pyvista/plotting/axes_actor.py

"""Axes actor module."""
from collections.abc import Iterable
from enum import Enum
from typing import Union

import pyvista as pv

from .actor_properties import ActorProperties


class AxesActor(pv._vtk.vtkAxesActor):
    """Axes actor wrapper for vtkAxesActor.

    Hybrid 2D/3D actor used to represent 3D axes in a scene. The user
    can define the geometry to use for the shaft or the tip, and the
    user can set the text for the three axes. To see full customization
    options, refer to `vtkAxesActor Details
    <https://vtk.org/doc/nightly/html/classvtkAxesActor.html#details>`.

    Examples
    --------
    Customize the axis shaft color and shape.

    >>> import pyvista as pv

    >>> axes = pv.Axes()
    >>> axes.axes_actor.z_axis_shaft_properties.color = (0, 1, 1)
    >>> axes.axes_actor.shaft_type = axes.axes_actor.ShaftType.CYLINDER
    >>> pl = pv.Plotter()
    >>> _ = pl.add_actor(axes.axes_actor)
    >>> _ = pl.add_mesh(pv.Sphere())
    >>> pl.show()

    Or you can use this as a custom orientation widget with
    :func:`add_orientation_widget() <pyvista.Renderer.add_orientation_widget>`:

    >>> import pyvista as pv

    >>> axes = pv.Axes()
    >>> axes_actor = axes.axes_actor
    >>> axes.axes_actor.shaft_type = 0

    >>> axes_actor.x_axis_shaft_properties.color = (1, 1, 1)
    >>> axes_actor.y_axis_shaft_properties.color = (1, 1, 1)
    >>> axes_actor.z_axis_shaft_properties.color = (1, 1, 1)

    >>> axes_actor.x_axis_label = 'U'
    >>> axes_actor.y_axis_label = 'V'
    >>> axes_actor.z_axis_label = 'W'

    >>> pl = pv.Plotter()
    >>> _ = pl.add_mesh(pv.Cone())
    >>> _ = pl.add_orientation_widget(
    ...     axes_actor,
    ...     viewport=(0, 0, 0.5, 0.5),
    ... )
    >>> pl.show()

    """

    class ShaftType(Enum):
        """Types of shaft shapes available."""

        CYLINDER = 0
        LINE = 1

    class TipType(Enum):
        """Types of tip shapes available."""

        CONE = 0
        SPHERE = 1

    def __init__(self):
        """Initialize actor."""
        super().__init__()

        self.x_axis_shaft_properties.color = pv.global_theme.axes.x_color.int_rgb
        self.x_axis_tip_properties.color = pv.global_theme.axes.x_color.int_rgb
        self.x_axis_shaft_properties.opacity = pv.global_theme.axes.x_color.int_rgba[3]
        self.x_axis_tip_properties.opacity = pv.global_theme.axes.x_color.int_rgba[3]
        self.x_axis_shaft_properties.lighting = pv.global_theme.lighting

        self.y_axis_shaft_properties.color = pv.global_theme.axes.y_color.int_rgb
        self.y_axis_tip_properties.color = pv.global_theme.axes.y_color.int_rgb
        self.y_axis_shaft_properties.opacity = pv.global_theme.axes.y_color.int_rgba[3]
        self.y_axis_tip_properties.opacity = pv.global_theme.axes.y_color.int_rgba[3]
        self.y_axis_shaft_properties.lighting = pv.global_theme.lighting

        self.z_axis_shaft_properties.color = pv.global_theme.axes.z_color.int_rgb
        self.z_axis_tip_properties.color = pv.global_theme.axes.z_color.int_rgb
        self.z_axis_shaft_properties.opacity = pv.global_theme.axes.z_color.int_rgba[3]
        self.z_axis_tip_properties.opacity = pv.global_theme.axes.z_color.int_rgba[3]
        self.z_axis_shaft_properties.lighting = pv.global_theme.lighting

    @property
    def visibility(self) -> bool:
        """Return or set AxesActor visibility.

        Examples
        --------
        Create an Axes object and then access the
        visibility attribute of its AxesActor.

        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.axes_actor.visibility
        True

        """
        return bool(self.GetVisibility())

    @visibility.setter
    def visibility(self, value: bool):
        return self.SetVisibility(value)

    @property
    def total_length(self) -> tuple:
        """Return or set the length of all axes.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.axes_actor.total_length
        (1.0, 1.0, 1.0)
        >>> axes.axes_actor.total_length = 1.2
        >>> axes.axes_actor.total_length
        (1.2, 1.2, 1.2)
        >>> axes.axes_actor.total_length = (1.0, 0.9, 0.5)
        >>> axes.axes_actor.total_length
        (1.0, 0.9, 0.5)

        """
        return self.GetTotalLength()

    @total_length.setter
    def total_length(self, length):
        if isinstance(length, Iterable):
            self.SetTotalLength(length[0], length[1], length[2])
        else:
            self.SetTotalLength(length, length, length)

    @property
    def shaft_length(self) -> tuple:
        """Return or set the length of the axes shaft.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.axes_actor.shaft_length
        (0.8, 0.8, 0.8)
        >>> axes.axes_actor.shaft_length = 0.7
        >>> axes.axes_actor.shaft_length
        (0.7, 0.7, 0.7)
        >>> axes.axes_actor.shaft_length = (1.0, 0.9, 0.5)
        >>> axes.axes_actor.shaft_length
        (1.0, 0.9, 0.5)

        """
        return self.GetNormalizedShaftLength()

    @shaft_length.setter
    def shaft_length(self, length):
        if isinstance(length, Iterable):
            self.SetNormalizedShaftLength(length[0], length[1], length[2])
        else:
            self.SetNormalizedShaftLength(length, length, length)

    @property
    def tip_length(self) -> tuple:
        """Return or set the length of the tip.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.axes_actor.tip_length
        (0.2, 0.2, 0.2)
        >>> axes.axes_actor.tip_length = 0.3
        >>> axes.axes_actor.tip_length
        (0.3, 0.3, 0.3)
        >>> axes.axes_actor.tip_length = (0.1, 0.4, 0.2)
        >>> axes.axes_actor.tip_length
        (0.1, 0.4, 0.2)

        """
        return self.GetNormalizedTipLength()

    @tip_length.setter
    def tip_length(self, length):
        if isinstance(length, Iterable):
            self.SetNormalizedTipLength(length[0], length[1], length[2])
        else:
            self.SetNormalizedTipLength(length, length, length)

    @property
    def label_position(self) -> tuple:
        """Position of the label along the axes.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.axes_actor.label_position
        (1.0, 1.0, 1.0)
        >>> axes.axes_actor.label_position = 0.3
        >>> axes.axes_actor.label_position
        (0.3, 0.3, 0.3)
        >>> axes.axes_actor.label_position = (0.1, 0.4, 0.2)
        >>> axes.axes_actor.label_position
        (0.1, 0.4, 0.2)

        """
        return self.GetNormalizedLabelPosition()

    @label_position.setter
    def label_position(self, length):
        if isinstance(length, Iterable):
            self.SetNormalizedLabelPosition(length[0], length[1], length[2])
        else:
            self.SetNormalizedLabelPosition(length, length, length)

    @property
    def cone_resolution(self) -> int:
        """Return or set the resolution of the cone tip.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.axes_actor.cone_resolution
        16
        >>> axes.axes_actor.cone_resolution = 24
        >>> axes.axes_actor.cone_resolution
        24

        """
        return self.GetConeResolution()

    @cone_resolution.setter
    def cone_resolution(self, res: int):
        self.SetConeResolution(res)

    @property
    def sphere_resolution(self) -> int:
        """Return or set the resolution of the spherical tip.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.axes_actor.sphere_resolution
        16
        >>> axes.axes_actor.sphere_resolution = 24
        >>> axes.axes_actor.sphere_resolution
        24

        """
        return self.GetSphereResolution()

    @sphere_resolution.setter
    def sphere_resolution(self, res: int):
        self.SetSphereResolution(res)

    @property
    def cylinder_resolution(self) -> int:
        """Return or set the resolution of the shaft cylinder.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.axes_actor.cylinder_resolution
        16
        >>> axes.axes_actor.cylinder_resolution = 24
        >>> axes.axes_actor.cylinder_resolution
        24

        """
        return self.GetCylinderResolution()

    @cylinder_resolution.setter
    def cylinder_resolution(self, res: int):
        self.SetCylinderResolution(res)

    @property
    def cone_radius(self) -> float:
        """Return or set the radius of the cone tip.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.axes_actor.cone_radius
        0.4
        >>> axes.axes_actor.cone_radius = 0.8
        >>> axes.axes_actor.cone_radius
        0.8

        """
        return self.GetConeRadius()

    @cone_radius.setter
    def cone_radius(self, rad: float):
        self.SetConeRadius(rad)

    @property
    def sphere_radius(self) -> float:
        """Return or set the radius of the spherical tip.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.axes_actor.sphere_radius
        0.4
        >>> axes.axes_actor.sphere_radius = 0.8
        >>> axes.axes_actor.sphere_radius
        0.8

        """
        return self.GetSphereRadius()

    @sphere_radius.setter
    def sphere_radius(self, rad: float):
        self.SetSphereRadius(rad)

    @property
    def cylinder_radius(self) -> float:
        """Return or set the radius of the shaft cylinder.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.axes_actor.cylinder_radius
        0.05
        >>> axes.axes_actor.cylinder_radius = 0.03
        >>> axes.axes_actor.cylinder_radius
        0.03

        """
        return self.GetCylinderRadius()

    @cylinder_radius.setter
    def cylinder_radius(self, rad: float):
        self.SetCylinderRadius(rad)

    @property
    def shaft_type(self) -> ShaftType:
        """Return or set the shaft type.

        Can be either a cylinder(0) or a line(1).

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.axes_actor.shaft_type = axes.axes_actor.ShaftType.LINE
        >>> axes.axes_actor.shaft_type
        <ShaftType.LINE: 1>

        """
        return AxesActor.ShaftType(self.GetShaftType())

    @shaft_type.setter
    def shaft_type(self, shaft_type: Union[ShaftType, int]):
        shaft_type = AxesActor.ShaftType(shaft_type)
        if shaft_type == AxesActor.ShaftType.CYLINDER:
            self.SetShaftTypeToCylinder()
        elif shaft_type == AxesActor.ShaftType.LINE:
            self.SetShaftTypeToLine()

    @property
    def tip_type(self) -> TipType:
        """Return or set the shaft type.

        Can be either a cone(0) or a sphere(1).

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.axes_actor.tip_type = axes.axes_actor.TipType.SPHERE
        >>> axes.axes_actor.tip_type
        <TipType.SPHERE: 1>

        """
        return AxesActor.TipType(self.GetTipType())

    @tip_type.setter
    def tip_type(self, tip_type: Union[TipType, int]):
        tip_type = AxesActor.TipType(tip_type)
        if tip_type == AxesActor.TipType.CONE:
            self.SetTipTypeToCone()
        elif tip_type == AxesActor.TipType.SPHERE:
            self.SetTipTypeToSphere()

    @property
    def x_axis_label(self) -> str:
        """Return or set the label for the X axis.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.axes_actor.x_axis_label = 'This axis'
        >>> axes.axes_actor.x_axis_label
        'This axis'

        """
        return self.GetXAxisLabelText()

    @x_axis_label.setter
    def x_axis_label(self, label: str):
        self.SetXAxisLabelText(label)

    @property
    def y_axis_label(self) -> str:
        """Return or set the label for the Y axis.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.axes_actor.y_axis_label = 'This axis'
        >>> axes.axes_actor.y_axis_label
        'This axis'

        """
        return self.GetYAxisLabelText()

    @y_axis_label.setter
    def y_axis_label(self, label: str):
        self.SetYAxisLabelText(label)

    @property
    def z_axis_label(self) -> str:
        """Return or set the label for the Z axis.

        Examples
        --------
        >>> import pyvista as pv
        >>> axes = pv.Axes()
        >>> axes.axes_actor.z_axis_label = 'This axis'
        >>> axes.axes_actor.z_axis_label
        'This axis'

        """
        return self.GetZAxisLabelText()

    @z_axis_label.setter
    def z_axis_label(self, label: str):
        self.SetZAxisLabelText(label)

    @property
    def x_axis_shaft_properties(self):
        """Return or set the properties of the X axis shaft."""
        return ActorProperties(self.GetXAxisShaftProperty())

    @property
    def y_axis_shaft_properties(self):
        """Return or set the properties of the Y axis shaft."""
        return ActorProperties(self.GetYAxisShaftProperty())

    @property
    def z_axis_shaft_properties(self):
        """Return or set the properties of the Z axis shaft."""
        return ActorProperties(self.GetZAxisShaftProperty())

    @property
    def x_axis_tip_properties(self):
        """Return or set the properties of the X axis tip."""
        return ActorProperties(self.GetXAxisTipProperty())

    @x_axis_tip_properties.setter
    def x_axis_tip_properties(self, properties: ActorProperties):
        self.x_axis_tip_properties = properties

    @property
    def y_axis_tip_properties(self):
        """Return or set the properties of the Y axis tip."""
        return ActorProperties(self.GetYAxisTipProperty())

    @y_axis_tip_properties.setter
    def y_axis_tip_properties(self, properties: ActorProperties):
        self.y_axis_tip_properties = properties

    @property
    def z_axis_tip_properties(self):
        """Return or set the properties of the Z axis tip."""
        return ActorProperties(self.GetZAxisTipProperty())

    @z_axis_tip_properties.setter
    def z_axis_tip_properties(self, properties: ActorProperties):
        self.z_axis_tip_properties = properties


# pyvista/plotting/background_renderer.py

"""Contains the BackgroundRenderer class."""
import numpy as np

import pyvista

from .renderer import Renderer


class BackgroundRenderer(Renderer):
    """BackgroundRenderer for visualizing a background image."""

    def __init__(self, parent, image_path, scale=1, view_port=None):
        """Initialize BackgroundRenderer with an image."""
        # avoiding circular import
        from pyvista import _vtk

        # read the image first as we don't need to create a render if
        # the image path is invalid
        image_data = pyvista.read(image_path)

        super().__init__(parent, border=False)
        self.SetLayer(0)
        self.InteractiveOff()
        self.SetBackground(self.parent.renderer.GetBackground())
        self._scale = scale
        self._modified_observer = None
        self._prior_window_size = None
        if view_port is not None:
            self.SetViewport(view_port)

        # create image actor
        image_actor = _vtk.vtkImageActor()
        image_actor.SetInputData(image_data)
        self.add_actor(image_actor, name='background')
        self.camera.enable_parallel_projection()
        self.reset_camera()  # necessary to get first render
        self.resize()

    def resize(self, *args):
        """Resize a background renderer."""
        if self.parent is None:  # when deleted
            return
        if self.parent.render_window is None:  # BasePlotter
            return

        if self._prior_window_size != self.parent.window_size:
            self._prior_window_size = self.parent.window_size

        actor = self._actors['background']
        image_data = actor.GetInput()
        origin = image_data.GetOrigin()
        extent = image_data.GetExtent()
        spacing = image_data.GetSpacing()
        xc = origin[0] + 0.5 * (extent[0] + extent[1]) * spacing[0]
        yc = origin[1] + 0.5 * (extent[2] + extent[3]) * spacing[1]
        yd = (extent[3] - extent[2] + 1) * spacing[1]
        dist = self.camera.distance

        # make the longest dimensions match the plotting window
        img_dim = np.array(image_data.dimensions[:2])
        self.camera.focus = np.array([xc, yc, 0.0])
        self.camera.position = np.array([xc, yc, dist])

        ratio = img_dim / np.array(self.parent.window_size)
        scale_value = 1
        if ratio.max() > 1:
            # images are not scaled if larger than the window
            scale_value = ratio.max()

        if self._scale is not None:
            scale_value /= self._scale

        self.camera.parallel_scale = 0.5 * yd / self._scale


# pyvista/plotting/camera.py

"""Module containing pyvista implementation of vtkCamera."""
from __future__ import annotations

from pathlib import Path
from typing import Union
from weakref import proxy
import xml.dom.minidom as md
from xml.etree import ElementTree

import numpy as np

import pyvista
from pyvista import _vtk

from .helpers import view_vectors


class Camera(_vtk.vtkCamera):
    """PyVista wrapper for the VTK Camera class.

    Parameters
    ----------
    renderer : pyvista.Renderer, optional
        Renderer to attach the camera to.

    Examples
    --------
    Create a camera at the pyvista module level.

    >>> import pyvista
    >>> camera = pyvista.Camera()

    Access the active camera of a plotter and get the position of the
    camera.

    >>> pl = pyvista.Plotter()
    >>> pl.camera.position
    (1.0, 1.0, 1.0)

    """

    def __init__(self, renderer=None):
        """Initialize a new camera descriptor."""
        self._parallel_projection = False
        self._elevation = 0.0
        self._azimuth = 0.0
        self._is_set = False

        if renderer:
            if not isinstance(renderer, pyvista.Renderer):
                raise TypeError(
                    'Camera only accepts a pyvista.Renderer or None as the ``renderer`` argument'
                )
            self._renderer = proxy(renderer)
        else:
            self._renderer = None

    def __repr__(self):
        """Print a repr specifying the id of the camera and its camera type."""
        return f'<{self.__class__.__name__} at {hex(id(self))}>'

    def __eq__(self, other):
        """Compare whether the relevant attributes of two cameras are equal."""
        # attributes which are native python types and thus implement __eq__

        native_attrs = [
            'position',
            'focal_point',
            'parallel_projection',
            'distance',
            'thickness',
            'parallel_scale',
            'clipping_range',
            'view_angle',
            'roll',
        ]
        for attr in native_attrs:
            if getattr(self, attr) != getattr(other, attr):
                return False

        this_trans = self.model_transform_matrix
        that_trans = other.model_transform_matrix
        trans_count = sum(1 for trans in [this_trans, that_trans] if trans is not None)
        if trans_count == 1:
            # either but not both are None
            return False
        if trans_count == 2:
            if not np.array_equal(this_trans, that_trans):
                return False

        return True

    def __del__(self):
        """Delete the camera."""
        self.RemoveAllObservers()
        self.parent = None

    @property
    def is_set(self) -> bool:
        """Get or set whether this camera has been configured."""
        return self._is_set

    @is_set.setter
    def is_set(self, value: bool):
        self._is_set = bool(value)

    @classmethod
    def from_paraview_pvcc(cls, filename: Union[str, Path]) -> Camera:
        """Load a Paraview camera file (.pvcc extension).

        Returns a pyvista.Camera object for which attributes has been read
        from the filename argument.

        Parameters
        ----------
        filename : str or pathlib.Path
            Path to Paraview camera file (.pvcc).

        Examples
        --------
        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> pl.camera = pv.Camera.from_paraview_pvcc(
        ...     "camera.pvcc"
        ... )  # doctest:+SKIP
        >>> pl.camera.position
        (1.0, 1.0, 1.0)
        """
        to_find = {
            "CameraPosition": ("position", float),
            "CameraFocalPoint": ("focal_point", float),
            "CameraViewAngle": ("view_angle", float),
            "CameraViewUp": ("up", float),
            "CameraParallelProjection": ("parallel_projection", int),
            "CameraParallelScale": ("parallel_scale", float),
        }
        camera = cls()

        tree = ElementTree.parse(filename)
        root = tree.getroot()[0]
        for element in root:
            attrib = element.attrib
            attrib_name = attrib["name"]

            if attrib_name in to_find:
                name, typ = to_find[attrib_name]
                nelems = int(attrib["number_of_elements"])

                # Set the camera attributes
                if nelems == 3:
                    values = [typ(e.attrib["value"]) for e in element]
                    setattr(camera, name, values)
                elif nelems == 1:
                    # Special case for bool since bool("0") returns True.
                    # So first convert to int from `to_find` and then apply bool
                    if "name" in element[-1].attrib and element[-1].attrib["name"] == "bool":
                        val = bool(typ(element[0].attrib["value"]))
                    else:
                        val = typ(element[0].attrib["value"])
                    setattr(camera, name, val)

        camera.is_set = True
        return camera

    def to_paraview_pvcc(self, filename: Union[str, Path]):
        """Write the camera parameters to a Paraview camera file (.pvcc extension).

        Parameters
        ----------
        filename : str or pathlib.Path
            Path to Paraview camera file (.pvcc).

        Examples
        --------
        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> pl.camera.to_paraview_pvcc("camera.pvcc")  # doctest:+SKIP
        """
        root = ElementTree.Element("PVCameraConfiguration")
        root.attrib["description"] = "ParaView camera configuration"
        root.attrib["version"] = "1.0"

        dico = dict(group="views", type="RenderView", id="0", servers="21")
        proxy = ElementTree.SubElement(root, "Proxy", dico)

        # Add tuples
        to_find = {
            "CameraPosition": "position",
            "CameraFocalPoint": "focal_point",
            "CameraViewUp": "up",
        }
        for name, attr in to_find.items():
            e = ElementTree.SubElement(
                proxy, "Property", dict(name=name, id=f"0.{name}", number_of_elements="3")
            )

            for i in range(3):
                tmp = ElementTree.Element("Element")
                tmp.attrib["index"] = str(i)
                tmp.attrib["value"] = str(getattr(self, attr)[i])
                e.append(tmp)

        # Add single values
        to_find = {
            "CameraViewAngle": "view_angle",
            "CameraParallelScale": "parallel_scale",
            "CameraParallelProjection": "parallel_projection",
        }

        for name, attr in to_find.items():
            e = ElementTree.SubElement(
                proxy, "Property", dict(name=name, id=f"0.{name}", number_of_elements="1")
            )
            tmp = ElementTree.Element("Element")
            tmp.attrib["index"] = "0"

            val = getattr(self, attr)
            if type(val) is not bool:
                tmp.attrib["value"] = str(val)
                e.append(tmp)
            else:
                tmp.attrib["value"] = "1" if val else "0"
                e.append(tmp)
                e.append(ElementTree.Element("Domain", dict(name="bool", id=f"0.{name}.bool")))

        xmlstr = ElementTree.tostring(root).decode()
        newxml = md.parseString(xmlstr)
        with open(filename, 'w') as outfile:
            outfile.write(newxml.toprettyxml(indent='\t', newl='\n'))

    @property
    def position(self):
        """Return or set the position of the camera in world coordinates.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.position
        (1.0, 1.0, 1.0)
        >>> pl.camera.position = (2.0, 1.0, 1.0)
        >>> pl.camera.position
        (2.0, 1.0, 1.0)

        """
        return self.GetPosition()

    @position.setter
    def position(self, value):
        """Set the position of the camera."""
        self.SetPosition(value)
        self._elevation = 0.0
        self._azimuth = 0.0
        if self._renderer:
            self.reset_clipping_range()
        self.is_set = True

    def reset_clipping_range(self):
        """Reset the camera clipping range based on the bounds of the visible actors.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(pyvista.Sphere())
        >>> pl.camera.clipping_range = (1, 2)
        >>> pl.camera.reset_clipping_range()  # doctest:+SKIP
        (0.0039213485598532955, 3.9213485598532953)

        """
        if self._renderer is None:
            raise AttributeError(
                'Camera is must be associated with a renderer to reset its clipping range.'
            )
        self._renderer.reset_camera_clipping_range()

    @property
    def focal_point(self):
        """Location of the camera's focus in world coordinates.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.focal_point
        (0.0, 0.0, 0.0)
        >>> pl.camera.focal_point = (2.0, 0.0, 0.0)
        >>> pl.camera.focal_point
        (2.0, 0.0, 0.0)
        """
        return self.GetFocalPoint()

    @focal_point.setter
    def focal_point(self, point):
        """Set the location of the camera's focus in world coordinates."""
        self.SetFocalPoint(point)
        self.is_set = True

    @property
    def model_transform_matrix(self):
        """Return or set the camera's model transformation matrix.

        Examples
        --------
        >>> import pyvista
        >>> import numpy as np
        >>> pl = pyvista.Plotter()
        >>> pl.camera.model_transform_matrix
        array([[1., 0., 0., 0.],
               [0., 1., 0., 0.],
               [0., 0., 1., 0.],
               [0., 0., 0., 1.]])
        >>> pl.camera.model_transform_matrix = np.array(
        ...     [
        ...         [1.0, 0.0, 0.0, 0.0],
        ...         [0.0, 1.0, 0.0, 0.0],
        ...         [0.0, 0.0, 1.0, 0.0],
        ...         [0.0, 0.0, 0.0, 0.5],
        ...     ]
        ... )
        >>>
        array([[1., 0., 0., 0.],
               [0., 1., 0., 0.],
               [0., 0., 1., 0.],
               [0., 0., 0., 0.5]])

        """
        vtk_matrix = self.GetModelTransformMatrix()
        matrix = np.empty((4, 4))
        vtk_matrix.DeepCopy(matrix.ravel(), vtk_matrix)
        return matrix

    @model_transform_matrix.setter
    def model_transform_matrix(self, matrix):
        """Set the camera's model transformation matrix."""
        vtk_matrix = _vtk.vtkMatrix4x4()
        vtk_matrix.DeepCopy(matrix.ravel())
        self.SetModelTransformMatrix(vtk_matrix)

    @property
    def distance(self):
        """Return or set the distance of the focal point from the camera.

        Notes
        -----
        Setting the distance keeps the camera fixed and moves the focal point.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.distance
        1.73205
        >>> pl.camera.distance = 2.0
        >>> pl.camera.distance
        2.0

        """
        return self.GetDistance()

    @distance.setter
    def distance(self, distance):
        """Set the distance from the camera position to the focal point."""
        self.SetDistance(distance)
        self.is_set = True

    @property
    def thickness(self):
        """Return or set the distance between clipping planes.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.thickness
        1000.0
        >>> pl.camera.thickness = 100
        >>> pl.camera.thickness
        100.0

        """
        return self.GetThickness()

    @thickness.setter
    def thickness(self, length):
        """Set the distance between clipping planes."""
        self.SetThickness(length)

    @property
    def parallel_scale(self):
        """Return or set the scaling used for a parallel projection.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.parallel_scale
        1.0
        >>> pl.camera.parallel_scale = 2.0
        >>> pl.camera.parallel_scale
        2.0

        """
        return self.GetParallelScale()

    @parallel_scale.setter
    def parallel_scale(self, scale):
        """Set the scaling used for parallel projection."""
        self.SetParallelScale(scale)

    def zoom(self, value):
        """Set the zoom of the camera.

        In perspective mode, decrease the view angle by the specified
        factor.

        In parallel mode, decrease the parallel scale by the specified
        factor. A value greater than 1 is a zoom-in, a value less than
        1 is a zoom-out.

        Parameters
        ----------
        value : float or str
            Zoom of the camera. If a float, must be greater than 0. Otherwise,
            if a string, must be ``"tight"``. If tight, the plot will be zoomed
            such that the actors fill the entire viewport.

        Examples
        --------
        Show the Default zoom.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Sphere())
        >>> pl.camera.zoom(1.0)
        >>> pl.show()

        Show 2x zoom.

        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Sphere())
        >>> pl.camera.zoom(2.0)
        >>> pl.show()

        Zoom so the actor fills the entire render window.

        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Sphere())
        >>> pl.camera.zoom('tight')
        >>> pl.show()

        """
        if isinstance(value, str):
            if not value == 'tight':
                raise ValueError('If a string, ``zoom`` can only be "tight"')
            self.tight()
            return

        self.Zoom(value)
        self.is_set = True

    @property
    def up(self):
        """Return or set the "up" of the camera.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.up
        (0.0, 0.0, 1.0)
        >>> pl.camera.up = (0.410018, 0.217989, 0.885644)
        >>> pl.camera.up
        (0.410018, 0.217989, 0.885644)

        """
        return self.GetViewUp()

    @up.setter
    def up(self, vector):
        """Set the "up" of the camera."""
        self.SetViewUp(vector)
        self.is_set = True

    def enable_parallel_projection(self):
        """Enable parallel projection.

        The camera will have a parallel projection. Parallel
        projection is often useful when viewing images or 2D datasets,
        but will look odd when viewing 3D datasets.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import demos
        >>> pl = pyvista.demos.orientation_plotter()
        >>> pl.enable_parallel_projection()
        >>> pl.show()

        """
        self._parallel_projection = True
        self.SetParallelProjection(True)

    def disable_parallel_projection(self):
        """Disable the use of parallel projection.

        This is default behavior.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import demos
        >>> pl = pyvista.demos.orientation_plotter()
        >>> pl.disable_parallel_projection()
        >>> pl.show()
        """
        self._parallel_projection = False
        self.SetParallelProjection(False)

    @property
    def parallel_projection(self):
        """Return the state of the parallel projection.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import demos
        >>> pl = pyvista.Plotter()
        >>> pl.disable_parallel_projection()
        >>> pl.parallel_projection
        False
        """
        return self._parallel_projection

    @parallel_projection.setter
    def parallel_projection(self, state):
        """Return the state of the parallel projection.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import demos
        >>> pl = pyvista.Plotter()
        >>> pl.disable_parallel_projection()
        >>> pl.parallel_projection
        False
        """
        if state:
            self.enable_parallel_projection()
        else:
            self.disable_parallel_projection()

    @property
    def clipping_range(self):
        """Return or set the location of the clipping planes.

        Clipping planes are the near and far clipping planes along
        the direction of projection.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.clipping_range
        (0.01, 1000.01)
        >>> pl.camera.clipping_range = (1, 10)
        >>> pl.camera.clipping_range
        (1.0, 10.0)

        """
        return self.GetClippingRange()

    @clipping_range.setter
    def clipping_range(self, points):
        """Set the clipping planes."""
        if points[0] > points[1]:
            raise ValueError('Near point must be lower than the far point.')
        self.SetClippingRange(points[0], points[1])

    @property
    def view_angle(self):
        """Return or set the camera view angle.

        Examples
        --------
        >>> import pyvista
        >>> plotter = pyvista.Plotter()
        >>> plotter.camera.view_angle
        30.0
        >>> plotter.camera.view_angle = 60.0
        >>> plotter.camera.view_angle
        60.0

        """
        return self.GetViewAngle()

    @view_angle.setter
    def view_angle(self, value):
        """Set the camera view angle."""
        self.SetViewAngle(value)

    @property
    def direction(self):
        """Vector from the camera position to the focal point.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.direction  # doctest:+SKIP
        (-0.5773502691896257, -0.5773502691896257, -0.5773502691896257)

        """
        return self.GetDirectionOfProjection()

    def view_frustum(self, aspect=1.0):
        """Get the view frustum.

        Parameters
        ----------
        aspect : float, default: 1.0
            The aspect of the viewport to compute the planes.

        Returns
        -------
        pyvista.PolyData
            View frustum.

        Examples
        --------
        >>> import pyvista
        >>> plotter = pyvista.Plotter()
        >>> frustum = plotter.camera.view_frustum(1.0)
        >>> frustum.n_points
        8
        >>> frustum.n_cells
        6

        """
        frustum_planes = [0] * 24
        self.GetFrustumPlanes(aspect, frustum_planes)
        planes = _vtk.vtkPlanes()
        planes.SetFrustumPlanes(frustum_planes)

        frustum_source = _vtk.vtkFrustumSource()
        frustum_source.ShowLinesOff()
        frustum_source.SetPlanes(planes)
        frustum_source.Update()

        frustum = pyvista.wrap(frustum_source.GetOutput())
        return frustum

    @property
    def roll(self):
        """Rotate the camera about the direction of projection.

        This will spin the camera about its axis.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.roll
        -120.00000000000001
        >>> pl.camera.roll = 45.0
        >>> pl.camera.roll
        45.0
        """
        return self.GetRoll()

    @roll.setter
    def roll(self, angle):
        """Set the rotate of the camera about the direction of projection."""
        self.SetRoll(angle)
        self.is_set = True

    @property
    def elevation(self):
        """Vertical rotation of the scene.

        Rotate the camera about the cross product of the negative of
        the direction of projection and the view up vector, using the
        focal point as the center of rotation.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.elevation
        0.0
        >>> pl.camera.elevation = 45.0
        >>> pl.camera.elevation
        45.0

        """
        return self._elevation

    @elevation.setter
    def elevation(self, angle):
        """Set the vertical rotation of the scene."""
        if self._elevation:
            self.Elevation(-self._elevation)
        self._elevation = angle
        self.Elevation(angle)
        self.is_set = True

    @property
    def azimuth(self):
        """Azimuth of the camera.

        Rotate the camera about the view up vector centered at the
        focal point. Note that the view up vector is whatever was set
        via SetViewUp, and is not necessarily perpendicular to the
        direction of projection.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera.azimuth
        0.0
        >>> pl.camera.azimuth = 45.0
        >>> pl.camera.azimuth
        45.0

        """
        return self._azimuth

    @azimuth.setter
    def azimuth(self, angle):
        """Set the azimuth rotation of the camera."""
        if self._azimuth:
            self.Azimuth(-self._azimuth)
        self._azimuth = angle
        self.Azimuth(angle)
        self.is_set = True

    def copy(self):
        """Return a deep copy of the camera.

        Returns
        -------
        pyvista.Camera
            Deep copy of the camera.

        Examples
        --------
        Create a camera and check that it shares a transformation
        matrix with its shallow copy.

        >>> import pyvista as pv
        >>> import numpy as np
        >>> camera = pv.Camera()
        >>> camera.model_transform_matrix = np.array(
        ...     [
        ...         [1.0, 0.0, 0.0, 0.0],
        ...         [0.0, 1.0, 0.0, 0.0],
        ...         [0.0, 0.0, 1.0, 0.0],
        ...         [0.0, 0.0, 0.0, 1.0],
        ...     ]
        ... )
        >>> copied_camera = camera.copy()
        >>> copied_camera == camera
        True
        >>> camera.model_transform_matrix = np.array(
        ...     [
        ...         [1.0, 0.0, 0.0, 0.0],
        ...         [0.0, 1.0, 0.0, 0.0],
        ...         [0.0, 0.0, 1.0, 0.0],
        ...         [0.0, 0.0, 0.0, 0.5],
        ...     ]
        ... )
        >>> copied_camera == camera
        False
        """
        immutable_attrs = [
            'position',
            'focal_point',
            'model_transform_matrix',
            'distance',
            'thickness',
            'parallel_scale',
            'up',
            'clipping_range',
            'view_angle',
            'roll',
            'parallel_projection',
            'is_set',
        ]
        new_camera = Camera()

        for attr in immutable_attrs:
            value = getattr(self, attr)
            setattr(new_camera, attr, value)

        return new_camera

    def tight(self, padding=0.0, adjust_render_window=True, view='xy', negative=False):
        """Adjust the camera position so that the actors fill the entire renderer.

        The camera view direction is reoriented to be normal to the ``view``
        plane. When ``negative=False``, The first letter of ``view`` refers
        to the axis that points to the right. The second letter of ``view``
        refers to axis that points up.  When ``negative=True``, the first
        letter refers to the axis that points left.  The up direction is
        unchanged.

        Parallel projection is enabled when using this function.

        Parameters
        ----------
        padding : float, default: 0.0
            Additional padding around the actor(s). This is effectively a zoom,
            where a value of 0.01 results in a zoom out of 1%.

        adjust_render_window : bool, default: True
            Adjust the size of the render window as to match the dimensions of
            the visible actors.

        view : {'xy', 'yx', 'xz', 'zx', 'yz', 'zy'}, default: 'xy'
            Plane to which the view is oriented.

        negative : bool, default: False
            Whether to view in opposite direction.

        Notes
        -----
        This resets the view direction to look at a plane with parallel projection.

        Examples
        --------
        Display the puppy image with a tight view.

        >>> import pyvista as pv
        >>> from pyvista import examples
        >>> puppy = examples.download_puppy()
        >>> pl = pv.Plotter(border=True, border_width=5)
        >>> _ = pl.add_mesh(puppy, rgb=True)
        >>> pl.camera.tight()
        >>> pl.show()

        Set the background to blue use a 5% padding around the image.

        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(puppy, rgb=True)
        >>> pl.background_color = 'b'
        >>> pl.camera.tight(padding=0.05)
        >>> pl.show()

        """
        # Inspired by vedo resetCamera. Thanks @marcomusy.
        x0, x1, y0, y1, z0, z1 = self._renderer.ComputeVisiblePropBounds()

        self.enable_parallel_projection()

        self._renderer.ComputeAspect()
        aspect = self._renderer.GetAspect()

        position0 = np.array([x0, y0, z0])
        position1 = np.array([x1, y1, z1])
        objects_size = position1 - position0
        position = position0 + objects_size / 2

        direction, viewup = view_vectors(view, negative)
        horizontal = np.cross(direction, viewup)

        vert_dist = abs(objects_size @ viewup)
        horiz_dist = abs(objects_size @ horizontal)

        # set focal point to objects' center
        # offset camera position from objects center by dist in opposite of viewing direction
        # (actual distance doesn't matter due to parallel projection)
        dist = 1
        camera_position = position + dist * direction

        self.SetViewUp(*viewup)
        self.SetPosition(*camera_position)
        self.SetFocalPoint(*position)

        ps = max(horiz_dist / aspect[0], vert_dist) / 2
        self.parallel_scale = ps * (1 + padding)
        self._renderer.ResetCameraClippingRange(x0, x1, y0, y1, z0, z1)

        if adjust_render_window:
            ren_win = self._renderer.GetRenderWindow()
            size = list(ren_win.GetSize())
            size_ratio = size[0] / size[1]
            tight_ratio = horiz_dist / vert_dist
            resize_ratio = tight_ratio / size_ratio
            if resize_ratio < 1:
                size[0] = round(size[0] * resize_ratio)
            else:
                size[1] = round(size[1] / resize_ratio)

            ren_win.SetSize(size)

            # simply call tight again to reset the parallel scale due to the
            # resized window
            self.tight(padding=padding, adjust_render_window=False, view=view, negative=negative)

        self.is_set = True


# pyvista/plotting/charts.py

"""Module containing pyvista wrappers for the vtk Charts API."""

from functools import wraps
import inspect
import itertools
import re
from typing import Dict, Optional, Sequence
import weakref

from matplotlib.backends.backend_agg import FigureCanvasAgg
import matplotlib.pyplot as plt
import numpy as np

import pyvista
from pyvista import _vtk

from .._typing import Chart
from ..utilities.misc import vtk_version_info
from .colors import COLOR_SCHEMES, SCHEME_NAMES, Color, color_synonyms, hexcolors


# region Some metaclass wrapping magic
class _vtkWrapperMeta(type):
    def __init__(cls, clsname, bases, attrs):
        # Restore the signature of classes inheriting from _vtkWrapper
        # Based on https://stackoverflow.com/questions/49740290/call-from-metaclass-shadows-signature-of-init
        sig = inspect.signature(cls.__init__)
        params = list(sig.parameters.values())
        params.insert(
            len(params) - 1 if params[-1].kind == inspect.Parameter.VAR_KEYWORD else len(params),
            inspect.Parameter("_wrap", inspect.Parameter.KEYWORD_ONLY, default=None),
        )
        cls.__signature__ = sig.replace(parameters=params[1:])
        super().__init__(clsname, bases, attrs)

    def __call__(cls, *args, _wrap=None, **kwargs):
        obj = cls.__new__(cls, *args, **kwargs)
        obj._wrapped = _wrap
        obj.__init__(*args, **kwargs)
        return obj


class _vtkWrapper(metaclass=_vtkWrapperMeta):
    def __getattribute__(self, item):
        unwrapped_attrs = ["_wrapped", "__class__", "__init__"]
        wrapped = super().__getattribute__("_wrapped")
        if item in unwrapped_attrs or wrapped is None:
            return super().__getattribute__(item)
        else:
            try:
                return wrapped.__getattribute__(item)
            except AttributeError:
                return super().__getattribute__(item)

    def __str__(self):
        if self._wrapped is None:
            return super().__str__()
        else:
            return "Wrapped: " + self._wrapped.__str__()


# endregion


# region Documentation substitution
class DocSubs:
    """Helper class to easily substitute the docstrings of the listed member functions or properties."""

    # The substitutions to use for this (sub)class
    _DOC_SUBS: Optional[Dict[str, str]] = None
    # Internal dictionary to store registered member functions/properties and their (to be substituted) docs.
    _DOC_STORE = {}  # type: ignore
    # Tag used to mark members that require docstring substitutions.
    _DOC_TAG = ":DOC_SUBS:"

    def __init_subclass__(cls, **kwargs):
        """Initialize subclasses."""
        # First substitute all members for this class (marked in a super class)
        if cls._DOC_SUBS is not None:
            subs = {**cls._DOC_SUBS}
            if "cls" not in subs:
                subs["cls"] = cls.__name__
            for member_name, (m, d) in cls._DOC_STORE.items():
                if member_name not in cls.__dict__:
                    # If the member is not part of the subclass' __dict__, we have to generate a wrapping
                    # function or property and add it to the subclass' __dict__. Otherwise, the docstring
                    # of the superclass would be used for the substitutions.
                    mem_sub = cls._wrap_member(m)
                    mem_sub.__doc__ = d
                    setattr(cls, member_name, mem_sub)
                # Get the member function/property and substitute its docstring.
                member = getattr(cls, member_name)
                member.__doc__ = member.__doc__.format(**subs)

        # Secondly, register all members of this class that require substitutions in subclasses
        # Create copy of registered members so far
        # TODO: B010
        setattr(cls, "_DOC_STORE", {**cls._DOC_STORE})  # noqa: B010
        for member_name, member in cls.__dict__.items():
            if member.__doc__ and member.__doc__.startswith(cls._DOC_TAG):
                # New method/property to register in this class (denoting their docstring should be
                # substituted in subsequent child classes).
                cls._DOC_STORE[member_name] = (member, member.__doc__[len(cls._DOC_TAG) :])
                # Overwrite original docstring to prevent doctest issues
                member.__doc__ = """Docstring to be specialized in subclasses."""

    @staticmethod
    def _wrap_member(member):
        if callable(member):

            @wraps(member)
            def mem_sub(*args, **kwargs):
                return member(*args, **kwargs)

        elif isinstance(member, property):
            mem_sub = property(member.fget, member.fset, member.fdel)
        else:
            raise NotImplementedError(
                "Members other than methods and properties are currently not supported."
            )
        return mem_sub


def doc_subs(member):
    """Doc subs wrapper.

    Only common attribute between methods and properties that we can
    modify is __doc__, so use that to mark members that need doc
    substitutions.
    Still, only methods can be marked for doc substitution (as for
    properties the docstring seems to be overwritten when specifying
    setters or deleters), hence this decorator should be applied
    before the property decorator. And 'type: ignore' comments are
    necessary because mypy cannot handle decorated properties (see
    https://github.com/python/mypy/issues/1362)
    """
    # Ensure we are operating on a method
    if not callable(member):  # pragma: no cover
        raise ValueError('`member` must be a callable.')
    member.__doc__ = DocSubs._DOC_TAG + member.__doc__
    return member


# endregion


class Pen(_vtkWrapper, _vtk.vtkPen):
    """Pythonic wrapper for a VTK Pen, used to draw lines.

    Parameters
    ----------
    color : ColorLike, default: "k"
        Color of the lines drawn using this pen. Any color parsable by
        :class:`pyvista.Color` is allowed.

    width : float, default: 1
        Width of the lines drawn using this pen.

    style : str, default: "-"
        Style of the lines drawn using this pen. See
        :ref:`Pen.LINE_STYLES <pen_line_styles>` for a list of allowed
        line styles.

    Other Parameters
    ----------------
    _wrap : vtk.vtkPen, optional
        Wrap an existing VTK Pen instance. Defaults to ``None`` (no wrapping).

    Notes
    -----
    .. _pen_line_styles:

    LINE_STYLES : dict
        Dictionary containing all allowed line styles as its keys.

        .. include:: ../pen_line_styles.rst

    """

    LINE_STYLES = {  # descr is used in the documentation, set to None to hide it from the docs.
        "": {"id": _vtk.vtkPen.NO_PEN, "descr": "Hidden"},
        "-": {"id": _vtk.vtkPen.SOLID_LINE, "descr": "Solid"},
        "--": {"id": _vtk.vtkPen.DASH_LINE, "descr": "Dashed"},
        ":": {"id": _vtk.vtkPen.DOT_LINE, "descr": "Dotted"},
        "-.": {"id": _vtk.vtkPen.DASH_DOT_LINE, "descr": "Dash-dot"},
        "-..": {"id": _vtk.vtkPen.DASH_DOT_DOT_LINE, "descr": "Dash-dot-dot"},
    }

    def __init__(self, color="k", width=1, style="-"):
        """Initialize a new Pen instance."""
        super().__init__()
        self.color = color
        self.width = width
        self.style = style

    @property
    def color(self):
        """Return or set the pen's color.

        Examples
        --------
        Set the pen's color to red.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.line([0, 1, 2], [2, 1, 3])
        >>> plot.pen.color = 'r'
        >>> chart.show()

        """
        return self._color

    @color.setter
    def color(self, val):
        self._color = Color(val, default_color="black")
        self.SetColor(*self._color.int_rgba)

    @property
    def width(self):
        """Return or set the pen's width.

        Examples
        --------
        Set the pen's width to 10

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.line([0, 1, 2], [2, 1, 3])
        >>> plot.pen.width = 10
        >>> chart.show()

        """
        return self.GetWidth()

    @width.setter
    def width(self, val):
        self.SetWidth(float(val))

    @property
    def style(self):
        """Return or set the pen's line style.

        See :ref:`Pen.LINE_STYLES <pen_line_styles>` for a list of allowed line styles.

        Examples
        --------
        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.line([0, 1, 2], [2, 1, 3])
        >>> plot.pen.style = '-.'
        >>> chart.show()

        """
        return self._line_style

    @style.setter
    def style(self, val):
        if val is None:
            val = ""
        try:
            self.SetLineType(self.LINE_STYLES[val]["id"])
            self._line_style = val
        except KeyError:
            formatted_styles = "\", \"".join(self.LINE_STYLES.keys())
            raise ValueError(f"Invalid line style. Allowed line styles: \"{formatted_styles}\"")


class Brush(_vtkWrapper, _vtk.vtkBrush):
    """Pythonic wrapper for a VTK Brush, used to fill shapes.

    Parameters
    ----------
    color : ColorLike, default: "k"
        Fill color of the shapes drawn using this brush. Any color
        parsable by :class:`pyvista.Color` is allowed.

    texture : pyvista.Texture, optional
        Texture used to fill shapes drawn using this brush. Any object
        convertible to a :class:`pyvista.Texture` is allowed. Defaults to
        ``None``.

    Other Parameters
    ----------------
    _wrap : vtk.vtkBrush, optional
        Wrap an existing VTK Brush instance. Defaults to ``None`` (no wrapping).

    """

    def __init__(self, color="k", texture=None):
        """Initialize a new Pen instance."""
        super().__init__()
        self.color = color
        self.texture = texture
        self._interpolate = True  # vtkBrush textureProperties defaults to LINEAR & STRETCH
        self._repeat = False

    @property
    def color(self):
        """Return or set the brush's color.

        Examples
        --------
        Set the brush's color to red.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])
        >>> plot.brush.color = 'r'
        >>> chart.show()

        """
        return self._color

    @color.setter
    def color(self, val):
        self._color = Color(val, default_color="black")
        self.SetColor(*self._color.int_rgba)

    @property
    def texture(self):
        """Return or set the brush's texture.

        Examples
        --------
        Set the brush's texture to the sample puppy texture.

        >>> import pyvista
        >>> from pyvista import examples
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])
        >>> plot.brush.texture = examples.download_puppy_texture()
        >>> chart.show()

        """
        return self._texture

    @texture.setter
    def texture(self, val):
        if val is None:
            self._texture = None
            self.SetTexture(None)
        else:
            self._texture = pyvista.Texture(val)
            self.SetTexture(self._texture.to_image())

    @property
    def texture_interpolate(self):
        """Set texture interpolation mode.

        There are two modes:

        * ``False`` - NEAREST
        * ``True`` - LINEAR

        Examples
        --------
        Set up a brush with a texture.

        >>> import pyvista
        >>> from pyvista import examples
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])
        >>> plot.brush.texture = examples.download_puppy_texture()
        >>> chart.show()

        Disable linear interpolation.

        >>> plot.brush.texture_interpolate = False
        >>> chart.show()

        """
        return self._interpolate

    @texture_interpolate.setter
    def texture_interpolate(self, val):
        self._interpolate = bool(val)
        self._update_textureprops()

    @property
    def texture_repeat(self):
        """Return or set the texture repeat mode.

        There are two modes:

        * ``False`` - STRETCH
        * ``True`` - REPEAT

        Examples
        --------
        Set up a brush with a texture.

        >>> import pyvista
        >>> from pyvista import examples
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])
        >>> plot.brush.texture = examples.download_puppy_texture()
        >>> chart.show()

        Enable texture repeat.

        >>> plot.brush.texture_repeat = True
        >>> chart.show()

        """
        return self._repeat

    @texture_repeat.setter
    def texture_repeat(self, val):
        self._repeat = bool(val)
        self._update_textureprops()

    def _update_textureprops(self):
        # Interpolation: NEAREST = 0x01, LINEAR = 0x02
        # Stretch/repeat: STRETCH = 0x04, REPEAT = 0x08
        self.SetTextureProperties(1 + int(self._interpolate) + 4 * (1 + int(self._repeat)))


class Axis(_vtkWrapper, _vtk.vtkAxis):
    """Pythonic interface for a VTK Axis, used by 2D charts.

    Parameters
    ----------
    label : str, default: ""
        Axis label.

    range : sequence[float], optional
        Axis range, denoting the minimum and maximum values
        displayed on this axis. Setting this to any valid value
        other than ``None`` will change this axis behavior to
        ``'fixed'``. Setting it to ``None`` will change the axis
        behavior to ``'auto'``.

    grid : bool, default: True
        Flag to toggle grid lines visibility for this axis.

    Attributes
    ----------
    pen : Pen
        Pen used to draw the axis.

    grid_pen : Pen
        Pen used to draw the grid lines.

    Other Parameters
    ----------------
    _wrap : vtk.vtkAxis, optional
        Wrap an existing VTK Axis instance. Defaults to ``None`` (no wrapping).

    """

    BEHAVIORS = {"auto": _vtk.vtkAxis.AUTO, "fixed": _vtk.vtkAxis.FIXED}

    def __init__(self, label="", range=None, grid=True):
        """Initialize a new Axis instance."""
        super().__init__()
        self._tick_locs = _vtk.vtkDoubleArray()
        self._tick_labels = _vtk.vtkStringArray()
        if vtk_version_info < (9, 2, 0):  # pragma: no cover
            # SetPen and SetGridPen methods are not available for older VTK versions,
            # so fallback to using wrapper objects.
            self.pen = Pen(color=(0, 0, 0), _wrap=self.GetPen())
            self.grid_pen = Pen(color=(0.95, 0.95, 0.95), _wrap=self.GetGridPen())
        else:
            self.pen = Pen(color=(0, 0, 0))
            self.grid_pen = Pen(color=(0.95, 0.95, 0.95))
            self.SetPen(self.pen)
            self.SetGridPen(self.grid_pen)
        self.label = label
        self._behavior = None  # Will be set by specifying the range below
        self.range = range
        self.grid = grid

    @property
    def label(self):
        """Return or set the axis label.

        Examples
        --------
        Set the axis label to ``"Axis Label"``.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.label = "Axis Label"
        >>> chart.show()

        """
        return self.GetTitle()

    @label.setter
    def label(self, val):
        self.SetTitle(val)

    @property
    def label_visible(self):
        """Return or set the axis label's visibility.

        Examples
        --------
        Hide the x-axis label of a 2D chart.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.label_visible = False
        >>> chart.show()

        """
        return self.GetTitleVisible()

    @label_visible.setter
    def label_visible(self, val):
        self.SetTitleVisible(bool(val))

    @property
    def label_size(self):
        """Return or set the size of the axis label font.

        Examples
        --------
        Set the x-axis label font size of a 2D chart to 20.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.label_size = 20
        >>> chart.x_axis.label_size
        20
        >>> chart.show()

        """
        return self.GetTitleProperties().GetFontSize()

    @label_size.setter
    def label_size(self, size):
        self.GetTitleProperties().SetFontSize(size)

    @property
    def range(self):
        """Return or set the axis range.

        This will automatically set the axis behavior to ``"fixed"``
        when a valid range is given. Setting the range to ``None``
        will set the axis behavior to ``"auto"``.

        Examples
        --------
        Manually specify the x-axis range of a 2D chart.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.range = [0, 5]
        >>> chart.show()

        Revert to automatic axis scaling.

        >>> chart.x_axis.range = None
        >>> chart.show()

        """
        r = [0.0, 0.0]
        self.GetRange(r)
        return r

    @range.setter
    def range(self, val):
        if val is None:
            self.behavior = "auto"
        else:
            self.behavior = "fixed"
            self.SetRange(*val)

    @property
    def behavior(self):
        """Set the axis' scaling behavior.

        Allowed behaviors are ``'auto'`` to automatically rescale the
        axis to fit all visible datapoints in the plot, or ``'fixed'``
        to use the user defined range.

        Examples
        --------
        Manually specify the x-axis range of a 2D chart.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.range = [0, 5]
        >>> chart.show()

        Revert to automatic axis scaling.

        >>> chart.x_axis.behavior = "auto"
        >>> chart.show()
        >>> chart.x_axis.range
        [0.0, 2.0]

        """
        return self._behavior

    @behavior.setter
    def behavior(self, val):
        try:
            self.SetBehavior(self.BEHAVIORS[val])
            self._behavior = val
        except KeyError:
            formatted_behaviors = "\", \"".join(self.BEHAVIORS.keys())
            raise ValueError(f"Invalid behavior. Allowed behaviors: \"{formatted_behaviors}\"")

    @property
    def margin(self):
        """Return or set the axis margin.

        Examples
        --------
        Create a 2D chart.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> chart.background_color = 'c'
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.show()

        Manually specify a larger (bottom) margin for the x-axis and a
        larger (left) margin for the y-axis.

        >>> chart.x_axis.margin = 50
        >>> chart.y_axis.margin = 50
        >>> chart.show()

        """
        return self.GetMargins()[0]

    @margin.setter
    def margin(self, val):
        # Second margin doesn't seem to have any effect? So we only expose the first entry as 'the margin'.
        m = self.GetMargins()
        self.SetMargins(val, m[1])

    @property
    def log_scale(self):
        """Flag denoting whether a log scale is used for this axis.

        Note that setting this property to ``True`` will not guarantee
        that the log scale will be enabled.  Verify whether activating
        the log scale succeeded by rereading this property.

        Examples
        --------
        Create a 2D chart.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2, 3, 4], [1e0, 1e1, 1e2, 1e3, 1e4])
        >>> chart.show()

        Try to enable the log scale on the y-axis.

        >>> chart.y_axis.log_scale = True
        >>> chart.show()
        >>> chart.y_axis.log_scale
        True

        """
        return self.GetLogScaleActive()

    @log_scale.setter
    def log_scale(self, val):
        # False: log_scale will be disabled, True: axis will attempt to activate log_scale if possible
        self.SetLogScale(bool(val))

    @property
    def grid(self):
        """Return or set the axis' grid line visibility.

        Examples
        --------
        Create a 2D chart with grid lines disabled for the x-axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.grid = False
        >>> chart.show()

        """
        return self.GetGridVisible()

    @grid.setter
    def grid(self, val):
        self.SetGridVisible(bool(val))

    @property
    def visible(self):
        """Return or set the axis' visibility.

        Examples
        --------
        Create a 2D chart with no visible y-axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.y_axis.visible = False
        >>> chart.show()

        """
        return self.GetAxisVisible()

    @visible.setter
    def visible(self, val):
        self.SetAxisVisible(bool(val))

    def toggle(self):
        """Toggle the axis' visibility.

        Examples
        --------
        Create a 2D chart.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.show()

        Toggle the visibility of the y-axis.

        >>> chart.y_axis.toggle()
        >>> chart.show()

        """
        self.visible = not self.visible

    # --- Ticks ---
    @property
    def tick_count(self):
        """Return or set the number of ticks drawn on this axis.

        Setting this property to a negative value or ``None`` will
        automatically determine the appropriate amount of ticks to
        draw.

        Examples
        --------
        Create a 2D chart with a reduced number of ticks on the x-axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.tick_count = 5
        >>> chart.show()

        Revert back to automatic tick behavior.

        >>> chart.x_axis.tick_count = None
        >>> chart.show()

        """
        return self.GetNumberOfTicks()

    @tick_count.setter
    def tick_count(self, val):
        if val is None or val < 0:
            val = -1
        self.SetNumberOfTicks(int(val))

    @property
    def tick_locations(self):
        """Return or set the tick locations for this axis.

        Setting this to ``None`` will revert back to the default,
        automatically determined, tick locations.

        Examples
        --------
        Create a 2D chart with custom tick locations and labels on the y-axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.y_axis.tick_locations = (0.2, 0.4, 0.6, 1, 1.5, 2, 3)
        >>> chart.y_axis.tick_labels = ["Very small", "Small", "Still small",
        ...                             "Small?", "Not large", "Large?",
        ...                             "Very large"]
        >>> chart.show()

        Revert back to automatic tick placement.

        >>> chart.y_axis.tick_locations = None
        >>> chart.y_axis.tick_labels = None
        >>> chart.show()

        """
        positions = self.GetTickPositions()
        return tuple(positions.GetValue(i) for i in range(positions.GetNumberOfValues()))

    @tick_locations.setter
    def tick_locations(self, val):
        self._tick_locs.Reset()
        if val is not None:
            for loc in val:
                self._tick_locs.InsertNextValue(loc)
        self._update_ticks()

    @property
    def tick_labels(self):
        """Return or set the tick labels for this axis.

        You can specify a sequence, to provide a unique label to every
        tick position; a string, to describe the label format to use
        for each label; or ``None``, which will revert back to the
        default tick labels.  A label format is a string consisting of
        an integer part, denoting the precision to use, and a final
        character, denoting the notation to use.

        Allowed notations:

        * ``"f"`` for fixed notation
        * ``"e"`` for scientific notation.

        Examples
        --------
        Create a 2D chart with custom tick locations and labels on the y-axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.y_axis.tick_locations = (0.2, 0.4, 0.6, 1, 1.5, 2, 3)
        >>> chart.y_axis.tick_labels = ["Very small", "Small", "Still small",
        ...                             "Small?", "Not large", "Large?",
        ...                             "Very large"]
        >>> chart.show()

        Revert back to automatic tick placement.

        >>> chart.y_axis.tick_locations = None
        >>> chart.y_axis.tick_labels = None
        >>> chart.show()

        Specify a custom label format to use (fixed notation with precision 2).

        >>> chart.y_axis.tick_labels = "2f"
        >>> chart.show()

        """
        labels = self.GetTickLabels()
        return tuple(labels.GetValue(i) for i in range(labels.GetNumberOfValues()))

    @tick_labels.setter
    def tick_labels(self, val):
        self._tick_labels.Reset()
        self.SetNotation(_vtk.vtkAxis.STANDARD_NOTATION)
        if isinstance(val, str):
            precision = int(val[:-1])
            notation = val[-1].lower()
            if notation == "f":
                self.SetNotation(_vtk.vtkAxis.FIXED_NOTATION)
                self.SetPrecision(precision)
            elif notation == "e":
                self.SetNotation(_vtk.vtkAxis.SCIENTIFIC_NOTATION)
                self.SetPrecision(precision)
        elif isinstance(val, Sequence):
            for label in val:
                self._tick_labels.InsertNextValue(label)
        self._update_ticks()

    @property
    def tick_label_size(self):
        """Return or set the size of the axis tick label font.

        Examples
        --------
        Set the x-axis tick label font size of a 2D chart to 20.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.tick_label_size = 20
        >>> chart.x_axis.tick_label_size
        20
        >>> chart.show()

        """
        return self.GetLabelProperties().GetFontSize()

    @tick_label_size.setter
    def tick_label_size(self, size):
        self.GetLabelProperties().SetFontSize(size)

    @property
    def tick_size(self):
        """Return or set the size of this axis' ticks.

        Examples
        --------
        Create a 2D chart with an x-axis with an increased tick size
        and adjusted offset for the tick labels.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.tick_size += 10
        >>> chart.x_axis.tick_labels_offset += 12
        >>> chart.show()

        """
        return self.GetTickLength()

    @tick_size.setter
    def tick_size(self, val):
        self.SetTickLength(val)

    @property
    def tick_labels_offset(self):
        """Return or set the offset of the tick labels for this axis.

        Examples
        --------
        Create a 2D chart with an x-axis with an increased tick size
        and adjusted offset for the tick labels.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.tick_size += 10
        >>> chart.x_axis.tick_labels_offset += 12
        >>> chart.show()

        """
        return self.GetLabelOffset()

    @tick_labels_offset.setter
    def tick_labels_offset(self, val):
        self.SetLabelOffset(float(val))

    @property
    def tick_labels_visible(self):
        """Return or set the tick label visibility for this axis.

        Examples
        --------
        Create a 2D chart with hidden tick labels on the y-axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.y_axis.tick_labels_visible = False
        >>> chart.show()

        """
        return self.GetLabelsVisible()

    @tick_labels_visible.setter
    def tick_labels_visible(self, val):
        self.SetLabelsVisible(bool(val))
        self.SetRangeLabelsVisible(bool(val))

    @property
    def ticks_visible(self):
        """Return or set the tick visibility for this axis.

        Examples
        --------
        Create a 2D chart with hidden ticks on the y-axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.y_axis.ticks_visible = False
        >>> chart.show()

        """
        return self.GetTicksVisible()

    @ticks_visible.setter
    def ticks_visible(self, val):
        self.SetTicksVisible(bool(val))

    def _update_ticks(self):
        locs = None if self._tick_locs.GetNumberOfValues() == 0 else self._tick_locs
        labels = None if self._tick_labels.GetNumberOfValues() == 0 else self._tick_labels
        self.SetCustomTickPositions(locs, labels)


class _CustomContextItem(_vtk.vtkPythonItem):
    class ItemWrapper:
        def Initialize(self, item):
            # item is the _CustomContextItem subclass instance
            return True

        def Paint(self, item, painter):
            # item is the _CustomContextItem subclass instance
            return item.paint(painter)

    def __init__(self):
        super().__init__()
        # This will also call ItemWrapper.Initialize
        self.SetPythonObject(_CustomContextItem.ItemWrapper())

    def paint(self, painter):
        return True


class _ChartBackground(_CustomContextItem):
    """Utility class for chart backgrounds."""

    def __init__(self, chart):
        super().__init__()
        # Note: This SHOULD be a weakref proxy, as otherwise the garbage collector will not clean up unused charts
        # (because of the cyclic references between charts and their background).
        self._chart = weakref.proxy(chart)  # Weakref proxy to the chart to draw the background for
        # Default background is translucent with black border line
        self.BorderPen = Pen(color=(0, 0, 0))
        self.BackgroundBrush = Brush(color=(0, 0, 0, 0))
        # Default active background is slightly more opaque with yellow border line
        self.ActiveBorderPen = Pen(color=(0.8, 0.8, 0.2))
        self.ActiveBackgroundBrush = Brush(color=(1.0, 1.0, 1.0, 0.4))

    def paint(self, painter):
        if self._chart.visible:
            painter.ApplyPen(self.ActiveBorderPen if self._chart._interactive else self.BorderPen)
            painter.ApplyBrush(
                self.ActiveBackgroundBrush if self._chart._interactive else self.BackgroundBrush
            )
            l, b, w, h = self._chart._geometry
            painter.DrawRect(l, b, w, h)
            if vtk_version_info < (9, 2, 0):  # pragma: no cover
                # Following 'patch' is necessary for earlier VTK versions. Otherwise Pie plots will use the same opacity
                # as the chart's background when their legend is hidden. As the default background is transparent,
                # this will cause Pie charts to completely disappear.
                painter.GetBrush().SetOpacity(255)
                painter.GetBrush().SetTexture(None)
        return True


class _Chart(DocSubs):
    """Common pythonic interface for vtkChart, vtkChartBox, vtkChartPie and ChartMPL instances."""

    # Subclasses should specify following substitutions: 'chart_name', 'chart_args', 'chart_init' and 'chart_set_labels'.
    _DOC_SUBS: Optional[Dict[str, str]] = None

    def __init__(self, size=(1, 1), loc=(0, 0)):
        super().__init__()
        self._background = _ChartBackground(self)
        self._x_axis = Axis()
        self._y_axis = Axis()
        if size is not None:
            self.size = size
        if loc is not None:
            self.loc = loc

    @property
    def _scene(self):
        """Get a reference to the vtkScene in which this chart is drawn."""
        return self.GetScene()

    @property
    def _renderer(self):
        """Get a reference to the vtkRenderer in which this chart is drawn."""
        return self._scene.GetRenderer() if self._scene is not None else None

    def _render_event(self, *args, plotter_render=False, **kwargs):
        """Update the chart right before it will be rendered."""
        # Only resize on real VTK render events (plotter.render calls will afterwards invoke a proper render event)
        if not plotter_render:
            self._resize()

    def _resize(self):
        """Resize this chart.

        Resize this chart such that it always occupies the specified
        geometry (matching the specified location and size).

        Returns
        -------
        bool
            ``True`` if the chart was resized, ``False`` otherwise.

        """
        # edge race case
        if self._renderer is None:  # pragma: no cover
            return

        r_w, r_h = self._renderer.GetSize()
        # Alternatively: self.scene.GetViewWidth(), self.scene.GetViewHeight()
        _, _, c_w, c_h = (int(g) for g in self._geometry)
        # Target size is calculated from specified normalized width and height and the renderer's current size
        t_w = int(self._size[0] * r_w)
        t_h = int(self._size[1] * r_h)
        resize = c_w != t_w or c_h != t_h
        if resize:
            # Mismatch between current size and target size, so resize chart:
            self._geometry = (int(self._loc[0] * r_w), int(self._loc[1] * r_h), t_w, t_h)
        return resize

    @property
    def _geometry(self):
        """Chart geometry (x and y position of bottom left corner and width and height in pixels)."""
        return tuple(self.GetSize())

    @_geometry.setter
    def _geometry(self, val):
        """Set the chart geometry."""
        self.SetSize(_vtk.vtkRectf(*val))

    @property
    def _interactive(self):
        """Return or set the chart's interactivity.

        Notes
        -----
        Users should not set this property directly, but use the
        :func:`Renderer.set_chart_interaction` method instead.

        """
        return self.GetInteractive()

    @_interactive.setter
    def _interactive(self, val):
        self.SetInteractive(val)

    def _is_within(self, pos):
        """Check whether the specified position (in pixels) lies within this chart's geometry."""
        l, b, w, h = self._geometry
        return l <= pos[0] <= l + w and b <= pos[1] <= b + h

    @property  # type: ignore
    @doc_subs
    def size(self):
        """Return or set the chart size in normalized coordinates.

        A size of ``(1, 1)`` occupies the whole renderer.

        Examples
        --------
        Create a half-sized {chart_name} centered in the middle of the
        renderer.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.size = (0.5, 0.5)
        >>> chart.loc = (0.25, 0.25)
        >>> chart.show()

        """
        return self._size

    @size.setter
    def size(self, val):
        if not (len(val) == 2 and 0 <= val[0] <= 1 and 0 <= val[1] <= 1):
            raise ValueError(f'Invalid size {val}.')
        self._size = val

    @property  # type: ignore
    @doc_subs
    def loc(self):
        """Return or set the chart position in normalized coordinates.

        This denotes the location of the chart's bottom left corner.

        Examples
        --------
        Create a half-sized {chart_name} centered in the middle of the
        renderer.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.size = (0.5, 0.5)
        >>> chart.loc = (0.25, 0.25)
        >>> chart.show()

        """
        return self._loc

    @loc.setter
    def loc(self, val):
        if not (len(val) == 2 and 0 <= val[0] <= 1 and 0 <= val[1] <= 1):
            raise ValueError(f'Invalid loc {val}.')
        self._loc = val

    @property  # type: ignore
    @doc_subs
    def border_color(self):
        """Return or set the chart's border color.

        Examples
        --------
        Create a {chart_name} with a thick, dashed red border.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.border_color = 'r'
        >>> chart.border_width = 5
        >>> chart.border_style = '--'
        >>> chart.show(interactive=False)

        """
        return self._background.BorderPen.color

    @border_color.setter
    def border_color(self, val):
        self._background.BorderPen.color = val

    @property  # type: ignore
    @doc_subs
    def border_width(self):
        """Return or set the chart's border width.

        Examples
        --------
        Create a {chart_name} with a thick, dashed red border.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.border_color = 'r'
        >>> chart.border_width = 5
        >>> chart.border_style = '--'
        >>> chart.show(interactive=False)

        """
        return self._background.BorderPen.width

    @border_width.setter
    def border_width(self, val):
        self._background.BorderPen.width = val
        self._background.ActiveBorderPen.width = val

    @property  # type: ignore
    @doc_subs
    def border_style(self):
        """Return or set the chart's border style.

        Examples
        --------
        Create a {chart_name} with a thick, dashed red border.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.border_color = 'r'
        >>> chart.border_width = 5
        >>> chart.border_style = '--'
        >>> chart.show(interactive=False)

        """
        return self._background.BorderPen.style

    @border_style.setter
    def border_style(self, val):
        self._background.BorderPen.style = val
        self._background.ActiveBorderPen.style = val

    @property  # type: ignore
    @doc_subs
    def active_border_color(self):
        """Return or set the chart's border color in interactive mode.

        Examples
        --------
        Create a {chart_name} with a thick, dashed red border.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.border_color = 'r'
        >>> chart.border_width = 5
        >>> chart.border_style = '--'
        >>> chart.show(interactive=False)

        Set the active border color to yellow and activate the chart.

        >>> chart.active_border_color = 'y'
        >>> chart.show(interactive=True)

        """
        return self._background.ActiveBorderPen.color

    @active_border_color.setter
    def active_border_color(self, val):
        self._background.ActiveBorderPen.color = val

    @property  # type: ignore
    @doc_subs
    def background_color(self):
        """Return or set the chart's background color.

        Examples
        --------
        Create a {chart_name} with a green background.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.background_color = (0.5, 0.9, 0.5)
        >>> chart.show(interactive=False)

        """
        return self._background.BackgroundBrush.color

    @background_color.setter
    def background_color(self, val):
        self._background.BackgroundBrush.color = val

    @property  # type: ignore
    @doc_subs
    def background_texture(self):
        """Return or set the chart's background texture.

        Examples
        --------
        Create a {chart_name} with an emoji as its background.

        >>> import pyvista
        >>> from pyvista import examples
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.background_texture = examples.download_emoji_texture()
        >>> chart.show(interactive=False)

        """
        return self._background.BackgroundBrush.texture

    @background_texture.setter
    def background_texture(self, val):
        self._background.BackgroundBrush.texture = val
        self._background.ActiveBackgroundBrush.texture = val

    @property  # type: ignore
    @doc_subs
    def active_background_color(self):
        """Return or set the chart's background color in interactive mode.

        Examples
        --------
        Create a {chart_name} with a green background.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.background_color = (0.5, 0.9, 0.5)
        >>> chart.show(interactive=False)

        Set the active background color to blue and activate the chart.

        >>> chart.active_background_color = 'b'
        >>> chart.show(interactive=True)

        """
        return self._background.ActiveBackgroundBrush.color

    @active_background_color.setter
    def active_background_color(self, val):
        self._background.ActiveBackgroundBrush.color = val

    @property  # type: ignore
    @doc_subs
    def visible(self):
        """Return or set the chart's visibility.

        Examples
        --------
        Create a {chart_name}.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.show()

        Hide it.

        >>> chart.visible = False
        >>> chart.show()

        """
        return self.GetVisible()

    @visible.setter
    def visible(self, val):
        self.SetVisible(val)

    @doc_subs
    def toggle(self):
        """Toggle the chart's visibility.

        Examples
        --------
        Create a {chart_name}.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.show()

        Hide it.

        >>> chart.toggle()
        >>> chart.show()

        """
        self.visible = not self.visible

    @property  # type: ignore
    @doc_subs
    def title(self):
        """Return or set the chart's title.

        Examples
        --------
        Create a {chart_name} with title 'My Chart'.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.title = 'My Chart'
        >>> chart.show()

        """
        return self.GetTitle()

    @title.setter
    def title(self, val):
        self.SetTitle(val)

    @property  # type: ignore
    @doc_subs
    def legend_visible(self):
        """Return or set the visibility of the chart's legend.

        Examples
        --------
        Create a {chart_name} with custom labels.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> {chart_set_labels}
        >>> chart.show()

        Hide the legend.

        >>> chart.legend_visible = False
        >>> chart.show()

        """
        return self.GetShowLegend()

    @legend_visible.setter
    def legend_visible(self, val):
        self.SetShowLegend(val)

    @doc_subs
    def show(
        self,
        interactive=True,
        off_screen=None,
        full_screen=None,
        screenshot=None,
        window_size=None,
        notebook=None,
        background='w',
        dev_kwargs={},
    ):
        """Show this chart in a self contained plotter.

        Parameters
        ----------
        interactive : bool, default: True
            Enable interaction with the chart. Interaction is not enabled
            when plotting off screen.

        off_screen : bool, optional
            Plots off screen when ``True``.  Helpful for saving screenshots
            without a window popping up. Defaults to active theme setting.

        full_screen : bool, optional
            Opens window in full screen.  When enabled, ignores
            ``window_size``. Defaults to active theme setting.

        screenshot : str | bool, default: False
            Saves screenshot to file when enabled.  See:
            :func:`Plotter.screenshot() <pyvista.Plotter.screenshot>`.

            When ``True``, takes screenshot and returns ``numpy`` array of
            image.

        window_size : list, optional
            Window size in pixels. Defaults to active theme setting.

        notebook : bool, optional
            When ``True``, the resulting plot is placed inline a
            jupyter notebook.  Assumes a jupyter console is active.

        background : ColorLike, default: "w"
            Use to make the entire mesh have a single solid color.
            Either a string, RGB list, or hex color string.  For example:
            ``color='white'``, ``color='w'``, ``color=[1.0, 1.0, 1.0]``, or
            ``color='#FFFFFF'``.

        dev_kwargs : dict, optional
            Optional developer keyword arguments.

        Returns
        -------
        np.ndarray
            Numpy array of the last image when ``screenshot=True``
            is set. Optionally contains alpha values. Sized:

            * [Window height x Window width x 3] if the theme sets
              ``transparent_background=False``.
            * [Window height x Window width x 4] if the theme sets
              ``transparent_background=True``.

        Examples
        --------
        Create a simple {chart_name} and show it.

        >>> import pyvista
        >>> chart = pyvista.{cls}({chart_args}){chart_init}
        >>> chart.show()

        """
        if off_screen is None:
            off_screen = pyvista.OFF_SCREEN
        pl = pyvista.Plotter(window_size=window_size, notebook=notebook, off_screen=off_screen)
        pl.background_color = background
        pl.add_chart(self)
        if interactive and (not off_screen or pyvista.BUILDING_GALLERY):  # pragma: no cover
            pl.set_chart_interaction(self)
        return pl.show(
            screenshot=screenshot,
            full_screen=full_screen,
            **dev_kwargs,
        )


class _Plot(DocSubs):
    """Common pythonic interface for vtkPlot and vtkPlot3D instances."""

    # Subclasses should specify following substitutions: 'plot_name', 'chart_init' and 'plot_init'.
    _DOC_SUBS: Optional[Dict[str, str]] = None

    def __init__(self, chart):
        super().__init__()
        self._chart = weakref.proxy(chart)
        self._pen = Pen()
        self._brush = Brush()
        self._label = ""
        if hasattr(self, "SetPen"):
            self.SetPen(self._pen)
        if hasattr(self, "SetBrush"):
            self.SetBrush(self._brush)

    @property  # type: ignore
    @doc_subs
    def color(self):
        """Return or set the plot's color.

        This is the color used by the plot's pen and brush to draw lines and shapes.

        Examples
        --------
        Set the {plot_name}'s color to red.

        >>> import pyvista
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> plot.color = 'r'
        >>> chart.show()

        """
        return self.pen.color

    @color.setter
    def color(self, val):
        self.pen.color = val
        self.brush.color = val

    @property  # type: ignore
    @doc_subs
    def pen(self):
        """Pen object controlling how lines in this plot are drawn.

        Returns
        -------
        Pen
            Pen object controlling how lines in this plot are drawn.

        Examples
        --------
        Increase the line width of the {plot_name}'s pen object.

        >>> import pyvista
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> plot.line_style = '-'  # Make sure all lines are visible
        >>> plot.pen.width = 10
        >>> chart.show()

        """
        return self._pen

    @property  # type: ignore
    @doc_subs
    def brush(self):
        """Brush object controlling how shapes in this plot are filled.

        Returns
        -------
        Brush
            Brush object controlling how shapes in this plot are filled.

        Examples
        --------
        Use a custom texture for the {plot_name}'s brush object.

        >>> import pyvista
        >>> from pyvista import examples
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> plot.brush.texture = examples.download_puppy_texture()
        >>> chart.show()

        """
        return self._brush

    @property  # type: ignore
    @doc_subs
    def line_width(self):
        """Return or set the line width of all lines drawn in this plot.

        This is equivalent to accessing/modifying the width of this plot's pen.

        Examples
        --------
        Set the line width to 10

        >>> import pyvista
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> plot.line_style = '-'  # Make sure all lines are visible
        >>> plot.line_width = 10
        >>> chart.show()

        """
        return self.pen.width

    @line_width.setter
    def line_width(self, val):
        self.pen.width = val

    @property  # type: ignore
    @doc_subs
    def line_style(self):
        """Return or set the line style of all lines drawn in this plot.

        This is equivalent to accessing/modifying the style of this plot's pen.

        Examples
        --------
        Set a custom line style.

        >>> import pyvista
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> plot.line_style = '-.'
        >>> chart.show()

        """
        return self.pen.style

    @line_style.setter
    def line_style(self, val):
        self.pen.style = val

    @property  # type: ignore
    @doc_subs
    def label(self):
        """Return or set the this plot's label, as shown in the chart's legend.

        Examples
        --------
        Create a {plot_name} with custom label.

        >>> import pyvista
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> plot.label = "My awesome plot"
        >>> chart.show()

        """
        return self._label

    @label.setter
    def label(self, val):
        self._label = "" if val is None else val
        self.SetLabel(self._label)

    @property  # type: ignore
    @doc_subs
    def visible(self):
        """Return or set the this plot's visibility.

        Examples
        --------
        Create a {plot_name}.

        >>> import pyvista
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> chart.show()

        Hide it.

        >>> plot.visible = False
        >>> chart.show()

        """
        return self.GetVisible()

    @visible.setter
    def visible(self, val):
        self.SetVisible(val)

    @doc_subs
    def toggle(self):
        """Toggle the plot's visibility.

        Examples
        --------
        Create a {plot_name}.

        >>> import pyvista
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> chart.show()

        Hide it.

        >>> plot.toggle()
        >>> chart.show()

        """
        self.visible = not self.visible


class _MultiCompPlot(_Plot):
    """Common pythonic interface for vtkPlot instances with multiple components.

    Example subclasses are BoxPlot, PiePlot, BarPlot and StackPlot.
    """

    DEFAULT_COLOR_SCHEME = "qual_accent"

    # Subclasses should specify following substitutions: 'plot_name', 'chart_init', 'plot_init', 'multichart_init' and 'multiplot_init'.
    _DOC_SUBS: Optional[Dict[str, str]] = None

    def __init__(self, chart):
        super().__init__(chart)
        self._color_series = _vtk.vtkColorSeries()
        self._lookup_table = self._color_series.CreateLookupTable(_vtk.vtkColorSeries.CATEGORICAL)
        self._labels = _vtk.vtkStringArray()
        self.SetLabels(self._labels)
        self.color_scheme = self.DEFAULT_COLOR_SCHEME

    @property  # type: ignore
    @doc_subs
    def color_scheme(self):
        """Return or set the plot's color scheme.

        This scheme defines the colors of the different
        components drawn by this plot.
        See the table below for the available color
        schemes.

        Notes
        -----
        .. _plot_color_schemes:

        Overview of all available color schemes.

        .. include:: ../plot_color_schemes.rst

        Examples
        --------
        Set the {plot_name}'s color scheme to warm.

        >>> import pyvista
        >>> chart = {multichart_init}
        >>> plot = {multiplot_init}
        >>> plot.color_scheme = "warm"
        >>> chart.show()

        """
        return SCHEME_NAMES.get(self._color_series.GetColorScheme(), "custom")

    @color_scheme.setter
    def color_scheme(self, val):
        self._color_series.SetColorScheme(COLOR_SCHEMES.get(val, COLOR_SCHEMES["custom"])["id"])
        self._color_series.BuildLookupTable(self._lookup_table, _vtk.vtkColorSeries.CATEGORICAL)
        self.brush.color = self.colors[0]

    @property  # type: ignore
    @doc_subs
    def colors(self):
        """Return or set the plot's colors.

        These are the colors used for the different
        components drawn by this plot.

        Examples
        --------
        Set the {plot_name}'s colors manually.

        >>> import pyvista
        >>> chart = {multichart_init}
        >>> plot = {multiplot_init}
        >>> plot.colors = ["b", "g", "r", "c"]
        >>> chart.show()

        """
        return [
            Color(self._color_series.GetColor(i))
            for i in range(self._color_series.GetNumberOfColors())
        ]

    @colors.setter
    def colors(self, val):
        if val is None:
            self.color_scheme = self.DEFAULT_COLOR_SCHEME
            # Setting color_scheme already sets brush.color
        elif isinstance(val, str):
            self.color_scheme = val
            # Setting color_scheme already sets brush.color
        else:
            try:
                self._color_series.SetNumberOfColors(len(val))
                for i, color in enumerate(val):
                    self._color_series.SetColor(i, Color(color).vtk_c3ub)
                self._color_series.BuildLookupTable(
                    self._lookup_table, _vtk.vtkColorSeries.CATEGORICAL
                )
                self.brush.color = self.colors[0]  # Synchronize "color" and "colors" properties
            except ValueError as e:
                self.color_scheme = self.DEFAULT_COLOR_SCHEME
                raise ValueError(
                    "Invalid colors specified, falling back to default color scheme."
                ) from e

    @property  # type: ignore
    @doc_subs
    def color(self):
        """Return or set the plot's color.

        This is the color used by the plot's brush
        to draw the different components.

        Examples
        --------
        Set the {plot_name}'s color to red.

        >>> import pyvista
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> plot.color = 'r'
        >>> chart.show()

        """
        return self.brush.color

    @color.setter
    def color(self, val):
        # Override default _Plot behaviour. This makes sure the plot's "color_scheme", "colors" and "color" properties
        # (and their internal representations through color series, lookup tables and brushes) stay synchronized.
        self.colors = [val]

    @property  # type: ignore
    @doc_subs
    def labels(self):
        """Return or set the this plot's labels, as shown in the chart's legend.

        Examples
        --------
        Create a {plot_name}.

        >>> import pyvista
        >>> chart = {multichart_init}
        >>> plot = {multiplot_init}
        >>> chart.show()

        Modify the labels.

        >>> plot.labels = ["A", "B", "C", "D"]
        >>> chart.show()

        """
        return [self._labels.GetValue(i) for i in range(self._labels.GetNumberOfValues())]

    @labels.setter
    def labels(self, val):
        self._labels.Reset()
        if isinstance(val, str):
            val = [val]
        try:
            if val is not None:
                for label in val:
                    self._labels.InsertNextValue(label)
        except TypeError:
            raise ValueError("Invalid labels specified.")

    @property  # type: ignore
    @doc_subs
    def label(self):
        """Return or set the this plot's label, as shown in the chart's legend.

        Examples
        --------
        Create a {plot_name} with custom label.

        >>> import pyvista
        >>> import numpy as np
        >>> chart = {chart_init}
        >>> plot = {plot_init}
        >>> chart.show()

        Modify the label.

        >>> plot.label = "My awesome plot"
        >>> chart.show()

        """
        return self.labels[0] if self._labels.GetNumberOfValues() > 0 else ""

    @label.setter
    def label(self, val):
        # Override default _Plot behaviour. This makes sure the plot's "labels" and "label" properties (and their
        # internal representations) stay synchronized.
        self.labels = None if val is None else [val]


class LinePlot2D(_vtk.vtkPlotLine, _Plot):
    """Class representing a 2D line plot.

    Users should typically not directly create new plot instances, but use the dedicated 2D chart's plotting methods.

    Parameters
    ----------
    chart : Chart2D
        The chart containing this plot.

    x : array_like
        X coordinates of the points through which a line should be drawn.

    y : array_like
        Y coordinates of the points through which a line should be drawn.

    color : ColorLike, default: "b"
        Color of the line drawn in this plot. Any color parsable by :class:`pyvista.Color` is allowed.

    width : float, default: 1
        Width of the line drawn in this plot.

    style : str, default: "-"
        Style of the line drawn in this plot. See :ref:`Pen.LINE_STYLES <pen_line_styles>` for a list of allowed line
        styles.

    label : str, default: ""
        Label of this plot, as shown in the chart's legend.

    Examples
    --------
    Create a 2D chart plotting an approximate satellite
    trajectory.

    >>> import pyvista
    >>> from pyvista import examples
    >>> import numpy as np
    >>> chart = pyvista.Chart2D()
    >>> x = np.linspace(0, 1, 100)
    >>> y = np.sin(6.5*x-1)
    >>> _ = chart.line(x, y, "y", 4)
    >>> chart.background_texture = examples.load_globe_texture()
    >>> chart.hide_axes()
    >>> chart.show()

    """

    _DOC_SUBS = {
        "plot_name": "2D line plot",
        "chart_init": "pyvista.Chart2D()",
        "plot_init": "chart.line([0, 1, 2], [2, 1, 3])",
    }

    def __init__(self, chart, x, y, color="b", width=1.0, style="-", label=""):
        """Initialize a new 2D line plot instance."""
        super().__init__(chart)
        self._table = pyvista.Table({"x": np.empty(0, np.float32), "y": np.empty(0, np.float32)})
        self.SetInputData(self._table, "x", "y")
        self.update(x, y)
        self.color = color
        self.line_width = width
        self.line_style = style
        self.label = label

    @property
    def x(self):
        """Retrieve the X coordinates of the points through which a line is drawn.

        Examples
        --------
        Create a line plot and display the x coordinates.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.line([0, 1, 2], [2, 1, 3])
        >>> plot.x
        pyvista_ndarray([0, 1, 2])
        >>> chart.show()

        """
        return self._table["x"]

    @property
    def y(self):
        """Retrieve the Y coordinates of the points through which a line is drawn.

        Examples
        --------
        Create a line plot and display the y coordinates.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.line([0, 1, 2], [2, 1, 3])
        >>> plot.y
        pyvista_ndarray([2, 1, 3])
        >>> chart.show()

        """
        return self._table["y"]

    def update(self, x, y):
        """Update this plot's points, through which a line is drawn.

        Parameters
        ----------
        x : array_like
            The new x coordinates of the points through which a line should be drawn.

        y : array_like
            The new y coordinates of the points through which a line should be drawn.

        Examples
        --------
        Create a line plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.show()

        Update the line's y coordinates.

        >>> plot.update([0, 1, 2], [3, 1, 2])
        >>> chart.show()

        """
        if len(x) > 1:
            self._table.update({"x": np.array(x, copy=False), "y": np.array(y, copy=False)})
            self.visible = True
        else:
            # Turn off visibility for fewer than 2 points as otherwise an error message is shown
            self.visible = False


class ScatterPlot2D(_vtk.vtkPlotPoints, _Plot):
    """Class representing a 2D scatter plot.

    Users should typically not directly create new plot instances, but use the dedicated 2D chart's plotting methods.

    Parameters
    ----------
    chart : Chart2D
        The chart containing this plot.

    x : array_like
        X coordinates of the points to draw.

    y : array_like
        Y coordinates of the points to draw.

    color : ColorLike, default: "b"
        Color of the points drawn in this plot. Any color parsable by :class:`pyvista.Color` is allowed.

    size : float, default: 10
        Size of the point markers drawn in this plot.

    style : str, default: "o"
        Style of the point markers drawn in this plot. See :ref:`ScatterPlot2D.MARKER_STYLES <scatter_marker_styles>`
        for a list of allowed marker styles.

    label : str, default: ""
        Label of this plot, as shown in the chart's legend.

    Notes
    -----
    .. _scatter_marker_styles:

    MARKER_STYLES : dict
        Dictionary containing all allowed marker styles as its keys.

        .. include:: ../scatter_marker_styles.rst

    Examples
    --------
    Plot a simple sine wave as a scatter plot.

    >>> import pyvista
    >>> import numpy as np
    >>> x = np.linspace(0, 2*np.pi, 20)
    >>> y = np.sin(x)
    >>> chart = pyvista.Chart2D()
    >>> _ = chart.scatter(x, y)
    >>> chart.show()

    """

    MARKER_STYLES = {  # descr is used in the documentation, set to None to hide it from the docs.
        "": {"id": _vtk.vtkPlotPoints.NONE, "descr": "Hidden"},
        "x": {"id": _vtk.vtkPlotPoints.CROSS, "descr": "Cross"},
        "+": {"id": _vtk.vtkPlotPoints.PLUS, "descr": "Plus"},
        "s": {"id": _vtk.vtkPlotPoints.SQUARE, "descr": "Square"},
        "o": {"id": _vtk.vtkPlotPoints.CIRCLE, "descr": "Circle"},
        "d": {"id": _vtk.vtkPlotPoints.DIAMOND, "descr": "Diamond"},
    }
    _DOC_SUBS = {
        "plot_name": "2D scatter plot",
        "chart_init": "pyvista.Chart2D()",
        "plot_init": "chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])",
    }

    def __init__(self, chart, x, y, color="b", size=10, style="o", label=""):
        """Initialize a new 2D scatter plot instance."""
        super().__init__(chart)
        self._table = pyvista.Table({"x": np.empty(0, np.float32), "y": np.empty(0, np.float32)})
        self.SetInputData(self._table, "x", "y")
        self.update(x, y)
        self.color = color
        self.marker_size = size
        self.marker_style = style
        self.label = label

    @property
    def x(self):
        """Retrieve the X coordinates of this plot's points.

        Examples
        --------
        Create a scatter plot and display the x coordinates.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
        >>> plot.x
        pyvista_ndarray([0, 1, 2, 3, 4])
        >>> chart.show()

        """
        return self._table["x"]

    @property
    def y(self):
        """Retrieve the Y coordinates of this plot's points.

        Examples
        --------
        Create a scatter plot and display the y coordinates.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
        >>> plot.y
        pyvista_ndarray([2, 1, 3, 4, 2])
        >>> chart.show()

        """
        return self._table["y"]

    def update(self, x, y):
        """Update this plot's points.

        Parameters
        ----------
        x : array_like
            The new x coordinates of the points to draw.

        y : array_like
            The new y coordinates of the points to draw.

        Examples
        --------
        Create a scatter plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
        >>> chart.show()

        Update the marker locations.

        >>> plot.update([0, 1, 2, 3, 4], [3, 2, 4, 2, 1])
        >>> chart.show()

        """
        if len(x) > 0:
            self._table.update({"x": np.array(x, copy=False), "y": np.array(y, copy=False)})
            self.visible = True
        else:
            self.visible = False

    @property
    def marker_size(self):
        """Return or set the plot's marker size.

        Examples
        --------
        Create a 2D scatter plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
        >>> chart.show()

        Increase the marker size.

        >>> plot.marker_size = 30
        >>> chart.show()

        """
        return self.GetMarkerSize()

    @marker_size.setter
    def marker_size(self, val):
        self.SetMarkerSize(val)

    @property
    def marker_style(self):
        """Return or set the plot's marker style.

        Examples
        --------
        Create a 2D scatter plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
        >>> chart.show()

        Change the marker style.

        >>> plot.marker_style = "d"
        >>> chart.show()

        """
        return self._marker_style

    @marker_style.setter
    def marker_style(self, val):
        if val is None:
            val = ""
        try:
            self.SetMarkerStyle(self.MARKER_STYLES[val]["id"])
            self._marker_style = val
        except KeyError:
            formatted_styles = "\", \"".join(self.MARKER_STYLES.keys())
            raise ValueError(f"Invalid marker style. Allowed marker styles: \"{formatted_styles}\"")


class AreaPlot(_vtk.vtkPlotArea, _Plot):
    """Class representing a 2D area plot.

    Users should typically not directly create new plot instances, but use the dedicated 2D chart's plotting methods.

    Parameters
    ----------
    chart : Chart2D
        The chart containing this plot.

    x : array_like
        X coordinates of the points outlining the area to draw.

    y1 : array_like
        Y coordinates of the points on the first outline of the area to draw.

    y2 : array_like, optional
        Y coordinates of the points on the second outline of the area to
        draw. Defaults to ``numpy.zeros_like(x)``.

    color : ColorLike, default: "b"
        Color of the area drawn in this plot. Any color parsable by :class:`pyvista.Color` is allowed.

    label : str, default: ""
        Label of this plot, as shown in the chart's legend.

    Examples
    --------
    Create an area plot showing the minimum and maximum precipitation observed in each month.

    >>> import pyvista
    >>> import numpy as np
    >>> x = np.arange(12)
    >>> p_min = [11, 0, 16, 2, 23, 18, 25, 17, 9, 12, 14, 21]
    >>> p_max = [87, 64, 92, 73, 91, 94, 107, 101, 84, 88, 95, 103]
    >>> chart = pyvista.Chart2D()
    >>> _ = chart.area(x, p_min, p_max)
    >>> chart.x_axis.tick_locations = x
    >>> chart.x_axis.tick_labels = ["Jan", "Feb", "Mar", "Apr", "May",
    ...                             "Jun", "Jul", "Aug", "Sep", "Oct",
    ...                             "Nov", "Dec"]
    >>> chart.x_axis.label = "Month"
    >>> chart.y_axis.label = "Precipitation [mm]"
    >>> chart.show()

    """

    _DOC_SUBS = {
        "plot_name": "area plot",
        "chart_init": "pyvista.Chart2D()",
        "plot_init": "chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])",
    }

    def __init__(self, chart, x, y1, y2=None, color="b", label=""):
        """Initialize a new 2D area plot instance."""
        super().__init__(chart)
        self._table = pyvista.Table(
            {
                "x": np.empty(0, np.float32),
                "y1": np.empty(0, np.float32),
                "y2": np.empty(0, np.float32),
            }
        )
        self.SetInputData(self._table)
        self.SetInputArray(0, "x")
        self.SetInputArray(1, "y1")
        self.SetInputArray(2, "y2")
        self.update(x, y1, y2)
        self.color = color
        self.label = label

    @property
    def x(self):
        """Retrieve the X coordinates of the points outlining the drawn area.

        Examples
        --------
        Create an area plot and display the x coordinates.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [2, 1, 3], [1, 0, 1])
        >>> plot.x
        pyvista_ndarray([0, 1, 2])
        >>> chart.show()

        """
        return self._table["x"]

    @property
    def y1(self):
        """Retrieve the Y coordinates of the points on the first outline of the drawn area.

        Examples
        --------
        Create an area plot and display the y1 coordinates.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [2, 1, 3], [1, 0, 1])
        >>> plot.y1
        pyvista_ndarray([2, 1, 3])
        >>> chart.show()

        """
        return self._table["y1"]

    @property
    def y2(self):
        """Retrieve the Y coordinates of the points on the second outline of the drawn area.

        Examples
        --------
        Create an area plot and display the y2 coordinates.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [2, 1, 3], [1, 0, 1])
        >>> plot.y2
        pyvista_ndarray([1, 0, 1])
        >>> chart.show()

        """
        return self._table["y2"]

    def update(self, x, y1, y2=None):
        """Update this plot's points, outlining the area to draw.

        Parameters
        ----------
        x : array_like
            The new x coordinates of the points outlining the area.

        y1 : array_like
            The new y coordinates of the points on the first outline of the area.

        y2 : array_like, optional
            The new y coordinates of the points on the second outline of the
            area. Default ``numpy.zeros_like(x)``.

        Examples
        --------
        Create an area plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [2, 1, 3])
        >>> chart.show()

        Update the points on the second outline of the area.

        >>> plot.update([0, 1, 2], [2, 1, 3], [1, 0, 1])
        >>> chart.show()

        """
        if len(x) > 0:
            if y2 is None:
                y2 = np.zeros_like(x)
            self._table.update(
                {
                    "x": np.array(x, copy=False),
                    "y1": np.array(y1, copy=False),
                    "y2": np.array(y2, copy=False),
                }
            )
            self.visible = True
        else:
            self.visible = False


class BarPlot(_vtk.vtkPlotBar, _MultiCompPlot):
    """Class representing a 2D bar plot.

    Users should typically not directly create new plot instances, but use the dedicated 2D chart's plotting methods.

    Parameters
    ----------
    chart : Chart2D
        The chart containing this plot.

    x : array_like
        Positions (along the x-axis for a vertical orientation, along the y-axis for
        a horizontal orientation) of the bars to draw.

    y : array_like
        Size of the bars to draw. Multiple bars can be stacked by passing a sequence of sequences.

    color : ColorLike, default: "b"
        Color of the bars drawn in this plot. Any color parsable by :class:`pyvista.Color` is allowed.

    orientation : str, default: "V"
        Orientation of the bars drawn in this plot. Either ``"H"`` for an horizontal orientation or ``"V"`` for a
        vertical orientation.

    label : str, default: ""
        Label of this plot, as shown in the chart's legend.

    Examples
    --------
    Create a stacked bar chart showing the average time spent on activities
    throughout the week.

    >>> import pyvista
    >>> import numpy as np
    >>> x = np.arange(1, 8)
    >>> y_s = [7, 8, 7.5, 8, 7.5, 9, 10]
    >>> y_h = [2, 3, 2, 2.5, 1.5, 4, 6.5]
    >>> y_w = [8, 8, 7, 8, 7, 0, 0]
    >>> y_r = [5, 2.5, 4.5, 3.5, 6, 9, 6.5]
    >>> y_t = [2, 2.5, 3, 2, 2, 2, 1]
    >>> labels = ["Sleep", "Household", "Work", "Relax", "Transport"]
    >>> chart = pyvista.Chart2D()
    >>> _ = chart.bar(x, [y_s, y_h, y_w, y_r, y_t], label=labels)
    >>> chart.x_axis.tick_locations = x
    >>> chart.x_axis.tick_labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
    >>> chart.x_label = "Day of week"
    >>> chart.y_label = "Average time spent"
    >>> chart.grid = False  # Disable the grid lines
    >>> chart.show()

    """

    ORIENTATIONS = {"H": _vtk.vtkPlotBar.HORIZONTAL, "V": _vtk.vtkPlotBar.VERTICAL}
    _DOC_SUBS = {
        "plot_name": "bar plot",
        "chart_init": "pyvista.Chart2D()",
        "plot_init": "chart.bar([1, 2, 3], [2, 1, 3])",
        "multichart_init": "pyvista.Chart2D()",
        "multiplot_init": "chart.bar([1, 2, 3], [[2, 1, 3], [1, 0, 2], [0, 3, 1], [3, 2, 0]])",
    }

    def __init__(self, chart, x, y, color=None, orientation="V", label=None):
        """Initialize a new 2D bar plot instance."""
        super().__init__(chart)
        if not isinstance(y[0], (Sequence, np.ndarray)):
            y = (y,)
        y_data = {f"y{i}": np.empty(0, np.float32) for i in range(len(y))}
        self._table = pyvista.Table({"x": np.empty(0, np.float32), **y_data})
        self.SetInputData(self._table, "x", "y0")
        for i in range(1, len(y)):
            self.SetInputArray(i + 1, f"y{i}")
        self.update(x, y)

        if len(y) > 1:
            self.SetColorSeries(self._color_series)
            self.colors = color  # None will use default scheme
            self.labels = label
        else:
            # Use blue bars by default in single component mode
            self.color = "b" if color is None else color
            self.label = label
        self.orientation = orientation

    @property
    def x(self):
        """Retrieve the positions of the drawn bars.

        Examples
        --------
        Create a bar plot and display the positions.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.bar([1, 2, 3], [[2, 1, 3], [1, 2, 0]])
        >>> plot.x
        pyvista_ndarray([1, 2, 3])
        >>> chart.show()

        """
        return self._table["x"]

    @property
    def y(self):
        """Retrieve the sizes of the drawn bars.

        Examples
        --------
        Create a bar plot and display the sizes.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.bar([1, 2, 3], [[2, 1, 3], [1, 2, 0]])
        >>> plot.y
        (pyvista_ndarray([2, 1, 3]), pyvista_ndarray([1, 2, 0]))
        >>> chart.show()

        """
        return tuple(self._table[f"y{i}"] for i in range(self._table.n_arrays - 1))

    def update(self, x, y):
        """Update the positions and/or size of the bars in this plot.

        Parameters
        ----------
        x : array_like
            The new positions of the bars to draw.

        y : array_like
            The new sizes of the bars to draw.

        Examples
        --------
        Create a bar plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.bar([1, 2, 3], [2, 1, 3])
        >>> chart.show()

        Update the bar sizes.

        >>> plot.update([1, 2, 3], [3, 1, 2])
        >>> chart.show()

        """
        if len(x) > 0:
            if not isinstance(y[0], (Sequence, np.ndarray)):
                y = (y,)
            y_data = {f"y{i}": np.array(y[i], copy=False) for i in range(len(y))}
            self._table.update({"x": np.array(x, copy=False), **y_data})
            self.visible = True
        else:
            self.visible = False

    @property
    def orientation(self):
        """Return or set the orientation of the bars in this plot.

        Examples
        --------
        Create a bar plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.bar([1, 2, 3], [[2, 1, 3], [1, 3, 2]])
        >>> chart.show()

        Change the orientation to horizontal.

        >>> plot.orientation = "H"
        >>> chart.show()

        """
        return self._orientation

    @orientation.setter
    def orientation(self, val):
        try:
            self.SetOrientation(self.ORIENTATIONS[val])
            self._orientation = val
        except KeyError:
            formatted_orientations = "\", \"".join(self.ORIENTATIONS.keys())
            raise ValueError(
                f"Invalid orientation. Allowed orientations: \"{formatted_orientations}\""
            )


class StackPlot(_vtk.vtkPlotStacked, _MultiCompPlot):
    """Class representing a 2D stack plot.

    Users should typically not directly create new plot instances, but use the dedicated 2D chart's plotting methods.

    Parameters
    ----------
    chart : Chart2D
        The chart containing this plot.

    x : array_like
        X coordinates of the points outlining the stacks (areas) to draw.

    ys : sequence[array_like]
        Size of the stacks (areas) to draw at the corresponding X
        coordinates. Each sequence defines the sizes of one stack
        (area), which are stacked on top of each other.

    colors : sequence[ColorLike], optional
        Color of the stacks (areas) drawn in this plot. Any color
        parsable by :class:`pyvista.Color` is allowed.

    labels : sequence[str], default: []
        Label for each stack (area) drawn in this plot, as shown in
        the chart's legend.

    Examples
    --------
    Create a stack plot showing the amount of vehicles sold per type.

    >>> import pyvista
    >>> import numpy as np
    >>> year = [f"{y}" for y in np.arange(2011, 2021)]
    >>> x = np.arange(len(year))
    >>> n_e = [1739, 4925, 9515, 21727, 31452, 29926, 40648,
    ...        57761, 76370, 93702]
    >>> n_h = [5563, 7642, 11937, 13905, 22807, 46700, 60875,
    ...        53689, 46650, 50321]
    >>> n_f = [166556, 157249, 151552, 138183, 129669,
    ...        113985, 92965, 73683, 57097, 29499]
    >>> chart = pyvista.Chart2D()
    >>> plot = chart.stack(x, [n_e, n_h, n_f])
    >>> plot.labels = ["Electric", "Hybrid", "Fossil"]
    >>> chart.x_axis.label = "Year"
    >>> chart.x_axis.tick_locations = x
    >>> chart.x_axis.tick_labels = year
    >>> chart.y_axis.label = "New car sales"
    >>> chart.show()

    """

    _DOC_SUBS = {
        "plot_name": "stack plot",
        "chart_init": "pyvista.Chart2D()",
        "plot_init": "chart.stack([0, 1, 2], [2, 1, 3])",
        "multichart_init": "pyvista.Chart2D()",
        "multiplot_init": "chart.stack([0, 1, 2], [[2, 1, 3], [1, 0, 2], [0, 3, 1], [3, 2, 0]])",
    }

    def __init__(self, chart, x, ys, colors=None, labels=None):
        """Initialize a new 2D stack plot instance."""
        super().__init__(chart)
        if not isinstance(ys[0], (Sequence, np.ndarray)):
            ys = (ys,)
        y_data = {f"y{i}": np.empty(0, np.float32) for i in range(len(ys))}
        self._table = pyvista.Table({"x": np.empty(0, np.float32), **y_data})
        self.SetInputData(self._table, "x", "y0")
        for i in range(1, len(ys)):
            self.SetInputArray(i + 1, f"y{i}")
        self.update(x, ys)

        if len(ys) > 1:
            self.SetColorSeries(self._color_series)
            self.colors = colors  # None will use default scheme
            self.labels = labels
        else:
            self.color = "b" if colors is None else colors
            self.label = labels
        self.pen.style = None  # Hide lines by default

    @property
    def x(self):
        """Retrieve the X coordinates of the drawn stacks.

        Examples
        --------
        Create a stack plot and display the x coordinates.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.stack([0, 1, 2], [[2, 1, 3], [1, 2, 0]])
        >>> plot.x
        pyvista_ndarray([0, 1, 2])
        >>> chart.show()

        """
        return self._table["x"]

    @property
    def ys(self):
        """Retrieve the sizes of the drawn stacks.

        Examples
        --------
        Create a stack plot and display the sizes.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.stack([0, 1, 2], [[2, 1, 3], [1, 2, 0]])
        >>> plot.ys
        (pyvista_ndarray([2, 1, 3]), pyvista_ndarray([1, 2, 0]))
        >>> chart.show()

        """
        return tuple(self._table[f"y{i}"] for i in range(self._table.n_arrays - 1))

    def update(self, x, ys):
        """Update the locations and/or size of the stacks (areas) in this plot.

        Parameters
        ----------
        x : array_like
            The new x coordinates of the stacks (areas) to draw.

        ys : sequence[array_like]
            The new sizes of the stacks (areas) to draw.

        Examples
        --------
        Create a stack plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.stack([0, 1, 2], [[2, 1, 3],[1, 2, 1]])
        >>> chart.show()

        Update the stack sizes.

        >>> plot.update([0, 1, 2], [[3, 1, 2], [0, 3, 1]])
        >>> chart.show()

        """
        if len(x) > 0:
            if not isinstance(ys[0], (Sequence, np.ndarray)):
                ys = (ys,)
            y_data = {f"y{i}": np.array(ys[i], copy=False) for i in range(len(ys))}
            self._table.update({"x": np.array(x, copy=False), **y_data})
            self.visible = True
        else:
            self.visible = False


class Chart2D(_vtk.vtkChartXY, _Chart):
    """2D chart class similar to a ``matplotlib`` figure.

    Parameters
    ----------
    size : sequence[float], default: (1, 1)
        Size of the chart in normalized coordinates. A size of ``(0,
        0)`` is invisible, a size of ``(1, 1)`` occupies the whole
        renderer's width and height.

    loc : sequence[float], default: (0, 0)
        Location of the chart (its bottom left corner) in normalized
        coordinates. A location of ``(0, 0)`` corresponds to the
        renderer's bottom left corner, a location of ``(1, 1)``
        corresponds to the renderer's top right corner.

    x_label : str, default: "x"
        Label along the x-axis.

    y_label : str, default: "y"
        Label along the y-axis.

    grid : bool, default: True
        Show the background grid in the plot.

    Examples
    --------
    Plot a simple sine wave as a scatter and line plot.

    >>> import pyvista
    >>> import numpy as np
    >>> x = np.linspace(0, 2*np.pi, 20)
    >>> y = np.sin(x)
    >>> chart = pyvista.Chart2D()
    >>> _ = chart.scatter(x, y)
    >>> _ = chart.line(x, y, 'r')
    >>> chart.show()

    Combine multiple types of plots in the same chart.

    >>> rng = np.random.default_rng(1)
    >>> x = np.arange(1, 8)
    >>> y = rng.integers(5, 15, 7)
    >>> e = np.abs(rng.normal(scale=2, size=7))
    >>> z = rng.integers(0, 5, 7)
    >>> chart = pyvista.Chart2D()
    >>> _ = chart.area(x, y-e, y+e, color=(0.12, 0.46, 0.71, 0.2))
    >>> _ = chart.line(x, y, color="tab:blue", style="--", label="Scores")
    >>> _ = chart.scatter(x, y, color="tab:blue", style="d")
    >>> _ = chart.bar(x, z, color="tab:orange", label="Violations")
    >>> chart.x_axis.tick_locations = x
    >>> chart.x_axis.tick_labels = ["Mon", "Tue", "Wed", "Thu", "Fri",
    ...                             "Sat", "Sun"]
    >>> chart.x_label = "Day of week"
    >>> chart.show()

    """

    PLOT_TYPES = {
        "scatter": ScatterPlot2D,
        "line": LinePlot2D,
        "area": AreaPlot,
        "bar": BarPlot,
        "stack": StackPlot,
    }
    _PLOT_CLASSES = {plot_class: plot_type for (plot_type, plot_class) in PLOT_TYPES.items()}
    _DOC_SUBS = {
        "chart_name": "2D chart",
        "chart_args": "",
        "chart_init": """
        >>> plot = chart.line([0, 1, 2], [2, 1, 3])""",
        "chart_set_labels": 'plot.label = "My awesome plot"',
    }

    def __init__(self, size=(1, 1), loc=(0, 0), x_label="x", y_label="y", grid=True):
        """Initialize the chart."""
        super().__init__(size, loc)
        self._plots = {plot_type: [] for plot_type in self.PLOT_TYPES.keys()}
        self.SetAutoSize(False)  # We manually set the appropriate size
        # Overwrite custom X and Y axis using a wrapper object, as using the
        # SetAxis method causes a crash at the end of the script's execution (nonzero exit code).
        self._x_axis = Axis(_wrap=self.GetAxis(_vtk.vtkAxis.BOTTOM))
        self._y_axis = Axis(_wrap=self.GetAxis(_vtk.vtkAxis.LEFT))
        # Note: registering the axis prevents the nonzero exit code at the end, however
        # this results in memory leaks in the plotting tests.
        # self.SetAxis(_vtk.vtkAxis.BOTTOM, self._x_axis)
        # self.SetAxis(_vtk.vtkAxis.LEFT, self._y_axis)
        # self.Register(self._x_axis)
        # self.Register(self._y_axis)
        self.x_label = x_label
        self.y_label = y_label
        self.grid = grid
        self.legend_visible = True

    def _render_event(self, *args, plotter_render=False, **kwargs):
        if plotter_render:
            # TODO: should probably be called internally by VTK when plot data or axis behavior/logscale is changed?
            self.RecalculateBounds()
        super()._render_event(*args, plotter_render=plotter_render, **kwargs)

    def _add_plot(self, plot_type, *args, **kwargs):
        """Add a plot of the given type to this chart."""
        plot = self.PLOT_TYPES[plot_type](self, *args, **kwargs)
        self.AddPlot(plot)
        self._plots[plot_type].append(plot)
        return plot

    @classmethod
    def _parse_format(cls, fmt):
        """Parse a format string and separate it into a marker style, line style and color.

        Parameters
        ----------
        fmt : str
            Format string to parse. A format string consists of any
            combination of a valid marker style, a valid line style
            and parsable color. The specific order does not
            matter. See :attr:`pyvista.ScatterPlot2D.MARKER_STYLES`
            for a list of valid marker styles,
            :attr:`pyvista.Pen.LINE_STYLES` for a list of valid line
            styles and :class:`pyvista.Color` for an overview of
            parsable colors.

        Returns
        -------
        marker_style : str
            Extracted marker style (empty string if no marker style
            was present in the format string).

        line_style : str
            Extracted line style (empty string if no line style was
            present in the format string).

        color : str
            Extracted color string (defaults to ``"b"`` if no color
            was present in the format string).

        Examples
        --------
        >>> import pyvista
        >>> m, l, c = pyvista.Chart2D._parse_format("x--b")

        """
        marker_style = ""
        line_style = ""
        color = None
        # Note: All colors, marker styles and line styles are sorted in decreasing order of length to be able to find
        # the largest match first (e.g. find 'darkred' and '--' first instead of 'red' and '-')
        colors = sorted(
            itertools.chain(hexcolors.keys(), color_synonyms.keys()),
            key=len,
            reverse=True,
        )
        marker_styles = sorted(ScatterPlot2D.MARKER_STYLES.keys(), key=len, reverse=True)
        line_styles = sorted(Pen.LINE_STYLES.keys(), key=len, reverse=True)
        hex_pattern = "(#|0x)[A-Fa-f0-9]{6}([A-Fa-f0-9]{2})?"  # Match RGB(A) hex string
        # Extract color from format string
        match = re.search(hex_pattern, fmt)  # Start with matching hex strings
        if match is not None:
            color = match.group()
        else:  # Proceed with matching color strings
            for c in colors:
                if c in fmt:
                    color = c
                    break
        if color is not None:
            fmt = fmt.replace(color, "", 1)  # Remove found color from format string
        else:
            color = "b"
        # Extract marker style from format string
        for style in marker_styles[:-1]:  # Last style is empty string
            if style in fmt:
                marker_style = style
                fmt = fmt.replace(
                    marker_style, "", 1
                )  # Remove found marker_style from format string
                break
        # Extract line style from format string
        for style in line_styles[:-1]:  # Last style is empty string
            if style in fmt:
                line_style = style
                fmt = fmt.replace(line_style, "", 1)  # Remove found line_style from format string
                break
        return marker_style, line_style, color

    def plot(self, x, y=None, fmt='-'):
        """Matplotlib like plot method.

        Parameters
        ----------
        x : array_like
            Values to plot on the X-axis. In case ``y`` is ``None``,
            these are the values to plot on the Y-axis instead.

        y : array_like, optional
            Values to plot on the Y-axis.

        fmt : str, default: "-"
            A format string, e.g. ``'ro'`` for red circles. See the Notes
            section for a full description of the format strings.

        Returns
        -------
        scatter_plot : plotting.charts.ScatterPlot2D, optional
            The created scatter plot when a valid marker style
            was present in the format string, ``None`` otherwise.

        line_plot : plotting.charts.LinePlot2D, optional
            The created line plot when a valid line style was
            present in the format string, ``None`` otherwise.

        Notes
        -----
        This plot method shares many of the same plotting features as
        the `matplotlib.pyplot.plot
        <https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html>`_.
        Please reference the documentation there for a full
        description of the allowable format strings.

        Examples
        --------
        Generate a line plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _, line_plot = chart.plot(range(10), range(10))
        >>> chart.show()

        Generate a line and scatter plot.

        >>> chart = pyvista.Chart2D()
        >>> scatter_plot, line_plot = chart.plot(range(10), fmt='o-')
        >>> chart.show()

        """
        if y is None:
            y = x
            x = np.arange(len(y))
        elif isinstance(y, str):
            fmt = y
            y = x
            x = np.arange(len(y))
        marker_style, line_style, color = self._parse_format(fmt)
        scatter_plot, line_plot = None, None
        if marker_style != "":
            scatter_plot = self.scatter(x, y, color, style=marker_style)
        if line_style != "":
            line_plot = self.line(x, y, color, style=line_style)
        return scatter_plot, line_plot

    def scatter(self, x, y, color="b", size=10, style="o", label=""):
        """Add a scatter plot to this chart.

        Parameters
        ----------
        x : array_like
            X coordinates of the points to draw.

        y : array_like
            Y coordinates of the points to draw.

        color : ColorLike, default: "b"
            Color of the points drawn in this plot. Any color parsable
            by :class:`pyvista.Color` is allowed.

        size : float, default: 10
            Size of the point markers drawn in this plot.

        style : str, default: "o"
            Style of the point markers drawn in this plot. See
            :ref:`ScatterPlot2D.MARKER_STYLES <scatter_marker_styles>`
            for a list of allowed marker styles.

        label : str, default: ""
            Label of this plot, as shown in the chart's legend.

        Returns
        -------
        plotting.charts.ScatterPlot2D
            The created scatter plot.

        Examples
        --------
        Generate a scatter plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.scatter([0, 1, 2], [2, 1, 3])
        >>> chart.show()

        """
        return self._add_plot("scatter", x, y, color=color, size=size, style=style, label=label)

    def line(self, x, y, color="b", width=1.0, style="-", label=""):
        """Add a line plot to this chart.

        Parameters
        ----------
        x : array_like
            X coordinates of the points through which a line should be drawn.

        y : array_like
            Y coordinates of the points through which a line should be drawn.

        color : ColorLike, default: "b"
            Color of the line drawn in this plot. Any color parsable
            by :class:`pyvista.Color` is allowed.

        width : float, default: 1
            Width of the line drawn in this plot.

        style : str, default: "-"
            Style of the line drawn in this plot. See
            :ref:`Pen.LINE_STYLES <pen_line_styles>` for a list of
            allowed line styles.

        label : str, default: ""
            Label of this plot, as shown in the chart's legend.

        Returns
        -------
        plotting.charts.LinePlot2D
            The created line plot.

        Examples
        --------
        Generate a line plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.show()

        """
        return self._add_plot("line", x, y, color=color, width=width, style=style, label=label)

    def area(self, x, y1, y2=None, color="b", label=""):
        """Add an area plot to this chart.

        Parameters
        ----------
        x : array_like
            X coordinates of the points outlining the area to draw.

        y1 : array_like
            Y coordinates of the points on the first outline of the area to draw.

        y2 : array_like, optional
            Y coordinates of the points on the second outline of the
            area to draw. Defaults to ``np.zeros_like(x)``.

        color : ColorLike, default: "b"
            Color of the area drawn in this plot. Any color parsable
            by :class:`pyvista.Color` is allowed.

        label : str, default: ""
            Label of this plot, as shown in the chart's legend.

        Returns
        -------
        plotting.charts.AreaPlot
            The created area plot.

        Examples
        --------
        Generate an area plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.area([0, 1, 2], [2, 1, 3])
        >>> chart.show()

        """
        return self._add_plot("area", x, y1, y2, color=color, label=label)

    def bar(self, x, y, color=None, orientation="V", label=None):
        """Add a bar plot to this chart.

        Parameters
        ----------
        x : array_like
            Positions (along the x-axis for a vertical orientation,
            along the y-axis for a horizontal orientation) of the bars
            to draw.

        y : array_like
            Size of the bars to draw. Multiple bars can be stacked by
            passing a sequence of sequences.

        color : ColorLike, default: "b"
            Color of the bars drawn in this plot. Any color parsable
            by :class:`pyvista.Color` is allowed.

        orientation : str, default: "V"
            Orientation of the bars drawn in this plot. Either ``"H"``
            for an horizontal orientation or ``"V"`` for a vertical
            orientation.

        label : str, default: ""
            Label of this plot, as shown in the chart's legend.

        Returns
        -------
        plotting.charts.BarPlot
            The created bar plot.

        Examples
        --------
        Generate a bar plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.bar([0, 1, 2], [2, 1, 3])
        >>> chart.show()

        """
        return self._add_plot("bar", x, y, color=color, orientation=orientation, label=label)

    def stack(self, x, ys, colors=None, labels=None):
        """Add a stack plot to this chart.

        Parameters
        ----------
        x : array_like
            X coordinates of the points outlining the stacks (areas) to draw.

        ys : sequence[array_like]
            Size of the stacks (areas) to draw at the corresponding X
            coordinates. Each sequence defines the sizes of one stack
            (area), which are stacked on top of each other.

        colors : sequence[ColorLike], optional
            Color of the stacks (areas) drawn in this plot. Any color
            parsable by :class:`pyvista.Color` is allowed.

        labels : sequence[str], default: []
            Label for each stack (area) drawn in this plot, as shown
            in the chart's legend.

        Returns
        -------
        plotting.charts.StackPlot
            The created stack plot.

        Examples
        --------
        Generate a stack plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> plot = chart.stack([0, 1, 2], [[2, 1, 3],[1, 2, 1]])
        >>> chart.show()

        """
        return self._add_plot("stack", x, ys, colors=colors, labels=labels)

    def plots(self, plot_type=None):
        """Return all plots of the specified type in this chart.

        Parameters
        ----------
        plot_type : str, optional
            The type of plots to return. Allowed types are
            ``"scatter"``, ``"line"``, ``"area"``, ``"bar"``
            and ``"stack"``.
            If no type is provided (``None``), all plots are returned,
            regardless of their type.

        Yields
        ------
        plot : plotting.charts.ScatterPlot2D | plotting.charts.LinePlot2D | plotting.charts.AreaPlot | plotting.charts.BarPlot | plotting.charts.StackPlot
            One of the plots (of the specified type) in this chart.

        Examples
        --------
        Create a 2D chart with a line and scatter plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> scatter_plot, line_plot = chart.plot([0, 1, 2], [2, 1, 3], "o-")
        >>> chart.show()

        Retrieve all plots in the chart.

        >>> plots = [*chart.plots()]
        >>> scatter_plot in plots and line_plot in plots
        True

        Retrieve all line plots in the chart.

        >>> line_plots = [*chart.plots("line")]
        >>> line_plot == line_plots[0]
        True

        """
        plot_types = self.PLOT_TYPES.keys() if plot_type is None else [plot_type]
        for plot_type in plot_types:
            yield from self._plots[plot_type]

    def remove_plot(self, plot):
        """Remove the given plot from this chart.

        Parameters
        ----------
        plot : plotting.charts.ScatterPlot2D | plotting.charts.LinePlot2D | plotting.charts.AreaPlot | plotting.charts.BarPlot | plotting.charts.StackPlot
            The plot to remove.

        Examples
        --------
        Create a 2D chart with a line and scatter plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> scatter_plot, line_plot = chart.plot([0, 1, 2], [2, 1, 3], "o-")
        >>> chart.show()

        Remove the scatter plot from the chart.

        >>> chart.remove_plot(scatter_plot)
        >>> chart.show()

        """
        try:
            plot_type = self._PLOT_CLASSES[type(plot)]
            self._plots[plot_type].remove(plot)
            self.RemovePlotInstance(plot)
        except (KeyError, ValueError):
            raise ValueError("The given plot is not part of this chart.")

    def clear(self, plot_type=None):
        """Remove all plots of the specified type from this chart.

        Parameters
        ----------
        plot_type : str, optional
            The type of the plots to remove. Allowed types are
            ``"scatter"``, ``"line"``, ``"area"``, ``"bar"``
            and ``"stack"``.

            If no type is provided (``None``), all plots are removed,
            regardless of their type.

        Examples
        --------
        Create a 2D chart with multiple line and scatter plot.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.plot([0, 1, 2], [2, 1, 3], "o-b")
        >>> _ = chart.plot([-2, -1, 0], [3, 1, 2], "d-r")
        >>> chart.show()

        Remove all scatter plots from the chart.

        >>> chart.clear("scatter")
        >>> chart.show()

        """
        plot_types = self.PLOT_TYPES.keys() if plot_type is None else [plot_type]
        for plot_type in plot_types:
            # Make a copy, as this list will be modified by remove_plot
            plots = [*self._plots[plot_type]]
            for plot in plots:
                self.remove_plot(plot)

    @property
    def x_axis(self):
        """Return this chart's horizontal (x) :class:`Axis <plotting.charts.Axis>`.

        Examples
        --------
        Create a 2D plot and hide the x axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_axis.toggle()
        >>> chart.show()

        """
        return self._x_axis

    @property
    def y_axis(self):
        """Return this chart's vertical (y) :class:`Axis <plotting.charts.Axis>`.

        Examples
        --------
        Create a 2D plot and hide the y axis.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.y_axis.toggle()
        >>> chart.show()

        """
        return self._y_axis

    @property
    def x_label(self):
        """Return or set the label of this chart's x axis.

        Examples
        --------
        Create a 2D plot and set custom axis labels.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_label = "Horizontal axis"
        >>> chart.y_label = "Vertical axis"
        >>> chart.show()

        """
        return self.x_axis.label

    @x_label.setter
    def x_label(self, val):
        self.x_axis.label = val

    @property
    def y_label(self):
        """Return or set the label of this chart's y axis.

        Examples
        --------
        Create a 2D plot and set custom axis labels.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_label = "Horizontal axis"
        >>> chart.y_label = "Vertical axis"
        >>> chart.show()

        """
        return self.y_axis.label

    @y_label.setter
    def y_label(self, val):
        self.y_axis.label = val

    @property
    def x_range(self):
        """Return or set the range of this chart's x axis.

        Examples
        --------
        Create a 2D plot and set custom axis ranges.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_range = [-2, 2]
        >>> chart.y_range = [0, 5]
        >>> chart.show()

        """
        return self.x_axis.range

    @x_range.setter
    def x_range(self, val):
        self.x_axis.range = val

    @property
    def y_range(self):
        """Return or set the range of this chart's y axis.

        Examples
        --------
        Create a 2D plot and set custom axis ranges.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.x_range = [-2, 2]
        >>> chart.y_range = [0, 5]
        >>> chart.show()

        """
        return self.y_axis.range

    @y_range.setter
    def y_range(self, val):
        self.y_axis.range = val

    @property
    def grid(self):
        """Enable or disable the chart grid.

        Examples
        --------
        Create a 2D chart with the grid disabled.

        >>> import pyvista
        >>> import numpy as np
        >>> x = np.linspace(0, 2*np.pi, 20)
        >>> y = np.sin(x)
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line(x, y, 'r')
        >>> chart.grid = False
        >>> chart.show()

        Enable the grid

        >>> chart.grid = True
        >>> chart.show()

        """
        return self.x_axis.grid and self.y_axis.grid

    @grid.setter
    def grid(self, val):
        self.x_axis.grid = val
        self.y_axis.grid = val

    def hide_axes(self):
        """Hide the x- and y-axis of this chart.

        This includes all labels, ticks and the grid.

        Examples
        --------
        Create a 2D plot and hide the axes.

        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.line([0, 1, 2], [2, 1, 3])
        >>> chart.hide_axes()
        >>> chart.show()

        """
        for axis in (self.x_axis, self.y_axis):
            axis.visible = False
            axis.label_visible = False
            axis.ticks_visible = False
            axis.tick_labels_visible = False
            axis.grid = False


class BoxPlot(_vtk.vtkPlotBox, _MultiCompPlot):
    """Class representing a box plot.

    Users should typically not directly create new plot instances, but
    use the dedicated ``ChartBox`` class.

    Parameters
    ----------
    chart : ChartBox
        The chart containing this plot.

    data : sequence[array_like]
        Dataset(s) from which the relevant statistics will be
        calculated used to draw the box plot.

    colors : sequence[ColorLike], optional
        Color of the boxes drawn in this plot. Any color parsable by
        :class:`pyvista.Color` is allowed. If omitted (``None``), the
        default color scheme is used.

    labels : sequence[str], default: []
        Label for each box drawn in this plot, as shown in the chart's
        legend.

    Examples
    --------
    Create boxplots for datasets sampled from shifted normal distributions.

    >>> import pyvista
    >>> import numpy as np
    >>> rng = np.random.default_rng(1)  # Seeded random number generator used for data generation
    >>> normal_data = [rng.normal(i, size=50) for i in range(5)]
    >>> chart = pyvista.ChartBox(normal_data, labels=[f"x ~ N({i},1)" for i in range(5)])
    >>> chart.show()

    """

    _DOC_SUBS = {
        "plot_name": "box plot",
        "chart_init": "pyvista.ChartBox([[0, 1, 1, 2, 3, 3, 4]])",
        "plot_init": "chart.plot",
        "multichart_init": "pyvista.ChartBox([[0, 1, 1, 2, 3, 4, 5], [0, 1, 2, 2, 3, 4, 5], [0, 1, 2, 3, 3, 4, 5], [0, 1, 2, 3, 4, 4, 5]])",
        "multiplot_init": "chart.plot",
    }

    def __init__(self, chart, data, colors=None, labels=None):
        """Initialize a new box plot instance."""
        super().__init__(chart)
        self._table = pyvista.Table(
            {f"data_{i}": np.array(d, copy=False) for i, d in enumerate(data)}
        )
        self._quartiles = _vtk.vtkComputeQuartiles()
        self._quartiles.SetInputData(self._table)
        self.SetInputData(self._quartiles.GetOutput())
        self.update(data)
        self.SetLookupTable(self._lookup_table)
        self.colors = colors
        self.labels = labels

    @property
    def data(self):
        """Retrieve the datasets of which the boxplots are drawn.

        Examples
        --------
        Create a box plot and display the datasets.

        >>> import pyvista
        >>> chart = pyvista.ChartBox([[0, 1, 1, 2, 3, 3, 4]])
        >>> chart.plot.data
        (pyvista_ndarray([0, 1, 1, 2, 3, 3, 4]),)
        >>> chart.show()

        """
        return tuple(self._table[f"data_{i}"] for i in range(self._table.n_arrays))

    @property
    def stats(self):
        """Retrieve the statistics (quartiles and extremum values) of the datasets of which the boxplots are drawn.

        Examples
        --------
        Create a box plot and display the statistics.

        >>> import pyvista
        >>> chart = pyvista.ChartBox([[0, 1, 1, 2, 3, 3, 4]])
        >>> chart.plot.stats
        (pyvista_ndarray([0., 1., 2., 3., 4.]),)
        >>> chart.show()

        """
        stats_table = pyvista.Table(self._quartiles.GetOutput())
        return tuple(stats_table[f"data_{i}"] for i in range(stats_table.n_arrays))

    def update(self, data):
        """Update the plot's underlying dataset(s).

        Parameters
        ----------
        data : sequence[array_like]
            The new dataset(s) used in this box plot.

        Examples
        --------
        Create a box plot from a standard Gaussian dataset.

        >>> import pyvista
        >>> import numpy as np
        >>> rng = np.random.default_rng(1)  # Seeded random number generator for data generation
        >>> chart = pyvista.ChartBox([rng.normal(size=100)])
        >>> chart.show()

        Update the box plot (shift the standard Gaussian distribution).

        >>> chart.plot.update([rng.normal(loc=2, size=100)])
        >>> chart.show()

        """
        self._table.update({f"data_{i}": np.array(d, copy=False) for i, d in enumerate(data)})
        self._quartiles.Update()


class ChartBox(_vtk.vtkChartBox, _Chart):
    """Dedicated chart for drawing box plots.

    Parameters
    ----------
    data : sequence[array_like]
        Dataset(s) from which the relevant statistics will be
        calculated used to draw the box plot.

    colors : sequence[ColorLike], optional
        Color used for each drawn boxplot. If omitted (``None``), the
        default color scheme is used.

    labels : sequence[str], default: []
        Label for each drawn boxplot, as shown in the chart's
        legend.

    size : sequence[float], optional
        Size of the chart in normalized coordinates. A size of ``(0,
        0)`` is invisible, a size of ``(1, 1)`` occupies the whole
        renderer's width and height.

    loc : sequence[float], optional
        Location of the chart (its bottom left corner) in normalized
        coordinates. A location of ``(0, 0)`` corresponds to the
        renderer's bottom left corner, a location of ``(1, 1)``
        corresponds to the renderer's top right corner.

    Examples
    --------
    Create boxplots for datasets sampled from shifted normal distributions.

    >>> import pyvista
    >>> import numpy as np
    >>> rng = np.random.default_rng(1)  # Seeded random number generator used for data generation
    >>> normal_data = [rng.normal(i, size=50) for i in range(5)]
    >>> chart = pyvista.ChartBox(normal_data, labels=[f"x ~ N({i},1)" for i in range(5)])
    >>> chart.show()

    """

    _DOC_SUBS = {
        "chart_name": "boxplot chart",
        "chart_args": "[[0, 1, 1, 2, 3, 3, 4]]",
        "chart_init": "",
        "chart_set_labels": 'chart.plot.label = "Data label"',
    }

    def __init__(self, data, colors=None, labels=None, size=None, loc=None):
        """Initialize a new chart containing box plots."""
        if vtk_version_info >= (9, 2, 0):
            self.SetAutoSize(False)  # We manually set the appropriate size
            if size is None:
                size = (1, 1)
            if loc is None:
                loc = (0, 0)
        super().__init__(size, loc)
        self._plot = BoxPlot(self, data, colors, labels)
        self.SetPlot(self._plot)
        self.SetColumnVisibilityAll(True)
        self.legend_visible = True

    def _render_event(self, *args, **kwargs):
        if vtk_version_info < (9, 2, 0):  # pragma: no cover
            # In older VTK versions, ChartBox fills the entire scene, so
            # no resizing is needed (nor possible).
            pass
        else:
            super()._render_event(*args, **kwargs)

    @property
    def _geometry(self):
        if vtk_version_info < (9, 2, 0):  # pragma: no cover
            return (0, 0, *self._renderer.GetSize())
        else:
            return _Chart._geometry.fget(self)

    @_geometry.setter
    def _geometry(self, value):
        if vtk_version_info < (9, 2, 0):  # pragma: no cover
            raise AttributeError(f'Cannot set the geometry of {type(self).__class__}')
        else:
            _Chart._geometry.fset(self, value)

    @property
    def plot(self):
        """Return the :class:`BoxPlot <plotting.charts.BoxPlot>` instance associated with this chart.

        Examples
        --------
        Create a box plot from a standard Gaussian dataset.

        >>> import pyvista
        >>> import numpy as np
        >>> rng = np.random.default_rng(1)  # Seeded random number generator for data generation
        >>> chart = pyvista.ChartBox([rng.normal(size=100)])
        >>> chart.show()

        Update the box plot (shift the standard Gaussian distribution).

        >>> chart.plot.update([rng.normal(loc=2, size=100)])
        >>> chart.show()

        """
        return self._plot

    @property
    def size(self):
        """Return or set the chart size in normalized coordinates.

        A size of ``(1, 1)`` occupies the whole renderer.

        Notes
        -----
        Customisable ChartBox geometry is only supported in VTK v9.2
        or newer. For older VTK versions, the size cannot be modified,
        filling up the entire viewport by default.

        Examples
        --------
        Create a half-sized boxplot chart centered in the middle of the
        renderer.

        >>> import pyvista
        >>> chart = pyvista.ChartBox([[0, 1, 1, 2, 3, 3, 4]])
        >>> chart.size = (0.5, 0.5)
        >>> chart.loc = (0.25, 0.25)
        >>> chart.show()

        """
        if vtk_version_info < (9, 2, 0):  # pragma: no cover
            return (1, 1)
        else:
            return _Chart.size.fget(self)

    @size.setter
    def size(self, val):
        if vtk_version_info < (9, 2, 0):  # pragma: no cover
            raise ValueError(
                "Cannot set ChartBox geometry, it fills up the entire viewport by default. "
                "Upgrade to VTK v9.2 or newer."
            )
        else:
            _Chart.size.fset(self, val)

    @property
    def loc(self):
        """Return or set the chart position in normalized coordinates.

        This denotes the location of the chart's bottom left corner.

        Notes
        -----
        Customisable ChartBox geometry is only supported in VTK v9.2
        or newer. For older VTK versions, the location cannot be modified,
        filling up the entire viewport by default.

        Examples
        --------
        Create a half-sized boxplot chart centered in the middle of the
        renderer.

        >>> import pyvista
        >>> chart = pyvista.ChartBox([[0, 1, 1, 2, 3, 3, 4]])
        >>> chart.size = (0.5, 0.5)
        >>> chart.loc = (0.25, 0.25)
        >>> chart.show()

        """
        if vtk_version_info < (9, 2, 0):  # pragma: no cover
            return (0, 0)
        else:
            return _Chart.loc.fget(self)

    @loc.setter
    def loc(self, val):
        if vtk_version_info < (9, 2, 0):  # pragma: no cover
            raise ValueError(
                "Cannot set ChartBox geometry, it fills up the entire viewport by default. "
                "Upgrade to VTK v9.2 or newer."
            )
        else:
            _Chart.loc.fset(self, val)


class PiePlot(_vtkWrapper, _vtk.vtkPlotPie, _MultiCompPlot):
    """Class representing a pie plot.

    Users should typically not directly create new plot instances, but
    use the dedicated :class:`ChartPie` class.

    Parameters
    ----------
    chart : ChartPie
        The chart containing this plot.

    data : array_like
        Relative size of each pie segment.

    colors : sequence[ColorLike], optional
        Color of the segments drawn in this plot. Any color parsable
        by :class:`pyvista.Color` is allowed. If omitted (``None``),
        the default color scheme is used.

    labels : sequence[str], default: []
        Label for each pie segment drawn in this plot, as shown in the
        chart's legend.

    Other Parameters
    ----------------
    _wrap : vtk.vtkPlotPie, optional
        Wrap an existing VTK PlotPie instance (no wrapping when ``None``).

    Examples
    --------
    Create a pie plot showing the usage of tax money.

    >>> import pyvista
    >>> x = [128.3, 32.9, 31.8, 29.3, 21.2]
    >>> l = ["Social benefits", "Governance", "Economic policy", "Education", "Other"]
    >>> chart = pyvista.ChartPie(x, labels=l)
    >>> chart.show()

    """

    _DOC_SUBS = {
        "plot_name": "pie plot",
        "chart_init": "pyvista.ChartPie([4, 3, 2, 1])",
        "plot_init": "chart.plot",
        "multichart_init": "pyvista.ChartPie([4, 3, 2, 1])",
        "multiplot_init": "chart.plot",
    }

    def __init__(self, chart, data, colors=None, labels=None):
        """Initialize a new pie plot instance."""
        super().__init__(chart)
        self._table = pyvista.Table(data)
        self.SetInputData(self._table)
        self.SetInputArray(0, self._table.keys()[0])
        self.update(data)

        self.labels = labels

        self.SetColorSeries(self._color_series)
        self.colors = colors

    @property
    def data(self):
        """Retrieve the sizes of the drawn segments.

        Examples
        --------
        Create a pie plot and display the sizes.

        >>> import pyvista
        >>> chart = pyvista.ChartPie([1, 2, 3])
        >>> chart.plot.data
        pyvista_ndarray([1, 2, 3])
        >>> chart.show()

        """
        return self._table[0]

    def update(self, data):
        """Update the size of the pie segments.

        Parameters
        ----------
        data : array_like
            The new relative size of each pie segment.

        Examples
        --------
        Create a pie plot with segments of increasing size.

        >>> import pyvista
        >>> chart = pyvista.ChartPie([1, 2, 3, 4, 5])
        >>> chart.show()

        Update the pie plot (segments of equal size).

        >>> chart.plot.update([1, 1, 1, 1, 1])
        >>> chart.show()

        """
        self._table.update(data)


class ChartPie(_vtk.vtkChartPie, _Chart):
    """Dedicated chart for drawing pie plots.

    Parameters
    ----------
    data : array_like
        Relative size of each pie segment.

    colors : sequence[ColorLike], optional
        Color used for each pie segment drawn in this plot. If
        omitted (``None``), the default color scheme is used.

    labels : sequence[str], default: []
        Label for each pie segment drawn in this plot, as shown in the
        chart's legend.

    size : sequence[float], optional
        Size of the chart in normalized coordinates. A size of ``(0,
        0)`` is invisible, a size of ``(1, 1)`` occupies the whole
        renderer's width and height.

    loc : sequence[float], optional
        Location of the chart (its bottom left corner) in normalized
        coordinates. A location of ``(0, 0)`` corresponds to the
        renderer's bottom left corner, a location of ``(1, 1)``
        corresponds to the renderer's top right corner.

    Examples
    --------
    Create a pie plot showing the usage of tax money.

    >>> import pyvista
    >>> x = [128.3, 32.9, 31.8, 29.3, 21.2]
    >>> l = ["Social benefits", "Governance", "Economic policy", "Education", "Other"]
    >>> chart = pyvista.ChartPie(x, labels=l)
    >>> chart.show()

    """

    _DOC_SUBS = {
        "chart_name": "pie chart",
        "chart_args": "[5, 4, 3, 2, 1]",
        "chart_init": "",
        "chart_set_labels": 'chart.plot.labels = ["A", "B", "C", "D", "E"]',
    }

    def __init__(self, data, colors=None, labels=None, size=None, loc=None):
        """Initialize a new chart containing a pie plot."""
        if vtk_version_info >= (9, 2, 0):
            self.SetAutoSize(False)  # We manually set the appropriate size
            if size is None:
                size = (1, 1)
            if loc is None:
                loc = (0, 0)
        super().__init__(size, loc)
        if vtk_version_info < (9, 2, 0):  # pragma: no cover
            # SetPlot method is not available for older VTK versions,
            # so fallback to using a wrapper object.
            self.AddPlot(0)
            self._plot = PiePlot(self, data, colors, labels, _wrap=self.GetPlot(0))
        else:
            self._plot = PiePlot(self, data, colors, labels)
            self.SetPlot(self._plot)
        self.legend_visible = True

    def _render_event(self, *args, **kwargs):
        if vtk_version_info < (9, 2, 0):  # pragma: no cover
            # In older VTK versions, ChartPie fills the entire scene, so
            # no resizing is needed (nor possible).
            pass
        else:
            super()._render_event(*args, **kwargs)

    @property
    def _geometry(self):
        if vtk_version_info < (9, 2, 0):  # pragma: no cover
            return (0, 0, *self._renderer.GetSize())
        else:
            return _Chart._geometry.fget(self)

    @_geometry.setter
    def _geometry(self, value):
        if vtk_version_info < (9, 2, 0):  # pragma: no cover
            raise AttributeError(f'Cannot set the geometry of {type(self).__class__}')
        else:
            _Chart._geometry.fset(self, value)

    @property
    def plot(self):
        """Return the :class:`PiePlot <plotting.charts.PiePlot>` instance associated with this chart.

        Examples
        --------
        Create a pie plot with segments of increasing size.

        >>> import pyvista
        >>> chart = pyvista.ChartPie([1, 2, 3, 4, 5])
        >>> chart.show()

        Update the pie plot (segments of equal size).

        >>> chart.plot.update([1, 1, 1, 1, 1])
        >>> chart.show()

        """
        return self._plot

    @property
    def size(self):
        """Return or set the chart size in normalized coordinates.

        A size of ``(1, 1)`` occupies the whole renderer.

        Notes
        -----
        Customisable ChartPie geometry is only supported in VTK v9.2
        or newer. For older VTK versions, the size cannot be modified,
        filling up the entire viewport by default.

        Examples
        --------
        Create a half-sized pie chart centered in the middle of the
        renderer.

        >>> import pyvista
        >>> chart = pyvista.ChartPie([5, 4, 3, 2, 1])
        >>> chart.size = (0.5, 0.5)
        >>> chart.loc = (0.25, 0.25)
        >>> chart.show()

        """
        if vtk_version_info < (9, 2, 0):  # pragma: no cover
            return (1, 1)
        else:
            return _Chart.size.fget(self)

    @size.setter
    def size(self, val):
        if vtk_version_info < (9, 2, 0):  # pragma: no cover
            raise ValueError(
                "Cannot set ChartPie geometry, it fills up the entire viewport by default. "
                "Upgrade to VTK v9.2 or newer."
            )
        else:
            _Chart.size.fset(self, val)

    @property
    def loc(self):
        """Return or set the chart position in normalized coordinates.

        This denotes the location of the chart's bottom left corner.

        Notes
        -----
        Customisable ChartPie geometry is only supported in VTK v9.2
        or newer. For older VTK versions, the location cannot be modified,
        filling up the entire viewport by default.

        Examples
        --------
        Create a half-sized pie chart centered in the middle of the
        renderer.

        >>> import pyvista
        >>> chart = pyvista.ChartPie([5, 4, 3, 2, 1])
        >>> chart.size = (0.5, 0.5)
        >>> chart.loc = (0.25, 0.25)
        >>> chart.show()

        """
        if vtk_version_info < (9, 2, 0):  # pragma: no cover
            return (0, 0)
        else:
            return _Chart.loc.fget(self)

    @loc.setter
    def loc(self, val):
        if vtk_version_info < (9, 2, 0):  # pragma: no cover
            raise ValueError(
                "Cannot set ChartPie geometry, it fills up the entire viewport by default. "
                "Upgrade to VTK v9.2 or newer."
            )
        else:
            _Chart.loc.fset(self, val)


# region 3D charts
# A basic implementation of 3D line, scatter and volume plots, to be used in a 3D chart was provided in this section
# but removed in commit 8ef8daea5d105e85f256d4e9af584aeea3c85040 of PR #1432. Unfortunately, these charts are much less
# customisable than their 2D counterparts and they do not respect the enforced size/geometry constraints once you start
# interacting with them.
# endregion


class ChartMPL(_vtk.vtkImageItem, _Chart):
    """Create new chart from an existing matplotlib figure.

    Parameters
    ----------
    figure : matplotlib.figure.Figure, optional
        The matplotlib figure to draw. If no figure is
        provided ( ``None`` ), a new figure is created.

    size : sequence[float], default: (1, 1)
        Size of the chart in normalized coordinates. A size of ``(0,
        0)`` is invisible, a size of ``(1, 1)`` occupies the whole
        renderer's width and height.

    loc : sequence[float], default: (0, 0)
        Location of the chart (its bottom left corner) in normalized
        coordinates. A location of ``(0, 0)`` corresponds to the
        renderer's bottom left corner, a location of ``(1, 1)``
        corresponds to the renderer's top right corner.

    redraw_on_render : bool, default: True
        Flag indicating whether the chart should be redrawn when
        the plotter is rendered. For static charts, setting this
        to ``False`` can improve performance.

    Examples
    --------
    Plot streamlines of a vector field with varying colors (based on `this example <https://matplotlib.org/stable/gallery/images_contours_and_fields/plot_streamplot.html>`_).

    .. pyvista-plot::

    >>> import pyvista
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt

    >>> w = 3
    >>> Y, X = np.mgrid[-w:w:100j, -w:w:100j]
    >>> U = -1 - X**2 + Y
    >>> V = 1 + X - Y**2
    >>> speed = np.sqrt(U**2 + V**2)

    >>> f, ax = plt.subplots()
    >>> strm = ax.streamplot(X, Y, U, V, color=U, linewidth=2, cmap='autumn')
    >>> _ = f.colorbar(strm.lines)
    >>> _ = ax.set_title('Streamplot with varying Color')
    >>> plt.tight_layout()

    >>> chart = pyvista.ChartMPL(f)
    >>> chart.show()

    """

    _DOC_SUBS = {
        "chart_name": "matplotlib chart",
        "chart_args": "",
        "chart_init": """
        >>> plots = chart.figure.axes[0].plot([0, 1, 2], [2, 1, 3])""",
        "chart_set_labels": 'plots[0].label = "My awesome plot"',
    }

    def __init__(self, figure=None, size=(1, 1), loc=(0, 0), redraw_on_render=True):
        """Initialize chart."""
        super().__init__(size, loc)
        if figure is None:
            figure, _ = plt.subplots()
        self._fig = figure
        self._canvas = FigureCanvasAgg(
            self._fig
        )  # Switch backends and store reference to figure's canvas
        # Make figure and axes fully transparent, as the background is already dealt with by self._background.
        self._fig.patch.set_alpha(0)
        for ax in self._fig.axes:
            ax.patch.set_alpha(0)
        self._canvas.mpl_connect('draw_event', self._redraw)  # Attach 'draw_event' callback
        self._redraw_on_render = redraw_on_render

        self._redraw()

        # Close the underlying matplotlib figure when creating the sphinx gallery.
        # This prevents the charts from being drawn twice in example scripts:
        # once as a pyvista plot (fetched by the 'pyvista' scraper) and once as a
        # matplotlib figure (fetched by the 'matplotlib' scraper).
        # See #1999 and #2031.
        if pyvista.BUILDING_GALLERY:  # pragma: no cover
            plt.close(self._fig)

    @property
    def figure(self):
        """Retrieve the matplotlib figure associated with this chart.

        Examples
        --------
        Create a matplotlib chart from an existing figure.

        .. pyvista-plot::

        >>> import pyvista
        >>> import matplotlib.pyplot as plt
        >>> f, ax = plt.subplots()
        >>> _ = ax.plot([0, 1, 2], [2, 1, 3])
        >>> chart = pyvista.ChartMPL(f)
        >>> chart.figure is f
        True
        >>> chart.show()
        """
        return self._fig

    @property
    def redraw_on_render(self):
        """Return or set the chart's redraw-on-render behavior.

        Notes
        -----
        When disabled, the chart will only be redrawn when the
        Plotter window is resized or the matplotlib figure is
        manually redrawn using ``fig.canvas.draw()``.
        When enabled, the chart will also be automatically
        redrawn whenever the Plotter is rendered using
        ``plotter.render()``.

        """
        return self._redraw_on_render

    @redraw_on_render.setter
    def redraw_on_render(self, val):
        self._redraw_on_render = bool(val)

    def _resize(self):
        r_w, r_h = self._renderer.GetSize()
        c_w, c_h = (int(s) for s in self._canvas.get_width_height())
        # Calculate target size from specified normalized width and height and the renderer's current size
        t_w = int(self._size[0] * r_w)
        t_h = int(self._size[1] * r_h)
        resize = c_w != t_w or c_h != t_h
        if resize:
            # Mismatch between canvas size and target size, so resize figure:
            f_w = t_w / self._fig.dpi
            f_h = t_h / self._fig.dpi
            self._fig.set_size_inches(f_w, f_h)
            self.position = (int(self._loc[0] * r_w), int(self._loc[1] * r_h))
        return resize

    def _redraw(self, event=None):
        """Redraw the chart."""
        if event is None:
            # Manual call, so make sure canvas is redrawn first (which will callback to _redraw with a proper event defined)
            self._canvas.draw()
        else:
            # Called from draw_event callback
            img = np.frombuffer(
                self._canvas.buffer_rgba(), dtype=np.uint8
            )  # Store figure data in numpy array
            w, h = self._canvas.get_width_height()
            img_arr = img.reshape([h, w, 4])
            img_data = pyvista.Texture(img_arr).to_image()  # Convert to vtkImageData
            self.SetImage(img_data)

    def _render_event(self, *args, plotter_render=False, **kwargs):
        # Redraw figure when geometry has changed (self._resize call
        # already updated figure dimensions in that case) OR the
        # plotter's render method was called and redraw_on_render is
        # enabled.
        if (plotter_render and self.redraw_on_render) or (not plotter_render and self._resize()):
            self._redraw()

    @property
    def _geometry(self):
        r_w, r_h = self._renderer.GetSize()
        t_w = self._size[0] * r_w
        t_h = self._size[1] * r_h
        return (*self.position, t_w, t_h)

    @_geometry.setter
    def _geometry(self, value):
        raise AttributeError(f'Cannot set the geometry of {type(self).__class__}')

    # Below code can be used to customize the chart's background without a _ChartBackground instance
    # @property
    # def background_color(self):
    #     return self._bg_color
    #
    # @background_color.setter
    # def background_color(self, val):
    #     color = Color(val).int_rgba if val is not None else [1.0, 1.0, 1.0, 1.0]
    #     opacity = color[3]
    #     self._bg_color = color
    #     self._fig.patch.set_color(color[:3])
    #     self._fig.patch.set_alpha(opacity)
    #     for ax in self._fig.axes:
    #         ax.patch.set_alpha(0 if opacity < 1 else 1)  # Make axes fully transparent if opacity is lower than 1

    @property
    def position(self):
        """Chart position w.r.t the bottom left corner (in pixels)."""
        return self.GetPosition()

    @position.setter
    def position(self, val):
        if len(val) != 2:
            raise ValueError(f'Invalid position {val}, must be length 2.')
        self.SetPosition(*val)

    @property
    def title(self):
        """Return or set the chart's title.

        Examples
        --------
        Create a matplotlib chart with title 'My Chart'.

        .. pyvista-plot::

        >>> import pyvista
        >>> import matplotlib.pyplot as plt
        >>> f, ax = plt.subplots()
        >>> _ = ax.plot([0, 1, 2], [2, 1, 3])
        >>> chart = pyvista.ChartMPL(f)
        >>> chart.title = 'My Chart'
        >>> chart.show()

        """
        return self._fig._suptitle.get_text()

    @title.setter
    def title(self, val):
        self._fig.suptitle(val)

    @property
    def legend_visible(self):
        """Return or set the visibility of the chart's legend.

        Examples
        --------
        Create a matplotlib chart with custom labels and show the legend.

        .. pyvista-plot::

        >>> import pyvista
        >>> import matplotlib.pyplot as plt
        >>> f, ax = plt.subplots()
        >>> _ = ax.plot([0, 1, 2], [2, 1, 3], label="Line")
        >>> _ = ax.scatter([0, 1, 2], [3, 2, 1], label="Points")
        >>> chart = pyvista.ChartMPL(f)
        >>> chart.legend_visible = True
        >>> chart.show()

        Hide the legend.

        >>> chart.legend_visible = False
        >>> chart.show()

        """
        legend = self._fig.axes[0].get_legend()
        return False if legend is None else legend.get_visible()

    @legend_visible.setter
    def legend_visible(self, val):
        legend = self._fig.axes[0].get_legend()
        if legend is None:
            legend = self._fig.axes[0].legend()
        legend.set_visible(val)


class Charts:
    """Collection of charts for a renderer.

    Users should typically not directly create new instances of this
    class, but use the dedicated ``Plotter.add_chart`` method.

    """

    def __init__(self, renderer):
        """Create a new collection of charts for the given renderer."""
        self._charts = []

        # Postpone creation of scene and actor objects until they are
        # needed.
        self._scene = None
        self._actor = None

        # a weakref.proxy would be nice here, but that doesn't play
        # nicely with SetRenderer, so instead we'll use a weak reference
        # plus a property to call it
        self.__renderer = weakref.ref(renderer)

    @property
    def _renderer(self):
        """Return the weakly dereferenced renderer, maybe None."""
        return self.__renderer()

    def _setup_scene(self):
        """Set up a new context scene and actor for these charts."""
        self._scene = _vtk.vtkContextScene()
        self._actor = _vtk.vtkContextActor()

        self._actor.SetScene(self._scene)
        self._renderer.AddActor(self._actor)
        self._scene.SetRenderer(self._renderer)

    def deep_clean(self):
        """Remove all references to the chart objects and internal objects."""
        if self._scene is not None:
            charts = [*self._charts]  # Make a copy, as this list will be modified by remove_chart
            for chart in charts:
                self.remove_chart(chart)
            if self._renderer is not None:
                self._renderer.RemoveActor(self._actor)
        self._scene = None
        self._actor = None

    def add_chart(self, *charts):
        """Add charts to the collection."""
        if self._scene is None:
            self._setup_scene()
        for chart in charts:
            self._charts.append(chart)
            if chart._background is not None:
                self._scene.AddItem(chart._background)
            self._scene.AddItem(chart)
            chart._interactive = False  # Charts are not interactive by default

    def set_interaction(self, interactive, toggle=False):
        """
        Set or toggle interaction with charts for this renderer.

        Interaction with other charts in this renderer is disabled when ``toggle``
        is ``False``.

        Parameters
        ----------
        interactive : bool | Chart | int | list[Chart] | list[int]
            Following parameter values are accepted:

            * A boolean to enable (``True``) or disable (``False``) interaction
              with all charts.
            * The chart or its index to enable interaction with. Interaction
              with multiple charts can be enabled by passing a list of charts
              or indices.

        toggle : bool, default: False
            Instead of enabling interaction with the provided chart(s), interaction
            with the provided chart(s) is toggled. Only applicable when ``interactive``
            is not a boolean.

        Returns
        -------
        list of Chart
            The list of all interactive charts for this renderer.

        """
        if isinstance(interactive, bool):
            # Disable toggle and convert to list of charts
            toggle = False
            interactive = self._charts if interactive else []
        if not isinstance(interactive, list):
            # Convert single chart parameter to list
            interactive = [interactive]
        # Convert to list of Charts
        charts = [
            self._charts[coi] if isinstance(coi, int) and 0 <= coi < len(self) else coi
            for coi in interactive
        ]
        interactive_charts = []

        for chart in self._charts:
            # Determine whether to enable interaction with the current chart.
            if toggle:
                enable = not chart._interactive if chart in charts else chart._interactive
            else:
                enable = chart in charts

            chart._interactive = enable
            if enable:
                interactive_charts.append(chart)

        return interactive_charts

    def remove_chart(self, chart_or_index):
        """Remove a chart from the collection."""
        chart = self._charts[chart_or_index] if isinstance(chart_or_index, int) else chart_or_index
        if chart not in self._charts:  # pragma: no cover
            raise ValueError('chart_index not present in charts collection.')
        self._charts.remove(chart)
        self._scene.RemoveItem(chart)
        if chart._background is not None:
            self._scene.RemoveItem(chart._background)

    def get_charts_by_pos(self, pos):
        """Retrieve visible charts indicated by the given mouse position.

        Parameters
        ----------
        pos : sequence[float]
            Tuple containing the mouse position.

        Returns
        -------
        list of Chart
            Visible charts indicated by the given mouse position.

        """
        return [chart for chart in self._charts if chart.visible and chart._is_within(pos)]

    def __getitem__(self, index) -> Chart:
        """Return a chart based on an index."""
        return self._charts[index]

    def __len__(self):
        """Return number of charts."""
        return len(self._charts)

    def __iter__(self):
        """Return an iterable of charts."""
        yield from self._charts

    def __del__(self):
        """Clean up before being destroyed."""
        self.deep_clean()


# pyvista/plotting/composite_mapper.py

"""Module containing composite data mapper."""
from itertools import cycle
import sys
from typing import Optional
import weakref

import matplotlib
import numpy as np

import pyvista as pv
from pyvista import _vtk
from pyvista.utilities import convert_array, convert_string_array

from ..utilities.misc import _check_range, vtk_version_info
from .colors import Color
from .mapper import _BaseMapper


class BlockAttributes:
    """Block attributes used to set the attributes of a block.

    Parameters
    ----------
    block : pyvista.DataObject
        PyVista data object.

    attr : pyvista.plotting.composite_mapper.CompositeAttributes
        Parent attributes.

    Notes
    -----
    This class employs VTK's flat indexing and allows for accessing both
    the blocks of a composite dataset as well as the entire composite
    dataset. If there is only one composite dataset, ``A``, which contains
    datasets ``[b, c]``, the indexing would be ``[A, b, c]``.

    If there are two composite datasets ``[B, C]`` in one composite
    dataset, ``A``, each of which containing three additional datasets
    ``[d, e, f]``, and ``[g, h, i]``, respectively, then the head node,
    ``A``, would be the zero index, followed by the first child, ``B``,
    followed by all the children of ``B``, ``[d, e, f]``. In data
    structures, this flat indexing would be known as "Depth-first search"
    and the entire indexing would be::

       [A, B, d, e, f, C, g, h, i]

    Note how the composite datasets themselves are capitalized and are
    accessible in the flat indexing, and not just the datasets.

    Examples
    --------
    Add a sphere and a cube as a multiblock dataset to a plotter and then
    change the visibility and color of the blocks. Note how the index of the
    cube is ``1`` as the index of the entire multiblock is ``0``.

    >>> import pyvista as pv
    >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
    >>> pl = pv.Plotter()
    >>> actor, mapper = pl.add_composite(dataset)
    >>> mapper.block_attr[1].color = 'b'
    >>> mapper.block_attr[1].opacity = 0.1
    >>> mapper.block_attr[1]
    Composite Block Addr=... Attributes
    Visible:   None
    Opacity:   0.1
    Color:     Color(name='blue', hex='#0000ffff', opacity=255)
    Pickable   None

    """

    def __init__(self, block, attr):
        """Initialize the block attributes class."""
        self._block = block
        self.__attr = weakref.ref(attr)

    @property
    def _attr(self):
        """Return the CompositeAttributes."""
        return self.__attr()

    @property
    def _has_color(self):
        """Return if a block has its color set."""
        return self._attr.HasBlockColor(self._block)

    @property
    def _has_visibility(self):
        """Return if a block has its visibility set."""
        return self._attr.HasBlockVisibility(self._block)

    @property
    def _has_opacity(self):
        """Return if a block has its opacity set."""
        return self._attr.HasBlockOpacity(self._block)

    @property
    def _has_pickable(self):
        """Return if a block has its pickability set."""
        return self._attr.HasBlockPickability(self._block)

    @property
    def color(self):
        """Get or set the color of a block.

        Examples
        --------
        Set the colors of a composite dataset to red and blue.

        Note how the zero index is the entire multiblock, so we have to add 1
        to our indexing to access the right block.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.block_attr[1].color = 'r'
        >>> mapper.block_attr[2].color = 'b'
        >>> pl.show()

        """
        if not self._has_color:
            return None
        return Color(tuple(self._attr.GetBlockColor(self._block)))

    @color.setter
    def color(self, new_color):
        if new_color is None:
            self._attr.RemoveBlockColor(self._block)
            self._attr.Modified()
            return
        self._attr.SetBlockColor(self._block, Color(new_color).float_rgb)

    @property
    def visible(self) -> Optional[bool]:
        """Get or set the visibility of a block.

        Examples
        --------
        Hide the first block of a composite dataset.

        Note how the zero index is the entire multiblock, so we have to add 1
        to our indexing to access the right block.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.block_attr[1].visible = False
        >>> pl.show()

        """
        if not self._has_visibility:
            return None
        return self._attr.GetBlockVisibility(self._block)

    @visible.setter
    def visible(self, new_visible: bool):
        if new_visible is None:
            self._attr.RemoveBlockVisibility(self._block)
            self._attr.Modified()
            return
        self._attr.SetBlockVisibility(self._block, new_visible)

    @property
    def opacity(self) -> Optional[float]:
        """Get or set the opacity of a block.

        If opacity has not been set this will be ``None``.

        Warnings
        --------
        VTK 9.0.3 has a bug where changing the opacity to less than 1.0 also
        changes the edge visibility on the block that is partially transparent.

        Examples
        --------
        Change the opacity of the second block of the dataset.

        Note how the zero index is the entire multiblock, so we have to add 1
        to our indexing to access the right block.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.block_attr[2].opacity = 0.5
        >>> pl.show()

        """
        if not self._has_opacity:
            return None
        return self._attr.GetBlockOpacity(self._block)

    @opacity.setter
    def opacity(self, new_opacity: float):
        """Get or set the visibility of a block."""
        if new_opacity is None:
            self._attr.RemoveBlockOpacity(self._block)
            self._attr.Modified()
            return

        _check_range(new_opacity, (0, 1), 'opacity')
        self._attr.SetBlockOpacity(self._block, new_opacity)

    @property
    def pickable(self) -> Optional[bool]:
        """Get or set the pickability of a block.

        Examples
        --------
        Make the cube of a multiblock dataset pickable and the sphere unpickable.

        Note how the zero index is the entire multiblock, so we have to add 1
        to our indexing to access the right block.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.block_attr[1].pickable = True
        >>> mapper.block_attr[2].pickable = False
        >>> pl.close()

        See :ref:`composite_picking_example` for a full example using block
        picking.

        """
        if not self._has_pickable:
            return None
        return self._attr.GetBlockPickability(self._block)

    @pickable.setter
    def pickable(self, new_pickable: bool):
        if new_pickable is None:
            self._attr.RemoveBlockPickability(self._block)
            self._attr.Modified()
            return
        self._attr.SetBlockPickability(self._block, new_pickable)

    def __repr__(self):
        """Representation of block properties."""
        return '\n'.join(
            [
                f'Composite Block {self._block.memory_address} Attributes',
                f'Visible:   {self.visible}',
                f'Opacity:   {self.opacity}',
                f'Color:     {self.color}',
                f'Pickable   {self.pickable}',
            ]
        )


class CompositeAttributes(_vtk.vtkCompositeDataDisplayAttributes):
    """Block attributes.

    Parameters
    ----------
    mapper : pyvista.plotting.composite_mapper.CompositePolyDataMapper
        Parent mapper.

    dataset : pyvista.MultiBlock
        Multiblock dataset.

    Notes
    -----
    This class employs VTK's flat indexing and allows for accessing both
    the blocks of a composite dataset as well as the entire composite
    dataset. If there is only one composite dataset, ``A``, which contains
    datasets ``[b, c]``, the indexing would be ``[A, b, c]``.

    If there are two composite datasets ``[B, C]`` in one composite
    dataset, ``A``, each of which containing three additional datasets
    ``[d, e, f]``, and ``[g, h, i]``, respectively, then the head node,
    ``A``, would be the zero index, followed by the first child, ``B``,
    followed by all the children of ``B``, ``[d, e, f]``. In data
    structures, this flat indexing would be known as "Depth-first search"
    and the entire indexing would be::

       [A, B, d, e, f, C, g, h, i]

    Note how the composite datasets themselves are capitalized and are
    accessible in the flat indexing, and not just the datasets.

    Examples
    --------
    Add a sphere and a cube as a multiblock dataset to a plotter and then
    change the visibility and color of the blocks. Note how the index of the
    cube is ``1`` as the index of the entire multiblock is ``0``.

    >>> import pyvista as pv
    >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
    >>> pl = pv.Plotter()
    >>> actor, mapper = pl.add_composite(dataset)
    >>> mapper.block_attr[1].color = 'b'
    >>> mapper.block_attr[1].opacity = 0.1
    >>> mapper.block_attr[1]
    Composite Block Addr=... Attributes
    Visible:   None
    Opacity:   0.1
    Color:     Color(name='blue', hex='#0000ffff', opacity=255)
    Pickable   None

    """

    def __init__(self, mapper, dataset):
        """Initialize CompositeAttributes."""
        super().__init__()
        mapper.SetCompositeDataDisplayAttributes(self)
        self._dataset = dataset

    def reset_visibilities(self):
        """Reset the visibility of all blocks.

        Examples
        --------
        Hide the first block of a composite dataset and then show all by
        resetting visibilities.

        Note how the zero index is the entire multiblock, so we have to add 1
        to our indexing to access the right block.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.block_attr[1].visible = False
        >>> mapper.block_attr.reset_visibilities()
        >>> pl.show()

        """
        self.RemoveBlockVisibilities()

    def reset_pickabilities(self):
        """Reset the pickability of all blocks.

        Examples
        --------
        Make the cube of a multiblock dataset pickable and the sphere
        unpickable, then reset it.

        Note how the zero index is the entire multiblock, so we have to add 1
        to our indexing to access the right block.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.block_attr[1].pickable = True
        >>> mapper.block_attr[2].pickable = False
        >>> mapper.block_attr.reset_pickabilities()
        >>> [
        ...     mapper.block_attr[1].pickable,
        ...     mapper.block_attr[2].pickable,
        ... ]
        [None, None]
        >>> pl.close()

        """
        self.RemoveBlockPickabilities()

    def reset_colors(self):
        """Reset the color of all blocks.

        Examples
        --------
        Set individual block colors and then reset them.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset, color='w')
        >>> mapper.block_attr[1].color = 'r'
        >>> mapper.block_attr[2].color = 'b'
        >>> mapper.block_attr.reset_colors()
        >>> pl.show()

        """
        self.RemoveBlockColors()

    def reset_opacities(self):
        """Reset the opacities of all blocks.

        Examples
        --------
        Change the opacity of the second block of the dataset then reset all
        opacities.

        Note how the zero index is the entire multiblock, so we have to add 1
        to our indexing to access the right block.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.block_attr[2].opacity = 0.5
        >>> mapper.block_attr.reset_opacities()
        >>> pl.show()

        """
        self.RemoveBlockOpacities()

    def get_block(self, index):
        """Return a block by its flat index.

        Parameters
        ----------
        index : int
            Flat index of the block to retrieve.

        Returns
        -------
        pyvista.DataObject
            PyVista data object.

        Notes
        -----
        This method employs VTK's flat indexing and allows for accessing both
        the blocks of a composite dataset as well as the entire composite
        dataset. If there is only one composite dataset, ``A``, which contains
        datasets ``[b, c]``, the indexing would be ``[A, b, c]``.

        If there are two composite datasets ``[B, C]`` in one composite
        dataset, ``A``, each of which containing three additional datasets
        ``[d, e, f]``, and ``[g, h, i]``, respectively, then the head node,
        ``A``, would be the zero index, followed by the first child, ``B``,
        followed by all the children of ``B``, ``[d, e, f]``. In data
        structures, this flat indexing would be known as "Depth-first search"
        and the entire indexing would be::

           [A, B, d, e, f, C, g, h, i]

        Note how the composite datasets themselves are capitalized and are
        accessible in the flat indexing, and not just the datasets.

        Examples
        --------
        Add a composite dataset to a plotter and access its block attributes.
        Note how the zero index is the entire multiblock and you can use ``1``
        and ``2`` to access the individual sub-blocks.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.block_attr.get_block(0)
        MultiBlock (...)
          N Blocks    2
          X Bounds    -0.500, 0.500
          Y Bounds    -0.500, 0.500
          Z Bounds    -0.500, 1.500

        Note this is the same as using ``__getitem__``

        >>> mapper.block_attr[0]
        Composite Block Addr=... Attributes
        Visible:   None
        Opacity:   None
        Color:     None
        Pickable   None

        """
        try:
            if vtk_version_info <= (9, 0, 3):  # pragma: no cover
                vtk_ref = _vtk.reference(0)  # needed for <=9.0.3
                block = self.DataObjectFromIndex(index, self._dataset, vtk_ref)
            else:
                block = self.DataObjectFromIndex(index, self._dataset)
        except OverflowError:
            raise KeyError(f'Invalid block key: {index}') from None
        if block is None:
            if index > len(self) - 1:
                raise KeyError(
                    f'index {index} is out of bounds. There are only {len(self)} blocks.'
                ) from None
        return block

    def __getitem__(self, index):
        """Return a block attribute by its flat index."""
        return BlockAttributes(self.get_block(index), self)

    def __len__(self):
        """Return the number of blocks in this dataset."""
        from pyvista import MultiBlock  # avoid circular

        # start with 1 as there is always a composite dataset and this is the
        # root of the tree
        cc = 1
        for dataset in self._dataset:
            if isinstance(dataset, MultiBlock):
                cc += len(dataset) + 1  # include the block itself
            else:
                cc += 1
        return cc

    def __iter__(self):
        """Return an iterator of all the block attributes."""
        for ii in range(len(self)):
            yield self[ii]


class CompositePolyDataMapper(_vtk.vtkCompositePolyDataMapper2, _BaseMapper):
    """Composite PolyData mapper.

    Parameters
    ----------
    dataset : pyvista.MultiBlock
        Multiblock dataset.

    theme : pyvista.themes.DefaultTheme, optional
        Plot-specific theme.

    color_missing_with_nan : bool, optional
        Color any missing values with the ``nan_color``. This is useful
        when not all blocks of the composite dataset have the specified
        ``scalars``.

    interpolate_before_map : bool, optional
        Enabling makes for a smoother scalars display.  Default is
        ``True``.  When ``False``, OpenGL will interpolate the
        mapped colors which can result is showing colors that are
        not present in the color map.

    """

    def __init__(
        self, dataset, theme=None, color_missing_with_nan=None, interpolate_before_map=None
    ):
        """Initialize this composite mapper."""
        super().__init__(theme=theme)
        self.SetInputDataObject(dataset)

        # this must be added to set the color, opacity, and visibility of
        # individual blocks
        self._attr = CompositeAttributes(self, dataset)
        self._dataset = dataset

        if color_missing_with_nan is not None:
            self.color_missing_with_nan = color_missing_with_nan
        if interpolate_before_map is not None:
            self.interpolate_before_map = interpolate_before_map

    @property
    def dataset(self) -> 'pv.MultiBlock':
        """Return the composite dataset assigned to this mapper.

        Examples
        --------
        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.dataset
        MultiBlock (...)
          N Blocks    2
          X Bounds    -0.500, 0.500
          Y Bounds    -0.500, 0.500
          Z Bounds    -0.500, 1.500

        """
        return self._dataset

    @property
    def block_attr(self) -> CompositeAttributes:
        """Return the block attributes.

        Notes
        -----
        ``block_attr`` employs VTK's flat indexing and allows for accessing
        both the blocks of a composite dataset as well as the entire composite
        dataset. If there is only one composite dataset, ``A``, which contains
        datasets ``[b, c]``, the indexing would be ``[A, b, c]``.

        If there are two composite datasets ``[B, C]`` in one composite
        dataset, ``A``, each of which containing three additional datasets
        ``[d, e, f]``, and ``[g, h, i]``, respectively, then the head node,
        ``A``, would be the zero index, followed by the first child, ``B``,
        followed by all the children of ``B``, ``[d, e, f]``. In data
        structures, this flat indexing would be known as "Depth-first search"
        and the entire indexing would be::

           [A, B, d, e, f, C, g, h, i]

        Examples
        --------
        Add a sphere and a cube as a multiblock dataset to a plotter and then
        change the visibility and color of the blocks.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.block_attr[1].color = 'b'
        >>> mapper.block_attr[1].opacity = 0.1
        >>> mapper.block_attr[1]
        Composite Block Addr=... Attributes
        Visible:   None
        Opacity:   0.1
        Color:     Color(name='blue', hex='#0000ffff', opacity=255)
        Pickable   None

        """
        return self._attr

    @property
    def color_missing_with_nan(self) -> bool:
        """Color missing arrays with the NaN color.

        Examples
        --------
        Enable coloring missing values with NaN.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> dataset[0].point_data['data'] = dataset[0].points[:, 2]
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(
        ...     dataset, scalars='data', show_scalar_bar=False
        ... )
        >>> mapper.nan_color = 'r'
        >>> mapper.color_missing_with_nan = True
        >>> pl.show()

        """
        return self.GetColorMissingArraysWithNanColor()

    @color_missing_with_nan.setter
    def color_missing_with_nan(self, value: bool):
        self.SetColorMissingArraysWithNanColor(value)

    def set_unique_colors(self):
        """Set each block of the dataset to a unique color.

        This uses ``matplotlib``'s color cycler.

        Examples
        --------
        Set each block of the composite dataset to a unique color.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.set_unique_colors()
        >>> mapper.block_attr[1].color
        Color(name='tab:orange', hex='#ff7f0eff', opacity=255)
        >>> mapper.block_attr[2].color
        Color(name='tab:green', hex='#2ca02cff', opacity=255)
        """
        self.scalar_visibility = False
        colors = cycle(matplotlib.rcParams['axes.prop_cycle'])
        for attr in self.block_attr:
            attr.color = next(colors)['color']

    def set_scalars(
        self,
        scalars_name,
        preference,
        component,
        annotations,
        rgb,
        scalar_bar_args,
        n_colors,
        nan_color,
        above_color,
        below_color,
        clim,
        cmap,
        flip_scalars,
        log_scale,
    ):
        """Set the scalars of the mapper.

        Parameters
        ----------
        scalars_name : str
            Name of the scalars in the dataset. Must already exist in at least
            of the blocks.

        preference : str
            For each block, when ``block.n_points == block.n_cells`` and
            setting scalars, this parameter sets how the scalars will be mapped
            to the mesh.  Default ``'point'``, causes the scalars will be
            associated with the mesh points.  Can be either ``'point'`` or
            ``'cell'``.

        component : int
            Set component of vector valued scalars to plot.  Must be
            nonnegative, if supplied. If ``None``, the magnitude of
            the vector is plotted.

        annotations : dict
            Pass a dictionary of annotations. Keys are the float
            values in the scalars range to annotate on the scalar bar
            and the values are the string annotations.

        rgb : bool
            If the ``scalars_name`` corresponds to a 2 dimensional array, plot
            those values as RGB(A) colors.

        scalar_bar_args : dict
            Dictionary of keyword arguments to pass when adding the
            scalar bar to the scene. For options, see
            :func:`pyvista.Plotter.add_scalar_bar`.

        n_colors : int
            Number of colors to use when displaying scalars.

        nan_color : ColorLike
            The color to use for all ``NaN`` values in the plotted
            scalar array.

        above_color : ColorLike
            Solid color for values below the scalars range
            (``clim``). This will automatically set the scalar bar
            ``above_label`` to ``'above'``.

        below_color : ColorLike
            Solid color for values below the scalars range
            (``clim``). This will automatically set the scalar bar
            ``below_label`` to ``'below'``.

        clim : Sequence
            Color bar range for scalars.  Defaults to minimum and
            maximum of scalars array.  Example: ``[-1, 2]``. ``rng``
            is also an accepted alias for this.

        cmap : str, list, or pyvista.LookupTable
            Name of the Matplotlib colormap to use when mapping the
            ``scalars``.  See available Matplotlib colormaps.  Only applicable
            for when displaying ``scalars``.
            ``colormap`` is also an accepted alias for this. If
            ``colorcet`` or ``cmocean`` are installed, their colormaps can be
            specified by name.

            You can also specify a list of colors to override an existing
            colormap with a custom one.  For example, to create a three color
            colormap you might specify ``['green', 'red', 'blue']``.

            This parameter also accepts a :class:`pyvista.LookupTable`. If this
            is set, all parameters controlling the color map like ``n_colors``
            will be ignored.
            are installed, their colormaps can be specified by name.

        flip_scalars : bool
            Flip direction of cmap. Most colormaps allow ``*_r``
            suffix to do this as well.

        log_scale : bool
            Use log scale when mapping data to colors. Scalars less
            than zero are mapped to the smallest representable
            positive float.

        Returns
        -------
        dict
            Dictionary of scalar bar arguments.

        """
        self._orig_scalars_name = scalars_name

        field, scalars_name, dtype = self._dataset._activate_plotting_scalars(
            scalars_name, preference, component, rgb
        )

        self.scalar_visibility = True
        if rgb:
            self.scalar_mode = 'direct'
            return scalar_bar_args
        else:
            self.scalar_map_mode = field.name.lower()

        scalar_bar_args.setdefault('title', scalars_name)

        if clim is None:
            clim = self._dataset.get_data_range(scalars_name, allow_missing=True)
        self.scalar_range = clim

        if log_scale:
            if clim[0] <= 0:
                clim = [sys.float_info.min, clim[1]]

        if isinstance(cmap, pv.LookupTable):
            self.lookup_table = cmap
        else:
            if dtype == np.bool_:
                cats = np.array([b'False', b'True'], dtype='|S5')
                values = np.array([0, 1])
                n_colors = 2
                scalar_bar_args.setdefault('n_labels', 0)
                self.lookup_table.SetAnnotations(convert_array(values), convert_string_array(cats))
                clim = [-0.5, 1.5]

            self.lookup_table.log_scale = log_scale

            if isinstance(annotations, dict):
                self.lookup_table.annotations = annotations

            # self.lookup_table.SetNumberOfTableValues(n_colors)
            if nan_color:
                self.lookup_table.nan_color = nan_color
            if above_color:
                self.lookup_table.above_range_color = above_color
                scalar_bar_args.setdefault('above_label', 'above')
            if below_color:
                self.lookup_table.below_range_color = below_color
                scalar_bar_args.setdefault('below_label', 'below')

            if cmap is None:
                if self._theme is None:
                    cmap = pv.global_theme.cmap
                else:
                    cmap = self._theme.cmap

            if cmap is not None:
                self.lookup_table.apply_cmap(cmap, n_colors, flip_scalars)
            else:  # pragma: no cover
                if flip_scalars:
                    self.lookup_table.SetHueRange(0.0, 0.66667)
                else:
                    self.lookup_table.SetHueRange(0.66667, 0.0)

        return scalar_bar_args


# pyvista/plotting/cube_axes_actor.py

"""Module containing the wrapping of CubeAxesActor."""
from typing import List, Tuple

import numpy as np

import pyvista as pv
from pyvista import _vtk
from pyvista.utilities import convert_string_array

from .._typing import BoundsLike


def make_axis_labels(vmin, vmax, n, fmt):
    """Create a axis labels as a vtkStringArray."""
    labels = _vtk.vtkStringArray()
    for v in np.linspace(vmin, vmax, n):
        if fmt:
            if fmt.startswith('%'):
                label = fmt % v
            else:
                label = fmt.format(v)
        else:
            label = f'{v}'
        labels.InsertNextValue(label)
    return labels


class CubeAxesActor(_vtk.vtkCubeAxesActor):
    """Wrap vtkCubeAxesActor.

    This class is created to wrap vtkCubeAxesActor, which is used to draw axes
    and labels for the input data bounds. This wrapping aims to provide a
    user-friendly interface to use `vtkCubeAxesActor
    <https://vtk.org/doc/nightly/html/classvtkCubeAxesActor.html>`_.

    Parameters
    ----------
    camera : pyvista.Camera
        Camera to link to the axes actor.

    minor_ticks : bool, default: False
        If ``True``, also plot minor ticks on all axes.

    tick_location : str, optional
        Set how the ticks are drawn on the axes grid. Options include:
        ``'inside', 'outside', 'both'``.

    x_title : str, default: "X Axis"
        Title of the X axis.

    y_title : str, default: "Y Axis"
        Title of the Y axis.

    z_title : str, default: "Z Axis"
        Title of the Z axis.

    x_axis_visibility : bool, default: True
        Visibility of the X axis.

    y_axis_visibility : bool, default: True
        Visibility of the Y axis.

    z_axis_visibility : bool, default: True
        Visibility of the Z axis.

    x_label_format : str, optional
        A format string defining how tick labels are generated from tick
        positions for the X axis. Defaults to the theme format if set,
        otherwise ``'%.1f'``.

    y_label_format : str, optional
        A format string defining how tick labels are generated from tick
        positions for the Y axis. Defaults to the theme format if set,
        otherwise ``'%.1f'``.

    z_label_format : str, optional
        A format string defining how tick labels are generated from tick
        positions for the Z axis. Defaults to the theme format if set,
        otherwise ``'%.1f'``.

    x_label_visibility : bool, default: True
        The visibility of the X axis labels.

    y_label_visibility : bool, default: True
        The visibility of the Y axis labels.

    z_label_visibility : bool, default: True
        The visibility of the Z axis labels.

    n_xlabels : int, default: 5
        Number of labels along the X axis.

    n_ylabels : int, default: 5
        Number of labels along the Y axis.

    n_zlabels : int, default: 5
        Number of labels along the Z axis.

    Examples
    --------
    Create a 3D plotter and add a CubeAxesActor to it.

    >>> import pyvista as pv
    >>> mesh = pv.Cube()
    >>> pl = pv.Plotter()
    >>> actor = pl.add_mesh(mesh)
    >>> cube_axes_actor = pv.CubeAxesActor(pl.camera)
    >>> cube_axes_actor.bounds = mesh.bounds
    >>> actor, property = pl.add_actor(cube_axes_actor)
    >>> pl.show()

    """

    def __init__(
        self,
        camera,
        minor_ticks=False,
        tick_location=None,
        x_title='X Axis',
        y_title='Y Axis',
        z_title='Z Axis',
        x_axis_visibility=True,
        y_axis_visibility=True,
        z_axis_visibility=True,
        x_label_format=None,
        y_label_format=None,
        z_label_format=None,
        x_label_visibility=True,
        y_label_visibility=True,
        z_label_visibility=True,
        n_xlabels=5,
        n_ylabels=5,
        n_zlabels=5,
    ):
        """Initialize CubeAxesActor."""
        super().__init__()
        self.camera = camera

        # empty string used for clearing axis labels
        self._empty_str = _vtk.vtkStringArray()
        self._empty_str.InsertNextValue('')

        # stop labels from being generated several times during init
        self.x_axis_visibility = False
        self.y_axis_visibility = False
        self.z_axis_visibility = False

        if not minor_ticks:
            self.x_axis_minor_tick_visibility = minor_ticks
            self.y_axis_minor_tick_visibility = minor_ticks
            self.z_axis_minor_tick_visibility = minor_ticks

        if tick_location:
            self.tick_location = tick_location
        self.x_title = x_title
        self.y_title = y_title
        self.z_title = z_title

        self._x_label_visibility = x_label_visibility
        self._y_label_visibility = y_label_visibility
        self._z_label_visibility = z_label_visibility

        if x_label_format is None:
            x_label_format = pv.global_theme.font.fmt
            if x_label_format is None:
                x_label_format = '%.1f'
        if y_label_format is None:
            y_label_format = pv.global_theme.font.fmt
            if y_label_format is None:
                y_label_format = '%.1f'
        if z_label_format is None:
            z_label_format = pv.global_theme.font.fmt
            if z_label_format is None:
                z_label_format = '%.1f'

        self.x_label_format = x_label_format
        self.y_label_format = y_label_format
        self.z_label_format = z_label_format

        self.n_xlabels = n_xlabels
        self.n_ylabels = n_ylabels
        self.n_zlabels = n_zlabels

        self.x_axis_visibility = x_axis_visibility
        self.y_axis_visibility = y_axis_visibility
        self.z_axis_visibility = z_axis_visibility

    @property
    def tick_location(self) -> str:
        """Return or set how the ticks are drawn on the axes grid.

        Options include: ``'inside', 'outside', 'both'``.
        """
        tloc = self.GetTickLocation()
        if tloc == 0:
            return 'inside'
        if tloc == 1:
            return 'outside'
        return 'both'

    @tick_location.setter
    def tick_location(self, value: str):
        if not isinstance(value, str):
            raise TypeError(f'`tick_location` must be a string, not {type(value)}')
        value = value.lower()
        if value in ('inside'):
            self.SetTickLocationToInside()
        elif value in ('outside'):
            self.SetTickLocationToOutside()
        elif value in ('both'):
            self.SetTickLocationToBoth()
        else:
            raise ValueError(
                f'Value of tick_location ("{value}") should be either "inside", "outside", '
                'or "both".'
            )

    @property
    def bounds(self) -> BoundsLike:
        """Return or set the bounding box."""
        return self.GetBounds()

    @bounds.setter
    def bounds(self, bounds: BoundsLike):
        self.SetBounds(bounds)
        self._update_labels()
        self.x_axis_range = float(bounds[0]), float(bounds[1])
        self.y_axis_range = float(bounds[2]), float(bounds[3])
        self.z_axis_range = float(bounds[4]), float(bounds[5])

    @property
    def x_axis_range(self) -> Tuple[float, float]:
        """Return or set the X axis range."""
        return self.GetXAxisRange()

    @x_axis_range.setter
    def x_axis_range(self, value: Tuple[float, float]):
        self.SetXAxisRange(value)

    @property
    def y_axis_range(self) -> Tuple[float, float]:
        """Return or set the Y axis range."""
        return self.GetYAxisRange()

    @y_axis_range.setter
    def y_axis_range(self, value: Tuple[float, float]):
        self.SetYAxisRange(value)

    @property
    def z_axis_range(self) -> Tuple[float, float]:
        """Return or set the Z axis range."""
        return self.GetZAxisRange()

    @z_axis_range.setter
    def z_axis_range(self, value: Tuple[float, float]):
        self.SetZAxisRange(value)

    @property
    def label_offset(self) -> float:
        """Return or set the distance between labels and the axis."""
        return self.GetLabelOffset()

    @label_offset.setter
    def label_offset(self, offset: float):
        self.SetLabelOffset(offset)

    @property
    def title_offset(self) -> float:
        """Return or set the distance between title and labels."""
        return self.GetTitleOffset()

    @title_offset.setter
    def title_offset(self, offset: float):
        self.SetTitleOffset(offset)

    @property
    def camera(self) -> 'pv.Camera':
        """Return or set the camera that performs scaling and translation."""
        return self.GetCamera()

    @camera.setter
    def camera(self, camera: 'pv.Camera'):
        self.SetCamera(camera)

    @property
    def x_axis_minor_tick_visibility(self) -> bool:
        """Return or set visibility of the X axis minior tick."""
        return bool(self.GetXAxisMinorTickVisibility())

    @x_axis_minor_tick_visibility.setter
    def x_axis_minor_tick_visibility(self, value: bool):
        self.SetXAxisMinorTickVisibility(value)

    @property
    def y_axis_minor_tick_visibility(self) -> bool:
        """Return or set visibility of the Y axis minior tick."""
        return bool(self.GetYAxisMinorTickVisibility())

    @y_axis_minor_tick_visibility.setter
    def y_axis_minor_tick_visibility(self, value: bool):
        self.SetYAxisMinorTickVisibility(value)

    @property
    def z_axis_minor_tick_visibility(self) -> bool:
        """Return or set visibility of the Z axis minior tick."""
        return bool(self.GetZAxisMinorTickVisibility())

    @z_axis_minor_tick_visibility.setter
    def z_axis_minor_tick_visibility(self, value: bool):
        self.SetZAxisMinorTickVisibility(value)

    @property
    def x_label_visibility(self) -> bool:
        """Return or set the visibility of the X axis labels."""
        return self._x_label_visibility

    @x_label_visibility.setter
    def x_label_visibility(self, value: bool):
        self._x_label_visibility = bool(value)
        self._update_x_labels()

    @property
    def y_label_visibility(self) -> bool:
        """Return or set the visibility of the Y axis labels."""
        return self._y_label_visibility

    @y_label_visibility.setter
    def y_label_visibility(self, value: bool):
        self._y_label_visibility = bool(value)
        self._update_y_labels()

    @property
    def z_label_visibility(self) -> bool:
        """Return or set the visibility of the Z axis labels."""
        return self._z_label_visibility

    @z_label_visibility.setter
    def z_label_visibility(self, value: bool):
        self._z_label_visibility = bool(value)
        self._update_z_labels()

    @property
    def x_axis_visibility(self) -> bool:
        """Return or set the visibility of the X axis."""
        return bool(self.GetXAxisVisibility())

    @x_axis_visibility.setter
    def x_axis_visibility(self, value: bool):
        self.SetXAxisVisibility(value)

    @property
    def y_axis_visibility(self) -> bool:
        """Return or set the visibility of the Y axis."""
        return bool(self.GetYAxisVisibility())

    @y_axis_visibility.setter
    def y_axis_visibility(self, value: bool):
        self.SetYAxisVisibility(value)

    @property
    def z_axis_visibility(self) -> bool:
        """Return or set the visibility of the Y axis."""
        return bool(self.GetZAxisVisibility())

    @z_axis_visibility.setter
    def z_axis_visibility(self, value: bool):
        self.SetZAxisVisibility(value)

    @property
    def x_label_format(self) -> str:
        """Return or set the label of the X axis."""
        return self.GetXLabelFormat()

    @x_label_format.setter
    def x_label_format(self, value: str):
        self.SetXLabelFormat(value)
        self._update_x_labels()

    @property
    def y_label_format(self) -> str:
        """Return or set the label of the Y axis."""
        return self.GetYLabelFormat()

    @y_label_format.setter
    def y_label_format(self, value: str):
        self.SetYLabelFormat(value)
        self._update_y_labels()

    @property
    def z_label_format(self) -> str:
        """Return or set the label of the Z axis."""
        return self.GetZLabelFormat()

    @z_label_format.setter
    def z_label_format(self, value: str):
        self.SetZLabelFormat(value)
        self._update_z_labels()

    @property
    def x_title(self) -> str:
        """Return or set the title of the X axis."""
        return self._x_title

    @x_title.setter
    def x_title(self, value: str):
        self._x_title = value
        self._update_x_labels()

    @property
    def y_title(self) -> str:
        """Return or set the title of the Y axis."""
        return self._y_title

    @y_title.setter
    def y_title(self, value: str):
        self._y_title = value
        self._update_y_labels()

    @property
    def z_title(self) -> str:
        """Return or set the title of the Z axis."""
        return self._z_title

    @z_title.setter
    def z_title(self, value: str):
        self._z_title = value
        self._update_z_labels()

    @property
    def use_2d_mode(self) -> bool:
        """Use the 2d render mode.

        This can be enabled for smoother plotting.
        """
        return bool(self.GetUse2DMode())

    @use_2d_mode.setter
    def use_2d_mode(self, value: bool):
        self.SetUse2DMode(value)

    @property
    def n_xlabels(self):
        """Number of labels on the X axis."""
        return self._n_xlabels

    @n_xlabels.setter
    def n_xlabels(self, value: int):
        self._n_xlabels = value
        self._update_x_labels()

    @property
    def n_ylabels(self):
        """Number of labels on the Y axis."""
        return self._n_ylabels

    @n_ylabels.setter
    def n_ylabels(self, value: int):
        self._n_ylabels = value
        self._update_y_labels()

    @property
    def n_zlabels(self):
        """Number of labels on the Z axis."""
        return self._n_zlabels

    @n_zlabels.setter
    def n_zlabels(self, value: int):
        self._n_zlabels = value
        self._update_z_labels()

    def _update_labels(self):
        """Update all labels."""
        self._update_x_labels()
        self._update_y_labels()
        self._update_z_labels()

    def _update_x_labels(self):
        """Regenerate X axis labels."""
        if self.x_axis_visibility:
            self.SetXTitle(self._x_title)
            if self._x_label_visibility:
                self.SetAxisLabels(
                    0, make_axis_labels(*self.bounds[0:2], self.n_xlabels, self.x_label_format)
                )
            else:
                self.SetAxisLabels(0, self._empty_str)
        else:
            self.SetXTitle('')
            self.SetAxisLabels(0, self._empty_str)

    def _update_y_labels(self):
        """Regenerate Y axis labels."""
        if self.y_axis_visibility:
            self.SetYTitle(self._y_title)
            if self._y_label_visibility:
                self.SetAxisLabels(
                    1, make_axis_labels(*self.bounds[2:4], self.n_ylabels, self.y_label_format)
                )
            else:
                self.SetAxisLabels(1, self._empty_str)
        else:
            self.SetYTitle('')
            self.SetAxisLabels(1, self._empty_str)

    def _update_z_labels(self):
        """Regenerate Z axis labels."""
        if self.z_axis_visibility:
            self.SetZTitle(self._z_title)
            if self._z_label_visibility:
                self.SetAxisLabels(
                    2, make_axis_labels(*self.bounds[4:6], self.n_zlabels, self.z_label_format)
                )
            else:
                self.SetAxisLabels(2, self._empty_str)
        else:
            self.SetZTitle('')
            self.SetAxisLabels(2, self._empty_str)

    @property
    def x_labels(self) -> List[str]:
        """Return the x axis labels."""
        return convert_string_array(self.GetAxisLabels(0))

    @property
    def y_labels(self) -> List[str]:
        """Return the y axis labels."""
        return convert_string_array(self.GetAxisLabels(1))

    @property
    def z_labels(self) -> List[str]:
        """Return the z axis labels."""
        return convert_string_array(self.GetAxisLabels(2))

    def update_bounds(self, bounds):
        """Update the bounds of this actor.

        Unlike the :attr:`CubeAxesActor.bounds` attribute, updating the bounds
        also updates the axis labels.

        Parameters
        ----------
        bounds : sequence[float]
            Bounds in the form of ``[xmin, xmax, ymin, ymax, zmin, zmax]``.

        """
        self.bounds = bounds


# pyvista/plotting/export_vtkjs.py

"""Export a rendering window to a VTKjs file.

This module holds a set of tools for exporting a VTK rendering window
to a VTKjs file that can be viewed in a web browser.

PVGeo has a webveiwer_ set up to load these files.

.. _webviewer: http://viewer.pyvista.org


Much of this export script was adopted from the
`VTKjs export script for ParaView`_.

.. VTKjs export script for ParaView: https://github.com/Kitware/vtk-js/blob/master/Utilities/ParaView/export-scene-macro.py

The license for the original export script is as follows:

Copyright (c) 2016, Kitware Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT
HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""
import errno
import gzip
import hashlib
import json
import os
import shutil
import sys
import time
import zipfile

FILENAME_EXTENSION = '.vtkjs'

arrayTypesMapping = '  bBhHiIlLfdL'  # last one is idtype

jsMapping = {
    'b': 'Int8Array',
    'B': 'Uint8Array',
    'h': 'Int16Array',
    'H': 'Int16Array',
    'i': 'Int32Array',
    'I': 'Uint32Array',
    'l': 'Int32Array',
    'L': 'Uint32Array',
    'f': 'Float32Array',
    'd': 'Float64Array',
}

writer_mapping = {}

# -----------------------------------------------------------------------------


def get_range_info(array, component):
    """Get the data range of the array's component."""
    r = array.GetRange(component)
    comp_range = {}
    comp_range['min'] = r[0]
    comp_range['max'] = r[1]
    comp_range['component'] = array.GetComponentName(component)
    return comp_range


# -----------------------------------------------------------------------------


def get_ref(dest_dir, md5):
    """Get reference."""
    ref = {}
    ref['id'] = md5
    ref['encode'] = 'BigEndian' if sys.byteorder == 'big' else 'LittleEndian'
    ref['basepath'] = dest_dir
    return ref


# -----------------------------------------------------------------------------


objIds = []  # type: ignore


def get_object_id(obj):
    """Get object identifier."""
    try:
        idx = objIds.index(obj)
        return idx + 1
    except ValueError:
        objIds.append(obj)
        return len(objIds)


# -----------------------------------------------------------------------------


def dump_data_array(dataset_dir, data_dir, array, root=None, compress=True):
    """Dump vtkjs data array."""
    # import here to avoid circular imports
    from pyvista import _vtk

    if root is None:
        root = {}
    if not array:
        return None

    if array.GetDataType() == 12:
        # IdType need to be converted to Uint32
        array_size = array.GetNumberOfTuples() * array.GetNumberOfComponents()
        new_array = _vtk.vtkTypeUInt32Array()
        new_array.SetNumberOfTuples(array_size)
        for i in range(array_size):
            new_array.SetValue(i, -1 if array.GetValue(i) < 0 else array.GetValue(i))
        pbuffer = memoryview(new_array)
    else:
        pbuffer = memoryview(array)

    pMd5 = hashlib.md5(pbuffer).hexdigest()
    ppath = os.path.join(data_dir, pMd5)
    with open(ppath, 'wb') as f:
        f.write(pbuffer)

    if compress:
        with open(ppath, 'rb') as f_in, gzip.open(
            os.path.join(data_dir, pMd5 + '.gz'), 'wb'
        ) as f_out:
            shutil.copyfileobj(f_in, f_out)
        # Close then remove.
        os.remove(ppath)

    root['ref'] = get_ref(os.path.relpath(data_dir, dataset_dir), pMd5)
    root['vtkClass'] = 'vtkDataArray'
    root['name'] = array.GetName()
    root['dataType'] = jsMapping[arrayTypesMapping[array.GetDataType()]]
    root['numberOfComponents'] = array.GetNumberOfComponents()
    root['size'] = array.GetNumberOfComponents() * array.GetNumberOfTuples()
    root['ranges'] = []
    if root['numberOfComponents'] > 1:
        for i in range(root['numberOfComponents']):
            root['ranges'].append(get_range_info(array, i))
        root['ranges'].append(get_range_info(array, -1))
    else:
        root['ranges'].append(get_range_info(array, 0))

    return root


# -----------------------------------------------------------------------------


def dump_color_array(dataset_dir, data_dir, color_array_info, root=None, compress=True):
    """Dump vtkjs color array."""
    if root is None:
        root = {}
    root['pointData'] = {
        'vtkClass': 'vtkDataSetAttributes',
        "activeGlobalIds": -1,
        "activeNormals": -1,
        "activePedigreeIds": -1,
        "activeScalars": -1,
        "activeTCoords": -1,
        "activeTensors": -1,
        "activeVectors": -1,
        "arrays": [],
    }
    root['cellData'] = {
        'vtkClass': 'vtkDataSetAttributes',
        "activeGlobalIds": -1,
        "activeNormals": -1,
        "activePedigreeIds": -1,
        "activeScalars": -1,
        "activeTCoords": -1,
        "activeTensors": -1,
        "activeVectors": -1,
        "arrays": [],
    }
    root['fieldData'] = {
        'vtkClass': 'vtkDataSetAttributes',
        "activeGlobalIds": -1,
        "activeNormals": -1,
        "activePedigreeIds": -1,
        "activeScalars": -1,
        "activeTCoords": -1,
        "activeTensors": -1,
        "activeVectors": -1,
        "arrays": [],
    }

    colorArray = color_array_info['colorArray']
    location = color_array_info['location']

    dumped_array = dump_data_array(dataset_dir, data_dir, colorArray, {}, compress)

    if dumped_array:
        root[location]['activeScalars'] = 0
        root[location]['arrays'].append({'data': dumped_array})

    return root


# -----------------------------------------------------------------------------


def dump_t_coords(dataset_dir, data_dir, dataset, root=None, compress=True):
    """Dump vtkjs texture coordinates."""
    if root is None:
        root = {}
    tcoords = dataset.GetPointData().GetTCoords()
    if tcoords:
        dumped_array = dump_data_array(dataset_dir, data_dir, tcoords, {}, compress)
        root['pointData']['activeTCoords'] = len(root['pointData']['arrays'])
        root['pointData']['arrays'].append({'data': dumped_array})


# -----------------------------------------------------------------------------


def dump_normals(dataset_dir, data_dir, dataset, root=None, compress=True):
    """Dump vtkjs normal vectors."""
    if root is None:
        root = {}
    normals = dataset.GetPointData().GetNormals()
    if normals:
        dumped_array = dump_data_array(dataset_dir, data_dir, normals, {}, compress)
        root['pointData']['activeNormals'] = len(root['pointData']['arrays'])
        root['pointData']['arrays'].append({'data': dumped_array})


# -----------------------------------------------------------------------------


def dump_all_arrays(dataset_dir, data_dir, dataset, root=None, compress=True):
    """Dump all data arrays to vtkjs."""
    if root is None:
        root = {}
    root['pointData'] = {
        'vtkClass': 'vtkDataSetAttributes',
        "activeGlobalIds": -1,
        "activeNormals": -1,
        "activePedigreeIds": -1,
        "activeScalars": -1,
        "activeTCoords": -1,
        "activeTensors": -1,
        "activeVectors": -1,
        "arrays": [],
    }
    root['cellData'] = {
        'vtkClass': 'vtkDataSetAttributes',
        "activeGlobalIds": -1,
        "activeNormals": -1,
        "activePedigreeIds": -1,
        "activeScalars": -1,
        "activeTCoords": -1,
        "activeTensors": -1,
        "activeVectors": -1,
        "arrays": [],
    }
    root['fieldData'] = {
        'vtkClass': 'vtkDataSetAttributes',
        "activeGlobalIds": -1,
        "activeNormals": -1,
        "activePedigreeIds": -1,
        "activeScalars": -1,
        "activeTCoords": -1,
        "activeTensors": -1,
        "activeVectors": -1,
        "arrays": [],
    }

    # Point data
    pd = dataset.GetPointData()
    pd_size = pd.GetNumberOfArrays()
    for i in range(pd_size):
        array = pd.GetArray(i)
        if array:
            dumped_array = dump_data_array(dataset_dir, data_dir, array, {}, compress)
            root['pointData']['activeScalars'] = 0
            root['pointData']['arrays'].append({'data': dumped_array})

    # Cell data
    cd = dataset.GetCellData()
    cd_size = pd.GetNumberOfArrays()
    for i in range(cd_size):
        array = cd.GetArray(i)
        if array:
            dumped_array = dump_data_array(dataset_dir, data_dir, array, {}, compress)
            root['cellData']['activeScalars'] = 0
            root['cellData']['arrays'].append({'data': dumped_array})

    return root


# -----------------------------------------------------------------------------


def dump_poly_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
    """Dump poly data object to vtkjs."""
    if root is None:
        root = {}
    root['vtkClass'] = 'vtkPolyData'
    container = root

    # Points
    points = dump_data_array(dataset_dir, data_dir, dataset.GetPoints().GetData(), {}, compress)
    points['vtkClass'] = 'vtkPoints'
    container['points'] = points

    # Cells
    _cells = container

    # Verts
    if dataset.GetVerts() and dataset.GetVerts().GetData().GetNumberOfTuples() > 0:
        _verts = dump_data_array(dataset_dir, data_dir, dataset.GetVerts().GetData(), {}, compress)
        _cells['verts'] = _verts
        _cells['verts']['vtkClass'] = 'vtkCellArray'

    # Lines
    if dataset.GetLines() and dataset.GetLines().GetData().GetNumberOfTuples() > 0:
        _lines = dump_data_array(dataset_dir, data_dir, dataset.GetLines().GetData(), {}, compress)
        _cells['lines'] = _lines
        _cells['lines']['vtkClass'] = 'vtkCellArray'

    # Polys
    if dataset.GetPolys() and dataset.GetPolys().GetData().GetNumberOfTuples() > 0:
        _polys = dump_data_array(dataset_dir, data_dir, dataset.GetPolys().GetData(), {}, compress)
        _cells['polys'] = _polys
        _cells['polys']['vtkClass'] = 'vtkCellArray'

    # Strips
    if dataset.GetStrips() and dataset.GetStrips().GetData().GetNumberOfTuples() > 0:
        _strips = dump_data_array(
            dataset_dir, data_dir, dataset.GetStrips().GetData(), {}, compress
        )
        _cells['strips'] = _strips
        _cells['strips']['vtkClass'] = 'vtkCellArray'

    dump_color_array(dataset_dir, data_dir, color_array_info, container, compress)

    # PointData TCoords
    dump_t_coords(dataset_dir, data_dir, dataset, container, compress)
    dump_normals(dataset_dir, data_dir, dataset, container, compress)

    return root


# -----------------------------------------------------------------------------
writer_mapping['vtkPolyData'] = dump_poly_data
# -----------------------------------------------------------------------------


def dump_image_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
    """Dump image data object to vtkjs."""
    if root is None:
        root = {}
    root['vtkClass'] = 'vtkImageData'
    container = root

    container['spacing'] = dataset.GetSpacing()
    container['origin'] = dataset.GetOrigin()
    container['extent'] = dataset.GetExtent()

    dump_all_arrays(dataset_dir, data_dir, dataset, container, compress)

    return root


# -----------------------------------------------------------------------------
writer_mapping['vtkImageData'] = dump_image_data
# -----------------------------------------------------------------------------


def write_data_set(file_path, dataset, output_dir, color_array_info, new_name=None, compress=True):
    """Write dataset to vtkjs."""
    fileName = new_name if new_name else os.path.basename(file_path)
    dataset_dir = os.path.join(output_dir, fileName)
    data_dir = os.path.join(dataset_dir, 'data')

    if not os.path.exists(data_dir):
        os.makedirs(data_dir)

    root = {}
    root['metadata'] = {}
    root['metadata']['name'] = fileName

    writer = writer_mapping[dataset.GetClassName()]
    if writer:
        writer(dataset_dir, data_dir, dataset, color_array_info, root, compress)
    else:
        print(dataset.GetClassName(), 'is not supported')

    with open(os.path.join(dataset_dir, "index.json"), 'w') as f:
        f.write(json.dumps(root, indent=2))

    return dataset_dir


### ----------------------------------------------------------------------- ###
###                          Main script contents                           ###
### ----------------------------------------------------------------------- ###


def mkdir_p(path):
    """Make directory at path."""
    try:
        os.makedirs(path)
    except OSError as exc:  # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise


def export_plotter_vtkjs(plotter, filename, compress_arrays=False):
    """Export a plotter's rendering window to the VTKjs format."""
    arrays = []  # assist in cleaning up references

    # import here to avoid circular imports
    from pyvista import _vtk

    sceneName = os.path.split(filename)[1]
    doCompressArrays = compress_arrays

    # Generate timestamp and use it to make subdirectory within the top level output dir
    timeStamp = time.strftime("%a-%d-%b-%Y-%H-%M-%S")
    root_output_directory = os.path.split(filename)[0]
    output_dir = os.path.join(root_output_directory, timeStamp)
    mkdir_p(output_dir)

    renderers = plotter.render_window.GetRenderers()

    scDirs = []
    sceneComponents = []
    textureToSave = {}

    for rIdx in range(renderers.GetNumberOfItems()):
        renderer = renderers.GetItemAsObject(rIdx)
        renProps = renderer.GetViewProps()
        for rpIdx in range(renProps.GetNumberOfItems()):
            renProp = renProps.GetItemAsObject(rpIdx)
            if not renProp.GetVisibility():
                continue
            if hasattr(renProp, 'GetMapper') and renProp.GetMapper() is not None:
                mapper = renProp.GetMapper()
                dataObject = mapper.GetInputDataObject(0, 0)
                dataset = None
                if dataObject is None:
                    continue
                if dataObject.IsA('vtkCompositeDataSet'):
                    if dataObject.GetNumberOfBlocks() == 1:
                        dataset = dataObject.GetBlock(0)
                    else:
                        gf = _vtk.vtkCompositeDataGeometryFilter()
                        gf.SetInputData(dataObject)
                        gf.Update()
                        dataset = gf.GetOutput()
                else:
                    dataset = mapper.GetInputAsDataSet()

                if dataset and not isinstance(dataset, (_vtk.vtkPolyData, _vtk.vtkImageData)):
                    # All data must be PolyData surfaces
                    gf = _vtk.vtkGeometryFilter()
                    gf.SetInputData(dataset)
                    gf.Update()
                    dataset = gf.GetOutputDataObject(0)

                if dataset:  # and dataset.GetPoints(): # NOTE: vtkImageData does not have points
                    componentName = f'data_{rIdx}_{rpIdx}'  # getComponentName(renProp)
                    scalarVisibility = mapper.GetScalarVisibility()
                    # arrayAccessMode = mapper.GetArrayAccessMode()
                    # colorArrayName = mapper.GetArrayName() #TODO: if arrayAccessMode == 1 else mapper.GetArrayId()
                    colorMode = mapper.GetColorMode()
                    scalarMode = mapper.GetScalarMode()
                    lookupTable = mapper.GetLookupTable()

                    dsAttrs = None
                    arrayLocation = ''

                    if scalarVisibility:
                        if scalarMode == 3 or scalarMode == 1:
                            # VTK_SCALAR_MODE_USE_POINT_FIELD_DATA or VTK_SCALAR_MODE_USE_POINT_DATA
                            dsAttrs = dataset.GetPointData()
                            arrayLocation = 'pointData'
                        # VTK_SCALAR_MODE_USE_CELL_FIELD_DATA or VTK_SCALAR_MODE_USE_CELL_DATA
                        elif scalarMode == 4 or scalarMode == 2:
                            dsAttrs = dataset.GetCellData()
                            arrayLocation = 'cellData'

                    colorArray = None
                    dataArray = None

                    if dsAttrs:
                        dataArray = dsAttrs.GetArray(0)  # Force getting the active array

                    if dataArray:
                        # component = -1 => let specific instance get scalar from vector before mapping
                        colorArray = lookupTable.MapScalars(dataArray, colorMode, -1)
                        colorArrayName = '__CustomRGBColorArray__'
                        colorArray.SetName(colorArrayName)
                        colorMode = 0

                        # track arrays for cleanup
                        arrays.append(colorArray)
                    else:
                        colorArrayName = ''

                    color_array_info = {'colorArray': colorArray, 'location': arrayLocation}

                    scDirs.append(
                        write_data_set(
                            '',
                            dataset,
                            output_dir,
                            color_array_info,
                            new_name=componentName,
                            compress=doCompressArrays,
                        )
                    )

                    # Handle texture if any
                    textureName = None
                    if renProp.GetTexture() and renProp.GetTexture().GetInput():
                        textureData = renProp.GetTexture().GetInput()
                        textureName = f'texture_{get_object_id(textureData)}'
                        textureToSave[textureName] = textureData

                    representation = (
                        renProp.GetProperty().GetRepresentation()
                        if hasattr(renProp, 'GetProperty')
                        else 2
                    )
                    colorToUse = (
                        renProp.GetProperty().GetDiffuseColor()
                        if hasattr(renProp, 'GetProperty')
                        else [1.0, 1.0, 1.0]
                    )
                    if representation == 1:
                        colorToUse = (
                            renProp.GetProperty().GetColor()
                            if hasattr(renProp, 'GetProperty')
                            else [1.0, 1.0, 1.0]
                        )
                    pointSize = (
                        renProp.GetProperty().GetPointSize()
                        if hasattr(renProp, 'GetProperty')
                        else 1.0
                    )
                    opacity = (
                        renProp.GetProperty().GetOpacity()
                        if hasattr(renProp, 'GetProperty')
                        else 1.0
                    )
                    edgeVisibility = (
                        renProp.GetProperty().GetEdgeVisibility()
                        if hasattr(renProp, 'GetProperty')
                        else False
                    )

                    p3dPosition = renProp.GetPosition() if renProp.IsA('vtkProp3D') else [0, 0, 0]
                    p3dScale = renProp.GetScale() if renProp.IsA('vtkProp3D') else [1, 1, 1]
                    p3dOrigin = renProp.GetOrigin() if renProp.IsA('vtkProp3D') else [0, 0, 0]
                    p3dRotateWXYZ = (
                        renProp.GetOrientationWXYZ() if renProp.IsA('vtkProp3D') else [0, 0, 0, 0]
                    )

                    sceneComponents.append(
                        {
                            "name": componentName,
                            "type": "httpDataSetReader",
                            "httpDataSetReader": {"url": componentName},
                            "actor": {
                                "origin": p3dOrigin,
                                "scale": p3dScale,
                                "position": p3dPosition,
                            },
                            "actorRotation": p3dRotateWXYZ,
                            "mapper": {
                                "colorByArrayName": colorArrayName,
                                "colorMode": colorMode,
                                "scalarMode": scalarMode,
                            },
                            "property": {
                                "representation": representation,
                                "edgeVisibility": edgeVisibility,
                                "diffuseColor": colorToUse,
                                "pointSize": pointSize,
                                "opacity": opacity,
                            },
                            "lookupTable": {
                                "tableRange": lookupTable.GetRange(),
                                "hueRange": lookupTable.GetHueRange()
                                if hasattr(lookupTable, 'GetHueRange')
                                else [0.5, 0],
                            },
                        }
                    )

                    if textureName:
                        sceneComponents[-1]['texture'] = textureName

    # Save texture data if any
    for key, val in textureToSave.items():
        write_data_set('', val, output_dir, None, new_name=key, compress=doCompressArrays)

    cameraClippingRange = plotter.camera.clipping_range

    sceneDescription = {
        "fetchGzip": doCompressArrays,
        "background": plotter.background_color.float_rgb,
        "camera": {
            "focalPoint": plotter.camera.focal_point,
            "position": plotter.camera.position,
            "viewUp": plotter.camera.up,
            "clippingRange": [elt for elt in cameraClippingRange],
        },
        "centerOfRotation": plotter.camera.focal_point,
        "scene": sceneComponents,
    }

    indexFilePath = os.path.join(output_dir, 'index.json')
    with open(indexFilePath, 'w') as outfile:
        json.dump(sceneDescription, outfile, indent=4)

    # -----------------------------------------------------------------------------

    # Now zip up the results and get rid of the temp directory
    sceneFileName = os.path.join(root_output_directory, f'{sceneName}{FILENAME_EXTENSION}')

    try:
        import zlib  # noqa

        compression = zipfile.ZIP_DEFLATED
    except:  # noqa: E722
        compression = zipfile.ZIP_STORED

    zf = zipfile.ZipFile(sceneFileName, mode='w')

    try:
        for dirName, _, fileList in os.walk(output_dir):
            for fname in fileList:
                fullPath = os.path.join(dirName, fname)
                relPath = f'{sceneName}/{os.path.relpath(fullPath, output_dir)}'
                zf.write(fullPath, arcname=relPath, compress_type=compression)
    finally:
        zf.close()

    shutil.rmtree(output_dir)

    # this must occur to avoid leaks
    scDirs.clear()
    for array in arrays:
        array.SetReferenceCount(0)


def convert_dropbox_url(url):
    """Convert dropbox url to direct download link."""
    return url.replace("https://www.dropbox.com", "https://dl.dropbox.com")


def generate_viewer_url(dataURL):
    """Generate viewer url with data link."""
    viewerURL = "http://viewer.pyvista.org/"
    return viewerURL + f'?fileURL={dataURL}'


def get_vtkjs_url(*args):
    """Provide shareable link from the vtkjs script.

    After using ``export_vtkjs()`` to create a ``.vtkjs`` file from a
    data scene which is uploaded to an online file hosting service like Dropbox,
    use this method to get a shareable link to that scene on the
    `PVGeo VTKjs viewer`_.

    .. _PVGeo VTKjs viewer: http://viewer.pyvista.org

    **Current file hosts supported:**

    - Dropbox

    Args
    ----
        host (str): the name of the file hosting service.
        inURL (str): the web URL to the ``.vtkjs`` file.

    """
    if len(args) == 1:
        host = 'dropbox'
        inURL = args[0]
    elif len(args) == 2:
        host = args[0]
        inURL = args[1]
    else:
        raise TypeError('Arguments not understood.')
    if host.lower() == "dropbox":
        convertURL = convert_dropbox_url(inURL)
    else:
        print(
            "--> Warning: Web host not specified or supported. URL is simply appended to standalone scene loader link."
        )
        convertURL = inURL
    # print("--> Your link: %s" % generate_viewer_url(convertURL))
    return generate_viewer_url(convertURL)


# pyvista/plotting/helpers.py

"""This module contains some convenience helper functions."""

from typing import Tuple

import numpy as np

import pyvista
from pyvista.utilities import is_pyvista_dataset


def plot(
    var_item,
    off_screen=None,
    full_screen=None,
    screenshot=None,
    interactive=True,
    cpos=None,
    window_size=None,
    show_bounds=False,
    show_axes=None,
    notebook=None,
    background=None,
    text='',
    return_img=False,
    eye_dome_lighting=False,
    volume=False,
    parallel_projection=False,
    jupyter_backend=None,
    return_viewer=False,
    return_cpos=False,
    jupyter_kwargs=None,
    theme=None,
    hidden_line_removal=None,
    anti_aliasing=None,
    zoom=None,
    border=False,
    border_color='k',
    border_width=2.0,
    ssao=False,
    **kwargs,
):
    """Plot a PyVista, numpy, or vtk object.

    Parameters
    ----------
    var_item : pyvista.DataSet
        See :func:`Plotter.add_mesh <pyvista.Plotter.add_mesh>` for all
        supported types.

    off_screen : bool, optional
        Plots off screen when ``True``.  Helpful for saving
        screenshots without a window popping up.  Defaults to the
        global setting ``pyvista.OFF_SCREEN``.

    full_screen : bool, default: :attr:`pyvista.themes.DefaultTheme.full_screen`
        Opens window in full screen.  When enabled, ignores
        ``window_size``.

    screenshot : str or bool, optional
        Saves screenshot to file when enabled.  See:
        :func:`Plotter.screenshot() <pyvista.Plotter.screenshot>`.
        Default ``False``.

        When ``True``, takes screenshot and returns ``numpy`` array of
        image.

    interactive : bool, default: :attr:`pyvista.themes.DefaultTheme.interactive`
        Allows user to pan and move figure.

    cpos : list, optional
        List of camera position, focal point, and view up.

    window_size : sequence, default: :attr:`pyvista.themes.DefaultTheme.window_size`
        Window size in pixels.

    show_bounds : bool, default: False
        Shows mesh bounds when ``True``.

    show_axes : bool, default: :attr:`pyvista.themes._AxesConfig.show`
        Shows a vtk axes widget.

    notebook : bool, default: :attr:`pyvista.themes.DefaultTheme.notebook`
        When ``True``, the resulting plot is placed inline a jupyter
        notebook.  Assumes a jupyter console is active.

    background : ColorLike, default: :attr:`pyvista.themes.DefaultTheme.background`
        Color of the background.

    text : str, optional
        Adds text at the bottom of the plot.

    return_img : bool, default: False
        Returns numpy array of the last image rendered.

    eye_dome_lighting : bool, optional
        Enables eye dome lighting.

    volume : bool, default: False
        Use the :func:`Plotter.add_volume()
        <pyvista.Plotter.add_volume>` method for volume rendering.

    parallel_projection : bool, default: False
        Enable parallel projection.

    jupyter_backend : str, default: :attr:`pyvista.themes.DefaultTheme.jupyter_backend`
        Jupyter notebook plotting backend to use.  One of the
        following:

        * ``'none'`` : Do not display in the notebook.
        * ``'static'`` : Display a static figure.
        * ``'ipygany'`` : Show a ``ipygany`` widget
        * ``'panel'`` : Show a ``panel`` widget.
        * ``'trame'`` : Display using ``trame``.

        This can also be set globally with
        :func:`pyvista.set_jupyter_backend`.

    return_viewer : bool, default: False
        Return the jupyterlab viewer, scene, or display object
        when plotting with jupyter notebook.

    return_cpos : bool, default: False
        Return the last camera position from the render window
        when enabled.  Defaults to value in theme settings.

    jupyter_kwargs : dict, optional
        Keyword arguments for the Jupyter notebook plotting backend.

    theme : pyvista.themes.DefaultTheme, optional
        Plot-specific theme.

    hidden_line_removal : bool, default: :attr:`pyvista.themes.DefaultTheme.hidden_line_removal`
        Wireframe geometry will be drawn using hidden line removal if
        the rendering engine supports it.  See
        :func:`Plotter.enable_hidden_line_removal
        <Plotter.enable_hidden_line_removal>`.

    anti_aliasing : bool, default: :attr:`pyvista.themes.DefaultTheme.anti_aliasing`
        Enable or disable anti-aliasing.

    zoom : float, str, optional
        Camera zoom.  Either ``'tight'`` or a float. A value greater than 1
        is a zoom-in, a value less than 1 is a zoom-out.  Must be greater
        than 0.

    border : bool, default: False
        Draw a border around each render window.

    border_color : ColorLike, default: "k"
        Either a string, rgb list, or hex color string.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

    border_width : float, default: 2.0
        Width of the border in pixels when enabled.

    ssao : bool, optional
        Enable surface space ambient occlusion (SSAO). See
        :func:`Plotter.enable_ssao` for more details.

    **kwargs : dict, optional
        See :func:`pyvista.Plotter.add_mesh` for additional options.

    Returns
    -------
    cpos : list
        List of camera position, focal point, and view up.
        Returned only when ``return_cpos=True`` or set in the
        default global or plot theme.  Not returned when in a
        jupyter notebook and ``return_viewer=True``.

    image : np.ndarray
        Numpy array of the last image when either ``return_img=True``
        or ``screenshot=True`` is set. Not returned when in a
        jupyter notebook with ``return_viewer=True``. Optionally
        contains alpha values. Sized:

        * [Window height x Window width x 3] if the theme sets
          ``transparent_background=False``.
        * [Window height x Window width x 4] if the theme sets
          ``transparent_background=True``.

    widget : ipywidgets.Widget
        IPython widget when ``return_viewer=True``.

    Examples
    --------
    Plot a simple sphere while showing its edges.

    >>> import pyvista as pv
    >>> mesh = pv.Sphere()
    >>> mesh.plot(show_edges=True)

    Plot a volume mesh. Color by distance from the center of the
    UniformGrid. Note ``volume=True`` is passed.

    >>> import numpy as np
    >>> grid = pv.UniformGrid(
    ...     dimensions=(32, 32, 32), spacing=(0.5, 0.5, 0.5)
    ... )
    >>> grid['data'] = np.linalg.norm(grid.center - grid.points, axis=1)
    >>> grid['data'] = np.abs(grid['data'] - grid['data'].max()) ** 3
    >>> grid.plot(volume=True)

    """
    if jupyter_kwargs is None:
        jupyter_kwargs = {}

    # undocumented kwarg used within pytest to run a function before closing
    before_close_callback = kwargs.pop('before_close_callback', None)

    # pop from kwargs here to avoid including them in add_mesh or add_volume
    eye_dome_lighting = kwargs.pop("edl", eye_dome_lighting)
    show_grid = kwargs.pop('show_grid', False)
    auto_close = kwargs.get('auto_close')

    pl = pyvista.Plotter(
        window_size=window_size,
        off_screen=off_screen,
        notebook=notebook,
        theme=theme,
        border=border,
        border_color=border_color,
        border_width=border_width,
    )

    if show_axes is None:
        show_axes = pl.theme.axes.show
    if show_axes:
        pl.add_axes()
    if anti_aliasing:
        pl.enable_anti_aliasing()

    pl.set_background(background)

    if isinstance(var_item, list):
        if len(var_item) == 2:  # might be arrows
            isarr_0 = isinstance(var_item[0], np.ndarray)
            isarr_1 = isinstance(var_item[1], np.ndarray)
            if isarr_0 and isarr_1:
                pl.add_arrows(var_item[0], var_item[1])
            else:
                for item in var_item:
                    if volume or (isinstance(item, np.ndarray) and item.ndim == 3):
                        pl.add_volume(item, **kwargs)
                    else:
                        pl.add_mesh(item, **kwargs)
        else:
            for item in var_item:
                if volume or (isinstance(item, np.ndarray) and item.ndim == 3):
                    pl.add_volume(item, **kwargs)
                else:
                    pl.add_mesh(item, **kwargs)
    else:
        if volume or (isinstance(var_item, np.ndarray) and var_item.ndim == 3):
            pl.add_volume(var_item, **kwargs)
        elif isinstance(var_item, pyvista.MultiBlock):
            pl.add_composite(var_item, **kwargs)
        else:
            pl.add_mesh(var_item, **kwargs)

    if text:
        pl.add_text(text)

    if show_grid:
        pl.show_grid()
    elif show_bounds:
        pl.show_bounds()

    if cpos is None:
        cpos = pl.get_default_cam_pos()
        pl.camera_position = cpos
        pl.camera_set = False
    else:
        pl.camera_position = cpos

    if eye_dome_lighting:
        pl.enable_eye_dome_lighting()

    if parallel_projection:
        pl.enable_parallel_projection()

    if ssao:
        pl.enable_ssao()

    if zoom is not None:
        pl.camera.zoom(zoom)

    return pl.show(
        auto_close=auto_close,
        interactive=interactive,
        full_screen=full_screen,
        screenshot=screenshot,
        return_img=return_img,
        jupyter_backend=jupyter_backend,
        before_close_callback=before_close_callback,
        jupyter_kwargs=jupyter_kwargs,
        return_viewer=return_viewer,
        return_cpos=return_cpos,
    )


def plot_arrows(cent, direction, **kwargs):
    """Plot arrows as vectors.

    Parameters
    ----------
    cent : array_like[float]
        Accepts a single 3d point or array of 3d points.

    direction : array_like[float]
        Accepts a single 3d point or array of 3d vectors.
        Must contain the same number of items as ``cent``.

    **kwargs : dict, optional
        See :func:`pyvista.plot`.

    Returns
    -------
    tuple
        See the returns of :func:`pyvista.plot`.

    See Also
    --------
    pyvista.plot

    Examples
    --------
    Plot a single random arrow.

    >>> import numpy as np
    >>> import pyvista
    >>> cent = np.random.random(3)
    >>> direction = np.random.random(3)
    >>> pyvista.plot_arrows(cent, direction)

    Plot 100 random arrows.

    >>> import numpy as np
    >>> import pyvista
    >>> cent = np.random.random((100, 3))
    >>> direction = np.random.random((100, 3))
    >>> pyvista.plot_arrows(cent, direction)

    """
    return plot([cent, direction], **kwargs)


def plot_compare_four(
    data_a,
    data_b,
    data_c,
    data_d,
    disply_kwargs=None,
    plotter_kwargs=None,
    show_kwargs=None,
    screenshot=None,
    camera_position=None,
    outline=None,
    outline_color='k',
    labels=('A', 'B', 'C', 'D'),
    link=True,
    notebook=None,
):
    """Plot a 2 by 2 comparison of data objects.

    Plotting parameters and camera positions will all be the same.

    """
    datasets = [[data_a, data_b], [data_c, data_d]]
    labels = [labels[0:2], labels[2:4]]

    if plotter_kwargs is None:
        plotter_kwargs = {}
    if disply_kwargs is None:
        disply_kwargs = {}
    if show_kwargs is None:
        show_kwargs = {}

    plotter_kwargs['notebook'] = notebook

    pl = pyvista.Plotter(shape=(2, 2), **plotter_kwargs)

    for i in range(2):
        for j in range(2):
            pl.subplot(i, j)
            pl.add_mesh(datasets[i][j], **disply_kwargs)
            pl.add_text(labels[i][j])
            if is_pyvista_dataset(outline):
                pl.add_mesh(outline, color=outline_color)
            if camera_position is not None:
                pl.camera_position = camera_position

    if link:
        pl.link_views()
        # when linked, camera must be reset such that the view range
        # of all subrender windows matches
        pl.reset_camera()

    return pl.show(screenshot=screenshot, **show_kwargs)


def view_vectors(view: str, negative: bool = False) -> Tuple[np.ndarray, np.ndarray]:
    """Given a plane to view, return vectors for setting up camera.

    Parameters
    ----------
    view : {'xy', 'yx', 'xz', 'zx', 'yz', 'zy'}
        Plane to return vectors for.

    negative : bool, default: False
        Whether to view from opposite direction.

    Returns
    -------
    vec : numpy.ndarray
        ``[x, y, z]`` vector that points in the viewing direction

    viewup : numpy.ndarray
        ``[x, y, z]`` vector that points to the viewup direction

    """
    if view == 'xy':
        vec = np.array([0, 0, 1])
        viewup = np.array([0, 1, 0])
    elif view == 'yx':
        vec = np.array([0, 0, -1])
        viewup = np.array([1, 0, 0])
    elif view == 'xz':
        vec = np.array([0, -1, 0])
        viewup = np.array([0, 0, 1])
    elif view == 'zx':
        vec = np.array([0, 1, 0])
        viewup = np.array([1, 0, 0])
    elif view == 'yz':
        vec = np.array([1, 0, 0])
        viewup = np.array([0, 0, 1])
    elif view == 'zy':
        vec = np.array([-1, 0, 0])
        viewup = np.array([0, 1, 0])
    else:
        raise ValueError(
            f"Unexpected value for direction {view}\n"
            "    Expected: 'xy', 'yx', 'xz', 'zx', 'yz', 'zy'"
        )

    if negative:
        vec *= -1
    return vec, viewup


# pyvista/plotting/lights.py

"""Module containing pyvista implementation of vtk.vtkLight."""

from enum import IntEnum

import numpy as np

# imports here rather than in _vtk to avoid circular imports
try:
    from vtkmodules.vtkCommonMath import vtkMatrix4x4
    from vtkmodules.vtkRenderingCore import vtkLight, vtkLightActor
except ImportError:  # pragma: no cover
    from vtk import vtkLight, vtkLightActor, vtkMatrix4x4

from ..utilities.helpers import vtkmatrix_from_array
from .colors import Color, ColorLike


class LightType(IntEnum):
    """An enumeration for the light types."""

    HEADLIGHT = 1
    CAMERA_LIGHT = 2
    SCENE_LIGHT = 3

    def __str__(self):
        """Pretty name for a light type."""
        return self.name.replace('_', ' ').title()


class Light(vtkLight):
    """Light class.

    Parameters
    ----------
    position : sequence[float], optional
        The position of the light. The interpretation of the position
        depends on the type of the light and whether the light has a
        transformation matrix.  See also the :py:attr:`position`
        property.

    focal_point : sequence[float], optional
        The focal point of the light. The interpretation of the focal
        point depends on the type of the light and whether the light
        has a transformation matrix.  See also the
        :py:attr:`focal_point` property.

    color : ColorLike, optional
        The color of the light. The ambient, diffuse and specular
        colors will all be set to this color on creation.

    light_type : str | int, default: 'scene light'
        The type of the light. If a string, one of ``'headlight'``,
        ``'camera light'`` or ``'scene light'``. If an int, one of 1,
        2 or 3, respectively. The class constants ``Light.HEADLIGHT``,
        ``Light.CAMERA_LIGHT`` and ``Light.SCENE_LIGHT`` are also
        available, respectively.

            - A headlight is attached to the camera, looking at its
              focal point along the axis of the camera.

            - A camera light also moves with the camera, but it can
              occupy a general position with respect to it.

            - A scene light is stationary with respect to the scene,
              as it does not follow the camera. This is the default.

    intensity : float, optional
        The brightness of the light (between 0 and 1).

    positional : bool, optional
        Set if the light is positional.

        The default is a directional light, i.e. an infinitely distant
        point source. A positional light with a cone angle of at least
        90 degrees acts like a spherical point source. A positional
        light with a cone angle that is less than 90 degrees is known
        as a spotlight.

    cone_angle : float, optional
        Cone angle of a positional light in degrees.

    show_actor : bool, default: False
        Show an actor for a spotlight that depicts the geometry of the
        beam.

    exponent : float, optional
        The exponent of the cosine used for spotlights. See also the
        :py:attr:`exponent` property.

    shadow_attenuation : float, optional
        The value of shadow attenuation.

        By default a light will be completely blocked when in shadow.
        By setting this value to less than 1.0 you can control how
        much light is attenuated when in shadow. Note that changing
        the :py:attr:`attenuation_values` of the light can make it pass
        through objects even if its shadow attenuation is 1.

    attenuation_values : sequence, optional
        Quadratic attenuation constants.

        The values are a 3-length sequence which specifies the constant,
        linear and quadratic constants in this order. These parameters
        only have an effect for positional lights.

    Examples
    --------
    Create a light at (10, 10, 10) and set its diffuse color to red.

    >>> import pyvista as pv
    >>> light = pv.Light(position=(10, 10, 10))
    >>> light.diffuse_color = 1.0, 0.0, 0.0

    Create a positional light at (0, 0, 3) with a cone angle of
    30, exponent of 20, and a visible actor.

    >>> light = pv.Light(
    ...     position=(0, 0, 3),
    ...     show_actor=True,
    ...     positional=True,
    ...     cone_angle=30,
    ...     exponent=20,
    ... )

    """

    # pull in light type enum values as class constants
    HEADLIGHT = LightType.HEADLIGHT
    CAMERA_LIGHT = LightType.CAMERA_LIGHT
    SCENE_LIGHT = LightType.SCENE_LIGHT

    def __init__(
        self,
        position=None,
        focal_point=None,
        color=None,
        light_type='scene light',
        intensity=None,
        positional=None,
        cone_angle=None,
        show_actor=False,
        exponent=None,
        shadow_attenuation=None,
        attenuation_values=None,
    ):
        """Initialize the light."""
        super().__init__()
        self._renderers = []
        self.actor = None

        if position is not None:
            self.position = position
        if focal_point is not None:
            self.focal_point = focal_point

        if color is not None:
            self.ambient_color = color
            self.diffuse_color = color
            self.specular_color = color

        if isinstance(light_type, str):
            # be forgiving: ignore spaces and case
            light_type_orig = light_type
            type_normalized = light_type.replace(' ', '').lower()
            mapping = {
                'headlight': LightType.HEADLIGHT,
                'cameralight': LightType.CAMERA_LIGHT,
                'scenelight': LightType.SCENE_LIGHT,
            }
            try:
                light_type = mapping[type_normalized]
            except KeyError:
                light_keys = ', '.join(mapping)
                msg = (
                    f'Invalid light_type "{light_type_orig}"\n'
                    f'Choose from one of the following: {light_keys}'
                )
                raise ValueError(msg) from None
        elif not isinstance(light_type, int):
            raise TypeError(
                f'Parameter light_type must be int or str, not {type(light_type).__name__}.'
            )
        # LightType is an int subclass

        self.light_type = light_type

        if intensity is not None:
            self.intensity = intensity

        if cone_angle is not None:
            self.cone_angle = cone_angle

        if exponent is not None:
            self.exponent = exponent

        if positional is not None:
            self.positional = positional

        if shadow_attenuation is not None:
            self.shadow_attenuation = shadow_attenuation

        if attenuation_values is not None:
            self.attenuation_values = attenuation_values

        # Add the light actor
        self.actor = vtkLightActor()
        self.actor.SetLight(self)
        self.actor.SetVisibility(show_actor)

    def __repr__(self):
        """Print a repr specifying the id of the light and its light type."""
        return f'<{self.__class__.__name__} ({self.light_type}) at {hex(id(self))}>'

    def __eq__(self, other):
        """Compare whether the relevant attributes of two lights are equal."""
        # attributes which are native python types and thus implement __eq__
        native_attrs = [
            'light_type',
            'position',
            'focal_point',
            'ambient_color',
            'diffuse_color',
            'specular_color',
            'intensity',
            'on',
            'positional',
            'exponent',
            'cone_angle',
            'attenuation_values',
            'shadow_attenuation',
        ]
        for attr in native_attrs:
            if getattr(self, attr) != getattr(other, attr):
                return False

        # check transformation matrix element by element (if it exists)
        this_trans = self.transform_matrix
        that_trans = other.transform_matrix
        trans_count = sum(1 for trans in [this_trans, that_trans] if trans is not None)
        if trans_count == 1:
            # either but not both are None
            return False
        if trans_count == 2:
            for i in range(4):
                for j in range(4):
                    if this_trans.GetElement(i, j) != that_trans.GetElement(i, j):
                        return False
        return True

    def __del__(self):
        """Clean up when the light is being destroyed."""
        self.actor = None
        self._renderers.clear()

    @property
    def shadow_attenuation(self):
        """Return or set the value of shadow attenuation.

        By default a light will be completely blocked when in shadow.
        By setting this value to less than 1.0 you can control how
        much light is attenuated when in shadow. Note that changing
        the :py:attr:`attenuation_values` of the light can make it pass
        through objects even if its shadow attenuation is 1.

        Examples
        --------
        Set the shadow attenuation to 0.5

        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.shadow_attenuation = 0.5
        >>> light.shadow_attenuation
        0.5

        """
        return self.GetShadowAttenuation()

    @shadow_attenuation.setter
    def shadow_attenuation(self, value):
        """Set the shadow intensity."""
        self.SetShadowAttenuation(value)

    @property
    def ambient_color(self):
        """Return or set the ambient color of the light.

        When setting, the color must be a 3-length sequence or a string.
        For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        Examples
        --------
        Create a light and set its ambient color to red.

        >>> import pyvista
        >>> light = pyvista.Light()
        >>> light.ambient_color = 'red'
        >>> light.ambient_color
        Color(name='red', hex='#ff0000ff', opacity=255)

        """
        return Color(self.GetAmbientColor())

    @ambient_color.setter
    def ambient_color(self, color: ColorLike):
        """Set the ambient color of the light."""
        self.SetAmbientColor(Color(color).float_rgb)

    @property
    def diffuse_color(self):
        """Return or set the diffuse color of the light.

        When setting, the color must be a 3-length sequence or a string.
        For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        Examples
        --------
        Create a light and set its diffuse color to blue.

        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.diffuse_color = (0.0, 0.0, 1.0)
        >>> light.diffuse_color
        Color(name='blue', hex='#0000ffff', opacity=255)

        """
        return Color(self.GetDiffuseColor())

    @diffuse_color.setter
    def diffuse_color(self, color: ColorLike):
        """Set the diffuse color of the light."""
        self.SetDiffuseColor(Color(color).float_rgb)

    @property
    def specular_color(self):
        """Return or set the specular color of the light.

        When setting, the color must be a 3-length sequence or a string.
        For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        Examples
        --------
        Create a light and set its specular color to bright green.

        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.specular_color = '#00FF00'
        >>> light.specular_color
        Color(name='lime', hex='#00ff00ff', opacity=255)

        """
        return Color(self.GetSpecularColor())

    @specular_color.setter
    def specular_color(self, color: ColorLike):
        """Set the specular color of the light."""
        self.SetSpecularColor(Color(color).float_rgb)

    @property
    def position(self):
        """Return the position of the light.

        Note: the position is defined in the coordinate space
        indicated by the light's transformation matrix (if it
        exists). To get the light's world space position, use the
        (read-only) :py:attr:`world_position` property.

        Examples
        --------
        Create a light positioned at ``(10, 10, 10)`` after
        initialization, and note how the position is unaffected by a
        non-trivial transform matrix.

        >>> import numpy as np
        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.position = (10, 10, 10)
        >>> # set a "random" transformation matrix
        >>> light.transform_matrix = np.arange(4 * 4).reshape(4, 4)
        >>> light.position
        (10.0, 10.0, 10.0)

        """
        return self.GetPosition()

    @position.setter
    def position(self, pos):
        """Set the position of the light."""
        self.SetPosition(pos)

    @property
    def world_position(self):
        """Return the world space position of the light.

        The world space position is the :py:attr:`position` property
        transformed by the light's transform matrix if it exists. The
        value of this read-only property corresponds to the
        ``vtk.vtkLight.GetTransformedPosition()`` method.

        Examples
        --------
        Create a light with a transformation matrix that corresponds to a
        90-degree rotation around the z axis and a shift by (0, 0, -1), and
        check that the light's position transforms as expected.

        >>> import numpy as np
        >>> import pyvista as pv
        >>> light = pv.Light(position=(1, 0, 3))
        >>> trans = np.zeros((4, 4))
        >>> trans[:-1, :-1] = [[0, -1, 0], [1, 0, 0], [0, 0, 1]]
        >>> trans[:-1, -1] = [0, 0, -1]
        >>> light.transform_matrix = trans
        >>> light.position
        (1.0, 0.0, 3.0)
        >>> light.world_position
        (0.0, 1.0, 2.0)

        """
        return self.GetTransformedPosition()

    @property
    def focal_point(self):
        """Return the focal point of the light.

        Note: the focal point is defined in the coordinate space
        indicated by the light's transformation matrix (if it
        exists). To get the light's world space focal point, use the
        (read-only) :py:attr:`world_focal_point` property.

        Examples
        --------
        Create a light at (10, 10, 10) shining at (0, 0, 1).

        >>> import pyvista as pv
        >>> light = pv.Light(position=(10, 10, 10))
        >>> light.focal_point = (0, 0, 1)

        """
        return self.GetFocalPoint()

    @focal_point.setter
    def focal_point(self, pos):
        """Set the focal point of the light."""
        self.SetFocalPoint(pos)

    @property
    def world_focal_point(self):
        """Return the world space focal point of the light.

        The world space focal point is the :py:attr:`focal_point`
        property transformed by the light's transform matrix if it
        exists. The value of this read-only property corresponds to
        the ``vtk.vtkLight.GetTransformedFocalPoint()`` method.

        Examples
        --------
        Create a light with a transformation matrix that corresponds
        to a 90-degree rotation around the z axis and a shift by (0,
        0, -1), and check that the light's focal point transforms as
        expected.

        >>> import numpy as np
        >>> import pyvista as pv
        >>> light = pv.Light(focal_point=(1, 0, 3))
        >>> trans = np.zeros((4, 4))
        >>> trans[:-1, :-1] = [[0, -1, 0], [1, 0, 0], [0, 0, 1]]
        >>> trans[:-1, -1] = [0, 0, -1]
        >>> light.transform_matrix = trans
        >>> light.focal_point
        (1.0, 0.0, 3.0)
        >>> light.world_focal_point
        (0.0, 1.0, 2.0)

        """
        return self.GetTransformedFocalPoint()

    @property
    def intensity(self):
        """Return the brightness of the light (between 0 and 1).

        Examples
        --------
        Light the two sides of a cube with lights of different
        brightness.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter(lighting='none')
        >>> _ = plotter.add_mesh(pv.Cube(), color='cyan')
        >>> light_bright = pv.Light(
        ...     position=(3, 0, 0), light_type='scene light'
        ... )
        >>> light_dim = pv.Light(
        ...     position=(0, 3, 0), light_type='scene light'
        ... )
        >>> light_dim.intensity = 0.5
        >>> for light in light_bright, light_dim:
        ...     light.positional = True
        ...     plotter.add_light(light)
        ...
        >>> plotter.show()

        """
        return self.GetIntensity()

    @intensity.setter
    def intensity(self, intensity):
        """Set the brightness of the light (between 0 and 1)."""
        self.SetIntensity(intensity)

    @property
    def on(self):
        """Return whether the light is on.

        This corresponds to the Switch state of the ``vtk.vtkLight`` class.

        Examples
        --------
        Create a light, check if it's on by default, and turn it off.

        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.on
        True
        >>> light.on = False

        """
        return bool(self.GetSwitch())

    @on.setter
    def on(self, state):
        """Set whether the light should be on."""
        self.SetSwitch(state)

    @property
    def positional(self):
        """Return whether the light is positional.

        The default is a directional light, i.e. an infinitely distant
        point source. A positional light with a cone angle of at least
        90 degrees acts like a spherical point source. A positional
        light with a cone angle that is less than 90 degrees is known
        as a spotlight.

        Attenuation and cone angles are only used for positional
        lights.  The :py:attr:`exponent` property is only used for
        spotlights.  Positional lights with a cone angle of at least
        90 degrees don't show angular dependence of their beams, but
        they display attenuation.

        If the light is changed to directional, its actor (if previously
        shown) is automatically hidden.

        Examples
        --------
        Create a spotlight shining on the origin.

        >>> import pyvista as pv
        >>> light = pv.Light(position=(1, 1, 1))
        >>> light.positional = True
        >>> light.cone_angle = 30

        """
        return bool(self.GetPositional())

    @positional.setter
    def positional(self, state):
        """Set whether the light should be positional."""
        if not state:
            self.hide_actor()
        self.SetPositional(state)
        self._check_actor()

    def _check_actor(self):
        """Check if the light actor should be added or removed from attached renderers.

        This should be called whenever positional state or cone angle
        are changed.

        """
        if self.actor is None:
            # only should occur on __init__
            return

        actor_state = self.cone_angle < 90 and self.positional
        actor_name = self.actor.GetAddressAsString("")

        # add or remove the actor from the renderer
        for renderer in self._renderers:
            if actor_state:
                if actor_name not in renderer.actors:
                    renderer.add_actor(self.actor, render=False)
            else:
                if actor_name in renderer.actors:
                    renderer.remove_actor(self.actor, render=False)

    @property
    def exponent(self):
        """Return the exponent of the cosine used for spotlights.

        With a spotlight (a positional light with cone angle less than
        90 degrees) the shape of the light beam within the light cone
        varies with the angle from the light's axis, and the variation
        of the intensity depends as the cosine of this angle raised to
        an exponent, which is 1 by default. Increasing the exponent
        makes the beam sharper (more focused around the axis),
        decreasing it spreads the beam out.

        Note that since the angular dependence defined by this
        property and the truncation performed by the
        :py:attr:`cone_angle` are independent, for spotlights with
        narrow beams (small :py:attr:`cone_angle`) it is harder to see
        the angular variation of the intensity, and a lot higher
        exponent might be necessary to visibly impact the angular
        distribution of the beam.

        Examples
        --------
        Plot three planes lit by three spotlights with exponents of 1,
        2 and 5.  The one with the lowest exponent has the broadest
        beam.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter(lighting='none')
        >>> for offset, exponent in zip([0, 1.5, 3], [1, 2, 5]):
        ...     _ = plotter.add_mesh(
        ...         pv.Plane((offset, 0, 0)), color='white'
        ...     )
        ...     light = pv.Light(
        ...         position=(offset, 0, 0.1),
        ...         focal_point=(offset, 0, 0),
        ...     )
        ...     light.exponent = exponent
        ...     light.positional = True
        ...     light.cone_angle = 80
        ...     plotter.add_light(light)
        ...
        >>> plotter.view_xy()
        >>> plotter.show()

        """
        return self.GetExponent()

    @exponent.setter
    def exponent(self, exp):
        """Set the exponent of the cosine used in positional lighting."""
        self.SetExponent(exp)

    @property
    def cone_angle(self):
        """Return the cone angle of a positional light.

        The angle is in degrees and is measured between the axis of
        the cone and an extremal ray of the cone. A value smaller than
        90 has spot lighting effects, anything equal to and above 90
        is just a positional light, i.e. a spherical point source.

        Regarding the angular distribution of the light, the cone
        angle merely truncates the beam, the shape of which is defined
        by the :py:attr:`exponent`.  If the cone angle is at least 90
        degrees then there is no angular dependence.

        If the light's cone angle is increased to 90 degrees or above,
        its actor (if previously shown) is automatically hidden.

        Examples
        --------
        Plot three planes lit by three spotlights with varying cone
        angles.  Use a large exponent to cause a visible angular
        variation of the intensity of the beams.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter(lighting='none')
        >>> for offset, angle in zip([0, 1.5, 3], [70, 30, 20]):
        ...     _ = plotter.add_mesh(
        ...         pv.Plane((offset, 0, 0)), color='white'
        ...     )
        ...     light = pv.Light(
        ...         position=(offset, 0, 1), focal_point=(offset, 0, 0)
        ...     )
        ...     light.exponent = 15
        ...     light.positional = True
        ...     light.cone_angle = angle
        ...     plotter.add_light(light)
        ...
        >>> plotter.view_xy()
        >>> plotter.show()

        """
        return self.GetConeAngle()

    @cone_angle.setter
    def cone_angle(self, angle):
        """Set the cone angle of a positional light."""
        if angle >= 90:
            self.hide_actor()
        self.SetConeAngle(angle)
        self._check_actor()

    @property
    def attenuation_values(self):
        """Return the quadratic attenuation constants.

        The values are 3-length sequences which specify the constant,
        linear and quadratic constants in this order. These parameters
        only have an effect for positional lights.

        Attenuation refers to the dampening of a beam of light as it
        gets further away from the point source. The three constants
        describe three different profiles for dampening with
        distance. A larger attenuation constant corresponds to more
        rapid decay with distance.

        Examples
        --------
        Plot three cubes lit by two lights with different attenuation
        profiles.  The blue light has slower linear attenuation, the
        green one has quadratic attenuation that makes it decay
        faster. Note that there are no shadow effects included so each
        box gets lit by both lights.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter(lighting='none')
        >>> for offset in 1, 2.5, 4:
        ...     _ = plotter.add_mesh(
        ...         pv.Cube(center=(offset, offset, 0)), color='white'
        ...     )
        ...
        >>> colors = ['b', 'g']
        >>> all_attenuations = [(0, 0.1, 0), (0, 0, 0.1)]
        >>> centers = [(0, 1, 0), (1, 0, 0)]
        >>> for color, attenuation_constants, center in zip(
        ...     colors, all_attenuations, centers
        ... ):
        ...     light = pv.Light(position=center, color=color)
        ...     light.focal_point = (1 + center[0], 1 + center[1], 0)
        ...     light.cone_angle = 90
        ...     light.positional = True
        ...     light.attenuation_values = attenuation_constants
        ...     plotter.add_light(light)
        >>> plotter.view_vector((-1, -1, 1))
        >>> plotter.show()

        """
        return self.GetAttenuationValues()

    @attenuation_values.setter
    def attenuation_values(self, values):
        """Set the quadratic attenuation constants."""
        self.SetAttenuationValues(values)

    @property
    def transform_matrix(self):
        """Return the transformation matrix of the light (if any).

        The transformation matrix is ``None`` by default, and it is
        stored as a ``vtk.vtkMatrix4x4`` object when set. If set, the
        light's parameters (position and focal point) are transformed
        by the matrix before being rendered. See also the
        :py:attr:`world_position` and :py:attr:`world_focal_point`
        read-only properties that can differ from :py:attr:`position`
        and :py:attr:`focal_point`, respectively.

        The 4-by-4 transformation matrix is a tool to encode a general
        linear transformation and a translation (an affine
        transform). The 3-by-3 principal submatrix (the top left
        corner of the matrix) encodes a three-dimensional linear
        transformation (e.g. some rotation around the origin). The top
        three elements in the last column of the matrix encode a
        three-dimensional translation. The last row of the matrix is
        redundant.

        Examples
        --------
        Create a light with a transformation matrix that corresponds
        to a 90-degree rotation around the z axis and a shift by (0,
        0, -1), and check that the light's position transforms as
        expected.

        >>> import numpy as np
        >>> import pyvista as pv
        >>> light = pv.Light(position=(1, 0, 3))
        >>> trans = np.zeros((4, 4))
        >>> trans[:-1, :-1] = [[0, -1, 0], [1, 0, 0], [0, 0, 1]]
        >>> trans[:-1, -1] = [0, 0, -1]
        >>> light.transform_matrix = trans
        >>> light.position
        (1.0, 0.0, 3.0)
        >>> light.world_position
        (0.0, 1.0, 2.0)

        """
        return self.GetTransformMatrix()

    @transform_matrix.setter
    def transform_matrix(self, matrix):
        """Set the 4x4 transformation matrix of the light."""
        if matrix is None or isinstance(matrix, vtkMatrix4x4):
            trans = matrix
        else:
            try:
                trans = vtkmatrix_from_array(matrix)
            except ValueError:
                raise ValueError(
                    'Transformation matrix must be a 4-by-4 matrix or array-like.'
                ) from None
        self.SetTransformMatrix(trans)

    @property
    def light_type(self):
        """Return the light type.

        The default light type is a scene light which lives in world
        coordinate space.

        A headlight is attached to the camera and always points at the
        camera's focal point.

        A camera light also moves with the camera, but it can have an
        arbitrary relative position to the camera. Camera lights are
        defined in a coordinate space where the camera is located at
        (0, 0, 1), looking towards (0, 0, 0) at a distance of 1, with
        up being (0, 1, 0). Camera lights use the transform matrix to
        establish this space, i.e. they have a fixed :py:attr:`position`
        with respect to the camera, and moving the camera only
        affects the :py:attr:`world_position` via changes in the
        :py:attr:`transform_matrix` (and the same goes for the focal
        point).

        The property returns class constant values from an enum:

            - ``Light.HEADLIGHT == 1``
            - ``Light.CAMERA_LIGHT == 2``
            - ``Light.SCENE_LIGHT == 3``

        Examples
        --------
        Check the type of lights for the first two lights of the default
        light kit of plotters.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> lights = plotter.renderer.lights[:2]
        >>> [light.light_type for light in lights]
        [<LightType.HEADLIGHT: 1>, <LightType.CAMERA_LIGHT: 2>]

        Change the light type of the default light kit's headlight to a scene light.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> lights = plotter.renderer.lights[:2]
        >>> lights[0].light_type = pv.Light.SCENE_LIGHT
        >>> [light.light_type for light in lights]
        [<LightType.SCENE_LIGHT: 3>, <LightType.CAMERA_LIGHT: 2>]

        """
        return LightType(self.GetLightType())

    @light_type.setter
    def light_type(self, ltype):
        """Set the light type.

        Either an integer code or a class constant enum value must be used.

        """
        if not isinstance(ltype, int):
            # note that LightType is an int subclass
            raise TypeError(
                f'Light type must be an integer subclass instance, got {ltype} instead.'
            )
        self.SetLightType(ltype)

    @property
    def is_headlight(self):
        """Return whether the light is a headlight.

        Examples
        --------
        Verify that the first light of the default light kit is a headlight.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> lights = plotter.renderer.lights
        >>> [light.is_headlight for light in lights]
        [True, False, False, False, False]

        """
        return bool(self.LightTypeIsHeadlight())

    @property
    def is_camera_light(self):
        """Return whether the light is a camera light.

        Examples
        --------
        Verify that four out of five lights of the default light kit
        are camera lights.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> lights = plotter.renderer.lights
        >>> [light.is_camera_light for light in lights]
        [False, True, True, True, True]

        """
        return bool(self.LightTypeIsCameraLight())

    @property
    def is_scene_light(self):
        """Return whether the light is a scene light.

        Examples
        --------
        Verify that none of the lights of the default light kit are
        scene lights.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> lights = plotter.renderer.lights
        >>> [light.is_scene_light for light in lights]
        [False, False, False, False, False]

        """
        return bool(self.LightTypeIsSceneLight())

    def switch_on(self):
        """Switch on the light.

        Examples
        --------
        Create a light, switch it off and switch it back on again.

        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.on = False
        >>> light.switch_on()

        """
        self.SwitchOn()

    def switch_off(self):
        """Switch off the light.

        Examples
        --------
        Create a light and switch it off.

        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.switch_off()

        """
        self.SwitchOff()

    def set_direction_angle(self, elev, azim):
        """Set the position and focal point of a directional light.

        The light is switched to directional (non-positional). The
        focal point is set to the origin. The position is defined in
        terms of an elevation and an azimuthal angle, both in degrees.

        Note that the equivalent ``vtk.vtkLight.SetDirectionAngle()`` method
        uses a surprising coordinate system where the (x', y', z') axes of
        the method correspond to the (z, x, y) axes of the renderer.
        This method reimplements the functionality in a way that ``elev``
        is the conventional elevation and ``azim`` is the conventional azimuth.
        In particular:

          * ``elev = 0``, ``azim = 0`` is the +x direction
          * ``elev = 0``, ``azim = 90`` is the +y direction
          * ``elev = 90``, ``azim = 0`` is the +z direction

        Parameters
        ----------
        elev : float
            The elevation of the directional light.

        azim : float
            The azimuthal angle of the directional light.

        Examples
        --------
        Create a light that shines on the origin from a 30-degree
        elevation in the xz plane.

        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.set_direction_angle(30, 0)

        """
        self.positional = False
        self.focal_point = (0, 0, 0)
        theta = np.radians(90 - elev)
        phi = np.radians(azim)
        self.position = (np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta))

    def copy(self, deep=True):
        """Return a shallow or a deep copy of the light.

        The only mutable attribute of :class:`pyvista.Light` is the
        transformation matrix (if it exists). Thus asking for a
        shallow copy merely implies that the returned light and the
        original share the transformation matrix instance.

        Parameters
        ----------
        deep : bool, default: True
            Whether to return a deep copy rather than a shallow
            one.

        Returns
        -------
        pyvista.Light
            Copied light.

        Examples
        --------
        Create a light and check that it shares a transformation
        matrix with its shallow copy.

        >>> import pyvista as pv
        >>> light = pv.Light()
        >>> light.transform_matrix = [
        ...     [1, 0, 0, 0],
        ...     [0, 1, 0, 0],
        ...     [0, 0, 1, 0],
        ...     [0, 0, 0, 1],
        ... ]
        >>> shallow_copied = light.copy(deep=False)
        >>> shallow_copied == light
        True
        >>> shallow_copied.transform_matrix is light.transform_matrix
        True

        """
        immutable_attrs = [
            'light_type',
            'position',
            'focal_point',
            'ambient_color',
            'diffuse_color',
            'specular_color',
            'intensity',
            'on',
            'positional',
            'exponent',
            'cone_angle',
            'attenuation_values',
            'shadow_attenuation',
        ]
        new_light = Light()

        for attr in immutable_attrs:
            value = getattr(self, attr)
            setattr(new_light, attr, value)

        if deep and self.transform_matrix is not None:
            new_light.transform_matrix = vtkMatrix4x4()
            new_light.transform_matrix.DeepCopy(self.transform_matrix)
        else:
            new_light.transform_matrix = self.transform_matrix

        # light actors are private, always copy, but copy visibility state as well
        new_light.actor.SetVisibility(self.actor.GetVisibility())

        return new_light

    def set_headlight(self):
        """Set the light to be a headlight.

        Headlights are fixed to the camera and always point to the
        focal point of the camera. Calling this method will reset the
        light's transformation matrix.

        Examples
        --------
        >>> import pyvista
        >>> light = pyvista.Light()
        >>> light.set_headlight()
        >>> light.light_type
        <LightType.HEADLIGHT: 1>

        """
        self.SetLightTypeToHeadlight()

    def set_camera_light(self):
        """Set the light to be a camera light.

        A camera light moves with the camera, but it can have an
        arbitrary relative position to the camera. Camera lights are
        defined in a coordinate space where the camera is located at
        (0, 0, 1), looking towards (0, 0, 0) at a distance of 1, with
        up being (0, 1, 0).  Camera lights use the transformation
        matrix to establish this space.  Calling this method will
        reset the light's transformation matrix.

        Examples
        --------
        >>> import pyvista
        >>> light = pyvista.Light()
        >>> light.set_camera_light()
        >>> light.light_type
        <LightType.CAMERA_LIGHT: 2>

        """
        self.SetLightTypeToCameraLight()

    def set_scene_light(self):
        """Set the light to be a scene light.

        Scene lights are stationary with respect to the scene.
        Calling this method will reset the light's transformation
        matrix.

        Examples
        --------
        >>> import pyvista
        >>> light = pyvista.Light()
        >>> light.set_scene_light()
        >>> light.light_type
        <LightType.SCENE_LIGHT: 3>

        """
        self.SetLightTypeToSceneLight()

    @classmethod
    def from_vtk(cls, vtk_light):
        """Create a light from a ``vtk.vtkLight``, resulting in a copy.

        Parameters
        ----------
        vtk_light : vtk.vtkLight
            The ``vtk.vtkLight`` to be copied.

        """
        if not isinstance(vtk_light, vtkLight):
            raise TypeError(
                f'Expected vtk.vtkLight object, got {type(vtk_light).__name__} instead.'
            )

        light = cls()
        light.light_type = vtk_light.GetLightType()  # resets transformation matrix
        light.position = vtk_light.GetPosition()
        light.focal_point = vtk_light.GetFocalPoint()
        light.ambient_color = vtk_light.GetAmbientColor()
        light.diffuse_color = vtk_light.GetDiffuseColor()
        light.specular_color = vtk_light.GetSpecularColor()
        light.intensity = vtk_light.GetIntensity()
        light.on = vtk_light.GetSwitch()
        light.positional = vtk_light.GetPositional()
        light.exponent = vtk_light.GetExponent()
        light.cone_angle = vtk_light.GetConeAngle()
        light.attenuation_values = vtk_light.GetAttenuationValues()
        trans = vtk_light.GetTransformMatrix()
        light.transform_matrix = trans
        light.shadow_attenuation = vtk_light.GetShadowAttenuation()

        return light

    def show_actor(self):
        """Show an actor for a spotlight that depicts the geometry of the beam.

        For a directional light or a positional light with
        :py:attr:`cone_angle` of at least 90 degrees the method
        doesn't do anything. If the light is changed so that it
        becomes a spotlight, this method has to be called again for
        the actor to show. To hide the actor see :func:`hide_actor`.

        Examples
        --------
        Create a scene containing a cube lit with a cyan spotlight and
        visualize the light using an actor.

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(), color='white')
        >>> for light in plotter.renderer.lights:
        ...     light.intensity /= 5
        ...
        >>> spotlight = pv.Light(position=(-1, 1, 1), color='cyan')
        >>> spotlight.positional = True
        >>> spotlight.cone_angle = 20
        >>> spotlight.intensity = 10
        >>> spotlight.exponent = 40
        >>> spotlight.show_actor()
        >>> plotter.add_light(spotlight)
        >>> plotter.show()

        """
        if not self.positional or self.cone_angle >= 90:
            return
        self.actor.VisibilityOn()

    def hide_actor(self):
        """Hide the actor for a positional light that depicts the geometry of the beam.

        For a directional light the function doesn't do anything.

        Examples
        --------
        >>> import pyvista
        >>> light = pyvista.Light()
        >>> light.hide_actor()

        """
        if not self.positional:
            return
        self.actor.VisibilityOff()

    @property
    def renderers(self):
        """Return the renderers associated with this light."""
        return self._renderers

    def add_renderer(self, renderer):
        """Attach a renderer to this light.

        Parameters
        ----------
        renderer : vtk.vtkRenderer
            Renderer.

        """
        # quick check to avoid adding twice
        if renderer not in self.renderers:
            self.renderers.append(renderer)

        # verify that the renderer has the light actor if applicable
        self._check_actor()


# pyvista/plotting/lookup_table.py

"""Wrap vtkLookupTable."""
from typing import Any, Optional, Tuple, Union

import numpy as np

import pyvista as pv
from pyvista import _vtk
from pyvista.utilities.helpers import convert_array
from pyvista.utilities.misc import no_new_attr

from .._typing import ColorLike
from .colors import Color, get_cmap_safe
from .tools import opacity_transfer_function

RAMP_MAP = {0: 'linear', 1: 's-curve', 2: 'sqrt'}
RAMP_MAP_INV = {k: v for v, k in RAMP_MAP.items()}


class lookup_table_ndarray(np.ndarray):
    """An ndarray which references the owning table and the underlying vtkArray.

    This class is used to ensure that the internal vtkLookupTable updates when
    the values array is updated.

    """

    def __new__(
        cls,
        array,
        table=None,
    ):
        """Allocate the array."""
        obj = convert_array(array).view(cls)
        obj.VTKObject = array

        obj.table = _vtk.vtkWeakReference()
        obj.table.Set(table)

        return obj

    def __array_finalize__(self, obj):
        """Finalize array (associate with parent metadata)."""
        _vtk.VTKArray.__array_finalize__(self, obj)
        if np.shares_memory(self, obj):
            self.table = getattr(obj, 'table', None)
            self.VTKObject = getattr(obj, 'VTKObject', None)
        else:
            self.table = None
            self.VTKObject = None

    def __setitem__(self, key, value):
        """Implement [] set operator.

        When the array is changed it triggers "Modified()" which updates
        all upstream objects, including any render windows holding the
        object.
        """
        super().__setitem__(key, value)
        if self.VTKObject is not None:
            self.VTKObject.Modified()

        # the associated dataset should also be marked as modified
        if self.table is not None and self.table.Get():
            # this creates a new shallow copy and is necessary to update the
            # internal VTK array
            self.table.Get().values = self

    def __array_wrap__(self, out_arr, context=None):
        """Return a numpy scalar if array is 0d.

        See https://github.com/numpy/numpy/issues/5819

        """
        if out_arr.ndim:
            return np.ndarray.__array_wrap__(self, out_arr, context)

        # Match numpy's behavior and return a numpy dtype scalar
        return out_arr[()]

    __getattr__ = _vtk.VTKArray.__getattr__


@no_new_attr
class LookupTable(_vtk.vtkLookupTable):
    """Scalar to RGBA mapping table.

    A lookup table is an array that maps input values to output values. When
    plotting data over a dataset, it is necessary to map those scalars to
    colors (in the RGBA format), and this class provides the functionality to
    do so.

    See `vtkLookupTable
    <https://vtk.org/doc/nightly/html/classvtkLookupTable.html>`_ for more
    details regarding the underlying VTK API.

    Parameters
    ----------
    cmap : str | colors.Colormap, optional
        Color map from ``matplotlib``, ``colorcet``, or ``cmocean``. Either
        ``cmap`` or ``values`` can be set, but not both.

    n_values : int, default: 256
        Number of colors in the color map.

    flip : bool, default: False
        Flip the direction of cmap. Most colormaps allow ``*_r`` suffix to do this
        as well.

    values : array_like[float], optional
        Lookup table values. Either ``values`` or ``cmap`` can be set, but not
        both.

    value_range : tuple, optional
        The range of the brightness of the mapped lookup table. This range is
        only used when creating custom color maps and will be ignored if
        ``cmap`` is set.

    hue_range : tuple, optional
        Lookup table hue range. This range is only used when creating custom
        color maps and will be ignored if ``cmap`` is set.

    alpha_range : tuple, optional
        Lookup table alpha (transparency) range. This range is only used when
        creating custom color maps and will be ignored if ``cmap`` is set.

    scalar_range : tuple, optional
        The range of scalars which will be mapped to colors. Values outside of
        this range will be colored according to
        :attr`LookupTable.below_range_color` and
        :attr`LookupTable.above_range_color`.

    log_scale : bool, optional
        Use a log scale when mapping scalar values.

    nan_color : ColorLike, optional
        Color to render any values that are NANs.

    above_range_color : ColorLike, optional
        Color to render any values above :attr:`LookupTable.scalar_range`.

    below_range_color : ColorLike, optional
        Color to render any values below :attr:`LookupTable.scalar_range`.

    ramp : str, optional
        The shape of the table ramp. This range is only used when creating
        custom color maps and will be ignored if ``cmap`` is set.

    annotations : dict, optional
        A dictionary of annotations. Keys are the float values in the scalars
        range to annotate on the scalar bar and the values are the string
        annotations.

    Examples
    --------
    Plot the lookup table with the default VTK color map.

    >>> import pyvista as pv
    >>> lut = pv.LookupTable()
    >>> lut
    LookupTable (...)
      Table Range:                (0.0, 1.0)
      N Values:                   256
      Above Range Color:          None
      Below Range Color:          None
      NAN Color:                  Color(name='maroon', hex='#800000ff', opacity=255)
      Log Scale:                  False
      Color Map:                  "PyVista Lookup Table"
        Alpha Range:              (1.0, 1.0)
        Hue Range:                (0.0, 0.66667)
        Saturation Range          (1.0, 1.0)
        Value Range               (1.0, 1.0)
        Ramp                      s-curve
    >>> lut.plot()

    Plot the lookup table with the ``'inferno'`` color map.

    >>> import pyvista as pv
    >>> lut = pv.LookupTable('inferno', n_values=32)
    >>> lut
    LookupTable (...)
      Table Range:                (0.0, 1.0)
      N Values:                   32
      Above Range Color:          None
      Below Range Color:          None
      NAN Color:                  Color(name='maroon', hex='#800000ff', opacity=255)
      Log Scale:                  False
      Color Map:                  "inferno"
    >>> lut.plot()

    """

    _nan_color_set = False
    _cmap = None
    _values_manual = False
    _opacity_parm: Tuple[Any, bool, str] = (None, False, 'quadratic')

    def __init__(
        self,
        cmap=None,
        n_values=256,
        flip=False,
        values=None,
        value_range=None,
        hue_range=None,
        alpha_range=None,
        scalar_range=None,
        log_scale=None,
        nan_color=None,
        above_range_color=None,
        below_range_color=None,
        ramp=None,
        annotations=None,
    ):
        """Initialize the lookup table."""
        if cmap is not None and values is not None:
            raise ValueError('Cannot set both `cmap` and `values`.')

        if cmap is not None:
            self.apply_cmap(cmap, n_values=n_values, flip=flip)
        elif values is not None:
            self.values = values
        else:
            self.n_values = n_values
            if value_range is not None:
                self.value_range = value_range
            if hue_range is not None:
                self.hue_range = hue_range
            if alpha_range is not None:
                self.alpha_range = alpha_range
            if ramp is not None:
                self.ramp = ramp

        if nan_color is not None:
            self.nan_color = nan_color
        if above_range_color is not None:
            self.above_range_color = above_range_color
        if below_range_color is not None:
            self.below_range_color = below_range_color
        if scalar_range is not None:
            self.scalar_range = scalar_range
        if log_scale is not None:
            self.log_scale = log_scale
        if annotations is not None:
            self.annotations = annotations

    @property
    def value_range(self) -> Optional[tuple]:
        """Return or set the brightness of the mapped lookup table.

        This range is only used when creating custom color maps and will return
        ``None`` when a color map has been set with :attr:`LookupTable.cmap`.

        This will clear any existing color map and create new values for the
        lookup table when set.

        Examples
        --------
        Show the effect of setting the value range on the default color
        map.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.value_range = (0, 1.0)
        >>> lut.plot()

        Demonstrate a different value range.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.value_range = (0.5, 0.8)
        >>> lut.plot()

        """
        if self._cmap:
            return
        return self.GetValueRange()

    @value_range.setter
    def value_range(self, value: tuple):
        self.SetValueRange(value)
        self.rebuild()

    @property
    def hue_range(self) -> Optional[tuple]:
        """Return or set the hue range.

        This range is only used when creating custom color maps and will return
        ``None`` when a color map has been set with :attr:`LookupTable.cmap`.

        This will clear any existing color map and create new values for the
        lookup table when set.

        Examples
        --------
        Set the hue range. This allows you to create a lookup table
        without setting a color map.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.hue_range = (0, 0.1)
        >>> lut.plot()

        Create a different color map.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.hue_range = (0.5, 0.8)
        >>> lut.plot()

        """
        if self._cmap:
            return
        return self.GetHueRange()

    @hue_range.setter
    def hue_range(self, value: tuple):
        self.SetHueRange(value)
        self.rebuild()

    @property
    def cmap(self) -> Optional[str]:
        """Return or set the color map used by this lookup table.

        Examples
        --------
        Apply the single Matplotlib color map ``"Oranges"``.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.cmap = 'Oranges'
        >>> lut.plot()

        Apply a list of colors as a colormap.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.cmap = ['black', 'red', 'orange']
        >>> lut.plot()

        """
        return self._cmap

    @cmap.setter
    def cmap(self, value):
        self.apply_cmap(value, self.n_values)

    @property
    def log_scale(self) -> bool:
        """Use log scale.

        When ``True`` the lookup table is a log scale to
        :attr:`LookupTable.scalar_range`. Otherwise, it is linear scale.

        Examples
        --------
        Use log scale for the lookup table.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.log_scale = True
        >>> lut.scalar_range = (1, 100)
        >>> lut.plot()

        """
        return bool(self.GetScale())

    @log_scale.setter
    def log_scale(self, value: bool):
        self.SetScale(value)

    def __repr__(self):
        """Return the representation."""
        lines = [f'{type(self).__name__} ({hex(id(self))})']
        lines.append(f'  Table Range:                {self.scalar_range}')
        lines.append(f'  N Values:                   {self.n_values}')
        lines.append(f'  Above Range Color:          {self.above_range_color}')
        lines.append(f'  Below Range Color:          {self.below_range_color}')
        lines.append(f'  NAN Color:                  {self.nan_color}')
        lines.append(f'  Log Scale:                  {self.log_scale}')

        lines.append(f'  Color Map:                  "{self._lookup_type}"')
        if not (self.cmap or self._values_manual):
            lines.append(f'    Alpha Range:              {self.alpha_range}')
            lines.append(f'    Hue Range:                {self.hue_range}')
            lines.append(f'    Saturation Range          {self.saturation_range}')
            lines.append(f'    Value Range               {self.value_range}')
            lines.append(f'    Ramp                      {self.ramp}')

        return '\n'.join(lines)

    @property
    def scalar_range(self) -> tuple:
        """Return or set the table range.

        This is the range of scalars which will be mapped to colors. Values
        outside of this range will be colored according to
        :attr`LookupTable.below_range_color` and
        :attr`LookupTable.above_range_color`.

        Examples
        --------
        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.scalar_range = (0, 10)
        >>> lut.scalar_range
        (0.0, 10.0)

        """
        return self.GetTableRange()

    @scalar_range.setter
    def scalar_range(self, value: tuple):
        self.SetTableRange(value)

    @property
    def alpha_range(self) -> tuple:
        """Return or set the alpha range.

        This range is only used when creating custom color maps and will return
        ``None`` when a color map has been set with :attr:`LookupTable.cmap`.

        This will clear any existing color map and create new values for the
        lookup table when set.

        Examples
        --------
        Create a custom "blues" lookup table that decreases in opacity.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.hue_range = (0.7, 0.7)
        >>> lut.alpha_range = (1.0, 0.0)
        >>> lut.plot(background='grey')

        """
        if self._cmap:
            return None
        return self.GetAlphaRange()

    @alpha_range.setter
    def alpha_range(self, value: tuple):
        self.SetAlphaRange(value)
        self.rebuild()

    @property
    def saturation_range(self) -> tuple:
        """Return or set the saturation range.

        This range is only used when creating custom color maps and will return
        ``None`` when a color map has been set with :attr:`LookupTable.cmap`.

        This will clear any existing color map and create new values for the
        lookup table when set.

        Examples
        --------
        Create a custom "blues" lookup table that increases in saturation.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.hue_range = (0.7, 0.7)
        >>> lut.saturation_range = (0.0, 1.0)
        >>> lut.plot(background='grey')

        """
        if self._cmap:
            return None
        return self.GetSaturationRange()

    @saturation_range.setter
    def saturation_range(self, value: tuple):
        self.SetSaturationRange(value)
        self.rebuild()

    def rebuild(self):
        """Clear the color map and recompute the values table.

        This is called automatically when setting values like
        :attr:`LookupTable.value_range`.

        Notes
        -----
        This will reset any colormap set with :func:`LookupTable.apply_cmap` or
        :attr:`LookupTable.values`.

        """
        self._cmap = None
        self._values_manual = False
        self.ForceBuild()

    @property
    def nan_color(self) -> Optional[Color]:
        """Return or set the not a number (NAN) color.

        Any values that are NANs will be rendered with this color.

        Examples
        --------
        Set the NAN color to ``'grey'``.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.nan_color = 'grey'
        >>> lut.plot()

        """
        return Color(self.GetNanColor())

    @nan_color.setter
    def nan_color(self, value):
        # NAN value is always set, but make it explicit for example plotting
        self._nan_color_set = True
        self.SetNanColor(*Color(value).float_rgba)

    @property
    def nan_opacity(self):
        """Return or set the not a number (NAN) opacity.

        Any values that are NANs will be rendered with this opacity.

        Examples
        --------
        Set the NAN opacity to ``0.5``.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.nan_color = 'grey'
        >>> lut.nan_opacity = 0.5
        >>> lut.plot()

        """
        color = self.nan_color
        return color.opacity

    @nan_opacity.setter
    def nan_opacity(self, value):
        # Hacky check to prevent auto activation
        if not self._nan_color_set and (value == 1.0 or value == 255):
            return
        color = self.nan_color
        if color is None:
            color = Color(pv.global_theme.nan_color)
        self.nan_color = Color(self.nan_color, opacity=value)

    @property
    def ramp(self) -> str:
        """Set the shape of the table ramp.

        This attribute is only used when creating custom color maps and will
        return ``None`` when a color map has been set with
        :attr:`LookupTable.cmap`. This will clear any existing color map and
        create new values for the lookup table when set.

        This value may be either ``"s-curve"``, ``"linear"``, or ``"sqrt"``.

        * The default is S-curve, which tails off gradually at either end.
        * The equation used for ``"s-curve"`` is ``y = (sin((x - 1/2)*pi) +
          1)/2``, For an S-curve greyscale ramp, you should set
          :attr:`pyvista.LookupTable.n_values`` to 402 (which is ``256*pi/2``) to provide
          room for the tails of the ramp.

        * The equation for the ``"linear"`` is simply ``y = x``.
        * The equation for the ``"sqrt"`` is ``y = sqrt(x)``.

        Examples
        --------
        Show the default s-curve ramp.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.hue_range = (0.0, 0.33)
        >>> lut.ramp = 's-curve'
        >>> lut.plot()

        Plot the linear ramp.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.hue_range = (0.0, 0.33)
        >>> lut.ramp = 'linear'
        >>> lut.plot()

        Plot the ``"sqrt"`` ramp.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.hue_range = (0.0, 0.33)
        >>> lut.ramp = 'sqrt'
        >>> lut.plot()

        """
        return RAMP_MAP[self.GetRamp()]

    @ramp.setter
    def ramp(self, value: str):
        try:
            self.SetRamp(RAMP_MAP_INV[value])
        except KeyError:
            raise ValueError(f'`ramp` must be one of the following:\n{list(RAMP_MAP_INV.keys())}')
        self.rebuild()

    @property
    def above_range_color(self) -> Optional[Color]:
        """Return or set the above range color.

        Any values above :attr:`LookupTable.scalar_range` will be rendered with this
        color.

        Examples
        --------
        Enable the usage of the above range color.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.above_range_color = 'blue'
        >>> lut.plot()

        Disable the usage of the above range color.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.above_range_color = None
        >>> lut.plot()

        """
        if self.GetUseAboveRangeColor():
            return Color(self.GetAboveRangeColor())
        return None

    @above_range_color.setter
    def above_range_color(self, value: Union[bool, ColorLike]):
        if value in (None, False):
            self.SetUseAboveRangeColor(False)
        elif value is True:
            self.SetAboveRangeColor(*Color(pv.global_theme.above_range_color).float_rgba)
            self.SetUseAboveRangeColor(True)
        else:
            self.SetAboveRangeColor(*Color(value).float_rgba)
            self.SetUseAboveRangeColor(True)

    @property
    def above_range_opacity(self):
        """Return or set the above range opacity.

        Examples
        --------
        Set the above range opacity to ``0.5``.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.above_range_color = 'grey'
        >>> lut.above_range_opacity = 0.5
        >>> lut.plot()

        """
        color = self.above_range_color
        return color.opacity

    @above_range_opacity.setter
    def above_range_opacity(self, value):
        color = self.above_range_color
        if color is None:
            color = Color(pv.global_theme.above_range_color)
        self.above_range_color = Color(color, opacity=value)

    @property
    def below_range_color(self) -> Optional[Color]:
        """Return or set the below range color.

        Any values below :attr:`LookupTable.scalar_range` will be rendered with this
        color.

        Examples
        --------
        Enable the usage of the below range color.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.below_range_color = 'blue'
        >>> lut.plot()

        Disable the usage of the below range color.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.below_range_color = None
        >>> lut.plot()

        """
        if self.GetUseBelowRangeColor():
            return Color(self.GetBelowRangeColor())
        return None

    @below_range_color.setter
    def below_range_color(self, value: Union[bool, ColorLike]):
        if value in (None, False):
            self.SetUseBelowRangeColor(False)
        elif value is True:
            self.SetBelowRangeColor(*Color(pv.global_theme.below_range_color).float_rgba)
            self.SetUseBelowRangeColor(True)
        else:
            self.SetBelowRangeColor(*Color(value).float_rgba)
            self.SetUseBelowRangeColor(True)

    @property
    def below_range_opacity(self):
        """Return or set the below range opacity.

        Examples
        --------
        Set the below range opacity to ``0.5``.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.below_range_color = 'grey'
        >>> lut.below_range_opacity = 0.5
        >>> lut.plot()

        """
        color = self.below_range_color
        return color.opacity

    @below_range_opacity.setter
    def below_range_opacity(self, value):
        color = self.below_range_color
        if color is None:
            color = Color(pv.global_theme.below_range_color)
        self.below_range_color = Color(color, opacity=value)

    def apply_cmap(self, cmap, n_values: int = 256, flip: bool = False):
        """Assign a colormap to this lookup table.

        This can be used instead of :attr:`LookupTable.cmap` when you need to
        set the number of values at the same time as the color map.

        Parameters
        ----------
        cmap : str, list, colors.Colormap
            Colormap from Matplotlib, colorcet, or cmocean.

        n_values : int, default: 256
            Number of colors in the color map.

        flip : bool, default: False
            Flip direction of cmap. Most colormaps allow ``*_r`` suffix to do
            this as well.

        Examples
        --------
        Apply ``matplotlib``'s ``'cividis'`` color map.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.apply_cmap('cividis', n_values=32)
        >>> lut.plot()

        """
        if isinstance(cmap, list):
            n_values = len(cmap)

        cmap = get_cmap_safe(cmap)
        values = cmap(np.linspace(0, 1, n_values)) * 255

        if flip:
            values = values[::-1]

        self.values = values
        self._values_manual = False

        # reapply the opacity
        if self._opacity_parm[0] is not None:
            self.apply_opacity(*self._opacity_parm)

        self._cmap = cmap

    def apply_opacity(self, opacity, interpolate: bool = True, kind: str = 'quadratic'):
        """Assign custom opacity to this lookup table.

        Parameters
        ----------
        opacity : float | array_like[float] | str
            The opacity mapping to use. Can be a ``str`` name of a predefined
            mapping including ``'linear'``, ``'geom'``, ``'sigmoid'``,
            ``'sigmoid_3-10'``.  Append an ``'_r'`` to any of those names to
            reverse that mapping.  This can also be a custom array or list of
            values that will be interpolated across the ``n_color`` range for
            user defined mappings. Values must be between 0 and 1.

            If a ``float``, simply applies the same opacity across the entire
            colormap and must be between 0 and 1. Note that ``int`` values are
            interpreted as if they were floats.

        interpolate : bool, default: True
            Flag on whether or not to interpolate the opacity mapping for all
            colors.

        kind : str, default: 'quadratic'
            The interpolation kind if ``interpolate`` is ``True`` and ``scipy``
            is available. See :class:`scipy.interpolate.interp1d` for the
            available interpolation kinds.

            If ``scipy`` is not available, ``'linear'`` interpolation is used.

        Examples
        --------
        Apply a user defined custom opacity to a lookup table and plot the
        random hills example.

        >>> import pyvista as pv
        >>> from pyvista import examples
        >>> mesh = examples.load_random_hills()
        >>> lut = pv.LookupTable(cmap='viridis')
        >>> lut.apply_opacity([1.0, 0.4, 0.0, 0.4, 0.9])
        >>> lut.scalar_range = (
        ...     mesh.active_scalars.min(),
        ...     mesh.active_scalars.max(),
        ... )
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, cmap=lut)
        >>> pl.show()

        """
        if isinstance(opacity, (float, int)):
            if not 0 <= opacity <= 1:
                raise ValueError(f'Opacity must be between 0 and 1, got {opacity}')
            self.values[:, -1] = opacity * 255
        elif len(opacity) == self.n_values:
            # no interpolation is necessary
            self.values[:, -1] = np.array(opacity)
        else:
            self.values[:, -1] = opacity_transfer_function(
                opacity, self.n_values, interpolate=interpolate, kind=kind
            )
        self._opacity_parm = (opacity, interpolate, kind)

    @property
    def values(self) -> lookup_table_ndarray:
        """Return or set the lookup table values.

        This attribute is used when creating a custom lookup table. The table
        must be a RGBA array shaped ``(n, 4)``.

        Examples
        --------
        Create a simple four value lookup table ranging from black to red.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.values = [
        ...     [0, 0, 0, 255],
        ...     [85, 0, 0, 255],
        ...     [170, 0, 0, 255],
        ...     [255, 0, 0, 255],
        ... ]
        >>> lut.values
        lookup_table_ndarray([[  0,   0,   0, 255],
                              [ 85,   0,   0, 255],
                              [170,   0,   0, 255],
                              [255,   0,   0, 255]], dtype=uint8)
        >>> lut.plot()

        """
        return lookup_table_ndarray(self.GetTable(), table=self)

    @values.setter
    def values(self, new_values):
        self._values_manual = True
        self._cmap = None
        new_values = np.array(new_values, copy=False).astype(np.uint8, copy=False)
        self.SetTable(_vtk.numpy_to_vtk(new_values))

    @property
    def n_values(self) -> int:
        """Return or set the number of values in the lookup table.

        Examples
        --------
        Plot the ``"reds"`` colormap with 10 values.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable('reds')
        >>> lut.n_values = 10
        >>> lut.plot()

        Plot the default colormap with 1024 values.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable()
        >>> lut.n_values = 1024
        >>> lut.plot()

        """
        return self.GetNumberOfColors()

    @n_values.setter
    def n_values(self, value: int):
        if self._cmap is not None:
            self.apply_cmap(self._cmap, value)
            self.SetNumberOfTableValues(value)
        elif self._values_manual:
            raise RuntimeError(
                'Number of values cannot be set when the values array has been manually set. Reassign the values array if you wish to change the number of values.'
            )
        else:
            self.SetNumberOfColors(value)
            self.ForceBuild()

    @property
    def annotations(self) -> dict:
        """Return or set annotations.

        Pass a dictionary of annotations. Keys are the float values in the
        scalars range to annotate on the scalar bar and the values are the
        string annotations.

        Examples
        --------
        Assign annotations to the lookup table.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable('magma')
        >>> lut.annotations = {0: 'low', 0.5: 'medium', 1: 'high'}
        >>> lut.plot()

        """
        vtk_values = self.GetAnnotatedValues()
        if vtk_values is None:
            return {}
        n_items = vtk_values.GetSize()
        keys = [vtk_values.GetValue(ii).ToFloat() for ii in range(n_items)]

        vtk_str = self.GetAnnotations()
        values = [str(vtk_str.GetValue(ii)) for ii in range(n_items)]
        return dict(zip(keys, values))

    @annotations.setter
    def annotations(self, values: Optional[dict]):
        self.ResetAnnotations()
        if values is not None:
            for val, anno in values.items():
                self.SetAnnotation(float(val), str(anno))

    @property
    def _lookup_type(self) -> str:
        """Return the lookup type."""
        if self.cmap:
            if hasattr(self.cmap, 'name'):
                return f'{self.cmap.name}'  # type: ignore
            else:  # pragma: no cover
                return f'{self.cmap}'
        elif self._values_manual:
            return 'From values array'
        else:
            return 'PyVista Lookup Table'

    def plot(self, **kwargs):
        """Plot this lookup table.

        Parameters
        ----------
        **kwargs : dict, optional
            Optional keyword arguments passed to :func:`pyvista.Plotter.show`.

        Examples
        --------
        Plot the ``"viridis"`` colormap with the below and above colors.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable('viridis', n_values=8)
        >>> lut.below_range_color = 'black'
        >>> lut.above_range_color = 'grey'
        >>> lut.nan_color = 'r'
        >>> lut.plot()

        Plot only ``"blues"`` colormap.

        >>> import pyvista as pv
        >>> lut = pv.LookupTable('blues', n_values=1024)
        >>> lut.plot()

        """
        # need a trivial polydata for this
        mesh = pv.PolyData(np.zeros((2, 3)))
        mesh['Lookup Table'] = self.scalar_range

        pl = pv.Plotter(window_size=(800, 230), off_screen=kwargs.pop('off_screen', None))
        actor = pl.add_mesh(mesh, scalars=None, show_scalar_bar=False)
        actor.mapper.lookup_table = self
        actor.visibility = False

        scalar_bar_kwargs = {
            'color': 'k',
            'title': self._lookup_type + '\n',
            'outline': False,
            'title_font_size': 40,
        }
        label_level = 0
        if self.below_range_color:
            scalar_bar_kwargs['below_label'] = 'below'
            label_level = 1
        if self.above_range_color:
            scalar_bar_kwargs['above_label'] = 'above'
            label_level = 1

        label_level += self._nan_color_set

        scalar_bar = pl.add_scalar_bar(**scalar_bar_kwargs)
        scalar_bar.SetLookupTable(self)
        scalar_bar.SetMaximumNumberOfColors(self.n_values)
        scalar_bar.SetPosition(0.03, 0.1 + label_level * 0.1)
        scalar_bar.SetPosition2(0.95, 0.9 - label_level * 0.1)
        # scalar_bar.SetTextPad(-10)
        if self._nan_color_set and self.nan_opacity > 0:
            scalar_bar.SetDrawNanAnnotation(self._nan_color_set)

        pl.background_color = kwargs.pop('background', 'w')
        pl.show(**kwargs)

    def to_color_tf(self) -> _vtk.vtkColorTransferFunction:
        """Return the VTK color transfer function of this table.

        Returns
        -------
        vtk.vtkColorTransferFunction
            VTK color transfer function.

        Examples
        --------
        >>> import pyvista
        >>> lut = pyvista.LookupTable()
        >>> tf = lut.to_color_tf()
        >>> tf
        <vtkmodules.vtkRenderingCore.vtkColorTransferFunction(...) at ...>

        """
        color_tf = _vtk.vtkColorTransferFunction()
        mn, mx = self.scalar_range
        for ii, value in enumerate(np.linspace(mn, mx, self.n_values)):
            color_tf.AddRGBPoint(ii, *self.map_value(value, False))
        return color_tf

    def to_opacity_tf(self):
        """Return the opacity transfer function of this table.

        Returns
        -------
        vtk.vtkPiecewiseFunction
            Piecewise function of the opacity of this color table.

        Examples
        --------
        >>> import pyvista
        >>> lut = pyvista.LookupTable()
        >>> tf = lut.to_opacity_tf()
        >>> tf
        <vtkmodules.vtkCommonDataModel.vtkPiecewiseFunction(...) at ...>

        """
        opacity_tf = _vtk.vtkPiecewiseFunction()
        for ii, value in enumerate(self.values[:, 3]):
            opacity_tf.AddPoint(ii, value / self.n_values)
        return opacity_tf

    def map_value(self, value: float, opacity: bool = True) -> tuple:
        """Map a single value through the lookup table, returning an RBG(A) color.

        Parameters
        ----------
        value : float
            Scalar value to map to an RGB(A) color.

        opacity : bool, default: True
            Map the opacity as well.

        Returns
        -------
        tuple
            Mapped RGB(A) color.

        Examples
        --------
        >>> import pyvista
        >>> lut = pyvista.LookupTable()
        >>> rgba_color = lut.map_value(0.0)
        >>> rgba_color
        (1.0, 0.0, 0.0, 1.0)

        """
        color = [0.0, 0.0, 0.0]
        self.GetColor(value, color)
        if opacity:
            color.append(self.GetOpacity(value))
        return tuple(color)

    def __call__(self, value):
        """Implement a Matplotlib colormap-like call."""
        if isinstance(value, (int, float)):
            return self.map_value(value)
        else:
            try:
                return np.array([self.map_value(item) for item in value])
            except:
                raise TypeError('LookupTable __call__ expects a single value or an iterable.')


# pyvista/plotting/mapper.py

"""An internal module for wrapping the use of mappers."""
import sys
from typing import Optional, Union

import numpy as np

import pyvista as pv
from pyvista import _vtk
from pyvista.utilities import (
    FieldAssociation,
    abstract_class,
    convert_array,
    convert_string_array,
    raise_not_matching,
    set_algorithm_input,
    wrap,
)
from pyvista.utilities.misc import no_new_attr

from .._typing import BoundsLike
from .colors import Color, get_cmap_safe
from .lookup_table import LookupTable
from .tools import normalize


@abstract_class
class _BaseMapper(_vtk.vtkAbstractMapper):
    """Base Mapper with methods common to other mappers."""

    _new_attr_exceptions = ('_theme',)

    def __init__(self, theme=None, **kwargs):
        self._theme = pv.themes.DefaultTheme()
        if theme is None:
            # copy global theme to ensure local property theme is fixed
            # after creation.
            self._theme.load_theme(pv.global_theme)
        else:
            self._theme.load_theme(theme)
        self.lookup_table = LookupTable()

        self.interpolate_before_map = kwargs.get(
            'interpolate_before_map', self._theme.interpolate_before_map
        )

    @property
    def bounds(self) -> BoundsLike:
        """Return the bounds of this mapper.

        Examples
        --------
        >>> import pyvista as pv
        >>> mapper = pv.DataSetMapper(dataset=pv.Cube())
        >>> mapper.bounds
        (-0.5, 0.5, -0.5, 0.5, -0.5, 0.5)

        """
        return self.GetBounds()

    def copy(self) -> '_BaseMapper':
        """Create a copy of this mapper.

        Returns
        -------
        pyvista.DataSetMapper
            A copy of this dataset mapper.

        Examples
        --------
        >>> import pyvista as pv
        >>> mapper = pv.DataSetMapper(dataset=pv.Cube())
        >>> mapper_copy = mapper.copy()

        """
        new_mapper = type(self)(theme=self._theme)
        # even though this uses ShallowCopy, the new mapper no longer retains
        # any connection with the original
        new_mapper.ShallowCopy(self)
        if hasattr(self, 'dataset'):
            new_mapper.dataset = self.dataset
        return new_mapper

    @property
    def scalar_range(self) -> tuple:
        """Return or set the scalar range.

        Examples
        --------
        Return the scalar range of a mapper.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere()
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(mesh, scalars=mesh.points[:, 2])
        >>> actor.mapper.scalar_range
        (-0.5, 0.5)
        >>> pl.close()

        Return the scalar range of a composite dataset. In this example it's
        set to its default value of ``(0.0, 1.0)``.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.scalar_range
        (0.0, 1.0)
        >>> pl.close()

        """
        return self.GetScalarRange()

    @scalar_range.setter
    def scalar_range(self, clim):
        self.SetScalarRange(*clim)

    @property
    def lookup_table(self) -> 'pv.LookupTable':
        """Return or set the lookup table.

        Examples
        --------
        Return the lookup table of a dataset mapper.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere()
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(
        ...     mesh, scalars=mesh.points[:, 2], cmap='bwr'
        ... )
        >>> actor.mapper.lookup_table
        LookupTable (...)
          Table Range:                (-0.5, 0.5)
          N Values:                   256
          Above Range Color:          None
          Below Range Color:          None
          NAN Color:                  Color(name='darkgray', hex='#a9a9a9ff', opacity=255)
          Log Scale:                  False
          Color Map:                  "bwr"

        Return the lookup table of a composite dataset mapper.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset)
        >>> mapper.lookup_table  # doctest:+SKIP
        <vtkmodules.vtkCommonCore.vtkLookupTable(...) at ...>

        """
        return self.GetLookupTable()

    @lookup_table.setter
    def lookup_table(self, table):
        self.SetLookupTable(table)

    @property
    def color_mode(self) -> str:
        """Return or set the color mode.

        Either ``'direct'``, or ``'map'``.

        * ``'direct'`` - All integer types are treated as colors with values in
          the range 0-255 and floating types are treated as colors with values
          in the range 0.0-1.0
        * ``'map'`` - All scalar data will be mapped through the lookup table.

        """
        mode = self.GetColorModeAsString().lower()
        if mode == 'mapscalars':
            return 'map'
        return 'direct'

    @color_mode.setter
    def color_mode(self, value: str):
        if value == 'direct':
            self.SetColorModeToDirectScalars()
        elif value == 'map':
            self.SetColorModeToMapScalars()
        else:
            raise ValueError('Color mode must be either "default", "direct" or "map"')

    @property
    def interpolate_before_map(self) -> bool:
        """Return or set the interpolation of scalars before mapping.

        Enabling makes for a smoother scalars display.  When ``False``,
        OpenGL will interpolate the mapped colors which can result in
        showing colors that are not present in the color map.

        Examples
        --------
        Disable interpolation before mapping.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> dataset[0].point_data['data'] = dataset[0].points[:, 2]
        >>> dataset[1].point_data['data'] = dataset[1].points[:, 2]
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(
        ...     dataset,
        ...     show_scalar_bar=False,
        ...     n_colors=3,
        ...     cmap='bwr',
        ... )
        >>> mapper.interpolate_before_map = False
        >>> pl.show()

        Enable interpolation before mapping.

        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(
        ...     dataset,
        ...     show_scalar_bar=False,
        ...     n_colors=3,
        ...     cmap='bwr',
        ... )
        >>> mapper.interpolate_before_map = True
        >>> pl.show()

        See :ref:`interpolate_before_mapping_example` for additional
        explanation regarding this attribute.

        """
        return bool(self.GetInterpolateScalarsBeforeMapping())

    @interpolate_before_map.setter
    def interpolate_before_map(self, value: bool):
        self.SetInterpolateScalarsBeforeMapping(value)

    @property
    def array_name(self) -> str:
        """Return or set the array name or number and component to color by.

        Examples
        --------
        Show the name of the active scalars in the mapper.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere()
        >>> mesh['my_scalars'] = mesh.points[:, 2]
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(mesh, scalars='my_scalars')
        >>> actor.mapper.array_name
        'my_scalars'
        >>> pl.close()

        """
        return self.GetArrayName()

    @array_name.setter
    def array_name(self, name: str):
        """Return or set the array name or number and component to color by."""
        self.SetArrayName(name)

    @property
    def scalar_map_mode(self) -> str:
        """Return or set the scalar map mode.

        Examples
        --------
        Show that the scalar map mode is set to ``'point'`` when setting the
        active scalars to point data.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> dataset[0].point_data['data'] = dataset[0].points[:, 2]
        >>> dataset[1].point_data['data'] = dataset[1].points[:, 2]
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(
        ...     dataset, scalars='data', show_scalar_bar=False
        ... )
        >>> mapper.scalar_map_mode
        'point'
        >>> pl.close()

        """
        # map vtk strings to more sensible strings
        vtk_to_pv = {
            'Default': 'default',
            'UsePointData': 'point',
            'UseCellData': 'cell',
            'UsePointFieldData': 'point_field',
            'UseCellFieldData': 'cell_field',
            'UseFieldData': 'field',
        }
        return vtk_to_pv[self.GetScalarModeAsString()]

    @scalar_map_mode.setter
    def scalar_map_mode(self, scalar_mode: Union[str, FieldAssociation]):
        if isinstance(scalar_mode, FieldAssociation):
            scalar_mode = scalar_mode.name
        scalar_mode = scalar_mode.lower()  # type: ignore
        if scalar_mode == 'default':
            self.SetScalarModeToDefault()
        elif scalar_mode == 'point':
            self.SetScalarModeToUsePointData()
        elif scalar_mode == 'cell':
            self.SetScalarModeToUseCellData()
        elif scalar_mode == 'point_field':
            self.SetScalarModeToUsePointFieldData()
        elif scalar_mode == 'cell_field':
            self.SetScalarModeToUseCellFieldData()
        elif scalar_mode == 'field':
            self.SetScalarModeToUseFieldData()
        else:
            raise ValueError(
                f'Invalid `scalar_map_mode` "{scalar_mode}". Should be either '
                '"default", "point", "cell", "point_field", "cell_field" or "field".'
            )

    @property
    def scalar_visibility(self) -> bool:
        """Return or set the scalar visibility.

        Examples
        --------
        Show that scalar visibility is ``False``.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere()
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(mesh)
        >>> actor.mapper.scalar_visibility
        False
        >>> pl.close()

        Show that scalar visibility is ``True``.

        >>> import pyvista as pv
        >>> dataset = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> dataset[0].point_data['data'] = dataset[0].points[:, 2]
        >>> dataset[1].point_data['data'] = dataset[1].points[:, 2]
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(dataset, scalars='data')
        >>> mapper.scalar_visibility
        True
        >>> pl.close()

        """
        return bool(self.GetScalarVisibility())

    @scalar_visibility.setter
    def scalar_visibility(self, value: bool):
        return self.SetScalarVisibility(value)

    def update(self):
        """Update this mapper."""
        self.Update()


@no_new_attr
class DataSetMapper(_vtk.vtkDataSetMapper, _BaseMapper):
    """Wrap _vtk.vtkDataSetMapper.

    Parameters
    ----------
    dataset : pyvista.DataSet, optional
        Dataset to assign to this mapper.

    theme : pyvista.themes.DefaultTheme, optional
        Plot-specific theme.

    Examples
    --------
    Create a mapper outside :class:`pyvista.Plotter` and assign it to an
    actor.

    >>> import pyvista as pv
    >>> mesh = pv.Cube()
    >>> mapper = pv.DataSetMapper(dataset=mesh)
    >>> actor = pv.Actor(mapper=mapper)
    >>> actor.plot()

    """

    _cmap = None

    def __init__(
        self,
        dataset: Optional['pv.DataSet'] = None,
        theme: Optional['pv.themes.DefaultTheme'] = None,
    ):
        """Initialize this class."""
        super().__init__(theme=theme)
        if dataset is not None:
            self.dataset = dataset

    @property
    def dataset(self) -> Optional['pv.core.dataset.DataSet']:
        """Return or set the dataset assigned to this mapper."""
        return wrap(self.GetInputAsDataSet())

    @dataset.setter
    def dataset(
        self, obj: Union['pv.core.dataset.DataSet', _vtk.vtkAlgorithm, _vtk.vtkAlgorithmOutput]
    ):
        set_algorithm_input(self, obj)

    def as_rgba(self):
        """Convert the active scalars to RGBA.

        This method is used to convert the active scalars to a fixed RGBA array
        and is used for certain mappers that do not support the "map" color
        mode.

        """
        if self.color_mode == 'direct':
            return

        self.dataset.point_data.pop('__rgba__', None)
        self._configure_scalars_mode(
            self.lookup_table(self.dataset.active_scalars),
            '__rgba__',
            self.scalar_map_mode,
            True,
        )

    def _configure_scalars_mode(
        self,
        scalars,
        scalars_name,
        preference,
        direct_scalars_color_mode,
    ):
        """Configure scalar mode.

        Parameters
        ----------
        scalars : numpy.ndarray
            Array of scalars to assign to the mapper.

        scalars_name : str
            If the name of this array exists, scalars is ignored. Otherwise,
            the scalars will be added to the existing dataset and this
            parameter is the name to assign the scalars.

        preference : str
            Either ``'point'`` or ``'cell'``.

        direct_scalars_color_mode : bool
            When ``True``, scalars are treated as RGB colors. When
            ``False``, scalars are mapped to the color table.

        """
        if scalars.shape[0] == self.dataset.n_points and scalars.shape[0] == self.dataset.n_cells:
            use_points = preference == 'point'
            use_cells = not use_points
        else:
            use_points = scalars.shape[0] == self.dataset.n_points
            use_cells = scalars.shape[0] == self.dataset.n_cells

        # Scalars interpolation approach
        if use_points:
            if (
                scalars_name not in self.dataset.point_data
                or scalars_name == pv.DEFAULT_SCALARS_NAME
            ):
                self.dataset.point_data.set_array(scalars, scalars_name, False)
            self.dataset.active_scalars_name = scalars_name
            self.scalar_map_mode = 'point'
        elif use_cells:
            if (
                scalars_name not in self.dataset.cell_data
                or scalars_name == pv.DEFAULT_SCALARS_NAME
            ):
                self.dataset.cell_data.set_array(scalars, scalars_name, False)
            self.dataset.active_scalars_name = scalars_name
            self.scalar_map_mode = 'cell'
        else:
            raise_not_matching(scalars, self.dataset)

        self.color_mode = 'direct' if direct_scalars_color_mode else 'map'

    def set_scalars(
        self,
        scalars,
        scalars_name,
        n_colors=256,
        scalar_bar_args=None,
        rgb=None,
        component=None,
        preference='point',
        custom_opac=False,
        annotations=None,
        log_scale=False,
        nan_color=None,
        above_color=None,
        below_color=None,
        cmap=None,
        flip_scalars=False,
        opacity=None,
        categories=False,
        clim=None,
    ):
        """Set the scalars on this mapper.

        Parameters
        ----------
        scalars : numpy.ndarray
            Array of scalars to assign to the mapper.

        scalars_name : str
            If the name of this array exists, scalars is ignored. Otherwise,
            the scalars will be added to the existing dataset and this
            parameter is the name to assign the scalars.

        n_colors : int, default: 256
            Number of colors to use when displaying scalars.

        scalar_bar_args : dict, optional
            Dictionary of keyword arguments to pass when adding the
            scalar bar to the scene. For options, see
            :func:`pyvista.Plotter.add_scalar_bar`.

        rgb : bool, default: False
            If an 2 dimensional array is passed as the scalars, plot
            those values as RGB(A) colors. ``rgba`` is also an
            accepted alias for this.  Opacity (the A) is optional.  If
            a scalars array ending with ``"_rgba"`` is passed, the default
            becomes ``True``.  This can be overridden by setting this
            parameter to ``False``.

        component : int, optional
            Set component of vector valued scalars to plot.  Must be
            nonnegative, if supplied. If ``None``, the magnitude of
            the vector is plotted.

        preference : str, default: 'Point'
            When ``dataset.n_points == dataset.n_cells`` and setting scalars,
            this parameter sets how the scalars will be mapped to the mesh.
            Can be either ``'point'`` or ``'cell'``.

        custom_opac : bool, default: False
            Use custom opacity.

        annotations : dict, optional
            Pass a dictionary of annotations. Keys are the float
            values in the scalars range to annotate on the scalar bar
            and the values are the string annotations.

        log_scale : bool, default: False
            Use log scale when mapping data to colors. Scalars less
            than zero are mapped to the smallest representable
            positive float.

        nan_color : pyvista.ColorLike, optional
            The color to use for all ``NaN`` values in the plotted
            scalar array.

        above_color : pyvista.ColorLike, optional
            Solid color for values below the scalars range
            (``clim``). This will automatically set the scalar bar
            ``above_label`` to ``'above'``.

        below_color : pyvista.ColorLike, optional
            Solid color for values below the scalars range
            (``clim``). This will automatically set the scalar bar
            ``below_label`` to ``'below'``.

        cmap : str, list, or pyvista.LookupTable
            Name of the Matplotlib colormap to use when mapping the
            ``scalars``.  See available Matplotlib colormaps.  Only applicable
            for when displaying ``scalars``.
            ``colormap`` is also an accepted alias for this. If
            ``colorcet`` or ``cmocean`` are installed, their colormaps can be
            specified by name.

            You can also specify a list of colors to override an existing
            colormap with a custom one.  For example, to create a three color
            colormap you might specify ``['green', 'red', 'blue']``.

            This parameter also accepts a :class:`pyvista.LookupTable`. If this
            is set, all parameters controlling the color map like ``n_colors``
            will be ignored.

        flip_scalars : bool, default: False
            Flip direction of cmap. Most colormaps allow ``*_r`` suffix to do
            this as well.

        opacity : str or numpy.ndarray, optional
            Opacity mapping for the scalars array.
            A string can also be specified to map the scalars range to a
            predefined opacity transfer function (options include: 'linear',
            'linear_r', 'geom', 'geom_r'). Or you can pass a custom made
            transfer function that is an array either ``n_colors`` in length or
            shorter.

        categories : bool, default: False
            If set to ``True``, then the number of unique values in the scalar
            array will be used as the ``n_colors`` argument.

        clim : Sequence, optional
            Color bar range for scalars.  Defaults to minimum and
            maximum of scalars array.  Example: ``(-1, 2)``.

        """
        if scalar_bar_args is None:
            scalar_bar_args = {'n_colors': n_colors}

        if not isinstance(scalars, np.ndarray):
            scalars = np.asarray(scalars)

        # Set the array title for when it is added back to the mesh
        if custom_opac:
            scalars_name = '__custom_rgba'

        if not np.issubdtype(scalars.dtype, np.number) and not isinstance(cmap, pv.LookupTable):
            # we can rapidly handle bools
            if scalars.dtype == np.bool_:
                cats = np.array([b'False', b'True'], dtype='|S5')
                values = np.array([0, 1])
                clim = [-0.5, 1.5]
            else:
                # If str array, digitize and annotate
                cats, scalars = np.unique(scalars.astype('|S'), return_inverse=True)
                values = np.unique(scalars)
                clim = [np.min(values) - 0.5, np.max(values) + 0.5]
                scalars_name = f'{scalars_name}-digitized'

            n_colors = len(cats)
            scalar_bar_args.setdefault('n_labels', 0)

            self.lookup_table.SetAnnotations(convert_array(values), convert_string_array(cats))

        # Use only the real component if an array is complex
        if np.issubdtype(scalars.dtype, np.complexfloating):
            scalars = scalars.astype(float)
            scalars_name = f'{scalars_name}-real'

        if scalars.ndim != 1:
            if rgb:
                pass
            elif scalars.ndim == 2 and (
                scalars.shape[0] == self.dataset.n_points
                or scalars.shape[0] == self.dataset.n_cells
            ):
                if not isinstance(component, (int, type(None))):
                    raise TypeError('component must be either None or an integer')
                if component is None:
                    scalars = np.linalg.norm(scalars.copy(), axis=1)
                    scalars_name = f'{scalars_name}-normed'
                elif component < scalars.shape[1] and component >= 0:
                    scalars = np.array(scalars[:, component]).copy()
                    scalars_name = f'{scalars_name}-{component}'
                else:
                    raise ValueError(
                        'Component must be nonnegative and less than the '
                        f'dimensionality of the scalars array: {scalars.shape[1]}'
                    )
            else:
                scalars = scalars.ravel()

        if scalars.dtype == np.bool_:
            scalars = scalars.astype(np.float_)

        # Set scalars range
        if clim is None:
            clim = [np.nanmin(scalars), np.nanmax(scalars)]
        elif isinstance(clim, (int, float)):
            clim = [-clim, clim]

        if log_scale:
            if clim[0] <= 0:
                clim = [sys.float_info.min, clim[1]]

        if np.any(clim) and not rgb:
            self.scalar_range = clim[0], clim[1]

        if isinstance(cmap, pv.LookupTable):
            self.lookup_table = cmap
            self.scalar_range = self.lookup_table.scalar_range
        else:
            self.lookup_table.scalar_range = self.scalar_range
            # Set default map
            if cmap is None:
                if self._theme is None:
                    cmap = pv.global_theme.cmap
                else:
                    cmap = self._theme.cmap

            # have to add the attribute to pass it onward to some classes
            if isinstance(cmap, str):
                self._cmap = cmap
            # ipygany uses different colormaps
            if self._theme is None:
                jupyter_backend = pv.global_theme.jupyter_backend
            else:
                jupyter_backend = self._theme.jupyter_backend
            if jupyter_backend == 'ipygany':  # pragma: no cover
                from ..jupyter.pv_ipygany import check_colormap

                check_colormap(cmap)
            else:
                if categories:
                    if categories is True:
                        n_colors = len(np.unique(scalars))
                    elif isinstance(categories, int):
                        n_colors = categories

                self.lookup_table.apply_cmap(cmap, n_colors)

                # Set opactities
                if isinstance(opacity, np.ndarray) and not custom_opac:
                    self.lookup_table.apply_opacity(opacity)

                if flip_scalars:
                    self.lookup_table.values[:] = self.lookup_table.values[::-1]

                if custom_opac:
                    # need to round the colors here since we're
                    # directly displaying the colors
                    hue = normalize(scalars, minimum=clim[0], maximum=clim[1])
                    scalars = np.round(hue * n_colors) / n_colors
                    scalars = get_cmap_safe(cmap)(scalars) * 255
                    scalars[:, -1] *= opacity
                    scalars = scalars.astype(np.uint8)

            # configure the lookup table
            if nan_color:
                self.lookup_table.nan_color = nan_color
            if above_color:
                self.lookup_table.above_range_color = above_color
                scalar_bar_args.setdefault('above_label', 'above')
            if below_color:
                self.lookup_table.below_range_color = below_color
                scalar_bar_args.setdefault('below_label', 'below')
            if isinstance(annotations, dict):
                self.lookup_table.annotations = annotations
            self.lookup_table.log_scale = log_scale

        self._configure_scalars_mode(
            scalars,
            scalars_name,
            preference,
            rgb or custom_opac,
        )

        if isinstance(self, PointGaussianMapper):
            self.as_rgba()

    @property
    def cmap(self):
        """Colormap assigned to this mapper."""
        return self._cmap

    def set_custom_opacity(self, opacity, color, n_colors, preference='point'):
        """Set custom opacity.

        Parameters
        ----------
        opacity : numpy.ndarray
            Opacity array to color the dataset. Array length must match either
            the number of points or cells.

        color : pyvista.ColorLike
            The color to use with the opacity array.

        n_colors : int
            Number of colors to use.

        preference : str, default: 'point'
            Either ``'point'`` or ``'cell'``. Used when the number of cells
            matches the number of points.

        """
        # Create a custom RGBA array to supply our opacity to
        if opacity.size == self.dataset.n_points:
            rgba = np.empty((self.dataset.n_points, 4), np.uint8)
        elif opacity.size == self.dataset.n_cells:
            rgba = np.empty((self.dataset.n_cells, 4), np.uint8)
        else:  # pragma: no cover
            raise ValueError(
                f"Opacity array size ({opacity.size}) does not equal "
                f"the number of points ({self.dataset.n_points}) or the "
                f"number of cells ({self.dataset.n_cells})."
            )

        if self._theme is not None:
            default_color = self._theme.color
        else:
            default_color = pv.global_theme.color

        rgba[:, :-1] = Color(color, default_color=default_color).int_rgb
        rgba[:, -1] = np.around(opacity * 255)

        self.color_mode = 'direct'
        self.lookup_table.n_values = n_colors
        self._configure_scalars_mode(rgba, '', preference, True)

    def __repr__(self):
        """Representation of the mapper."""
        mapper_attr = [
            f'{type(self).__name__} ({hex(id(self))})',
            f'  Scalar visibility:           {self.scalar_visibility}',
            f'  Scalar range:                {self.scalar_range}',
            f'  Interpolate before mapping:  {self.interpolate_before_map}',
            f'  Scalar map mode:             {self.scalar_map_mode}',
            f'  Color mode:                  {self.color_mode}',
            '',
        ]

        mapper_attr.append('Attached dataset:')
        mapper_attr.append(str(self.dataset))

        return '\n'.join(mapper_attr)


@no_new_attr
class PointGaussianMapper(_vtk.vtkPointGaussianMapper, DataSetMapper):
    """Wrap vtkPointGaussianMapper."""

    def __init__(self, theme=None, emissive=None, scale_factor=1.0) -> None:
        super().__init__(theme=theme)
        if emissive is None:
            emissive = self._theme.lighting_params.emissive
        self.emissive = emissive
        self.scale_factor = scale_factor

    @property
    def emissive(self) -> bool:
        """Set or return emissive.

        This treats points as emissive light sources. Two points that overlap
        will have their brightness combined.
        """
        return bool(self.GetEmissive())

    @emissive.setter
    def emissive(self, value: bool):
        return self.SetEmissive(value)

    @property
    def scale_factor(self) -> float:
        """Set or return the scale factor.

        Ranges from 0 to 1. A value of 0 will cause the splats to be rendered
        as simple points. Defaults to 1.0.

        """
        return self.GetScaleFactor()

    @scale_factor.setter
    def scale_factor(self, value: float):
        return self.SetScaleFactor(value)

    def use_circular_splat(self, opacity: float = 1.0):
        """Set the fragment shader code to create a circular splat.

        Parameters
        ----------
        opacity : float, default: 1.0
            Desired opacity between 0 and 1.

        Notes
        -----
        This very close to ParaView's PointGaussianMapper, but uses opacity to
        modify the scale as the opacity cannot be set from the actor's property.
        """
        self.SetSplatShaderCode(
            "//VTK::Color::Impl\n"
            "float dist = dot(offsetVCVSOutput.xy,offsetVCVSOutput.xy);\n"
            "if (dist > 1.0) {\n"
            "  discard;\n"
            "} else {\n"
            f"  float scale = ({opacity} - dist);\n"
            "  ambientColor *= scale;\n"
            "  diffuseColor *= scale;\n"
            "}\n"
        )
        # maintain consistency with the default style
        self.emissive = True
        self.scale_factor *= 1.5

    def use_default_splat(self):
        """Clear the fragment shader and use the default splat."""
        self.SetSplatShaderCode(None)
        self.scale_factor /= 1.5

    def __repr__(self):
        """Representation of the Gaussian mapper."""
        mapper_attr = [
            f'{type(self).__name__} ({hex(id(self))})',
            f'  Scalar visibility:           {self.scalar_visibility}',
            f'  Scalar range:                {self.scalar_range}',
            f'  Emissive:                    {self.emissive}',
            f'  Scale Factor:                {self.scale_factor}',
            f'  Using custom splat:          {self.GetSplatShaderCode() is None}',
            '',
        ]

        mapper_attr.append('Attached dataset:')
        mapper_attr.append(str(self.dataset))

        return '\n'.join(mapper_attr)


@abstract_class
class _BaseVolumeMapper(_BaseMapper):
    """Volume mapper class to override methods and attributes for to volume mappers."""

    def __init__(self, theme=None):
        """Initialize this class."""
        super().__init__(theme=theme)
        self._lut = LookupTable()
        self._scalar_range = (0.0, 256.0)

    @property
    def interpolate_before_map(self):
        """Interpolate before map is not supported with volume mappers."""
        return None

    @interpolate_before_map.setter
    def interpolate_before_map(self, *args):
        pass

    @property
    def dataset(self):
        """Return or set the dataset assigned to this mapper."""
        # GetInputAsDataSet unavailable on volume mappers
        return wrap(self.GetDataSetInput())

    @dataset.setter
    def dataset(
        self, obj: Union['pv.core.dataset.DataSet', _vtk.vtkAlgorithm, _vtk.vtkAlgorithmOutput]
    ):
        set_algorithm_input(self, obj)

    @property
    def lookup_table(self):
        return self._lut

    @lookup_table.setter
    def lookup_table(self, lut):
        self._lut = lut

    @property
    def scalar_range(self) -> tuple:
        """Return or set the scalar range."""
        return self._scalar_range

    @scalar_range.setter
    def scalar_range(self, clim):
        if self.lookup_table is not None:
            self.lookup_table.SetRange(*clim)
        self._scalar_range = tuple(clim)

    @property
    def blend_mode(self) -> str:
        """Return or set the blend mode.

        One of the following:

        * ``"composite"``
        * ``"maximum"``
        * ``"minimum"``
        * ``"average"``
        * ``"additive"``

        Also accepts integer values corresponding to
        ``vtk.vtkVolumeMapper.BlendModes``. For example
        ``vtk.vtkVolumeMapper.COMPOSITE_BLEND``.

        """
        value = self.GetBlendMode()
        if value == 0:
            return 'composite'
        elif value == 1:
            return 'maximum'
        elif value == 2:
            return 'minimum'
        elif value == 3:
            return 'average'
        elif value == 4:
            return 'additive'

        raise NotImplementedError(
            f'Unsupported blend mode return value {value}'
        )  # pragma: no cover

    @blend_mode.setter
    def blend_mode(self, value: Union[str, int]):
        if isinstance(value, int):
            self.SetBlendMode(value)
        elif isinstance(value, str):
            value = value.lower()
            if value in ['additive', 'add', 'sum']:
                self.SetBlendModeToAdditive()
            elif value in ['average', 'avg', 'average_intensity']:
                self.SetBlendModeToAverageIntensity()
            elif value in ['composite', 'comp']:
                self.SetBlendModeToComposite()
            elif value in ['maximum', 'max', 'maximum_intensity']:
                self.SetBlendModeToMaximumIntensity()
            elif value in ['minimum', 'min', 'minimum_intensity']:
                self.SetBlendModeToMinimumIntensity()
            else:
                raise ValueError(
                    f'Blending mode {value!r} invalid. '
                    'Please choose either "additive", '
                    '"composite", "minimum" or "maximum".'
                )
        else:
            raise TypeError(f'`blend_mode` should be either an int or str, not `{type(value)}`')

    def __del__(self):
        self._lut = None


class FixedPointVolumeRayCastMapper(_vtk.vtkFixedPointVolumeRayCastMapper, _BaseVolumeMapper):
    """Wrap _vtk.vtkFixedPointVolumeRayCastMapper."""

    pass


class GPUVolumeRayCastMapper(_vtk.vtkGPUVolumeRayCastMapper, _BaseVolumeMapper):
    """Wrap _vtk.vtkGPUVolumeRayCastMapper."""

    pass


class OpenGLGPUVolumeRayCastMapper(_vtk.vtkOpenGLGPUVolumeRayCastMapper, _BaseVolumeMapper):
    """Wrap _vtk.vtkOpenGLGPUVolumeRayCastMapper."""

    pass


class SmartVolumeMapper(_vtk.vtkSmartVolumeMapper, _BaseVolumeMapper):
    """Wrap _vtk.vtkSmartVolumeMapper."""

    pass


class UnstructuredGridVolumeRayCastMapper(
    _vtk.vtkUnstructuredGridVolumeRayCastMapper, _BaseVolumeMapper
):
    """Wrap _vtk.vtkUnstructuredGridVolumeMapper."""

    pass


# pyvista/plotting/opts.py

"""Module with enum options classes for plotting."""
from enum import Enum


class AnnotatedIntEnum(int, Enum):
    """Annotated enum type."""

    def __new__(cls, value, annotation):
        """Initialize."""
        obj = int.__new__(cls, value)
        obj._value_ = value
        obj.annotation = annotation
        return obj

    @classmethod
    def from_str(cls, input_str):
        """Create from string."""
        for value in cls:
            if value.annotation.lower() == input_str.lower():
                return value
        raise ValueError(f"{cls.__name__} has no value matching {input_str}")

    @classmethod
    def from_any(cls, value):
        """Create from string, int, etc."""
        if isinstance(value, cls):
            return value
        elif isinstance(value, int):
            return cls(value)
        elif isinstance(value, str):
            return cls.from_str(value)
        else:
            raise ValueError(f"{cls.__name__} has no value matching {value}")


class InterpolationType(AnnotatedIntEnum):
    """Lighting interpolation types."""

    FLAT = (0, 'Flat')
    GOURAUD = (1, 'Gouraud')
    PHONG = (2, 'PHONG')
    PBR = (3, 'Physically based rendering')

    @classmethod
    def from_str(cls, input_str):
        """Create from string."""
        aliases = {
            'pbr': 'Physically based rendering',
        }
        if input_str in aliases:
            input_str = aliases[input_str]
        return super().from_str(input_str)


class RepresentationType(AnnotatedIntEnum):
    """Types of representations the models can have."""

    POINTS = (0, 'Points')
    WIREFRAME = (1, 'Wireframe')
    SURFACE = (2, 'Surface')


# pyvista/plotting/picking.py

"""Module managing picking events."""

from functools import partial
import warnings
import weakref

import numpy as np

import pyvista
from pyvista import _vtk
from pyvista.utilities import try_callback

from .composite_mapper import CompositePolyDataMapper


def _launch_pick_event(interactor, event):
    """Create a Pick event based on coordinate or left-click."""
    click_x, click_y = interactor.GetEventPosition()
    click_z = 0

    picker = interactor.GetPicker()
    renderer = interactor.GetInteractorStyle()._parent()._plotter.renderer
    picker.Pick(click_x, click_y, click_z, renderer)


class PickingHelper:
    """An internal class to hold picking related features."""

    def __init__(self, *args, **kwargs):
        """Initialize the picking helper."""
        super().__init__(*args, **kwargs)
        self.picked_cells = None
        self._picked_point = None
        self._picked_mesh = None
        self.picked_path = None
        self.picked_geodesic = None
        self.picked_horizon = None
        self._picking_left_clicking_observer = None
        self._picking_text = None
        self._picker = None
        self._picked_block_index = None

    def get_pick_position(self):
        """Get the pick position or area.

        Returns
        -------
        sequence
            Picked position or area as ``(x0, y0, x1, y1)``.

        """
        return self.renderer.get_pick_position()

    def enable_mesh_picking(
        self,
        callback=None,
        show=True,
        show_message=True,
        style='wireframe',
        line_width=5,
        color='pink',
        font_size=18,
        left_clicking=False,
        use_actor=False,
        **kwargs,
    ):
        """Enable picking of a mesh.

        Parameters
        ----------
        callback : callable, optional
            When input, calls this callable after a selection is made. The
            ``mesh`` is input as the first parameter to this callable.

        show : bool, default: True
            Show the selection interactively. Best when combined with
            ``left_clicking``.

        show_message : bool | str, default: True
            Show the message about how to use the mesh picking tool. If this
            is a string, that will be the message shown.

        style : str, default: "wireframe"
            Visualization style of the selection. One of the following:

            * ``'surface'``
            * ``'wireframe'``
            * ``'points'``

        line_width : float, default: 5.0
            Thickness of selected mesh edges.

        color : ColorLike, default: "pink"
            The color of the selected mesh when shown.

        font_size : int, default: 18
            Sets the font size of the message.

        left_clicking : bool, default: False
            When ``True``, meshes can be picked by clicking the left
            mousebutton.

            .. note::
               If enabled, left-clicking will **not** display the bounding box
               around the picked point.

        use_actor : bool, default: False
            If True, the callback will be passed the picked actor instead of
            the mesh object.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the picked path is interactively displayed.

        Returns
        -------
        vtk.vtkPropPicker
            Property picker.

        Examples
        --------
        Add a sphere and a cube to a plot and enable mesh picking. Enable
        ``left_clicking`` to immediately start picking on the left click and
        disable showing the box. You can still press the ``p`` key to select
        meshes.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere(center=(1, 0, 0))
        >>> cube = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh)
        >>> _ = pl.add_mesh(cube)
        >>> _ = pl.enable_mesh_picking(left_clicking=True)

        See :ref:`mesh_picking_example` for a full example using this method.

        """

        def end_pick_call_back(picked, event):
            is_valid_selection = False
            self_ = weakref.ref(self)
            actor = picked.GetActor()
            if actor:
                mesh = actor.GetMapper().GetInputAsDataSet()
                is_valid_selection = True

            if is_valid_selection:
                self_()._picked_mesh = mesh

            if callback and is_valid_selection:
                if use_actor:
                    try_callback(callback, actor)
                else:
                    try_callback(callback, mesh)

            if show and is_valid_selection:
                # Select the renderer where the mesh is added.
                active_renderer_index = self_().renderers._active_index
                for index in range(len(self.renderers)):
                    renderer = self.renderers[index]
                    for actor in renderer._actors.values():
                        mapper = actor.GetMapper()
                        if (
                            isinstance(mapper, _vtk.vtkDataSetMapper)
                            and mapper.GetInputAsDataSet() == mesh
                        ):
                            loc = self_().renderers.index_to_loc(index)
                            self_().subplot(*loc)
                            break

                # Use try in case selection is empty or invalid
                try:
                    self_().add_mesh(
                        mesh,
                        name='_mesh_picking_selection',
                        style=style,
                        color=color,
                        line_width=line_width,
                        pickable=False,
                        reset_camera=False,
                        **kwargs,
                    )
                except Exception as e:  # pragma: no cover
                    warnings.warn("Unable to show mesh when picking:\n\n%s", str(e))

                # Reset to the active renderer.
                loc = self_().renderers.index_to_loc(active_renderer_index)
                self_().subplot(*loc)

                # render here prior to running the callback
                self_().render()
            elif not is_valid_selection:
                self.remove_actor('_mesh_picking_selection')
                self_()._picked_mesh = None

        # add on-screen message about point-selection
        if show_message:
            if show_message is True:
                show_message = "\nPress P to pick a single dataset under the mouse pointer."
                if left_clicking:
                    show_message += "\nor click to select a dataset under the mouse pointer."

            self._picking_text = self.add_text(
                str(show_message), font_size=font_size, name='_mesh_picking_message'
            )

        if left_clicking:
            self._picking_left_clicking_observer = self.iren.interactor.AddObserver(
                "LeftButtonPressEvent",
                partial(try_callback, _launch_pick_event),
            )

        self._picker = _vtk.vtkPropPicker()
        self._picker.AddObserver(_vtk.vtkCommand.EndPickEvent, end_pick_call_back)
        self.enable_trackball_style()
        self.iren.set_picker(self._picker)
        return self._picker

    def enable_cell_picking(
        self,
        callback=None,
        through=True,
        show=True,
        show_message=True,
        style='wireframe',
        line_width=5,
        color='pink',
        font_size=18,
        start=False,
        **kwargs,
    ):
        """Enable picking at cells.

        Press ``"r"`` to enable retangle based selection.  Press
        ``"r"`` again to turn it off. Selection will be saved to
        ``self.picked_cells``. Also press ``"p"`` to pick a single
        cell under the mouse location.

        All meshes in the scene are available for picking by default.
        If you would like to only pick a single mesh in the scene,
        use the ``pickable=False`` argument when adding the other
        meshes to the scene.

        When multiple meshes are being picked, the picked cells
        in ``self.picked_cells`` will be a :class:`MultiBlock`
        dataset for each mesh's selection.

        Uses last input mesh for input by default.

        .. warning::
           Visible cell picking (``through=False``) will only work if
           the mesh is displayed with a ``'surface'`` representation
           style (the default).

        .. warning::
            Cell picking can only be enabled for a single renderer
            or subplot at a time.

        Parameters
        ----------
        callback : callable, optional
            When input, calls this callable after a selection is made.
            The picked_cells are input as the first parameter to this
            callable.

        through : bool, default: True
            When ``True`` the picker will select all cells
            through the mesh(es). When ``False``, the picker will select
            only visible cells on the selected surface(s).

        show : bool, default: True
            Show the selection interactively.

        show_message : bool | str, default: True
            Show the message about how to use the cell picking tool. If this
            is a string, that will be the message shown.

        style : str, default: "wireframe"
            Visualization style of the selection.  One of the
            following: ``style='surface'``, ``style='wireframe'``, or
            ``style='points'``.

        line_width : float, default: 5.0
            Thickness of selected mesh edges.

        color : ColorLike, default: "pink"
            The color of the selected mesh when shown.

        font_size : int, default: 18
            Sets the font size of the message.

        start : bool, default: True
            Automatically start the cell selection tool.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the selection is interactively displayed.

        Examples
        --------
        Add a mesh and a cube to a plot and enable cell picking.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere(center=(1, 0, 0))
        >>> cube = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh)
        >>> _ = pl.add_mesh(cube)
        >>> _ = pl.enable_cell_picking(left_clicking=True)

        """
        self_ = weakref.ref(self)

        # make sure to consistently use renderer
        renderer_ = weakref.ref(self.renderer)

        def end_pick_helper(picker, event_id):
            # Merge the selection into a single mesh
            picked = self_().picked_cells
            if isinstance(picked, pyvista.MultiBlock):
                if picked.n_blocks > 0:
                    picked = picked.combine()
                else:
                    picked = pyvista.UnstructuredGrid()
            # Check if valid
            is_valid_selection = picked.n_cells > 0

            if show and is_valid_selection:
                # Select the renderer where the mesh is added.
                active_renderer_index = self_().renderers._active_index
                for index in range(len(self.renderers)):
                    renderer = self.renderers[index]
                    for actor in renderer._actors.values():
                        mapper = actor.GetMapper()
                        if isinstance(mapper, _vtk.vtkDataSetMapper):
                            loc = self_().renderers.index_to_loc(index)
                            self_().subplot(*loc)
                            break

                # Use try in case selection is empty
                self_().add_mesh(
                    picked,
                    name='_cell_picking_selection',
                    style=style,
                    color=color,
                    line_width=line_width,
                    pickable=False,
                    reset_camera=False,
                    **kwargs,
                )

                # Reset to the active renderer.
                loc = self_().renderers.index_to_loc(active_renderer_index)
                self_().subplot(*loc)

                # render here prior to running the callback
                self_().render()
            elif not is_valid_selection:
                self.remove_actor('_cell_picking_selection')
                self_().picked_cells = None

            if callback is not None:
                try_callback(callback, self_().picked_cells)

            # TODO: Deactivate selection tool
            return

        def through_pick_call_back(picker, event_id):
            picked = pyvista.MultiBlock()
            for actor in renderer_().actors.values():
                if actor.GetMapper() and actor.GetPickable():
                    input_mesh = pyvista.wrap(actor.GetMapper().GetInputAsDataSet())
                    input_mesh.cell_data['orig_extract_id'] = np.arange(input_mesh.n_cells)
                    extract = _vtk.vtkExtractGeometry()
                    extract.SetInputData(input_mesh)
                    extract.SetImplicitFunction(picker.GetFrustum())
                    extract.Update()
                    picked.append(pyvista.wrap(extract.GetOutput()))

            if len(picked) == 1:
                self_().picked_cells = picked[0]
            else:
                self_().picked_cells = picked
            return end_pick_helper(picker, event_id)

        def visible_pick_call_back(picker, event_id):
            picked = pyvista.MultiBlock()
            x0, y0, x1, y1 = renderer_().get_pick_position()
            if x0 >= 0:  # initial pick position is (-1, -1, -1, -1)
                selector = _vtk.vtkOpenGLHardwareSelector()
                selector.SetFieldAssociation(_vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS)
                selector.SetRenderer(renderer_())
                selector.SetArea(x0, y0, x1, y1)
                selection = selector.Select()

                for node in range(selection.GetNumberOfNodes()):
                    selection_node = selection.GetNode(node)
                    if selection_node is None:  # pragma: no cover
                        # No selection
                        continue
                    cids = pyvista.convert_array(selection_node.GetSelectionList())
                    actor = selection_node.GetProperties().Get(_vtk.vtkSelectionNode.PROP())

                    # TODO: this is too hacky - find better way to avoid non-dataset actors
                    if not actor.GetMapper() or not hasattr(
                        actor.GetProperty(), 'GetRepresentation'
                    ):
                        continue

                    # if not a surface
                    if actor.GetProperty().GetRepresentation() != 2:  # pragma: no cover
                        warnings.warn(
                            "Display representations other than `surface` will result in incorrect results."
                        )
                    smesh = pyvista.wrap(actor.GetMapper().GetInputAsDataSet())
                    smesh = smesh.copy()
                    smesh["original_cell_ids"] = np.arange(smesh.n_cells)
                    tri_smesh = smesh.extract_surface().triangulate()
                    cids_to_get = tri_smesh.extract_cells(cids)["original_cell_ids"]
                    picked.append(smesh.extract_cells(cids_to_get))

                # memory leak issues on vtk==9.0.20210612.dev0
                # See: https://gitlab.kitware.com/vtk/vtk/-/issues/18239#note_973826
                selection.UnRegister(selection)

            if len(picked) == 1:
                self_().picked_cells = picked[0]
            else:
                self_().picked_cells = picked
            return end_pick_helper(picker, event_id)

        self._picker = _vtk.vtkRenderedAreaPicker()
        if through:
            self._picker.AddObserver(_vtk.vtkCommand.EndPickEvent, through_pick_call_back)
        else:
            # NOTE: there can be issues with non-triangulated meshes
            # Reference:
            #     https://github.com/pyvista/pyvista/issues/277
            #     https://github.com/pyvista/pyvista/pull/281
            #     https://discourse.vtk.org/t/visible-cell-selection-hardwareselector-py-example-is-not-working-reliably/1262
            self._picker.AddObserver(_vtk.vtkCommand.EndPickEvent, visible_pick_call_back)

        self.enable_rubber_band_style()
        self.iren.set_picker(self._picker)

        # Now add text about cell-selection
        if show_message:
            if show_message is True:
                show_message = "Press R to toggle selection tool"
                if not through:
                    show_message += "\nPress P to pick a single cell under the mouse"
            self._picking_text = self.add_text(
                str(show_message), font_size=font_size, name='_cell_picking_message'
            )

        if start:
            self.iren._style_class.StartSelect()

    @property
    def picked_mesh(self):
        """Return the picked mesh.

        This returns the picked mesh after selecting a mesh with
        :func:`enable_mesh_picking <pyvista.Plotter.enable_mesh_picking>` or
        :func:`enable_point_picking <pyvista.Plotter.enable_point_picking>`.

        Returns
        -------
        pyvista.DataSet or None
            Picked mesh if available.

        """
        return self._picked_mesh

    @property
    def picked_point(self):
        """Return the picked point.

        This returns the picked point after selecting a point.

        Returns
        -------
        numpy.ndarray or None
            Picked point if available.

        """
        return self._picked_point

    @property
    def picked_block_index(self):
        """Return the picked block index.

        This returns the picked block index after selecting a point with
        :func:`enable_point_picking <pyvista.Plotter.enable_point_picking>`.

        Returns
        -------
        int or None
            Picked block if available. If ``-1``, then a non-composite dataset
            was selected.

        """
        return self._picked_block_index

    def enable_surface_picking(
        self,
        callback=None,
        show_message=True,
        font_size=18,
        color='pink',
        show_point=True,
        point_size=10,
        tolerance=0.025,
        pickable_window=False,
        left_clicking=False,
        **kwargs,
    ):
        """Enable picking of a point on the surface of a mesh.

        Parameters
        ----------
        callback : callable, optional
            When input, calls this callable after a selection is made. The
            ``mesh`` is input as the first parameter to this callable.

        show_message : bool | str, default: True
            Show the message about how to use the mesh picking tool. If this
            is a string, that will be the message shown.

        font_size : int, default: 18
            Sets the font size of the message.

        color : ColorLike, default: "pink"
            The color of the selected mesh when shown.

        show_point : bool, default: True
            Show the selection interactively.

        point_size : int, default: 10
            Size of picked points if ``show_point`` is ``True``.

        tolerance : float, default: 0.025
            Specify tolerance for performing pick operation. Tolerance
            is specified as fraction of rendering window
            size. Rendering window size is measured across diagonal.

        pickable_window : bool, default: False
            When ``True``, points in the 3D window are pickable.

        left_clicking : bool, default: False
            When ``True``, meshes can be picked by clicking the left
            mousebutton.

            .. note::
               If enabled, left-clicking will **not** display the bounding box
               around the picked mesh.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the picked path is interactively displayed.

        Returns
        -------
        vtk.vtkPropPicker
            Property picker.

        Notes
        -----
        Picked point can be accessed from :attr:`picked_point
        <pyvista.Plotter.picked_point>` attribute.

        Examples
        --------
        Add a cube to a plot and enable cell picking. Enable ``left_clicking``
        to immediately start picking on the left click and disable showing the
        box. You can still press the ``p`` key to select meshes.

        >>> import pyvista as pv
        >>> cube = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(cube)
        >>> _ = pl.enable_surface_picking(left_clicking=True)

        See :ref:`surface_picking_example` for a full example using this method.

        """

        def _end_pick_event(picker, event):
            picked_point_id = picker.GetPointId()
            if not pickable_window and picked_point_id < 0:
                self._picked_point = None
                return

            self._picked_point = np.array(picker.GetPickPosition())
            self._picked_mesh = picker.GetDataSet()
            if show_point:
                self.add_mesh(
                    self.picked_point,
                    color=color,
                    point_size=point_size,
                    name='_picked_point',
                    pickable=False,
                    reset_camera=False,
                    **kwargs,
                )
            if callable(callback):
                try_callback(callback, self.picked_point)

        picker = _vtk.vtkCellPicker()
        picker.SetTolerance(tolerance)
        self._picker = picker
        picker.AddObserver(_vtk.vtkCommand.EndPickEvent, _end_pick_event)

        self.enable_trackball_style()
        self.iren.set_picker(picker)

        if left_clicking:
            self._picking_left_clicking_observer = self.iren.interactor.AddObserver(
                "LeftButtonPressEvent",
                partial(try_callback, _launch_pick_event),
            )

        # add on-screen message about point-selection
        if show_message:
            if show_message is True:
                show_message = "\nPress P to pick a point on the surface under the mouse pointer."
                if left_clicking:
                    show_message += "\nor click to select a point under the mouse pointer."

            self._picking_text = self.add_text(
                str(show_message), font_size=font_size, name='_surf_picking_message'
            )

        return picker

    def enable_point_picking(
        self,
        callback=None,
        show_message=True,
        font_size=18,
        color='pink',
        point_size=10,
        use_mesh=False,
        show_point=True,
        tolerance=0.025,
        pickable_window=False,
        left_clicking=False,
        **kwargs,
    ):
        """Enable picking at points.

        Enable picking a point at the mouse location in the render
        view using the ``P`` key. This point is saved to the
        ``.picked_point`` attribute on the plotter. Pass a callback
        that takes that point as an argument. The picked
        point can either be a point on the first intersecting mesh, or
        a point in the 3D window.

        Parameters
        ----------
        callback : callable, optional
            When input, calls this callable after a pick is made.  The
            picked point is input as the first parameter to this
            callable.  If ``use_mesh`` is ``True``, the callback
            callable will be passed a pointer to the picked mesh and
            the point ID of the selected mesh.

        show_message : bool | str, default: True
            Show the message about how to use the point picking
            tool. If this is a string, that will be the message shown.

        font_size : int, default: 18
            Sets the size of the message.

        color : ColorLike, default: "pink"
            The color of the selected mesh when shown.

        point_size : int, default: 10
            Size of picked points if ``show_point`` is ``True``.

        use_mesh : bool, default: False
            If ``True``, the callback will be passed the picked
            mesh and the point ID of the selected mesh.

        show_point : bool, default: True
            Show the picked point after clicking.

        tolerance : float, tolerance: 0.025
            Specify tolerance for performing pick operation. Tolerance
            is specified as fraction of rendering window
            size. Rendering window size is measured across diagonal.

        pickable_window : bool, default: False
            When ``True``, points in the 3D window are pickable.

        left_clicking : bool, default: False
            When ``True``, points can be picked by clicking the left mouse
            button.  Note, if enabled, left-clicking will **not** display the
            bounding box around the picked mesh.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the picked point is interactively displayed.

        Examples
        --------
        Enable point picking with a custom message.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Sphere())
        >>> _ = pl.add_mesh(pv.Cube(), pickable=False)
        >>> pl.enable_point_picking(show_message="Press P to pick")

        See :ref:`point_picking_example` for a full example using this method.

        """

        def _end_pick_event(picker, event):
            picked_point_id = picker.GetPointId()
            if (not pickable_window) and (picked_point_id < 0):
                return None

            self._picked_point = np.array(picker.GetPickPosition())
            self._picked_mesh = picker.GetDataSet()
            self._picked_block_index = picker.GetFlatBlockIndex()

            self.picked_point_id = picked_point_id
            if show_point:
                self.add_mesh(
                    self.picked_point,
                    color=color,
                    point_size=point_size,
                    name='_picked_point',
                    pickable=False,
                    reset_camera=False,
                    **kwargs,
                )
            if callable(callback):
                if use_mesh:
                    try_callback(callback, self.picked_mesh, self.picked_point_id)
                else:
                    try_callback(callback, self.picked_point)

        point_picker = _vtk.vtkPointPicker()
        point_picker.SetTolerance(tolerance)
        self._picker = point_picker
        point_picker.AddObserver(_vtk.vtkCommand.EndPickEvent, _end_pick_event)

        self.enable_trackball_style()
        self.iren.set_picker(point_picker)

        if left_clicking:
            self._picking_left_clicking_observer = self.iren.add_observer(
                "LeftButtonPressEvent",
                partial(try_callback, _launch_pick_event),
            )

        # Now add text about cell-selection
        if show_message:
            if show_message is True and left_clicking:
                show_message = "Left-click or press P to pick under the mouse"
            elif show_message is True:
                show_message = "Press P to pick under the mouse"
            self._picking_text = self.add_text(
                str(show_message), font_size=font_size, name='_point_picking_message'
            )

    def enable_path_picking(
        self,
        callback=None,
        show_message=True,
        font_size=18,
        color='pink',
        point_size=10,
        line_width=5,
        show_path=True,
        tolerance=0.025,
        **kwargs,
    ):
        """Enable picking at paths.

        This is a convenience method for :func:`enable_point_picking
        <pyvista.Plotter.enable_point_picking>` to keep track of the
        picked points and create a line using those points.

        The line is saved to the ``.picked_path`` attribute of this
        plotter

        Parameters
        ----------
        callback : callable, optional
            When given, calls this callable after a pick is made.  The
            entire picked path is passed as the only parameter to this
            callable.

        show_message : bool | str, default: True
            Show the message about how to use the point picking
            tool. If this is a string, that will be the message shown.

        font_size : int, default: 18
            Sets the size of the message.

        color : ColorLike, default: "pink"
            The color of the selected mesh when shown.

        point_size : int, default: 10
            Size of picked points if ``show_path`` is ``True``.

        line_width : float, default: 5.0
            Thickness of path representation if ``show_path`` is
            ``True``.

        show_path : bool, default: True
            Show the picked path interactively.

        tolerance : float, default: 0.025
            Specify tolerance for performing pick operation. Tolerance
            is specified as fraction of rendering window
            size.  Rendering window size is measured across diagonal.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the picked path is interactively displayed.

        """
        kwargs.setdefault('pickable', False)

        def make_line_cells(n_points):
            cells = np.arange(0, n_points, dtype=np.int_)
            cells = np.insert(cells, 0, n_points)
            return cells

        the_points = []
        the_ids = []

        def _the_callback(mesh, idx):
            if mesh is None:
                return
            the_ids.append(idx)
            the_points.append(mesh.points[idx])
            self.picked_path = pyvista.PolyData(np.array(the_points))
            self.picked_path.lines = make_line_cells(len(the_points))
            if show_path:
                self.add_mesh(
                    self.picked_path,
                    color=color,
                    name='_picked_path',
                    line_width=line_width,
                    point_size=point_size,
                    reset_camera=False,
                    **kwargs,
                )
            if callable(callback):
                try_callback(callback, self.picked_path)

        def _clear_path_event_watcher():
            del the_points[:]
            del the_ids[:]
            self.remove_actor('_picked_path')

        self.add_key_event('c', _clear_path_event_watcher)
        if show_message is True:
            show_message = "Press P to pick under the mouse\nPress C to clear"

        self.enable_point_picking(
            callback=_the_callback,
            use_mesh=True,
            font_size=font_size,
            show_message=show_message,
            show_point=False,
            tolerance=tolerance,
        )

    def enable_geodesic_picking(
        self,
        callback=None,
        show_message=True,
        font_size=18,
        color='pink',
        point_size=10,
        line_width=5,
        tolerance=0.025,
        show_path=True,
        keep_order=True,
        **kwargs,
    ):
        """Enable picking at geodesic paths.

        This is a convenience method for ``enable_point_picking`` to
        keep track of the picked points and create a geodesic path
        using those points.

        The geodesic path is saved to the ``.picked_geodesic``
        attribute of this plotter.

        Parameters
        ----------
        callback : callable, optional
            When given, calls this callable after a pick is made.  The
            entire picked, geodesic path is passed as the only
            parameter to this callable.

        show_message : bool | str, default: True
            Show the message about how to use the point picking
            tool. If this is a string, that will be the message shown.

        font_size : int, default: 18
            Sets the size of the message.

        color : ColorLike, default: "pink"
            The color of the selected mesh when shown.

        point_size : int, default: 10
            Size of picked points if ``show_path`` is ``True``.

        line_width : float, default: 5.0
            Thickness of path representation if ``show_path`` is
            ``True``.

        tolerance : float, default: 0.025
            Specify tolerance for performing pick operation. Tolerance
            is specified as fraction of rendering window
            size.  Rendering window size is measured across diagonal.

        show_path : bool, default: True
            Show the picked path interactively.

        keep_order : bool, default: True
            If ``True``, the created geodesic path is a single ordered
            and cleaned line from the first point to the last.

            .. note::

                In older versions there were apparent discontinuities
                in the resulting path due to the behavior of the
                underlying VTK filter which corresponds to
                ``keep_order=False``.

            .. versionadded:: 0.32.0

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the picked path is interactively displayed.

        """
        kwargs.setdefault('pickable', False)

        self.picked_geodesic = pyvista.PolyData()
        self._last_picked_idx = None

        def _the_callback(mesh, idx):
            if mesh is None:
                return
            point = mesh.points[idx]
            if self._last_picked_idx is None:
                self.picked_geodesic = pyvista.PolyData(point)
                self.picked_geodesic['vtkOriginalPointIds'] = [idx]
            else:
                surface = mesh.extract_surface().triangulate()
                locator = _vtk.vtkPointLocator()
                locator.SetDataSet(surface)
                locator.BuildLocator()
                start_idx = locator.FindClosestPoint(mesh.points[self._last_picked_idx])
                end_idx = locator.FindClosestPoint(point)
                self.picked_geodesic += surface.geodesic(start_idx, end_idx, keep_order=keep_order)
                if keep_order:
                    # it makes sense to remove adjacent duplicate points
                    self.picked_geodesic.clean(
                        inplace=True,
                        lines_to_points=False,
                        polys_to_lines=False,
                        strips_to_polys=False,
                    )
            self._last_picked_idx = idx

            if show_path:
                self.add_mesh(
                    self.picked_geodesic,
                    color=color,
                    name='_picked_path',
                    line_width=line_width,
                    point_size=point_size,
                    reset_camera=False,
                    **kwargs,
                )
            if callable(callback):
                try_callback(callback, self.picked_geodesic)

        def _clear_g_path_event_watcher():
            self.picked_geodesic = pyvista.PolyData()
            self.remove_actor('_picked_path')
            self._last_picked_idx = None

        self.add_key_event('c', _clear_g_path_event_watcher)
        if show_message is True:
            show_message = "Press P to pick under the mouse\nPress C to clear"

        self.enable_point_picking(
            callback=_the_callback,
            use_mesh=True,
            font_size=font_size,
            show_message=show_message,
            tolerance=tolerance,
            show_point=False,
        )

    def enable_horizon_picking(
        self,
        callback=None,
        normal=(0.0, 0.0, 1.0),
        width=None,
        show_message=True,
        font_size=18,
        color='pink',
        point_size=10,
        line_width=5,
        show_path=True,
        opacity=0.75,
        show_horizon=True,
        **kwargs,
    ):
        """Enable horizon picking.

        Helper for the ``enable_path_picking`` method to also show a
        ribbon surface along the picked path. Ribbon is saved under
        ``.picked_horizon``.

        Parameters
        ----------
        callback : callable, optional
            When given, calls this callable after a pick is made.  The
            entire picked path is passed as the only parameter to this
            callable.

        normal : sequence[float], default: (0.0, 0.0, 1.0)
            The normal to the horizon surface's projection plane.

        width : float, optional
            The width of the horizon surface. Default behaviour will
            dynamically change the surface width depending on its
            length.

        show_message : bool | str, default: True
            Show the message about how to use the horizon picking
            tool. If this is a string, that will be the message shown.

        font_size : int, default: 18
            Sets the font size of the message.

        color : ColorLike, default: "pink"
            The color of the horizon surface if shown.

        point_size : int, default: 10
            Size of picked points if ``show_horizon`` is ``True``.

        line_width : float, default: 5.0
            Thickness of path representation if ``show_horizon`` is
            ``True``.

        show_path : bool, default: True
            Show the picked path that the horizon is built from
            interactively.

        opacity : float, default: 0.75
            The opacity of the horizon surface if shown.

        show_horizon : bool, default: True
            Show the picked horizon surface interactively.

        **kwargs : dict, optional
            All remaining keyword arguments are used to control how
            the picked path is interactively displayed.

        """
        name = '_horizon'
        self.add_key_event('c', lambda: self.remove_actor(name))

        def _the_callback(path):
            if path.n_points < 2:
                self.remove_actor(name)
                return
            self.picked_horizon = path.ribbon(normal=normal, width=width)

            if show_horizon:
                self.add_mesh(
                    self.picked_horizon,
                    name=name,
                    color=color,
                    opacity=opacity,
                    pickable=False,
                    reset_camera=False,
                )

            if callable(callback):
                try_callback(callback, path)

        self.enable_path_picking(
            callback=_the_callback,
            show_message=show_message,
            font_size=font_size,
            color=color,
            point_size=point_size,
            line_width=line_width,
            show_path=show_path,
            **kwargs,
        )

    def enable_block_picking(
        self,
        callback=None,
        side='left',
    ):
        """Enable composite block picking.

        Use this picker to return the index of a DataSet when using composite
        dataset like :class:`pyvista.MultiBlock` and pass it to a callback.

        Parameters
        ----------
        callback : callable, optional
            When input, this picker calls this callable after a selection is
            made. The composite index is passed to ``callback`` as the first
            argument and the dataset as the second argument.

        side : str, default: "left"
            The mouse button to track (either ``'left'`` or ``'right'``).
            Also accepts ``'r'`` or ``'l'``.

        Notes
        -----
        The picked block index can be accessed from :attr:`picked_block_index
        <pyvista.Plotter.picked_block_index>` attribute.

        Examples
        --------
        Enable block picking with a multiblock dataset. Left clicking will turn
        blocks blue while right picking will turn the block back to the default
        color.

        >>> import pyvista as pv
        >>> multiblock = pv.MultiBlock(
        ...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
        ... )
        >>> pl = pv.Plotter()
        >>> actor, mapper = pl.add_composite(multiblock)
        >>> def turn_blue(index, dataset):
        ...     mapper.block_attr[index].color = 'blue'
        ...
        >>> pl.enable_block_picking(callback=turn_blue, side='left')
        >>> def clear_color(index, dataset):
        ...     mapper.block_attr[index].color = None
        ...
        >>> pl.enable_block_picking(callback=clear_color, side='right')
        >>> pl.show()

        """
        # use a weak reference to enable garbage collection
        renderer_ = weakref.ref(self.renderer)

        sel_index = _vtk.vtkSelectionNode.COMPOSITE_INDEX()
        sel_prop = _vtk.vtkSelectionNode.PROP()

        def get_picked_block(*args, **kwargs):
            """Get the picked block and pass it to the user callback."""
            x, y = self.mouse_position
            selector = _vtk.vtkOpenGLHardwareSelector()
            selector.SetRenderer(renderer_())
            selector.SetArea(x, y, x, y)  # single pixel
            selection = selector.Select()

            for ii in range(selection.GetNumberOfNodes()):
                node = selection.GetNode(ii)
                if node is None:  # pragma: no cover
                    continue
                node_prop = node.GetProperties()
                self._picked_block_index = node_prop.Get(sel_index)

                # Safely return the dataset as it's possible a non pyvista
                # mapper was added
                mapper = node_prop.Get(sel_prop).GetMapper()
                if isinstance(mapper, CompositePolyDataMapper):
                    dataset = mapper.block_attr.get_block(self._picked_block_index)
                else:  # pragma: no cover
                    dataset = None

                if callable(callback):
                    try_callback(callback, self._picked_block_index, dataset)

        self.track_click_position(callback=get_picked_block, viewport=True, side=side)

    def pick_click_position(self):
        """Get corresponding click location in the 3D plot.

        Returns
        -------
        tuple
            Three item tuple with the 3D picked position.

        """
        if self.click_position is None:
            self.store_click_position()
        picker = _vtk.vtkWorldPointPicker()
        picker.Pick(self.click_position[0], self.click_position[1], 0, self.renderer)
        return picker.GetPickPosition()

    def pick_mouse_position(self):
        """Get corresponding mouse location in the 3D plot.

        Returns
        -------
        tuple
            Three item tuple with the 3D picked position.

        """
        if self.mouse_position is None:
            self.store_mouse_position()
        picker = _vtk.vtkWorldPointPicker()
        picker.Pick(self.mouse_position[0], self.mouse_position[1], 0, self.renderer)
        return picker.GetPickPosition()

    def fly_to_mouse_position(self, focus=False):
        """Focus on last stored mouse position."""
        if self.mouse_position is None:
            self.store_mouse_position()
        click_point = self.pick_mouse_position()
        if focus:
            self.set_focus(click_point)
        else:
            self.fly_to(click_point)

    def enable_fly_to_right_click(self, callback=None):
        """Set the camera to track right click positions.

        A convenience method to track right click positions and fly to
        the picked point in the scene. The callback will be passed the
        point in 3D space.

        Parameters
        ----------
        callback : callable
            Callback to call immediately after right clicking.

        """

        def _the_callback(*args):
            click_point = self.pick_mouse_position()
            self.fly_to(click_point)
            if callable(callback):
                try_callback(callback, click_point)

        self.track_click_position(callback=_the_callback, side="right")

    def disable_picking(self):
        """Disable any active picking.

        Examples
        --------
        Enable and then disable picking.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere(center=(1, 0, 0))
        >>> cube = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh)
        >>> _ = pl.add_mesh(cube)
        >>> _ = pl.enable_mesh_picking(left_clicking=True)
        >>> pl.disable_picking()

        """
        if getattr(self, '_picker', None):
            self._picker.RemoveObservers(_vtk.vtkCommand.EndPickEvent)

        # remove left clicking observer if available
        if getattr(self, 'iren', None):
            self.iren.remove_observer(self._picking_left_clicking_observer)
        self._picking_left_clicking_observer = None

        # remove any picking text
        if hasattr(self, 'renderers'):
            self.remove_actor(self._picking_text, render=False)
        self._picking_text = None


# pyvista/plotting/prop3d.py

"""Prop3D module."""
from typing import Tuple

from pyvista import _vtk

from .._typing import BoundsLike, Vector


class Prop3D(_vtk.vtkProp3D):
    """Prop3D wrapper for vtkProp3D.

    Used to represent an entity in a rendering scene. It handles functions
    related to the position, orientation and scaling. Used as parent class
    in Actor and Volume class.
    """

    def __init__(self):
        """Initialize Prop3D."""
        super().__init__()

    @property
    def scale(self) -> Tuple[float, float, float]:
        """Return or set entity scale.

        Examples
        --------
        Create an actor using the :class:`pyvista.Plotter` and then change the
        scale of the actor.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(pv.Sphere())
        >>> actor.scale = (2.0, 2.0, 2.0)
        >>> actor.scale
        (2.0, 2.0, 2.0)

        """
        return self.GetScale()

    @scale.setter
    def scale(self, value: Vector):
        return self.SetScale(value)

    @property
    def position(self) -> Tuple[float, float, float]:
        """Return or set the entity position.

        Examples
        --------
        Change the position of an actor. Note how this does not change the
        position of the underlying dataset, just the relative location of the
        actor in the :class:`pyvista.Plotter`.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, color='b')
        >>> actor = pl.add_mesh(mesh, color='r')
        >>> actor.position = (0, 0, 1)  # shifts the red sphere up
        >>> pl.show()

        """
        return self.GetPosition()

    @position.setter
    def position(self, value: Vector):
        self.SetPosition(value)

    def rotate_x(self, angle: float):
        """Rotate the entity about the x axis.

        Parameters
        ----------
        angle : float
            Angle to rotate the entity about the x axis in degrees.

        Examples
        --------
        Rotate the actor about the x axis 45 degrees. Note how this does not
        change the location of the underlying dataset.

        >>> import pyvista as pv
        >>> mesh = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, color='b')
        >>> actor = pl.add_mesh(
        ...     mesh,
        ...     color='r',
        ...     style='wireframe',
        ...     line_width=5,
        ...     lighting=False,
        ... )
        >>> actor.rotate_x(45)
        >>> pl.show_axes()
        >>> pl.show()

        """
        self.RotateX(angle)

    def rotate_y(self, angle: float):
        """Rotate the entity about the y axis.

        Parameters
        ----------
        angle : float
            Angle to rotate the entity about the y axis in degrees.

        Examples
        --------
        Rotate the actor about the y axis 45 degrees. Note how this does not
        change the location of the underlying dataset.

        >>> import pyvista as pv
        >>> mesh = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, color='b')
        >>> actor = pl.add_mesh(
        ...     mesh,
        ...     color='r',
        ...     style='wireframe',
        ...     line_width=5,
        ...     lighting=False,
        ... )
        >>> actor.rotate_y(45)
        >>> pl.show_axes()
        >>> pl.show()

        """
        self.RotateY(angle)

    def rotate_z(self, angle: float):
        """Rotate the entity about the z axis.

        Parameters
        ----------
        angle : float
            Angle to rotate the entity about the z axis in degrees.

        Examples
        --------
        Rotate the actor about the Z axis 45 degrees. Note how this does not
        change the location of the underlying dataset.

        >>> import pyvista as pv
        >>> mesh = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, color='b')
        >>> actor = pl.add_mesh(
        ...     mesh,
        ...     color='r',
        ...     style='wireframe',
        ...     line_width=5,
        ...     lighting=False,
        ... )
        >>> actor.rotate_z(45)
        >>> pl.show_axes()
        >>> pl.show()

        """
        self.RotateZ(angle)

    @property
    def orientation(self) -> tuple:
        """Return or set the entity orientation.

        Orientation is defined as the rotation from the global axes in degrees
        about the actor's x, y, and z axes.

        Examples
        --------
        Reorient just the actor and plot it. Note how the actor is rotated
        about its own axes as defined by its position.

        >>> import pyvista as pv
        >>> mesh = pv.Cube()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, color='b')
        >>> actor = pl.add_mesh(
        ...     mesh,
        ...     color='r',
        ...     style='wireframe',
        ...     line_width=5,
        ...     lighting=False,
        ... )
        >>> actor.position = (0, 0, 1)
        >>> actor.orientation = (45, 0, 0)
        >>> pl.show_axes()
        >>> pl.show()

        Show that the orientation changes with rotation.

        >>> import pyvista as pv
        >>> mesh = pv.Cube()
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(mesh)
        >>> actor.rotate_x(90)
        >>> actor.orientation  # doctest:+SKIP
        (90, 0, 0)

        Set the orientation directly.

        >>> actor.orientation = (0, 45, 45)
        >>> actor.orientation  # doctest:+SKIP
        (0, 45, 45)

        """
        return self.GetOrientation()

    @orientation.setter
    def orientation(self, value: tuple):
        self.SetOrientation(value)

    @property
    def bounds(self) -> BoundsLike:
        """Return the bounds of the entity.

        Bounds are ``(-X, +X, -Y, +Y, -Z, +Z)``

        Examples
        --------
        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> mesh = pv.Cube(x_length=0.1, y_length=0.2, z_length=0.3)
        >>> actor = pl.add_mesh(mesh)
        >>> actor.bounds
        (-0.05, 0.05, -0.1, 0.1, -0.15, 0.15)

        """
        return self.GetBounds()

    @property
    def center(self) -> tuple:
        """Return the center of the entity.

        Examples
        --------
        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> actor = pl.add_mesh(pv.Sphere(center=(0.5, 0.5, 1)))
        >>> actor.center  # doctest:+SKIP
        (0.5, 0.5, 1)
        """
        return self.GetCenter()


# pyvista/plotting/render_passes.py

"""Render passes module for PyVista."""
import weakref

from pyvista import _vtk

# The order of both the pre and post-passes matters.
PRE_PASS = [
    'vtkEDLShading',
]

POST_PASS = [
    'vtkDepthOfFieldPass',
    'vtkGaussianBlurPass',
    'vtkOpenGLFXAAPass',
    'vtkSSAOPass',
    'vtkSSAAPass',  # should be last
]


class RenderPasses:
    """Class to support multiple render passes for a renderer.

    Notes
    -----
    Passes are organized here as "primary" (vtkOpenGLRenderPass) that act
    within the renderer and "post-processing" (vtkImageProcessingPass) passes,
    which act on the image generated from the renderer.

    The primary passes are added as part of a vtk.vtkRenderPassCollection or
    are "stacked", while the post-processing passes are added as a final pass
    to the rendered image.

    """

    def __init__(self, renderer):
        """Initialize render passes."""
        self._renderer_ref = weakref.ref(renderer)

        self._passes = {}
        self._fxaa_pass = None
        self._shadow_map_pass = None
        self._edl_pass = None
        self._dof_pass = None
        self._ssaa_pass = None
        self._ssao_pass = None
        self._blur_passes = []
        self.__pass_collection = None
        self.__seq_pass = None
        self.__camera_pass = None

    @property
    def _pass_collection(self):
        """Initialize (when necessary) the pass collection and return it.

        This lets us lazily generate the pass collection only when we need it
        rather than at initialization of the class.

        """
        if self.__pass_collection is None:
            self._init_passes()
        return self.__pass_collection

    @property
    def _seq_pass(self):
        """Initialize (when necessary) the sequence collection and return it.

        This lets us lazily generate the sequence collection only when we need it
        rather than at initialization of the class.

        """
        if self.__seq_pass is None:
            self._init_passes()
        return self.__seq_pass

    @property
    def _camera_pass(self):
        """Initialize (when necessary) the camera pass and return it.

        This lets us lazily generate the camera pass only when we need it
        rather than at initialization of the class.

        """
        if self.__camera_pass is None:
            self._init_passes()
        return self.__camera_pass

    def _init_passes(self):
        """Initialize the renderer's standard passes."""
        # simulate the standard VTK rendering passes and put them in a sequence
        self.__pass_collection = _vtk.vtkRenderPassCollection()
        self.__pass_collection.AddItem(_vtk.vtkRenderStepsPass())

        self.__seq_pass = _vtk.vtkSequencePass()
        self.__seq_pass.SetPasses(self._pass_collection)

        # Make the sequence the delegate of a camera pass.
        self.__camera_pass = _vtk.vtkCameraPass()
        self.__camera_pass.SetDelegatePass(self._seq_pass)

    @property
    def _renderer(self):
        """Return the renderer."""
        if self._renderer_ref is not None:
            return self._renderer_ref()

    def deep_clean(self):
        """Delete all render passes."""
        if self._renderer is not None:
            self._renderer.SetPass(None)
        self._renderer_ref = None
        if self.__seq_pass is not None:
            self.__seq_pass.SetPasses(None)
        self.__seq_pass = None
        self.__pass_collection = None
        self.__camera_pass = None
        self._passes = {}
        self._shadow_map_pass = None
        self._edl_pass = None
        self._dof_pass = None
        self._ssaa_pass = None
        self._ssao_pass = None
        self._blur_passes = []

    def enable_edl_pass(self):
        """Enable the EDL pass."""
        if self._edl_pass is not None:
            return
        self._edl_pass = _vtk.vtkEDLShading()
        self._add_pass(self._edl_pass)
        return self._edl_pass

    def disable_edl_pass(self):
        """Disable the EDL pass."""
        if self._edl_pass is None:
            return
        self._remove_pass(self._edl_pass)
        self._edl_pass = None

    def add_blur_pass(self):
        """Add a vtkGaussianBlurPass pass.

        This is a vtkImageProcessingPass and delegates to the last pass.

        """
        blur_pass = _vtk.vtkGaussianBlurPass()
        self._add_pass(blur_pass)
        self._blur_passes.append(blur_pass)
        return blur_pass

    def remove_blur_pass(self):
        """Remove a single vtkGaussianBlurPass pass."""
        if self._blur_passes:
            # order of the blur passes does not matter
            self._remove_pass(self._blur_passes.pop())

    def enable_shadow_pass(self):
        """Enable shadow pass."""
        # shadow pass can be directly added to the base pass collection
        if self._shadow_map_pass is not None:
            return
        self._shadow_map_pass = _vtk.vtkShadowMapPass()
        self._pass_collection.AddItem(self._shadow_map_pass.GetShadowMapBakerPass())
        self._pass_collection.AddItem(self._shadow_map_pass)
        self._update_passes()
        return self._shadow_map_pass

    def disable_shadow_pass(self):
        """Disable shadow pass."""
        if self._shadow_map_pass is None:
            return
        self._pass_collection.RemoveItem(self._shadow_map_pass.GetShadowMapBakerPass())
        self._pass_collection.RemoveItem(self._shadow_map_pass)
        self._update_passes()

    def enable_depth_of_field_pass(self, automatic_focal_distance=True):
        """Enable the depth of field pass."""
        if self._dof_pass is not None:
            return

        if self._ssao_pass is not None:
            raise RuntimeError('Depth of field pass is incompatible with the SSAO pass.')

        self._dof_pass = _vtk.vtkDepthOfFieldPass()
        self._dof_pass.SetAutomaticFocalDistance(automatic_focal_distance)
        self._add_pass(self._dof_pass)
        return self._dof_pass

    def disable_depth_of_field_pass(self):
        """Disable the depth of field pass."""
        if self._dof_pass is None:
            return
        self._remove_pass(self._dof_pass)
        self._dof_pass = None

    def enable_ssao_pass(self, radius, bias, kernel_size, blur):
        """Enable the screen space ambient occlusion pass."""
        if self._dof_pass is not None:
            raise RuntimeError('SSAO pass is incompatible with the depth of field pass.')

        if self._ssao_pass is not None:
            return
        self._ssao_pass = _vtk.vtkSSAOPass()
        self._ssao_pass.SetRadius(radius)
        self._ssao_pass.SetBias(bias)
        self._ssao_pass.SetKernelSize(kernel_size)
        self._ssao_pass.SetBlur(blur)
        self._add_pass(self._ssao_pass)
        return self._ssao_pass

    def disable_ssao_pass(self):
        """Disable the screen space ambient occlusion pass."""
        if self._ssao_pass is None:
            return
        self._remove_pass(self._ssao_pass)
        self._ssao_pass = None

    def enable_ssaa_pass(self):
        """Enable super-sample anti-aliasing pass."""
        if self._ssaa_pass is not None:
            return
        self._ssaa_pass = _vtk.vtkSSAAPass()
        self._add_pass(self._ssaa_pass)
        return self._ssaa_pass

    def disable_ssaa_pass(self):
        """Disable super-sample anti-aliasing pass."""
        if self._ssaa_pass is None:
            return
        self._remove_pass(self._ssaa_pass)
        self._ssaa_pass = None

    def _update_passes(self):
        """Reassemble pass delegation."""
        if self._renderer is None:  # pragma: no cover
            raise RuntimeError('The renderer has been closed.')

        current_pass = self._camera_pass
        for class_name in PRE_PASS + POST_PASS:
            if class_name in self._passes:
                for render_pass in self._passes[class_name]:
                    render_pass.SetDelegatePass(current_pass)
                    current_pass = render_pass

        # reset to the default rendering if no special passes have been added
        if current_pass is self._camera_pass and self._shadow_map_pass is None:
            self._renderer.SetPass(None)
        else:
            self._renderer.SetPass(current_pass)

    def _add_pass(self, render_pass):
        """Add a render pass."""
        class_name = render_pass.GetClassName()

        if class_name in PRE_PASS and render_pass in self._passes:
            return

        if class_name not in self._passes:
            self._passes[class_name] = [render_pass]
        else:
            self._passes[class_name].append(render_pass)

        self._update_passes()

    def _remove_pass(self, render_pass):
        """Remove a pass.

        Remove a pass and reassemble the pass ordering.

        """
        class_name = render_pass.GetClassName()

        if class_name not in self._passes:  # pragma: no cover
            return
        else:
            self._passes[class_name].remove(render_pass)
            if not self._passes[class_name]:
                self._passes.pop(class_name)

        self._update_passes()


# pyvista/plotting/render_window_interactor.py

"""Wrap vtk.vtkRenderWindowInteractor."""
import collections.abc
from functools import partial
import logging
import time
import warnings
import weakref

from pyvista import _vtk
from pyvista.utilities import try_callback
from pyvista.utilities.misc import vtk_version_info

log = logging.getLogger(__name__)
log.setLevel('CRITICAL')
log.addHandler(logging.StreamHandler())

_CLASSES = {}


class RenderWindowInteractor:
    """Wrap vtk.vtkRenderWindowInteractor.

    This class has been added for the purpose of making some methods
    we add to the RenderWindowInteractor more python, like certain
    testing methods.

    """

    def __init__(self, plotter, desired_update_rate=30, light_follow_camera=True, interactor=None):
        """Initialize."""
        if interactor is None:
            interactor = _vtk.vtkRenderWindowInteractor()
        self.interactor = interactor
        self.interactor.SetDesiredUpdateRate(desired_update_rate)
        if not light_follow_camera:
            self.interactor.LightFollowCameraOff()

        # Map of observers to events
        self._observers = {}
        self._key_press_event_callbacks = collections.defaultdict(list)
        self._click_event_callbacks = {
            event: {(double, v): [] for double in (False, True) for v in (False, True)}
            for event in ("LeftButtonPressEvent", "RightButtonPressEvent")
        }
        self._click_time = 0
        self._MAX_CLICK_DELAY = 0.8  # seconds
        self._MAX_CLICK_DELTA = 40  # squared => ~6 pixels

        # Set default style
        self._style = 'RubberBandPick'
        self._style_class = None
        self.__plotter = weakref.ref(plotter)

        # Toggle interaction style when clicked on a visible chart (to
        # enable interaction with visible charts)
        self._context_style = _vtk.vtkContextInteractorStyle()
        self.track_click_position(
            self._toggle_chart_interaction, side="left", double=True, viewport=True
        )

    @property
    def _plotter(self):
        """Return the plotter."""
        return self.__plotter()

    def add_key_event(self, key, callback):
        """Add a function to callback when the given key is pressed.

        These are non-unique - thus a key could map to many callback
        functions. The callback function must not have any arguments.

        Parameters
        ----------
        key : str
            The key to trigger the event.

        callback : callable
            A callable that takes no arguments.

        """
        if not callable(callback):
            raise TypeError('callback must be callable.')
        self._key_press_event_callbacks[key].append(callback)

    @staticmethod
    def _get_event_str(event):
        if isinstance(event, str):
            # Make sure we pass it at least once through these functions, such that
            # invalid event names are mapped to "NoEvent".
            event = _vtk.vtkCommand.GetEventIdFromString(event)
        return _vtk.vtkCommand.GetStringFromEventId(event)

    def add_observer(self, event, call):
        """Add an observer for the given event.

        Parameters
        ----------
        event : str | int
            The event to observe. Either the name of this event (string) or
            a VTK event identifier (int).

        call : callable
            Callback to be called when the event is invoked.

        Returns
        -------
        int
            The identifier of the added observer.

        Examples
        --------
        Add a custom observer.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> obs_enter = pl.iren.add_observer(
        ...     "EnterEvent", lambda *_: print('Enter!')
        ... )

        """
        call = partial(try_callback, call)
        event = self._get_event_str(event)
        observer = self.interactor.AddObserver(event, call)
        self._observers[observer] = event
        return observer

    def remove_observer(self, observer):
        """Remove an observer.

        Parameters
        ----------
        observer : int
            The identifier of the observer to remove.

        Examples
        --------
        Add an observer and immediately remove it.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> obs_enter = pl.iren.add_observer(
        ...     "EnterEvent", lambda *_: print('Enter!')
        ... )
        >>> pl.iren.remove_observer(obs_enter)

        """
        if observer in self._observers:
            self.interactor.RemoveObserver(observer)
            del self._observers[observer]

    def remove_observers(self, event=None):
        """Remove all observers.

        Parameters
        ----------
        event : str | int, optional
            If provided, only removes observers of the given event. Otherwise,
            if it is ``None``, removes all observers.

        Examples
        --------
        Add two observers and immediately remove them.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> obs_enter = pl.iren.add_observer(
        ...     "EnterEvent", lambda *_: print('Enter!')
        ... )
        >>> obs_leave = pl.iren.add_observer(
        ...     "LeaveEvent", lambda *_: print('Leave!')
        ... )
        >>> pl.iren.remove_observers()

        """
        if event is None:
            observers = list(self._observers.keys())
        else:
            event = self._get_event_str(event)
            observers = [obs for obs, ev in self._observers.items() if event == ev]
        for observer in observers:
            self.remove_observer(observer)

    def clear_events_for_key(self, key, raise_on_missing=False):
        """Remove the callbacks associated to the key.

        Parameters
        ----------
        key : str
            Key to clear events for.

        raise_on_missing : bool, default: False
            Whether to raise a :class:`ValueError` if there are no events
            registered for the given key.
        """
        try:
            self._key_press_event_callbacks.pop(key)
        except KeyError:
            if raise_on_missing:
                raise ValueError(f'No events found for key {key!r}.') from None

    def track_mouse_position(self, callback):
        """Keep track of the mouse position.

        This will potentially slow down the interactor. No callbacks supported
        here - use :func:`pyvista.Plotter.track_click_position` instead.

        """
        self.add_observer(_vtk.vtkCommand.MouseMoveEvent, callback)

    def untrack_mouse_position(self):
        """Stop tracking the mouse position."""
        self.remove_observers(_vtk.vtkCommand.MouseMoveEvent)

    @staticmethod
    def _get_click_event(side):
        side = str(side).lower()
        if side in ["right", "r"]:
            return "RightButtonPressEvent"
        elif side in ["left", "l"]:
            return "LeftButtonPressEvent"
        else:
            raise TypeError(f"Side ({side}) not supported. Try `left` or `right`.")

    def _click_event(self, obj, event):
        t = time.time()
        dt = t - self._click_time
        last_pos = self._plotter.click_position or (0, 0)

        self._plotter.store_click_position()
        dp = (self._plotter.click_position[0] - last_pos[0]) ** 2
        dp += (self._plotter.click_position[1] - last_pos[1]) ** 2
        double = dp < self._MAX_CLICK_DELTA and dt < self._MAX_CLICK_DELAY
        # Reset click time in case of a double click, otherwise a subsequent third click
        # is considered to be a double click as well.
        self._click_time = 0 if double else t

        for callback in self._click_event_callbacks[event][double, False]:
            callback(self._plotter.pick_click_position())
        for callback in self._click_event_callbacks[event][double, True]:
            callback(self._plotter.click_position)

    def track_click_position(self, callback=None, side="right", double=False, viewport=False):
        """Keep track of the click position.

        By default, it only tracks right clicks.

        Parameters
        ----------
        callback : callable, optional
            A callable method that will use the click position. Passes
            the click position as a length two tuple.

        side : str, default: "right"
            The mouse button to track (either ``'left'`` or ``'right'``).
            Also accepts ``'r'`` or ``'l'``.

        double : bool, default: False
            Track single clicks if ``False``, double clicks if ``True``.
            Defaults to single clicks.

        viewport : bool, default: False
            If ``True``, uses the normalized viewport coordinate
            system (values between 0.0 and 1.0 and support for HiDPI)
            when passing the click position to the callback.

        """
        event = self._get_click_event(side)
        add_observer = all(len(cbs) == 0 for cbs in self._click_event_callbacks[event].values())
        if callback is None and add_observer:
            # No observers for this event yet and custom callback not given => insert dummy callback
            callback = lambda obs, event: None
        if callable(callback):
            self._click_event_callbacks[event][double, viewport].append(callback)
        else:
            raise ValueError(
                "Invalid callback provided, it should be either ``None`` or a callable."
            )

        if add_observer:
            self.add_observer(event, self._click_event)

    def untrack_click_position(self, side="right"):
        """Stop tracking the click position.

        Parameters
        ----------
        side : str, optional
            The mouse button to stop tracking (either ``'left'`` or
            ``'right'``). Default is ``'right'``. Also accepts ``'r'``
            or ``'l'``.

        """
        event = self._get_click_event(side)
        self.remove_observers(event)
        for cbs in self._click_event_callbacks[event].values():
            cbs.clear()

    def clear_key_event_callbacks(self):
        """Clear key event callbacks."""
        self._key_press_event_callbacks.clear()

    def key_press_event(self, obj, event):
        """Listen for key press event."""
        key = self.interactor.GetKeySym()
        log.debug(f'Key {key} pressed')
        self._last_key = key
        if key in self._key_press_event_callbacks.keys():
            # Note that defaultdict's will never throw a key error
            callbacks = self._key_press_event_callbacks[key]
            for func in callbacks:
                func()

    def update_style(self):
        """Update the camera interactor style."""
        if self._style_class is None:
            # We need an actually custom style to handle button up events
            self._style_class = _style_factory(self._style)(self)
        self.interactor.SetInteractorStyle(self._style_class)

    def _toggle_chart_interaction(self, mouse_pos):
        """Toggle interaction with indicated charts.

        Parameters
        ----------
        mouse_pos : tuple of float
            Tuple containing the mouse position.

        """
        # Loop over all renderers to see whether any charts need to be made interactive
        interactive_scene = None
        for renderer in self._plotter.renderers:
            if interactive_scene is None and renderer.IsInViewport(*mouse_pos):
                # No interactive charts yet and mouse is within this renderer's viewport,
                # so collect all charts indicated by the mouse (typically only one, except
                # when there are overlapping charts).
                origin = renderer.GetOrigin()  # Correct for viewport origin (see #3278)
                charts = renderer._get_charts_by_pos(
                    (mouse_pos[0] - origin[0], mouse_pos[1] - origin[1])
                )
                if charts:
                    # Toggle interaction for indicated charts and determine whether
                    # there are any remaining interactive charts.
                    interactive_charts = renderer.set_chart_interaction(charts, toggle=True)
                    if interactive_charts:
                        # Save a reference to this renderer's scene if there are
                        # remaining interactive charts.
                        interactive_scene = renderer._charts._scene
                else:
                    # No indicated charts, so disable interaction with all charts
                    # for this renderer.
                    renderer.set_chart_interaction(False)
            else:
                # Not in viewport or interactive charts were already found in another
                # renderer, so disable interaction with all charts for this renderer.
                renderer.set_chart_interaction(False)
        # Manually set context_style based on found interactive scene (or stop interaction
        # with any scene if there are no interactive charts).
        self._set_context_style(interactive_scene)

    def _set_context_style(self, scene):
        """
        Set the context style interactor or switch back to previous interactor style.

        Parameters
        ----------
        scene : vtkContextScene, optional
            The scene to interact with or ``None`` to stop interaction with any scene.

        """
        # Set scene to interact with or reset it to stop interaction (otherwise crash)
        if vtk_version_info < (9, 3, 0):  # pragma: no cover
            if scene is not None and len(self._plotter.renderers) > 1:
                warnings.warn(
                    "Interaction with charts is not possible when using multiple subplots."
                    "Upgrade to VTK 9.3 or newer to enable this feature."
                )
                scene = None
        self._context_style.SetScene(scene)
        if scene is None and self._style == "Context":
            # Switch back to previous interactor style
            self._style = self._prev_style
            self._style_class = self._prev_style_class
            self._prev_style = None
            self._prev_style_class = None
        elif scene is not None and self._style != "Context":
            # Enable context interactor style
            self._prev_style = self._style
            self._prev_style_class = self._style_class
            self._style = "Context"
            self._style_class = self._context_style
        self.update_style()

    def enable_trackball_style(self):
        """Set the interactive style to Trackball Camera.

        The trackball camera is the default interactor style. Moving
        the mouse moves the camera around, leaving the scene intact.

        For a 3-button mouse, the left button is for rotation, the
        right button for zooming, the middle button for panning, and
        ctrl + left button for spinning the view around the vewing
        axis of the camera.  Alternatively, ctrl + shift + left button
        or mouse wheel zooms, and shift + left button pans.

        Examples
        --------
        Create a simple scene with a plotter that has the Trackball
        Camera interactive style (which is also the default):

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_trackball_style()
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'TrackballCamera'
        self._style_class = None
        self.update_style()

    def enable_trackball_actor_style(self):
        """Set the interactive style to Trackball Actor.

        This allows to rotate actors around the scene. The controls
        are similar to the default Trackball Camera style, but
        movements transform specific objects under the mouse cursor.

        For a 3-button mouse, the left button is for rotation, the
        right button for zooming, the middle button for panning, and
        ctrl + left button for spinning objects around the axis
        connecting the camera with the their center.  Alternatively,
        shift + left button pans.

        Examples
        --------
        Create a simple scene with a plotter that has the Trackball
        Actor interactive style:

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_trackball_actor_style()
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'TrackballActor'
        self._style_class = None
        self.update_style()

    def enable_image_style(self):
        """Set the interactive style to Image.

        Controls:
         - Left Mouse button triggers window level events
         - CTRL Left Mouse spins the camera around its view plane normal
         - SHIFT Left Mouse pans the camera
         - CTRL SHIFT Left Mouse dollies (a positional zoom) the camera
         - Middle mouse button pans the camera
         - Right mouse button dollies the camera
         - SHIFT Right Mouse triggers pick events

        Examples
        --------
        Create a simple scene with a plotter that has the Image
        interactive style:

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_image_style()
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'Image'
        self._style_class = None
        self.update_style()

    def enable_joystick_style(self):
        """Set the interactive style to Joystick Camera.

        It allows the user to move (rotate, pan, etc.) the camera, the
        point of view for the scene.  The position of the mouse
        relative to the center of the scene determines the speed at
        which the camera moves, so the camera continues to move even
        if the mouse if not moving.

        For a 3-button mouse, the left button is for rotation, the
        right button for zooming, the middle button for panning, and
        ctrl + left button for spinning.  (With fewer mouse buttons,
        ctrl + shift + left button is for zooming, and shift + left
        button is for panning.)

        Examples
        --------
        Create a simple scene with a plotter that has the Joystick
        Camera interactive style:

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_joystick_style()
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'JoystickCamera'
        self._style_class = None
        self.update_style()

    def enable_joystick_actor_style(self):
        """Set the interactive style to Joystick Actor.

        Similar to the Joystick Camera interaction style, however
        in case of the Joystick Actor style the objects in the scene
        rather than the camera can be moved (rotated, panned, etc.).
        The position of the mouse relative to the center of the object
        determines the speed at which the object moves, so the object
        continues to move even if the mouse is not moving.

        For a 3-button mouse, the left button is for rotation, the
        right button for zooming, the middle button for panning, and
        ctrl + left button for spinning.  (With fewer mouse buttons,
        ctrl + shift + left button is for zooming, and shift + left
        button is for panning.)

        Examples
        --------
        Create a simple scene with a plotter that has the Joystick
        Actor interactive style:

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_joystick_actor_style()
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'JoystickActor'
        self._style_class = None
        self.update_style()

    def enable_zoom_style(self):
        """Set the interactive style to Rubber Band Zoom.

        This interactor style allows the user to draw a rectangle in
        the render window using the left mouse button.  When the mouse
        button is released, the current camera zooms by an amount
        determined from the shorter side of the drawn rectangle.

        Examples
        --------
        Create a simple scene with a plotter that has the Rubber Band
        Zoom interactive style:

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_zoom_style()
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'RubberBandZoom'
        self._style_class = None
        self.update_style()

    def enable_terrain_style(self, mouse_wheel_zooms=False, shift_pans=False):
        """Set the interactive style to Terrain.

        Used to manipulate a camera which is viewing a scene with a
        natural view up, e.g., terrain. The camera in such a scene is
        manipulated by specifying azimuth (angle around the view up
        vector) and elevation (the angle from the horizon). Similar to
        the default Trackball Camera style and in contrast to the
        Joystick Camera style, movements of the mouse translate to
        movements of the camera.

        Left mouse click rotates the camera around the focal point
        using both elevation and azimuth invocations on the camera.
        Left mouse motion in the horizontal direction results in
        azimuth motion; left mouse motion in the vertical direction
        results in elevation motion. Therefore, diagonal motion results
        in a combination of azimuth and elevation. (If the shift key is
        held during motion, then only one of elevation or azimuth is
        invoked, depending on the whether the mouse motion is primarily
        horizontal or vertical.) Middle mouse button pans the camera
        across the scene (again the shift key has a similar effect on
        limiting the motion to the vertical or horizontal direction.
        The right mouse is used to dolly towards or away from the focal
        point (zoom in or out). Panning and zooming behavior can be
        overridden to match the Trackball Camera style.

        The class also supports some keypress events. The ``r`` key
        resets the camera. The ``e`` key invokes the exit callback
        and closes the plotter. The ``f`` key sets a new
        camera focal point and flies towards that point. The ``u``
        key invokes the user event. The ``3`` key toggles between
        stereo and non-stero mode. The ``l`` key toggles on/off
        latitude/longitude markers that can be used to estimate/control
        position.

        Parameters
        ----------
        mouse_wheel_zooms : bool, default: False
            Whether to use the mouse wheel for zooming. By default
            zooming can be performed with right click and drag.

        shift_pans : bool, default: False
            Whether shift + left mouse button pans the scene. By default
            shift + left mouse button rotates the view restricted to
            only horizontal or vertical movements, and panning is done
            holding down the middle mouse button.

        Examples
        --------
        Create a simple scene with a plotter that has the Terrain
        interactive style:

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_terrain_style()
        >>> plotter.show()  # doctest:+SKIP

        Use controls that are closer to the default style:

        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_terrain_style(
        ...     mouse_wheel_zooms=True, shift_pans=True
        ... )
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'Terrain'
        self._style_class = None
        self.update_style()

        if mouse_wheel_zooms:

            def wheel_zoom_callback(obj, event):  # pragma: no cover
                """Zoom in or out on mouse wheel roll."""
                if event == 'MouseWheelForwardEvent':
                    # zoom in
                    zoom_factor = 1.1
                elif event == 'MouseWheelBackwardEvent':
                    # zoom out
                    zoom_factor = 1 / 1.1
                self._plotter.camera.zoom(zoom_factor)
                self._plotter.render()

            callback = partial(try_callback, wheel_zoom_callback)

            for event in 'MouseWheelForwardEvent', 'MouseWheelBackwardEvent':
                self._style_class.add_observer(event, callback)

        if shift_pans:

            def pan_on_shift_callback(obj, event):  # pragma: no cover
                """Trigger left mouse panning if shift is pressed."""
                if event == 'LeftButtonPressEvent':
                    if self.interactor.GetShiftKey():
                        self._style_class.StartPan()
                    self._style_class.OnLeftButtonDown()
                elif event == 'LeftButtonReleaseEvent':
                    # always stop panning on release
                    self._style_class.EndPan()
                    self._style_class.OnLeftButtonUp()

            callback = partial(try_callback, pan_on_shift_callback)

            for event in 'LeftButtonPressEvent', 'LeftButtonReleaseEvent':
                self._style_class.add_observer(event, callback)

    def enable_rubber_band_style(self):
        """Set the interactive style to Rubber Band Picking.

        This interactor style allows the user to draw a rectangle in
        the render window by hitting ``r`` and then using the left
        mouse button. When the mouse button is released, the attached
        picker operates on the pixel in the center of the selection
        rectangle. If the picker happens to be a ``vtkAreaPicker``
        it will operate on the entire selection rectangle. When the
        ``p`` key is hit the above pick operation occurs on a 1x1
        rectangle. In other respects it behaves the same as the
        Trackball Camera style.

        Examples
        --------
        Create a simple scene with a plotter that has the Rubber Band
        Pick interactive style:

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_rubber_band_style()
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'RubberBandPick'
        self._style_class = None
        self.update_style()

    def enable_rubber_band_2d_style(self):
        """Set the interactive style to Rubber Band 2D.

        Camera rotation is not enabled with this interactor
        style. Zooming affects the camera's parallel scale only, and
        assumes that the camera is in parallel projection mode. The
        style also allows to draw a rubber band using the left mouse
        button. All camera changes invoke ``StartInteractionEvent`` when
        the button is pressed, ``InteractionEvent`` when the mouse (or
        wheel) is moved, and ``EndInteractionEvent`` when the button is
        released. The bindings are as follows:

          * Left mouse: Select (invokes a ``SelectionChangedEvent``).
          * Right mouse: Zoom.
          * Middle mouse: Pan.
          * Scroll wheel: Zoom.

        Examples
        --------
        Create a simple scene with a plotter that has the Rubber Band
        2D interactive style:

        >>> import pyvista as pv
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
        >>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
        >>> plotter.show_axes()
        >>> plotter.enable_rubber_band_2d_style()
        >>> plotter.show()  # doctest:+SKIP

        """
        self._style = 'RubberBand2D'
        self._style_class = None
        self.update_style()

    def _simulate_keypress(self, key):  # pragma: no cover
        """Simulate a keypress."""
        if len(key) > 1:
            raise ValueError('Only accepts a single key')
        self.interactor.SetKeyCode(key)
        self.interactor.CharEvent()

    def _mouse_left_button_press(self, x=None, y=None):  # pragma: no cover
        """Simulate a left mouse button press.

        If ``x`` and ``y`` are entered then simulates a movement to
        that position.

        """
        if x is not None and y is not None:
            self._mouse_move(x, y)
        self.interactor.LeftButtonPressEvent()

    def _mouse_left_button_release(self, x=None, y=None):  # pragma: no cover
        """Simulate a left mouse button release."""
        if x is not None and y is not None:
            self._mouse_move(x, y)
        self.interactor.LeftButtonReleaseEvent()

    def _mouse_left_button_click(self, x=None, y=None, count=1):
        for _ in range(count):
            self._mouse_left_button_press(x, y)
            self._mouse_left_button_release()

    def _mouse_right_button_press(self, x=None, y=None):  # pragma: no cover
        """Simulate a right mouse button press.

        If ``x`` and ``y`` are entered then simulates a movement to
        that position.

        """
        if x is not None and y is not None:
            self._mouse_move(x, y)
        self.interactor.RightButtonPressEvent()

    def _mouse_right_button_release(self, x=None, y=None):  # pragma: no cover
        """Simulate a right mouse button release."""
        if x is not None and y is not None:
            self._mouse_move(x, y)
        self.interactor.RightButtonReleaseEvent()

    def _mouse_right_button_click(self, x=None, y=None, count=1):
        for _ in range(count):
            self._mouse_right_button_press(x, y)
            self._mouse_right_button_release()

    def _mouse_move(self, x, y):  # pragma: no cover
        """Simulate moving the mouse to ``(x, y)`` screen coordinates."""
        self.interactor.SetEventInformation(x, y)
        self.interactor.MouseMoveEvent()

    def get_event_position(self):
        """Get the event position.

        Returns
        -------
        tuple
            The ``(x, y)`` coordinate position.

        """
        return self.interactor.GetEventPosition()

    def get_interactor_style(self):
        """Get the interactor style.

        Returns
        -------
        vtk.vtkInteractorStyle
            VTK interactor style.
        """
        return self.interactor.GetInteractorStyle()

    def get_desired_update_rate(self):
        """Get the desired update rate.

        Returns
        -------
        float
            Desired update rate.
        """
        return self.interactor.GetDesiredUpdateRate()

    def create_timer(self, duration, repeating=True):
        """Create a timer.

        Parameters
        ----------
        duration : int
            Time (in milliseconds) before the timer emits a TimerEvent.

        repeating : bool, default: True
            When ``False`` a one-shot timer is created, which only fires
            once. When ``True`` a repeating timer is created, which
            continuously fires (every ``duration`` milliseconds) until
            destruction.

        Returns
        -------
        int
            Timer ID.
        """
        if repeating:
            timer_id = self.interactor.CreateRepeatingTimer(duration)
        else:
            timer_id = self.interactor.CreateOneShotTimer(duration)
        return timer_id

    def destroy_timer(self, timer_id):
        """Destroy the given timer."""
        self.interactor.DestroyTimer(timer_id)

    def start(self):
        """Start interactions."""
        self.interactor.Start()

    def initialize(self):
        """Initialize the interactor."""
        self.interactor.Initialize()

    def set_render_window(self, render_window):
        """Set the render window."""
        self.interactor.SetRenderWindow(render_window)

    def process_events(self):
        """Process events."""
        if not self.initialized:
            raise RuntimeError(
                'Render window interactor must be initialized before processing events.'
            )
        self.interactor.ProcessEvents()

    @property
    def initialized(self):
        """Return if the interactor has been initialized."""
        return self.interactor.GetInitialized()

    def get_picker(self):
        """Get the picker.

        Returns
        -------
        vtk.vtkAbstractPicker
            VTK picker.
        """
        return self.interactor.GetPicker()

    def set_picker(self, picker):
        """Set the picker."""
        self.interactor.SetPicker(picker)

    def fly_to(self, renderer, point):
        """Fly to the given point."""
        self.interactor.FlyTo(renderer, *point)

    def terminate_app(self):
        """Terminate the app."""
        if self.initialized:
            # #################################################################
            # 9.0.2+ compatibility:
            # See: https://gitlab.kitware.com/vtk/vtk/-/issues/18242
            if hasattr(self.interactor, 'GetDone'):
                self.interactor.SetDone(True)
            # #################################################################

            self.interactor.TerminateApp()

    def close(self):
        """Close out the render window interactor.

        This will terminate the render window if it is not already closed.
        """
        self.remove_observers()
        if self._style_class == self._context_style:  # pragma: no cover
            self._set_context_style(None)  # Disable context interactor style first
        if self._style_class is not None:
            self._style_class.remove_observers()
            self._style_class = None

        self.terminate_app()
        self.interactor = None
        self._click_event_callbacks = None


def _style_factory(klass):
    """Create a subclass with capturing ability, return it."""
    # We have to use a custom subclass for this because the default ones
    # swallow the release events
    # http://vtk.1045678.n5.nabble.com/Mouse-button-release-event-is-still-broken-in-VTK-6-0-0-td5724762.html  # noqa

    def _make_class(klass):
        """Make the class."""
        try:
            from vtkmodules import vtkInteractionStyle
        except ImportError:  # pragma: no cover
            import vtk as vtkInteractionStyle

        class CustomStyle(getattr(vtkInteractionStyle, 'vtkInteractorStyle' + klass)):
            def __init__(self, parent):
                super().__init__()
                self._parent = weakref.ref(parent)

                self._observers = []
                self._observers.append(
                    self.AddObserver("LeftButtonPressEvent", partial(try_callback, self._press))
                )
                self._observers.append(
                    self.AddObserver("LeftButtonReleaseEvent", partial(try_callback, self._release))
                )

            def _press(self, obj, event):
                # Figure out which renderer has the event and disable the
                # others
                super().OnLeftButtonDown()
                parent = self._parent()
                if len(parent._plotter.renderers) > 1:
                    click_pos = parent.get_event_position()
                    for renderer in parent._plotter.renderers:
                        interact = renderer.IsInViewport(*click_pos)
                        renderer.SetInteractive(interact)

            def _release(self, obj, event):
                super().OnLeftButtonUp()
                parent = self._parent()
                if len(parent._plotter.renderers) > 1:
                    for renderer in parent._plotter.renderers:
                        renderer.SetInteractive(True)

            def add_observer(self, event, callback):
                self._observers.append(self.AddObserver(event, callback))

            def remove_observers(self):
                for obs in self._observers:
                    self.RemoveObserver(obs)

        return CustomStyle

    # cache classes
    if klass not in _CLASSES:
        _CLASSES[klass] = _make_class(klass)
    return _CLASSES[klass]


# pyvista/plotting/renderer.py

"""Module containing pyvista implementation of vtkRenderer."""

import collections.abc
from functools import partial, wraps
from typing import Sequence, cast
import warnings

import numpy as np

import pyvista
from pyvista import MAX_N_COLOR_BARS, _vtk
from pyvista.utilities import assert_empty_kwargs, check_depth_peeling, try_callback, wrap
from pyvista.utilities.misc import PyVistaDeprecationWarning, uses_egl

from .._typing import BoundsLike
from .actor import Actor
from .camera import Camera
from .charts import Charts
from .colors import Color, get_cycler
from .helpers import view_vectors
from .render_passes import RenderPasses
from .tools import create_axes_marker, create_axes_orientation_box, parse_font_family

ACTOR_LOC_MAP = [
    'upper right',
    'upper left',
    'lower left',
    'lower right',
    'center left',
    'center right',
    'lower center',
    'upper center',
    'center',
]


def map_loc_to_pos(loc, size, border=0.05):
    """Map location and size to a VTK position and position2.

    Attempt to place 2d actor in a sensible position.

    """
    if not isinstance(size, Sequence) or len(size) != 2:
        raise ValueError(f'`size` must be a list of length 2. Passed value is {size}')

    if 'right' in loc:
        x = 1 - size[1] - border
    elif 'left' in loc:
        x = border
    else:
        x = 0.5 - size[1] / 2

    if 'upper' in loc:
        y = 1 - size[1] - border
    elif 'lower' in loc:
        y = border
    else:
        y = 0.5 - size[1] / 2

    return x, y, size


def make_legend_face(face):
    """Create the legend face."""
    if face is None:
        legendface = pyvista.PolyData([0.0, 0.0, 0.0])
    elif face in ["-", "line"]:
        legendface = _line_for_legend()
    elif face in ["^", "triangle"]:
        legendface = pyvista.Triangle()
    elif face in ["o", "circle"]:
        legendface = pyvista.Circle()
    elif face in ["r", "rectangle"]:
        legendface = pyvista.Rectangle()
    elif isinstance(face, pyvista.PolyData):
        legendface = face
    else:
        raise ValueError(
            f'Invalid face "{face}".  Must be one of the following:\n'
            '\t"triangle"\n'
            '\t"circle"\n'
            '\t"rectangle"\n'
            '\tNone'
            '\tpyvista.PolyData'
        )
    return legendface


def scale_point(camera, point, invert=False):
    """Scale a point using the camera's transform matrix.

    Parameters
    ----------
    camera : Camera
        The camera who's matrix to use.

    point : sequence[float]
        Scale point coordinates.

    invert : bool, default: False
        If ``True``, invert the matrix to transform the point out of
        the camera's transformed space. Default is ``False`` to
        transform a point from world coordinates to the camera's
        transformed space.

    Returns
    -------
    tuple
        Scaling of the camera in ``(x, y, z)``.

    """
    if invert:
        mtx = _vtk.vtkMatrix4x4()
        mtx.DeepCopy(camera.GetModelTransformMatrix())
        mtx.Invert()
    else:
        mtx = camera.GetModelTransformMatrix()
    scaled = mtx.MultiplyDoublePoint((point[0], point[1], point[2], 0.0))
    return (scaled[0], scaled[1], scaled[2])


class CameraPosition:
    """Container to hold camera location attributes.

    Parameters
    ----------
    position : sequence[float]
        Position of the camera.

    focal_point : sequence[float]
        The focal point of the camera.

    viewup : sequence[float]
        View up of the camera.

    """

    def __init__(self, position, focal_point, viewup):
        """Initialize a new camera position descriptor."""
        self._position = position
        self._focal_point = focal_point
        self._viewup = viewup

    def to_list(self):
        """Convert to a list of the position, focal point, and viewup.

        Returns
        -------
        list
            List of the position, focal point, and view up of the camera.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.camera_position.to_list()
        [(0.0, 0.0, 1.0), (0.0, 0.0, 0.0), (0.0, 1.0, 0.0)]

        """
        return [self._position, self._focal_point, self._viewup]

    def __repr__(self):
        """List representation method."""
        return "[{},\n {},\n {}]".format(*self.to_list())

    def __getitem__(self, index):
        """Fetch a component by index location like a list."""
        return self.to_list()[index]

    def __eq__(self, other):
        """Comparison operator to act on list version of CameraPosition object."""
        if isinstance(other, CameraPosition):
            return self.to_list() == other.to_list()
        return self.to_list() == other

    @property
    def position(self):
        """Location of the camera in world coordinates."""
        return self._position

    @position.setter
    def position(self, value):
        self._position = value

    @property
    def focal_point(self):
        """Location of the camera's focus in world coordinates."""
        return self._focal_point

    @focal_point.setter
    def focal_point(self, value):
        self._focal_point = value

    @property
    def viewup(self):
        """Viewup vector of the camera."""
        return self._viewup

    @viewup.setter
    def viewup(self, value):
        self._viewup = value


class Renderer(_vtk.vtkOpenGLRenderer):
    """Renderer class."""

    # map camera_position string to an attribute
    CAMERA_STR_ATTR_MAP = {
        'xy': 'view_xy',
        'xz': 'view_xz',
        'yz': 'view_yz',
        'yx': 'view_yx',
        'zx': 'view_zx',
        'zy': 'view_zy',
        'iso': 'view_isometric',
    }

    def __init__(self, parent, border=True, border_color='w', border_width=2.0):
        """Initialize the renderer."""
        super().__init__()
        self._actors = {}
        self.parent = parent  # weakref.proxy to the plotter from Renderers
        self._theme = parent.theme
        self.bounding_box_actor = None
        self.scale = [1.0, 1.0, 1.0]
        self.AutomaticLightCreationOff()
        self._labels = {}  # tracks labeled actors
        self._legend = None
        self._floor = None
        self._floors = []
        self._floor_kwargs = []
        # this keeps track of lights added manually to prevent garbage collection
        self._lights = []
        self._camera = Camera(self)
        self.SetActiveCamera(self._camera)
        self._empty_str = None  # used to track reference to a vtkStringArray
        self._shadow_pass = None
        self._render_passes = RenderPasses(self)
        self.cube_axes_actor = None

        # This is a private variable to keep track of how many colorbars exist
        # This allows us to keep adding colorbars without overlapping
        self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS))
        self._scalar_bar_slot_lookup = {}
        self.__charts = None

        self._border_actor = None
        if border:
            self.add_border(border_color, border_width)

        self.set_color_cycler(self._theme.color_cycler)

    @property
    def camera_set(self) -> bool:
        """Get or set whether this camera has been configured."""
        if self.camera is None:  # pragma: no cover
            return False
        return self.camera.is_set

    @camera_set.setter
    def camera_set(self, is_set: bool):
        self.camera.is_set = is_set

    def set_color_cycler(self, color_cycler):
        """Set or reset this renderer's color cycler.

        This color cycler is iterated over by each sequential :class:`add_mesh() <pyvista.Plotter.add_mesh>`
        call to set the default color of the dataset being plotted.

        When setting, the value must be either a list of color-like objects,
        or a cycler of color-like objects. If the value passed is a single
        string, it must be one of:

            * ``'default'`` - Use the default color cycler (matches matplotlib's default)
            * ``'matplotlib`` - Dynamically get matplotlib's current theme's color cycler.
            * ``'all'`` - Cycle through all of the available colors in ``pyvista.plotting.colors.hexcolors``

        Setting to ``None`` will disable the use of the color cycler on this
        renderer.

        Parameters
        ----------
        color_cycler : str | cycler.Cycler | sequence[ColorLike]
            The colors to cycle through.

        Examples
        --------
        Set the default color cycler to iterate through red, green, and blue.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> pl.renderer.set_color_cycler(['red', 'green', 'blue'])
        >>> _ = pl.add_mesh(pv.Cone(center=(0, 0, 0)))  # red
        >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))  # green
        >>> _ = pl.add_mesh(pv.Sphere(center=(1, 1, 0)))  # blue
        >>> _ = pl.add_mesh(pv.Cylinder(center=(0, 1, 0)))  # red again
        >>> pl.show()

        """
        cycler = get_cycler(color_cycler)
        if cycler is not None:
            # Color cycler - call object to generate `cycle` instance
            self._color_cycle = cycler()
        else:
            self._color_cycle = None

    @property
    def next_color(self):
        """Return next color from this renderer's color cycler."""
        if self._color_cycle is None:
            return self._theme.color
        return next(self._color_cycle)['color']

    @property
    def _charts(self):
        """Return the charts collection."""
        # lazy instantiation here to avoid creating the charts object unless needed.
        if self.__charts is None:
            self.__charts = Charts(self)
            self.AddObserver("StartEvent", partial(try_callback, self._before_render_event))
        return self.__charts

    @property
    def camera_position(self):
        """Return camera position of active render window.

        Returns
        -------
        pyvista.CameraPosition
            Camera position.

        """
        return CameraPosition(
            scale_point(self.camera, self.camera.position, invert=True),
            scale_point(self.camera, self.camera.focal_point, invert=True),
            self.camera.up,
        )

    @camera_position.setter
    def camera_position(self, camera_location):
        """Set camera position of all active render windows."""
        if camera_location is None:
            return
        elif isinstance(camera_location, str):
            camera_location = camera_location.lower()
            if camera_location not in self.CAMERA_STR_ATTR_MAP:
                err = pyvista.core.errors.InvalidCameraError
                raise err(
                    'Invalid view direction.  '
                    'Use one of the following:\n   '
                    f'{", ".join(self.CAMERA_STR_ATTR_MAP)}'
                )

            getattr(self, self.CAMERA_STR_ATTR_MAP[camera_location])()

        elif isinstance(camera_location[0], (int, float)):
            if len(camera_location) != 3:
                raise pyvista.core.errors.InvalidCameraError
            self.view_vector(camera_location)
        else:
            # check if a valid camera position
            if not isinstance(camera_location, CameraPosition):
                if not len(camera_location) == 3:
                    raise pyvista.core.errors.InvalidCameraError
                elif any([len(item) != 3 for item in camera_location]):
                    raise pyvista.core.errors.InvalidCameraError

            # everything is set explicitly
            self.camera.position = scale_point(self.camera, camera_location[0], invert=False)
            self.camera.focal_point = scale_point(self.camera, camera_location[1], invert=False)
            self.camera.up = camera_location[2]

        # reset clipping range
        self.reset_camera_clipping_range()
        self.camera_set = True
        self.Modified()

    def reset_camera_clipping_range(self):
        """Reset the camera clipping range based on the bounds of the visible actors.

        This ensures that no props are cut off
        """
        self.ResetCameraClippingRange()

    @property
    def camera(self):
        """Return the active camera for the rendering scene."""
        return self._camera

    @camera.setter
    def camera(self, source):
        """Set the active camera for the rendering scene."""
        self._camera = source
        self.SetActiveCamera(self._camera)
        self.camera_position = CameraPosition(
            scale_point(source, source.position, invert=True),
            scale_point(source, source.focal_point, invert=True),
            source.up,
        )
        self.Modified()
        self.camera_set = True

    @property
    def bounds(self) -> BoundsLike:
        """Return the bounds of all actors present in the rendering window."""
        the_bounds = np.array([np.inf, -np.inf, np.inf, -np.inf, np.inf, -np.inf])

        def _update_bounds(bounds):
            def update_axis(ax):
                if bounds[ax * 2] < the_bounds[ax * 2]:
                    the_bounds[ax * 2] = bounds[ax * 2]
                if bounds[ax * 2 + 1] > the_bounds[ax * 2 + 1]:
                    the_bounds[ax * 2 + 1] = bounds[ax * 2 + 1]

            for ax in range(3):
                update_axis(ax)
            return

        for actor in self._actors.values():
            if isinstance(actor, (_vtk.vtkCubeAxesActor, _vtk.vtkLightActor)):
                continue
            if (
                hasattr(actor, 'GetBounds')
                and actor.GetBounds() is not None
                and id(actor) != id(self.bounding_box_actor)
            ):
                _update_bounds(actor.GetBounds())

        if np.any(np.abs(the_bounds)):
            the_bounds[the_bounds == np.inf] = -1.0
            the_bounds[the_bounds == -np.inf] = 1.0

        return cast(BoundsLike, tuple(the_bounds))

    @property
    def length(self):
        """Return the length of the diagonal of the bounding box of the scene.

        Returns
        -------
        float
            Length of the diagional of the bounding box.
        """
        return pyvista.Box(self.bounds).length

    @property
    def center(self):
        """Return the center of the bounding box around all data present in the scene.

        Returns
        -------
        list
            Cartesian coordinates of the center.

        """
        bounds = self.bounds
        x = (bounds[1] + bounds[0]) / 2
        y = (bounds[3] + bounds[2]) / 2
        z = (bounds[5] + bounds[4]) / 2
        return [x, y, z]

    @property
    def background_color(self):
        """Return the background color of this renderer."""
        return Color(self.GetBackground())

    @background_color.setter
    def background_color(self, color):
        """Set the background color of this renderer."""
        self.set_background(color)
        self.Modified()

    def _before_render_event(self, *args, **kwargs):
        """Notify all charts about render event."""
        for chart in self._charts:
            chart._render_event(*args, **kwargs)

    def enable_depth_peeling(self, number_of_peels=None, occlusion_ratio=None):
        """Enable depth peeling to improve rendering of translucent geometry.

        Parameters
        ----------
        number_of_peels : int, optional
            The maximum number of peeling layers. Initial value is 4
            and is set in the ``pyvista.global_theme``. A special value of
            0 means no maximum limit.  It has to be a positive value.

        occlusion_ratio : float, optional
            The threshold under which the depth peeling algorithm
            stops to iterate over peel layers. This is the ratio of
            the number of pixels that have been touched by the last
            layer over the total number of pixels of the viewport
            area. Initial value is 0.0, meaning rendering has to be
            exact. Greater values may speed up the rendering with
            small impact on the quality.

        Returns
        -------
        bool
            If depth peeling is supported.

        """
        if number_of_peels is None:
            number_of_peels = self._theme.depth_peeling.number_of_peels
        if occlusion_ratio is None:
            occlusion_ratio = self._theme.depth_peeling.occlusion_ratio
        depth_peeling_supported = check_depth_peeling(number_of_peels, occlusion_ratio)
        if depth_peeling_supported:
            self.SetUseDepthPeeling(True)
            self.SetMaximumNumberOfPeels(number_of_peels)
            self.SetOcclusionRatio(occlusion_ratio)
        self.Modified()
        return depth_peeling_supported

    def disable_depth_peeling(self):
        """Disable depth peeling."""
        self.SetUseDepthPeeling(False)
        self.Modified()

    def enable_anti_aliasing(self, aa_type='fxaa'):
        """Enable anti-aliasing.

        Parameters
        ----------
        aa_type : str, default: 'fxaa'
            Anti-aliasing type. Either ``"fxaa"`` or ``"ssaa"``.

        """
        if not isinstance(aa_type, str):
            raise TypeError(f'`aa_type` must be a string, not {type(aa_type)}')
        aa_type = aa_type.lower()

        if aa_type == 'fxaa':
            if uses_egl():  # pragma: no cover
                # only display the warning when not building documentation
                if not pyvista.BUILDING_GALLERY:
                    warnings.warn(
                        "VTK compiled with OSMesa does not properly support "
                        "FXAA anti-aliasing and SSAA will be used instead."
                    )
                self._render_passes.enable_ssaa_pass()
                return
            self._enable_fxaa()

        elif aa_type == 'ssaa':
            self._render_passes.enable_ssaa_pass()

        else:
            raise ValueError(f'Invalid `aa_type` "{aa_type}". Should be either "fxaa" or "ssaa"')

    def disable_anti_aliasing(self):
        """Disable all anti-aliasing."""
        self._render_passes.disable_ssaa_pass()
        self.SetUseFXAA(False)
        self.Modified()

    def _enable_fxaa(self):
        """Enable FXAA anti-aliasing."""
        self.SetUseFXAA(True)
        self.Modified()

    def _disable_fxaa(self):
        """Disable FXAA anti-aliasing."""
        self.SetUseFXAA(False)
        self.Modified()

    def add_border(self, color='white', width=2.0):
        """Add borders around the frame.

        Parameters
        ----------
        color : ColorLike, default: "white"
            Color of the border.

        width : float, default: 2.0
            Width of the border.

        Returns
        -------
        vtk.vtkActor2D
            Border actor.

        """
        points = np.array([[1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0]])

        lines = np.array([[2, 0, 1], [2, 1, 2], [2, 2, 3], [2, 3, 0]]).ravel()

        poly = pyvista.PolyData()
        poly.points = points
        poly.lines = lines

        coordinate = _vtk.vtkCoordinate()
        coordinate.SetCoordinateSystemToNormalizedViewport()

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

        actor = _vtk.vtkActor2D()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(Color(color).float_rgb)
        actor.GetProperty().SetLineWidth(width)

        self.AddViewProp(actor)
        self.Modified()

        self._border_actor = actor
        return actor

    @property
    def has_border(self):
        """Return if the renderer has a border."""
        return self._border_actor is not None

    @property
    def border_width(self):
        """Return the border width."""
        if self.has_border:
            return self._border_actor.GetProperty().GetLineWidth()
        return 0

    @property
    def border_color(self):
        """Return the border color."""
        if self.has_border:
            return Color(self._border_actor.GetProperty().GetColor())
        return None

    def add_chart(self, chart, *charts):
        """Add a chart to this renderer.

        Parameters
        ----------
        chart : Chart
            Chart to add to renderer.

        *charts : Chart
            Charts to add to renderer.

        Examples
        --------
        >>> import pyvista
        >>> chart = pyvista.Chart2D()
        >>> _ = chart.plot(range(10), range(10))
        >>> pl = pyvista.Plotter()
        >>> pl.add_chart(chart)
        >>> pl.show()

        """
        if not _vtk._has_vtkRenderingContextOpenGL2:  # pragma: no cover
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError(
                "VTK is missing vtkRenderingContextOpenGL2. Try installing VTK v9.1.0 or newer."
            )
        self._charts.add_chart(chart, *charts)

    @property
    def has_charts(self):
        """Return whether this renderer has charts."""
        return self.__charts is not None

    @wraps(Charts.set_interaction)
    def set_chart_interaction(self, interactive, toggle=False):
        """Wrap ``Charts.set_interaction``."""
        # Make sure we don't create the __charts object if this renderer has no charts yet.
        return self._charts.set_interaction(interactive, toggle) if self.has_charts else []

    @wraps(Charts.get_charts_by_pos)
    def _get_charts_by_pos(self, pos):
        """Wrap ``Charts.get_charts_by_pos``."""
        # Make sure we don't create the __charts object if this renderer has no charts yet.
        return self._charts.get_charts_by_pos(pos) if self.has_charts else []

    def remove_chart(self, chart_or_index):
        """Remove a chart from this renderer.

        Parameters
        ----------
        chart_or_index : Chart or int
            Either the chart to remove from this renderer or its index in the collection of charts.

        Examples
        --------
        First define a function to add two charts to a renderer.

        >>> import pyvista
        >>> def plotter_with_charts():
        ...     pl = pyvista.Plotter()
        ...     pl.background_color = 'w'
        ...     chart_left = pyvista.Chart2D(size=(0.5, 1))
        ...     _ = chart_left.line([0, 1, 2], [2, 1, 3])
        ...     pl.add_chart(chart_left)
        ...     chart_right = pyvista.Chart2D(size=(0.5, 1), loc=(0.5, 0))
        ...     _ = chart_right.line([0, 1, 2], [3, 1, 2])
        ...     pl.add_chart(chart_right)
        ...     return pl, chart_left, chart_right
        ...
        >>> pl, *_ = plotter_with_charts()
        >>> pl.show()

        Now reconstruct the same plotter but remove the right chart by index.

        >>> pl, *_ = plotter_with_charts()
        >>> pl.remove_chart(1)
        >>> pl.show()

        Finally, remove the left chart by reference.

        >>> pl, chart_left, chart_right = plotter_with_charts()
        >>> pl.remove_chart(chart_left)
        >>> pl.show()

        """
        # Make sure we don't create the __charts object if this renderer has no charts yet.
        if self.has_charts:
            self._charts.remove_chart(chart_or_index)

    @property
    def actors(self):
        """Return a dictionary of actors assigned to this renderer."""
        return self._actors

    def add_actor(
        self,
        actor,
        reset_camera=False,
        name=None,
        culling=False,
        pickable=True,
        render=True,
        remove_existing_actor=True,
    ):
        """Add an actor to render window.

        Creates an actor if input is a mapper.

        Parameters
        ----------
        actor : vtk.vtkActor | vtk.vtkMapper | pyvista.Actor
            The actor to be added. Can be either ``vtkActor`` or ``vtkMapper``.

        reset_camera : bool, default: False
            Resets the camera when ``True``.

        name : str, optional
            Name to assign to the actor.  Defaults to the memory address.

        culling : str, default: False
            Does not render faces that are culled. Options are
            ``'front'`` or ``'back'``. This can be helpful for dense
            surface meshes, especially when edges are visible, but can
            cause flat meshes to be partially displayed.

        pickable : bool, default: True
            Whether to allow this actor to be pickable within the
            render window.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after adding the actor.

        remove_existing_actor : bool, default: True
            Removes any existing actor if the named actor ``name`` is already
            present.

        Returns
        -------
        actor : vtk.vtkActor or pyvista.Actor
            The actor.

        actor_properties : vtk.Properties
            Actor properties.
        """
        # Remove actor by that name if present
        rv = None
        if name and remove_existing_actor:
            rv = self.remove_actor(name, reset_camera=False, render=False)

        if isinstance(actor, _vtk.vtkMapper):
            actor = Actor(mapper=actor, name=name)

        if isinstance(actor, Actor) and name:
            # WARNING: this will override the name if already set on Actor
            actor.name = name

        if name is None:
            if isinstance(actor, Actor):
                name = actor.name
            else:
                # Fallback for non-wrapped actors
                # e.g., vtkScalarBarActor
                name = actor.GetAddressAsString("")

        actor.SetPickable(pickable)
        # Apply this renderer's scale to the actor (which can be further scaled)
        if hasattr(actor, 'SetScale'):
            actor.SetScale(np.array(actor.GetScale()) * np.array(self.scale))
        self.AddActor(actor)  # must add actor before resetting camera
        self._actors[name] = actor

        if reset_camera:
            self.reset_camera(render)
        elif not self.camera_set and reset_camera is None and not rv:
            self.reset_camera(render)
        elif render:
            self.parent.render()

        self.update_bounds_axes()

        if isinstance(culling, str):
            culling = culling.lower()

        if culling:
            if culling in [True, 'back', 'backface', 'b']:
                try:
                    actor.GetProperty().BackfaceCullingOn()
                except AttributeError:  # pragma: no cover
                    pass
            elif culling in ['front', 'frontface', 'f']:
                try:
                    actor.GetProperty().FrontfaceCullingOn()
                except AttributeError:  # pragma: no cover
                    pass
            else:
                raise ValueError(f'Culling option ({culling}) not understood.')

        self.Modified()

        prop = None
        if hasattr(actor, 'GetProperty'):
            prop = actor.GetProperty()

        return actor, prop

    def add_axes_at_origin(
        self,
        x_color=None,
        y_color=None,
        z_color=None,
        xlabel='X',
        ylabel='Y',
        zlabel='Z',
        line_width=2,
        labels_off=False,
    ):
        """Add axes actor at origin.

        Parameters
        ----------
        x_color : ColorLike, optional
            The color of the x axes arrow.

        y_color : ColorLike, optional
            The color of the y axes arrow.

        z_color : ColorLike, optional
            The color of the z axes arrow.

        xlabel : str, default: "X"
            The label of the x axes arrow.

        ylabel : str, default: "Y"
            The label of the y axes arrow.

        zlabel : str, default: "Z"
            The label of the z axes arrow.

        line_width : int, default: 2
            Width of the arrows.

        labels_off : bool, default: False
            Disables the label text when ``True``.

        Returns
        -------
        vtk.vtkAxesActor
            Actor of the axes.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(pyvista.Sphere(center=(2, 0, 0)), color='r')
        >>> _ = pl.add_mesh(pyvista.Sphere(center=(0, 2, 0)), color='g')
        >>> _ = pl.add_mesh(pyvista.Sphere(center=(0, 0, 2)), color='b')
        >>> _ = pl.add_axes_at_origin()
        >>> pl.show()

        """
        self._marker_actor = create_axes_marker(
            line_width=line_width,
            x_color=x_color,
            y_color=y_color,
            z_color=z_color,
            xlabel=xlabel,
            ylabel=ylabel,
            zlabel=zlabel,
            labels_off=labels_off,
        )
        self.AddActor(self._marker_actor)
        memory_address = self._marker_actor.GetAddressAsString("")
        self._actors[memory_address] = self._marker_actor
        self.Modified()
        return self._marker_actor

    def add_orientation_widget(
        self, actor, interactive=None, color=None, opacity=1.0, viewport=None
    ):
        """Use the given actor in an orientation marker widget.

        Color and opacity are only valid arguments if a mesh is passed.

        Parameters
        ----------
        actor : vtk.vtkActor | pyvista.DataSet
            The mesh or actor to use as the marker.

        interactive : bool, optional
            Control if the orientation widget is interactive.  By
            default uses the value from
            :attr:`pyvista.global_theme.interactive
            <pyvista.themes.DefaultTheme.interactive>`.

        color : ColorLike, optional
            The color of the actor.  This only applies if ``actor`` is
            a :class:`pyvista.DataSet`.

        opacity : int | float, default: 1.0
            Opacity of the marker.

        viewport : sequence[float], optional
            Viewport ``(xstart, ystart, xend, yend)`` of the widget.

        Returns
        -------
        vtk.vtkOrientationMarkerWidget
            Orientation marker widget.

        Examples
        --------
        Use an Arrow as the orientation widget.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Cube(), show_edges=True)
        >>> actor = pl.add_orientation_widget(pyvista.Arrow(), color='r')
        >>> pl.show()

        """
        if isinstance(actor, pyvista.DataSet):
            mapper = _vtk.vtkDataSetMapper()
            mesh = actor.copy()
            mesh.clear_data()
            mapper.SetInputData(mesh)
            actor = pyvista.Actor(mapper=mapper)
            if color is not None:
                actor.prop.color = color
            actor.prop.opacity = opacity
        if hasattr(self, 'axes_widget'):
            # Delete the old one
            self.axes_widget.EnabledOff()
            self.Modified()
            del self.axes_widget
        if interactive is None:
            interactive = self._theme.interactive
        self.axes_widget = _vtk.vtkOrientationMarkerWidget()
        self.axes_widget.SetOrientationMarker(actor)
        if hasattr(self.parent, 'iren'):
            self.axes_widget.SetInteractor(self.parent.iren.interactor)
            self.axes_widget.SetEnabled(1)
            self.axes_widget.SetInteractive(interactive)
        self.axes_widget.SetCurrentRenderer(self)
        if viewport is not None:
            self.axes_widget.SetViewport(viewport)
        self.Modified()
        return self.axes_widget

    def add_axes(
        self,
        interactive=None,
        line_width=2,
        color=None,
        x_color=None,
        y_color=None,
        z_color=None,
        xlabel='X',
        ylabel='Y',
        zlabel='Z',
        labels_off=False,
        box=None,
        box_args=None,
        viewport=(0, 0, 0.2, 0.2),
        marker_args=None,
        **kwargs,
    ):
        """Add an interactive axes widget in the bottom left corner.

        Parameters
        ----------
        interactive : bool, optional
            Enable this orientation widget to be moved by the user.

        line_width : int, default: 2
            The width of the marker lines.

        color : ColorLike, optional
            Color of the labels.

        x_color : ColorLike, optional
            Color used for the x axis arrow.  Defaults to theme axes parameters.

        y_color : ColorLike, optional
            Color used for the y axis arrow.  Defaults to theme axes parameters.

        z_color : ColorLike, optional
            Color used for the z axis arrow.  Defaults to theme axes parameters.

        xlabel : str, default: "X"
            Text used for the x axis.

        ylabel : str, default: "Y"
            Text used for the y axis.

        zlabel : str, default: "Z"
            Text used for the z axis.

        labels_off : bool, default: false
            Enable or disable the text labels for the axes.

        box : bool, optional
            Show a box orientation marker. Use ``box_args`` to adjust.
            See :func:`pyvista.create_axes_orientation_box` for details.

        box_args : dict, optional
            Parameters for the orientation box widget when
            ``box=True``. See the parameters of
            :func:`pyvista.create_axes_orientation_box`.

        viewport : sequence[float], default: (0, 0, 0.2, 0.2)
            Viewport ``(xstart, ystart, xend, yend)`` of the widget.

        marker_args : dict, optional
            Marker arguments.

            .. deprecated:: 0.37.0
               Use ``**kwargs`` for passing parameters for the orientation
               marker widget. See the parameters of
               :func:`pyvista.create_axes_marker`.

        **kwargs : dict, optional
            Used for passing parameters for the orientation marker
            widget. See the parameters of :func:`pyvista.create_axes_marker`.

        Returns
        -------
        vtk.vtkAxesActor
            Axes actor.

        Examples
        --------
        Show axes without labels and with thick lines.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Box(), show_edges=True)
        >>> _ = pl.add_axes(line_width=5, labels_off=True)
        >>> pl.show()

        Use the axes orientation widget instead of the default arrows.

        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Sphere())
        >>> _ = pl.add_axes(box=True)
        >>> pl.show()

        Specify more parameters for the axes marker.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Box(), show_edges=True)
        >>> _ = pl.add_axes(
        ...     line_width=5,
        ...     cone_radius=0.6,
        ...     shaft_length=0.7,
        ...     tip_length=0.3,
        ...     ambient=0.5,
        ...     label_size=(0.4, 0.16),
        ... )
        >>> pl.show()

        """
        # Deprecated on v0.37.0, estimated removal on v0.40.0
        if marker_args is not None:  # pragma: no cover
            warnings.warn(
                "Use of `marker_args` is deprecated. Use `**kwargs` instead.",
                PyVistaDeprecationWarning,
            )
            kwargs.update(marker_args)

        if interactive is None:
            interactive = self._theme.interactive
        if hasattr(self, 'axes_widget'):
            self.axes_widget.EnabledOff()
            self.Modified()
            del self.axes_widget
        if box is None:
            box = self._theme.axes.box
        if box:
            if box_args is None:
                box_args = {}
            self.axes_actor = create_axes_orientation_box(
                label_color=color,
                line_width=line_width,
                x_color=x_color,
                y_color=y_color,
                z_color=z_color,
                xlabel=xlabel,
                ylabel=ylabel,
                zlabel=zlabel,
                labels_off=labels_off,
                **box_args,
            )
        else:
            self.axes_actor = create_axes_marker(
                label_color=color,
                line_width=line_width,
                x_color=x_color,
                y_color=y_color,
                z_color=z_color,
                xlabel=xlabel,
                ylabel=ylabel,
                zlabel=zlabel,
                labels_off=labels_off,
                **kwargs,
            )
        axes_widget = self.add_orientation_widget(
            self.axes_actor, interactive=interactive, color=None
        )
        axes_widget.SetViewport(viewport)
        return self.axes_actor

    def hide_axes(self):
        """Hide the axes orientation widget.

        Examples
        --------
        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> pl.hide_axes()

        """
        if hasattr(self, 'axes_widget') and self.axes_widget.GetEnabled():
            self.axes_widget.EnabledOff()
            self.Modified()

    def show_axes(self):
        """Show the axes orientation widget.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.show_axes()

        """
        if hasattr(self, 'axes_widget'):
            self.axes_widget.EnabledOn()
            self.axes_widget.SetCurrentRenderer(self)
        else:
            self.add_axes()
        self.Modified()

    @property
    def axes_enabled(self):
        """Return ``True`` when axes are enabled.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.hide_axes()
        >>> pl.renderer.axes_enabled
        False

        """
        if hasattr(self, 'axes_widget'):
            return bool(self.axes_widget.GetEnabled())
        return False

    def show_bounds(
        self,
        mesh=None,
        bounds=None,
        axes_ranges=None,
        show_xaxis=True,
        show_yaxis=True,
        show_zaxis=True,
        show_xlabels=True,
        show_ylabels=True,
        show_zlabels=True,
        bold=True,
        font_size=None,
        font_family=None,
        color=None,
        xtitle='X Axis',
        ytitle='Y Axis',
        ztitle='Z Axis',
        n_xlabels=5,
        n_ylabels=5,
        n_zlabels=5,
        use_2d=False,
        grid=None,
        location='closest',
        ticks=None,
        all_edges=False,
        corner_factor=0.5,
        fmt=None,
        minor_ticks=False,
        padding=0.0,
        use_3d_text=True,
        render=None,
        **kwargs,
    ):
        """Add bounds axes.

        Shows the bounds of the most recent input mesh unless mesh is
        specified.

        Parameters
        ----------
        mesh : pyvista.DataSet | pyvista.MultiBlock, optional
            Input mesh to draw bounds axes around.

        bounds : sequence[float], optional
            Bounds to override mesh bounds in the form ``[xmin, xmax,
            ymin, ymax, zmin, zmax]``.

        axes_ranges : sequence[float], optional
            When set, these values override the values that are shown on the
            axes. This can be useful when plotting scaled datasets or if you wish
            to manually display different values. These values must be in the
            form:

            ``[xmin, xmax, ymin, ymax, zmin, zmax]``.

        show_xaxis : bool, default: True
            Makes X axis visible.

        show_yaxis : bool, default: True
            Makes Y axis visible.

        show_zaxis : bool, default: True
            Makes Z axis visible.

        show_xlabels : bool, default: True
            Shows X labels.

        show_ylabels : bool, default: True
            Shows Y labels.

        show_zlabels : bool, default: True
            Shows Z labels.

        bold : bool, default: True
            Bolds axis labels and numbers.

        font_size : float, optional
            Sets the size of the label font. Defaults to
            :attr:`pyvista.global_theme.font.size
            <pyvista.themes._Font.size>`.

        font_family : str, optional
            Font family.  Must be either ``'courier'``, ``'times'``,
            or ``'arial'``. Defaults to :attr:`pyvista.global_theme.font.family
            <pyvista.themes._Font.family>`.

        color : ColorLike, optional
            Color of all labels and axis titles.  Defaults to
            :attr:`pyvista.global_theme.font.color
            <pyvista.themes._Font.color>`.

            Either a string, RGB list, or hex color string.  For
            example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        xtitle : str, default: "X Axis"
            Title of the X axis.  Default ``"X Axis"``.

        ytitle : str, default: "Y Axis"
            Title of the Y axis.  Default ``"Y Axis"``.

        ztitle : str, default: "Z Axis"
            Title of the Z axis.  Default ``"Z Axis"``.

        n_xlabels : int, default: 5
            Number of labels for the X axis.

        n_ylabels : int, default: 5
            Number of labels for the Y axis.

        n_zlabels : int, default: 5
            Number of labels for the Z axis.

        use_2d : bool, default: False
            This can be enabled for smoother plotting.

        grid : bool or str, optional
            Add grid lines to the backface (``True``, ``'back'``, or
            ``'backface'``) or to the frontface (``'front'``,
            ``'frontface'``) of the axes actor.

        location : str, default: "closest"
            Set how the axes are drawn: either static (``'all'``), closest
            triad (``'front'``, ``'closest'``, ``'default'``), furthest triad
            (``'back'``, ``'furthest'``), static closest to the origin
            (``'origin'``), or outer edges (``'outer'``) in relation to the
            camera position.

        ticks : str, optional
            Set how the ticks are drawn on the axes grid. Options include:
            ``'inside', 'outside', 'both'``.

        all_edges : bool, default: False
            Adds an unlabeled and unticked box at the boundaries of
            plot. Useful for when wanting to plot outer grids while
            still retaining all edges of the boundary.

        corner_factor : float, default: 0.5
            If ``all_edges``, this is the factor along each axis to
            draw the default box. Default shows the full box.

        fmt : str, optional
            A format string defining how tick labels are generated from
            tick positions. A default is looked up on the active theme.

        minor_ticks : bool, default: False
            If ``True``, also plot minor ticks on all axes.

        padding : float, default: 0.0
            An optional percent padding along each axial direction to
            cushion the datasets in the scene from the axes
            annotations. Defaults no padding.

        use_3d_text : bool, default: True
            Use ``vtkTextActor3D`` for titles and labels.

        render : bool, optional
            If the render window is being shown, trigger a render
            after showing bounds.

        **kwargs : dict, optional
            Deprecated keyword arguments.

        Returns
        -------
        vtk.vtkCubeAxesActor
            Bounds actor.

        Examples
        --------
        >>> import pyvista as pv
        >>> from pyvista import examples

        >>> mesh = pv.Sphere()
        >>> plotter = pv.Plotter()
        >>> actor = plotter.add_mesh(mesh)
        >>> actor = plotter.show_bounds(
        ...     grid='front',
        ...     location='outer',
        ...     all_edges=True,
        ... )
        >>> plotter.show()

        Control how many labels are displayed.

        >>> mesh = examples.load_random_hills()

        >>> plotter = pv.Plotter()
        >>> actor = plotter.add_mesh(
        ...     mesh, cmap='terrain', show_scalar_bar=False
        ... )
        >>> actor = plotter.show_bounds(
        ...     grid='back',
        ...     location='outer',
        ...     ticks='both',
        ...     n_xlabels=2,
        ...     n_ylabels=2,
        ...     n_zlabels=2,
        ...     xtitle='Easting',
        ...     ytitle='Northing',
        ...     ztitle='Elevation',
        ... )
        >>> plotter.show()

        Hide labels, but still show axis titles.

        >>> plotter = pv.Plotter()
        >>> actor = plotter.add_mesh(
        ...     mesh, cmap='terrain', show_scalar_bar=False
        ... )
        >>> actor = plotter.show_bounds(
        ...     grid='back',
        ...     location='outer',
        ...     ticks='both',
        ...     show_xlabels=False,
        ...     show_ylabels=False,
        ...     show_zlabels=False,
        ...     xtitle='Easting',
        ...     ytitle='Northing',
        ...     ztitle='Elevation',
        ... )
        >>> plotter.show()

        """
        self.remove_bounds_axes()

        if font_family is None:
            font_family = self._theme.font.family
        if font_size is None:
            font_size = self._theme.font.size
        if fmt is None:
            fmt = self._theme.font.fmt
        if fmt is None:
            fmt = '%.1f'  # fallback

        if 'xlabel' in kwargs:  # pragma: no cover
            xtitle = kwargs.pop('xlabel')
            warnings.warn(
                "`xlabel` is deprecated. Use `xtitle` instead.",
                PyVistaDeprecationWarning,
            )
        if 'ylabel' in kwargs:  # pragma: no cover
            ytitle = kwargs.pop('ylabel')
            warnings.warn(
                "`ylabel` is deprecated. Use `ytitle` instead.",
                PyVistaDeprecationWarning,
            )
        if 'zlabel' in kwargs:  # pragma: no cover
            ztitle = kwargs.pop('zlabel')
            warnings.warn(
                "`zlabel` is deprecated. Use `ztitle` instead.",
                PyVistaDeprecationWarning,
            )
        assert_empty_kwargs(**kwargs)

        color = Color(color, default_color=self._theme.font.color)

        if mesh is None and bounds is None:
            # Use the bounds of all data in the rendering window
            bounds = np.array(self.bounds)
        elif bounds is None:
            # otherwise, use the bounds of the mesh (if available)
            bounds = np.array(mesh.bounds)
        else:
            bounds = np.asanyarray(bounds, dtype=float)

        # create actor
        cube_axes_actor = pyvista.CubeAxesActor(
            self.camera,
            minor_ticks=minor_ticks,
            tick_location=ticks,
            x_title=xtitle,
            y_title=ytitle,
            z_title=ztitle,
            x_axis_visibility=show_xaxis,
            y_axis_visibility=show_yaxis,
            z_axis_visibility=show_zaxis,
            x_label_format=fmt,
            y_label_format=fmt,
            z_label_format=fmt,
            x_label_visibility=show_xlabels,
            y_label_visibility=show_ylabels,
            z_label_visibility=show_zlabels,
            n_xlabels=n_xlabels,
            n_ylabels=n_ylabels,
            n_zlabels=n_zlabels,
        )

        cube_axes_actor.use_2d_mode = use_2d or not np.allclose(self.scale, [1.0, 1.0, 1.0])

        if grid:
            grid = 'back' if grid is True else grid
            if not isinstance(grid, str):
                raise TypeError(f'`grid` must be a str, not {type(grid)}')
            grid = grid.lower()
            if grid in ('front', 'frontface'):
                cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_CLOSEST)
            elif grid in ('both', 'all'):
                cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_ALL)
            elif grid in ('back', True):
                cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_FURTHEST)
            else:
                raise ValueError(f'`grid` must be either "front", "back, or, "all", not {grid}')
            # Only show user desired grid lines
            cube_axes_actor.SetDrawXGridlines(show_xaxis)
            cube_axes_actor.SetDrawYGridlines(show_yaxis)
            cube_axes_actor.SetDrawZGridlines(show_zaxis)
            # Set the colors
            cube_axes_actor.GetXAxesGridlinesProperty().SetColor(color.float_rgb)
            cube_axes_actor.GetYAxesGridlinesProperty().SetColor(color.float_rgb)
            cube_axes_actor.GetZAxesGridlinesProperty().SetColor(color.float_rgb)

        if isinstance(location, str):
            location = location.lower()
            if location in ('all'):
                cube_axes_actor.SetFlyModeToStaticEdges()
            elif location in ('origin'):
                cube_axes_actor.SetFlyModeToStaticTriad()
            elif location in ('outer'):
                cube_axes_actor.SetFlyModeToOuterEdges()
            elif location in ('default', 'closest', 'front'):
                cube_axes_actor.SetFlyModeToClosestTriad()
            elif location in ('furthest', 'back'):
                cube_axes_actor.SetFlyModeToFurthestTriad()
            else:
                raise ValueError(
                    f'Value of location ("{location}") should be either "all", "origin",'
                    ' "outer", "default", "closest", "front", "furthest", or "back".'
                )
        elif location is not None:
            raise TypeError('location must be a string')

        if isinstance(padding, (int, float)) and 0.0 <= padding < 1.0:
            if not np.any(np.abs(bounds) == np.inf):
                cushion = (
                    np.array(
                        [
                            np.abs(bounds[1] - bounds[0]),
                            np.abs(bounds[3] - bounds[2]),
                            np.abs(bounds[5] - bounds[4]),
                        ]
                    )
                    * padding
                )
                bounds[::2] -= cushion
                bounds[1::2] += cushion
        else:
            raise ValueError(f'padding ({padding}) not understood. Must be float between 0 and 1')
        cube_axes_actor.bounds = bounds

        # set axes ranges if input
        if axes_ranges is not None:
            if isinstance(axes_ranges, (collections.abc.Sequence, np.ndarray)):
                axes_ranges = np.asanyarray(axes_ranges)
            else:
                raise TypeError('Input axes_ranges must be a numeric sequence.')

            if not np.issubdtype(axes_ranges.dtype, np.number):
                raise TypeError('All of the elements of axes_ranges must be numbers.')

            # set the axes ranges
            if axes_ranges.shape != (6,):
                raise ValueError(
                    '`axes_ranges` must be passed as a [xmin, xmax, ymin, ymax, zmin, zmax] sequence.'
                )

            cube_axes_actor.x_axis_range = axes_ranges[0], axes_ranges[1]
            cube_axes_actor.y_axis_range = axes_ranges[2], axes_ranges[3]
            cube_axes_actor.z_axis_range = axes_ranges[4], axes_ranges[5]

        # set color
        cube_axes_actor.GetXAxesLinesProperty().SetColor(color.float_rgb)
        cube_axes_actor.GetYAxesLinesProperty().SetColor(color.float_rgb)
        cube_axes_actor.GetZAxesLinesProperty().SetColor(color.float_rgb)

        # set font
        font_family = parse_font_family(font_family)

        if not use_3d_text or not np.allclose(self.scale, [1.0, 1.0, 1.0]):
            use_3d_text = False
            cube_axes_actor.SetUseTextActor3D(False)
        else:
            cube_axes_actor.SetUseTextActor3D(True)

        props = [
            cube_axes_actor.GetTitleTextProperty(0),
            cube_axes_actor.GetTitleTextProperty(1),
            cube_axes_actor.GetTitleTextProperty(2),
            cube_axes_actor.GetLabelTextProperty(0),
            cube_axes_actor.GetLabelTextProperty(1),
            cube_axes_actor.GetLabelTextProperty(2),
        ]

        for prop in props:
            prop.SetColor(color.float_rgb)
            prop.SetFontFamily(font_family)
            prop.SetBold(bold)

            # this merely makes the font sharper
            if use_3d_text:
                prop.SetFontSize(50)

        # Note: font_size does nothing as a property, use SetScreenSize instead
        # Here, we normalize relative to 12 to give the user an illusion of
        # just changing the font size relative to a font size of 12. 10 is used
        # here since it's the default "screen size".
        cube_axes_actor.SetScreenSize(font_size / 12 * 10.0)

        self.add_actor(cube_axes_actor, reset_camera=False, pickable=False, render=render)
        self.cube_axes_actor = cube_axes_actor

        if all_edges:
            self.add_bounding_box(color=color, corner_factor=corner_factor)

        self.Modified()
        return cube_axes_actor

    def show_grid(self, **kwargs):
        """Show grid lines and bounds axes labels.

        A wrapped implementation of :func:`show_bounds()
        <pyvista.Renderer.show_bounds>` to change default behavior to use
        grid lines and showing the axes labels on the outer edges.

        This is intended to be similar to :func:`matplotlib.pyplot.grid`.

        Parameters
        ----------
        **kwargs : dict, optional
            See :func:`Renderer.show_bounds` for additional keyword
            arguments.

        Returns
        -------
        vtk.vtkAxesActor
            Bounds actor.

        Examples
        --------
        >>> import pyvista as pv
        >>> mesh = pv.Cone()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh)
        >>> _ = pl.show_grid()
        >>> pl.show()

        """
        kwargs.setdefault('grid', 'back')
        kwargs.setdefault('location', 'outer')
        kwargs.setdefault('ticks', 'both')
        return self.show_bounds(**kwargs)

    def remove_bounding_box(self, render=True):
        """Remove bounding box.

        Parameters
        ----------
        render : bool, default: True
            Trigger a render once the bounding box is removed.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_bounding_box()
        >>> pl.remove_bounding_box()

        """
        if hasattr(self, '_box_object'):
            actor = self.bounding_box_actor
            self.bounding_box_actor = None
            del self._box_object
            self.remove_actor(actor, reset_camera=False, render=render)
            self.Modified()

    def add_bounding_box(
        self,
        color="grey",
        corner_factor=0.5,
        line_width=None,
        opacity=1.0,
        render_lines_as_tubes=False,
        lighting=None,
        reset_camera=None,
        outline=True,
        culling='front',
    ):
        """Add an unlabeled and unticked box at the boundaries of plot.

        Useful for when wanting to plot outer grids while still
        retaining all edges of the boundary.

        Parameters
        ----------
        color : ColorLike, default: "grey"
            Color of all labels and axis titles.  Default white.
            Either a string, rgb sequence, or hex color string.  For
            example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        corner_factor : float, default: 0.5
            This is the factor along each axis to draw the default
            box. Default is 0.5 to show the full box.

        line_width : float, optional
            Thickness of lines.

        opacity : float, default: 1.0
            Opacity of mesh. Should be between 0 and 1.

        render_lines_as_tubes : bool, default: False
            Show lines as thick tubes rather than flat lines.  Control
            the width with ``line_width``.

        lighting : bool, optional
            Enable or disable directional lighting for this actor.

        reset_camera : bool, optional
            Reset camera position when ``True`` to include all actors.

        outline : bool, default: True
            Default is ``True``. when ``False``, a box with faces is
            shown with the specified culling.

        culling : str, default: "front"
            Does not render faces on the bounding box that are culled. Options
            are ``'front'`` or ``'back'``.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the bounding box.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(pyvista.Sphere())
        >>> _ = pl.add_bounding_box(line_width=5, color='black')
        >>> pl.show()

        """
        if lighting is None:
            lighting = self._theme.lighting

        self.remove_bounding_box()
        if outline:
            self._bounding_box = _vtk.vtkOutlineCornerSource()
            self._bounding_box.SetCornerFactor(corner_factor)
        else:
            self._bounding_box = _vtk.vtkCubeSource()
        self._bounding_box.SetBounds(self.bounds)
        self._bounding_box.Update()
        self._box_object = wrap(self._bounding_box.GetOutput())
        name = f'BoundingBox({hex(id(self._box_object))})'

        mapper = _vtk.vtkDataSetMapper()
        mapper.SetInputData(self._box_object)
        self.bounding_box_actor, prop = self.add_actor(
            mapper, reset_camera=reset_camera, name=name, culling=culling, pickable=False
        )

        prop.SetColor(Color(color, default_color=self._theme.outline_color).float_rgb)
        prop.SetOpacity(opacity)
        if render_lines_as_tubes:
            prop.SetRenderLinesAsTubes(render_lines_as_tubes)

        # lighting display style
        if lighting is False:
            prop.LightingOff()

        # set line thickness
        if line_width:
            prop.SetLineWidth(line_width)

        prop.SetRepresentationToSurface()
        self.Modified()
        return self.bounding_box_actor

    def add_floor(
        self,
        face='-z',
        i_resolution=10,
        j_resolution=10,
        color=None,
        line_width=None,
        opacity=1.0,
        show_edges=False,
        lighting=False,
        edge_color=None,
        reset_camera=None,
        pad=0.0,
        offset=0.0,
        pickable=False,
        store_floor_kwargs=True,
    ):
        """Show a floor mesh.

        This generates planes at the boundaries of the scene to behave
        like floors or walls.

        Parameters
        ----------
        face : str, default: "-z"
            The face at which to place the plane. Options are
            (``'-z'``, ``'-y'``, ``'-x'``, ``'+z'``, ``'+y'``, and
            ``'+z'``). Where the ``-/+`` sign indicates on which side of
            the axis the plane will lie.  For example, ``'-z'`` would
            generate a floor on the XY-plane and the bottom of the
            scene (minimum z).

        i_resolution : int, default: 10
            Number of points on the plane in the i direction.

        j_resolution : int, default: 10
            Number of points on the plane in the j direction.

        color : ColorLike, optional
            Color of all labels and axis titles.  Default gray.
            Either a string, rgb list, or hex color string.

        line_width : int, optional
            Thickness of the edges. Only if ``show_edges`` is
            ``True``.

        opacity : float, default: 1.0
            The opacity of the generated surface.

        show_edges : bool, default: False
            Flag on whether to show the mesh edges for tiling.

        line_width : float, default: False
            Thickness of lines.  Only valid for wireframe and surface
            representations.

        lighting : bool, default: False
            Enable or disable view direction lighting.

        edge_color : ColorLike, optional
            Color of the edges of the mesh.

        reset_camera : bool, optional
            Resets the camera when ``True`` after adding the floor.

        pad : float, default: 0.0
            Percentage padding between 0 and 1.

        offset : float, default: 0.0
            Percentage offset along plane normal.

        pickable : bool, default: false
            Make this floor actor pickable in the renderer.

        store_floor_kwargs : bool, default: True
            Stores the keyword arguments used when adding this floor.
            Useful when updating the bounds and regenerating the
            floor.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the floor.

        Examples
        --------
        Add a floor below a sphere and plot it.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Sphere())
        >>> actor = pl.add_floor()
        >>> pl.show()

        """
        if store_floor_kwargs:
            kwargs = locals()
            kwargs.pop('self')
            self._floor_kwargs.append(kwargs)
        ranges = np.array(self.bounds).reshape(-1, 2).ptp(axis=1)
        ranges += ranges * pad
        center = np.array(self.center)
        if face.lower() in '-z':
            center[2] = self.bounds[4] - (ranges[2] * offset)
            normal = (0, 0, 1)
            i_size = ranges[0]
            j_size = ranges[1]
        elif face.lower() in '-y':
            center[1] = self.bounds[2] - (ranges[1] * offset)
            normal = (0, 1, 0)
            i_size = ranges[0]
            j_size = ranges[2]
        elif face.lower() in '-x':
            center[0] = self.bounds[0] - (ranges[0] * offset)
            normal = (1, 0, 0)
            i_size = ranges[2]
            j_size = ranges[1]
        elif face.lower() in '+z':
            center[2] = self.bounds[5] + (ranges[2] * offset)
            normal = (0, 0, -1)
            i_size = ranges[0]
            j_size = ranges[1]
        elif face.lower() in '+y':
            center[1] = self.bounds[3] + (ranges[1] * offset)
            normal = (0, -1, 0)
            i_size = ranges[0]
            j_size = ranges[2]
        elif face.lower() in '+x':
            center[0] = self.bounds[1] + (ranges[0] * offset)
            normal = (-1, 0, 0)
            i_size = ranges[2]
            j_size = ranges[1]
        else:
            raise NotImplementedError(f'Face ({face}) not implementd')
        self._floor = pyvista.Plane(
            center=center,
            direction=normal,
            i_size=i_size,
            j_size=j_size,
            i_resolution=i_resolution,
            j_resolution=j_resolution,
        )
        self._floor.clear_data()

        if lighting is None:
            lighting = self._theme.lighting

        self.remove_bounding_box()
        mapper = _vtk.vtkDataSetMapper()
        mapper.SetInputData(self._floor)
        actor, prop = self.add_actor(
            mapper, reset_camera=reset_camera, name=f'Floor({face})', pickable=pickable
        )

        prop.SetColor(Color(color, default_color=self._theme.floor_color).float_rgb)
        prop.SetOpacity(opacity)

        # edge display style
        if show_edges:
            prop.EdgeVisibilityOn()
        prop.SetEdgeColor(Color(edge_color, default_color=self._theme.edge_color).float_rgb)

        # lighting display style
        if lighting is False:
            prop.LightingOff()

        # set line thickness
        if line_width:
            prop.SetLineWidth(line_width)

        prop.SetRepresentationToSurface()
        self._floors.append(actor)
        return actor

    def remove_floors(self, clear_kwargs=True, render=True):
        """Remove all floor actors.

        Parameters
        ----------
        clear_kwargs : bool, default: True
            Clear default floor arguments.

        render : bool, default: True
            Render upon removing the floor.

        Examples
        --------
        Add a floor below a sphere, remove it, and then plot it.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Sphere())
        >>> actor = pl.add_floor()
        >>> pl.remove_floors()
        >>> pl.show()

        """
        if getattr(self, '_floor', None) is not None:
            self._floor.ReleaseData()
            self._floor = None
        for actor in self._floors:
            self.remove_actor(actor, reset_camera=False, render=render)
        self._floors.clear()
        if clear_kwargs:
            self._floor_kwargs.clear()

    def remove_bounds_axes(self):
        """Remove bounds axes.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter(shape=(1, 2))
        >>> pl.subplot(0, 0)
        >>> actor = pl.add_mesh(pyvista.Sphere())
        >>> actor = pl.show_bounds(grid='front', location='outer')
        >>> pl.subplot(0, 1)
        >>> actor = pl.add_mesh(pyvista.Sphere())
        >>> actor = pl.show_bounds(grid='front', location='outer')
        >>> actor = pl.remove_bounds_axes()
        >>> pl.show()

        """
        if self.cube_axes_actor is not None:
            self.remove_actor(self.cube_axes_actor)
            self.cube_axes_actor = None
            self.Modified()

    def add_light(self, light):
        """Add a light to the renderer.

        Parameters
        ----------
        light : vtk.vtkLight or pyvista.Light
            Light to add.

        """
        # convert from a vtk type if applicable
        if isinstance(light, _vtk.vtkLight) and not isinstance(light, pyvista.Light):
            light = pyvista.Light.from_vtk(light)

        if not isinstance(light, pyvista.Light):
            raise TypeError(f'Expected Light instance, got {type(light).__name__} instead.')
        self._lights.append(light)
        self.AddLight(light)
        self.Modified()

        # we add the renderer to add/remove the light actor if
        # positional or cone angle is modified
        light.add_renderer(self)

    @property
    def lights(self):
        """Return a list of all lights in the renderer.

        Returns
        -------
        list
            Lights in the renderer.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.renderer.lights  # doctest:+SKIP
        [<Light (Headlight) at ...>,
         <Light (Camera Light) at 0x7f1dd8155760>,
         <Light (Camera Light) at 0x7f1dd8155340>,
         <Light (Camera Light) at 0x7f1dd8155460>,
         <Light (Camera Light) at 0x7f1dd8155f40>]

        """
        return list(self.GetLights())

    def remove_all_lights(self):
        """Remove all lights from the renderer."""
        self.RemoveAllLights()
        self._lights.clear()

    def clear_actors(self):
        """Remove all actors (keep lights and properties)."""
        if self._actors:
            for actor in list(self._actors):
                try:
                    self.remove_actor(actor, reset_camera=False, render=False)
                except KeyError:
                    pass
            self.Modified()

    def clear(self):
        """Remove all actors and properties."""
        self.clear_actors()
        if self.__charts is not None:
            self._charts.deep_clean()
        self.remove_all_lights()
        self.RemoveAllViewProps()
        self.Modified()

        self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS))
        self._scalar_bar_slot_lookup = {}

    def set_focus(self, point):
        """Set focus to a point.

        Parameters
        ----------
        point : sequence[float]
            Cartesian point to focus on in the form of ``[x, y, z]``.

        Examples
        --------
        >>> import pyvista
        >>> mesh = pyvista.Cube()
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(mesh, show_edges=True)
        >>> _ = pl.add_point_labels([mesh.points[1]], ["Focus"])
        >>> _ = pl.camera  # this initializes the camera
        >>> pl.set_focus(mesh.points[1])
        >>> pl.show()

        """
        if isinstance(point, np.ndarray):
            if point.ndim != 1:
                point = point.ravel()
        self.camera.focal_point = scale_point(self.camera, point, invert=False)
        self.camera_set = True
        self.Modified()

    def set_position(self, point, reset=False, render=True):
        """Set camera position to a point.

        Parameters
        ----------
        point : sequence
            Cartesian point to focus on in the form of ``[x, y, z]``.

        reset : bool, default: False
            Whether to reset the camera after setting the camera
            position.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the position.

        Examples
        --------
        Move the camera far away to ``[7, 7, 7]``.

        >>> import pyvista
        >>> mesh = pyvista.Cube()
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(mesh, show_edges=True)
        >>> pl.set_position([7, 7, 7])
        >>> pl.show()

        """
        if isinstance(point, np.ndarray):
            if point.ndim != 1:
                point = point.ravel()
        self.camera.position = scale_point(self.camera, point, invert=False)
        if reset:
            self.reset_camera(render=render)
        self.camera_set = True
        self.Modified()

    def set_viewup(self, vector, reset=True, render=True):
        """Set camera viewup vector.

        Parameters
        ----------
        vector : sequence[float]
            New camera viewup vector.

        reset : bool, default: True
            Whether to reset the camera after setting the camera
            position.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the viewup.

        Examples
        --------
        Look from the top down by setting view up to ``[0, 1, 0]``.
        Notice how the Y axis appears vertical.

        >>> from pyvista import demos
        >>> pl = demos.orientation_plotter()
        >>> pl.set_viewup([0, 1, 0])
        >>> pl.show()

        """
        if isinstance(vector, np.ndarray):
            if vector.ndim != 1:
                vector = vector.ravel()

        self.camera.up = vector
        if reset:
            self.reset_camera(render=render)

        self.camera_set = True
        self.Modified()

    def enable_parallel_projection(self):
        """Enable parallel projection.

        The camera will have a parallel projection. Parallel projection is
        often useful when viewing images or 2D datasets.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import demos
        >>> pl = pyvista.demos.orientation_plotter()
        >>> pl.enable_parallel_projection()
        >>> pl.show()

        """
        # Fix the 'reset camera' effect produced by the VTK when parallel
        # projection is enabled.
        angle = np.radians(self.camera.view_angle)
        self.camera.parallel_scale = self.camera.distance * np.sin(0.5 * angle)

        self.camera.enable_parallel_projection()
        self.Modified()

    def disable_parallel_projection(self):
        """Reset the camera to use perspective projection.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import demos
        >>> pl = pyvista.demos.orientation_plotter()
        >>> pl.disable_parallel_projection()
        >>> pl.show()

        """
        # Fix the 'reset camera' effect produced by the VTK when parallel
        # projection is disabled.
        focus = self.camera.focal_point
        angle = np.radians(self.camera.view_angle)
        distance = self.camera.parallel_scale / np.sin(0.5 * angle)
        direction = self.camera.direction
        x = focus[0] - distance * direction[0]
        y = focus[1] - distance * direction[1]
        z = focus[2] - distance * direction[2]
        self.camera.position = (x, y, z)
        self.ResetCameraClippingRange()

        self.camera.disable_parallel_projection()
        self.Modified()

    @property
    def parallel_projection(self):
        """Return parallel projection state of active render window.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.parallel_projection = False
        >>> pl.parallel_projection
        False
        """
        return self.camera.parallel_projection

    @parallel_projection.setter
    def parallel_projection(self, state):
        """Set parallel projection state of all active render windows."""
        self.camera.parallel_projection = state
        self.Modified()

    @property
    def parallel_scale(self):
        """Return parallel scale of active render window.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.parallel_scale = 2
        """
        return self.camera.parallel_scale

    @parallel_scale.setter
    def parallel_scale(self, value):
        """Set parallel scale of all active render windows."""
        self.camera.parallel_scale = value
        self.Modified()

    def remove_actor(self, actor, reset_camera=False, render=True):
        """Remove an actor from the Renderer.

        Parameters
        ----------
        actor : str, vtk.vtkActor, list or tuple
            If the type is ``str``, removes the previously added actor
            with the given name. If the type is ``vtk.vtkActor``,
            removes the actor if it's previously added to the
            Renderer. If ``list`` or ``tuple``, removes iteratively
            each actor.

        reset_camera : bool, optional
            Resets camera so all actors can be seen.

        render : bool, optional
            Render upon actor removal.  Set this to ``False`` to stop
            the render window from rendering when an actor is removed.

        Returns
        -------
        bool
            ``True`` when actor removed.  ``False`` when actor has not
            been removed.

        Examples
        --------
        Add two meshes to a plotter and then remove the sphere actor.

        >>> import pyvista
        >>> mesh = pyvista.Cube()
        >>> pl = pyvista.Plotter()
        >>> cube_actor = pl.add_mesh(pyvista.Cube(), show_edges=True)
        >>> sphere_actor = pl.add_mesh(pyvista.Sphere(), show_edges=True)
        >>> _ = pl.remove_actor(cube_actor)
        >>> pl.show()

        """
        name = None
        if isinstance(actor, str):
            name = actor
            keys = list(self._actors.keys())
            names = []
            for k in keys:
                if k.startswith(f'{name}-'):
                    names.append(k)
            if len(names) > 0:
                self.remove_actor(names, reset_camera=reset_camera)
            try:
                actor = self._actors[name]
            except KeyError:
                # If actor of that name is not present then return success
                return False
        if isinstance(actor, collections.abc.Iterable):
            success = False
            for a in actor:
                rv = self.remove_actor(a, reset_camera=reset_camera)
                if rv or success:
                    success = True
            return success
        if actor is None:
            return False

        # remove any labels associated with the actor
        self._labels.pop(actor.GetAddressAsString(""), None)

        # ensure any scalar bars associated with this actor are removed
        try:
            self.parent.scalar_bars._remove_mapper_from_plotter(actor)
        except (AttributeError, ReferenceError):
            pass
        self.RemoveActor(actor)

        if name is None:
            for k, v in self._actors.items():
                if v == actor:
                    name = k
        self._actors.pop(name, None)
        self.update_bounds_axes()
        if reset_camera:
            self.reset_camera(render=render)
        elif not self.camera_set and reset_camera is None:
            self.reset_camera(render=render)
        elif render:
            self.parent.render()

        self.Modified()
        return True

    def set_scale(self, xscale=None, yscale=None, zscale=None, reset_camera=True, render=True):
        """Scale all the actors in the scene.

        Scaling in performed independently on the X, Y and Z axis.
        A scale of zero is illegal and will be replaced with one.

        .. warning::
            Setting the scale on the renderer is a convenience method to
            individually scale each of the actors in the scene. If a scale
            was set on an actor previously, it will be reset to the scale
            of this Renderer.

        Parameters
        ----------
        xscale : float, optional
            Scaling in the x direction.  Default is ``None``, which
            does not change existing scaling.

        yscale : float, optional
            Scaling in the y direction.  Default is ``None``, which
            does not change existing scaling.

        zscale : float, optional
            Scaling in the z direction.  Default is ``None``, which
            does not change existing scaling.

        reset_camera : bool, default: True
            Resets camera so all actors can be seen.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the scale.

        Examples
        --------
        Set the scale in the z direction to be 2 times that of
        nominal.  Leave the other axes unscaled.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.set_scale(zscale=2)
        >>> _ = pl.add_mesh(pyvista.Sphere())  # perfect sphere
        >>> pl.show()

        """
        if xscale is None:
            xscale = self.scale[0]
        if yscale is None:
            yscale = self.scale[1]
        if zscale is None:
            zscale = self.scale[2]
        self.scale = [xscale, yscale, zscale]

        # Reset all actors to match this scale
        for actor in self.actors.values():
            if hasattr(actor, 'SetScale'):
                actor.SetScale(self.scale)

        self.parent.render()
        if reset_camera:
            self.update_bounds_axes()
            self.reset_camera(render=render)
        self.Modified()

    def get_default_cam_pos(self, negative=False):
        """Return the default focal points and viewup.

        Uses ResetCamera to make a useful view.

        Parameters
        ----------
        negative : bool, default: False
            View from the opposite direction.

        Returns
        -------
        list
            List of camera position:

            * Position
            * Focal point
            * View up

        """
        focal_pt = self.center
        if any(np.isnan(focal_pt)):
            focal_pt = (0.0, 0.0, 0.0)
        position = np.array(self._theme.camera['position']).astype(float)
        if negative:
            position *= -1
        position = position / np.array(self.scale).astype(float)
        cpos = [position + np.array(focal_pt), focal_pt, self._theme.camera['viewup']]
        return cpos

    def update_bounds_axes(self):
        """Update the bounds axes of the render window."""
        if (
            hasattr(self, '_box_object')
            and self._box_object is not None
            and self.bounding_box_actor is not None
        ):
            if not np.allclose(self._box_object.bounds, self.bounds):
                color = self.bounding_box_actor.GetProperty().GetColor()
                self.remove_bounding_box()
                self.add_bounding_box(color=color)
                self.remove_floors(clear_kwargs=False)
                for floor_kwargs in self._floor_kwargs:
                    floor_kwargs['store_floor_kwargs'] = False
                    self.add_floor(**floor_kwargs)
        if self.cube_axes_actor is not None:
            self.cube_axes_actor.update_bounds(self.bounds)
            if not np.allclose(self.scale, [1.0, 1.0, 1.0]):
                self.cube_axes_actor.SetUse2DMode(True)
            else:
                self.cube_axes_actor.SetUse2DMode(False)
            self.Modified()

    def reset_camera(self, render=True, bounds=None):
        """Reset the camera of the active render window.

        The camera slides along the vector defined from camera
        position to focal point until all of the actors can be seen.

        Parameters
        ----------
        render : bool, default: True
            Trigger a render after resetting the camera.

        bounds : iterable(int), optional
            Automatically set up the camera based on a specified bounding box
            ``(xmin, xmax, ymin, ymax, zmin, zmax)``.

        Examples
        --------
        Add a mesh and place the camera position too close to the
        mesh.  Then reset the camera and show the mesh.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Sphere(), show_edges=True)
        >>> pl.set_position((0, 0.1, 0.1))
        >>> pl.reset_camera()
        >>> pl.show()

        """
        if bounds is not None:
            self.ResetCamera(*bounds)
        else:
            self.ResetCamera()

        self.reset_camera_clipping_range()

        if render:
            self.parent.render()
        self.Modified()

    def isometric_view(self):
        """Reset the camera to a default isometric view.

        DEPRECATED: Please use ``view_isometric``.

        """
        self.view_isometric()

    def view_isometric(self, negative=False, render=True):
        """Reset the camera to a default isometric view.

        The view will show all the actors in the scene.

        Parameters
        ----------
        negative : bool, default: False
            View from the other isometric direction.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the camera position.

        Examples
        --------
        Isometric view.

        >>> from pyvista import demos
        >>> pl = demos.orientation_plotter()
        >>> pl.view_isometric()
        >>> pl.show()

        Negative isometric view.

        >>> from pyvista import demos
        >>> pl = demos.orientation_plotter()
        >>> pl.view_isometric(negative=True)
        >>> pl.show()

        """
        position = self.get_default_cam_pos(negative=negative)
        self.camera_position = CameraPosition(*position)
        self.camera_set = negative
        self.reset_camera(render=render)

    def view_vector(self, vector, viewup=None, render=True):
        """Point the camera in the direction of the given vector.

        Parameters
        ----------
        vector : sequence[float]
            Direction to point the camera in.

        viewup : sequence[float], optional
            Sequence describing the view up of the camera.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the camera position.

        """
        focal_pt = self.center
        if viewup is None:
            viewup = self._theme.camera['viewup']
        cpos = CameraPosition(vector + np.array(focal_pt), focal_pt, viewup)
        self.camera_position = cpos
        self.reset_camera(render=render)

    def view_xy(self, negative=False, render=True):
        """View the XY plane.

        Parameters
        ----------
        negative : bool, default: False
            View from the opposite direction.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the camera position.

        Examples
        --------
        View the XY plane of a built-in mesh example.

        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> airplane = examples.load_airplane()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(airplane)
        >>> pl.view_xy()
        >>> pl.show()

        """
        self.view_vector(*view_vectors('xy', negative=negative), render=render)

    def view_yx(self, negative=False, render=True):
        """View the YX plane.

        Parameters
        ----------
        negative : bool, default: False
            View from the opposite direction.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the camera position.

        Examples
        --------
        View the YX plane of a built-in mesh example.

        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> airplane = examples.load_airplane()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(airplane)
        >>> pl.view_yx()
        >>> pl.show()

        """
        self.view_vector(*view_vectors('yx', negative=negative), render=render)

    def view_xz(self, negative=False, render=True):
        """View the XZ plane.

        Parameters
        ----------
        negative : bool, default: False
            View from the opposite direction.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the camera position.

        Examples
        --------
        View the XZ plane of a built-in mesh example.

        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> airplane = examples.load_airplane()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(airplane)
        >>> pl.view_xz()
        >>> pl.show()

        """
        self.view_vector(*view_vectors('xz', negative=negative), render=render)

    def view_zx(self, negative=False, render=True):
        """View the ZX plane.

        Parameters
        ----------
        negative : bool, default: False
            View from the opposite direction.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the camera position.

        Examples
        --------
        View the ZX plane of a built-in mesh example.

        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> airplane = examples.load_airplane()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(airplane)
        >>> pl.view_zx()
        >>> pl.show()

        """
        self.view_vector(*view_vectors('zx', negative=negative), render=render)

    def view_yz(self, negative=False, render=True):
        """View the YZ plane.

        Parameters
        ----------
        negative : bool, default: False
            View from the opposite direction.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the camera position.

        Examples
        --------
        View the YZ plane of a built-in mesh example.

        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> airplane = examples.load_airplane()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(airplane)
        >>> pl.view_yz()
        >>> pl.show()

        """
        self.view_vector(*view_vectors('yz', negative=negative), render=render)

    def view_zy(self, negative=False, render=True):
        """View the ZY plane.

        Parameters
        ----------
        negative : bool, default: False
            View from the opposite direction.

        render : bool, default: True
            If the render window is being shown, trigger a render
            after setting the camera position.

        Examples
        --------
        View the ZY plane of a built-in mesh example.

        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> airplane = examples.load_airplane()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(airplane)
        >>> pl.view_zy()
        >>> pl.show()

        """
        self.view_vector(*view_vectors('zy', negative=negative), render=render)

    def disable(self):
        """Disable this renderer's camera from being interactive."""
        self.SetInteractive(0)

    def enable(self):
        """Enable this renderer's camera to be interactive."""
        self.SetInteractive(1)

    def add_blurring(self):
        """Add blurring.

        This can be added several times to increase the degree of blurring.

        Examples
        --------
        Add two blurring passes to the plotter and show it.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Sphere(), show_edges=True)
        >>> pl.add_blurring()
        >>> pl.add_blurring()
        >>> pl.show()

        See :ref:`blur_example` for a full example using this method.

        """
        self._render_passes.add_blur_pass()

    def remove_blurring(self):
        """Remove a single blurring pass.

        You will need to run this multiple times to remove all blurring passes.

        Examples
        --------
        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Sphere())
        >>> pl.add_blurring()
        >>> pl.remove_blurring()
        >>> pl.show()

        """
        self._render_passes.remove_blur_pass()

    def enable_depth_of_field(self, automatic_focal_distance=True):
        """Enable depth of field plotting.

        Parameters
        ----------
        automatic_focal_distance : bool, default: True
            Use automatic focal distance calculation. When enabled, the center
            of the viewport will always be in focus regardless of where the
            focal point is.

        Examples
        --------
        Create five spheres and demonstrate the effect of depth of field.

        >>> import pyvista as pv
        >>> from pyvista import examples
        >>> pl = pv.Plotter(lighting="three lights")
        >>> pl.background_color = "w"
        >>> for i in range(5):
        ...     mesh = pv.Sphere(center=(-i * 4, 0, 0))
        ...     color = [0, 255 - i * 20, 30 + i * 50]
        ...     _ = pl.add_mesh(
        ...         mesh,
        ...         show_edges=False,
        ...         pbr=True,
        ...         metallic=1.0,
        ...         color=color,
        ...     )
        ...
        >>> pl.camera.zoom(1.8)
        >>> pl.camera_position = [
        ...     (4.74, 0.959, 0.525),
        ...     (0.363, 0.3116, 0.132),
        ...     (-0.088, -0.0075, 0.996),
        ... ]
        >>> pl.enable_depth_of_field()
        >>> pl.show()

        See :ref:`depth_of_field_example` for a full example using this method.

        """
        self._render_passes.enable_depth_of_field_pass(automatic_focal_distance)

    def disable_depth_of_field(self):
        """Disable depth of field plotting.

        Examples
        --------
        >>> import pyvista as pv
        >>> pl = pv.Plotter(lighting="three lights")
        >>> pl.enable_depth_of_field()
        >>> pl.disable_depth_of_field()

        """
        self._render_passes.disable_depth_of_field_pass()

    def enable_eye_dome_lighting(self):
        """Enable eye dome lighting (EDL).

        Returns
        -------
        vtk.vtkOpenGLRenderer
            VTK renderer with eye dome lighting pass.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> _ = pl.enable_eye_dome_lighting()

        """
        self._render_passes.enable_edl_pass()

    def disable_eye_dome_lighting(self):
        """Disable eye dome lighting (EDL).

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.disable_eye_dome_lighting()

        """
        self._render_passes.disable_edl_pass()

    def enable_shadows(self):
        """Enable shadows.

        Examples
        --------
        First, plot without shadows enabled (default)

        >>> import pyvista
        >>> mesh = pyvista.Sphere()
        >>> pl = pyvista.Plotter(lighting='none', window_size=(1000, 1000))
        >>> light = pyvista.Light()
        >>> light.set_direction_angle(20, -20)
        >>> pl.add_light(light)
        >>> _ = pl.add_mesh(mesh, color='white', smooth_shading=True)
        >>> _ = pl.add_mesh(pyvista.Box((-1.2, -1, -1, 1, -1, 1)))
        >>> pl.show()

        Now, enable shadows.

        >>> import pyvista
        >>> mesh = pyvista.Sphere()
        >>> pl = pyvista.Plotter(lighting='none', window_size=(1000, 1000))
        >>> light = pyvista.Light()
        >>> light.set_direction_angle(20, -20)
        >>> pl.add_light(light)
        >>> _ = pl.add_mesh(mesh, color='white', smooth_shading=True)
        >>> _ = pl.add_mesh(pyvista.Box((-1.2, -1, -1, 1, -1, 1)))
        >>> pl.enable_shadows()
        >>> pl.show()

        """
        self._render_passes.enable_shadow_pass()

    def disable_shadows(self):
        """Disable shadows.

        Examples
        --------
        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> pl.disable_shadows()

        """
        self._render_passes.disable_shadow_pass()

    def enable_ssao(self, radius=0.5, bias=0.005, kernel_size=256, blur=True):
        """Enable surface space ambient occlusion (SSAO).

        SSAO can approximate shadows more efficiently than ray-tracing
        and produce similar results. Use this when you wish to plot the
        occlusion effect that nearby meshes have on each other by blocking
        nearby light sources.

        See `Kitware: Screen-Space Ambient Occlusion
        <https://www.kitware.com/ssao/>`_ for more details

        Parameters
        ----------
        radius : float, default: 0.5
            Neighbor pixels considered when computing the occlusion.

        bias : float, default: 0.005
            Tolerance factor used when comparing pixel depth.

        kernel_size : int, default: 256
            Number of samples used. This controls the quality where a higher
            number increases the quality at the expense of computation time.

        blur : bool, default: True
            Controls if occlusion buffer should be blurred before combining it
            with the color buffer.

        Examples
        --------
        Generate a :class:`pyvista.UnstructuredGrid` with many tetrahedrons
        nearby each other and plot it without SSAO.

        >>> import pyvista as pv
        >>> ugrid = pv.UniformGrid(dimensions=(3, 2, 2)).to_tetrahedra(12)
        >>> exploded = ugrid.explode()
        >>> exploded.plot()

        Enable SSAO with the default parameters.

        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(exploded)
        >>> pl.enable_ssao()
        >>> pl.show()

        """
        self._render_passes.enable_ssao_pass(radius, bias, kernel_size, blur)

    def disable_ssao(self):
        """Disable surface space ambient occlusion (SSAO)."""
        self._render_passes.disable_ssao_pass()

    def get_pick_position(self):
        """Get the pick position/area as ``x0, y0, x1, y1``.

        Returns
        -------
        tuple
            Pick position as ``x0, y0, x1, y1``.

        """
        x0 = int(self.GetPickX1())
        x1 = int(self.GetPickX2())
        y0 = int(self.GetPickY1())
        y1 = int(self.GetPickY2())
        return x0, y0, x1, y1

    def set_background(self, color, top=None):
        """Set the background color of this renderer.

        Parameters
        ----------
        color : ColorLike, optional
            Either a string, rgb list, or hex color string.  Defaults
            to theme default.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        top : ColorLike, optional
            If given, this will enable a gradient background where the
            ``color`` argument is at the bottom and the color given in
            ``top`` will be the color at the top of the renderer.

        Examples
        --------
        Set the background color to black with a gradient to white at
        the top of the plot.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Cone())
        >>> pl.set_background('black', top='white')
        >>> pl.show()

        """
        use_gradient = False
        if top is not None:
            use_gradient = True

        self.SetBackground(Color(color, default_color=self._theme.background).float_rgb)
        if use_gradient:
            self.SetGradientBackground(True)
            self.SetBackground2(Color(top).float_rgb)
        else:
            self.SetGradientBackground(False)
        self.Modified()

    def set_environment_texture(self, texture, is_srgb=False):
        """Set the environment texture used for image based lighting.

        This texture is supposed to represent the scene background. If
        it is not a cubemap, the texture is supposed to represent an
        equirectangular projection. If used with raytracing backends,
        the texture must be an equirectangular projection and must be
        constructed with a valid ``vtk.vtkImageData``.

        Parameters
        ----------
        texture : vtk.vtkTexture
            Texture.

        is_srgb : bool, default: False
            If the texture is in sRGB color space, set the color flag on the
            texture or set this parameter to ``True``. Textures are assumed
            to be in linear color space by default.

        Examples
        --------
        Add a skybox cubemap as an environment texture and show that the
        lighting from the texture is mapped on to a sphere dataset. Note how
        even when disabling the default lightkit, the scene lighting will still
        be mapped onto the actor.

        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> pl = pv.Plotter(lighting=None)
        >>> cubemap = examples.download_sky_box_cube_map()
        >>> _ = pl.add_mesh(
        ...     pv.Sphere(), pbr=True, metallic=0.9, roughness=0.4
        ... )
        >>> pl.set_environment_texture(cubemap)
        >>> pl.camera_position = 'xy'
        >>> pl.show()

        """
        # cube_map textures cannot use spherical harmonics
        if texture.cube_map:
            self.AutomaticLightCreationOff()
            # disable spherical harmonics was added in 9.1.0
            if hasattr(self, 'UseSphericalHarmonicsOff'):
                self.UseSphericalHarmonicsOff()

        self.UseImageBasedLightingOn()
        self.SetEnvironmentTexture(texture, is_srgb)
        self.Modified()

    def remove_environment_texture(self):
        """Remove the environment texture.

        Examples
        --------
        >>> from pyvista import examples
        >>> import pyvista as pv
        >>> pl = pv.Plotter(lighting=None)
        >>> cubemap = examples.download_sky_box_cube_map()
        >>> _ = pl.add_mesh(
        ...     pv.Sphere(), pbr=True, metallic=0.9, roughness=0.4
        ... )
        >>> pl.set_environment_texture(cubemap)
        >>> pl.remove_environment_texture()
        >>> pl.camera_position = 'xy'
        >>> pl.show()

        """
        self.UseImageBasedLightingOff()
        self.SetEnvironmentTexture(None)
        self.Modified()

    def close(self):
        """Close out widgets and sensitive elements."""
        self.RemoveAllObservers()
        if hasattr(self, 'axes_widget'):
            self.hide_axes()  # Necessary to avoid segfault
            self.axes_actor = None
            del self.axes_widget

        if self._empty_str is not None:
            self._empty_str.SetReferenceCount(0)
            self._empty_str = None

    def on_plotter_render(self):
        """Notify renderer components of explicit plotter render call."""
        if self.__charts is not None:
            for chart in self.__charts:
                # Notify Charts that plotter.render() is called
                chart._render_event(plotter_render=True)

    def deep_clean(self, render=False):
        """Clean the renderer of the memory.

        Parameters
        ----------
        render : bool, optional
            Render the render window after removing the bounding box
            (if applicable).

        """
        if self.cube_axes_actor is not None:
            self.cube_axes_actor = None

        if hasattr(self, 'edl_pass'):
            del self.edl_pass
        if hasattr(self, '_box_object'):
            self.remove_bounding_box(render=render)
        if hasattr(self, '_shadow_pass') and self._shadow_pass is not None:
            self.disable_shadows()
        try:
            if self.__charts is not None:
                self.__charts.deep_clean()
                self.__charts = None
        except AttributeError:  # pragma: no cover
            pass

        self._render_passes.deep_clean()
        self.remove_floors(render=render)
        self.remove_legend(render=render)
        self.RemoveAllViewProps()
        self._actors = {}
        self._camera = None
        self._bounding_box = None
        self._marker_actor = None
        self._border_actor = None
        # remove reference to parent last
        self.parent = None

    def __del__(self):
        """Delete the renderer."""
        self.deep_clean()

    def enable_hidden_line_removal(self):
        """Enable hidden line removal."""
        self.UseHiddenLineRemovalOn()

    def disable_hidden_line_removal(self):
        """Disable hidden line removal."""
        self.UseHiddenLineRemovalOff()

    @property
    def layer(self):
        """Return or set the current layer of this renderer."""
        return self.GetLayer()

    @layer.setter
    def layer(self, layer):
        self.SetLayer(layer)

    @property
    def viewport(self):
        """Viewport of the renderer.

        Viewport describes the ``(xstart, ystart, xend, yend)`` square
        of the renderer relative to the main renderer window.

        For example, a renderer taking up the entire window will have
        a viewport of ``(0.0, 0.0, 1.0, 1.0)``, while the viewport of
        a renderer on the left-hand side of a horizontally split window
        would be ``(0.0, 0.0, 0.5, 1.0)``.

        Returns
        -------
        tuple
            Viewport in the form ``(xstart, ystart, xend, yend)``.

        Examples
        --------
        Show the viewport of a renderer taking up half the render
        window.

        >>> import pyvista
        >>> pl = pyvista.Plotter(shape=(1, 2))
        >>> pl.renderers[0].viewport
        (0.0, 0.0, 0.5, 1.0)

        """
        return self.GetViewport()

    @property
    def width(self):
        """Width of the renderer."""
        xmin, _, xmax, _ = self.viewport
        return self.parent.window_size[0] * (xmax - xmin)

    @property
    def height(self):
        """Height of the renderer."""
        _, ymin, _, ymax = self.viewport
        return self.parent.window_size[1] * (ymax - ymin)

    def add_legend(
        self,
        labels=None,
        bcolor=(0.5, 0.5, 0.5),
        border=False,
        size=(0.2, 0.2),
        name=None,
        loc='upper right',
        face='triangle',
    ):
        """Add a legend to render window.

        Entries must be a list containing one string and color entry for each
        item.

        Parameters
        ----------
        labels : list, optional
            When set to ``None``, uses existing labels as specified by

            - :func:`add_mesh <Plotter.add_mesh>`
            - :func:`add_lines <Plotter.add_lines>`
            - :func:`add_points <Plotter.add_points>`

            List containing one entry for each item to be added to the
            legend.  Each entry must contain two strings, [label,
            color], where label is the name of the item to add, and
            color is the color of the label to add.

        bcolor : ColorLike, default: (0.5, 0.5, 0.5)
            Background color, either a three item 0 to 1 RGB color
            list, or a matplotlib color string (e.g. ``'w'`` or ``'white'``
            for a white color).  If None, legend background is
            disabled.

        border : bool, default: False
            Controls if there will be a border around the legend.
            Default False.

        size : sequence[float], default: (0.2, 0.2)
            Two float sequence, each float between 0 and 1.  For example
            ``(0.1, 0.1)`` would make the legend 10% the size of the
            entire figure window.

        name : str, optional
            The name for the added actor so that it can be easily
            updated.  If an actor of this name already exists in the
            rendering window, it will be replaced by the new actor.

        loc : str, default: "upper right"
            Location string.  One of the following:

            * ``'upper right'``
            * ``'upper left'``
            * ``'lower left'``
            * ``'lower right'``
            * ``'center left'``
            * ``'center right'``
            * ``'lower center'``
            * ``'upper center'``
            * ``'center'``

        face : str | pyvista.PolyData | NoneType, default: "triangle"
            Face shape of legend face.  One of the following:

            * None: ``None``
            * Line: ``"-"`` or ``"line"``
            * Triangle: ``"^"`` or ``'triangle'``
            * Circle: ``"o"`` or ``'circle'``
            * Rectangle: ``"r"`` or ``'rectangle'``
            * Custom: :class:`pyvista.PolyData`

            Passing ``None`` removes the legend face.  A custom face can be
            created using :class:`pyvista.PolyData`.  This will be rendered
            from the XY plane.

        Returns
        -------
        vtk.vtkLegendBoxActor
            Actor for the legend.

        Examples
        --------
        Create a legend by labeling the meshes when using ``add_mesh``

        >>> import pyvista
        >>> from pyvista import examples
        >>> sphere = pyvista.Sphere(center=(0, 0, 1))
        >>> cube = pyvista.Cube()
        >>> plotter = pyvista.Plotter()
        >>> _ = plotter.add_mesh(
        ...     sphere, 'grey', smooth_shading=True, label='Sphere'
        ... )
        >>> _ = plotter.add_mesh(cube, 'r', label='Cube')
        >>> _ = plotter.add_legend(bcolor='w', face=None)
        >>> plotter.show()

        Alternatively provide labels in the plotter.

        >>> plotter = pyvista.Plotter()
        >>> _ = plotter.add_mesh(sphere, 'grey', smooth_shading=True)
        >>> _ = plotter.add_mesh(cube, 'r')
        >>> legend_entries = []
        >>> legend_entries.append(['My Mesh', 'w'])
        >>> legend_entries.append(['My Other Mesh', 'k'])
        >>> _ = plotter.add_legend(legend_entries)
        >>> plotter.show()

        """
        if self.legend is not None:
            self.remove_legend()
        self._legend = _vtk.vtkLegendBoxActor()

        if labels is None:
            # use existing labels
            if not self._labels:
                raise ValueError(
                    'No labels input.\n\n'
                    'Add labels to individual items when adding them to'
                    'the plotting object with the "label=" parameter.  '
                    'or enter them as the "labels" parameter.'
                )

            self._legend.SetNumberOfEntries(len(self._labels))
            for i, (vtk_object, text, color) in enumerate(self._labels.values()):
                if face is None:
                    # dummy vtk object
                    vtk_object = pyvista.PolyData([0.0, 0.0, 0.0])

                self._legend.SetEntry(i, vtk_object, text, color.float_rgb)

        else:
            self._legend.SetNumberOfEntries(len(labels))

            legend_face = make_legend_face(face)
            for i, (text, color) in enumerate(labels):
                self._legend.SetEntry(i, legend_face, text, Color(color).float_rgb)

        if loc is not None:
            if loc not in ACTOR_LOC_MAP:
                allowed = '\n'.join([f'\t * "{item}"' for item in ACTOR_LOC_MAP])
                raise ValueError(f'Invalid loc "{loc}".  Expected one of the following:\n{allowed}')
            x, y, size = map_loc_to_pos(loc, size, border=0.05)
            self._legend.SetPosition(x, y)
            self._legend.SetPosition2(size[0], size[1])

        if bcolor is None:
            self._legend.SetUseBackground(False)
        else:
            self._legend.SetUseBackground(True)
            self._legend.SetBackgroundColor(Color(bcolor).float_rgb)

        self._legend.SetBorder(border)

        self.add_actor(self._legend, reset_camera=False, name=name, pickable=False)
        return self._legend

    def remove_legend(self, render=True):
        """Remove the legend actor.

        Parameters
        ----------
        render : bool, default: True
            Render upon actor removal.  Set this to ``False`` to stop
            the render window from rendering when a the legend is removed.

        Examples
        --------
        >>> import pyvista
        >>> mesh = pyvista.Sphere()
        >>> pl = pyvista.Plotter()
        >>> _ = pl.add_mesh(mesh, label='sphere')
        >>> _ = pl.add_legend()
        >>> pl.remove_legend()

        """
        if self.legend is not None:
            self.remove_actor(self.legend, reset_camera=False, render=render)
            self._legend = None

    @property
    def legend(self):
        """Legend actor."""
        return self._legend

    def add_ruler(
        self,
        pointa,
        pointb,
        flip_range=False,
        number_labels=5,
        show_labels=True,
        font_size_factor=0.6,
        label_size_factor=1.0,
        label_format=None,
        title="Distance",
        number_minor_ticks=0,
        tick_length=5,
        minor_tick_length=3,
        show_ticks=True,
        tick_label_offset=2,
        label_color=None,
        tick_color=None,
    ):
        """Add ruler.

        The ruler is a 2D object that is not occluded by 3D objects.
        To avoid issues with perspective, it is recommended to use
        parallel projection, i.e. :func:`Plotter.enable_parallel_projection`,
        and place the ruler orthogonal to the viewing direction.

        The title and labels are placed to the right of ruler moving from
        ``pointa`` to ``pointb``. Use ``flip_range`` to flip the ``0`` location,
        if needed.

        Since the ruler is placed in an overlay on the viewing scene, the camera
        does not automatically reset to include the ruler in the view.

        Parameters
        ----------
        pointa : sequence[float]
            Starting point for ruler.

        pointb : sequence[float]
            Ending point for ruler.

        flip_range : bool, default: False
            If ``True``, the distance range goes from ``pointb`` to ``pointa``.

        number_labels : int, default: 5
            Number of labels to place on ruler.

        show_labels : bool, default: True
            Whether to show labels.

        font_size_factor : float, default: 0.6
            Factor to scale font size overall.

        label_size_factor : float, default: 1.0
            Factor to scale label size relative to title size.

        label_format : str, optional
            A printf style format for labels, e.g. '%E'.

        title : str, default: "Distance"
            The title to display.

        number_minor_ticks : int, default: 0
            Number of minor ticks between major ticks.

        tick_length : int, default: 5
            Length of ticks in pixels.

        minor_tick_length : int, default: 3
            Length of minor ticks in pixels.

        show_ticks : bool, default: True
            Whether to show the ticks.

        tick_label_offset : int, default: 2
            Offset between tick and label in pixels.

        label_color : ColorLike, optional
            Either a string, rgb list, or hex color string for
            label and title colors.

            .. warning::
                This is either white or black.

        tick_color : ColorLike, optional
            Either a string, rgb list, or hex color string for
            tick line colors.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the ruler.

        Examples
        --------
        >>> import pyvista as pv
        >>> cone = pv.Cone(height=2.0, radius=0.5)
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(cone)

        Measure x direction of cone and place ruler slightly below.

        >>> _ = plotter.add_ruler(
        ...     pointa=[cone.bounds[0], cone.bounds[2] - 0.1, 0.0],
        ...     pointb=[cone.bounds[1], cone.bounds[2] - 0.1, 0.0],
        ...     title="X Distance",
        ... )

        Measure y direction of cone and place ruler slightly to left.
        The title and labels are placed to the right of the ruler when
        traveling from ``pointa`` to ``pointb``.

        >>> _ = plotter.add_ruler(
        ...     pointa=[cone.bounds[0] - 0.1, cone.bounds[3], 0.0],
        ...     pointb=[cone.bounds[0] - 0.1, cone.bounds[2], 0.0],
        ...     flip_range=True,
        ...     title="Y Distance",
        ... )
        >>> plotter.enable_parallel_projection()
        >>> plotter.view_xy()
        >>> plotter.show()

        """
        label_color = Color(label_color, default_color=self._theme.font.color)
        tick_color = Color(tick_color, default_color=self._theme.font.color)

        ruler = _vtk.vtkAxisActor2D()

        ruler.GetPositionCoordinate().SetCoordinateSystemToWorld()
        ruler.GetPosition2Coordinate().SetCoordinateSystemToWorld()
        ruler.GetPositionCoordinate().SetReferenceCoordinate(None)
        ruler.GetPositionCoordinate().SetValue(pointa[0], pointa[1], pointa[2])
        ruler.GetPosition2Coordinate().SetValue(pointb[0], pointb[1], pointb[2])

        distance = np.linalg.norm(np.asarray(pointa) - np.asarray(pointb))
        if flip_range:
            ruler.SetRange(distance, 0)
        else:
            ruler.SetRange(0, distance)

        ruler.SetTitle(title)
        ruler.SetFontFactor(font_size_factor)
        ruler.SetLabelFactor(label_size_factor)
        ruler.SetNumberOfLabels(number_labels)
        ruler.SetLabelVisibility(show_labels)
        if label_format:
            ruler.SetLabelFormat(label_format)
        ruler.GetProperty().SetColor(*tick_color.int_rgb)
        if label_color != Color('white'):
            # This property turns black if set
            ruler.GetLabelTextProperty().SetColor(*label_color.int_rgb)
            ruler.GetTitleTextProperty().SetColor(*label_color.int_rgb)
        ruler.SetNumberOfMinorTicks(number_minor_ticks)
        ruler.SetTickVisibility(show_ticks)
        ruler.SetTickLength(tick_length)
        ruler.SetMinorTickLength(minor_tick_length)
        ruler.SetTickOffset(tick_label_offset)

        self.add_actor(ruler, reset_camera=True, pickable=False)
        return ruler

    def add_legend_scale(
        self,
        corner_offset_factor=2.0,
        bottom_border_offset=30,
        top_border_offset=30,
        left_border_offset=30,
        right_border_offset=30,
        bottom_axis_visibility=True,
        top_axis_visibility=True,
        left_axis_visibility=True,
        right_axis_visibility=True,
        legend_visibility=True,
        xy_label_mode=False,
        render=True,
        color=None,
        font_size_factor=0.6,
        label_size_factor=1.0,
        label_format=None,
        number_minor_ticks=0,
        tick_length=5,
        minor_tick_length=3,
        show_ticks=True,
        tick_label_offset=2,
    ):
        """Annotate the render window with scale and distance information.

        Its basic goal is to provide an indication of the scale of the scene.
        Four axes surrounding the render window indicate (in a variety of ways)
        the scale of what the camera is viewing. An option also exists for
        displaying a scale legend.

        Parameters
        ----------
        corner_offset_factor : float, default: 2.0
            The corner offset value.

        bottom_border_offset : int, default: 30
            Bottom border offset. Recommended value ``50``.

        top_border_offset : int, default: 30
            Top border offset. Recommended value ``50``.

        left_border_offset : int, default: 30
            Left border offset. Recommended value ``100``.

        right_border_offset : int, default: 30
            Right border offset. Recommended value ``100``.

        bottom_axis_visibility : bool, default: True
            Whether the bottom axis is visible.

        top_axis_visibility : bool, default: True
            Whether the top axis is visible.

        left_axis_visibility : bool, default: True
            Whether the left axis is visible.

        right_axis_visibility : bool, default: True
            Whether the right axis is visible.

        legend_visibility : bool, default: True
            Whether the legend scale is visible.

        xy_label_mode : bool, default: False
            The axes can be programmed either to display distance scales
            or x-y coordinate values. By default,
            the scales display a distance. However, if you know that the
            view is down the z-axis, the scales can be programmed to display
            x-y coordinate values.

        render : bool, default: True
            Whether to render when the actor is added.

        color : ColorLike, optional
            Either a string, rgb list, or hex color string for tick text
            and tick line colors.

            .. warning::
                The axis labels tend to be either white or black.

        font_size_factor : float, default: 0.6
            Factor to scale font size overall.

        label_size_factor : float, default: 1.0
            Factor to scale label size relative to title size.

        label_format : str, optional
            A printf style format for labels, e.g. ``'%E'``.
            See :ref:`old-string-formatting`.

        number_minor_ticks : int, default: 0
            Number of minor ticks between major ticks.

        tick_length : int, default: 5
            Length of ticks in pixels.

        minor_tick_length : int, default: 3
            Length of minor ticks in pixels.

        show_ticks : bool, default: True
            Whether to show the ticks.

        tick_label_offset : int, default: 2
            Offset between tick and label in pixels.

        Returns
        -------
        vtk.vtkActor
            The actor for the added ``vtkLegendScaleActor``.

        Warnings
        --------
        Please be aware that the axes and scale values are subject to perspective
        effects. The distances are computed in the focal plane of the camera. When
        there are large view angles (i.e., perspective projection), the computed
        distances may provide users the wrong sense of scale. These effects are not
        present when parallel projection is enabled.

        Examples
        --------
        >>> import pyvista as pv
        >>> cone = pv.Cone(height=2.0, radius=0.5)
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(cone)
        >>> _ = pl.add_legend_scale()
        >>> pl.show()

        """
        color = Color(color, default_color=self._theme.font.color)

        legend_scale = _vtk.vtkLegendScaleActor()
        legend_scale.SetCornerOffsetFactor(corner_offset_factor)
        legend_scale.SetLegendVisibility(legend_visibility)
        if xy_label_mode:
            legend_scale.SetLabelModeToXYCoordinates()
        else:
            legend_scale.SetLabelModeToDistance()
        legend_scale.SetBottomAxisVisibility(bottom_axis_visibility)
        legend_scale.SetBottomBorderOffset(bottom_border_offset)
        legend_scale.SetLeftAxisVisibility(left_axis_visibility)
        legend_scale.SetLeftBorderOffset(left_border_offset)
        legend_scale.SetRightAxisVisibility(right_axis_visibility)
        legend_scale.SetRightBorderOffset(right_border_offset)
        legend_scale.SetTopAxisVisibility(top_axis_visibility)
        legend_scale.SetTopBorderOffset(top_border_offset)

        for text in ['Label', 'Title']:
            prop = getattr(legend_scale, f'GetLegend{text}Property')()
            if color != Color('white'):
                # This property turns black if set
                prop.SetColor(*color.int_rgb)
            prop.SetFontSize(
                int(font_size_factor * 20)
            )  # hack to avoid multiple font size arguments

        for ax in ['Bottom', 'Left', 'Right', 'Top']:
            axis = getattr(legend_scale, f'Get{ax}Axis')()
            axis.GetProperty().SetColor(*color.int_rgb)
            if color != Color('white'):
                # This label property turns black if set
                axis.GetLabelTextProperty().SetColor(*color.int_rgb)
            axis.SetFontFactor(font_size_factor)
            axis.SetLabelFactor(label_size_factor)
            if label_format:
                axis.SetLabelFormat(label_format)
            axis.SetNumberOfMinorTicks(number_minor_ticks)
            axis.SetTickLength(tick_length)
            axis.SetMinorTickLength(minor_tick_length)
            axis.SetTickVisibility(show_ticks)
            axis.SetTickOffset(tick_label_offset)

        return self.add_actor(
            legend_scale,
            reset_camera=False,
            name='_vtkLegendScaleActor',
            culling=False,
            pickable=False,
            render=render,
        )


def _line_for_legend():
    """Create a simple line-like rectangle for the legend."""
    points = [
        [0, 0, 0],
        [0.4, 0, 0],
        [0.4, 0.07, 0],
        [0, 0.07, 0],
        [
            0.5,
            0,
            0,
        ],  # last point needed to expand the bounds of the PolyData to be rendered smaller
    ]
    legendface = pyvista.PolyData()
    legendface.points = np.array(points)
    legendface.faces = [4, 0, 1, 2, 3]
    return legendface


# pyvista/plotting/renderers.py

"""Organize Renderers for ``pyvista.Plotter``."""
import collections
from weakref import proxy

import numpy as np

import pyvista

from .background_renderer import BackgroundRenderer
from .renderer import Renderer


class Renderers:
    """Organize Renderers for ``pyvista.Plotter``."""

    def __init__(
        self,
        plotter,
        shape=(1, 1),
        splitting_position=None,
        row_weights=None,
        col_weights=None,
        groups=None,
        border=None,
        border_color='k',
        border_width=2.0,
    ):
        """Initialize renderers."""
        self._active_index = 0  # index of the active renderer
        self._plotter = proxy(plotter)
        self._renderers = []
        self._shadow_renderer = None

        # by default add border for multiple plots
        if border is None:
            if shape != (1, 1):
                border = True
            else:
                border = False

        self.groups = np.empty((0, 4), dtype=int)

        if isinstance(shape, str):
            if '|' in shape:
                n = int(shape.split('|')[0])
                m = int(shape.split('|')[1])
                rangen = reversed(range(n))
                rangem = reversed(range(m))
            else:
                m = int(shape.split('/')[0])
                n = int(shape.split('/')[1])
                rangen = range(n)
                rangem = range(m)

            if splitting_position is None:
                splitting_position = pyvista.global_theme.multi_rendering_splitting_position

            if splitting_position is None:
                if n >= m:
                    xsplit = m / (n + m)
                else:
                    xsplit = 1 - n / (n + m)
            else:
                xsplit = splitting_position

            for i in rangen:
                arenderer = Renderer(self._plotter, border, border_color, border_width)
                if '|' in shape:
                    arenderer.SetViewport(0, i / n, xsplit, (i + 1) / n)
                else:
                    arenderer.SetViewport(i / n, 0, (i + 1) / n, xsplit)
                self._renderers.append(arenderer)
            for i in rangem:
                arenderer = Renderer(self._plotter, border, border_color, border_width)
                if '|' in shape:
                    arenderer.SetViewport(xsplit, i / m, 1, (i + 1) / m)
                else:
                    arenderer.SetViewport(i / m, xsplit, (i + 1) / m, 1)
                self._renderers.append(arenderer)

            self._shape = (n + m,)
            self._render_idxs = np.arange(n + m)

        else:
            if not isinstance(shape, (np.ndarray, collections.abc.Sequence)):
                raise TypeError('"shape" should be a list, tuple or string descriptor')
            if len(shape) != 2:
                raise ValueError('"shape" must have length 2.')
            shape = np.asarray(shape)
            if not np.issubdtype(shape.dtype, np.integer) or (shape <= 0).any():
                raise ValueError('"shape" must contain only positive integers.')
            # always assign shape as a tuple
            self._shape = tuple(shape)
            self._render_idxs = np.empty(self._shape, dtype=int)
            # Check if row and col weights correspond to given shape,
            # or initialize them to defaults (equally weighted).

            # and convert to normalized offsets
            if row_weights is None:
                row_weights = np.ones(shape[0])
            if col_weights is None:
                col_weights = np.ones(shape[1])

            # also make flattening and abs explicit
            row_weights = np.abs(np.asanyarray(row_weights).ravel())
            col_weights = np.abs(np.asanyarray(col_weights).ravel())
            if row_weights.size != shape[0]:
                raise ValueError(
                    f'"row_weights" must have {shape[0]} items '
                    f'for {shape[0]} rows of subplots, not '
                    f'{row_weights.size}.'
                )
            if col_weights.size != shape[1]:
                raise ValueError(
                    f'"col_weights" must have {shape[1]} items '
                    f'for {shape[1]} columns of subplots, not '
                    f'{col_weights.size}.'
                )
            row_off = np.cumsum(row_weights) / np.sum(row_weights)
            row_off = 1 - np.concatenate(([0], row_off))
            col_off = np.cumsum(col_weights) / np.sum(col_weights)
            col_off = np.concatenate(([0], col_off))

            # Check and convert groups to internal format (Nx4 matrix
            # where every row contains the row and col index of the
            # top left cell)

            if groups is not None:
                if not isinstance(groups, collections.abc.Sequence):
                    raise TypeError(
                        f'"groups" should be a list or tuple, not {type(groups).__name__}.'
                    )
                for group in groups:
                    if not isinstance(group, collections.abc.Sequence):
                        raise TypeError(
                            'Each group entry should be a list or '
                            f'tuple, not {type(group).__name__}.'
                        )
                    if len(group) != 2:
                        raise ValueError('Each group entry must have length 2.')

                    rows = group[0]
                    if isinstance(rows, slice):
                        rows = np.arange(self.shape[0], dtype=int)[rows]
                    cols = group[1]
                    if isinstance(cols, slice):
                        cols = np.arange(self.shape[1], dtype=int)[cols]
                    # Get the normalized group, i.e. extract top left corner
                    # and bottom right corner from the given rows and cols
                    norm_group = [np.min(rows), np.min(cols), np.max(rows), np.max(cols)]
                    # Check for overlap with already defined groups:
                    for i in range(norm_group[0], norm_group[2] + 1):
                        for j in range(norm_group[1], norm_group[3] + 1):
                            if self.loc_to_group((i, j)) is not None:
                                raise ValueError(
                                    f'Groups cannot overlap. Overlap found at position {(i, j)}.'
                                )
                    self.groups = np.concatenate(
                        (self.groups, np.array([norm_group], dtype=int)), axis=0
                    )
            # Create subplot renderers
            for row in range(shape[0]):
                for col in range(shape[1]):
                    group = self.loc_to_group((row, col))
                    nb_rows = None
                    nb_cols = None
                    if group is not None:
                        if row == self.groups[group, 0] and col == self.groups[group, 1]:
                            # Only add renderer for first location of the group
                            nb_rows = 1 + self.groups[group, 2] - self.groups[group, 0]
                            nb_cols = 1 + self.groups[group, 3] - self.groups[group, 1]
                    else:
                        nb_rows = 1
                        nb_cols = 1
                    if nb_rows is not None:
                        renderer = Renderer(self._plotter, border, border_color, border_width)
                        x0 = col_off[col]
                        y0 = row_off[row + nb_rows]
                        x1 = col_off[col + nb_cols]
                        y1 = row_off[row]
                        renderer.SetViewport(x0, y0, x1, y1)
                        self._render_idxs[row, col] = len(self)
                        self._renderers.append(renderer)
                    else:
                        self._render_idxs[row, col] = self._render_idxs[
                            self.groups[group, 0], self.groups[group, 1]
                        ]

        # each render will also have an associated background renderer
        self._background_renderers = [None for _ in range(len(self))]

        # create a shadow renderer that lives on top of all others
        self._shadow_renderer = Renderer(self._plotter, border, border_color, border_width)
        self._shadow_renderer.SetViewport(0, 0, 1, 1)
        self._shadow_renderer.SetDraw(False)

    def loc_to_group(self, loc):
        """Return group id of the given location index or ``None`` if this location is not part of any group."""
        group_idxs = np.arange(self.groups.shape[0])
        index = (
            (loc[0] >= self.groups[:, 0])
            & (loc[0] <= self.groups[:, 2])
            & (loc[1] >= self.groups[:, 1])
            & (loc[1] <= self.groups[:, 3])
        )
        group = group_idxs[index]
        return None if group.size == 0 else group[0]

    def loc_to_index(self, loc):
        """Return index of the render window given a location index.

        Parameters
        ----------
        loc : int | sequence[int]
            Index of the renderer to add the actor to.  For example,
            ``loc=2`` or ``loc=(1, 1)``.

        Returns
        -------
        idx : int
            Index of the render window.

        """
        if isinstance(loc, (int, np.integer)):
            return loc
        elif isinstance(loc, (np.ndarray, collections.abc.Sequence)):
            if not len(loc) == 2:
                raise ValueError('"loc" must contain two items')
            index_row = loc[0]
            index_column = loc[1]
            if index_row < 0 or index_row >= self.shape[0]:
                raise IndexError(f'Row index is out of range ({self.shape[0]})')
            if index_column < 0 or index_column >= self.shape[1]:
                raise IndexError(f'Column index is out of range ({self.shape[1]})')
            return self._render_idxs[index_row, index_column]
        else:
            raise TypeError('"loc" must be an integer or a sequence.')

    def __getitem__(self, index):
        """Return a renderer based on an index."""
        return self._renderers[index]

    def __len__(self):
        """Return number of renderers."""
        return len(self._renderers)

    def __iter__(self):
        """Return a iterable of renderers."""
        yield from self._renderers

    @property
    def active_index(self):
        """Return the active index."""
        return self._active_index

    def index_to_loc(self, index):
        """Convert a 1D index location to the 2D location on the plotting grid."""
        if not isinstance(index, (int, np.integer)):
            raise TypeError('"index" must be a scalar integer.')
        if len(self.shape) == 1:
            return index
        args = np.argwhere(self._render_idxs == index)
        if len(args) < 1:
            raise IndexError(f'Index ({index}) is out of range.')
        return args[0]

    @property
    def active_renderer(self):
        """Return the active renderer."""
        return self._renderers[self._active_index]

    @property
    def shape(self):
        """Return the shape of the renderers."""
        return self._shape

    def set_active_renderer(self, index_row, index_column=None):
        """Set the index of the active renderer.

        Parameters
        ----------
        index_row : int
            Index of the subplot to activate along the rows.

        index_column : int, optional
            Index of the subplot to activate along the columns.

        """
        if len(self.shape) == 1:
            self._active_index = index_row
            return

        if index_row < 0 or index_row >= self.shape[0]:
            raise IndexError(f'Row index is out of range ({self.shape[0]})')
        if index_column < 0 or index_column >= self.shape[1]:
            raise IndexError(f'Column index is out of range ({self.shape[1]})')
        self._active_index = self.loc_to_index((index_row, index_column))

    def set_chart_interaction(self, interactive, toggle=False):
        """
        Set or toggle interaction with charts for the active renderer.

        Interaction with other charts in other renderers is disabled.
        Interaction with other charts in the active renderer is only disabled
        when ``toggle`` is ``False``.

        Parameters
        ----------
        interactive : bool | Chart | int | sequence[Chart] | sequence[int]
            Following parameter values are accepted:

            * A boolean to enable (``True``) or disable (``False``) interaction
              with all charts in the active renderer.
            * The chart or its index to enable interaction with. Interaction
              with multiple charts can be enabled by passing a list of charts
              or indices.

        toggle : bool, default: False
            Instead of enabling interaction with the provided chart(s), interaction
            with the provided chart(s) is toggled. Only applicable when ``interactive``
            is not a boolean.

        Returns
        -------
        list of Chart
            The list of all interactive charts for the active renderer.

        """
        interactive_scene, interactive_charts = None, []
        if self.active_renderer.has_charts:
            interactive_scene = self.active_renderer._charts._scene
            interactive_charts = self.active_renderer.set_chart_interaction(interactive, toggle)
        # Disable chart interaction for other renderers
        for renderer in self:
            if renderer is not self.active_renderer:
                renderer.set_chart_interaction(False)
        # Setup the context interactor style based on the resulting amount of interactive charts.
        self._plotter.iren._set_context_style(interactive_scene if interactive_charts else None)
        return interactive_charts

    def on_plotter_render(self):
        """Notify all renderers of explicit plotter render call."""
        for renderer in self:
            renderer.on_plotter_render()

    def deep_clean(self):
        """Clean all renderers."""
        # Do not remove the renderers on the clean
        for renderer in self:
            renderer.deep_clean()
        if self._shadow_renderer is not None:
            self._shadow_renderer.deep_clean()
        if hasattr(self, '_background_renderers'):
            for renderer in self._background_renderers:
                if renderer is not None:
                    renderer.deep_clean()

    def add_background_renderer(self, image_path, scale, as_global):
        """Add a background image to the renderers.

        Parameters
        ----------
        image_path : str
            Path to an image file.

        scale : float
            Scale the image larger or smaller relative to the size of
            the window.  For example, a scale size of 2 will make the
            largest dimension of the image twice as large as the
            largest dimension of the render window.  Defaults to 1.

        as_global : bool
            When multiple render windows are present, setting
            ``as_global=False`` will cause the background to only
            appear in one window.

        Returns
        -------
        pyvista.BackgroundRenderer
            Newly created background renderer.

        """
        # verify no render exists
        if as_global:
            for renderer in self:
                renderer.layer = 2
            view_port = None
        else:
            self.active_renderer.layer = 2
            view_port = self.active_renderer.GetViewport()

        renderer = BackgroundRenderer(self._plotter, image_path, scale, view_port)
        renderer.layer = 1
        self._background_renderers[self.active_index] = renderer
        return renderer

    @property
    def has_active_background_renderer(self):
        """Return ``True`` when Renderer has an active background renderer."""
        return self._background_renderers[self.active_index] is not None

    def clear_background_renderers(self):
        """Clear all background renderers."""
        for renderer in self._background_renderers:
            if renderer is not None:
                renderer.clear()

    def clear_actors(self):
        """Clear actors from all renderers."""
        for renderer in self:
            renderer.clear_actors()

    def clear(self):
        """Clear all renders."""
        for renderer in self:
            renderer.clear()
        self._shadow_renderer.clear()
        self.clear_background_renderers()

    def close(self):
        """Close all renderers."""
        for renderer in self:
            renderer.close()

        self._shadow_renderer.close()

        for renderer in self._background_renderers:
            if renderer is not None:
                renderer.close()

    def remove_all_lights(self):
        """Remove all lights from all renderers."""
        for renderer in self:
            renderer.remove_all_lights()

    @property
    def shadow_renderer(self):
        """Shadow renderer."""
        return self._shadow_renderer

    def set_background(self, color, top=None, all_renderers=True):
        """Set the background color.

        Parameters
        ----------
        color : ColorLike, optional
            Either a string, rgb list, or hex color string.  Defaults
            to current theme parameters.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        top : ColorLike, optional
            If given, this will enable a gradient background where the
            ``color`` argument is at the bottom and the color given in ``top``
            will be the color at the top of the renderer.

        all_renderers : bool, default: True
            If ``True``, applies to all renderers in subplots. If ``False``,
            then only applies to the active renderer.

        Examples
        --------
        Set the background color to black.

        >>> import pyvista
        >>> plotter = pyvista.Plotter()
        >>> plotter.set_background('black')
        >>> plotter.background_color
        Color(name='black', hex='#000000ff', opacity=255)
        >>> plotter.close()

        Set the background color at the bottom to black and white at
        the top.  Display a cone as well.

        >>> import pyvista
        >>> pl = pyvista.Plotter()
        >>> actor = pl.add_mesh(pyvista.Cone())
        >>> pl.set_background('black', top='white')
        >>> pl.show()

        """
        if all_renderers:
            for renderer in self:
                renderer.set_background(color, top=top)
            self._shadow_renderer.set_background(color)
        else:
            self.active_renderer.set_background(color, top=top)

    def set_color_cycler(self, color_cycler, all_renderers=True):
        """Set or reset the color cycler.

        This color cycler is iterated over by each sequential :class:`add_mesh() <pyvista.Plotter.add_mesh>`
        call to set the default color of the dataset being plotted.

        When setting, the value must be either a list of color-like objects,
        or a cycler of color-like objects. If the value passed is a single
        string, it must be one of:

            * ``'default'`` - Use the default color cycler (matches matplotlib's default)
            * ``'matplotlib`` - Dynamically get matplotlib's current theme's color cycler.
            * ``'all'`` - Cycle through all of the available colors in ``pyvista.plotting.colors.hexcolors``

        Setting to ``None`` will disable the use of the color cycler on this
        renderer.

        Parameters
        ----------
        color_cycler : str | cycler.Cycler | sequence[ColorLike]
            The colors to cycle through.

        all_renderers : bool, default: True
            If ``True``, applies to all renderers in subplots. If ``False``,
            then only applies to the active renderer.

        Examples
        --------
        Set the default color cycler to iterate through red, green, and blue.

        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> pl.set_color_cycler(['red', 'green', 'blue'])
        >>> _ = pl.add_mesh(pv.Cone(center=(0, 0, 0)))  # red
        >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))  # green
        >>> _ = pl.add_mesh(pv.Sphere(center=(1, 1, 0)))  # blue
        >>> _ = pl.add_mesh(pv.Cylinder(center=(0, 1, 0)))  # red again
        >>> pl.show()

        """
        if all_renderers:
            for renderer in self:
                renderer.set_color_cycler(color_cycler)
        else:
            self.active_renderer.set_color_cycler(color_cycler)

    def remove_background_image(self):
        """Remove the background image at the current renderer.

        Examples
        --------
        >>> import pyvista
        >>> from pyvista import examples
        >>> pl = pyvista.Plotter(shape=(1, 2))
        >>> pl.subplot(0, 0)
        >>> actor = pl.add_mesh(pyvista.Sphere())
        >>> pl.add_background_image(examples.mapfile, as_global=False)
        >>> pl.subplot(0, 1)
        >>> actor = pl.add_mesh(pyvista.Cube())
        >>> pl.add_background_image(examples.mapfile, as_global=False)
        >>> pl.remove_background_image()
        >>> pl.show()

        """
        renderer = self._background_renderers[self.active_index]
        if renderer is None:
            raise RuntimeError('No background image to remove at this subplot')
        renderer.deep_clean()
        self._background_renderers[self.active_index] = None

    def __del__(self):
        """Destructor."""
        self._shadow_renderer = None


# pyvista/plotting/scalar_bars.py

"""PyVista Scalar bar module."""
import weakref

import numpy as np

import pyvista
from pyvista import MAX_N_COLOR_BARS, _vtk

from .colors import Color
from .tools import parse_font_family


class ScalarBars:
    """Plotter Scalar Bars."""

    def __init__(self, plotter):
        """Initialize ScalarBars."""
        self._plotter = weakref.proxy(plotter)
        self._scalar_bar_ranges = {}
        self._scalar_bar_mappers = {}
        self._scalar_bar_actors = {}
        self._scalar_bar_widgets = {}

    def clear(self):
        """Remove all scalar bars and resets all scalar bar properties."""
        self._scalar_bar_ranges = {}
        self._scalar_bar_mappers = {}
        self._scalar_bar_actors = {}
        self._scalar_bar_widgets = {}

    def __repr__(self):
        """Nice representation of this class."""
        lines = []
        lines.append('Scalar Bar Title     Interactive')
        for title in self._scalar_bar_actors:
            interactive = title in self._scalar_bar_widgets
            title = f'"{title}"'
            lines.append(f'{title:20} {str(interactive):5}')
        return '\n'.join(lines)

    def _remove_mapper_from_plotter(self, actor, reset_camera=False, render=False):
        """Remove an actor's mapper from the given plotter's _scalar_bar_mappers.

        This ensures that when actors are removed, their corresponding
        scalar bars are removed.

        """
        try:
            mapper = actor.GetMapper()
        except AttributeError:
            return

        # NOTE: keys to list to prevent iterator changing during loop
        for name in list(self._scalar_bar_mappers):
            try:
                self._scalar_bar_mappers[name].remove(mapper)
            except ValueError:
                pass

            if not self._scalar_bar_mappers[name]:
                slot = self._plotter._scalar_bar_slot_lookup.pop(name, None)
                if slot is not None:
                    self._scalar_bar_mappers.pop(name)
                    self._scalar_bar_ranges.pop(name)
                    self._plotter.remove_actor(
                        self._scalar_bar_actors.pop(name), reset_camera=reset_camera, render=render
                    )
                    self._plotter._scalar_bar_slots.add(slot)
            return

    def remove_scalar_bar(self, title=None, render=True):
        """Remove a scalar bar.

        Parameters
        ----------
        title : str, optional
            Title of the scalar bar to remove.  Required if there is
            more than one scalar bar.

        render : bool, default: True
            Render upon scalar bar removal.  Set this to ``False`` to
            stop the render window from rendering when a scalar bar
            is removed.

        Examples
        --------
        Remove a scalar bar from a plotter.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere()
        >>> mesh['data'] = mesh.points[:, 2]
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(mesh, cmap='coolwarm')
        >>> pl.remove_scalar_bar()
        >>> pl.show()

        """
        if title is None:
            if len(self) > 1:
                titles = ', '.join(f'"{key}"' for key in self._scalar_bar_actors)
                raise ValueError(
                    'Multiple scalar bars found.  Pick title of the'
                    f'scalar bar from one of the following:\n{titles}'
                )
            else:
                title = list(self._scalar_bar_actors.keys())[0]

        actor = self._scalar_bar_actors.pop(title)
        self._plotter.remove_actor(actor, render=render)
        self._scalar_bar_ranges.pop(title)
        self._scalar_bar_mappers.pop(title)

        # add back in the scalar bar slot
        slot = self._plotter._scalar_bar_slot_lookup.pop(title, None)
        if slot is not None:
            self._plotter._scalar_bar_slots.add(slot)

        widget = self._scalar_bar_widgets.pop(title, None)
        if widget is not None:
            widget.SetEnabled(0)

    def __len__(self):
        """Return the number of scalar bar actors."""
        return len(self._scalar_bar_actors)

    def __getitem__(self, index):
        """Return a scalar bar actor."""
        return self._scalar_bar_actors[index]

    def keys(self):
        """Scalar bar keys."""
        return self._scalar_bar_actors.keys()

    def values(self):
        """Scalar bar values."""
        return self._scalar_bar_actors.values()

    def items(self):
        """Scalar bar items."""
        return self._scalar_bar_actors.items()

    def __contains__(self, key):
        """Check if a title is a valid actors."""
        return key in self._scalar_bar_actors

    def add_scalar_bar(
        self,
        title='',
        mapper=None,
        n_labels=5,
        italic=False,
        bold=False,
        title_font_size=None,
        label_font_size=None,
        color=None,
        font_family=None,
        shadow=False,
        width=None,
        height=None,
        position_x=None,
        position_y=None,
        vertical=None,
        interactive=None,
        fmt=None,
        use_opacity=True,
        outline=False,
        nan_annotation=False,
        below_label=None,
        above_label=None,
        background_color=None,
        n_colors=None,
        fill=False,
        render=False,
        theme=None,
    ):
        """Create scalar bar using the ranges as set by the last input mesh.

        Parameters
        ----------
        title : str, default: ""
            Title of the scalar bar.  Default is rendered as an empty title.

        mapper : vtkMapper, optional
            Mapper used for the scalar bar.  Defaults to the last
            mapper created by the plotter.

        n_labels : int, default: 5
            Number of labels to use for the scalar bar.

        italic : bool, default: False
            Italicises title and bar labels.

        bold : bool, default: False
            Bolds title and bar labels.

        title_font_size : float, optional
            Sets the size of the title font.  Defaults to ``None`` and is sized
            according to :attr:`pyvista.themes.DefaultTheme.font`.

        label_font_size : float, optional
            Sets the size of the title font.  Defaults to ``None`` and is sized
            according to :attr:`pyvista.themes.DefaultTheme.font`.

        color : ColorLike, optional
            Either a string, rgb list, or hex color string.  Default
            set by :attr:`pyvista.themes.DefaultTheme.font`.  Can be
            in one of the following formats:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        font_family : {'courier', 'times', 'arial'}
            Font family.  Default is set by
            :attr:`pyvista.themes.DefaultTheme.font`.

        shadow : bool, default: False
            Adds a black shadow to the text.

        width : float, optional
            The percentage (0 to 1) width of the window for the colorbar.
            Default set by
            :attr:`pyvista.themes.DefaultTheme.colorbar_vertical` or
            :attr:`pyvista.themes.DefaultTheme.colorbar_horizontal`
            depending on the value of ``vertical``.

        height : float, optional
            The percentage (0 to 1) height of the window for the
            colorbar.  Default set by
            :attr:`pyvista.themes.DefaultTheme.colorbar_vertical` or
            :attr:`pyvista.themes.DefaultTheme.colorbar_horizontal`
            depending on the value of ``vertical``.

        position_x : float, optional
            The percentage (0 to 1) along the windows's horizontal
            direction to place the bottom left corner of the colorbar.
            Default set by
            :attr:`pyvista.themes.DefaultTheme.colorbar_vertical` or
            :attr:`pyvista.themes.DefaultTheme.colorbar_horizontal`
            depending on the value of ``vertical``.

        position_y : float, optional
            The percentage (0 to 1) along the windows's vertical
            direction to place the bottom left corner of the colorbar.
            Default set by
            :attr:`pyvista.themes.DefaultTheme.colorbar_vertical` or
            :attr:`pyvista.themes.DefaultTheme.colorbar_horizontal`
            depending on the value of ``vertical``.

        vertical : bool, optional
            Use vertical or horizontal scalar bar.  Default set by
            :attr:`pyvista.themes.DefaultTheme.colorbar_orientation`.

        interactive : bool, optional
            Use a widget to control the size and location of the scalar bar.
            Default set by :attr:`pyvista.themes.DefaultTheme.interactive`.

        fmt : str, optional
            ``printf`` format for labels.
            Default set by :attr:`pyvista.themes.DefaultTheme.font`.

        use_opacity : bool, default: True
            Optionally display the opacity mapping on the scalar bar.

        outline : bool, default: False
            Optionally outline the scalar bar to make opacity mappings more
            obvious.

        nan_annotation : bool, default: False
            Annotate the NaN color.

        below_label : str, optional
            String annotation for values below the scalars range.

        above_label : str, optional
            String annotation for values above the scalars range.

        background_color : ColorLike, optional
            The color used for the background in RGB format.

        n_colors : int, optional
            The maximum number of color displayed in the scalar bar.

        fill : bool, default: False
            Draw a filled box behind the scalar bar with the
            ``background_color``.

        render : bool, default: False
            Force a render when True.

        theme : pyvista.themes.DefaultTheme, optional
            Plot-specific theme.  By default, calling from the
            ``Plotter``, will use the plotter theme.  Setting to
            ``None`` will use the global theme.

        Returns
        -------
        vtk.vtkScalarBarActor
            Scalar bar actor.

        Notes
        -----
        Setting ``title_font_size``, or ``label_font_size`` disables
        automatic font sizing for both the title and label.

        Examples
        --------
        Add a custom interactive scalar bar that is horizontal, has an
        outline, and has a custom formatting.

        >>> import pyvista as pv
        >>> sphere = pv.Sphere()
        >>> sphere['Data'] = sphere.points[:, 2]
        >>> plotter = pv.Plotter()
        >>> _ = plotter.add_mesh(sphere, show_scalar_bar=False)
        >>> _ = plotter.add_scalar_bar(
        ...     'Data',
        ...     interactive=True,
        ...     vertical=False,
        ...     title_font_size=35,
        ...     label_font_size=30,
        ...     outline=True,
        ...     fmt='%10.5f',
        ... )
        >>> plotter.show()

        """
        if mapper is None:
            raise ValueError('Mapper cannot be ``None`` when creating a scalar bar')

        if theme is None:
            theme = pyvista.global_theme

        if interactive is None:
            interactive = theme.interactive
        if font_family is None:
            font_family = theme.font.family
        if label_font_size is None:
            label_font_size = theme.font.label_size
        if title_font_size is None:
            title_font_size = theme.font.title_size
        if fmt is None:
            fmt = theme.font.fmt
        if vertical is None:
            if theme.colorbar_orientation.lower() == 'vertical':
                vertical = True

        # Automatically choose size if not specified
        if width is None:
            if vertical:
                width = theme.colorbar_vertical.width
            else:
                width = theme.colorbar_horizontal.width
        if height is None:
            if vertical:
                height = theme.colorbar_vertical.height
            else:
                height = theme.colorbar_horizontal.height

        # Check that this data hasn't already been plotted
        if title in list(self._scalar_bar_ranges.keys()):
            clim = list(self._scalar_bar_ranges[title])
            newrng = mapper.scalar_range
            oldmappers = self._scalar_bar_mappers[title]
            # get max for range and reset everything
            if newrng[0] < clim[0]:
                clim[0] = newrng[0]
            if newrng[1] > clim[1]:
                clim[1] = newrng[1]
            for mh in oldmappers:
                mh.scalar_range = clim[0], clim[1]
            mapper.scalar_range = clim[0], clim[1]
            self._scalar_bar_mappers[title].append(mapper)
            self._scalar_bar_ranges[title] = clim
            self._scalar_bar_actors[title].SetLookupTable(mapper.lookup_table)
            # Color bar already present and ready to be used so returning
            return

        # Automatically choose location if not specified
        if position_x is None or position_y is None:
            if not self._plotter._scalar_bar_slots:
                raise RuntimeError(f'Maximum number of color bars ({MAX_N_COLOR_BARS}) reached.')

            slot = min(self._plotter._scalar_bar_slots)
            self._plotter._scalar_bar_slots.remove(slot)
            self._plotter._scalar_bar_slot_lookup[title] = slot

            if position_x is None:
                if vertical:
                    position_x = theme.colorbar_vertical.position_x
                    position_x -= slot * (width + 0.2 * width)
                else:
                    position_x = theme.colorbar_horizontal.position_x

            if position_y is None:
                if vertical:
                    position_y = theme.colorbar_vertical.position_y
                else:
                    position_y = theme.colorbar_horizontal.position_y
                    position_y += slot * height

        # parse color
        color = Color(color, default_color=theme.font.color)

        # Create scalar bar
        scalar_bar = _vtk.vtkScalarBarActor()
        # self._scalar_bars.append(scalar_bar)

        if background_color is not None:
            background_color = np.array(Color(background_color).int_rgba)
            scalar_bar.GetBackgroundProperty().SetColor(background_color[0:3])

            if fill:
                scalar_bar.DrawBackgroundOn()

            lut = pyvista.LookupTable()
            lut.DeepCopy(mapper.lookup_table)
            ctable = _vtk.vtk_to_numpy(lut.GetTable())
            alphas = ctable[:, -1][:, np.newaxis] / 255.0
            use_table = ctable.copy()
            use_table[:, -1] = 255.0
            ctable = (use_table * alphas) + background_color * (1 - alphas)
            lut.SetTable(_vtk.numpy_to_vtk(ctable, array_type=_vtk.VTK_UNSIGNED_CHAR))
        else:
            lut = mapper.lookup_table

        scalar_bar.SetLookupTable(lut)
        if n_colors is None:
            # ensure the number of colors in the scalarbar's lookup table is at
            # least the number in the mapper
            n_colors = mapper.lookup_table.n_values

        scalar_bar.SetMaximumNumberOfColors(n_colors)

        if n_labels < 1:
            scalar_bar.SetDrawTickLabels(False)
        else:
            scalar_bar.SetDrawTickLabels(True)
            scalar_bar.SetNumberOfLabels(n_labels)

        if nan_annotation:
            scalar_bar.DrawNanAnnotationOn()

        if above_label is not None:
            scalar_bar.DrawAboveRangeSwatchOn()
            scalar_bar.SetAboveRangeAnnotation(above_label)
        elif lut.above_range_color:
            scalar_bar.DrawAboveRangeSwatchOn()
            scalar_bar.SetAboveRangeAnnotation('above')
        if below_label is not None:
            scalar_bar.DrawBelowRangeSwatchOn()
            scalar_bar.SetBelowRangeAnnotation(below_label)
        elif lut.below_range_color:
            scalar_bar.DrawBelowRangeSwatchOn()
            scalar_bar.SetBelowRangeAnnotation('below')

        # edit the size of the colorbar
        scalar_bar.SetHeight(height)
        scalar_bar.SetWidth(width)
        scalar_bar.SetPosition(position_x, position_y)

        if fmt is not None:
            scalar_bar.SetLabelFormat(fmt)

        if vertical:
            scalar_bar.SetOrientationToVertical()
        else:
            scalar_bar.SetOrientationToHorizontal()

        if label_font_size is not None or title_font_size is not None:
            scalar_bar.SetUnconstrainedFontSize(True)
            scalar_bar.SetAnnotationTextScaling(False)
        else:
            scalar_bar.SetAnnotationTextScaling(True)

        label_text = scalar_bar.GetLabelTextProperty()
        anno_text = scalar_bar.GetAnnotationTextProperty()
        label_text.SetColor(color.float_rgb)
        anno_text.SetColor(color.float_rgb)
        label_text.SetShadow(shadow)
        anno_text.SetShadow(shadow)

        # Set font
        label_text.SetFontFamily(parse_font_family(font_family))
        anno_text.SetFontFamily(parse_font_family(font_family))
        label_text.SetItalic(italic)
        anno_text.SetItalic(italic)
        label_text.SetBold(bold)
        anno_text.SetBold(bold)
        if label_font_size:
            label_text.SetFontSize(label_font_size)
            anno_text.SetFontSize(label_font_size)

        # Set properties
        self._scalar_bar_ranges[title] = mapper.scalar_range
        self._scalar_bar_mappers[title] = [mapper]

        scalar_bar.SetTitle(title)
        title_text = scalar_bar.GetTitleTextProperty()

        title_text.SetJustificationToCentered()

        title_text.SetItalic(italic)
        title_text.SetBold(bold)
        title_text.SetShadow(shadow)
        if title_font_size:
            title_text.SetFontSize(title_font_size)

        # Set font
        title_text.SetFontFamily(parse_font_family(font_family))

        # set color
        title_text.SetColor(color.float_rgb)

        self._scalar_bar_actors[title] = scalar_bar
        if interactive:
            scalar_widget = _vtk.vtkScalarBarWidget()
            scalar_widget.SetScalarBarActor(scalar_bar)
            scalar_widget.SetInteractor(self._plotter.iren.interactor)
            scalar_widget.SetEnabled(1)
            rep = scalar_widget.GetRepresentation()

            scalar_widget.On()
            if vertical is True or vertical is None:
                rep.SetOrientation(1)  # 0 = Horizontal, 1 = Vertical
            else:
                # y position determined empirically
                y = -position_y / 2 - height - scalar_bar.GetPosition()[1]
                rep.GetPositionCoordinate().SetValue(width, y)
                rep.GetPosition2Coordinate().SetValue(height, width)
                rep.SetOrientation(0)  # 0 = Horizontal, 1 = Vertical
            self._scalar_bar_widgets[title] = scalar_widget

        if use_opacity:
            scalar_bar.SetUseOpacity(True)

        if outline:
            scalar_bar.SetDrawFrame(True)
            frame_prop = scalar_bar.GetFrameProperty()
            frame_prop.SetColor(color.float_rgb)
        else:
            scalar_bar.SetDrawFrame(False)

        # finally, add to the actor and return the scalar bar
        self._plotter.add_actor(scalar_bar, reset_camera=False, pickable=False, render=render)

        return scalar_bar


# pyvista/plotting/theme.py

"""Here for backwards compatibility with pyvistaqt."""

from pyvista import rcParams  # noqa


# pyvista/plotting/tools.py

"""Module containing useful plotting tools."""

from enum import Enum
import os
import platform
from subprocess import PIPE, Popen, TimeoutExpired

import numpy as np

import pyvista
from pyvista import _vtk

from .colors import Color


class FONTS(Enum):
    """Font families available to PyVista."""

    arial = _vtk.VTK_ARIAL
    courier = _vtk.VTK_COURIER
    times = _vtk.VTK_TIMES


# Track render window support and plotting
SUPPORTS_OPENGL = None
SUPPORTS_PLOTTING = None


def supports_open_gl():
    """Return if the system supports OpenGL."""
    global SUPPORTS_OPENGL
    if SUPPORTS_OPENGL is None:
        ren_win = _vtk.vtkRenderWindow()
        SUPPORTS_OPENGL = bool(ren_win.SupportsOpenGL())
    return SUPPORTS_OPENGL


def _system_supports_plotting():
    """Check if the environment supports plotting on Windows, Linux, or Mac OS.

    Returns
    -------
    system_supports_plotting : bool
        ``True`` when system supports plotting.

    """
    if os.environ.get('ALLOW_PLOTTING', '').lower() == 'true':
        return True

    # Windows case
    if os.name == 'nt':
        # actually have to check here.  Somewhat expensive.
        return supports_open_gl()

    # mac case
    if platform.system() == 'Darwin':
        # check if finder available
        proc = Popen(["pgrep", "-qx", "Finder"], stdout=PIPE, stderr=PIPE, encoding="utf8")
        try:
            proc.communicate(timeout=10)
        except TimeoutExpired:
            return False
        if proc.returncode == 0:
            return True

        # display variable set, likely available
        return 'DISPLAY' in os.environ

    # Linux case
    try:
        proc = Popen(["xset", "-q"], stdout=PIPE, stderr=PIPE, encoding="utf8")
        proc.communicate(timeout=10)
        return proc.returncode == 0
    except (OSError, TimeoutExpired):
        return False


def system_supports_plotting():
    """Check if the environment supports plotting.

    Returns
    -------
    bool
        ``True`` when system supports plotting.

    """
    global SUPPORTS_PLOTTING
    if SUPPORTS_PLOTTING is None:
        SUPPORTS_PLOTTING = _system_supports_plotting()

    # always use the cached response
    return SUPPORTS_PLOTTING


def _update_axes_label_color(axes_actor, color=None):
    """Set the axes label color (internal helper)."""
    color = Color(color, default_color=pyvista.global_theme.font.color)
    if isinstance(axes_actor, _vtk.vtkAxesActor):
        prop_x = axes_actor.GetXAxisCaptionActor2D().GetCaptionTextProperty()
        prop_y = axes_actor.GetYAxisCaptionActor2D().GetCaptionTextProperty()
        prop_z = axes_actor.GetZAxisCaptionActor2D().GetCaptionTextProperty()
        for prop in [prop_x, prop_y, prop_z]:
            prop.SetColor(color.float_rgb)
            prop.SetShadow(False)
    elif isinstance(axes_actor, _vtk.vtkAnnotatedCubeActor):
        axes_actor.GetTextEdgesProperty().SetColor(color.float_rgb)


def create_axes_marker(
    label_color=None,
    x_color=None,
    y_color=None,
    z_color=None,
    xlabel='X',
    ylabel='Y',
    zlabel='Z',
    labels_off=False,
    line_width=2,
    cone_radius=0.4,
    shaft_length=0.8,
    tip_length=0.2,
    ambient=0.5,
    label_size=(0.25, 0.1),
):
    """Create an axis actor.

    Parameters
    ----------
    label_color : ColorLike, optional
        Color of the label text.

    x_color : ColorLike, optional
        Color of the x axis text.

    y_color : ColorLike, optional
        Color of the y axis text.

    z_color : ColorLike, optional
        Color of the z axis text.

    xlabel : str, default: "X"
        Text used for the x axis.

    ylabel : str, default: "Y"
        Text used for the y axis.

    zlabel : str, default: "Z"
        Text used for the z axis.

    labels_off : bool, default: False
        Enable or disable the text labels for the axes.

    line_width : float, default: 2
        The width of the marker lines.

    cone_radius : float, default: 0.4
        The radius of the axes arrow tips.

    shaft_length : float, default: 0.8
        The length of the axes arrow shafts.

    tip_length : float, default: 0.2
        Length of the tip.

    ambient : float, default: 0.5
        The ambient of the axes arrows. Value should be between 0 and 1.

    label_size : sequence[float], default: (0.25, 0.1)
        The width and height of the axes label actors. Values should be between
        0 and 1. For example ``(0.2, 0.1)``.

    Returns
    -------
    vtk.vtkAxesActor
        Axes actor.

    Examples
    --------
    Create the default axes marker.

    >>> import pyvista as pv
    >>> marker = pv.create_axes_marker()
    >>> pl = pv.Plotter()
    >>> _ = pl.add_actor(marker)
    >>> pl.show()

    Create an axes marker at the origin with custom colors and axis labels.

    >>> import pyvista as pv
    >>> marker = pv.create_axes_marker(
    ...     line_width=4,
    ...     ambient=0.0,
    ...     x_color="#378df0",
    ...     y_color="#ab2e5d",
    ...     z_color="#f7fb9a",
    ...     xlabel="X Axis",
    ...     ylabel="Y Axis",
    ...     zlabel="Z Axis",
    ...     label_size=(0.1, 0.1),
    ... )
    >>> pl = pv.Plotter()
    >>> _ = pl.add_actor(marker)
    >>> pl.show()

    """
    x_color = Color(x_color, default_color=pyvista.global_theme.axes.x_color)
    y_color = Color(y_color, default_color=pyvista.global_theme.axes.y_color)
    z_color = Color(z_color, default_color=pyvista.global_theme.axes.z_color)
    axes_actor = _vtk.vtkAxesActor()
    axes_actor.GetXAxisShaftProperty().SetColor(x_color.float_rgb)
    axes_actor.GetXAxisTipProperty().SetColor(x_color.float_rgb)
    axes_actor.GetYAxisShaftProperty().SetColor(y_color.float_rgb)
    axes_actor.GetYAxisTipProperty().SetColor(y_color.float_rgb)
    axes_actor.GetZAxisShaftProperty().SetColor(z_color.float_rgb)
    axes_actor.GetZAxisTipProperty().SetColor(z_color.float_rgb)
    # Set labels
    axes_actor.SetXAxisLabelText(xlabel)
    axes_actor.SetYAxisLabelText(ylabel)
    axes_actor.SetZAxisLabelText(zlabel)
    if labels_off:
        axes_actor.AxisLabelsOff()
    # Set Line width
    axes_actor.GetXAxisShaftProperty().SetLineWidth(line_width)
    axes_actor.GetYAxisShaftProperty().SetLineWidth(line_width)
    axes_actor.GetZAxisShaftProperty().SetLineWidth(line_width)

    axes_actor.SetConeRadius(cone_radius)
    axes_actor.SetNormalizedShaftLength([shaft_length] * 3)
    axes_actor.SetNormalizedTipLength([tip_length] * 3)
    axes_actor.GetXAxisShaftProperty().SetAmbient(ambient)
    axes_actor.GetYAxisShaftProperty().SetAmbient(ambient)
    axes_actor.GetZAxisShaftProperty().SetAmbient(ambient)
    axes_actor.GetXAxisTipProperty().SetAmbient(ambient)
    axes_actor.GetYAxisTipProperty().SetAmbient(ambient)
    axes_actor.GetZAxisTipProperty().SetAmbient(ambient)

    for label_actor in [
        axes_actor.GetXAxisCaptionActor2D(),
        axes_actor.GetYAxisCaptionActor2D(),
        axes_actor.GetZAxisCaptionActor2D(),
    ]:
        label_actor.SetWidth(label_size[0])
        label_actor.SetHeight(label_size[1])

    _update_axes_label_color(axes_actor, label_color)

    return axes_actor


def create_axes_orientation_box(
    line_width=1,
    text_scale=0.366667,
    edge_color='black',
    x_color=None,
    y_color=None,
    z_color=None,
    xlabel='X',
    ylabel='Y',
    zlabel='Z',
    x_face_color='red',
    y_face_color='green',
    z_face_color='blue',
    color_box=False,
    label_color=None,
    labels_off=False,
    opacity=0.5,
):
    """Create a Box axes orientation widget with labels.

    Parameters
    ----------
    line_width : float, optional
        The width of the marker lines.

    text_scale : float, optional
        Size of the text relative to the faces.

    edge_color : ColorLike, optional
        Color of the edges.

    x_color : ColorLike, optional
        Color of the x axis text.

    y_color : ColorLike, optional
        Color of the y axis text.

    z_color : ColorLike, optional
        Color of the z axis text.

    xlabel : str, optional
        Text used for the x axis.

    ylabel : str, optional
        Text used for the y axis.

    zlabel : str, optional
        Text used for the z axis.

    x_face_color : ColorLike, optional
        Color used for the x axis arrow.  Defaults to theme axes
        parameters.

    y_face_color : ColorLike, optional
        Color used for the y axis arrow.  Defaults to theme axes
        parameters.

    z_face_color : ColorLike, optional
        Color used for the z axis arrow.  Defaults to theme axes
        parameters.

    color_box : bool, optional
        Enable or disable the face colors.  Otherwise, box is white.

    label_color : ColorLike, optional
        Color of the labels.

    labels_off : bool, optional
        Enable or disable the text labels for the axes.

    opacity : float, optional
        Opacity in the range of ``[0, 1]`` of the orientation box.

    Returns
    -------
    vtk.vtkAnnotatedCubeActor
        Annotated cube actor.

    Examples
    --------
    Create and plot an orientation box

    >>> import pyvista
    >>> actor = pyvista.create_axes_orientation_box(
    ...     line_width=1,
    ...     text_scale=0.53,
    ...     edge_color='black',
    ...     x_color='k',
    ...     y_color=None,
    ...     z_color=None,
    ...     xlabel='X',
    ...     ylabel='Y',
    ...     zlabel='Z',
    ...     color_box=False,
    ...     labels_off=False,
    ...     opacity=1.0,
    ... )
    >>> pl = pyvista.Plotter()
    >>> _ = pl.add_actor(actor)
    >>> pl.show()

    """
    x_color = Color(x_color, default_color=pyvista.global_theme.axes.x_color)
    y_color = Color(y_color, default_color=pyvista.global_theme.axes.y_color)
    z_color = Color(z_color, default_color=pyvista.global_theme.axes.z_color)
    edge_color = Color(edge_color, default_color=pyvista.global_theme.edge_color)
    x_face_color = Color(x_face_color)
    y_face_color = Color(y_face_color)
    z_face_color = Color(z_face_color)
    axes_actor = _vtk.vtkAnnotatedCubeActor()
    axes_actor.SetFaceTextScale(text_scale)
    if xlabel is not None:
        axes_actor.SetXPlusFaceText(f"+{xlabel}")
        axes_actor.SetXMinusFaceText(f"-{xlabel}")
    if ylabel is not None:
        axes_actor.SetYPlusFaceText(f"+{ylabel}")
        axes_actor.SetYMinusFaceText(f"-{ylabel}")
    if zlabel is not None:
        axes_actor.SetZPlusFaceText(f"+{zlabel}")
        axes_actor.SetZMinusFaceText(f"-{zlabel}")
    axes_actor.SetFaceTextVisibility(not labels_off)
    axes_actor.SetTextEdgesVisibility(False)
    # axes_actor.GetTextEdgesProperty().SetColor(edge_color.float_rgb)
    # axes_actor.GetTextEdgesProperty().SetLineWidth(line_width)
    axes_actor.GetXPlusFaceProperty().SetColor(x_color.float_rgb)
    axes_actor.GetXMinusFaceProperty().SetColor(x_color.float_rgb)
    axes_actor.GetYPlusFaceProperty().SetColor(y_color.float_rgb)
    axes_actor.GetYMinusFaceProperty().SetColor(y_color.float_rgb)
    axes_actor.GetZPlusFaceProperty().SetColor(z_color.float_rgb)
    axes_actor.GetZMinusFaceProperty().SetColor(z_color.float_rgb)

    axes_actor.GetCubeProperty().SetOpacity(opacity)
    # axes_actor.GetCubeProperty().SetEdgeColor(edge_color.float_rgb)
    axes_actor.GetCubeProperty().SetEdgeVisibility(True)
    axes_actor.GetCubeProperty().BackfaceCullingOn()
    if opacity < 1.0:
        # Hide the text edges
        axes_actor.GetTextEdgesProperty().SetOpacity(0)

    if color_box:
        # Hide the cube so we can color each face
        axes_actor.GetCubeProperty().SetOpacity(0)
        axes_actor.GetCubeProperty().SetEdgeVisibility(False)

        cube = pyvista.Cube()
        cube.clear_data()  # remove normals
        face_colors = np.array(
            [
                x_face_color.int_rgb,
                x_face_color.int_rgb,
                y_face_color.int_rgb,
                y_face_color.int_rgb,
                z_face_color.int_rgb,
                z_face_color.int_rgb,
            ],
            np.uint8,
        )
        cube.cell_data['face_colors'] = face_colors

        cube_mapper = _vtk.vtkPolyDataMapper()
        cube_mapper.SetInputData(cube)
        cube_mapper.SetColorModeToDirectScalars()
        cube_mapper.Update()

        cube_actor = pyvista.Actor(mapper=cube_mapper)
        cube_actor.prop.culling = 'back'
        cube_actor.prop.opacity = opacity

        prop_assembly = _vtk.vtkPropAssembly()
        prop_assembly.AddPart(axes_actor)
        prop_assembly.AddPart(cube_actor)
        actor = prop_assembly
    else:
        actor = axes_actor

    _update_axes_label_color(actor, label_color)

    return actor


def normalize(x, minimum=None, maximum=None):
    """Normalize the given value between [minimum, maximum]."""
    if minimum is None:
        minimum = np.nanmin(x)
    if maximum is None:
        maximum = np.nanmax(x)
    return (x - minimum) / (maximum - minimum)


def opacity_transfer_function(mapping, n_colors, interpolate=True, kind='quadratic'):
    """Get the opacity transfer function for a mapping.

    These values will map on to a scalar bar range and thus the number of
    colors (``n_colors``) must correspond to the number of colors in the color
    mapping that these opacities are associated to.

    If interpolating, ``scipy.interpolate.interp1d`` is used if available,
    otherwise ``np.interp`` is used. The ``kind`` argument controls the kind of
    interpolation for ``interp1d``.

    This returns the opacity range from 0 to 255, where 0 is totally
    transparent and 255 is totally opaque.

    The equation to create the sigmoid mapping is: ``1 / (1 + exp(-x))`` where
    ``x`` is the range from ``-a`` to ``+a`` and ``a`` is the value given in
    the ``mapping`` string. Default is ``a=10`` for 'sigmoid' mapping.

    Parameters
    ----------
    mapping : list(float) or str
        The opacity mapping to use. Can be a ``str`` name of a predefined
        mapping including ``'linear'``, ``'geom'``, ``'sigmoid'``,
        ``'sigmoid_3-10'``. Append an ``'_r'`` to any of those names to
        reverse that mapping. This can also be a custom array/list of values
        that will be interpolated across the ``n_color`` range for user
        defined mappings.

    n_colors : int
        The amount of colors that the opacities must be mapped to.

    interpolate : bool
        Flag on whether or not to interpolate the opacity mapping for all
        colors.

    kind : str
        The interpolation kind if ``interpolate`` is ``True`` and ``scipy``
        is available. If ``scipy`` is not available, linear interpolation
        is always used. Options are:

        - ``'linear'``
        - ``'nearest'``
        - ``'zero'``
        - ``'slinear'``
        - ``'quadratic'``
        - ``'cubic'``
        - ``'previous'``
        - ``'next'``

    Returns
    -------
    numpy.ndarray
        Array of ``numpy.uint8`` values ``n_colors`` long containing the
        [0-255] opacity mapping values.

    Examples
    --------
    >>> import pyvista as pv
    >>> # Fetch the `sigmoid` mapping between 0 and 255
    >>> tf = pv.opacity_transfer_function("sigmoid", 256)
    >>> # Fetch the `geom_r` mapping between 0 and 1
    >>> tf = (
    ...     pv.opacity_transfer_function("geom_r", 256).astype(float)
    ...     / 255.0
    ... )
    >>> # Interpolate a user defined opacity mapping
    >>> opacity = [0, 0.2, 0.9, 0.6, 0.3]
    >>> tf = pv.opacity_transfer_function(opacity, 256)

    """
    sigmoid = lambda x: np.array(1 / (1 + np.exp(-x)) * 255, dtype=np.uint8)
    transfer_func = {
        'linear': np.linspace(0, 255, n_colors, dtype=np.uint8),
        'geom': np.geomspace(1e-6, 255, n_colors, dtype=np.uint8),
        'geom_r': np.geomspace(255, 1e-6, n_colors, dtype=np.uint8),
        'sigmoid': sigmoid(np.linspace(-10.0, 10.0, n_colors)),
        'sigmoid_1': sigmoid(np.linspace(-1.0, 1.0, n_colors)),
        'sigmoid_2': sigmoid(np.linspace(-2.0, 2.0, n_colors)),
        'sigmoid_3': sigmoid(np.linspace(-3.0, 3.0, n_colors)),
        'sigmoid_4': sigmoid(np.linspace(-4.0, 4.0, n_colors)),
        'sigmoid_5': sigmoid(np.linspace(-5.0, 5.0, n_colors)),
        'sigmoid_6': sigmoid(np.linspace(-6.0, 6.0, n_colors)),
        'sigmoid_7': sigmoid(np.linspace(-7.0, 7.0, n_colors)),
        'sigmoid_8': sigmoid(np.linspace(-8.0, 8.0, n_colors)),
        'sigmoid_9': sigmoid(np.linspace(-9.0, 9.0, n_colors)),
        'sigmoid_10': sigmoid(np.linspace(-10.0, 10.0, n_colors)),
    }
    transfer_func['linear_r'] = transfer_func['linear'][::-1]
    transfer_func['sigmoid_r'] = transfer_func['sigmoid'][::-1]
    for i in range(3, 11):
        k = f'sigmoid_{i}'
        rk = f'{k}_r'
        transfer_func[rk] = transfer_func[k][::-1]
    if isinstance(mapping, str):
        try:
            return transfer_func[mapping]
        except KeyError:
            raise ValueError(
                f'Opacity transfer function ({mapping}) unknown. '
                f'Valid options: {list(transfer_func.keys())}'
            ) from None
    elif isinstance(mapping, (np.ndarray, list, tuple)):
        mapping = np.array(mapping)
        if mapping.size == n_colors:
            # User could pass transfer function ready for lookup table
            pass
        elif mapping.size < n_colors:
            # User pass custom transfer function to be linearly interpolated
            if np.max(mapping) > 1.0 or np.min(mapping) < 0.0:
                mapping = normalize(mapping)
            # Interpolate transfer function to match lookup table
            xo = np.linspace(0, n_colors, len(mapping), dtype=np.int_)
            xx = np.linspace(0, n_colors, n_colors, dtype=np.int_)
            try:
                if not interpolate:
                    raise ValueError('No interpolation.')
                # Use a quadratic interp if scipy is available
                from scipy.interpolate import interp1d

                # quadratic has best/smoothest results
                f = interp1d(xo, mapping, kind=kind)
                vals = f(xx)
                vals[vals < 0] = 0.0
                vals[vals > 1.0] = 1.0
                mapping = (vals * 255.0).astype(np.uint8)

            except (ImportError, ValueError):
                # Otherwise use simple linear interp
                mapping = (np.interp(xx, xo, mapping) * 255).astype(np.uint8)
        else:
            raise RuntimeError(
                f'Transfer function cannot have more values than `n_colors`. This has {mapping.size} elements'
            )
        return mapping
    raise TypeError(f'Transfer function type ({type(mapping)}) not understood')


def parse_font_family(font_family):
    """Check font name."""
    font_family = font_family.lower()
    fonts = [font.name for font in FONTS]
    if font_family not in fonts:
        raise ValueError(f'Font must one of the following:\n{", ".join(fonts)}')
    return FONTS[font_family].value


def check_matplotlib_vtk_compatibility():
    """Check if VTK and Matplotlib versions are compatible.

    This is primarily geared towards checking if MathText rendering is
    supported. These are the version constraints for VTK and Matplotlib:

    * VTK <= 9.2.2 requires Matplotlib < 3.6
    * VTK > 9.2.2 requires Matplotlib >= 3.6

    Other version combinations of VTK and Matplotlib will work without
    errors, but some features (like MathText/LaTeX rendering) may
    silently fail.

    """
    import matplotlib

    mpl_vers = tuple(map(int, matplotlib.__version__.split('.')[:2]))
    if pyvista.vtk_version_info <= (9, 2, 2):
        if mpl_vers >= (3, 6):
            return False
        return True
    elif pyvista.vtk_version_info > (9, 2, 2):
        if mpl_vers >= (3, 6):
            return True
        return False  # pragma: no cover
    raise RuntimeError('Uncheckable versions.')  # pragma: no cover


def check_math_text_support():
    """Check if MathText and LaTeX symbols are supported."""
    return (
        _vtk.vtkMathTextFreeTypeTextRenderer().MathTextIsSupported()
        and check_matplotlib_vtk_compatibility()
    )


# pyvista/plotting/volume.py

"""PyVista volume module."""
from pyvista import _vtk

from ._property import Property
from .mapper import _BaseMapper
from .prop3d import Prop3D


class Volume(Prop3D, _vtk.vtkVolume):
    """Wrapper class for VTK volume.

    This class represents a volume in a rendered scene. It inherits
    functions related to the volume's position, orientation and origin
    from Prop3D.

    """

    def __init__(self):
        """Initialize volume."""
        super().__init__()

    @property
    def mapper(self) -> _BaseMapper:
        """Return or set the mapper of the volume.

        Examples
        --------
        Add a volume to a :class:`pyvista.Plotter` and get its mapper.

        >>> import pyvista as pv
        >>> vol = pv.UniformGrid(dimensions=(10, 10, 10))
        >>> vol['scalars'] = 255 - vol.z * 25
        >>> pl = pv.Plotter()
        >>> actor = pl.add_volume(vol)
        >>> actor.mapper.bounds
        (0.0, 9.0, 0.0, 9.0, 0.0, 9.0)
        """
        return self.GetMapper()

    @mapper.setter
    def mapper(self, obj):
        return self.SetMapper(obj)

    @property
    def prop(self):
        """Return or set the property of this actor.

        Examples
        --------
        Create an volume and get its properties.

        >>> import pyvista as pv
        >>> vol = pv.UniformGrid(dimensions=(10, 10, 10))
        >>> vol['scalars'] = 255 - vol.z * 25
        >>> pl = pv.Plotter()
        >>> actor = pl.add_volume(vol)
        >>> actor.prop.GetShade()
        0

        """
        return self.GetProperty()

    @prop.setter
    def prop(self, obj: Property):
        self.SetProperty(obj)


# pyvista/plotting/volume_property.py

"""This module contains the VolumeProperty class."""
import pyvista as pv
from pyvista import _vtk
from pyvista.utilities.misc import no_new_attr


@no_new_attr
class VolumeProperty(_vtk.vtkVolumeProperty):
    """Wrap the VTK class vtkVolumeProperty.

    This class is used to represent common properties associated with volume
    rendering. This includes properties for determining the type of
    interpolation to use when sampling a volume, the color of a volume, the
    scalar opacity of a volume, the gradient opacity of a volume, and the
    shading parameters of a volume.

    Parameters
    ----------
    lookup_table : pyvista.LookupTable, optional
        Lookup table to set the color and opacity transfer functions.

    interpolation_type : str, optional
        Value must be either ``'linear'`` or ``'nearest'``.

    ambient : float, optional
        When lighting is enabled, this is the amount of light in
        the range of 0 to 1 (default 0.0) that reaches the actor
        when not directed at the light source emitted from the
        viewer.

    diffuse : float, optional
        The diffuse lighting coefficient.

    specular : float, optional
        The specular lighting coefficient.

    specular_power : float, optional
        The specular power. Between 0.0 and 128.0.

    shade : bool, optional
        Enable or disable volume shading.  If shading is turned off, then the
        mapper for the volume will not perform shading calculations. If shading
        is turned on, the mapper may perform shading calculations - in some
        cases shading does not apply (for example, in a maximum intensity
        projection) and therefore shading will not be performed even if this
        flag is on. For a compositing type of mapper, turning shading off is
        generally the same as setting ``ambient=1``, ``diffuse=0``,
        ``specular=0``. Shading can be independently turned on/off per
        component.

    opacity_unit_distance : float, optional
        This is the unit distance on which the scalar opacity transfer function
        is defined. By default this is 1.0, meaning that over a distance of 1.0
        units, a given opacity (from the transfer function) is
        accumulated. This is adjusted for the actual sampling distance during
        rendering.

    Examples
    --------
    Create a sample dataset from perlin noise and apply a lookup table to the
    :class:`VolumeProperty`.

    >>> import pyvista as pv
    >>> noise = pv.perlin_noise(1, (1, 3, 5), (0, 0, 0))
    >>> grid = pv.sample_function(
    ...     noise, [0, 3.0, -0, 1.0, 0, 1.0], dim=(40, 40, 40)
    ... )
    >>> grid['scalars'] -= grid['scalars'].min()
    >>> grid['scalars'] *= 255 / grid['scalars'].max()
    >>> pl = pv.Plotter()
    >>> actor = pl.add_volume(grid, show_scalar_bar=False)
    >>> lut = pv.LookupTable(cmap='bwr')
    >>> lut.apply_opacity([1.0, 0.0, 0.0, 0.3, 0.0, 0.0, 0.0, 0.3])
    >>> actor.prop.apply_lookup_table(lut)
    >>> pl.show()


    """

    def __init__(
        self,
        lookup_table=None,
        interpolation_type=None,
        ambient=None,
        diffuse=None,
        specular=None,
        specular_power=None,
        shade=None,
        opacity_unit_distance=None,
    ):
        """Initialize the vtkVolumeProperty class."""
        super().__init__()
        if lookup_table is not None:
            self.apply_lookup_table(lookup_table)
        if interpolation_type is not None:
            self.interpolation_type = interpolation_type
        if ambient is not None:
            self.ambient = ambient
        if diffuse is not None:
            self.diffuse = diffuse
        if specular is not None:
            self.specular = specular
        if specular_power is not None:
            self.specular_power = specular_power
        if shade is not None:
            self.shade = shade
        if opacity_unit_distance is not None:
            self.opacity_unit_distance = opacity_unit_distance

    def apply_lookup_table(self, lookup_table: 'pv.LookupTable'):
        """Apply a lookup table to the volume property.

        Applies both the color and opacity of the lookup table as transfer
        functions.

        Parameters
        ----------
        lookup_table : pyvista.LookupTable, optional
            Lookup table to set the color and opacity transfer functions.

        Examples
        --------
        Plot perlin noise volumetrically using a custom lookup table.

        >>> import pyvista as pv
        >>> noise = pv.perlin_noise(1, (1, 3, 5), (0, 0, 0))
        >>> grid = pv.sample_function(
        ...     noise, [0, 3.0, -0, 1.0, 0, 1.0], dim=(40, 40, 40)
        ... )
        >>> grid['scalars'] -= grid['scalars'].min()
        >>> grid['scalars'] *= 255 / grid['scalars'].max()
        >>> pl = pv.Plotter()
        >>> actor = pl.add_volume(grid, show_scalar_bar=False)
        >>> lut = pv.LookupTable(cmap='bwr')
        >>> lut.apply_opacity([1.0, 0.0, 0.0, 0.3, 0.0, 0.0, 0.0, 0.3])
        >>> actor.prop.apply_lookup_table(lut)
        >>> pl.show()

        """
        if not isinstance(lookup_table, pv.LookupTable):
            raise TypeError('`lookup_table` must be a `pyvista.LookupTable`')

        self.SetColor(lookup_table.to_color_tf())
        self.SetScalarOpacity(lookup_table.to_opacity_tf())

    @property
    def interpolation_type(self) -> str:
        """Return or set the interpolation type.

        Value must be either ``'linear'`` or ``'nearest'``.

        Examples
        --------
        Create a sample :class:`pyvista.UniformGrid` dataset.

        >>> import numpy as np
        >>> import pyvista as pv
        >>> n = 21
        >>> c = -(n - 1) / 2
        >>> vol = pv.UniformGrid(dimensions=(n, n, n), origin=(c, c, c))
        >>> scalars = np.linalg.norm(vol.points, axis=1)
        >>> scalars *= 255 / scalars.max()
        >>> vol['scalars'] = scalars

        Demonstrate nearest (default) interpolation.

        >>> pl = pv.Plotter()
        >>> actor = pl.add_volume(
        ...     vol,
        ...     show_scalar_bar=False,
        ...     opacity=[0.3, 0.0, 0.05, 0.0, 0.0, 0.0, 1.0, 0.0],
        ...     cmap='plasma',
        ... )
        >>> actor.prop.interpolation_type = 'nearest'
        >>> pl.show()

        Demonstrate linear interpolation.

        >>> pl = pv.Plotter()
        >>> actor = pl.add_volume(
        ...     vol,
        ...     show_scalar_bar=False,
        ...     opacity=[0.3, 0.0, 0.05, 0.0, 0.0, 0.0, 1.0, 0.0],
        ...     cmap='plasma',
        ... )
        >>> actor.prop.interpolation_type = 'linear'
        >>> pl.show()

        """
        return self.GetInterpolationTypeAsString().split()[0].lower()

    @interpolation_type.setter
    def interpolation_type(self, value: str):
        if value == 'linear':
            self.SetInterpolationTypeToLinear()
        elif value == 'nearest':
            self.SetInterpolationTypeToNearest()
        else:
            raise ValueError('`interpolation_type` must be either "linear" or "nearest"')

    @property
    def opacity_unit_distance(self) -> float:
        """Return or set the opacity unit distance.

        This is the unit distance on which the scalar opacity transfer function
        is defined.

        By default this is 1.0, meaning that over a distance of 1.0 units, a
        given opacity (from the transfer function) is accumulated. This is
        adjusted for the actual sampling distance during rendering.
        """
        return self.GetScalarOpacityUnitDistance()

    @opacity_unit_distance.setter
    def opacity_unit_distance(self, value: float):
        self.SetScalarOpacityUnitDistance(value)

    @property
    def shade(self) -> bool:
        """Return or set shading of a volume.

        If shading is turned off, then the mapper for the volume will not
        perform shading calculations. If shading is turned on, the mapper may
        perform shading calculations - in some cases shading does not apply
        (for example, in a maximum intensity projection) and therefore shading
        will not be performed even if this flag is on. For a compositing type
        of mapper, turning shading off is generally the same as setting
        ``ambient=1``, ``diffuse=0``, ``specular=0``. Shading can be
        independently turned on/off per component.

        """
        return bool(self.GetShade())

    @shade.setter
    def shade(self, value: bool):
        self.SetShade(value)

    @property
    def independent_components(self) -> bool:
        """Return or set independent components.

        If ``False``, then you must have either 2 or 4 component data.
        For 2 component data, the first is passed through the
        first color transfer function and the second component is passed
        through the first scalar opacity (and gradient opacity) transfer
        function. Normals will be generated off of the second component. When
        using gradient based opacity modulation, the gradients are computed off
        of the second component.

        For 4 component data, the first three will directly represent RGB (no
        lookup table). The fourth component will be passed through the first
        scalar opacity transfer function for opacity and first gradient opacity
        transfer function for gradient based opacity modulation. Normals will
        be generated from the fourth component. When using gradient based
        opacity modulation, the gradients are computed off of the fourth
        component.
        """
        return bool(self.GetIndependentComponents())

    @independent_components.setter
    def independent_components(self, value: bool):
        self.SetIndependentComponents(value)

    @property
    def ambient(self) -> float:
        """Return or set ambient lighting coefficient.

        This is the amount of light in the range of 0 to 1 (default 0.0) that
        reaches the actor when not directed at the light source emitted from
        the viewer.

        Changing attribute has no effect unless :attr:`VolumeProperty.shade` is
        set to ``True``.

        """
        return self.GetAmbient()

    @ambient.setter
    def ambient(self, value: float):
        self.SetAmbient(value)

    @property
    def diffuse(self) -> float:
        """Return or set the diffuse lighting coefficient.

        This is the scattering of light by reflection or transmission. Diffuse
        reflection results when light strikes an irregular surface such as a
        frosted window or the surface of a frosted or coated light bulb.

        Changing attribute has no effect unless :attr:`VolumeProperty.shade` is
        set to ``True``.

        """
        return self.GetDiffuse()

    @diffuse.setter
    def diffuse(self, value: float):
        self.SetDiffuse(value)

    @property
    def specular(self) -> float:
        """Return or set specular.

        Default 0.0

        Specular lighting simulates the bright spot of a light that appears on
        shiny objects.

        Changing attribute has no effect unless :attr:`VolumeProperty.shade` is
        set to ``True``.

        """
        return self.GetSpecular()

    @specular.setter
    def specular(self, value: float):
        self.SetSpecular(value)

    @property
    def specular_power(self) -> float:
        """Return or set specular power.

        The specular power. Between 0.0 and 128.0. Default 10.0

        """
        return self.GetSpecularPower()

    @specular_power.setter
    def specular_power(self, value: float):
        self.SetSpecularPower(value)

    def copy(self) -> 'VolumeProperty':
        """Create a deep copy of this property.

        Returns
        -------
        pyvista.plotting.volume_property.VolumeProperty
            Deep copy of this property.

        """
        new_prop = VolumeProperty()
        new_prop.DeepCopy(self)
        return new_prop

    def __repr__(self):
        """Representation of this property."""
        props = [
            f'{type(self).__name__} ({hex(id(self))})',
        ]

        for attr in dir(self):
            if not attr.startswith('_') and attr[0].islower():
                name = ' '.join(attr.split('_')).capitalize() + ':'
                value = getattr(self, attr)
                if callable(value):
                    continue
                if isinstance(value, str):
                    value = f'"{value}"'
                props.append(f'  {name:28s} {value}')

        return '\n'.join(props)


# pyvista/plotting/widgets.py

"""Module dedicated to widgets."""

import numpy as np

import pyvista
from pyvista import _vtk
from pyvista.utilities import (
    NORMALS,
    assert_empty_kwargs,
    generate_plane,
    get_array,
    get_array_association,
    try_callback,
)
from pyvista.utilities.algorithms import (
    add_ids_algorithm,
    algorithm_to_mesh_handler,
    crinkle_algorithm,
    outline_algorithm,
    pointset_to_polydata_algorithm,
    set_algorithm_input,
)

from .colors import Color


def _parse_interaction_event(interaction_event):
    """Parse the interaction event.

    Parameters
    ----------
    interaction_event : vtk.vtkCommand.EventIds, str, optional
        The VTK interaction event to use for triggering the callback. Accepts
        either the strings ``'start'``, ``'end'``, ``'always'`` or a
        ``vtk.vtkCommand.EventIds``.

    Returns
    -------
    vtk.vtkCommand.EventIds
        VTK Event type.

    """
    if interaction_event == 'start':
        interaction_event = _vtk.vtkCommand.StartInteractionEvent
    elif interaction_event == 'end':
        interaction_event = _vtk.vtkCommand.EndInteractionEvent
    elif interaction_event == 'always':
        interaction_event = _vtk.vtkCommand.InteractionEvent
    elif isinstance(interaction_event, str):
        raise ValueError(
            "Expected value for `interaction_event` is 'start', "
            f"'end', or 'always'. {interaction_event} was given."
        )
    elif not isinstance(interaction_event, _vtk.vtkCommand.EventIds):
        raise TypeError(
            "Expected type for `interaction_event` is either a str "
            "or an instance of `vtk.vtkCommand.EventIds`."
            f" ({type(interaction_event)}) was given."
        )
    return interaction_event


class WidgetHelper:
    """An internal class to manage widgets.

    It also manages and other helper methods involving widgets.

    """

    def __init__(self, *args, **kwargs):
        """Initialize widget helper."""
        super().__init__(*args, **kwargs)
        self.camera_widgets = []
        self.box_widgets = []
        self.box_clipped_meshes = []
        self.plane_widgets = []
        self.plane_clipped_meshes = []
        self.plane_sliced_meshes = []
        self.line_widgets = []
        self.slider_widgets = []
        self.threshold_meshes = []
        self.isovalue_meshes = []
        self.spline_widgets = []
        self.spline_sliced_meshes = []
        self.sphere_widgets = []
        self.button_widgets = []

    def add_box_widget(
        self,
        callback,
        bounds=None,
        factor=1.25,
        rotation_enabled=True,
        color=None,
        use_planes=False,
        outline_translation=True,
        pass_widget=False,
        interaction_event='end',
    ):
        """Add a box widget to the scene.

        This is useless without a callback function. You can pass a
        callable function that takes a single argument, the PolyData
        box output from this widget, and performs a task with that
        box.

        Parameters
        ----------
        callback : callable
            The method called every time the box is updated. This has
            two options: Take a single argument, the ``PolyData`` box
            (default) or if ``use_planes=True``, then it takes a
            single argument of the plane collection as a ``vtkPlanes``
            object.

        bounds : tuple(float)
            Length 6 tuple of the bounding box where the widget is
            placed.

        factor : float, optional
            An inflation factor to expand on the bounds when placing.

        rotation_enabled : bool, optional
            If ``False``, the box widget cannot be rotated and is
            strictly orthogonal to the Cartesian axes.

        color : ColorLike, optional
            Either a string, rgb sequence, or hex color string.
            Defaults to :attr:`pyvista.global_theme.font.color
            <pyvista.themes._Font.color>`.

        use_planes : bool, optional
            Changes the arguments passed to the callback to the planes
            that make up the box.

        outline_translation : bool, optional
            If ``False``, the box widget cannot be translated and is
            strictly placed at the given bounds.

        pass_widget : bool, optional
            If ``True``, the widget will be passed as the last
            argument of the callback.

        interaction_event : vtk.vtkCommand.EventIds, str, optional
            The VTK interaction event to use for triggering the
            callback. Accepts either the strings ``'start'``, ``'end'``,
            ``'always'`` or a ``vtk.vtkCommand.EventIds``.

            .. versionchanged:: 0.38.0
               Now accepts either strings or ``vtk.vtkCommand.EventIds``.

        Returns
        -------
        vtk.vtkBoxWidget
            Box widget.

        Examples
        --------
        Shows an interactive clip box.

        >>> import pyvista as pv
        >>> mesh = pv.ParametricConicSpiral()
        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh_clip_box(mesh, color='white')
        >>> pl.show()

        For a full example see :ref:`box_widget_example`.

        """
        interaction_event = _parse_interaction_event(interaction_event)

        if bounds is None:
            bounds = self.bounds

        def _the_callback(box_widget, event_id):
            the_box = pyvista.PolyData()
            box_widget.GetPolyData(the_box)
            planes = _vtk.vtkPlanes()
            box_widget.GetPlanes(planes)
            if callable(callback):
                if use_planes:
                    args = [planes]
                else:
                    args = [the_box]
                if pass_widget:
                    args.append(box_widget)
                try_callback(callback, *args)
            return

        box_widget = _vtk.vtkBoxWidget()
        box_widget.GetOutlineProperty().SetColor(
            Color(color, default_color=pyvista.global_theme.font.color).float_rgb
        )
        box_widget.SetInteractor(self.iren.interactor)
        box_widget.SetCurrentRenderer(self.renderer)
        box_widget.SetPlaceFactor(factor)
        box_widget.SetRotationEnabled(rotation_enabled)
        box_widget.SetTranslationEnabled(outline_translation)
        box_widget.PlaceWidget(bounds)
        box_widget.On()
        box_widget.AddObserver(interaction_event, _the_callback)
        _the_callback(box_widget, None)

        self.box_widgets.append(box_widget)
        return box_widget

    def clear_box_widgets(self):
        """Remove all of the box widgets."""
        self.box_widgets.clear()

    def add_mesh_clip_box(
        self,
        mesh,
        invert=False,
        rotation_enabled=True,
        widget_color=None,
        outline_translation=True,
        merge_points=True,
        crinkle=False,
        interaction_event='end',
        **kwargs,
    ):
        """Clip a mesh using a box widget.

        Add a mesh to the scene with a box widget that is used to clip
        the mesh interactively.

        The clipped mesh is saved to the ``.box_clipped_meshes`` attribute on
        the plotter.

        Parameters
        ----------
        mesh : pyvista.DataSet or vtk.vtkAlgorithm
            The input dataset to add to the scene and clip or algorithm that
            produces said mesh.

        invert : bool, optional
            Flag on whether to flip/invert the clip.

        rotation_enabled : bool, optional
            If ``False``, the box widget cannot be rotated and is strictly
            orthogonal to the cartesian axes.

        widget_color : ColorLike, optional
            Color of the widget.  Either a string, RGB sequence, or
            hex color string.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        outline_translation : bool, optional
            If ``False``, the plane widget cannot be translated and is
            strictly placed at the given bounds.

        merge_points : bool, optional
            If ``True`` (default), coinciding points of independently
            defined mesh elements will be merged.

        crinkle : bool, optional
            Crinkle the clip by extracting the entire cells along the clip.

        interaction_event : vtk.vtkCommand.EventIds, str, optional
            The VTK interaction event to use for triggering the
            callback. Accepts either the strings ``'start'``, ``'end'``,
            ``'always'`` or a ``vtk.vtkCommand.EventIds``.

            .. versionchanged:: 0.38.0
               Changed from ``event_type`` to ``interaction_event`` and now
               accepts either strings and ``vtk.vtkCommand.EventIds``.

        **kwargs : dict, optional
            All additional keyword arguments are passed to
            :func:`Plotter.add_mesh` to control how the mesh is
            displayed.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the mesh.

        """
        from pyvista.core.filters import _get_output  # avoids circular import

        mesh, algo = algorithm_to_mesh_handler(
            add_ids_algorithm(mesh, point_ids=False, cell_ids=True)
        )

        name = kwargs.get('name', mesh.memory_address)
        rng = mesh.get_data_range(kwargs.get('scalars', None))
        kwargs.setdefault('clim', kwargs.pop('rng', rng))
        mesh.set_active_scalars(kwargs.get('scalars', mesh.active_scalars_name))

        self.add_mesh(outline_algorithm(algo), name=f"{name}-outline", opacity=0.0)

        port = 1 if invert else 0

        clipper = _vtk.vtkBoxClipDataSet()
        if not merge_points:
            # vtkBoxClipDataSet uses vtkMergePoints by default
            clipper.SetLocator(_vtk.vtkNonMergingPointLocator())
        set_algorithm_input(clipper, algo)
        clipper.GenerateClippedOutputOn()

        if crinkle:
            crinkler = crinkle_algorithm(clipper.GetOutputPort(port), algo)
            box_clipped_mesh = _get_output(crinkler)
        else:
            box_clipped_mesh = _get_output(clipper, oport=port)

        self.box_clipped_meshes.append(box_clipped_mesh)

        def callback(planes):
            bounds = []
            for i in range(planes.GetNumberOfPlanes()):
                plane = planes.GetPlane(i)
                bounds.append(plane.GetNormal())
                bounds.append(plane.GetOrigin())

            clipper.SetBoxClip(*bounds)
            clipper.Update()
            if crinkle:
                clipped = pyvista.wrap(crinkler.GetOutputDataObject(0))
            else:
                clipped = _get_output(clipper, oport=port)
            box_clipped_mesh.shallow_copy(clipped)

        self.add_box_widget(
            callback=callback,
            bounds=mesh.bounds,
            factor=1.25,
            rotation_enabled=rotation_enabled,
            use_planes=True,
            color=widget_color,
            outline_translation=outline_translation,
            interaction_event=interaction_event,
        )

        if crinkle:
            return self.add_mesh(crinkler, reset_camera=False, **kwargs)
        return self.add_mesh(clipper.GetOutputPort(port), reset_camera=False, **kwargs)

    def add_plane_widget(
        self,
        callback,
        normal='x',
        origin=None,
        bounds=None,
        factor=1.25,
        color=None,
        assign_to_axis=None,
        tubing=False,
        outline_translation=False,
        origin_translation=True,
        implicit=True,
        pass_widget=False,
        test_callback=True,
        normal_rotation=True,
        interaction_event='end',
    ):
        """Add a plane widget to the scene.

        This is useless without a callback function. You can pass a
        callable function that takes two arguments, the normal and
        origin of the plane in that order output from this widget, and
        performs a task with that plane.

        Parameters
        ----------
        callback : callable
            The method called every time the plane is updated. Takes
            two arguments, the normal and origin of the plane in that
            order.

        normal : str or tuple(float)
            The starting normal vector of the plane.

        origin : tuple(float)
            The starting coordinate of the center of the plane.

        bounds : tuple(float)
            Length 6 tuple of the bounding box where the widget is placed.

        factor : float, optional
            An inflation factor to expand on the bounds when placing.

        color : ColorLike, optional
            Either a string, rgb list, or hex color string.

        assign_to_axis : str or int, optional
            Assign the normal of the plane to be parallel with a given
            axis: options are ``(0, 'x')``, ``(1, 'y')``, or ``(2,
            'z')``.

        tubing : bool, optional
            When using an implicit plane wiget, this controls whether
            or not tubing is shown around the plane's boundaries.

        outline_translation : bool, optional
            If ``False``, the plane widget cannot be translated and is
            strictly placed at the given bounds. Only valid when using
            an implicit plane.

        origin_translation : bool, optional
            If ``False``, the plane widget cannot be translated by its
            origin and is strictly placed at the given origin. Only
            valid when using an implicit plane.

        implicit : bool, optional
            When ``True``, a ``vtkImplicitPlaneWidget`` is used and
            when ``False``, a ``vtkPlaneWidget`` is used.

        pass_widget : bool, optional
            If ``True``, the widget will be passed as the last
            argument of the callback.

        test_callback : bool, optional
            If ``True``, run the callback function after the widget is
            created.

        normal_rotation : bool, optional
            Set the opacity of the normal vector arrow to 0 such that
            it is effectively disabled. This prevents the user from
            rotating the normal. This is forced to ``False`` when
            ``assign_to_axis`` is set.

        interaction_event : vtk.vtkCommand.EventIds, str, optional
            The VTK interaction event to use for triggering the
            callback. Accepts either the strings ``'start'``, ``'end'``,
            ``'always'`` or a ``vtk.vtkCommand.EventIds``.

            .. versionchanged:: 0.38.0
               Now accepts either strings and ``vtk.vtkCommand.EventIds``.

        Returns
        -------
        vtk.vtkImplicitPlaneWidget or vtk.vtkPlaneWidget
            Plane widget.

        """
        interaction_event = _parse_interaction_event(interaction_event)

        if origin is None:
            origin = self.center
        if bounds is None:
            bounds = self.bounds

        if isinstance(normal, str):
            normal = NORMALS[normal.lower()]

        color = Color(color, default_color=pyvista.global_theme.font.color)

        if assign_to_axis:
            normal_rotation = False

        def _the_callback(widget, event_id):
            the_plane = _vtk.vtkPlane()
            widget.GetPlane(the_plane)
            normal = the_plane.GetNormal()
            origin = the_plane.GetOrigin()
            if callable(callback):
                if pass_widget:
                    try_callback(callback, normal, origin, widget)
                else:
                    try_callback(callback, normal, origin)
            return

        if implicit:
            plane_widget = _vtk.vtkImplicitPlaneWidget()
            plane_widget.GetNormalProperty().SetColor(color.float_rgb)
            plane_widget.GetOutlineProperty().SetColor(color.float_rgb)
            plane_widget.GetOutlineProperty().SetColor(color.float_rgb)
            plane_widget.GetOutlineProperty().SetOpacity(color.opacity)
            plane_widget.SetTubing(tubing)
            plane_widget.SetOutlineTranslation(outline_translation)
            plane_widget.SetOriginTranslation(origin_translation)

            _start_interact = lambda plane_widget, event: plane_widget.SetDrawPlane(True)
            _stop_interact = lambda plane_widget, event: plane_widget.SetDrawPlane(False)

            plane_widget.SetDrawPlane(False)
            plane_widget.AddObserver(_vtk.vtkCommand.StartInteractionEvent, _start_interact)
            plane_widget.AddObserver(_vtk.vtkCommand.EndInteractionEvent, _stop_interact)
            plane_widget.SetPlaceFactor(factor)
            plane_widget.PlaceWidget(bounds)
            plane_widget.SetOrigin(origin)

            if not normal_rotation:
                plane_widget.GetNormalProperty().SetOpacity(0)

        else:
            # Position of the small plane
            source = _vtk.vtkPlaneSource()
            source.SetNormal(normal)
            source.SetCenter(origin)
            source.SetPoint1(
                origin[0] + (bounds[1] - bounds[0]) * 0.01,
                origin[1] - (bounds[3] - bounds[2]) * 0.01,
                origin[2],
            )
            source.SetPoint2(
                origin[0] - (bounds[1] - bounds[0]) * 0.01,
                origin[1] + (bounds[3] - bounds[2]) * 0.01,
                origin[2],
            )
            source.Update()
            plane_widget = _vtk.vtkPlaneWidget()
            plane_widget.SetHandleSize(0.01)
            # Position of the widget
            plane_widget.SetInputData(source.GetOutput())
            plane_widget.SetRepresentationToOutline()
            plane_widget.SetPlaceFactor(factor)
            plane_widget.PlaceWidget(bounds)
            plane_widget.SetCenter(origin)  # Necessary
            plane_widget.GetPlaneProperty().SetColor(color.float_rgb)  # self.C_LOT[fn])
            plane_widget.GetHandleProperty().SetColor(color.float_rgb)

            if not normal_rotation:
                plane_widget.GetHandleProperty().SetOpacity(0)

        plane_widget.GetPlaneProperty().SetOpacity(0.5)
        plane_widget.SetInteractor(self.iren.interactor)
        plane_widget.SetCurrentRenderer(self.renderer)

        if assign_to_axis:
            # Note that normal_rotation was forced to False
            if assign_to_axis in [0, "x", "X"]:
                plane_widget.NormalToXAxisOn()
                plane_widget.SetNormal(NORMALS["x"])
            elif assign_to_axis in [1, "y", "Y"]:
                plane_widget.NormalToYAxisOn()
                plane_widget.SetNormal(NORMALS["y"])
            elif assign_to_axis in [2, "z", "Z"]:
                plane_widget.NormalToZAxisOn()
                plane_widget.SetNormal(NORMALS["z"])
            else:
                raise RuntimeError("assign_to_axis not understood")
        else:
            plane_widget.SetNormal(normal)

        plane_widget.Modified()
        plane_widget.UpdatePlacement()
        plane_widget.On()
        plane_widget.AddObserver(
            interaction_event,
            # _vtk.vtkCommand.InteractionEvent,
            _the_callback,
        )
        if test_callback:
            _the_callback(plane_widget, None)  # Trigger immediate update

        self.plane_widgets.append(plane_widget)
        return plane_widget

    def clear_plane_widgets(self):
        """Remove all of the plane widgets."""
        self.plane_widgets.clear()

    def add_mesh_clip_plane(
        self,
        mesh,
        normal='x',
        invert=False,
        widget_color=None,
        value=0.0,
        assign_to_axis=None,
        tubing=False,
        origin_translation=True,
        outline_translation=False,
        implicit=True,
        normal_rotation=True,
        crinkle=False,
        interaction_event='end',
        origin=None,
        **kwargs,
    ):
        """Clip a mesh using a plane widget.

        Add a mesh to the scene with a plane widget that is used to clip
        the mesh interactively.

        The clipped mesh is saved to the ``.plane_clipped_meshes``
        attribute on the plotter.

        Parameters
        ----------
        mesh : pyvista.DataSet or vtk.vtkAlgorithm
            The input dataset to add to the scene and clip or algorithm that
            produces said mesh.

        normal : str or tuple(float), optional
            The starting normal vector of the plane.

        invert : bool, optional
            Flag on whether to flip/invert the clip.

        widget_color : ColorLike, optional
            Either a string, RGB list, or hex color string.

        value : float, optional
            Set the clipping value along the normal direction.
            The default value is 0.0.

        assign_to_axis : str or int, optional
            Assign the normal of the plane to be parallel with a given
            axis.  Options are ``(0, 'x')``, ``(1, 'y')``, or ``(2,
            'z')``.

        tubing : bool, optional
            When using an implicit plane wiget, this controls whether
            or not tubing is shown around the plane's boundaries.

        origin_translation : bool, optional
            If ``False``, the plane widget cannot be translated by its
            origin and is strictly placed at the given origin. Only
            valid when using an implicit plane.

        outline_translation : bool, optional
            If ``False``, the box widget cannot be translated and is
            strictly placed at the given bounds.

        implicit : bool, optional
            When ``True``, a ``vtkImplicitPlaneWidget`` is used and
            when ``False``, a ``vtkPlaneWidget`` is used.

        normal_rotation : bool, optional
            Set the opacity of the normal vector arrow to 0 such that
            it is effectively disabled. This prevents the user from
            rotating the normal. This is forced to ``False`` when
            ``assign_to_axis`` is set.

        crinkle : bool, optional
            Crinkle the clip by extracting the entire cells along the clip.

        interaction_event : vtk.vtkCommand.EventIds, str, optional
            The VTK interaction event to use for triggering the
            callback. Accepts either the strings ``'start'``, ``'end'``,
            ``'always'`` or a ``vtk.vtkCommand.EventIds``.

            .. versionchanged:: 0.38.0
               Now accepts either strings or ``vtk.vtkCommand.EventIds``.

        origin : tuple(float), optional
            The starting coordinate of the center of the plane.

        **kwargs : dict, optional
            All additional keyword arguments are passed to
            :func:`Plotter.add_mesh` to control how the mesh is
            displayed.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the mesh.

        """
        from pyvista.core.filters import _get_output  # avoids circular import

        mesh, algo = algorithm_to_mesh_handler(
            add_ids_algorithm(mesh, point_ids=False, cell_ids=True)
        )

        name = kwargs.get('name', mesh.memory_address)
        rng = mesh.get_data_range(kwargs.get('scalars', None))
        kwargs.setdefault('clim', kwargs.pop('rng', rng))
        mesh.set_active_scalars(kwargs.get('scalars', mesh.active_scalars_name))
        if origin is None:
            origin = mesh.center

        self.add_mesh(outline_algorithm(algo), name=f"{name}-outline", opacity=0.0)

        if isinstance(mesh, _vtk.vtkPolyData):
            clipper = _vtk.vtkClipPolyData()
        # elif isinstance(mesh, vtk.vtkImageData):
        #     clipper = vtk.vtkClipVolume()
        #     clipper.SetMixed3DCellGeneration(True)
        else:
            clipper = _vtk.vtkTableBasedClipDataSet()
        set_algorithm_input(clipper, algo)
        clipper.SetValue(value)
        clipper.SetInsideOut(invert)  # invert the clip if needed

        if crinkle:
            crinkler = crinkle_algorithm(clipper, algo)
            plane_clipped_mesh = _get_output(crinkler)
        else:
            plane_clipped_mesh = _get_output(clipper)
        self.plane_clipped_meshes.append(plane_clipped_mesh)

        def callback(normal, loc):
            function = generate_plane(normal, loc)
            clipper.SetClipFunction(function)  # the implicit function
            clipper.Update()  # Perform the Cut
            if crinkle:
                clipped = pyvista.wrap(crinkler.GetOutputDataObject(0))
            else:
                clipped = pyvista.wrap(clipper.GetOutput())
            plane_clipped_mesh.shallow_copy(clipped)

        self.add_plane_widget(
            callback=callback,
            bounds=mesh.bounds,
            factor=1.25,
            normal=normal,
            color=widget_color,
            tubing=tubing,
            assign_to_axis=assign_to_axis,
            origin_translation=origin_translation,
            outline_translation=outline_translation,
            implicit=implicit,
            origin=origin,
            normal_rotation=normal_rotation,
            interaction_event=interaction_event,
        )

        if crinkle:
            return self.add_mesh(crinkler, **kwargs)
        return self.add_mesh(clipper, **kwargs)

    def add_volume_clip_plane(
        self,
        volume,
        normal='x',
        invert=False,
        widget_color=None,
        value=0.0,
        assign_to_axis=None,
        tubing=False,
        origin_translation=True,
        outline_translation=False,
        implicit=True,
        normal_rotation=True,
        interaction_event='end',
        origin=None,
        **kwargs,
    ):
        """Clip a volume using a plane widget.

        Parameters
        ----------
        volume : pyvista.plotting.volume.Volume or pyvista.UniformGrid or pyvista.RectilinearGrid
            New dataset of type :class:`pyvista.UniformGrid` or
            :class:`pyvista.RectilinearGrid`, or the return value from
            :class:`pyvista.plotting.volume.Volume` from :func:`Plotter.add_volume`.

        normal : str or tuple(float), optional
            The starting normal vector of the plane.

        invert : bool, optional
            Flag on whether to flip/invert the clip.

        widget_color : ColorLike, optional
            Either a string, RGB list, or hex color string.

        value : float, optional
            Set the clipping value along the normal direction.
            The default value is 0.0.

        assign_to_axis : str or int, optional
            Assign the normal of the plane to be parallel with a given
            axis.  Options are ``(0, 'x')``, ``(1, 'y')``, or ``(2,
            'z')``.

        tubing : bool, optional
            When using an implicit plane wiget, this controls whether
            or not tubing is shown around the plane's boundaries.

        origin_translation : bool, optional
            If ``False``, the plane widget cannot be translated by its
            origin and is strictly placed at the given origin. Only
            valid when using an implicit plane.

        outline_translation : bool, optional
            If ``False``, the box widget cannot be translated and is
            strictly placed at the given bounds.

        implicit : bool, optional
            When ``True``, a ``vtkImplicitPlaneWidget`` is used and
            when ``False``, a ``vtkPlaneWidget`` is used.

        normal_rotation : bool, optional
            Set the opacity of the normal vector arrow to 0 such that
            it is effectively disabled. This prevents the user from
            rotating the normal. This is forced to ``False`` when
            ``assign_to_axis`` is set.

        interaction_event : vtk.vtkCommand.EventIds, optional
            The VTK interaction event to use for triggering the callback.

        origin : tuple(float), optional
            The starting coordinate of the center of the plane.

        **kwargs : dict, optional
            All additional keyword arguments are passed to
            :func:`Plotter.add_volume` to control how the volume is
            displayed. Only applicable if ``volume`` is either a
            :class:`pyvista.UniformGrid` and :class:`pyvista.RectilinearGrid`.

        Returns
        -------
        vtk.vtkPlaneWidget or vtk.vtkImplicitPlaneWidget
            The VTK plane widget depending on the value of ``implicit``.

        """
        if isinstance(volume, (pyvista.UniformGrid, pyvista.RectilinearGrid)):
            volume = self.add_volume(volume, **kwargs)
        elif not isinstance(volume, pyvista.plotting.Volume):
            raise TypeError(
                'The `volume` parameter type must be either pyvista.UniformGrid, '
                'pyvista.RectilinearGrid, or a pyvista.plotting.volume.Volume '
                'from `Plotter.add_volume`.'
            )
        else:
            assert_empty_kwargs(**kwargs)

        plane = _vtk.vtkPlane()

        def callback(normal, origin):
            """Update the plane used to clip the volume."""
            plane.SetNormal(normal)
            plane.SetOrigin(origin)

        widget = self.add_plane_widget(
            callback=callback,
            bounds=volume.bounds,
            factor=1.25,
            normal=normal,
            color=widget_color,
            tubing=tubing,
            assign_to_axis=assign_to_axis,
            origin_translation=origin_translation,
            outline_translation=outline_translation,
            implicit=implicit,
            origin=origin,
            normal_rotation=normal_rotation,
            interaction_event=interaction_event,
        )
        widget.GetPlane(plane)
        volume.mapper.AddClippingPlane(plane)
        self.plane_widgets.append(widget)

        return widget

    def add_mesh_slice(
        self,
        mesh,
        normal='x',
        generate_triangles=False,
        widget_color=None,
        assign_to_axis=None,
        tubing=False,
        origin_translation=True,
        outline_translation=False,
        implicit=True,
        normal_rotation=True,
        interaction_event=_vtk.vtkCommand.EndInteractionEvent,
        origin=None,
        **kwargs,
    ):
        """Slice a mesh using a plane widget.

        Add a mesh to the scene with a plane widget that is used to slice
        the mesh interactively.

        The sliced mesh is saved to the ``.plane_sliced_meshes`` attribute on
        the plotter.

        Parameters
        ----------
        mesh : pyvista.DataSet or vtk.vtkAlgorithm
            The input dataset to add to the scene and slice or algorithm that
            produces said mesh.

        normal : str or tuple(float), optional
            The starting normal vector of the plane.

        generate_triangles : bool, optional
            If this is enabled (``False`` by default), the output will be
            triangles otherwise, the output will be the intersection polygons.

        widget_color : ColorLike, optional
            Either a string, RGB sequence, or hex color string.  Defaults
            to ``'white'``.

        assign_to_axis : str or int, optional
            Assign the normal of the plane to be parallel with a given axis:
            options are (0, 'x'), (1, 'y'), or (2, 'z').

        tubing : bool, optional
            When using an implicit plane wiget, this controls whether or not
            tubing is shown around the plane's boundaries.

        origin_translation : bool, optional
            If ``False``, the plane widget cannot be translated by its origin
            and is strictly placed at the given origin. Only valid when using
            an implicit plane.

        outline_translation : bool, optional
            If ``False``, the box widget cannot be translated and is strictly
            placed at the given bounds.

        implicit : bool, optional
            When ``True``, a ``vtkImplicitPlaneWidget`` is used and when
            ``False``, a ``vtkPlaneWidget`` is used.

        normal_rotation : bool, optional
            Set the opacity of the normal vector arrow to 0 such that it is
            effectively disabled. This prevents the user from rotating the
            normal. This is forced to ``False`` when ``assign_to_axis`` is set.

        interaction_event : vtk.vtkCommand.EventIds, optional
            The VTK interaction event to use for triggering the callback.

        origin : tuple(float), optional
            The starting coordinate of the center of the plane.

        **kwargs : dict, optional
            All additional keyword arguments are passed to
            :func:`Plotter.add_mesh` to control how the mesh is
            displayed.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the mesh.

        """
        mesh, algo = algorithm_to_mesh_handler(mesh)

        name = kwargs.get('name', mesh.memory_address)
        rng = mesh.get_data_range(kwargs.get('scalars', None))
        kwargs.setdefault('clim', kwargs.pop('rng', rng))
        mesh.set_active_scalars(kwargs.get('scalars', mesh.active_scalars_name))
        if origin is None:
            origin = mesh.center

        self.add_mesh(outline_algorithm(algo or mesh), name=f"{name}-outline", opacity=0.0)

        alg = _vtk.vtkCutter()  # Construct the cutter object
        set_algorithm_input(alg, algo or mesh)
        if not generate_triangles:
            alg.GenerateTrianglesOff()

        plane_sliced_mesh = pyvista.wrap(alg.GetOutput())
        self.plane_sliced_meshes.append(plane_sliced_mesh)

        def callback(normal, origin):
            # create the plane for clipping
            plane = generate_plane(normal, origin)
            alg.SetCutFunction(plane)  # the cutter to use the plane we made
            alg.Update()  # Perform the Cut
            plane_sliced_mesh.shallow_copy(alg.GetOutput())

        self.add_plane_widget(
            callback=callback,
            bounds=mesh.bounds,
            factor=1.25,
            normal=normal,
            color=widget_color,
            tubing=tubing,
            assign_to_axis=assign_to_axis,
            origin_translation=origin_translation,
            outline_translation=outline_translation,
            implicit=implicit,
            origin=origin,
            normal_rotation=normal_rotation,
            interaction_event=interaction_event,
        )

        return self.add_mesh(alg, **kwargs)

    def add_mesh_slice_orthogonal(
        self,
        mesh,
        generate_triangles=False,
        widget_color=None,
        tubing=False,
        interaction_event=_vtk.vtkCommand.EndInteractionEvent,
        **kwargs,
    ):
        """Slice a mesh with three interactive planes.

        Adds three interactive plane slicing widgets for orthogonal slicing
        along each cartesian axis.

        Parameters
        ----------
        mesh : pyvista.DataSet or vtk.vtkAlgorithm
            The input dataset to add to the scene and threshold or algorithm
            that produces said mesh.

        generate_triangles : bool, optional
            If this is enabled (``False`` by default), the output will be
            triangles otherwise, the output will be the intersection polygons.

        widget_color : ColorLike, optional
            Color of the widget.  Either a string, RGB sequence, or
            hex color string.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        tubing : bool, optional
            When using an implicit plane wiget, this controls whether or not
            tubing is shown around the plane's boundaries.

        interaction_event : vtk.vtkCommand.EventIds, optional
            The VTK interaction event to use for triggering the callback.

        **kwargs : dict, optional
            All additional keyword arguments are passed to
            :func:`Plotter.add_mesh` to control how the mesh is
            displayed.

        Returns
        -------
        list
            List of vtk.vtkActor(s).

        """
        actors = []
        name = kwargs.pop("name", None)
        for ax in ["x", "y", "z"]:
            axkwargs = kwargs.copy()
            if name:
                axkwargs["name"] = f"{name}-{ax}"
            a = self.add_mesh_slice(
                mesh,
                assign_to_axis=ax,
                origin_translation=False,
                outline_translation=False,
                generate_triangles=generate_triangles,
                widget_color=widget_color,
                tubing=tubing,
                interaction_event=interaction_event,
                **axkwargs,
            )
            actors.append(a)

        return actors

    def add_line_widget(
        self,
        callback,
        bounds=None,
        factor=1.25,
        resolution=100,
        color=None,
        use_vertices=False,
        pass_widget=False,
        interaction_event=_vtk.vtkCommand.EndInteractionEvent,
    ):
        """Add a line widget to the scene.

        This is useless without a callback function. You can pass a
        callable function that takes a single argument, the PolyData
        line output from this widget, and performs a task with that
        line.

        Parameters
        ----------
        callback : callable
            The method called every time the line is updated. This has
            two options: Take a single argument, the ``PolyData`` line
            (default) or if ``use_vertices=True``, then it can take
            two arguments of the coordinates of the line's end points.

        bounds : tuple(float), optional
            Length 6 tuple of the bounding box where the widget is
            placed.

        factor : float, optional
            An inflation factor to expand on the bounds when placing.

        resolution : int, optional
            The number of points in the line created.

        color : ColorLike, optional
            Either a string, rgb sequence, or hex color string.

        use_vertices : bool, optional
            Changes the arguments of the callback method to take the end
            points of the line instead of a PolyData object.

        pass_widget : bool, default: False
            If ``True``, the widget will be passed as the last
            argument of the callback.

        interaction_event : vtk.vtkCommand.EventIds, optional
            The VTK interaction event to use for triggering the callback.

        Returns
        -------
        vtk.vtkLineWidget
            Created line widget.

        """
        if bounds is None:
            bounds = self.bounds

        color = Color(color, default_color=pyvista.global_theme.font.color)

        def _the_callback(widget, event_id):
            pointa = widget.GetPoint1()
            pointb = widget.GetPoint2()
            if callable(callback):
                if use_vertices:
                    args = [pointa, pointb]
                else:
                    the_line = pyvista.Line(pointa, pointb, resolution=resolution)
                    args = [the_line]
                if pass_widget:
                    args.append(widget)
                try_callback(callback, *args)

        line_widget = _vtk.vtkLineWidget()
        line_widget.GetLineProperty().SetColor(color.float_rgb)
        line_widget.SetInteractor(self.iren.interactor)
        line_widget.SetCurrentRenderer(self.renderer)
        line_widget.SetPlaceFactor(factor)
        line_widget.PlaceWidget(bounds)
        line_widget.SetResolution(resolution)
        line_widget.Modified()
        line_widget.On()
        line_widget.AddObserver(interaction_event, _the_callback)
        _the_callback(line_widget, None)

        self.line_widgets.append(line_widget)
        return line_widget

    def clear_line_widgets(self):
        """Remove all of the line widgets."""
        self.line_widgets.clear()

    def add_text_slider_widget(
        self,
        callback,
        data,
        value=None,
        pointa=(0.4, 0.9),
        pointb=(0.9, 0.9),
        color=None,
        interaction_event='end',
        style=None,
        **kwargs,
    ):
        """Add a text slider bar widget.

        This is useless without a callback function. You can pass a callable
        function that takes a single argument, the value of this slider widget,
        and performs a task with that value.

        Parameters
        ----------
        callback : callable
            The method called every time the slider is updated. This should take
            a single parameter: the float value of the slider.

        data : list
            The list of possible values displayed on the slider bar.

        value : float, optional
            The starting value of the slider.

        pointa : tuple(float), optional
            The relative coordinates of the left point of the slider on the
            display port.

        pointb : tuple(float), optional
            The relative coordinates of the right point of the slider on the
            display port.

        color : ColorLike, optional
            Either a string, RGB list, or hex color string.  Defaults
            to :attr:`pyvista.global_theme.font.color
            <pyvista.themes._Font.color>`.

        interaction_event : vtk.vtkCommand.EventIds, str, optional
            The VTK interaction event to use for triggering the
            callback. Accepts either the strings ``'start'``, ``'end'``,
            ``'always'`` or a ``vtk.vtkCommand.EventIds``.

            .. versionchanged:: 0.38.0
               Changed from ``event_type`` to ``interaction_event`` and now
               accepts either strings or ``vtk.vtkCommand.EventIds``.

        style : str, optional
            The name of the slider style. The list of available styles
            are in ``pyvista.global_theme.slider_styles``. Defaults to
            ``None``.

        **kwargs : dict, optional
            Deprecated keyword arguments.

            .. deprecated:: 0.38.0
               Keyword argument ``event_type`` deprecated in favor of
               ``interaction_event``.

        Returns
        -------
        vtk.vtkSliderWidget
            The VTK slider widget configured to display text.

        """
        if not isinstance(data, list):
            raise TypeError(
                f"The `data` parameter must be a list but {type(data).__name__} was passed instead"
            )
        n_states = len(data)
        if n_states == 0:
            raise ValueError("The input list of values is empty")
        delta = (n_states - 1) / float(n_states)
        # avoid division by zero in case there is only one element
        delta = 1 if delta == 0 else delta

        def _the_callback(value):
            if isinstance(value, float):
                idx = int(value / delta)
                # handle limit index
                if idx == n_states:
                    idx = n_states - 1
                if callable(callback):
                    try_callback(callback, data[idx])
            return

        slider_widget = self.add_slider_widget(
            callback=_the_callback,
            rng=[0, n_states - 1],
            value=value,
            pointa=pointa,
            pointb=pointb,
            color=color,
            interaction_event=interaction_event,
            style=style,
        )
        slider_rep = slider_widget.GetRepresentation()
        slider_rep.ShowSliderLabelOff()

        def title_callback(widget, event):
            value = widget.GetRepresentation().GetValue()
            idx = int(value / delta)
            # handle limit index
            if idx == n_states:
                idx = n_states - 1
            slider_rep.SetTitleText(data[idx])

        slider_widget.AddObserver(_parse_interaction_event(interaction_event), title_callback)
        title_callback(slider_widget, None)
        return slider_widget

    def add_slider_widget(
        self,
        callback,
        rng,
        value=None,
        title=None,
        pointa=(0.4, 0.9),
        pointb=(0.9, 0.9),
        color=None,
        pass_widget=False,
        interaction_event='end',
        style=None,
        title_height=0.03,
        title_opacity=1.0,
        title_color=None,
        fmt=None,
        slider_width=None,
        tube_width=None,
        **kwargs,
    ):
        """Add a slider bar widget.

        This is useless without a callback function. You can pass a
        callable function that takes a single argument, the value of
        this slider widget, and performs a task with that value.

        Parameters
        ----------
        callback : callable
            Called every time the slider is updated. This should take a single
            parameter: the float value of the slider. If ``pass_widget=True``,
            callable should take two parameters: the float value of the slider
            and the widget itself.

        rng : tuple(float)
            Length two tuple of the minimum and maximum ranges of the
            slider.

        value : float, optional
            The starting value of the slider.

        title : str, optional
            The string label of the slider widget.

        pointa : tuple(float), optional
            The relative coordinates of the left point of the slider
            on the display port.

        pointb : tuple(float), optional
            The relative coordinates of the right point of the slider
            on the display port.

        color : ColorLike, optional
            Either a string, RGB list, or hex color string.  Defaults
            to :attr:`pyvista.global_theme.font.color
            <pyvista.themes._Font.color>`.

        pass_widget : bool, optional
            If ``True``, the widget will be passed as the last
            argument of the callback.

        interaction_event : vtk.vtkCommand.EventIds, str, optional
            The VTK interaction event to use for triggering the
            callback. Accepts either the strings ``'start'``, ``'end'``,
            ``'always'`` or a ``vtk.vtkCommand.EventIds``.

            .. versionchanged:: 0.38.0
               Changed from ``event_type`` to ``interaction_event`` and now accepts
               either strings or ``vtk.vtkCommand.EventIds``.

        style : str, optional
            The name of the slider style. The list of available styles
            are in ``pyvista.global_theme.slider_styles``. Defaults to
            ``None``.

        title_height : float, optional
            Relative height of the title as compared to the length of
            the slider.

        title_opacity : float, optional
            Opacity of title. Defaults to 1.0.

        title_color : ColorLike, optional
            Either a string, RGB sequence, or hex color string.  Defaults
            to the value given in ``color``.

        fmt : str, optional
            String formatter used to format numerical data. Defaults
            to ``None``.

        slider_width : float, optional
            Normalized width of the slider. Defaults to the theme's slider width.

        tube_width : float, optional
            Normalized width of the tube. Defaults to the theme's tube width.

        **kwargs : dict, optional
            Deprecated keyword arguments.

            .. deprecated:: 0.38.0
               Keyword argument ``event_type`` deprecated in favor of
               ``interaction_event``.

        Returns
        -------
        vtk.vtkSliderWidget
            Slider widget.

        Examples
        --------
        >>> import pyvista as pv
        >>> pl = pv.Plotter()
        >>> def create_mesh(value):
        ...     res = int(value)
        ...     sphere = pv.Sphere(
        ...         phi_resolution=res, theta_resolution=res
        ...     )
        ...     pl.add_mesh(sphere, name="sphere", show_edges=True)
        ...
        >>> slider = pl.add_slider_widget(
        ...     create_mesh,
        ...     [5, 100],
        ...     title="Resolution",
        ...     title_opacity=0.5,
        ...     title_color="red",
        ...     fmt="%0.9f",
        ...     title_height=0.08,
        ... )
        >>> pl.show()
        """
        if self.iren is None:
            raise RuntimeError('Cannot add a widget to a closed plotter.')

        if value is None:
            value = ((rng[1] - rng[0]) / 2) + rng[0]

        color = Color(color, default_color=pyvista.global_theme.font.color)
        title_color = Color(title_color, default_color=color)

        if fmt is None:
            fmt = pyvista.global_theme.font.fmt

        def normalize(point, viewport):
            return (point[0] * (viewport[2] - viewport[0]), point[1] * (viewport[3] - viewport[1]))

        pointa = normalize(pointa, self.renderer.GetViewport())
        pointb = normalize(pointb, self.renderer.GetViewport())

        slider_rep = _vtk.vtkSliderRepresentation2D()
        slider_rep.SetPickable(False)
        slider_rep.SetMinimumValue(rng[0])
        slider_rep.SetMaximumValue(rng[1])
        slider_rep.SetValue(value)
        slider_rep.SetTitleText(title)
        slider_rep.GetTitleProperty().SetColor(color.float_rgb)
        slider_rep.GetSliderProperty().SetColor(color.float_rgb)
        slider_rep.GetCapProperty().SetColor(color.float_rgb)
        slider_rep.GetLabelProperty().SetColor(color.float_rgb)
        slider_rep.GetTubeProperty().SetColor(color.float_rgb)
        slider_rep.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
        slider_rep.GetPoint1Coordinate().SetValue(pointa[0], pointa[1])
        slider_rep.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
        slider_rep.GetPoint2Coordinate().SetValue(pointb[0], pointb[1])
        slider_rep.SetSliderLength(0.05)
        slider_rep.SetSliderWidth(0.05)
        slider_rep.SetEndCapLength(0.01)

        if style is not None:
            if not isinstance(style, str):
                raise TypeError(
                    f"Expected type for ``style`` is str but {type(style).__name__} was given."
                )
            slider_style = getattr(pyvista.global_theme.slider_styles, style)
            slider_rep.SetSliderLength(slider_style.slider_length)
            slider_rep.SetSliderWidth(slider_style.slider_width)
            slider_rep.GetSliderProperty().SetColor(slider_style.slider_color.float_rgb)
            slider_rep.SetTubeWidth(slider_style.tube_width)
            slider_rep.GetTubeProperty().SetColor(slider_style.tube_color.float_rgb)
            slider_rep.GetCapProperty().SetOpacity(slider_style.cap_opacity)
            slider_rep.SetEndCapLength(slider_style.cap_length)
            slider_rep.SetEndCapWidth(slider_style.cap_width)

        if slider_width is not None:
            slider_rep.SetSliderWidth(slider_width)
        if tube_width is not None:
            slider_rep.SetTubeWidth(tube_width)

        def _the_callback(widget, event):
            value = widget.GetRepresentation().GetValue()
            if callable(callback):
                if pass_widget:
                    try_callback(callback, value, widget)
                else:
                    try_callback(callback, value)
            return

        slider_widget = _vtk.vtkSliderWidget()
        slider_widget.SetInteractor(self.iren.interactor)
        slider_widget.SetCurrentRenderer(self.renderer)
        slider_widget.SetRepresentation(slider_rep)
        slider_widget.GetRepresentation().SetTitleHeight(title_height)
        slider_widget.GetRepresentation().GetTitleProperty().SetOpacity(title_opacity)
        slider_widget.GetRepresentation().GetTitleProperty().SetColor(title_color.float_rgb)
        if fmt is not None:
            slider_widget.GetRepresentation().SetLabelFormat(fmt)
        slider_widget.On()
        slider_widget.AddObserver(_parse_interaction_event(interaction_event), _the_callback)
        _the_callback(slider_widget, None)

        self.slider_widgets.append(slider_widget)
        return slider_widget

    def clear_slider_widgets(self):
        """Remove all of the slider widgets."""
        self.slider_widgets.clear()

    def add_mesh_threshold(
        self,
        mesh,
        scalars=None,
        invert=False,
        widget_color=None,
        preference='cell',
        title=None,
        pointa=(0.4, 0.9),
        pointb=(0.9, 0.9),
        continuous=False,
        all_scalars=False,
        method='upper',
        **kwargs,
    ):
        """Apply a threshold on a mesh with a slider.

        Add a mesh to the scene with a slider widget that is used to
        threshold the mesh interactively.

        The threshold mesh is saved to the ``.threshold_meshes`` attribute on
        the plotter.

        Parameters
        ----------
        mesh : pyvista.DataSet or vtk.vtkAlgorithm
            The input dataset to add to the scene and threshold or algorithm
            that produces said mesh.

        scalars : str, optional
            The string name of the scalars on the mesh to threshold and display.

        invert : bool, default: False
            Invert the threshold results. That is, cells that would have been
            in the output with this option off are excluded, while cells that
            would have been excluded from the output are included.

        widget_color : ColorLike, optional
            Color of the widget.  Either a string, RGB sequence, or
            hex color string.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        preference : str, default: 'cell'
            When ``mesh.n_points == mesh.n_cells`` and setting
            scalars, this parameter sets how the scalars will be
            mapped to the mesh.  Default ``'cell'``, causes the
            scalars to be associated with the mesh cells.  Can be
            either ``'point'`` or ``'cell'``.

        title : str, optional
            The string label of the slider widget.

        pointa : sequence, default: (0.4, 0.9)
            The relative coordinates of the left point of the slider
            on the display port.

        pointb : sequence, default: (0.9, 0.9)
            The relative coordinates of the right point of the slider
            on the display port.

        continuous : bool, default: False
            If this is enabled (default is ``False``), use the continuous
            interval ``[minimum cell scalar, maximum cell scalar]``
            to intersect the threshold bound, rather than the set of
            discrete scalar values from the vertices.

        all_scalars : bool, default: False
            If using scalars from point data, all
            points in a cell must satisfy the threshold when this
            value is ``True``.  When ``False``, any point of the cell
            with a scalar value satisfying the threshold criterion
            will extract the cell. Has no effect when using cell data.

        method : str, default: 'upper'
            Set the threshold method for single-values, defining which
            threshold bounds to use. If the ``value`` is a range, this
            parameter will be ignored, extracting data between the two
            values. For single values, ``'lower'`` will extract data
            lower than the  ``value``. ``'upper'`` will extract data
            larger than the ``value``.

        **kwargs : dict, optional
            All additional keyword arguments are passed to ``add_mesh`` to
            control how the mesh is displayed.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the mesh.

        """
        # avoid circular import
        from ..core.filters.data_set import _set_threshold_limit

        mesh, algo = algorithm_to_mesh_handler(mesh)

        if isinstance(mesh, pyvista.PointSet):
            # vtkThreshold is CELL-wise and PointSets have no cells
            algo = pointset_to_polydata_algorithm(algo or mesh)
            mesh, algo = algorithm_to_mesh_handler(algo)

        if isinstance(mesh, pyvista.MultiBlock):
            raise TypeError('MultiBlock datasets are not supported for threshold widget.')
        name = kwargs.get('name', mesh.memory_address)
        if scalars is None:
            field, scalars = mesh.active_scalars_info
        arr = get_array(mesh, scalars, preference=preference)
        if arr is None:
            raise ValueError('No arrays present to threshold.')
        field = get_array_association(mesh, scalars, preference=preference)

        rng = mesh.get_data_range(scalars)
        kwargs.setdefault('clim', kwargs.pop('rng', rng))
        if title is None:
            title = scalars
        mesh.set_active_scalars(scalars)

        self.add_mesh(outline_algorithm(algo or mesh), name=f"{name}-outline", opacity=0.0)

        alg = _vtk.vtkThreshold()
        set_algorithm_input(alg, algo or mesh)
        alg.SetInputArrayToProcess(
            0, 0, 0, field.value, scalars
        )  # args: (idx, port, connection, field, name)
        alg.SetUseContinuousCellRange(continuous)
        alg.SetAllScalars(all_scalars)

        threshold_mesh = pyvista.wrap(alg.GetOutput())
        self.threshold_meshes.append(threshold_mesh)

        def callback(value):
            _set_threshold_limit(alg, value, method, invert)
            alg.Update()
            threshold_mesh.shallow_copy(alg.GetOutput())

        self.add_slider_widget(
            callback=callback,
            rng=rng,
            title=title,
            color=widget_color,
            pointa=pointa,
            pointb=pointb,
        )

        kwargs.setdefault("reset_camera", False)
        return self.add_mesh(alg, scalars=scalars, **kwargs)

    def add_mesh_isovalue(
        self,
        mesh,
        scalars=None,
        compute_normals=False,
        compute_gradients=False,
        compute_scalars=True,
        preference='point',
        title=None,
        pointa=(0.4, 0.9),
        pointb=(0.9, 0.9),
        widget_color=None,
        **kwargs,
    ):
        """Create a contour of a mesh with a slider.

        Add a mesh to the scene with a slider widget that is used to
        contour at an isovalue of the *point* data on the mesh
        interactively.

        The isovalue mesh is saved to the ``.isovalue_meshes``
        attribute on the plotter.

        .. warning::
            This will not work with :class:`pyvista.PointSet` as
            creating an isovalue is a dimension reducing operation
            on the geometry and point clouds are zero dimensional.
            This will similarly fail for point clouds in
            :class:`pyvista.PolyData`.

        Parameters
        ----------
        mesh : pyvista.DataSet or vtk.vtkAlgorithm
            The input dataset to add to the scene and contour or algorithm
            that produces said mesh.

        scalars : str, optional
            The string name of the scalars on the mesh to contour and display.

        compute_normals : bool, optional
            Enable or disable the computation of normals.  If the
            output data will be processed by filters that modify
            topology or geometry, it may be wise to disable computing
            normals.

        compute_gradients : bool, optional
            Enable or disable the computation of gradients.  If the
            output data will be processed by filters that modify
            topology or geometry, it may be wise to disable computing
            gradients.

        compute_scalars : bool, optional
            Enable or disable the computation of scalars.

        preference : str, optional
            When ``mesh.n_points == mesh.n_cells`` and setting
            scalars, this parameter sets how the scalars will be
            mapped to the mesh.  Default ``'point'``, causes the
            scalars will be associated with the mesh points.  Can be
            either ``'point'`` or ``'cell'``.

        title : str, optional
            The string label of the slider widget.

        pointa : sequence, optional
            The relative coordinates of the left point of the slider
            on the display port.

        pointb : sequence
            The relative coordinates of the right point of the slider
            on the display port.

        widget_color : ColorLike, optional
            Color of the widget.  Either a string, RGB sequence, or
            hex color string.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        **kwargs : dict, optional
            All additional keyword arguments are passed to
            :func:`Plotter.add_mesh` to control how the mesh is
            displayed.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the mesh.

        """
        mesh, algo = algorithm_to_mesh_handler(mesh)
        if isinstance(mesh, pyvista.PointSet):
            raise TypeError('PointSets are 0-dimensional and thus cannot produce contours.')
        if isinstance(mesh, pyvista.MultiBlock):
            raise TypeError('MultiBlock datasets are not supported for this widget.')
        name = kwargs.get('name', mesh.memory_address)
        # set the array to contour on
        if mesh.n_arrays < 1:
            raise ValueError('Input dataset for the contour filter must have data arrays.')
        if scalars is None:
            field, scalars = mesh.active_scalars_info
        else:
            field = get_array_association(mesh, scalars, preference=preference)
        # NOTE: only point data is allowed? well cells works but seems buggy?
        if field != pyvista.FieldAssociation.POINT:
            raise TypeError(
                f'Contour filter only works on Point data. Array ({scalars}) is in the Cell data.'
            )

        rng = mesh.get_data_range(scalars)
        kwargs.setdefault('clim', kwargs.pop('rng', rng))
        if title is None:
            title = scalars
        mesh.set_active_scalars(scalars)

        alg = _vtk.vtkContourFilter()
        set_algorithm_input(alg, algo or mesh)
        alg.SetComputeNormals(compute_normals)
        alg.SetComputeGradients(compute_gradients)
        alg.SetComputeScalars(compute_scalars)
        alg.SetInputArrayToProcess(0, 0, 0, field.value, scalars)
        alg.SetNumberOfContours(1)  # Only one contour level

        self.add_mesh(outline_algorithm(algo or mesh), name=f"{name}-outline", opacity=0.0)

        isovalue_mesh = pyvista.wrap(alg.GetOutput())
        self.isovalue_meshes.append(isovalue_mesh)

        def callback(value):
            alg.SetValue(0, value)
            alg.Update()
            isovalue_mesh.shallow_copy(alg.GetOutput())

        self.add_slider_widget(
            callback=callback,
            rng=rng,
            title=title,
            color=widget_color,
            pointa=pointa,
            pointb=pointb,
        )

        kwargs.setdefault("reset_camera", False)
        return self.add_mesh(alg, scalars=scalars, **kwargs)

    def add_spline_widget(
        self,
        callback,
        bounds=None,
        factor=1.25,
        n_handles=5,
        resolution=25,
        color="yellow",
        show_ribbon=False,
        ribbon_color="pink",
        ribbon_opacity=0.5,
        pass_widget=False,
        closed=False,
        initial_points=None,
        interaction_event=_vtk.vtkCommand.EndInteractionEvent,
    ):
        """Create and add a spline widget to the scene.

        Use the bounds argument to place this widget. Several "handles" are
        used to control a parametric function for building this spline. Click
        directly on the line to translate the widget.

        Parameters
        ----------
        callback : callable
            The method called every time the spline is updated. This passes a
            :class:`pyvista.PolyData` object to the callback function of the
            generated spline.

        bounds : sequence[float], optional
            Length 6 sequence of the bounding box where the widget is placed.

        factor : float, optional
            An inflation factor to expand on the bounds when placing.

        n_handles : int, optional
            The number of interactive spheres to control the spline's
            parametric function.

        resolution : int, optional
            The number of points in the spline created between all the handles.

        color : ColorLike, optional
            Either a string, RGB sequence, or hex color string.

        show_ribbon : bool, optional
            If ``True``, the poly plane used for slicing will also be shown.

        ribbon_color : ColorLike, optional
            Color of the ribbon.  Either a string, RGB sequence, or
            hex color string.

        ribbon_opacity : float, optional
            Opacity of ribbon. Defaults to 1.0 and must be between
            ``[0, 1]``.

        pass_widget : bool, optional
            If ``True``, the widget will be passed as the last argument of the
            callback.

        closed : bool, optional
            Make the spline a closed loop.

        initial_points : sequence, optional
            The points to initialize the widget placement. Must have
            same number of elements as ``n_handles``. If the first and
            last point are the same, this will be a closed loop
            spline.

        interaction_event : vtk.vtkCommand.EventIds, optional
            The VTK interaction event to use for triggering the callback.

        Returns
        -------
        vtk.vtkSplineWidget
            The newly created spline widget.

        Notes
        -----
        This widget has trouble displaying certain colors. Use only simple
        colors (white, black, yellow).

        """
        if initial_points is not None and len(initial_points) != n_handles:
            raise ValueError("`initial_points` must be length `n_handles`.")

        color = Color(color, default_color=pyvista.global_theme.color)

        if bounds is None:
            bounds = self.bounds

        ribbon = pyvista.PolyData()

        def _the_callback(widget, event_id):
            para_source = _vtk.vtkParametricFunctionSource()
            para_source.SetParametricFunction(widget.GetParametricSpline())
            para_source.Update()
            polyline = pyvista.wrap(para_source.GetOutput())
            ribbon.shallow_copy(polyline.ribbon(normal=(0, 0, 1), angle=90.0))
            if callable(callback):
                if pass_widget:
                    try_callback(callback, polyline, widget)
                else:
                    try_callback(callback, polyline)
            return

        spline_widget = _vtk.vtkSplineWidget()
        spline_widget.GetLineProperty().SetColor(color.float_rgb)
        spline_widget.SetNumberOfHandles(n_handles)
        spline_widget.SetInteractor(self.iren.interactor)
        spline_widget.SetCurrentRenderer(self.renderer)
        spline_widget.SetPlaceFactor(factor)
        spline_widget.PlaceWidget(bounds)
        spline_widget.SetResolution(resolution)
        if initial_points is not None:
            spline_widget.InitializeHandles(pyvista.vtk_points(initial_points))
        else:
            spline_widget.SetClosed(closed)
        spline_widget.Modified()
        spline_widget.On()
        spline_widget.AddObserver(interaction_event, _the_callback)
        _the_callback(spline_widget, None)

        if show_ribbon:
            self.add_mesh(ribbon, color=ribbon_color, opacity=ribbon_opacity)

        self.spline_widgets.append(spline_widget)
        return spline_widget

    def clear_spline_widgets(self):
        """Remove all of the spline widgets."""
        self.spline_widgets.clear()

    def add_mesh_slice_spline(
        self,
        mesh,
        generate_triangles=False,
        n_handles=5,
        resolution=25,
        widget_color=None,
        show_ribbon=False,
        ribbon_color="pink",
        ribbon_opacity=0.5,
        initial_points=None,
        closed=False,
        interaction_event=_vtk.vtkCommand.EndInteractionEvent,
        **kwargs,
    ):
        """Slice a mesh with a spline widget.

        Add a mesh to the scene with a spline widget that is used to slice
        the mesh interactively.

        The sliced mesh is saved to the ``.spline_sliced_meshes`` attribute on
        the plotter.

        Parameters
        ----------
        mesh : pyvista.DataSet or vtk.vtkAlgorithm
            The input dataset to add to the scene and slice along the spline
            or algorithm that produces said mesh.

        generate_triangles : bool, optional
            If this is enabled (``False`` by default), the output will be
            triangles otherwise, the output will be the intersection polygons.

        n_handles : int, optional
            The number of interactive spheres to control the spline's
            parametric function.

        resolution : int, optional
            The number of points to generate on the spline.

        widget_color : ColorLike, optional
            Color of the widget.  Either a string, RGB sequence, or
            hex color string.  For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        show_ribbon : bool, optional
            If ``True``, the poly plane used for slicing will also be shown.

        ribbon_color : ColorLike, optional
            Color of the ribbon.  Either a string, RGB sequence, or
            hex color string.

        ribbon_opacity : float, optional
            Opacity of ribbon. Defaults to 1.0 and must be between
            ``[0, 1]``.

        initial_points : sequence, optional
            The points to initialize the widget placement. Must have same
            number of elements as ``n_handles``. If the first and last point
            are the same, this will be a closed loop spline.

        closed : bool, optional
            Make the spline a closed loop.

        interaction_event : vtk.vtkCommand.EventIds, optional
            The VTK interaction event to use for triggering the callback.

        **kwargs : dict, optional
            All additional keyword arguments are passed to
            :func:`Plotter.add_mesh` to control how the mesh is
            displayed.

        Returns
        -------
        vtk.vtkActor
            VTK actor of the mesh.

        """
        mesh, algo = algorithm_to_mesh_handler(mesh)
        name = kwargs.get('name', None)
        if name is None:
            name = mesh.memory_address
        rng = mesh.get_data_range(kwargs.get('scalars', None))
        kwargs.setdefault('clim', kwargs.pop('rng', rng))
        mesh.set_active_scalars(kwargs.get('scalars', mesh.active_scalars_name))

        self.add_mesh(outline_algorithm(algo or mesh), name=f"{name}-outline", opacity=0.0)

        alg = _vtk.vtkCutter()  # Construct the cutter object
        # Use the grid as the data we desire to cut
        set_algorithm_input(alg, algo or mesh)
        if not generate_triangles:
            alg.GenerateTrianglesOff()

        spline_sliced_mesh = pyvista.wrap(alg.GetOutput())
        self.spline_sliced_meshes.append(spline_sliced_mesh)

        def callback(spline):
            polyline = spline.GetCell(0)
            # create the plane for clipping
            polyplane = _vtk.vtkPolyPlane()
            polyplane.SetPolyLine(polyline)
            alg.SetCutFunction(polyplane)  # the cutter to use the poly planes
            alg.Update()  # Perform the Cut
            spline_sliced_mesh.shallow_copy(alg.GetOutput())

        self.add_spline_widget(
            callback=callback,
            bounds=mesh.bounds,
            factor=1.25,
            color=widget_color,
            n_handles=n_handles,
            resolution=resolution,
            show_ribbon=show_ribbon,
            ribbon_color=ribbon_color,
            ribbon_opacity=ribbon_opacity,
            initial_points=initial_points,
            closed=closed,
            interaction_event=interaction_event,
        )

        return self.add_mesh(alg, **kwargs)

    def add_sphere_widget(
        self,
        callback,
        center=(0, 0, 0),
        radius=0.5,
        theta_resolution=30,
        phi_resolution=30,
        color=None,
        style="surface",
        selected_color="pink",
        indices=None,
        pass_widget=False,
        test_callback=True,
        interaction_event=_vtk.vtkCommand.EndInteractionEvent,
    ):
        """Add one or many sphere widgets to a scene.

        Use a sphere widget to control a vertex location.

        Parameters
        ----------
        callback : callable
            The function to call back when the widget is modified. It takes a
            single argument: the center of the sphere as an XYZ coordinate (a
            3-length sequence), unless ``pass_widget=True``, in which case the
            callback must accept the widget object as the second parameter.  If
            multiple centers are passed in the ``center`` parameter, the
            callback must also accept an index of that widget.

        center : sequence[float], optional
            The cartesian coordinate of the sphere's center when placing it in
            the scene. If more than one location is passed, then that many
            widgets will be added and the callback will also be passed the
            integer index of that widget.

        radius : float, optional
            The radius of the sphere.

        theta_resolution : int, optional
            Set the number of points in the longitude direction.

        phi_resolution : int, optional
            Set the number of points in the latitude direction.

        color : ColorLike, optional
            The color of the sphere's surface.  If multiple centers
            are passed, then this must be a list of colors.  Each
            color is either a string, rgb list, or hex color string.
            For example:

            * ``color='white'``
            * ``color='w'``
            * ``color=[1.0, 1.0, 1.0]``
            * ``color='#FFFFFF'``

        style : str, optional
            Representation style: ``'surface'`` or ``'wireframe'``.

        selected_color : ColorLike, optional
            Color of the widget when selected during interaction.

        indices : sequence[int], optional
            Indices to assign the sphere widgets.

        pass_widget : bool, optional
            If ``True``, the widget will be passed as the last
            argument of the callback.

        test_callback : bool, optional
            If ``True``, run the callback function after the widget is
            created.

        interaction_event : vtk.vtkCommand.EventIds, optional
            The VTK interaction event to use for triggering the callback.

        Returns
        -------
        vtk.vtkSphereWidget
            The sphere widget.

        """
        if color is None:
            color = pyvista.global_theme.color.float_rgb
        selected_color = Color(selected_color)

        center = np.array(center)
        num = 1
        if center.ndim > 1:
            num = len(center)

        if isinstance(color, (list, tuple, np.ndarray)):
            if len(color) == num and not isinstance(color[0], float):
                colors = color
            else:
                colors = [color] * num
        else:
            colors = [color] * num

        def _the_callback(widget, event_id):
            point = widget.GetCenter()
            index = widget.WIDGET_INDEX
            if callable(callback):
                if num > 1:
                    args = [point, index]
                else:
                    args = [point]
                if pass_widget:
                    args.append(widget)
                try_callback(callback, *args)
            return

        if indices is None:
            indices = [x for x in range(num)]

        for i in range(num):
            if center.ndim > 1:
                loc = center[i]
            else:
                loc = center
            sphere_widget = _vtk.vtkSphereWidget()
            sphere_widget.WIDGET_INDEX = indices[i]  # Monkey patch the index
            if style in "wireframe":
                sphere_widget.SetRepresentationToWireframe()
            else:
                sphere_widget.SetRepresentationToSurface()
            sphere_widget.GetSphereProperty().SetColor(Color(colors[i]).float_rgb)
            sphere_widget.GetSelectedSphereProperty().SetColor(selected_color.float_rgb)
            sphere_widget.SetInteractor(self.iren.interactor)
            sphere_widget.SetCurrentRenderer(self.renderer)
            sphere_widget.SetRadius(radius)
            sphere_widget.SetCenter(loc)
            sphere_widget.SetThetaResolution(theta_resolution)
            sphere_widget.SetPhiResolution(phi_resolution)
            sphere_widget.Modified()
            sphere_widget.On()
            sphere_widget.AddObserver(interaction_event, _the_callback)
            self.sphere_widgets.append(sphere_widget)

        if test_callback is True:
            # Test call back in the last
            _the_callback(sphere_widget, None)
        if num > 1:
            return self.sphere_widgets

        return sphere_widget

    def clear_sphere_widgets(self):
        """Remove all of the sphere widgets."""
        self.sphere_widgets.clear()

    def add_checkbox_button_widget(
        self,
        callback,
        value=False,
        position=(10.0, 10.0),
        size=50,
        border_size=5,
        color_on='blue',
        color_off='grey',
        background_color='white',
    ):
        """Add a checkbox button widget to the scene.

        This is useless without a callback function. You can pass a callable
        function that takes a single argument, the state of this button widget
        and performs a task with that value.

        Parameters
        ----------
        callback : callable
            The method called every time the button is clicked. This should take
            a single parameter: the bool value of the button.

        value : bool, default: False
            The default state of the button.

        position : sequence[float], default: (10.0, 10.0)
            The absolute coordinates of the bottom left point of the button.

        size : int, default: 50
            The size of the button in number of pixels.

        border_size : int, default: 5
            The size of the borders of the button in pixels.

        color_on : ColorLike, optional
            The color used when the button is checked. Default is ``'blue'``.

        color_off : ColorLike, optional
            The color used when the button is not checked. Default is ``'grey'``.

        background_color : ColorLike, optional
            The background color of the button. Default is ``'white'``.

        Returns
        -------
        vtk.vtkButtonWidget
            The VTK button widget configured as a checkbox button.

        Examples
        --------
        The following example generates a static image of the widget.

        >>> import pyvista as pv
        >>> mesh = pv.Sphere()
        >>> p = pv.Plotter()
        >>> actor = p.add_mesh(mesh)
        >>> def toggle_vis(flag):
        ...     actor.SetVisibility(flag)
        ...
        >>> _ = p.add_checkbox_button_widget(toggle_vis, value=True)
        >>> p.show()

        Download the interactive example at :ref:`checkbox_widget_example`.

        """
        if self.iren is None:  # pragma: no cover
            raise RuntimeError('Cannot add a widget to a closed plotter.')

        def create_button(color1, color2, color3, dims=(size, size, 1)):
            color1 = np.array(Color(color1).int_rgb)
            color2 = np.array(Color(color2).int_rgb)
            color3 = np.array(Color(color3).int_rgb)

            n_points = dims[0] * dims[1]
            button = pyvista.UniformGrid(dimensions=dims)
            arr = np.array([color1] * n_points).reshape(dims[0], dims[1], 3)  # fill with color1
            arr[1 : dims[0] - 1, 1 : dims[1] - 1] = color2  # apply color2
            arr[
                border_size : dims[0] - border_size, border_size : dims[1] - border_size
            ] = color3  # apply color3
            button.point_data['texture'] = arr.reshape(n_points, 3).astype(np.uint8)
            return button

        button_on = create_button(color_on, background_color, color_on)
        button_off = create_button(color_on, background_color, color_off)

        bounds = [position[0], position[0] + size, position[1], position[1] + size, 0.0, 0.0]

        button_rep = _vtk.vtkTexturedButtonRepresentation2D()
        button_rep.SetNumberOfStates(2)
        button_rep.SetState(value)
        button_rep.SetButtonTexture(0, button_off)
        button_rep.SetButtonTexture(1, button_on)
        button_rep.SetPlaceFactor(1)
        button_rep.PlaceWidget(bounds)

        button_widget = _vtk.vtkButtonWidget()
        button_widget.SetInteractor(self.iren.interactor)
        button_widget.SetRepresentation(button_rep)
        button_widget.SetCurrentRenderer(self.renderer)
        button_widget.On()

        def _the_callback(widget, event):
            state = widget.GetRepresentation().GetState()
            if callable(callback):
                try_callback(callback, bool(state))

        button_widget.AddObserver(_vtk.vtkCommand.StateChangedEvent, _the_callback)
        self.button_widgets.append(button_widget)
        return button_widget

    def add_camera_orientation_widget(self, animate=True, n_frames=20):
        """Add a camera orientation widget to the active renderer.

        .. note::
           This widget requires ``vtk>=9.1.0``.

        Parameters
        ----------
        animate : bool, default: True
            Enable or disable jump-to-axis-view animation.

        n_frames : int, default: 20
            The number of frames to animate the jump-to-axis-viewpoint feature.

        Returns
        -------
        vtkCameraOrientationWidget
            Camera orientation widget.

        Examples
        --------
        Add a camera orientation widget to the scene.

        >>> import pyvista
        >>> mesh = pyvista.Cube()
        >>> plotter = pyvista.Plotter()
        >>> _ = plotter.add_mesh(
        ...     mesh, scalars=range(6), show_scalar_bar=False
        ... )
        >>> _ = plotter.add_camera_orientation_widget()
        >>> plotter.show()

        """
        try:
            from vtkmodules.vtkInteractionWidgets import vtkCameraOrientationWidget
        except ImportError:  # pragma: no cover
            from pyvista.core.errors import VTKVersionError

            raise VTKVersionError('vtkCameraOrientationWidget requires vtk>=9.1.0')

        widget = vtkCameraOrientationWidget()
        widget.SetParentRenderer(self.renderer)
        widget.SetAnimate(animate)
        widget.SetAnimatorTotalFrames(n_frames)
        widget.On()
        self.camera_widgets.append(widget)
        return widget

    def clear_camera_widgets(self):
        """Remove all of the camera widgets."""
        self.camera_widgets.clear()

    def clear_button_widgets(self):
        """Remove all of the button widgets."""
        self.button_widgets.clear()

    def close(self):
        """Close the widgets."""
        self.clear_box_widgets()
        self.clear_plane_widgets()
        self.clear_line_widgets()
        self.clear_slider_widgets()
        self.clear_sphere_widgets()
        self.clear_spline_widgets()
        self.clear_button_widgets()
        self.clear_camera_widgets()


# pyvista/trame/__init__.py

"""Trame interface for PyVista."""
from pyvista.trame.jupyter import launch_server, show_trame, elegantly_launch
from pyvista.trame.ui import get_or_create_viewer, plotter_ui
from pyvista.trame.views import PyVistaLocalView, PyVistaRemoteLocalView, PyVistaRemoteView


# __all__ only left for mypy --strict to work when pyvista is a dependency
__all__ = [
    'elegantly_launch',
    'get_or_create_viewer',
    'launch_server',
    'plotter_ui',
    'show_trame',
    'PyVistaLocalView',
    'PyVistaRemoteLocalView',
    'PyVistaRemoteView',
]


# pyvista/trame/jupyter.py

"""Trame utilities for running in Jupyter."""
import asyncio
import logging
import os
import warnings

from trame.app import get_server
from trame.ui.vuetify import VAppLayout
from trame.widgets import html as html_widgets, vtk as vtk_widgets, vuetify as vuetify_widgets

try:
    from ipywidgets.widgets import HTML
except ImportError:
    HTML = object


import pyvista
from pyvista.trame.ui import UI_TITLE, get_or_create_viewer
from pyvista.trame.views import CLOSED_PLOTTER_ERROR

SERVER_DOWN_MESSAGE = """Trame server has not launched.

You must start the trame server before attempting to `show()`
with PyVista.

You can use the following snippet to launch the server:

    from pyvista.trame.jupyter import launch_server
    await launch_server('{name}').ready

"""
JUPYTER_SERVER_DOWN_MESSAGE = """Trame server has not launched.

Prior to plotting, please make sure to run `set_jupyter_backend('trame')` when using the `'trame'`, `'server'`, or `'client'` Jupyter backends.

    import pyvista as pv
    pv.set_jupyter_backend('trame')

If this issue persists, please open an issue in PyVista: https://github.com/pyvista/pyvista/issues

"""

logger = logging.getLogger(__name__)


class TrameServerDownError(RuntimeError):
    """Exception when trame server is down for Jupyter."""

    def __init__(self, server_name):
        """Call the base class constructor with the custom message."""
        super().__init__(SERVER_DOWN_MESSAGE.format(name=server_name))


class TrameJupyterServerDownError(RuntimeError):
    """Exception when trame server is down for Jupyter."""

    def __init__(self):
        """Call the base class constructor with the custom message."""
        # Be incredibly verbose on how users should launch trame server
        # Both warn so it appears at top
        warnings.warn(JUPYTER_SERVER_DOWN_MESSAGE)
        # and Error
        super().__init__(JUPYTER_SERVER_DOWN_MESSAGE)


class Widget(HTML):
    """Custom HTML iframe widget for trame viewer."""

    def __init__(self, viewer, src, width, height, **kwargs):
        """Initialize."""
        if HTML is object:
            raise ImportError('Please install `ipywidgets`.')
        value = f"<iframe src='{src}' style='width: {width}; height: {height};'></iframe>"
        super().__init__(value, **kwargs)
        self._viewer = viewer
        self._src = src

    @property
    def viewer(self):
        """Get the associated viewer instance."""
        return self._viewer

    @property
    def src(self):
        """Get the src URL."""
        return self._src


def launch_server(server=None, port=None, host=None):
    """Launch a trame server for use with Jupyter.

    Parameters
    ----------
    server : str, optional
        By default this uses :attr:`pyvista.global_theme.trame.jupyter_server_name
        <pyvista.themes._TrameConfig.jupyter_server_name>`, which by default is
        set to ``'pyvista-jupyter'``.

        If a server name is given and such server is not available yet, it will
        be created otherwise the previously created instance will be returned.

    port : int, optional
        The port on which to bind the server. Defaults to 0 to automatically
        find an available port.

    host : str, optional
        The host name to bind the server to on launch. Server will bind to
        ``127.0.0.1`` by default unless user sets the environment variable ``TRAME_DEFAULT_HOST``.

    Returns
    -------
    trame_server.core.Server
        The launched Trame server. To ``await`` the launch, use the
        ``.ready`` future attribute on the server.

    """
    if server is None:
        server = pyvista.global_theme.trame.jupyter_server_name
    if isinstance(server, str):
        server = get_server(server)
    if port is None:
        port = pyvista.global_theme.trame.jupyter_server_port
    if host is None:
        # Default to `127.0.0.1` unless user sets TRAME_DEFAULT_HOST
        host = os.environ.get('TRAME_DEFAULT_HOST', '127.0.0.1')

    # Must enable all used modules
    html_widgets.initialize(server)
    vtk_widgets.initialize(server)
    vuetify_widgets.initialize(server)

    def on_ready(**_):
        logger.debug(f'Server ready: {server}')

    if server._running_stage == 0:
        server.controller.on_server_ready.add(on_ready)
        server.start(
            exec_mode='task',
            host=host,
            port=port,
            open_browser=False,
            show_connection_info=False,
            disable_logging=True,
            timeout=0,
        )
    # else, server is already running or launching
    return server


def build_url(
    _server,
    ui=None,
    server_proxy_enabled=None,
    server_proxy_prefix=None,
    host='localhost',
    protocol='http',
):
    """Build the URL for the iframe."""
    params = f'?ui={ui}&reconnect=auto' if ui else '?reconnect=auto'
    if server_proxy_enabled is None:
        server_proxy_enabled = pyvista.global_theme.trame.server_proxy_enabled
    if server_proxy_enabled:
        if server_proxy_prefix is None:
            server_proxy_prefix = pyvista.global_theme.trame.server_proxy_prefix
        # server_proxy_prefix assumes trailing slash
        src = (
            f"{server_proxy_prefix if server_proxy_prefix else ''}{_server.port}/index.html{params}"
        )
    else:
        src = f'{protocol}://{host}:{_server.port}/index.html{params}'
    logger.debug(src)
    return src


def initialize(
    server, plotter, mode=None, default_server_rendering=True, collapse_menu=False, **kwargs
):
    """Generate the UI for a given plotter."""
    state = server.state
    state.trame__title = UI_TITLE

    viewer = get_or_create_viewer(plotter, suppress_rendering=mode == 'client')

    with VAppLayout(server, template_name=plotter._id_name):
        viewer.ui(
            mode=mode,
            default_server_rendering=default_server_rendering,
            collapse_menu=collapse_menu,
            **kwargs,
        )

    return viewer


def show_trame(
    plotter,
    mode=None,
    name=None,
    server_proxy_enabled=None,
    server_proxy_prefix=None,
    collapse_menu=False,
    add_menu=True,
    default_server_rendering=True,
    handler=None,
    **kwargs,
):
    """Run and display the trame application in jupyter's event loop.

    Parameters
    ----------
    plotter : pyvista.Plotter
        The PyVista plotter to show.

    mode : str, optional
        The UI view mode. This can be set on the global theme. Options are:

        * ``'trame'``: Uses a view that can switch between client and server
          rendering modes.
        * ``'server'``: Uses a view that is purely server rendering.
        * ``'client'``: Uses a view that is purely client rendering (generally
          safe without a virtual frame buffer)

    name : str, optional
        The name of the trame server on which the UI is defined.

    server_proxy_enabled : bool, default: False
        Build a relative URL for use with ``jupyter-server-proxy``.

    server_proxy_prefix : str, optional
        URL prefix when using ``server_proxy_enabled``. This can be set
        globally in the theme. To ignore, pass ``False``. For use with
        ``jupyter-server-proxy``, often set to ``proxy/``.

    collapse_menu : bool, default: False
        Collapse the UI menu (camera controls, etc.) on start.

    add_menu : bool, default: True
        Add a UI controls VCard to the VContainer.

    default_server_rendering : bool, default: True
        Whether to use server-side or client-side rendering on-start when
        using the ``'trame'`` mode.

    handler : callable, optional
        Pass a callable that accptes the viewer instance, the string URL,
        and ``**kwargs`` to create custom HTML representations of the output.

        .. code:: python

            import pyvista as pv
            from IPython.display import IFrame

            mesh = pv.Wavelet()


            def handler(viewer, src, **kwargs):
                return IFrame(src, '75%', '500px')


            p = pv.Plotter(notebook=True)
            _ = p.add_mesh(mesh)
            iframe = p.show(
                jupyter_backend='trame',
                jupyter_kwargs=dict(handler=handler),
                return_viewer=True,
            )
            iframe

    **kwargs : dict, optional
        Mostly ignored, though ``protocol`` and ``host`` can be use to
        override the iframe src url and ``height`` and ``width`` can be
        used to override the iframe style. Remaining kwargs are passed to
        ``ipywidgets.widgets.HTML``.

    Returns
    -------
    ipywidgets.widgets.HTML or handler result
        Returns a HTML IFrame widget or the result of the passed handler.

    """
    if plotter.render_window is None:
        raise RuntimeError(CLOSED_PLOTTER_ERROR)

    if name is None:
        server = get_server(name=pyvista.global_theme.trame.jupyter_server_name)
    else:
        server = get_server(name=name)
    if name is None and not server.running:
        elegantly_launch(server)
        if not server.running:
            raise TrameJupyterServerDownError()
    elif not server.running:
        raise TrameServerDownError(name)

    # Initialize app
    viewer = initialize(
        server,
        plotter,
        mode=mode,
        default_server_rendering=default_server_rendering,
        collapse_menu=collapse_menu,
        add_menu=add_menu,
    )

    # Show as cell result
    src = build_url(
        server,
        ui=plotter._id_name,
        server_proxy_enabled=server_proxy_enabled,
        server_proxy_prefix=server_proxy_prefix,
        host=kwargs.get('host', 'localhost'),
        protocol=kwargs.get('protocol', 'http'),
    )

    if plotter._window_size_unset:
        dw, dh = '99%', '600px'
    else:
        dw, dh = plotter.window_size
        dw = f'{dw}px'
        dh = f'{dh}px'
    kwargs.setdefault('width', dw)
    kwargs.setdefault('height', dh)

    if callable(handler):
        return handler(viewer, src, **kwargs)
    return Widget(viewer, src, **kwargs)


def elegantly_launch(*args, **kwargs):
    """Elegantly launch the Trame server without await.

    This provides a mechanism to launch the Trame Jupyter backend in
    a way that does not require users to await the call.

    This is a thin wrapper of
    :func:`launch_server() <pyvista.trame.jupyter.launch_server>`.

    Returns
    -------
    trame_server.core.Server
        The launched trame server.

    Warnings
    --------
    This uses `nest_asyncio <https://github.com/erdewit/nest_asyncio>`_ which
    patches the standard lib `asyncio` package and may have unintended
    consequences for some uses cases. We advise strongly to make sure PyVista's
    Jupyter backend is not set to use Trame when not in a Jupyter environment.

    """
    try:
        import nest_asyncio
    except ImportError:
        raise ImportError(
            """Please install `nest_asyncio` to automagically launch the trame server without await. Or, to avoid `nest_asynctio` run:

    from pyvista.trame.jupyter import launch_server
    await launch_server().ready
"""
        )

    async def launch_it():
        await launch_server(*args, **kwargs).ready

    # Basically monkey patches asyncio to support this
    nest_asyncio.apply()

    return asyncio.run(launch_it())


# pyvista/trame/ui.py

# flake8: noqa: D102,D103,D107
"""PyVista Trame User Interface.

This module builds a base UI for manipulating a PyVista Plotter.
The UI generated here is the default for rendering in Jupyter
environments and provides a starting point for custom user-built
applications.
"""
import io

from trame.widgets import html, vuetify

import pyvista
from pyvista.trame.views import PyVistaLocalView, PyVistaRemoteLocalView, PyVistaRemoteView

UI_TITLE = 'PyVista'

VALID_UI_MODES = [
    'trame',
    'client',
    'server',
]

_VIEWERS = {}


def button(click, icon, tooltip):
    """Create a vuetify button."""
    with vuetify.VTooltip(bottom=True):
        with vuetify.Template(v_slot_activator='{ on, attrs }'):
            with vuetify.VBtn(icon=True, v_bind='attrs', v_on='on', click=click):
                vuetify.VIcon(icon)
        html.Span(tooltip)


def checkbox(model, icons, tooltip):
    """Create a vuetify checkbox."""
    with vuetify.VTooltip(bottom=True):
        with vuetify.Template(v_slot_activator='{ on, attrs }'):
            with html.Div(v_on='on', v_bind='attrs'):
                vuetify.VCheckbox(
                    v_model=model,
                    on_icon=icons[0],
                    off_icon=icons[1],
                    dense=True,
                    hide_details=True,
                    classes='my-0 py-0 ml-1',
                )
        html.Span(tooltip)


class Viewer:
    """Internal wrapper to sync trame view with Plotter."""

    def __init__(self, plotter, suppress_rendering=False):
        """Initialize Viewer."""
        if plotter._id_name in _VIEWERS:
            raise RuntimeError('A viewer instance already exists for this Plotter.')
        _VIEWERS[plotter._id_name] = self
        self._html_views = set()

        self.plotter = plotter
        self.plotter.suppress_rendering = suppress_rendering

        # State variable names
        self.SHOW_UI = f'{plotter._id_name}_show_ui'
        self.GRID = f'{plotter._id_name}_grid_visibility'
        self.OUTLINE = f'{plotter._id_name}_outline_visibility'
        self.EDGES = f'{plotter._id_name}_edge_visibility'
        self.AXIS = f'{plotter._id_name}_axis_visiblity'
        self.SERVER_RENDERING = f'{plotter._id_name}_use_server_rendering'

    @property
    def views(self):
        """Get a set of all associate trame views for this viewer."""
        return self._html_views

    def update(self, **kwargs):
        """Update all associated views.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        for view in self._html_views:
            view.update()

    def push_camera(self, **kwargs):
        """Push camera to all associated views.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        for view in self._html_views:
            view.push_camera()

    def reset_camera(self, **kwargs):
        """Reset camera for all associated views.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        for view in self._html_views:
            view.reset_camera()

    def update_image(self, **kwargs):
        """Update image for all associated views.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        for view in self._html_views:
            view.update_image()

    def update_camera(self, **kwargs):
        """Update image and camera for all associated views.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        for view in self._html_views:
            view.update_camera()

    def view_isometric(self):
        """View isometric."""
        self.plotter.view_isometric(render=False)
        self.update_camera()

    def view_yz(self):
        """View YZ plane."""
        self.plotter.view_yz(render=False)
        self.update_camera()

    def view_xz(self):
        """View XZ plane."""
        self.plotter.view_xz(render=False)
        self.update_camera()

    def view_xy(self):
        """View XY plane."""
        self.plotter.view_xy(render=False)
        self.update_camera()

    def on_edge_visiblity_change(self, **kwargs):
        """Toggle edge visibility for all actors.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        value = kwargs[self.EDGES]
        for renderer in self.plotter.renderers:
            for _, actor in renderer.actors.items():
                if isinstance(actor, pyvista.Actor):
                    actor.prop.show_edges = value
        self.update()

    def on_grid_visiblity_change(self, **kwargs):
        """Handle axes grid visibility.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        value = kwargs[self.GRID]
        for renderer in self.plotter.renderers:
            if value:
                renderer.show_grid()
            else:
                renderer.remove_bounds_axes()
        self.update()

    def on_outline_visiblity_change(self, **kwargs):
        """Handle outline visibility.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        value = kwargs[self.OUTLINE]
        for renderer in self.plotter.renderers:
            if value:
                renderer.add_bounding_box(reset_camera=False)
            else:
                renderer.remove_bounding_box()
        self.update()

    def on_axis_visiblity_change(self, **kwargs):
        """Handle outline visibility.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        value = kwargs[self.AXIS]
        for renderer in self.plotter.renderers:
            if value:
                renderer.show_axes()
            else:
                renderer.hide_axes()
        self.update()

    def on_rendering_mode_change(self, **kwargs):
        """Handle any configurations when the render mode changes between client and server.

        Parameters
        ----------
        **kwargs : dict, optional
            Unused keyword arguments.

        """
        if not kwargs[self.SERVER_RENDERING]:
            self.update_camera()

    @property
    def actors(self):
        """Get dataset actors."""
        return {k: v for k, v in self.plotter.actors.items() if isinstance(v, pyvista.Actor)}

    def screenshot(self):
        """Take screenshot and add attachament.

        Returns
        -------
        memoryview
            Screenshot as a ``memoryview``.

        """
        self.plotter.render()
        self.update()  # makes sure the plotter and views are in sync
        buffer = io.BytesIO()
        self.plotter.screenshot(filename=buffer)
        buffer.seek(0)
        return memoryview(buffer.read())

    def ui_controls(self, mode=None, default_server_rendering=True, v_show=None):
        """Create a VRow for the UI controls.

        Parameters
        ----------
        mode : str, default: 'trame'
            The UI view mode. Options are:

            * ``'trame'``: Uses a view that can switch between client and server
              rendering modes.
            * ``'server'``: Uses a view that is purely server rendering.
            * ``'client'``: Uses a view that is purely client rendering (generally
              safe without a virtual frame buffer)

        default_server_rendering : bool, default: True
            Whether to use server-side or client-side rendering on-start when
            using the ``'trame'`` mode.

        v_show : bool, optional
            Conditionally show the viewer controls.

        """
        if mode is None:
            mode = self.plotter._theme.trame.default_mode
        if mode not in VALID_UI_MODES:
            raise ValueError(f'`{mode}` is not a valid mode choice. Use one of: {VALID_UI_MODES}')
        if mode != 'trame':
            default_server_rendering = mode == 'server'

        with vuetify.VRow(
            v_show=v_show,
            classes='pa-0 ma-0 align-center',
        ) as row:
            server = row.server
            # Listen to state changes
            server.state.change(self.EDGES)(self.on_edge_visiblity_change)
            server.state.change(self.GRID)(self.on_grid_visiblity_change)
            server.state.change(self.OUTLINE)(self.on_outline_visiblity_change)
            server.state.change(self.AXIS)(self.on_axis_visiblity_change)
            server.state.change(self.SERVER_RENDERING)(self.on_rendering_mode_change)
            vuetify.VDivider(vertical=True, classes='mr-1')
            button(
                click=self.reset_camera,
                icon='mdi-arrow-expand-all',
                tooltip='Reset Camera',
            )
            vuetify.VDivider(vertical=True, classes='mx-1')
            button(
                click=self.view_isometric,
                icon='mdi-axis-arrow',
                tooltip='Perspective view',
            )
            button(
                click=self.view_yz,
                icon='mdi-axis-x-arrow',
                tooltip='Reset Camera X',
            )
            button(
                click=self.view_xz,
                icon='mdi-axis-y-arrow',
                tooltip='Reset Camera Y',
            )
            button(
                click=self.view_xy,
                icon='mdi-axis-z-arrow',
                tooltip='Reset Camera Z',
            )
            vuetify.VDivider(vertical=True, classes='mx-1')
            checkbox(
                model=(self.EDGES, False),
                icons=('mdi-grid', 'mdi-grid-off'),
                tooltip=f"Toggle edge visibility ({{{{ {self.EDGES} ? 'on' : 'off' }}}})",
            )
            checkbox(
                model=(self.OUTLINE, False),
                icons=('mdi-cube', 'mdi-cube-off'),
                tooltip=f"Toggle bounding box ({{{{ {self.OUTLINE} ? 'on' : 'off' }}}})",
            )
            checkbox(
                model=(self.GRID, False),
                icons=('mdi-ruler-square', 'mdi-ruler-square'),
                tooltip=f"Toggle ruler ({{{{ {self.GRID} ? 'on' : 'off' }}}})",
            )
            checkbox(
                model=(self.AXIS, False),
                icons=('mdi-axis-arrow-info', 'mdi-axis-arrow-info'),
                tooltip=f"Toggle axis ({{{{ {self.AXIS} ? 'on' : 'off' }}}})",
            )
            # Server rendering options
            if mode == 'trame':
                vuetify.VDivider(vertical=True, classes='mx-1')
                checkbox(
                    model=(self.SERVER_RENDERING, default_server_rendering),
                    icons=('mdi-dns', 'mdi-open-in-app'),
                    tooltip=f"Toggle rendering mode ({{{{ {self.SERVER_RENDERING} ? 'remote' : 'local' }}}})",
                )
            with vuetify.VRow(
                v_show=(self.SERVER_RENDERING, default_server_rendering),
                classes='pa-0 ma-0 align-center',
            ):

                def attach_screenshot():
                    return server.protocol.addAttachment(self.screenshot())

                button(
                    # Must use single-quote string for JS here
                    click=f"utils.download('screenshot.png', trigger('{server.trigger_name(attach_screenshot)}'), 'image/png')",
                    icon='mdi-file-png-box',
                    tooltip='Save screenshot',
                )

    def ui(
        self,
        mode=None,
        default_server_rendering=True,
        collapse_menu=False,
        add_menu=True,
        **kwargs,
    ):
        """Generate VContainer for PyVista Plotter.

        Parameters
        ----------
        mode : str, default: 'trame'
            The UI view mode. Options are:

            * ``'trame'``: Uses a view that can switch between client and server
              rendering modes.
            * ``'server'``: Uses a view that is purely server rendering.
            * ``'client'``: Uses a view that is purely client rendering (generally
              safe without a virtual frame buffer)

        default_server_rendering : bool, default: True
            Whether to use server-side or client-side rendering on-start when
            using the ``'trame'`` mode.

        collapse_menu : bool, default: False
            Collapse the UI menu (camera controls, etc.) on start.

        add_menu : bool, default: True
            Add a UI controls VCard to the VContainer.

        **kwargs : dict, optional
            Additional keyword arguments are passed to the view being created.

        Returns
        -------
        PyVistaRemoteLocalView, PyVistaRemoteView, or PyVistaLocalView
            Trame view interface for pyvista.

        """
        if mode is None:
            mode = self.plotter._theme.trame.default_mode
        if mode not in VALID_UI_MODES:
            raise ValueError(f'`{mode}` is not a valid mode choice. Use one of: {VALID_UI_MODES}')
        if mode != 'trame':
            default_server_rendering = mode == 'server'

        with vuetify.VContainer(
            fluid=True,
            classes='pa-0 fill-height',
        ) as container:
            server = container.server
            # Initialize state variables
            server.state[self.EDGES] = False
            server.state[self.GRID] = self.plotter.renderer.cube_axes_actor is not None
            server.state[self.OUTLINE] = hasattr(self.plotter.renderer, '_box_object')
            server.state[self.AXIS] = (
                hasattr(self.plotter.renderer, 'axes_widget')
                and self.plotter.renderer.axes_widget.GetEnabled()
            )
            server.state[self.SERVER_RENDERING] = default_server_rendering
            if add_menu:
                server.state[self.SHOW_UI] = not collapse_menu
                with vuetify.VCard(
                    style='position: absolute; top: 20px; left: 20px; z-index: 1; height: 36px;',
                    classes=(f"{{ 'rounded-circle': !{self.SHOW_UI} }}",),
                ):
                    with vuetify.VRow(classes='pa-0 ma-0') as row:
                        button(
                            click=f'{self.SHOW_UI}=!{self.SHOW_UI}',
                            icon='mdi-dots-vertical',
                            tooltip=f"{{{{ {self.SHOW_UI} ? 'Hide' : 'Show' }}}} menu",
                        )
                        self.ui_controls(
                            mode=mode,
                            default_server_rendering=default_server_rendering,
                            v_show=(f'{self.SHOW_UI}',),
                        )
            if mode == 'trame':
                view = PyVistaRemoteLocalView(
                    self.plotter,
                    mode=(
                        # Must use single-quote string for JS here
                        f"{self.SERVER_RENDERING} ? 'remote' : 'local'",
                        'remote' if default_server_rendering else 'local',
                    ),
                    **kwargs,
                )
            elif mode == 'server':
                view = PyVistaRemoteView(self.plotter, **kwargs)
            elif mode == 'client':
                view = PyVistaLocalView(self.plotter, **kwargs)

            self._html_views.add(view)

        return view


def get_or_create_viewer(plotter, suppress_rendering=False):
    """Get or create a Viewer instance for a given Plotter.

    There should be only one Viewer instance per plotter. A Viewer
    can have multiple UI views though.

    Parameters
    ----------
    plotter : pyvista.Plotter
        Plotter to return or create the viewer instance for.

    suppress_rendering : bool, default: False
        Suppress rendering on the plotter.

    Returns
    -------
    pyvista.trame.ui.Viewer
        Trame viewer.

    """
    if plotter._id_name in _VIEWERS:
        viewer = _VIEWERS[plotter._id_name]
        if suppress_rendering != plotter.suppress_rendering:
            plotter.suppress_rendering = suppress_rendering
            # TODO: warn user?
        return viewer
    return Viewer(plotter, suppress_rendering=suppress_rendering)


def plotter_ui(
    plotter, mode=None, default_server_rendering=True, collapse_menu=False, add_menu=True, **kwargs
):
    """Create a UI view for the given Plotter.

    Parameters
    ----------
    plotter : pyvista.Plotter
        Plotter to create the UI for.

    mode : str, default: 'trame'
        The UI view mode. Options are:

        * ``'trame'``: Uses a view that can switch between client and server
          rendering modes.
        * ``'server'``: Uses a view that is purely server rendering.
        * ``'client'``: Uses a view that is purely client rendering (generally
          safe without a virtual frame buffer)

    default_server_rendering : bool, default: True
        Whether to use server-side or client-side rendering on-start when
        using the ``'trame'`` mode.

    collapse_menu : bool, default: False
        Collapse the UI menu (camera controls, etc.) on start.

    add_menu : bool, default: True
        Add a UI controls VCard to the VContainer.

    **kwargs : dict, optional
        Additional keyword arguments are passed to the viewer being created.

    Returns
    -------
    PyVistaRemoteLocalView, PyVistaRemoteView, or PyVistaLocalView
        Trame view interface for pyvista.

    """
    viewer = get_or_create_viewer(plotter, suppress_rendering=mode == 'client')
    return viewer.ui(
        mode=mode,
        default_server_rendering=default_server_rendering,
        collapse_menu=collapse_menu,
        add_menu=add_menu,
        **kwargs,
    )


# pyvista/trame/views.py

"""Trame view interface for PyVista."""
import weakref

from trame.widgets.vtk import VtkLocalView, VtkRemoteLocalView, VtkRemoteView

CLOSED_PLOTTER_ERROR = "The render window for this plotter has been destroyed. Do not call `show()` for the plotter before passing to trame."


class _BasePyVistaView:
    def __init__(self, plotter):
        self._plotter = weakref.ref(plotter)
        self.pyvista_initialize()

    def pyvista_initialize(self):
        if self._plotter().render_window is None:
            raise RuntimeError(CLOSED_PLOTTER_ERROR)
        for renderer in self._plotter().renderers:
            if not renderer.camera.is_set:
                renderer.camera_position = renderer.get_default_cam_pos()
                renderer.ResetCamera()

    def _post_initialize(self):
        if self._server.running:
            self.update()
        else:
            self._server.controller.on_server_ready.add(self.update)

        # Callback to sync view on PyVista's render call when renders are suppressed
        self._plotter().add_on_render_callback(lambda *args: self.update(), render_event=False)

    def update_camera(self):
        """Update camera or push the image."""
        self.push_camera()
        self.update_image()


class PyVistaRemoteView(VtkRemoteView, _BasePyVistaView):
    """PyVista wrapping of trame ``VtkRemoteView`` for server rendering.

    This will connect to a PyVista plotter and stream the server-side
    renderings.

    Parameters
    ----------
    plotter : pyvista.Plotter
        The PyVista Plotter to display in the output view.

    interactive_ratio : int, optional
        Image size scale factor while interacting. Increasing this
        value will give higher resulotuion images during interaction
        events at the cost of performance. Use lower values (e.g.,
        ``0.5``) to increase performance while interacting.
        Defaults to 1.

    still_ratio : int, optional
        Image size scale factor while not interacting (still).
        Increasing this value will give higher resulotuion images
        when not interacting with the scene. Defaults to 1.

    namespace : str, optional
        The namespace for this view component. A default value is
        chosen based on the ``_id_name`` of the plotter.

    **kwargs : dict, optional
        Any additional keyword arguments to pass to
        ``trame.widgets.vtk.VtkRemoteView``.

    Notes
    -----
    For optimal rendering results, you may want to have the same
    value for ``interactive_ratio`` and ``still_ratio`` so that
    the entire rendering is not re-scaled between interaction events.

    """

    def __init__(self, plotter, interactive_ratio=None, still_ratio=None, namespace=None, **kwargs):
        """Create a trame remote view from a PyVista Plotter."""
        _BasePyVistaView.__init__(self, plotter)
        if namespace is None:
            namespace = f'{plotter._id_name}'
        if interactive_ratio is None:
            interactive_ratio = plotter._theme.trame.interactive_ratio
        if still_ratio is None:
            still_ratio = plotter._theme.trame.still_ratio
        VtkRemoteView.__init__(
            self,
            self._plotter().render_window,
            interactive_ratio=interactive_ratio,
            still_ratio=still_ratio,
            __properties=[('still_ratio', 'stillRatio')],
            ref=f'view_{plotter._id_name}',
            namespace=namespace,
            **kwargs,
        )
        self._post_initialize()

    def push_camera(self, *args, **kwargs):
        """No-op implementation to match local viewers."""
        pass  # pragma: no cover

    def update_image(self, *args, **kwargs):
        """Wrap update call."""
        return self.update(*args, **kwargs)


class PyVistaLocalView(VtkLocalView, _BasePyVistaView):
    """PyVista wrapping of trame VtkLocalView for in-browser rendering.

    This will connect to and synchronize with a PyVista plotter to
    perform client-side rendering with VTK.js in the browser.

    Parameters
    ----------
    plotter : pyvista.Plotter
        The PyVista Plotter to represent in the output view.

    namespace : str, optional
        The namespace for this view component. A default value is
        chosen based on the ``_id_name`` of the plotter.

    **kwargs : dict, optional
        Any additional keyword arguments to pass to
        ``trame.widgets.vtk.VtkLocalView``.

    """

    def __init__(self, plotter, namespace=None, **kwargs):
        """Create a trame local view from a PyVista Plotter."""
        _BasePyVistaView.__init__(self, plotter)
        if namespace is None:
            namespace = f'{plotter._id_name}'
        VtkLocalView.__init__(
            self,
            self._plotter().render_window,
            ref=f'view_{plotter._id_name}',
            namespace=namespace,
            **kwargs,
        )
        self._post_initialize()

    def update_image(self, *args, **kwargs):
        """No-op implementation to match remote viewers."""
        pass  # pragma: no cover


class PyVistaRemoteLocalView(VtkRemoteLocalView, _BasePyVistaView):
    """PyVista wrapping of trame ``VtkRemoteLocalView``.

    Dynamically switch between client and server rendering.

    Parameters
    ----------
    plotter : pyvista.Plotter
        The PyVista Plotter to display in the output view.

    interactive_ratio : int, optional
        Image size scale factor while interacting. Increasing this
        value will give higher resulotuion images during interaction
        events at the cost of performance. Use lower values (e.g.,
        ``0.5``) to increase performance while interacting.
        Defaults to 1. This is only valid in the ``'remote'`` mode.

    still_ratio : int, optional
        Image size scale factor while not interacting (still).
        Increasing this value will give higher resulotuion images
        when not interacting with the scene. Defaults to 1.
        This is only valid in the ``'remote'`` mode.

    namespace : str, optional
        The namespace for this view component. A default value is
        chosen based on the ``_id_name`` of the plotter.

    **kwargs : dict, optional
        Any additional keyword arguments to pass to
        ``trame.widgets.vtk.VtkRemoteLocalView``.

    """

    def __init__(self, plotter, interactive_ratio=None, still_ratio=None, namespace=None, **kwargs):
        """Create a trame remote/local view from a PyVista Plotter."""
        _BasePyVistaView.__init__(self, plotter)
        if namespace is None:
            namespace = f'{plotter._id_name}'
        if interactive_ratio is None:
            interactive_ratio = plotter._theme.trame.interactive_ratio
        if still_ratio is None:
            still_ratio = plotter._theme.trame.still_ratio
        VtkRemoteLocalView.__init__(
            self,
            self._plotter().render_window,
            interactive_ratio=interactive_ratio,
            still_ratio=still_ratio,
            __properties=[('still_ratio', 'stillRatio')],
            ref=f'view_{plotter._id_name}',
            namespace=namespace,
            **kwargs,
        )
        # Track namespace for our use since trame attributes are name mangled
        self._namespace = namespace

        self._post_initialize()


# pyvista/utilities/__init__.py

"""Utilities routines."""
from .algorithms import algorithm_to_mesh_handler, set_algorithm_input
from .common import perlin_noise, sample_function
from .errors import (
    GPUInfo,
    Observer,
    Report,
    assert_empty_kwargs,
    get_gpu_info,
    send_errors_to_logging,
    set_error_output_file,
    check_valid_vector,
    VtkErrorCatcher,
)
from .features import *
from .fileio import *
from .geometric_objects import *
from .helpers import *
from .parametric_objects import *
from .sphinx_gallery import Scraper, _get_sg_image_scraper
from .regression import compare_images
from . import transformations
from .xvfb import start_xvfb
from .reader import (
    get_reader,
    AVSucdReader,
    BaseReader,
    BinaryMarchingCubesReader,
    BMPReader,
    BYUReader,
    CGNSReader,
    DEMReader,
    EnSightReader,
    FacetReader,
    FluentReader,
    GIFReader,
    GLTFReader,
    HDFReader,
    HDRReader,
    JPEGReader,
    MetaImageReader,
    MFIXReader,
    MultiBlockPlot3DReader,
    NIFTIReader,
    NRRDReader,
    OBJReader,
    OpenFOAMReader,
    POpenFOAMReader,
    Plot3DFunctionEnum,
    Plot3DMetaReader,
    PLYReader,
    PNGReader,
    PNMReader,
    PointCellDataSelection,
    PTSReader,
    PVDDataSet,
    PVDReader,
    SegYReader,
    SLCReader,
    STLReader,
    TecplotReader,
    TIFFReader,
    TimeReader,
    VTKDataSetReader,
    VTKPDataSetReader,
    XMLImageDataReader,
    XMLPImageDataReader,
    XMLRectilinearGridReader,
    XMLPRectilinearGridReader,
    XMLUnstructuredGridReader,
    XMLPUnstructuredGridReader,
    XMLPolyDataReader,
    XMLStructuredGridReader,
    XMLMultiBlockDataReader,
    DICOMReader,
    XdmfReader,
)


# setup.py

"""See pyproject.toml for project metadata."""
from setuptools import setup

setup()


# pyvista/__init__.py

"""PyVista package for 3D plotting and mesh analysis."""

MAX_N_COLOR_BARS = 10

from typing import Optional
import warnings
import os

from pyvista._version import __version__
from pyvista.plotting import *
from pyvista.utilities import *
from pyvista.core import *
from pyvista.utilities.misc import (
    _get_vtk_id_type,
    vtk_version_info,
    _set_plot_theme_from_env,
    set_pickle_format,
)
from pyvista import _vtk
from pyvista.jupyter import set_jupyter_backend
from pyvista.themes import set_plot_theme, load_theme, _rcParams
from pyvista.themes import DefaultTheme as _GlobalTheme  # hide this

# Per contract with Sphinx-Gallery, this method must be available at top level
from pyvista.utilities.sphinx_gallery import _get_sg_image_scraper

from pyvista.utilities.wrappers import _wrappers

global_theme = _GlobalTheme()
rcParams = _rcParams()  # raises DeprecationError when used

# Set preferred plot theme
_set_plot_theme_from_env()

# get the int type from vtk
ID_TYPE = _get_vtk_id_type()

# determine if using at least vtk 9.0.0
if vtk_version_info.major < 9:  # pragma: no cover
    from pyvista.core.errors import VTKVersionError

    raise VTKVersionError('VTK version must be 9.0.0 or greater.')

# catch annoying numpy/vtk future warning:
warnings.simplefilter(action='ignore', category=FutureWarning)

# A simple flag to set when generating the documentation
OFF_SCREEN = os.environ.get("PYVISTA_OFF_SCREEN", "false").lower() == "true"

# flag for when building the sphinx_gallery
BUILDING_GALLERY = False
if 'PYVISTA_BUILDING_GALLERY' in os.environ:
    if os.environ['PYVISTA_BUILDING_GALLERY'].lower() == 'true':
        BUILDING_GALLERY = True

# A threshold for the max cells to compute a volume for when repr-ing
REPR_VOLUME_MAX_CELLS = 1e6

# Set where figures are saved
FIGURE_PATH = None

# Send VTK messages to the logging module:
send_errors_to_logging()

# theme to use by default for the plot directive
PLOT_DIRECTIVE_THEME = None

# Set a parameter to control default print format for floats outside
# of the plotter
FLOAT_FORMAT = "{:.3e}"

# Serialization format to be used when pickling `DataObject`
PICKLE_FORMAT = 'xml'

# Name used for unnamed scalars
DEFAULT_SCALARS_NAME = 'Data'


# pyvista/_version.py

"""Version info for pyvista.

On the ``main`` branch, use 'dev0' to denote a development version.
For example:

version_info = 0, 27, 'dev0'

When generating pre-release wheels, use '0rcN', for example:

version_info = 0, 28, '0rc1'

Denotes the first release candidate.

"""
# major, minor, patch
version_info = 0, 40, 'dev0'

# Nice string for the version
__version__ = '.'.join(map(str, version_info))


# pyvista/conftest.py

"""Close all plotters to help control memory usage for our doctests."""

import pytest

import pyvista


@pytest.fixture(autouse=True)
def autoclose_plotters():
    """Close all plotters."""
    yield
    pyvista.close_all()


@pytest.fixture(autouse=True)
def reset_gloal_theme():
    """Reset global_theme."""
    # this stops any doctest-module tests from overriding the global theme and
    # creating test side effects
    yield
    pyvista.global_theme.restore_defaults()


# pyvista/errors.py

"""PyVista specific errors."""


class MissingDataError(ValueError):
    """Exception when data is missing, e.g. no active scalars can be set."""

    def __init__(self, message='No data available.'):
        """Call the base class constructor with the custom message."""
        super().__init__(message)


class AmbiguousDataError(ValueError):
    """Exception when data is ambiguous, e.g. multiple active scalars can be set."""

    def __init__(self, message="Multiple data available."):
        """Call the base class constructor with the custom message."""
        super().__init__(message)


class PyVistaPipelineError(RuntimeError):
    """Exception when a VTK pipeline runs into an issue."""

    def __init__(self, message="VTK pipeline issue detected by PyVista."):
        """Call the base class constructor with the custom message."""
        super().__init__(message)


class RenderWindowUnavailable(RuntimeError):
    """Exception when the render window is not available."""

    def __init__(self, message="Render window is not available."):
        """Call the base class constructor with the custom message."""
        super().__init__(message)


# pyvista/themes.py

"""API description for managing plotting theme parameters in pyvista.

Examples
--------
Apply a built-in theme

>>> import pyvista as pv
>>> pv.set_plot_theme('default')
>>> pv.set_plot_theme('document')
>>> pv.set_plot_theme('dark')
>>> pv.set_plot_theme('paraview')

Load a theme into pyvista

>>> from pyvista.themes import DefaultTheme
>>> theme = DefaultTheme()
>>> theme.save('my_theme.json')  # doctest:+SKIP
>>> loaded_theme = pv.load_theme('my_theme.json')  # doctest:+SKIP

Create a custom theme from the default theme and load it into
pyvista.

>>> my_theme = DefaultTheme()
>>> my_theme.font.size = 20
>>> my_theme.font.title_size = 40
>>> my_theme.cmap = 'jet'
>>> pv.global_theme.load_theme(my_theme)
>>> pv.global_theme.font.size
20

"""

from enum import Enum
import json
import os
from typing import Callable, List, Optional, Union
import warnings

from ._typing import ColorLike, Number
from .plotting.colors import Color, get_cmap_safe, get_cycler
from .plotting.opts import InterpolationType
from .plotting.plotting import Plotter
from .plotting.tools import parse_font_family
from .utilities.misc import PyVistaDeprecationWarning, _check_range


class _rcParams(dict):  # pragma: no cover
    """Reference to the deprecated rcParams dictionary."""

    def __getitem__(self, key):
        import pyvista  # avoids circular import

        warnings.warn(
            'rcParams is deprecated.  Please use ``pyvista.global_theme``.', DeprecationWarning
        )
        return getattr(pyvista.global_theme, key)

    def __setitem__(self, key, value):
        import pyvista  # avoids circular import

        warnings.warn(
            'rcParams is deprecated.  Please use ``pyvista.global_theme``.', DeprecationWarning
        )
        setattr(pyvista.global_theme, key, value)

    def __repr__(self):
        """Use the repr of global_theme."""
        import pyvista  # avoids circular import

        warnings.warn(
            'rcParams is deprecated.  Please use ``pyvista.global_theme``', DeprecationWarning
        )
        return repr(pyvista.global_theme)


def load_theme(filename):
    """Load a theme from a file.

    Parameters
    ----------
    filename : str
        Theme file. Must be json.

    Examples
    --------
    >>> import pyvista as pv
    >>> from pyvista.themes import DefaultTheme
    >>> theme = DefaultTheme()
    >>> theme.save('my_theme.json')  # doctest:+SKIP
    >>> loaded_theme = pv.load_theme('my_theme.json')  # doctest:+SKIP

    """
    with open(filename) as f:
        theme_dict = json.load(f)
    return DefaultTheme.from_dict(theme_dict)


def set_plot_theme(theme):
    """Set the plotting parameters to a predefined theme using a string.

    Parameters
    ----------
    theme : str
        Theme name.  Either ``'default'``, ``'document'``, ``'dark'``,
        or ``'paraview'``.

    Examples
    --------
    Set to the default theme.

    >>> import pyvista as pv
    >>> pv.set_plot_theme('default')

    Set to the document theme.

    >>> pv.set_plot_theme('document')

    Set to the dark theme.

    >>> pv.set_plot_theme('dark')

    Set to the ParaView theme.

    >>> pv.set_plot_theme('paraview')

    """
    import pyvista

    if isinstance(theme, str):
        theme = theme.lower()
        try:
            new_theme_type = _NATIVE_THEMES[theme].value
        except KeyError:
            raise ValueError(f"Theme {theme} not found in PyVista's native themes.")
        pyvista.global_theme.load_theme(new_theme_type())
    elif isinstance(theme, DefaultTheme):
        pyvista.global_theme.load_theme(theme)
    else:
        raise TypeError(
            f'Expected a ``pyvista.themes.DefaultTheme`` or ``str``, not '
            f'a {type(theme).__name__}'
        )


class _ThemeConfig:
    """Provide common methods for theme configuration classes."""

    __slots__: List[str] = []

    @classmethod
    def from_dict(cls, dict_):
        """Create from a dictionary."""
        inst = cls()
        for key, value in dict_.items():
            attr = getattr(inst, key)
            if hasattr(attr, 'from_dict'):
                setattr(inst, key, attr.from_dict(value))
            else:
                setattr(inst, key, value)
        return inst

    def to_dict(self) -> dict:
        """Return theme config parameters as a dictionary.

        Returns
        -------
        dict
            This theme parameter represented as a dictionary.

        """
        # remove the first underscore in each entry
        dict_ = {}
        for key in self.__slots__:
            value = getattr(self, key)
            key = key[1:]
            if hasattr(value, 'to_dict'):
                dict_[key] = value.to_dict()
            else:
                dict_[key] = value
        return dict_

    def __eq__(self, other):
        if not isinstance(self, type(other)):
            return False

        for attr_name in other.__slots__:
            attr = getattr(self, attr_name)
            other_attr = getattr(other, attr_name)
            if isinstance(attr, (tuple, list)):
                if tuple(attr) != tuple(other_attr):
                    return False
            else:
                if not attr == other_attr:
                    return False

        return True

    def __getitem__(self, key):
        """Get a value via a key.

        Implemented here for backwards compatibility.
        """
        return getattr(self, key)

    def __setitem__(self, key, value):
        """Set a value via a key.

        Implemented here for backwards compatibility.
        """
        setattr(self, key, value)


class _LightingConfig(_ThemeConfig):
    """PyVista lighting configuration.

    This will control the lighting interpolation type, parameters,
    and Physically Based Rendering (PBR) options

    Examples
    --------
    Set global PBR parameters.

    >>> import pyvista as pv
    >>> pv.global_theme.lighting_params.interpolation = 'pbr'
    >>> pv.global_theme.lighting_params.metallic = 0.5
    >>> pv.global_theme.lighting_params.roughness = 0.25

    """

    __slots__ = [
        '_interpolation',
        '_metallic',
        '_roughness',
        '_ambient',
        '_diffuse',
        '_specular',
        '_specular_power',
        '_emissive',
    ]

    def __init__(self):
        self._interpolation = InterpolationType.FLAT.value
        self._metallic = 0.0
        self._roughness = 0.5
        self._ambient = 0.0
        self._diffuse = 1.0
        self._specular = 0.0
        self._specular_power = 100.0
        self._emissive = False

    @property
    def interpolation(self) -> InterpolationType:
        """Return or set the default interpolation type.

        See :class:`pyvista.plotting.opts.InterpolationType`.

        Options are:

        * ``'Phong'``
        * ``'Flat'``
        * ``'Physically based rendering'``

        This is stored as an integer value of the ``InterpolationType``
        so that the theme can be JSON-serializable.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.lighting_params.interpolation = 'Phong'
        >>> pv.global_theme.lighting_params.interpolation
        <InterpolationType.PHONG: 2>


        """
        return InterpolationType.from_any(self._interpolation)

    @interpolation.setter
    def interpolation(self, interpolation: Union[str, int, InterpolationType]):
        self._interpolation = InterpolationType.from_any(interpolation).value

    @property
    def metallic(self) -> float:
        """Return or set the metallic value.

        This requires that the interpolation be set to ``'Physically based
        rendering'``. Must be between 0 and 1.

        Examples
        --------
        Set the global metallic value used in physically based rendering to
        ``0.5``.

        >>> import pyvista as pv
        >>> pv.global_theme.lighting_params.metallic = 0.5
        >>> pv.global_theme.lighting_params.metallic
        0.5

        """
        return self._metallic

    @metallic.setter
    def metallic(self, metallic: float):
        _check_range(metallic, (0, 1), 'metallic')
        self._metallic = metallic

    @property
    def roughness(self) -> float:
        """Return or set the roughness value.

        This value has to be between 0 (glossy) and 1 (rough). A glossy
        material has reflections and a high specular part. This parameter is
        only used by PBR interpolation.

        Examples
        --------
        Set the global roughness value used in physically based rendering to
        ``0.25``.

        >>> import pyvista as pv
        >>> pv.global_theme.lighting_params.roughness = 0.25
        >>> pv.global_theme.lighting_params.roughness
        0.25

        """
        return self._roughness

    @roughness.setter
    def roughness(self, roughness: float):
        _check_range(roughness, (0, 1), 'roughness')
        self._roughness = roughness

    @property
    def ambient(self) -> float:
        """Return or set the ambient value.

        When lighting is enabled, this is the amount of light in the range of 0
        to 1 that reaches the actor when not directed at the light source
        emitted from the viewer.

        Examples
        --------
        Set the global ambient lighting value to ``0.2``.

        >>> import pyvista as pv
        >>> pv.global_theme.lighting_params.ambient = 0.2
        >>> pv.global_theme.lighting_params.ambient
        0.2

        """
        return self._ambient

    @ambient.setter
    def ambient(self, ambient: float):
        _check_range(ambient, (0, 1), 'ambient')
        self._ambient = ambient

    @property
    def diffuse(self) -> float:
        """Return or set the diffuse value.

        This is the scattering of light by reflection or
        transmission. Diffuse reflection results when light strikes an
        irregular surface such as a frosted window or the surface of a
        frosted or coated light bulb. Must be between 0 and 1.

        Examples
        --------
        Set the global diffuse lighting value to ``0.5``.

        >>> import pyvista as pv
        >>> pv.global_theme.lighting_params.diffuse = 0.5
        >>> pv.global_theme.lighting_params.diffuse
        0.5

        """
        return self._diffuse

    @diffuse.setter
    def diffuse(self, diffuse: float):
        _check_range(diffuse, (0, 1), 'diffuse')
        self._diffuse = diffuse

    @property
    def specular(self) -> float:
        """Return or set the specular value.

        Specular lighting simulates the bright spot of a light that appears
        on shiny objects. Must be between 0 and 1.

        Examples
        --------
        Set the global specular value to ``0.1``.

        >>> import pyvista as pv
        >>> pv.global_theme.lighting_params.specular = 0.1
        >>> pv.global_theme.lighting_params.specular
        0.1

        """
        return self._specular

    @specular.setter
    def specular(self, specular: float):
        _check_range(specular, (0, 1), 'specular')
        self._specular = specular

    @property
    def specular_power(self) -> float:
        """Return or set the specular power value.

        Must be between 0.0 and 128.0.

        Examples
        --------
        Set the global specular power value to ``50``.

        >>> import pyvista as pv
        >>> pv.global_theme.lighting_params.specular_power = 50
        >>> pv.global_theme.lighting_params.specular_power
        50

        """
        return self._specular_power

    @specular_power.setter
    def specular_power(self, specular_power: float):
        _check_range(specular_power, (0, 128), 'specular_power')
        self._specular_power = specular_power

    @property
    def emissive(self) -> bool:
        """Return or set if emissive is used with point Gaussian style.

        Examples
        --------
        Globally enable emissive lighting when using the point Gaussian style.

        >>> import pyvista as pv
        >>> pv.global_theme.lighting_params.emissive = True
        >>> pv.global_theme.lighting_params.emissive
        True

        """
        return self._emissive

    @emissive.setter
    def emissive(self, emissive: bool):
        self._emissive = bool(emissive)


class _DepthPeelingConfig(_ThemeConfig):
    """PyVista depth peeling configuration.

    Examples
    --------
    Set global depth peeling parameters.

    >>> import pyvista as pv
    >>> pv.global_theme.depth_peeling.number_of_peels = 1
    >>> pv.global_theme.depth_peeling.occlusion_ratio = 0.0
    >>> pv.global_theme.depth_peeling.enabled = True

    """

    __slots__ = ['_number_of_peels', '_occlusion_ratio', '_enabled']

    def __init__(self):
        self._number_of_peels = 4
        self._occlusion_ratio = 0.0
        self._enabled = False

    @property
    def number_of_peels(self) -> int:
        """Return or set the number of peels in depth peeling.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.depth_peeling.number_of_peels = 1

        """
        return self._number_of_peels

    @number_of_peels.setter
    def number_of_peels(self, number_of_peels: int):
        self._number_of_peels = int(number_of_peels)

    @property
    def occlusion_ratio(self) -> float:
        """Return or set the occlusion ratio in depth peeling.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.depth_peeling.occlusion_ratio = 0.0

        """
        return self._occlusion_ratio

    @occlusion_ratio.setter
    def occlusion_ratio(self, occlusion_ratio: float):
        self._occlusion_ratio = float(occlusion_ratio)

    @property
    def enabled(self) -> bool:
        """Return or set if depth peeling is enabled.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.depth_peeling.enabled = True

        """
        return self._enabled

    @enabled.setter
    def enabled(self, enabled: bool):
        self._enabled = bool(enabled)

    def __repr__(self):
        txt = ['']
        parm = {
            'Number': 'number_of_peels',
            'Occlusion ratio': 'occlusion_ratio',
            'Enabled': 'enabled',
        }
        for name, attr in parm.items():
            setting = getattr(self, attr)
            txt.append(f'    {name:<21}: {setting}')
        return '\n'.join(txt)


class _SilhouetteConfig(_ThemeConfig):
    """PyVista silhouette configuration.

    Examples
    --------
    Set global silhouette parameters.

    >>> import pyvista as pv
    >>> pv.global_theme.silhouette.enabled = True
    >>> pv.global_theme.silhouette.color = 'grey'
    >>> pv.global_theme.silhouette.line_width = 2
    >>> pv.global_theme.silhouette.feature_angle = 20

    """

    __slots__ = ['_color', '_line_width', '_opacity', '_feature_angle', '_decimate', '_enabled']

    def __init__(self):
        self._color = Color('black')
        self._line_width = 2
        self._opacity = 1.0
        self._feature_angle = None
        self._decimate = None
        self._enabled = False

    @property
    def enabled(self) -> bool:
        """Return or set whether silhouette is on or off."""
        return self._enabled

    @enabled.setter
    def enabled(self, enabled: bool):
        self._enabled = bool(enabled)

    @property
    def color(self) -> Color:
        """Return or set the silhouette color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.silhouette.color = 'red'

        """
        return self._color

    @color.setter
    def color(self, color: ColorLike):
        self._color = Color(color)

    @property
    def line_width(self) -> float:
        """Return or set the silhouette line width.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.silhouette.line_width = 2.0

        """
        return self._line_width

    @line_width.setter
    def line_width(self, line_width: float):
        self._line_width = float(line_width)

    @property
    def opacity(self) -> float:
        """Return or set the silhouette opacity.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.silhouette.opacity = 1.0

        """
        return self._opacity

    @opacity.setter
    def opacity(self, opacity: float):
        _check_range(opacity, (0, 1), 'opacity')
        self._opacity = float(opacity)

    @property
    def feature_angle(self) -> Union[float, None]:
        """Return or set the silhouette feature angle.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.silhouette.feature_angle = 20.0

        """
        return self._feature_angle

    @feature_angle.setter
    def feature_angle(self, feature_angle: Union[float, None]):
        self._feature_angle = feature_angle

    @property
    def decimate(self) -> float:
        """Return or set the amount to decimate the silhouette.

        Parameter must be between 0 and 1.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.silhouette.decimate = 0.9

        """
        return self._decimate

    @decimate.setter
    def decimate(self, decimate: float):
        if decimate is None:
            self._decimate = None
        else:
            _check_range(decimate, (0, 1), 'decimate')
            self._decimate = float(decimate)

    def __repr__(self):
        txt = ['']
        parm = {
            'Color': 'color',
            'Line width': 'line_width',
            'Opacity': 'opacity',
            'Feature angle': 'feature_angle',
            'Decimate': 'decimate',
        }
        for name, attr in parm.items():
            setting = getattr(self, attr)
            txt.append(f'    {name:<21}: {setting}')
        return '\n'.join(txt)


class _ColorbarConfig(_ThemeConfig):
    """PyVista colorbar configuration.

    Examples
    --------
    Set the colorbar width.

    >>> import pyvista as pv
    >>> pv.global_theme.colorbar_horizontal.width = 0.2

    """

    __slots__ = ['_width', '_height', '_position_x', '_position_y']

    def __init__(self):
        self._width = None
        self._height = None
        self._position_x = None
        self._position_y = None

    @property
    def width(self) -> float:
        """Return or set colorbar width.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.colorbar_horizontal.width = 0.2

        """
        return self._width

    @width.setter
    def width(self, width: float):
        self._width = float(width)

    @property
    def height(self) -> float:
        """Return or set colorbar height.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.colorbar_horizontal.height = 0.2

        """
        return self._height

    @height.setter
    def height(self, height: float):
        self._height = float(height)

    @property
    def position_x(self) -> float:
        """Return or set colorbar x position.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.colorbar_horizontal.position_x = 0.2

        """
        return self._position_x

    @position_x.setter
    def position_x(self, position_x: float):
        self._position_x = float(position_x)

    @property
    def position_y(self) -> float:
        """Return or set colorbar y position.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.colorbar_horizontal.position_y = 0.2

        """
        return self._position_y

    @position_y.setter
    def position_y(self, position_y: float):
        self._position_y = float(position_y)

    def __repr__(self):
        txt = ['']
        parm = {
            'Width': 'width',
            'Height': 'height',
            'X Position': 'position_x',
            'Y Position': 'position_y',
        }
        for name, attr in parm.items():
            setting = getattr(self, attr)
            txt.append(f'    {name:<21}: {setting}')

        return '\n'.join(txt)


class _AxesConfig(_ThemeConfig):
    """PyVista axes configuration.

    Examples
    --------
    Set the x axis color to black.

    >>> import pyvista as pv
    >>> pv.global_theme.axes.x_color = 'black'

    Show axes by default.

    >>> pv.global_theme.axes.show = True

    Use the ``vtk.vtkCubeAxesActor``.

    >>> pv.global_theme.axes.box = True

    """

    __slots__ = ['_x_color', '_y_color', '_z_color', '_box', '_show']

    def __init__(self):
        self._x_color = Color('tomato')
        self._y_color = Color('seagreen')
        self._z_color = Color('mediumblue')
        self._box = False
        self._show = True

    def __repr__(self):
        txt = ['Axes configuration']
        parm = {
            'X Color': 'x_color',
            'Y Color': 'y_color',
            'Z Color': 'z_color',
            'Use Box': 'box',
            'Show': 'show',
        }
        for name, attr in parm.items():
            setting = getattr(self, attr)
            txt.append(f'    {name:<21}: {setting}')

        return '\n'.join(txt)

    @property
    def x_color(self) -> Color:
        """Return or set x axis color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.axes.x_color = 'red'
        """
        return self._x_color

    @x_color.setter
    def x_color(self, color: ColorLike):
        self._x_color = Color(color)

    @property
    def y_color(self) -> Color:
        """Return or set y axis color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.axes.y_color = 'red'
        """
        return self._y_color

    @y_color.setter
    def y_color(self, color: ColorLike):
        self._y_color = Color(color)

    @property
    def z_color(self) -> Color:
        """Return or set z axis color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.axes.z_color = 'red'
        """
        return self._z_color

    @z_color.setter
    def z_color(self, color: ColorLike):
        self._z_color = Color(color)

    @property
    def box(self) -> bool:
        """Use the ``vtk.vtkCubeAxesActor`` instead of the default ``vtk.vtkAxesActor``.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.axes.box = True

        """
        return self._box

    @box.setter
    def box(self, box: bool):
        self._box = bool(box)

    @property
    def show(self) -> bool:
        """Show or hide the axes actor.

        Examples
        --------
        Hide the axes by default.

        >>> import pyvista as pv
        >>> pv.global_theme.axes.show = False

        """
        return self._show

    @show.setter
    def show(self, show: bool):
        self._show = bool(show)


class _Font(_ThemeConfig):
    """PyVista plotter font configuration.

    Examples
    --------
    Set the default font family to 'arial'.  Must be either
    'arial', 'courier', or 'times'.

    >>> import pyvista as pv
    >>> pv.global_theme.font.family = 'arial'

    Set the default font size to 20.

    >>> pv.global_theme.font.size = 20

    Set the default title size to 40

    >>> pv.global_theme.font.title_size = 40

    Set the default label size to 10

    >>> pv.global_theme.font.label_size = 10

    Set the default text color to 'grey'

    >>> pv.global_theme.font.color = 'grey'

    Set the string formatter used to format numerical data to '%.6e'

    >>> pv.global_theme.font.fmt = '%.6e'

    """

    __slots__ = ['_family', '_size', '_title_size', '_label_size', '_color', '_fmt']

    def __init__(self):
        self._family = 'arial'
        self._size = 12
        self._title_size = None
        self._label_size = None
        self._color = Color('white')
        self._fmt = None

    def __repr__(self):
        txt = ['']
        parm = {
            'Family': 'family',
            'Size': 'size',
            'Title size': 'title_size',
            'Label size': 'label_size',
            'Color': 'color',
            'Float format': 'fmt',
        }
        for name, attr in parm.items():
            setting = getattr(self, attr)
            txt.append(f'    {name:<21}: {setting}')

        return '\n'.join(txt)

    @property
    def family(self) -> str:
        """Return or set the font family.

        Must be one of the following:

        * ``"arial"``
        * ``"courier"``
        * ``"times"``

        Examples
        --------
        Set the default global font family to 'courier'.

        >>> import pyvista as pv
        >>> pv.global_theme.font.family = 'courier'

        """
        return self._family

    @family.setter
    def family(self, family: str):
        parse_font_family(family)  # check valid font
        self._family = family

    @property
    def size(self) -> int:
        """Return or set the font size.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.font.size = 20

        """
        return self._size

    @size.setter
    def size(self, size: int):
        self._size = int(size)

    @property
    def title_size(self) -> int:
        """Return or set the title size.

        If ``None``, then VTK uses ``UnconstrainedFontSizeOn`` for titles.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.font.title_size = 20
        """
        return self._title_size

    @title_size.setter
    def title_size(self, title_size: int):
        if title_size is None:
            self._title_size = None
        else:
            self._title_size = int(title_size)

    @property
    def label_size(self) -> int:
        """Return or set the label size.

        If ``None``, then VTK uses ``UnconstrainedFontSizeOn`` for labels.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.font.label_size = 20
        """
        return self._label_size

    @label_size.setter
    def label_size(self, label_size: int):
        if label_size is None:
            self._label_size = None
        else:
            self._label_size = int(label_size)

    @property
    def color(self) -> Color:
        """Return or set the font color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.font.color = 'black'
        """
        return self._color

    @color.setter
    def color(self, color: ColorLike):
        self._color = Color(color)

    @property
    def fmt(self) -> str:
        """Return or set the string formatter used to format numerical data.

        Examples
        --------
        Set the string formatter used to format numerical data to '%.6e'.

        >>> import pyvista as pv
        >>> pv.global_theme.font.fmt = '%.6e'

        """
        return self._fmt

    @fmt.setter
    def fmt(self, fmt: str):
        self._fmt = fmt


class _SliderStyleConfig(_ThemeConfig):
    """PyVista configuration for a single slider style."""

    __slots__ = [
        '_name',
        '_slider_length',
        '_slider_width',
        '_slider_color',
        '_tube_width',
        '_tube_color',
        '_cap_opacity',
        '_cap_length',
        '_cap_width',
    ]

    def __init__(self):
        """Initialize the slider style configuration."""
        self._name = None
        self._slider_length = None
        self._slider_width = None
        self._slider_color = None
        self._tube_width = None
        self._tube_color = None
        self._cap_opacity = None
        self._cap_length = None
        self._cap_width = None

    @property
    def name(self) -> str:
        """Return the name of the slider style configuration."""
        return self._name

    @name.setter
    def name(self, name: str):
        self._name = name

    @property
    def cap_width(self) -> float:
        """Return or set the cap width.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.slider_styles.modern.cap_width = 0.02

        """
        return self._cap_width

    @cap_width.setter
    def cap_width(self, cap_width: float):
        self._cap_width = float(cap_width)

    @property
    def cap_length(self) -> float:
        """Return or set the cap length.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.slider_styles.modern.cap_length = 0.01

        """
        return self._cap_length

    @cap_length.setter
    def cap_length(self, cap_length: float):
        self._cap_length = float(cap_length)

    @property
    def cap_opacity(self) -> float:
        """Return or set the cap opacity.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.slider_styles.modern.cap_opacity = 1.0

        """
        return self._cap_opacity

    @cap_opacity.setter
    def cap_opacity(self, cap_opacity: float):
        _check_range(cap_opacity, (0, 1), 'cap_opacity')
        self._cap_opacity = float(cap_opacity)

    @property
    def tube_color(self) -> Color:
        """Return or set the tube color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.slider_styles.modern.tube_color = 'black'
        """
        return self._tube_color

    @tube_color.setter
    def tube_color(self, tube_color: ColorLike):
        self._tube_color = Color(tube_color)

    @property
    def tube_width(self) -> float:
        """Return or set the tube_width.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.slider_styles.modern.tube_width = 0.005

        """
        return self._tube_width

    @tube_width.setter
    def tube_width(self, tube_width: float):
        self._tube_width = float(tube_width)

    @property
    def slider_color(self) -> Color:
        """Return or set the slider color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.slider_styles.modern.slider_color = 'grey'

        """
        return self._slider_color

    @slider_color.setter
    def slider_color(self, slider_color: ColorLike):
        self._slider_color = Color(slider_color)

    @property
    def slider_width(self) -> float:
        """Return or set the slider width.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.slider_styles.modern.slider_width = 0.04

        """
        return self._slider_width

    @slider_width.setter
    def slider_width(self, slider_width: float):
        self._slider_width = float(slider_width)

    @property
    def slider_length(self) -> float:
        """Return or set the slider_length.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.slider_styles.modern.slider_length = 0.02

        """
        return self._slider_length

    @slider_length.setter
    def slider_length(self, slider_length: float):
        self._slider_length = float(slider_length)

    def __repr__(self):
        txt = ['']
        parm = {
            'Slider length': 'slider_length',
            'Slider width': 'slider_width',
            'Slider color': 'slider_color',
            'Tube width': 'tube_width',
            'Tube color': 'tube_color',
            'Cap opacity': 'cap_opacity',
            'Cap length': 'cap_length',
            'Cap width': 'cap_width',
        }
        for name, attr in parm.items():
            setting = getattr(self, attr)
            txt.append(f'        {name:<17}: {setting}')
        return '\n'.join(txt)


class _SliderConfig(_ThemeConfig):
    """PyVista configuration encompassing all slider styles.

    Examples
    --------
    Set the classic slider configuration.

    >>> import pyvista as pv
    >>> slider_styles = pv.global_theme.slider_styles
    >>> slider_styles.classic.slider_length = 0.02
    >>> slider_styles.classic.slider_width = 0.04
    >>> slider_styles.classic.slider_color = (0.5, 0.5, 0.5)
    >>> slider_styles.classic.tube_width = 0.005
    >>> slider_styles.classic.tube_color = (1.0, 1.0, 1.0)
    >>> slider_styles.classic.cap_opacity = 1
    >>> slider_styles.classic.cap_length = 0.01
    >>> slider_styles.classic.cap_width = 0.02

    Set the modern slider configuration.

    >>> slider_styles.modern.slider_length = 0.02
    >>> slider_styles.modern.slider_width = 0.04
    >>> slider_styles.modern.slider_color = (0.43, 0.44, 0.45)
    >>> slider_styles.modern.tube_width = 0.04
    >>> slider_styles.modern.tube_color = (0.69, 0.70, 0.709)
    >>> slider_styles.modern.cap_opacity = 0
    >>> slider_styles.modern.cap_length = 0.01
    >>> slider_styles.modern.cap_width = 0.02

    """

    __slots__ = ['_classic', '_modern']

    def __init__(self):
        """Initialize the slider configuration."""
        self._classic = _SliderStyleConfig()
        self._classic.name = 'classic'
        self._classic.slider_length = 0.02
        self._classic.slider_width = 0.04
        self._classic.slider_color = 'gray'
        self._classic.tube_width = 0.005
        self._classic.tube_color = 'white'
        self._classic.cap_opacity = 1
        self._classic.cap_length = 0.01
        self._classic.cap_width = 0.02

        self._modern = _SliderStyleConfig()
        self._modern.name = 'modern'
        self._modern.slider_length = 0.02
        self._modern.slider_width = 0.04
        self._modern.slider_color = (110, 113, 117)
        self._modern.tube_width = 0.04
        self._modern.tube_color = (178, 179, 181)
        self._modern.cap_opacity = 0
        self._modern.cap_length = 0.01
        self._modern.cap_width = 0.02

    @property
    def classic(self) -> _SliderStyleConfig:
        """Return the Classic slider configuration."""
        return self._classic

    @classic.setter
    def classic(self, config: _SliderStyleConfig):
        if not isinstance(config, _SliderStyleConfig):
            raise TypeError('Configuration type must be `_SliderStyleConfig`')
        self._classic = config

    @property
    def modern(self) -> _SliderStyleConfig:
        """Return the Modern slider configuration."""
        return self._modern

    @modern.setter
    def modern(self, config: _SliderStyleConfig):
        if not isinstance(config, _SliderStyleConfig):
            raise TypeError('Configuration type must be `_SliderStyleConfig`')
        self._modern = config

    def __repr__(self):
        txt = ['']
        parm = {
            'Classic': 'classic',
            'Modern': 'modern',
        }
        for name, attr in parm.items():
            setting = getattr(self, attr)
            txt.append(f'    {name:<21}: {setting}')
        return '\n'.join(txt)

    def __iter__(self):
        for style in [self._classic, self._modern]:
            yield style.name


class _TrameConfig(_ThemeConfig):
    """PyVista Trame configuration.

    Examples
    --------
    Set global trame view parameters.

    >>> import pyvista as pv
    >>> pv.global_theme.trame.interactive_ratio = 2
    >>> pv.global_theme.trame.still_ratio = 2

    """

    __slots__ = [
        '_interactive_ratio',
        '_still_ratio',
        '_jupyter_server_name',
        '_jupyter_server_port',
        '_server_proxy_enabled',
        '_server_proxy_prefix',
        '_default_mode',
    ]

    def __init__(self):
        self._interactive_ratio = 1
        self._still_ratio = 1
        self._jupyter_server_name = 'pyvista-jupyter'
        self._jupyter_server_port = 0
        self._server_proxy_enabled = 'PYVISTA_TRAME_SERVER_PROXY_PREFIX' in os.environ
        # default for ``jupyter-server-proxy``
        service = os.environ.get('JUPYTERHUB_SERVICE_PREFIX', '')
        prefix = os.environ.get('PYVISTA_TRAME_SERVER_PROXY_PREFIX', '/proxy/')
        if service and not prefix.startswith('http'):  # pragma: no cover
            self._server_proxy_prefix = os.path.join(service, prefix.lstrip('/'))
        else:
            self._server_proxy_prefix = prefix
        self._default_mode = 'trame'

    @property
    def interactive_ratio(self) -> Number:
        """Return or set the interactive ratio for PyVista Trame views.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.trame.interactive_ratio = 2

        """
        return self._interactive_ratio

    @interactive_ratio.setter
    def interactive_ratio(self, interactive_ratio: Number):
        self._interactive_ratio = interactive_ratio

    @property
    def still_ratio(self) -> Number:
        """Return or set the still ratio for PyVista Trame views.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.trame.still_ratio = 2

        """
        return self._still_ratio

    @still_ratio.setter
    def still_ratio(self, still_ratio: Number):
        self._still_ratio = still_ratio

    @property
    def jupyter_server_name(self):
        """Return or set the trame server name PyVista uses in Jupyter.

        This defaults to ``'pyvista-jupyter'``.

        This must be set before running :func:`pyvista.set_jupyter_backend`
        to ensure a server of this name is launched.

        Most users should not need to modify this.

        """
        return self._jupyter_server_name

    @jupyter_server_name.setter
    def jupyter_server_name(self, name: str):
        self._jupyter_server_name = name

    @property
    def jupyter_server_port(self) -> int:
        """Return or set the port for the Trame Jupyter server."""
        return self._jupyter_server_port

    @jupyter_server_port.setter
    def jupyter_server_port(self, port: int):
        self._jupyter_server_port = port

    @property
    def server_proxy_enabled(self) -> bool:
        """Return or set if use of relative URLs is enabled for the Jupyter interface."""
        return self._server_proxy_enabled

    @server_proxy_enabled.setter
    def server_proxy_enabled(self, enabled: bool):
        self._server_proxy_enabled = bool(enabled)

    @property
    def server_proxy_prefix(self):
        """Return or set URL prefix when using relative URLs with the Jupyter interface."""
        return self._server_proxy_prefix

    @server_proxy_prefix.setter
    def server_proxy_prefix(self, prefix: str):
        self._server_proxy_prefix = prefix

    @property
    def default_mode(self):
        """Return or set the default mode of the Trame backend.

        * ``'trame'``: Uses a view that can switch between client and server
          rendering modes.
        * ``'server'``: Uses a view that is purely server rendering.
        * ``'client'``: Uses a view that is purely client rendering (generally
          safe without a virtual frame buffer)

        """
        return self._default_mode

    @default_mode.setter
    def default_mode(self, mode: str):
        self._default_mode = mode


class DefaultTheme(_ThemeConfig):
    """PyVista default theme.

    Examples
    --------
    Change the global default background color to white.

    >>> import pyvista as pv
    >>> pv.global_theme.color = 'white'

    Show edges by default.

    >>> pv.global_theme.show_edges = True

    Create a new theme from the default theme and apply it globally.

    >>> from pyvista.themes import DefaultTheme
    >>> my_theme = DefaultTheme()
    >>> my_theme.color = 'red'
    >>> my_theme.background = 'white'
    >>> pv.global_theme.load_theme(my_theme)

    """

    __slots__ = [
        '_name',
        '_background',
        '_jupyter_backend',
        '_trame',
        '_full_screen',
        '_window_size',
        '_image_scale',
        '_camera',
        '_notebook',
        '_font',
        '_auto_close',
        '_cmap',
        '_color',
        '_color_cycler',
        '_above_range_color',
        '_below_range_color',
        '_nan_color',
        '_edge_color',
        '_line_width',
        '_point_size',
        '_outline_color',
        '_floor_color',
        '_colorbar_orientation',
        '_colorbar_horizontal',
        '_colorbar_vertical',
        '_show_scalar_bar',
        '_show_edges',
        '_show_vertices',
        '_lighting',
        '_interactive',
        '_render_points_as_spheres',
        '_render_lines_as_tubes',
        '_transparent_background',
        '_title',
        '_axes',
        '_multi_samples',
        '_multi_rendering_splitting_position',
        '_volume_mapper',
        '_smooth_shading',
        '_depth_peeling',
        '_silhouette',
        '_slider_styles',
        '_return_cpos',
        '_hidden_line_removal',
        '_anti_aliasing',
        '_enable_camera_orientation_widget',
        '_split_sharp_edges',
        '_sharp_edges_feature_angle',
        '_before_close_callback',
        '_lighting_params',
        '_interpolate_before_map',
        '_opacity',
    ]

    def __init__(self):
        """Initialize the theme."""
        self._name = 'default'
        self._background = Color([0.3, 0.3, 0.3])
        self._full_screen = False
        self._camera = {
            'position': [1, 1, 1],
            'viewup': [0, 0, 1],
        }

        self._notebook = None
        self._window_size = [1024, 768]
        self._image_scale = 1
        self._font = _Font()
        self._cmap = 'viridis'
        self._color = Color('white')
        self._color_cycler = None
        self._nan_color = Color('darkgray')
        self._above_range_color = Color('grey')
        self._below_range_color = Color('grey')
        self._edge_color = Color('black')
        self._line_width = 1.0
        self._point_size = 5.0
        self._outline_color = Color('white')
        self._floor_color = Color('gray')
        self._colorbar_orientation = 'horizontal'

        self._colorbar_horizontal = _ColorbarConfig()
        self._colorbar_horizontal.width = 0.6
        self._colorbar_horizontal.height = 0.08
        self._colorbar_horizontal.position_x = 0.35
        self._colorbar_horizontal.position_y = 0.05

        self._colorbar_vertical = _ColorbarConfig()
        self._colorbar_vertical.width = 0.08
        self._colorbar_vertical.height = 0.45
        self._colorbar_vertical.position_x = 0.9
        self._colorbar_vertical.position_y = 0.02

        self._show_scalar_bar = True
        self._show_edges = False
        self._show_vertices = False
        self._lighting = True
        self._interactive = False
        self._render_points_as_spheres = False
        self._render_lines_as_tubes = False
        self._transparent_background = False
        self._title = 'PyVista'
        self._axes = _AxesConfig()
        self._split_sharp_edges = False
        self._sharp_edges_feature_angle = 30.0
        self._before_close_callback = None

        # Grab system flag for anti-aliasing
        try:
            self._multi_samples = int(os.environ.get('PYVISTA_MULTI_SAMPLES', 4))
        except ValueError:  # pragma: no cover
            self._multi_samples = 4

        # Grab system flag for auto-closing
        self._auto_close = os.environ.get('PYVISTA_AUTO_CLOSE', '').lower() != 'false'

        self._jupyter_backend = os.environ.get('PYVISTA_JUPYTER_BACKEND', 'trame')
        self._trame = _TrameConfig()

        self._multi_rendering_splitting_position = None
        self._volume_mapper = 'fixed_point' if os.name == 'nt' else 'smart'
        self._smooth_shading = False
        self._depth_peeling = _DepthPeelingConfig()
        self._silhouette = _SilhouetteConfig()
        self._slider_styles = _SliderConfig()
        self._return_cpos = True
        self._hidden_line_removal = False
        self._anti_aliasing = None
        self._enable_camera_orientation_widget = False

        self._lighting_params = _LightingConfig()
        self._interpolate_before_map = True
        self._opacity = 1.0

    @property
    def hidden_line_removal(self) -> bool:
        """Return or set hidden line removal.

        Wireframe geometry will be drawn using hidden line removal if
        the rendering engine supports it.

        See Also
        --------
        pyvista.Plotter.enable_hidden_line_removal

        Examples
        --------
        Enable hidden line removal.

        >>> import pyvista as pv
        >>> pv.global_theme.hidden_line_removal = True
        >>> pv.global_theme.hidden_line_removal
        True

        """
        return self._hidden_line_removal

    @hidden_line_removal.setter
    def hidden_line_removal(self, value: bool):
        self._hidden_line_removal = value

    @property
    def interpolate_before_map(self) -> bool:
        """Return or set whether to interpolate colors before mapping.

        If the ``interpolate_before_map`` is turned off, the color
        mapping occurs at polygon points and colors are interpolated,
        which is generally less accurate whereas if the
        ``interpolate_before_map`` is on (the default), then the scalars
        will be interpolated across the topology of the dataset which is
        more accurate.

        See also :ref:`interpolate_before_mapping_example`.

        Examples
        --------
        Enable hidden line removal.

        >>> import pyvista as pv

        Load a cylinder which has cells with a wide spread

        >>> cyl = pv.Cylinder(direction=(0, 0, 1), height=2).elevation()

        Common display argument to make sure all else is constant

        >>> dargs = dict(
        ...     scalars='Elevation', cmap='rainbow', show_edges=True
        ... )

        >>> p = pv.Plotter(shape=(1, 2))
        >>> _ = p.add_mesh(
        ...     cyl,
        ...     interpolate_before_map=False,
        ...     scalar_bar_args={'title': 'Elevation - interpolated'},
        ...     **dargs
        ... )
        >>> p.subplot(0, 1)
        >>> _ = p.add_mesh(
        ...     cyl,
        ...     interpolate_before_map=True,
        ...     scalar_bar_args={'title': 'Elevation - interpolated'},
        ...     **dargs
        ... )
        >>> p.link_views()
        >>> p.camera_position = [
        ...     (-1.67, -5.10, 2.06),
        ...     (0.0, 0.0, 0.0),
        ...     (0.00, 0.37, 0.93),
        ... ]
        >>> p.show()  # doctest: +SKIP

        """
        return self._interpolate_before_map

    @interpolate_before_map.setter
    def interpolate_before_map(self, value: bool):
        self._interpolate_before_map = value

    @property
    def opacity(self) -> float:
        """Return or set the opacity.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.opacity = 0.5

        """
        return self._opacity

    @opacity.setter
    def opacity(self, opacity: float):
        _check_range(opacity, (0, 1), 'opacity')
        self._opacity = float(opacity)

    @property
    def above_range_color(self) -> Color:
        """Return or set the default above range color.

        Examples
        --------
        Set the above range color to red.

        >>> import pyvista as pv
        >>> pv.global_theme.above_range_color = 'r'
        >>> pv.global_theme.above_range_color
        Color(name='red', hex='#ff0000ff', opacity=255)

        """
        return self._above_range_color

    @above_range_color.setter
    def above_range_color(self, value: ColorLike):
        self._above_range_color = Color(value)

    @property
    def below_range_color(self) -> Color:
        """Return or set the default below range color.

        Examples
        --------
        Set the below range color to blue.

        >>> import pyvista as pv
        >>> pv.global_theme.below_range_color = 'b'
        >>> pv.global_theme.below_range_color
        Color(name='blue', hex='#0000ffff', opacity=255)

        """
        return self._below_range_color

    @below_range_color.setter
    def below_range_color(self, value: ColorLike):
        self._below_range_color = Color(value)

    @property
    def return_cpos(self) -> bool:
        """Return or set the default behavior of returning the camera position.

        Examples
        --------
        Disable returning camera position by ``show`` and ``plot`` methods.

        >>> import pyvista as pv
        >>> pv.global_theme.return_cpos = False
        """
        return self._return_cpos

    @return_cpos.setter
    def return_cpos(self, value: bool):
        self._return_cpos = value

    @property
    def background(self) -> Color:
        """Return or set the default background color of pyvista plots.

        Examples
        --------
        Set the default global background of all plots to white.

        >>> import pyvista as pv
        >>> pv.global_theme.background = 'white'
        """
        return self._background

    @background.setter
    def background(self, new_background: ColorLike):
        self._background = Color(new_background)

    @property
    def jupyter_backend(self) -> str:
        """Return or set the jupyter notebook plotting backend.

        Jupyter backend to use when plotting.  Must be one of the
        following:

        * ``'ipyvtklink'`` : DEPRECATED. Render remotely and stream the
          resulting VTK images back to the client.  Supports all VTK
          methods, but suffers from lag due to remote rendering.
          Requires that a virtual framebuffer be set up when displaying
          on a headless server.  Must have ``ipyvtklink`` installed.

        * ``'panel'`` : Convert the VTK render window to a vtkjs
          object and then visualize that within jupyterlab. Supports
          most VTK objects.  Requires that a virtual framebuffer be
          set up when displaying on a headless server.  Must have
          ``panel`` installed.

        * ``'ipygany'`` : Convert all the meshes into ``ipygany``
          meshes and streams those to be rendered on the client side.
          Supports VTK meshes, but few others.  Aside from ``none``,
          this is the only method that does not require a virtual
          framebuffer.  Must have ``ipygany`` installed.

        * ``'pythreejs'`` : Convert all the meshes into ``pythreejs``
          meshes and streams those to be rendered on the client side.
          Aside from ``ipygany``, this is the only method that does
          not require a virtual framebuffer.  Must have ``pythreejs``
          installed.

        * ``'static'`` : Display a single static image within the
          JupyterLab environment.  Still requires that a virtual
          framebuffer be set up when displaying on a headless server,
          but does not require any additional modules to be installed.

        * ``'none'`` : Do not display any plots within jupyterlab,
          instead display using dedicated VTK render windows.  This
          will generate nothing on headless servers even with a
          virtual framebuffer.

        Examples
        --------
        Enable the pythreejs backend.

        >>> import pyvista as pv
        >>> pv.set_jupyter_backend('pythreejs')  # doctest:+SKIP

        Enable the ipygany backend.

        >>> pv.set_jupyter_backend('ipygany')  # doctest:+SKIP

        Enable the panel backend.

        >>> pv.set_jupyter_backend('panel')  # doctest:+SKIP

        Enable the ipyvtklink backend (DEPRECATED).

        >>> pv.set_jupyter_backend('ipyvtklink')  # doctest:+SKIP

        Just show static images.

        >>> pv.set_jupyter_backend('static')  # doctest:+SKIP

        Disable all plotting within JupyterLab and display using a
        standard desktop VTK render window.

        >>> pv.set_jupyter_backend(None)  # doctest:+SKIP

        """
        return self._jupyter_backend

    @jupyter_backend.setter
    def jupyter_backend(self, backend: 'str'):
        from pyvista.jupyter import _validate_jupyter_backend

        self._jupyter_backend = _validate_jupyter_backend(backend)

    @property
    def trame(self) -> _TrameConfig:
        """Return or set the default trame parameters."""
        return self._trame

    @trame.setter
    def trame(self, config: _TrameConfig):
        if not isinstance(config, _TrameConfig):
            raise TypeError('Configuration type must be `_TrameConfig`.')
        self._trame = config

    @property
    def auto_close(self) -> bool:
        """Automatically close the figures when finished plotting.

        .. DANGER::
           Set to ``False`` with extreme caution.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.auto_close = False

        """
        return self._auto_close

    @auto_close.setter
    def auto_close(self, value: bool):
        self._auto_close = value

    @property
    def full_screen(self) -> bool:
        """Return if figures are shown in full screen.

        Examples
        --------
        Set windows to be full screen by default.

        >>> import pyvista as pv
        >>> pv.global_theme.full_screen = True
        """
        return self._full_screen

    @full_screen.setter
    def full_screen(self, value: bool):
        self._full_screen = value

    @property
    def enable_camera_orientation_widget(self) -> bool:
        """Enable the camera orientation widget in all plotters.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.enable_camera_orientation_widget = True
        >>> pv.global_theme.enable_camera_orientation_widget
        True

        """
        return self._enable_camera_orientation_widget

    @enable_camera_orientation_widget.setter
    def enable_camera_orientation_widget(self, value: bool):
        self._enable_camera_orientation_widget = value

    @property
    def camera(self):
        """Return or set the default camera position.

        Examples
        --------
        Set both the position and view of the camera.

        >>> import pyvista as pv
        >>> pv.global_theme.camera = {
        ...     'position': [1, 1, 1],
        ...     'viewup': [0, 0, 1],
        ... }

        Set the default position of the camera.

        >>> pv.global_theme.camera['position'] = [1, 1, 1]

        Set the default view of the camera.

        >>> pv.global_theme.camera['viewup'] = [0, 0, 1]

        """
        return self._camera

    @camera.setter
    def camera(self, camera):
        if not isinstance(camera, dict):
            raise TypeError(f'Expected ``camera`` to be a dict, not {type(camera).__name__}.')

        if 'position' not in camera:
            raise KeyError('Expected the "position" key in the camera dict.')
        if 'viewup' not in camera:
            raise KeyError('Expected the "viewup" key in the camera dict.')

        self._camera = camera

    @property
    def notebook(self) -> Union[bool, None]:
        """Return or set the state of notebook plotting.

        Setting this to ``True`` always enables notebook plotting,
        while setting it to ``False`` disables plotting even when
        plotting within a jupyter notebook and plots externally.

        Examples
        --------
        Disable all jupyter notebook plotting.

        >>> import pyvista as pv
        >>> pv.global_theme.notebook = False

        """
        return self._notebook

    @notebook.setter
    def notebook(self, value: Union[bool, None]):
        self._notebook = value

    @property
    def window_size(self) -> List[int]:
        """Return or set the default render window size.

        Examples
        --------
        Set window size to ``[400, 400]``.

        >>> import pyvista as pv
        >>> pv.global_theme.window_size = [400, 400]

        """
        return self._window_size

    @window_size.setter
    def window_size(self, window_size: List[int]):
        if len(window_size) != 2:
            raise ValueError('Expected a length 2 iterable for ``window_size``.')

        # ensure positive size
        if window_size[0] < 0 or window_size[1] < 0:
            raise ValueError('Window size must be a positive value.')

        self._window_size = window_size

    @property
    def image_scale(self) -> int:
        """Return or set the default image scale factor."""
        return self._image_scale

    @image_scale.setter
    def image_scale(self, value: int):
        value = int(value)
        if value < 1:
            raise ValueError('Scale factor must be a positive integer.')
        self._image_scale = int(value)

    @property
    def font(self) -> _Font:
        """Return or set the default font size, family, and/or color.

        Examples
        --------
        Set the default font family to 'arial'.  Must be either
        'arial', 'courier', or 'times'.

        >>> import pyvista as pv
        >>> pv.global_theme.font.family = 'arial'

        Set the default font size to 20.

        >>> pv.global_theme.font.size = 20

        Set the default title size to 40.

        >>> pv.global_theme.font.title_size = 40

        Set the default label size to 10.

        >>> pv.global_theme.font.label_size = 10

        Set the default text color to 'grey'.

        >>> pv.global_theme.font.color = 'grey'

        String formatter used to format numerical data to '%.6e'.

        >>> pv.global_theme.font.fmt = '%.6e'

        """
        return self._font

    @font.setter
    def font(self, config: _Font):
        if not isinstance(config, _Font):
            raise TypeError('Configuration type must be `_Font`.')
        self._font = config

    @property
    def cmap(self):
        """Return or set the default colormap of pyvista.

        See available Matplotlib colormaps.  Only applicable for when
        displaying ``scalars``.  If ``colorcet`` or ``cmocean`` are
        installed, their colormaps can be specified by name.

        You can also specify a list of colors to override an existing
        colormap with a custom one.  For example, to create a three
        color colormap you might specify ``['green', 'red', 'blue']``

        Examples
        --------
        Set the default global colormap to 'jet'.

        >>> import pyvista as pv
        >>> pv.global_theme.cmap = 'jet'

        """
        return self._cmap

    @cmap.setter
    def cmap(self, cmap):
        out = get_cmap_safe(cmap)  # for validation
        if out is None:
            raise ValueError(f'Invalid color map {cmap}')
        self._cmap = cmap

    @property
    def color(self) -> Color:
        """Return or set the default color of meshes in pyvista.

        Used for meshes without ``scalars``.

        When setting, the value must be either a string, rgb list,
        or hex color string.  For example:

        * ``color='white'``
        * ``color='w'``
        * ``color=[1.0, 1.0, 1.0]``
        * ``color='#FFFFFF'``

        Examples
        --------
        Set the default mesh color to 'red'.

        >>> import pyvista as pv
        >>> pv.global_theme.color = 'red'

        """
        return self._color

    @color.setter
    def color(self, color: ColorLike):
        self._color = Color(color)

    @property
    def color_cycler(self):
        """Return or set the default color cycler used to color meshes.

        This color cycler is iterated over by each renderer to sequentially
        color datasets when displaying them through ``add_mesh``.

        When setting, the value must be either a list of color-like objects,
        or a cycler of color-like objects. If the value passed is a single
        string, it must be one of:

            * ``'default'`` - Use the default color cycler (matches matplotlib's default)
            * ``'matplotlib`` - Dynamically get matplotlib's current theme's color cycler.
            * ``'all'`` - Cycle through all of the available colors in ``pyvista.plotting.colors.hexcolors``

        Setting to ``None`` will disable the use of the color cycler.

        Examples
        --------
        Set the default color cycler to iterate through red, green, and blue.

        >>> import pyvista as pv
        >>> pv.global_theme.color_cycler = ['red', 'green', 'blue']

        >>> pl = pv.Plotter()
        >>> _ = pl.add_mesh(pv.Cone(center=(0, 0, 0)))  # red
        >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))  # green
        >>> _ = pl.add_mesh(pv.Sphere(center=(1, 1, 0)))  # blue
        >>> _ = pl.add_mesh(pv.Cylinder(center=(0, 1, 0)))  # red again
        >>> pl.show()  # doctest: +SKIP

        """
        return self._color_cycler

    @color_cycler.setter
    def color_cycler(self, color_cycler):
        self._color_cycler = get_cycler(color_cycler)

    @property
    def nan_color(self) -> Color:
        """Return or set the default NaN color.

        This color is used to plot all NaN values.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.nan_color = 'darkgray'

        """
        return self._nan_color

    @nan_color.setter
    def nan_color(self, nan_color: ColorLike):
        self._nan_color = Color(nan_color)

    @property
    def edge_color(self) -> Color:
        """Return or set the default edge color.

        Examples
        --------
        Set the global edge color to 'blue'.

        >>> import pyvista as pv
        >>> pv.global_theme.edge_color = 'blue'

        """
        return self._edge_color

    @edge_color.setter
    def edge_color(self, edge_color: ColorLike):
        self._edge_color = Color(edge_color)

    @property
    def line_width(self) -> float:
        """Return or set the default line width.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.line_width = 2.0

        """
        return self._line_width

    @line_width.setter
    def line_width(self, line_width: float):
        self._line_width = float(line_width)

    @property
    def point_size(self) -> float:
        """Return or set the default point size.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.line_width = 10.0

        """
        return self._point_size

    @point_size.setter
    def point_size(self, point_size: float):
        self._point_size = float(point_size)

    @property
    def outline_color(self) -> Color:
        """Return or set the default outline color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.outline_color = 'white'

        """
        return self._outline_color

    @outline_color.setter
    def outline_color(self, outline_color: ColorLike):
        self._outline_color = Color(outline_color)

    @property
    def floor_color(self) -> Color:
        """Return or set the default floor color.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.floor_color = 'black'

        """
        return self._floor_color

    @floor_color.setter
    def floor_color(self, floor_color: ColorLike):
        self._floor_color = Color(floor_color)

    @property
    def colorbar_orientation(self) -> str:
        """Return or set the default colorbar orientation.

        Must be either ``'vertical'`` or ``'horizontal'``.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.colorbar_orientation = 'horizontal'

        """
        return self._colorbar_orientation

    @colorbar_orientation.setter
    def colorbar_orientation(self, colorbar_orientation: str):
        if colorbar_orientation not in ['vertical', 'horizontal']:
            raise ValueError('Colorbar orientation must be either "vertical" or "horizontal"')
        self._colorbar_orientation = colorbar_orientation

    @property
    def colorbar_horizontal(self) -> _ColorbarConfig:
        """Return or set the default parameters of a horizontal colorbar.

        Examples
        --------
        Set the default horizontal colorbar width to 0.6.

        >>> import pyvista as pv
        >>> pv.global_theme.colorbar_horizontal.width = 0.6

        Set the default horizontal colorbar height to 0.2.

        >>> pv.global_theme.colorbar_horizontal.height = 0.2

        """
        return self._colorbar_horizontal

    @colorbar_horizontal.setter
    def colorbar_horizontal(self, config: _ColorbarConfig):
        if not isinstance(config, _ColorbarConfig):
            raise TypeError('Configuration type must be `_ColorbarConfig`.')
        self._colorbar_horizontal = config

    @property
    def colorbar_vertical(self) -> _ColorbarConfig:
        """Return or set the default parameters of a vertical colorbar.

        Examples
        --------
        Set the default colorbar width to 0.45.

        >>> import pyvista as pv
        >>> pv.global_theme.colorbar_vertical.width = 0.45

        Set the default colorbar height to 0.8.

        >>> import pyvista as pv
        >>> pv.global_theme.colorbar_vertical.height = 0.8

        """
        return self._colorbar_vertical

    @colorbar_vertical.setter
    def colorbar_vertical(self, config: _ColorbarConfig):
        if not isinstance(config, _ColorbarConfig):
            raise TypeError('Configuration type must be `_ColorbarConfig`.')
        self._colorbar_vertical = config

    @property
    def show_scalar_bar(self) -> bool:
        """Return or set the default color bar visibility.

        Examples
        --------
        Show the scalar bar by default when scalars are available.

        >>> import pyvista as pv
        >>> pv.global_theme.show_scalar_bar = True

        """
        return self._show_scalar_bar

    @show_scalar_bar.setter
    def show_scalar_bar(self, show_scalar_bar: bool):
        self._show_scalar_bar = bool(show_scalar_bar)

    @property
    def show_edges(self) -> bool:
        """Return or set the default edge visibility.

        Examples
        --------
        Show edges globally by default.

        >>> import pyvista as pv
        >>> pv.global_theme.show_edges = True

        """
        return self._show_edges

    @show_edges.setter
    def show_edges(self, show_edges: bool):
        self._show_edges = bool(show_edges)

    @property
    def show_vertices(self) -> bool:
        """Return or set the default vertex visibility.

        Examples
        --------
        Show vertices globally by default.

        >>> import pyvista as pv
        >>> pv.global_theme.show_vertices = True

        """
        return self._show_vertices

    @show_vertices.setter
    def show_vertices(self, show_vertices: bool):
        self._show_vertices = bool(show_vertices)

    @property
    def lighting(self) -> bool:
        """Return or set the default ``lighting``.

        Examples
        --------
        Disable lighting globally.

        >>> import pyvista as pv
        >>> pv.global_theme.lighting = False
        """
        return self._lighting

    @lighting.setter
    def lighting(self, lighting: bool):
        self._lighting = lighting

    @property
    def interactive(self) -> bool:
        """Return or set the default ``interactive`` parameter.

        Examples
        --------
        Make all plots non-interactive globally.

        >>> import pyvista as pv
        >>> pv.global_theme.interactive = False
        """
        return self._interactive

    @interactive.setter
    def interactive(self, interactive: bool):
        self._interactive = bool(interactive)

    @property
    def render_points_as_spheres(self) -> bool:
        """Return or set the default ``render_points_as_spheres`` parameter.

        Examples
        --------
        Render points as spheres by default globally.

        >>> import pyvista as pv
        >>> pv.global_theme.render_points_as_spheres = True
        """
        return self._render_points_as_spheres

    @render_points_as_spheres.setter
    def render_points_as_spheres(self, render_points_as_spheres: bool):
        self._render_points_as_spheres = bool(render_points_as_spheres)

    @property
    def render_lines_as_tubes(self) -> bool:
        """Return or set the default ``render_lines_as_tubes`` parameter.

        Examples
        --------
        Render points as spheres by default globally.

        >>> import pyvista as pv
        >>> pv.global_theme.render_lines_as_tubes = True
        """
        return self._render_lines_as_tubes

    @render_lines_as_tubes.setter
    def render_lines_as_tubes(self, render_lines_as_tubes: bool):
        self._render_lines_as_tubes = bool(render_lines_as_tubes)

    @property
    def transparent_background(self) -> bool:
        """Return or set the default ``transparent_background`` parameter.

        Examples
        --------
        Set transparent_background globally to ``True``.

        >>> import pyvista as pv
        >>> pv.global_theme.transparent_background = True

        """
        return self._transparent_background

    @transparent_background.setter
    def transparent_background(self, transparent_background: bool):
        self._transparent_background = transparent_background

    @property
    def title(self) -> str:
        """Return or set the default ``title`` parameter.

        This is the VTK render window title.

        Examples
        --------
        Set title globally to 'plot'.

        >>> import pyvista as pv
        >>> pv.global_theme.title = 'plot'

        """
        return self._title

    @title.setter
    def title(self, title: str):
        self._title = title

    @property
    def anti_aliasing(self) -> Optional[str]:
        """Enable or disable anti-aliasing.

        Should be either ``"ssaa"``, ``"msaa"``, ``"fxaa"``, or ``None``.

        Examples
        --------
        Use super-sampling anti-aliasing in the global theme.

        >>> import pyvista as pv
        >>> pv.global_theme.anti_aliasing = 'ssaa'
        >>> pv.global_theme.anti_aliasing
        'ssaa'

        Disable anti-aliasing in the global theme.

        >>> import pyvista as pv
        >>> pv.global_theme.anti_aliasing = None

        See :ref:`anti_aliasing_example` for more information regarding
        anti-aliasing.

        """
        return self._anti_aliasing

    @anti_aliasing.setter
    def anti_aliasing(self, anti_aliasing: Union[str, None]):
        if isinstance(anti_aliasing, bool):
            # Deprecated on v0.37.0, estimated removal on v0.40.0
            warnings.warn(
                '`anti_aliasing` is now a string or None and must be either "ssaa", '
                '"msaa", "fxaa", or None',
                PyVistaDeprecationWarning,
            )
            anti_aliasing = 'fxaa' if anti_aliasing else None

        if isinstance(anti_aliasing, str):
            if anti_aliasing not in ['ssaa', 'msaa', 'fxaa']:
                raise ValueError('anti_aliasing must be either "ssaa", "msaa", or "fxaa"')
        elif anti_aliasing is not None:
            raise TypeError('anti_aliasing must be either "ssaa", "msaa", "fxaa", or None')

        self._anti_aliasing = anti_aliasing

    @property
    def antialiasing(self):
        """Enable or disable anti-aliasing.

        .. deprecated:: 0.37.0
           Deprecated in favor of :attr:`anti_aliasing <DefaultTheme.anti_aliasing>`.
        """
        # Recommended removing at pyvista==0.40.0
        warnings.warn(
            'antialising is deprecated.  Please use `anti_aliasing` instead.',
            PyVistaDeprecationWarning,
        )
        return self.anti_aliasing

    @antialiasing.setter
    def antialiasing(self, value):  # pragma: no cover
        # Recommended removing at pyvista==0.40.0
        warnings.warn(
            'antialising is deprecated.  Please use `anti_aliasing` instead.',
            PyVistaDeprecationWarning,
        )
        self.anti_aliasing = value

    @property
    def multi_samples(self) -> int:
        """Return or set the default ``multi_samples`` parameter.

        Set the number of multisamples to used with hardware anti_aliasing. This
        is only used when :attr:`anti_aliasing <DefaultTheme.anti_aliasing>` is
        set to ``"msaa"``.

        Examples
        --------
        Set the default number of multisamples to 2 and enable ``"msaa"``

        >>> import pyvista as pv
        >>> pv.global_theme.anti_aliasing = 'msaa'
        >>> pv.global_theme.multi_samples = 2

        """
        return self._multi_samples

    @multi_samples.setter
    def multi_samples(self, multi_samples: int):
        self._multi_samples = int(multi_samples)

    @property
    def multi_rendering_splitting_position(self) -> float:
        """Return or set the default ``multi_rendering_splitting_position`` parameter.

        Examples
        --------
        Set multi_rendering_splitting_position globally to 0.5 (the
        middle of the window).

        >>> import pyvista as pv
        >>> pv.global_theme.multi_rendering_splitting_position = 0.5

        """
        return self._multi_rendering_splitting_position

    @multi_rendering_splitting_position.setter
    def multi_rendering_splitting_position(self, multi_rendering_splitting_position: float):
        self._multi_rendering_splitting_position = multi_rendering_splitting_position

    @property
    def volume_mapper(self) -> str:
        """Return or set the default ``volume_mapper`` parameter.

        Must be one of the following strings, which are mapped to the
        following VTK volume mappers.

        * ``'fixed_point'`` : ``vtk.vtkFixedPointVolumeRayCastMapper``
        * ``'gpu'`` : ``vtk.vtkGPUVolumeRayCastMapper``
        * ``'open_gl'`` : ``vtk.vtkOpenGLGPUVolumeRayCastMapper``
        * ``'smart'`` : ``vtk.vtkSmartVolumeMapper``

        Examples
        --------
        Set default volume mapper globally to 'gpu'.

        >>> import pyvista as pv
        >>> pv.global_theme.volume_mapper = 'gpu'

        """
        return self._volume_mapper

    @volume_mapper.setter
    def volume_mapper(self, mapper: str):
        mappers = ['fixed_point', 'gpu', 'open_gl', 'smart']
        if mapper not in mappers:
            raise ValueError(
                f"Mapper ({mapper}) unknown. Available volume mappers "
                f"include:\n {', '.join(mappers)}"
            )

        self._volume_mapper = mapper

    @property
    def smooth_shading(self) -> bool:
        """Return or set the default ``smooth_shading`` parameter.

        Examples
        --------
        Set the global smooth_shading parameter default to ``True``.

        >>> import pyvista as pv
        >>> pv.global_theme.smooth_shading = True

        """
        return self._smooth_shading

    @smooth_shading.setter
    def smooth_shading(self, smooth_shading: bool):
        self._smooth_shading = bool(smooth_shading)

    @property
    def depth_peeling(self) -> _DepthPeelingConfig:
        """Return or set the default depth peeling parameters.

        Examples
        --------
        Set the global depth_peeling parameter default to be enabled
        with 8 peels.

        >>> import pyvista as pv
        >>> pv.global_theme.depth_peeling.number_of_peels = 8
        >>> pv.global_theme.depth_peeling.occlusion_ratio = 0.0
        >>> pv.global_theme.depth_peeling.enabled = True

        """
        return self._depth_peeling

    @depth_peeling.setter
    def depth_peeling(self, config: _DepthPeelingConfig):
        if not isinstance(config, _DepthPeelingConfig):
            raise TypeError('Configuration type must be `_DepthPeelingConfig`.')
        self._depth_peeling = config

    @property
    def silhouette(self) -> _SilhouetteConfig:
        """Return or set the default ``silhouette`` configuration.

        Examples
        --------
        Set parameters of the silhouette.

        >>> import pyvista as pv
        >>> pv.global_theme.silhouette.color = 'grey'
        >>> pv.global_theme.silhouette.line_width = 2.0
        >>> pv.global_theme.silhouette.feature_angle = 20

        """
        return self._silhouette

    @silhouette.setter
    def silhouette(self, config: _SilhouetteConfig):
        if not isinstance(config, _SilhouetteConfig):
            raise TypeError('Configuration type must be `_SilhouetteConfig`')
        self._silhouette = config

    @property
    def slider_styles(self) -> _SliderConfig:
        """Return the default slider style configurations."""
        return self._slider_styles

    @slider_styles.setter
    def slider_styles(self, config: _SliderConfig):
        if not isinstance(config, _SliderConfig):
            raise TypeError('Configuration type must be `_SliderConfig`.')
        self._slider_styles = config

    @property
    def axes(self) -> _AxesConfig:
        """Return or set the default ``axes`` configuration.

        Examples
        --------
        Set the x axis color to black.

        >>> import pyvista as pv
        >>> pv.global_theme.axes.x_color = 'black'

        Show axes by default.

        >>> pv.global_theme.axes.show = True

        Use the ``vtk.vtkCubeAxesActor``.

        >>> pv.global_theme.axes.box = True

        """
        return self._axes

    @axes.setter
    def axes(self, config: _AxesConfig):
        if not isinstance(config, _AxesConfig):
            raise TypeError('Configuration type must be `_AxesConfig`.')
        self._axes = config

    @property
    def before_close_callback(self) -> Callable[[Plotter], None]:
        """Return the default before_close_callback function for Plotter."""
        return self._before_close_callback

    @before_close_callback.setter
    def before_close_callback(self, value: Callable[[Plotter], None]):
        self._before_close_callback = value

    def restore_defaults(self):
        """Restore the theme defaults.

        Examples
        --------
        >>> import pyvista as pv
        >>> pv.global_theme.restore_defaults()

        """
        self.__init__()

    def __repr__(self):
        """User friendly representation of the current theme."""
        txt = [f'{self.name.capitalize()} Theme']
        txt.append('-' * len(txt[0]))
        parm = {
            'Background': 'background',
            'Jupyter backend': 'jupyter_backend',
            'Full screen': 'full_screen',
            'Window size': 'window_size',
            'Camera': 'camera',
            'Notebook': 'notebook',
            'Font': 'font',
            'Auto close': 'auto_close',
            'Colormap': 'cmap',
            'Color': 'color',
            'Color Cycler': 'color_cycler',
            'NaN color': 'nan_color',
            'Edge color': 'edge_color',
            'Outline color': 'outline_color',
            'Floor color': 'floor_color',
            'Colorbar orientation': 'colorbar_orientation',
            'Colorbar - horizontal': 'colorbar_horizontal',
            'Colorbar - vertical': 'colorbar_vertical',
            'Show scalar bar': 'show_scalar_bar',
            'Show edges': 'show_edges',
            'Lighting': 'lighting',
            'Interactive': 'interactive',
            'Render points as spheres': 'render_points_as_spheres',
            'Transparent Background': 'transparent_background',
            'Title': 'title',
            'Axes': 'axes',
            'Multi-samples': 'multi_samples',
            'Multi-renderer Split Pos': 'multi_rendering_splitting_position',
            'Volume mapper': 'volume_mapper',
            'Smooth shading': 'smooth_shading',
            'Depth peeling': 'depth_peeling',
            'Silhouette': 'silhouette',
            'Slider Styles': 'slider_styles',
            'Return Camera Position': 'return_cpos',
            'Hidden Line Removal': 'hidden_line_removal',
            'Anti-Aliasing': '_anti_aliasing',
            'Split sharp edges': '_split_sharp_edges',
            'Sharp edges feat. angle': '_sharp_edges_feature_angle',
            'Before close callback': '_before_close_callback',
        }
        for name, attr in parm.items():
            setting = getattr(self, attr)
            txt.append(f'{name:<25}: {setting}')

        return '\n'.join(txt)

    @property
    def name(self) -> str:
        """Return or set the name of the theme."""
        return self._name

    @name.setter
    def name(self, name: str):
        self._name = name

    def load_theme(self, theme):
        """Overwrite the current theme with a theme.

        Parameters
        ----------
        theme : pyvista.themes.DefaultTheme
            Theme to use to overwrite this theme.

        Examples
        --------
        Create a custom theme from the default theme and load it into
        the global theme of pyvista.

        >>> import pyvista as pv
        >>> from pyvista.themes import DefaultTheme
        >>> my_theme = DefaultTheme()
        >>> my_theme.font.size = 20
        >>> my_theme.font.title_size = 40
        >>> my_theme.cmap = 'jet'
        >>> pv.global_theme.load_theme(my_theme)
        >>> pv.global_theme.font.size
        20

        Create a custom theme from the dark theme and load it into
        pyvista.

        >>> from pyvista.themes import DarkTheme
        >>> my_theme = DarkTheme()
        >>> my_theme.show_edges = True
        >>> pv.global_theme.load_theme(my_theme)
        >>> pv.global_theme.show_edges
        True

        """
        if isinstance(theme, str):
            theme = load_theme(theme)

        if not isinstance(theme, DefaultTheme):
            raise TypeError(
                '``theme`` must be a pyvista theme like ``pyvista.themes.DefaultTheme``.'
            )

        for attr_name in theme.__slots__:
            setattr(self, attr_name, getattr(theme, attr_name))

    def save(self, filename):
        """Serialize this theme to a json file.

        ``before_close_callback`` is non-serializable and is omitted.

        Parameters
        ----------
        filename : str
            Path to save the theme to.  Should end in ``'.json'``.

        Examples
        --------
        Export and then load back in a theme.

        >>> import pyvista as pv
        >>> theme = pv.themes.DefaultTheme()
        >>> theme.background = 'white'
        >>> theme.save('my_theme.json')  # doctest:+SKIP
        >>> loaded_theme = pv.load_theme('my_theme.json')  # doctest:+SKIP

        """
        data = self.to_dict()
        # functions are not serializable
        del data["before_close_callback"]
        with open(filename, 'w') as f:
            json.dump(data, f)

    @property
    def split_sharp_edges(self) -> bool:
        """Set or return splitting sharp edges.

        See :ref:`shading_example` for an example showing split sharp edges.

        Examples
        --------
        Enable the splitting of sharp edges globally.

        >>> import pyvista as pv
        >>> pv.global_theme.split_sharp_edges = True
        >>> pv.global_theme.split_sharp_edges
        True

        Disable the splitting of sharp edges globally.

        >>> import pyvista as pv
        >>> pv.global_theme.split_sharp_edges = False
        >>> pv.global_theme.split_sharp_edges
        False

        """
        return self._split_sharp_edges

    @split_sharp_edges.setter
    def split_sharp_edges(self, value: bool):
        self._split_sharp_edges = value

    @property
    def sharp_edges_feature_angle(self) -> float:
        """Set or return the angle of the sharp edges feature angle.

        See :ref:`shading_example` for an example showing split sharp edges.

        Examples
        --------
        Change the sharp edges feature angle to 45 degrees.

        >>> import pyvista as pv
        >>> pv.global_theme.sharp_edges_feature_angle = 45.0
        >>> pv.global_theme.sharp_edges_feature_angle
        45.0

        """
        return self._sharp_edges_feature_angle

    @sharp_edges_feature_angle.setter
    def sharp_edges_feature_angle(self, value: float):
        self._sharp_edges_feature_angle = float(value)

    @property
    def lighting_params(self) -> _LightingConfig:
        """Return or set the default lighting configuration."""
        return self._lighting_params

    @lighting_params.setter
    def lighting_params(self, config: _LightingConfig):
        if not isinstance(config, _LightingConfig):
            raise TypeError('Configuration type must be `_LightingConfig`.')
        self._lighting_params = config


class DarkTheme(DefaultTheme):
    """Dark mode theme.

    Black background, "viridis" colormap, tan meshes, white (hidden) edges.

    Examples
    --------
    Make the dark theme the global default.

    >>> import pyvista as pv
    >>> from pyvista import themes
    >>> pv.set_plot_theme(themes.DarkTheme())

    Alternatively, set via a string.

    >>> pv.set_plot_theme('dark')

    """

    def __init__(self):
        """Initialize the theme."""
        super().__init__()
        self.name = 'dark'
        self.background = 'black'
        self.cmap = 'viridis'
        self.font.color = 'white'
        self.show_edges = False
        self.color = 'tan'
        self.outline_color = 'white'
        self.edge_color = 'white'
        self.axes.x_color = 'tomato'
        self.axes.y_color = 'seagreen'
        self.axes.z_color = 'blue'


class ParaViewTheme(DefaultTheme):
    """A paraview-like theme.

    Examples
    --------
    Make the paraview-like theme the global default.

    >>> import pyvista as pv
    >>> from pyvista import themes
    >>> pv.set_plot_theme(themes.ParaViewTheme())

    Alternatively, set via a string.

    >>> pv.set_plot_theme('paraview')

    """

    def __init__(self):
        """Initialize theme."""
        super().__init__()
        self.name = 'paraview'
        self.background = 'paraview'
        self.cmap = 'coolwarm'
        self.font.family = 'arial'
        self.font.label_size = 16
        self.font.color = 'white'
        self.show_edges = False
        self.color = 'white'
        self.outline_color = 'white'
        self.edge_color = 'black'
        self.axes.x_color = 'tomato'
        self.axes.y_color = 'gold'
        self.axes.z_color = 'green'


class DocumentTheme(DefaultTheme):
    """A document theme well suited for papers and presentations.

    This theme uses:

    * A white background
    * Black fonts
    * The "viridis" colormap
    * disables edges for surface plots
    * Hidden edge removal

    Best used for presentations, papers, etc.

    Examples
    --------
    Make the document theme the global default.

    >>> import pyvista as pv
    >>> from pyvista import themes
    >>> pv.set_plot_theme(themes.DocumentTheme())

    Alternatively, set via a string.

    >>> pv.set_plot_theme('document')

    """

    def __init__(self):
        """Initialize the theme."""
        super().__init__()
        self.name = 'document'
        self.background = 'white'
        self.cmap = 'viridis'
        self.font.size = 18
        self.font.title_size = 18
        self.font.label_size = 18
        self.font.color = 'black'
        self.show_edges = False
        self.color = 'tan'
        self.outline_color = 'black'
        self.edge_color = 'black'
        self.axes.x_color = 'tomato'
        self.axes.y_color = 'seagreen'
        self.axes.z_color = 'blue'


class DocumentProTheme(DocumentTheme):
    """A more professional document theme.

    This theme extends the base document theme with:

    * Default color cycling
    * Rendering points as spheres
    * MSAA anti aliassing
    * Depth peeling

    """

    def __init__(self):
        """Initialize the theme."""
        super().__init__()
        self.color_cycler = get_cycler('default')
        self.render_points_as_spheres = True
        self.anti_aliasing = 'msaa'  # or 'ssaa'?
        self.multi_samples = 2
        self.depth_peeling.number_of_peels = 4
        self.depth_peeling.occlusion_ratio = 0.0
        self.depth_peeling.enabled = True


class _TestingTheme(DefaultTheme):
    """Low resolution testing theme for ``pytest``.

    Necessary for image regression.  Xvfb doesn't support
    multi-sampling, it's disabled for consistency between desktops and
    remote testing.

    Also disables ``return_cpos`` to make it easier for us to write
    examples without returning camera positions.

    """

    def __init__(self):
        super().__init__()
        self.name = 'testing'
        self.multi_samples = 1
        self.window_size = [400, 400]
        self.axes.show = False
        self.return_cpos = False


class _NATIVE_THEMES(Enum):
    """Global built-in themes available to PyVista."""

    paraview = ParaViewTheme
    document = DocumentTheme
    document_pro = DocumentProTheme
    dark = DarkTheme
    default = DefaultTheme
    testing = _TestingTheme


# pyvista/report.py
"""Module managing errors."""
from collections import namedtuple
import re
import subprocess
import sys
import warnings

import scooby
from vtkmodules.vtkCommonCore import vtkVersion


def VTKVersionInfo():
    """Return the vtk version as a namedtuple."""
    version_info = namedtuple('VTKVersionInfo', ['major', 'minor', 'micro'])

    try:
        ver = vtkVersion()
        major = ver.GetVTKMajorVersion()
        minor = ver.GetVTKMinorVersion()
        micro = ver.GetVTKBuildVersion()
    except AttributeError:  # pragma: no cover
        warnings.warn("Unable to detect VTK version. Defaulting to v4.0.0")
        major, minor, micro = (4, 0, 0)

    return version_info(major, minor, micro)


vtk_version_info = VTKVersionInfo()


_cmd = """\
import pyvista; \
plotter = pyvista.Plotter(notebook=False, off_screen=True); \
plotter.add_mesh(pyvista.Sphere()); \
plotter.show(auto_close=False); \
gpu_info = plotter.render_window.ReportCapabilities(); \
print(gpu_info); \
plotter.close()\
"""


def get_gpu_info():
    """Get all information about the GPU."""
    # an OpenGL context MUST be opened before trying to do this.
    proc = subprocess.run([sys.executable, '-c', _cmd], check=False, capture_output=True)
    gpu_info = '' if proc.returncode else proc.stdout.decode()
    return gpu_info


class GPUInfo:
    """A class to hold GPU details."""

    def __init__(self):
        """Instantiate a container for the GPU information."""
        self._gpu_info = get_gpu_info()

    @property
    def renderer(self):
        """GPU renderer name."""
        regex = re.compile("OpenGL renderer string:(.+)\n")
        try:
            renderer = regex.findall(self._gpu_info)[0]
        except IndexError:
            raise RuntimeError("Unable to parse GPU information for the renderer.") from None
        return renderer.strip()

    @property
    def version(self):
        """GPU renderer version."""
        regex = re.compile("OpenGL version string:(.+)\n")
        try:
            version = regex.findall(self._gpu_info)[0]
        except IndexError:
            raise RuntimeError("Unable to parse GPU information for the version.") from None
        return version.strip()

    @property
    def vendor(self):
        """GPU renderer vendor."""
        regex = re.compile("OpenGL vendor string:(.+)\n")
        try:
            vendor = regex.findall(self._gpu_info)[0]
        except IndexError:
            raise RuntimeError("Unable to parse GPU information for the vendor.") from None
        return vendor.strip()

    def get_info(self):
        """All GPU information as tuple pairs."""
        return [
            ("GPU Vendor", self.vendor),
            ("GPU Renderer", self.renderer),
            ("GPU Version", self.version),
        ]

    def _repr_html_(self):
        """HTML table representation."""
        fmt = "<table>"
        row = "<tr><th>{}</th><td>{}</td></tr>\n"
        for meta in self.get_info():
            fmt += row.format(*meta)
        fmt += "</table>"
        return fmt

    def __repr__(self):
        """Representation method."""
        content = "\n"
        for k, v in self.get_info():
            content += f"{k:>18} : {v}\n"
        content += "\n"
        return content


class Report(scooby.Report):
    """Generate a PyVista software environment report.

    Parameters
    ----------
    additional : sequence[types.ModuleType], sequence[str]
        List of packages or package names to add to output information.

    ncol : int, default: 3
        Number of package-columns in html table; only has effect if
        ``mode='HTML'`` or ``mode='html'``.

    text_width : int, default: 80
        The text width for non-HTML display modes.

    sort : bool, default: False
        Alphabetically sort the packages.

    gpu : bool, default: True
        Gather information about the GPU. Defaults to ``True`` but if
        experiencing rendering issues, pass ``False`` to safely generate a
        report.

    Examples
    --------
    >>> import pyvista as pv
    >>> pv.Report()  # doctest:+SKIP
      Date: Fri Oct 28 15:54:11 2022 MDT
    <BLANKLINE>
                    OS : Linux
                CPU(s) : 6
               Machine : x86_64
          Architecture : 64bit
                   RAM : 62.6 GiB
           Environment : IPython
           File system : ext4
            GPU Vendor : NVIDIA Corporation
          GPU Renderer : Quadro P2000/PCIe/SSE2
           GPU Version : 4.5.0 NVIDIA 470.141.03
    <BLANKLINE>
      Python 3.8.10 (default, Jun 22 2022, 20:18:18)  [GCC 9.4.0]
    <BLANKLINE>
               pyvista : 0.37.dev0
                   vtk : 9.1.0
                 numpy : 1.23.3
               imageio : 2.22.0
                scooby : 0.7.1.dev1+gf097dad
                 pooch : v1.6.0
            matplotlib : 3.6.0
               IPython : 7.31.0
              colorcet : 3.0.1
               cmocean : 2.0
            ipyvtklink : 0.2.3
                 scipy : 1.9.1
                  tqdm : 4.64.1
                meshio : 5.3.4
            jupyterlab : 3.4.7
             pythreejs : Version unknown

    """

    def __init__(self, additional=None, ncol=3, text_width=80, sort=False, gpu=True):
        """Generate a :class:`scooby.Report` instance."""
        from pyvista.plotting.tools import check_math_text_support

        # Mandatory packages
        core = ['pyvista', 'vtk', 'numpy', 'matplotlib', 'scooby', 'pooch']

        # Optional packages.
        optional = [
            'imageio',
            'pyvistaqt',
            'PyQt5',
            'IPython',
            'colorcet',
            'cmocean',
            'ipyvtklink',
            'ipywidgets',
            'scipy',
            'tqdm',
            'meshio',
            'jupyterlab',
            'pythreejs',
            'pytest_pyvista',
            'trame',
            'trame_client',
            'trame_server',
            'trame_vtk',
            'jupyter_server_proxy',
            'nest_asyncio',
        ]

        # Information about the GPU - bare except in case there is a rendering
        # bug that the user is trying to report.
        if gpu:
            try:
                extra_meta = GPUInfo().get_info()
            except:
                extra_meta = [
                    ("GPU Details", "error"),
                ]
        else:
            extra_meta = [
                ("GPU Details", "None"),
            ]

        extra_meta.append(('MathText Support', check_math_text_support()))

        scooby.Report.__init__(
            self,
            additional=additional,
            core=core,
            optional=optional,
            ncol=ncol,
            text_width=text_width,
            sort=sort,
            extra_meta=extra_meta,
        )
