Skip to content

Plots

spawn_plot draws a function of x and y.

from ue_spawn import spawn_plot
from unreal_engine import FVector

spawn_plot('sin(x)+cos(y)', location=FVector(0, 0, 0))

Kinds of plot

spawn_plot('sin(sqrt(x**2+y**2))', plot_type='surface', colormap='plasma')
spawn_plot('sin(x)*cos(y)',        plot_type='heatmap', colormap='inferno')
spawn_plot('x**2-y**2',            plot_type='contour')
spawn_plot('x**2-y**2',            plot_type='wireframe')

Options

Option Default Does
plot_type 'surface' 'surface', 'heatmap', 'contour', 'wireframe'
mesh_mode 'mesh_section' 'mesh_section', 'triangles', 'spheres', 'sphere_lines', 'glb'
orientation 'ground_table' 'ground_table' flat, 'wall_table' (y down), 'wall_graph' (y up)
resolution 32 Samples per axis; 64 is more detailed
x_range, y_range, z_range (-π, π), (-π, π), (-2, 2) Axis limits
units_per_uu 100.0 Scale
show_grid True Axis grid
colormap 'viridis' See ue_math/ue_math_color.py
color_function None Colour by f(x, y, z) instead of height, such as 'atan2(y,x)'

The expression can use sin cos tan sqrt log exp abs pi e.

Change colours live

Surfaces, heat maps and domain-colouring plots can change colormap while you look at them: [ ] C \, or

from ue_math.plot_color_controls import CONTROLS
CONTROLS.set('sin(x)*y', 'plasma')

Mandelbrot zoom

from ue_spawn import spawn_zoom_plot
spawn_zoom_plot(location=FVector(0, 0, 300))

Point at it and scroll to zoom. It is computed on the GPU.

In the tests

Copied from the code when this site is built.

