Skip to content

Headless 3-D rendering#

The 3-D tier draws through PyVista, and PyVista draws through VTK, which needs an OpenGL context even when no window is shown. On Windows and macOS the platform provides one. On Linux the stock vtk wheel gets it from an X server, so a machine with no screen — a server, a container, a remote Jupyter kernel — cannot render a Scene3D until it is given one. There are three ways to do that.

1. Render off-screen#

Whatever else you do, ask for no window:

from digitalearth.three_d import Scene3D

with Scene3D(off_screen=True) as scene:
    scene.terrain(dem)
    scene.screenshot("relief.png")

off_screen=None (the default) follows pyvista.OFF_SCREEN, so setting that once at the top of a script does the same for every scene. Off-screen stops a window being opened; it does not remove the need for an OpenGL context on Linux — the next two sections are where that comes from.

2. A virtual X server (Xvfb)#

Around the whole process. xvfb-run starts a virtual X server, sets DISPLAY, runs the command and stops the server afterwards. It is what this project's CI does for every 3-D job:

sudo apt-get install -y xvfb libgl1 libglx-mesa0 libgl1-mesa-dri
xvfb-run -a python render_scene.py

From inside Python. When you cannot wrap the process — a notebook kernel someone else started, say — call start_xvfb() once before the first scene is drawn. It needs the Xvfb binary installed (the xvfb package above) and does nothing where a display already exists, so it is safe to leave in a script that also runs on a desktop, under xvfb-run, or on Windows and macOS:

from digitalearth.three_d import Scene3D, start_xvfb

server = start_xvfb()          # None when no server was needed
with Scene3D(off_screen=True) as scene:
    scene.terrain(dem)
    scene.screenshot("relief.png")
if server is not None:
    server.terminate()

PyVista used to ship a helper of this name and no longer does — the PyVista this tier is tested against has none — which is why Digital-Earth carries its own.

3. EGL or OSMesa — no X server at all#