From the tests: test_plot (Content/Scripts/test_spawn.py:1482)
def test_plot(base_y=0):
    """
    Seven plot tests spread along Y from *base_y*. Each plot's x_range=(-π,π)
    × units_per_uu=80 makes it ~502 UU wide, so origins are stepped by 600
    and shifted by +260 so the leftmost edge of plot 0 sits at ~base_y
    (instead of bleeding −251 UU into the previous test's band):
      base_y +  260 — colormap surface, spheres
      base_y +  860 — colormap surface, sphere_lines
      base_y + 1460 — spherical ripple sphere_lines
      base_y + 2060 — 2D tan(x) curve
      base_y + 2660 — glb surface, colour function atan2(y,x)
      base_y + 3260 — heatmap
      base_y + 3860 — domain colouring of (z²-1)/(z²+1)

    The surfaces, heatmap and domain plot register with
    plot_color_controls.CONTROLS, so their colours can be changed live
    ([ ] C Backslash, or CONTROLS.set('sin(x)*y', 'plasma')).

    Uses spawn_plot() — a dynamic PyActorPlotter spawned via spawn_pyactor.
    Falls back to create_plotter() directly if spawn_plot errors out.
    """
    import math
    results = {}

    PLOT_HALF_WIDTH = 260   # ≈ π × units_per_uu (80) — covers ±251 UU plot extent
    PLOT_STRIDE     = 600   # one full plot width (~502) + small gutter

    variants = [
        dict(name='plot_spheres',        func='sin(x)+cos(y)',
             plot_type='surface',   mesh_mode='spheres',      orientation='ground_table',
             location=FVector(0, base_y + PLOT_HALF_WIDTH + 0 * PLOT_STRIDE, 0)),
        dict(name='plot_sphere_lines',   func='sin(x)+cos(y)',
             plot_type='surface',   mesh_mode='sphere_lines', orientation='ground_table',
             location=FVector(0, base_y + PLOT_HALF_WIDTH + 1 * PLOT_STRIDE, 0)),
        dict(name='plot_ripple_sphere_lines', func='sin(sqrt(x**2+y**2))',
             plot_type='surface',   mesh_mode='sphere_lines', orientation='ground_table',
             location=FVector(0, base_y + PLOT_HALF_WIDTH + 2 * PLOT_STRIDE, 0)),
        dict(name='plot_color_function', func='sin(x)+cos(y)',
             plot_type='surface',   mesh_mode='glb',          orientation='ground_table',
             location=FVector(0, base_y + PLOT_HALF_WIDTH + 4 * PLOT_STRIDE, 0),
             colormap='phase', color_function='angle'),
        dict(name='plot_heatmap',        func='sin(x)*cos(y)',
             plot_type='heatmap',   mesh_mode='glb',          orientation='ground_table',
             location=FVector(0, base_y + PLOT_HALF_WIDTH + 5 * PLOT_STRIDE, 0),
             colormap='inferno'),
    ]

    from ue_math.plot_color_controls import CONTROLS

    for v in variants:
        actor = None
        name = v['name']
        t0 = time.monotonic()

        # Primary path: PyActorPlotter via spawn_plot
        try:
            from ue_spawn import spawn_plot
            actor = spawn_plot(
                function_expr = v['func'],
                plot_type = v['plot_type'],
                orientation = v['orientation'],
                resolution = 32,
                location = v['location'],
                mesh_mode = v.get('mesh_mode', 'triangles'),
                colormap = v.get('colormap', 'viridis'),
                color_function = v.get('color_function'),
            )
            if actor is not None:
                CONTROLS.add(actor.get_py_proxy())
        except Exception as e:
            _log(f'  {name}: spawn_plot failed ({e}), trying direct plotter...')

        # fallback: create_plotter directly (debug=True shows mesh errors)
        if actor is None:
            try:
                from ue_math.ue_math_plotter import create_plotter
                p = create_plotter(
                    world = get_world(),
                    origin = v['location'],
                    x_range = (-3.14159, 3.14159),
                    y_range = (-3.14159, 3.14159),
                    z_range = (-2.0,  2.0),
                    units_per_uu = 80.0,
                    orientation = v['orientation'],
                    debug = True,
                )
                p.mesh_mode = v.get('mesh_mode', 'triangles')
                if 'point_mesh' in v:
                    p.point_mesh = v['point_mesh']
                p.labs(title=v['func'], x='x', y='y', z='z')
                p.grid(True, mode='3d')
                fn_expr = v['func']
                fn = lambda x, y, _e=fn_expr: float(eval(
                    compile(_e, '<test>', 'eval'), {"__builtins__": {}},
                    dict(sin=math.sin, cos=math.cos, sqrt=math.sqrt,
                         pi=math.pi, e=math.e, abs=abs, x=x, y=y)))
                cmap = v.get('colormap', 'viridis')
                if v['plot_type'] == 'heatmap':
                    p.heatmap(fn, resolution=32, colormap=cmap)
                elif v['plot_type'] == 'wireframe':
                    p.wireframe(fn, resolution=32)
                else:
                    p.colormap_surface(fn, resolution=32, colormap=cmap)
                p.show()
                if v.get('color_function'):
                    p.recolor(v['color_function'])
                CONTROLS.add(p)
                actor = p
            except Exception as e2:
                _log(f'  {name} direct plotter also failed: {e2}')

        results.update(_result(name, actor, elapsed=time.monotonic() - t0))

    # 2D curve: tan(x) with asymptote breaks
    plot_2d = None
    t0 = time.monotonic()
    try:
        from ue_math.ue_math_plotter import create_plotter

        def _tan_safe(x):
            """Return NaN near asymptotes so the curve breaks cleanly."""
            v = math.tan(x)
            if abs(v) > 5.0:
                return float('nan')
            return v

        p = create_plotter(
            world = get_world(),
            origin = FVector(0, base_y + PLOT_HALF_WIDTH + 3 * PLOT_STRIDE, 0),
            x_range = (-3.14159, 3.14159),
            y_range = (-5.0, 5.0),
            z_range = (-5.0, 5.0),
            units_per_uu = 80.0,
            orientation = 'wall_table',
            debug = True,
        )
        p.mesh_mode = 'glb'   # per-triangle actors would need ~90k for this curve
        p.labs(title='tan(x)', x='x', y='y')
        p.grid(True)
        p.plot(_tan_safe, n=256)
        p.show()
        if p.render_errors:
            raise RuntimeError('; '.join(p.render_errors))
        plot_2d = p
    except Exception as e:
        _log(f'  plot_tan_2d failed: {e}')
    results.update(_result('plot_tan_2d', plot_2d, extra='2D tan(x)',
                           elapsed=time.monotonic() - t0))

    # Domain colouring: hue = arg f, lightness = |f|
    domain = None
    t0 = time.monotonic()
    try:
        from ue_math.ue_math_plotter import create_plotter
        p = create_plotter(
            world = get_world(),
            origin = FVector(0, base_y + PLOT_HALF_WIDTH + 6 * PLOT_STRIDE, 250),
            x_range = (-3.0, 3.0),
            y_range = (-3.0, 3.0),
            z_range = (-3.0, 3.0),
            units_per_uu = 80.0,
            orientation = 'wall_graph',
        )
        p.domain_color(lambda z: (z**2 - 1) / (z**2 + 1), resolution=256)
        p.show()
        if p.render_errors:
            raise RuntimeError('; '.join(p.render_errors))
        CONTROLS.add(p)
        domain = p
    except Exception as e:
        _log(f'  plot_domain_color failed: {e}')
    results.update(_result('plot_domain_color', domain,
                           extra='(z^2-1)/(z^2+1)',
                           elapsed=time.monotonic() - t0))

    return results

View it on GitHub

From the tests: test_math_examples (Content/Scripts/test_spawn.py:1679)
def test_math_examples(base_y=0):
    """Run every ue_math_examples test in the world, one plot per grid slot.

    A test passes if it raises nothing, its plotters report no render errors
    and every plotter spawned at least one actor. Plots with coloured
    surfaces or images register with plot_color_controls.CONTROLS.
    """
    from ue_math.plot_color_controls import CONTROLS
    try:
        import ue_math.ue_math_examples as ex
    except (Exception, SystemExit) as e:   # it sys.exit()s on missing deps
        _log_exception('math_examples/import', e)
        return _result('math_examples', None, extra=f'import failed: {e!r}')

    results = {}
    world = get_world()
    original = ex.create_plotter
    plotters = []
    slot = 0

    def make_plotter(fn_name, args, kwargs):
        nonlocal slot
        if fn_name in _MATH_WIDE_Y:
            x, y = _MATH_WIDE_X, _MATH_WIDE_Y[fn_name]
        else:
            x = (slot // _MATH_COLS) * _MATH_STRIDE
            y = (slot % _MATH_COLS + 0.5) * _MATH_STRIDE
            slot += 1
        kwargs.update(world=world, origin=FVector(x, base_y + y, 300),
                      units_per_uu=_MATH_UU, debug=False, advanced_debug=False)
        p = original(*args, **kwargs)
        p.mesh_mode = 'glb'
        plotters.append(p)
        return p

    try:
        for label, fn in ex.ALL_TESTS:
            name = 'math_' + fn.__name__[len('test_'):]
            if fn.__name__ == 'test_sympy_expressions' and not ex.SYMPY_OK:
                results.update(_skip(name, 'sympy not installed'))
                continue
            if fn.__name__ == 'test_ga_with_kingdon' and not ex.KINGDON_OK:
                results.update(_skip(name, 'kingdon not installed'))
                continue

            plotters = []
            ex.create_plotter = (
                lambda *a, _n=fn.__name__, **k: make_plotter(_n, a, k))
            problems = []
            t0 = time.monotonic()
            try:
                fn()
            except Exception as e:
                _log_exception(name, e)
                problems.append(repr(e))
            for p in plotters:
                problems += p.render_errors
                if p._paints:
                    CONTROLS.add(p)
                if not p.factory._spawned:
                    problems.append('a plotter spawned no actors')
            n_actors = sum(len(p.factory._spawned) for p in plotters)
            results.update(_result(
                name, None if problems else (plotters or True),
                extra=f'{label}: ' + ('; '.join(problems) or f'{n_actors} actors'),
                elapsed=time.monotonic() - t0))
    finally:
        ex.create_plotter = original
    return results

View it on GitHub

From the tests: test_swaptube (Content/Scripts/test_spawn.py:1781)
def test_swaptube(base_y=0):
    """Spawn every SWAPTUBE_EXAMPLES plot in a row along Y."""
    from ue_math.plot_color_controls import CONTROLS
    try:
        from ue_math.ue_math_examples import SWAPTUBE_EXAMPLES, plotter_factory
    except (Exception, SystemExit) as e:   # it sys.exit()s on missing deps
        _log_exception('swaptube/import', e)
        return _result('swaptube', None, extra=f'import failed: {e!r}')

    results = {}
    for i, (name, fn) in enumerate(SWAPTUBE_EXAMPLES):
        origin = FVector(0, base_y + 300 + i * 600, 300)
        problems = []
        p = None
        t0 = time.monotonic()
        try:
            p = fn(plotter_factory(get_world(), origin))
            problems += p.render_errors
            if not p.factory._spawned:
                problems.append('no actors spawned')
            if p._paints:
                CONTROLS.add(p)
        except Exception as e:
            _log_exception(f'swaptube_{name}', e)
            problems.append(repr(e))
        results.update(_result(
            f'swaptube_{name}', None if problems else p,
            extra='; '.join(problems) or f'{len(p.factory._spawned)} actors',
            elapsed=time.monotonic() - t0))
    return results

View it on GitHub

From the tests: test_zoom_plot (Content/Scripts/test_spawn.py:1816)
def test_zoom_plot(base_y=0):
    from ue_spawn import spawn_zoom_plot
    t0 = time.monotonic()
    try:
        actor = spawn_zoom_plot(location=FVector(0, base_y + 300, 250))
    except Exception as e:
        _log_exception('zoom_plot', e)
        actor = None
    return _result('zoom_plot', actor, elapsed=time.monotonic() - t0)

View it on GitHub