VTK can also create its context through EGL (GPU drivers, no X server) or OSMesa (Mesa's software renderer). On Linux, VTK picks a backend at run time and lets you override the choice with the VTK_DEFAULT_OPENGL_WINDOW environment variable, set before VTK is imported:

Value Backend
vtkXOpenGLRenderWindow X server (the default when one is reachable)
vtkEGLRenderWindow EGL — needs a VTK built with EGL and a driver that provides it
vtkOSOpenGLRenderWindow OSMesa — needs libOSMesa.so installed
VTK_DEFAULT_OPENGL_WINDOW=vtkEGLRenderWindow python render_scene.py

Which of these a given vtk build supports, and what each needs installed, is VTK's to document — see VTK runtime settings. Choosing one is an installation decision rather than something Digital-Earth switches for you; nothing in the 3d extra pins a particular backend.

digitalearth.three_d.app.headless.start_xvfb(display=':99', *, window_size=(1024, 768), wait=0.5) #

Start a virtual X server and point DISPLAY at it, so the 3-D tier can render with no screen.

Call it once, before the first scene is drawn. It does nothing — and returns None — when there is nothing to do: DISPLAY is already set (a desktop session, or a process run under xvfb-run), or the platform is Windows or macOS, where VTK renders without an X server. That makes it safe to call unconditionally at the top of a script meant to run everywhere.

On Linux with no display it launches Xvfb <display> -screen 0 <width>x<height>x24 -nolisten tcp, waits wait seconds to see that the server stays up, and only then sets DISPLAY.

Stopping it. Call .terminate() on the returned process when you are done, or leave it: the helper registers an :mod:atexit hook that terminates the server, waits (briefly, and killing it if it will not go) for it to actually exit, and unsets the DISPLAY it set, so a script that forgets leaves no stray server behind. The OS does not do this for you — a subprocess.Popen child outlives the interpreter that started it, and Popen.__del__ deliberately does not terminate a running one (dropping the last reference to a live child only warns subprocess <pid> is still running). Until the hook existed, a forgotten server went on holding :99; the next run then found no DISPLAY, asked for :99 again, and failed with the RuntimeError below — so "safe to call unconditionally" was false from the second run onward (review M3).

Parameters:

Name Type Description Default
display str

The X display to create, such as ":99". Pick another number if that one is taken.

':99'
window_size Sequence[int]

(width, height) of the virtual screen in pixels. It bounds the largest window or screenshot VTK can render, so make it at least the window_size of the scenes you draw.

(1024, 768)
wait float

Seconds to wait for the server to come up before declaring it started. A server that exits within that time (a display number already in use, for instance) is reported as an error. It must be a positive finite number, and anything else is refused by name: 0 and any negative make the check pass instantly — the same as not checking at all — nan disables it the same way by comparing false against every bound, and inf turns it into a hang.

0.5

Returns:

Type Description
Popen | None

The subprocess.Popen of the server that was started — call .terminate() on it to stop it

Popen | None

early, or leave it to the atexit hook — or None when no server was needed.

Raises:

Type Description
ValueError

when display is not an X display name, window_size is not two positive ints, or wait is not a positive finite number of seconds.

FileNotFoundError

when Xvfb is not on PATH (apt install xvfb on Debian/Ubuntu, dnf install xorg-x11-server-Xvfb on Fedora/RHEL).

RuntimeError

when the server exits during the startup wait; DISPLAY is left unset.

Examples:

  • Start a display before drawing, on a headless Linux box (skipped here, since it launches a real X server):
    >>> from digitalearth.three_d import Scene3D, start_xvfb  # doctest: +SKIP
    >>> server = start_xvfb()                                  # doctest: +SKIP
    >>> with Scene3D(off_screen=True) as scene:                # doctest: +SKIP
    ...     scene.screenshot("frame.png")
    >>> if server is not None:                                 # doctest: +SKIP
    ...     server.terminate()
    
  • A size Xvfb would reject is refused before anything is launched, on every platform:
    >>> from digitalearth.three_d import start_xvfb
    >>> try:
    ...     start_xvfb(window_size=(0, 768))
    ... except ValueError as error:
    ...     print(error)
    start_xvfb() needs window_size as two positive ints (width, height); got (0, 768)
    
  • So is a startup wait that would not wait: the argument is checked before the platform is, so these answer the same way on Linux, Windows and macOS:
    >>> from digitalearth.three_d import start_xvfb
    >>> for wait in (0, -1, float("inf"), float("nan")):
    ...     try:
    ...         start_xvfb(wait=wait)
    ...     except ValueError as error:
    ...         print(error)
    start_xvfb() needs wait as a positive finite number of seconds; got 0
    start_xvfb() needs wait as a positive finite number of seconds; got -1
    start_xvfb() needs wait as a positive finite number of seconds; got inf
    start_xvfb() needs wait as a positive finite number of seconds; got nan
    
See Also

digitalearth.three_d.core.base.Scene3DBase: off_screen= is the other half of rendering headless.

Source code in src/digitalearth/three_d/app/headless.py
def start_xvfb(
    display: str = ":99",
    *,
    window_size: Sequence[int] = (1024, 768),
    wait: float = 0.5,
) -> subprocess.Popen | None:
    """Start a virtual X server and point ``DISPLAY`` at it, so the 3-D tier can render with no screen.

    Call it once, before the first scene is drawn. It does nothing — and returns ``None`` — when there is
    nothing to do: ``DISPLAY`` is already set (a desktop session, or a process run under ``xvfb-run``), or the
    platform is Windows or macOS, where VTK renders without an X server. That makes it safe to call
    unconditionally at the top of a script meant to run everywhere.

    On Linux with no display it launches ``Xvfb <display> -screen 0 <width>x<height>x24 -nolisten tcp``,
    waits ``wait`` seconds to see that the server stays up, and only then sets ``DISPLAY``.

    **Stopping it.** Call ``.terminate()`` on the returned process when you are done, or leave it: the
    helper registers an :mod:`atexit` hook that terminates the server, waits (briefly, and killing it if
    it will not go) for it to actually exit, and unsets the ``DISPLAY`` it set, so a script that forgets
    leaves no stray server behind. The OS does **not** do this for you — a
    ``subprocess.Popen`` child outlives the interpreter that started it, and ``Popen.__del__``
    deliberately does not terminate a running one (dropping the last reference to a live child only warns
    ``subprocess <pid> is still running``). Until the hook existed, a forgotten server went on holding
    ``:99``; the next run then found no ``DISPLAY``, asked for ``:99`` again, and failed with the
    ``RuntimeError`` below — so "safe to call unconditionally" was false from the second run onward
    (review M3).

    Args:
        display: The X display to create, such as ``":99"``. Pick another number if that one is taken.
        window_size: ``(width, height)`` of the virtual screen in pixels. It bounds the largest window or
            screenshot VTK can render, so make it at least the ``window_size`` of the scenes you draw.
        wait: Seconds to wait for the server to come up before declaring it started. A server that exits
            within that time (a display number already in use, for instance) is reported as an error.
            It must be a positive finite number, and anything else is refused by name: ``0`` and any
            negative make the check pass instantly — the same as not checking at all — ``nan`` disables it
            the same way by comparing false against every bound, and ``inf`` turns it into a hang.

    Returns:
        The ``subprocess.Popen`` of the server that was started — call ``.terminate()`` on it to stop it
        early, or leave it to the ``atexit`` hook — or ``None`` when no server was needed.

    Raises:
        ValueError: when ``display`` is not an X display name, ``window_size`` is not two positive ints,
            or ``wait`` is not a positive finite number of seconds.
        FileNotFoundError: when ``Xvfb`` is not on ``PATH`` (``apt install xvfb`` on Debian/Ubuntu,
            ``dnf install xorg-x11-server-Xvfb`` on Fedora/RHEL).
        RuntimeError: when the server exits during the startup wait; ``DISPLAY`` is left unset.

    Examples:
        - Start a display before drawing, on a headless Linux box (skipped here, since it launches a real
          X server):
            ```python
            >>> from digitalearth.three_d import Scene3D, start_xvfb  # doctest: +SKIP
            >>> server = start_xvfb()                                  # doctest: +SKIP
            >>> with Scene3D(off_screen=True) as scene:                # doctest: +SKIP
            ...     scene.screenshot("frame.png")
            >>> if server is not None:                                 # doctest: +SKIP
            ...     server.terminate()

            ```
        - A size Xvfb would reject is refused before anything is launched, on every platform:
            ```python
            >>> from digitalearth.three_d import start_xvfb
            >>> try:
            ...     start_xvfb(window_size=(0, 768))
            ... except ValueError as error:
            ...     print(error)
            start_xvfb() needs window_size as two positive ints (width, height); got (0, 768)

            ```
        - So is a startup wait that would not wait: the argument is checked before the platform is, so
          these answer the same way on Linux, Windows and macOS:
            ```python
            >>> from digitalearth.three_d import start_xvfb
            >>> for wait in (0, -1, float("inf"), float("nan")):
            ...     try:
            ...         start_xvfb(wait=wait)
            ...     except ValueError as error:
            ...         print(error)
            start_xvfb() needs wait as a positive finite number of seconds; got 0
            start_xvfb() needs wait as a positive finite number of seconds; got -1
            start_xvfb() needs wait as a positive finite number of seconds; got inf
            start_xvfb() needs wait as a positive finite number of seconds; got nan

            ```

    See Also:
        digitalearth.three_d.core.base.Scene3DBase: ``off_screen=`` is the other half of rendering headless.
    """
    _check_request(display, window_size, wait)
    if os.environ.get("DISPLAY") or not sys.platform.startswith("linux"):
        return None
    xvfb = shutil.which("Xvfb")
    if xvfb is None:
        raise FileNotFoundError(
            "start_xvfb() needs the Xvfb binary on PATH and found none; install it (apt install xvfb on "
            "Debian/Ubuntu, dnf install xorg-x11-server-Xvfb on Fedora/RHEL), run under `xvfb-run`, or use "
            "an EGL/OSMesa build of VTK, which needs no X server"
        )
    # Not `int(side)`: `_check_request` above has already refused anything that is not an `int`, so the
    # coercion could only ever have been applied to an `int` (review N3).
    width, height = window_size
    server = subprocess.Popen(  # nosec B603 (fixed Xvfb command; size validated as int)
        [xvfb, display, "-screen", "0", f"{width}x{height}x24", "-nolisten", "tcp"],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )
    try:
        code = server.wait(timeout=wait)
    except subprocess.TimeoutExpired:
        # Still running after the wait: the server is up, and VTK will find it through DISPLAY.
        os.environ["DISPLAY"] = display
        # And it is stopped when the interpreter exits, because nothing else does: a `Popen` child
        # outlives its parent, and `Popen.__del__` deliberately does not terminate a running one —
        # dropping the last reference to a live child only warns `subprocess <pid> is still running`.
        # `_reap` waits for the child it terminates, which is what keeps that warning from firing here.
        # Left behind, the server kept holding the display, and the next run found no DISPLAY, asked for
        # the same number and raised the startup RuntimeError below (review M3).
        atexit.register(_reap, server, display)
        return server
    raise RuntimeError(
        f"Xvfb on display {display} exited with code {code} while starting; the display may already be in "
        f"use — pass another one, e.g. start_xvfb(':100')"
    )