Primitives 3d

Cubes, spheres, cylinders, cones and planes as lit meshes, with their segments, rings and caps.

Primitives 3d
View on GitHubgaanim examples/3d/primitives_3d.py
Code · 85 lines
"""3D primitives: the lit meshes scene.geometry builds, and their resolution options.

Each primitive is a Primitive3D tilted toward the viewer so its depth shows,
and appears with ``create()``, which grows the mesh from its center. The
default camera is orthographic and looks down the z axis, so the z = 0 plane
lines up with the layout zones. Without a material a primitive is lit matte
white; each label is the ``scene.geometry`` call that builds the variant.
"""

import os

from gaanim import Scene, Zones

DRAW = 1.2
HOLD = 0.8
# Turn every primitive about x to show its top and about y to show a side.
TILT = (0.45, -0.6, 0)

scene = Scene()


def gallery(rows, tilt=TILT):
    """Lay out rows of (label, primitive) pairs, each primitive above its label.

    Every row splits its width evenly between its variants, and every
    primitive turns by ``tilt``.
    """
    bands = scene.layout.zones(Zones.rows(len(rows), gap="48px", padding="page_padding"))
    shapes = []
    for band, variants in zip(bands, rows):
        for cell, (label, shape) in zip(band.split(Zones.columns(len(variants), gap="48px")), variants):
            art, caption = cell.split(Zones.rows(["1fr", 0.5]))
            scene.text(label, role="code").place(caption)
            shapes.append(shape.move_to(*art.center).rotate_to_3d(*tilt))
    scene.play([shape.animate.create() for shape in shapes], duration=DRAW)
    scene.wait(HOLD)


# Cylinders and cones stand along y; a plane lies flat in x and z, facing up,
# and takes subdivisions=(columns, rows) to split it into cells.
scene.segment("solids")
gallery([
    [
        ("cube(2.2)", scene.geometry.cube(2.2)),
        ("sphere(1.5)", scene.geometry.sphere(1.5)),
        ("cylinder(1.1, 2.4)", scene.geometry.cylinder(1.1, 2.4)),
    ],
    [
        ("cone(1.3, 2.3)", scene.geometry.cone(1.3, 2.3)),
        ("plane(4, 3)", scene.geometry.plane(4, 3)),
    ],
])

# segments sets how many sides round primitives have, and a sphere's rings how
# many bands run from pole to pole: few of them make faceted solids.
scene.segment("facets")
gallery([
    [
        ("sphere(1.4, segments=8, rings=4)", scene.geometry.sphere(1.4, segments=8, rings=4)),
        ("sphere(1.4, segments=12, rings=8)", scene.geometry.sphere(1.4, segments=12, rings=8)),
    ],
    [
        ("cylinder(1.1, 2.2, segments=6)", scene.geometry.cylinder(1.1, 2.2, segments=6)),
        ("cone(1.3, 2.4, segments=4)", scene.geometry.cone(1.3, 2.4, segments=4)),
    ],
])

# Without their caps, cylinders and cones are open shells, here seen from
# below. Lit meshes hide the faces turned away from the viewer, so the inside
# of the far wall does not draw.
scene.segment("open")
gallery(
    [[
        ("cylinder(1.6, 3.4, caps=False)", scene.geometry.cylinder(1.6, 3.4, caps=False)),
        ("cone(1.8, 3.4, cap=False)", scene.geometry.cone(1.8, 3.4, cap=False)),
    ]],
    tilt=(-0.5, -0.6, 0),
)

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    # Growing and settled, in each of the three segments.
    scene.snapshots(snapshots, [(DRAW + HOLD) * index + t for index in range(3) for t in (0.5, 1.6)])
else:
    scene.render()

Materials 3d

Matte, metal and emissive materials, roughness, metallic and emission settings, and animated materials and fills.

Materials 3d
View on GitHubgaanim examples/3d/materials_3d.py
Code · 149 lines
"""3D materials: Material3D presets, surface finish, emission and material animations.

Presets and animations show each material on a cube, whose flat faces each
take one shade, and on a sphere, whose smooth shading shows the highlight;
the channel tables use spheres alone. Segments cover the presets, the
roughness and metallic channels of the constructor, emission, and animating
a primitive from one material to another.
"""

import os

from gaanim import Material3D, Scene, Zones

DRAW = 1.0
DURATION = 1.6
HOLD = 0.8
TILT = (0.45, -0.6, 0)

scene = Scene()
accent = scene.colors.accent
success = scene.colors.success
danger = scene.colors.danger
rule = scene.colors.rule

# One studio rig lights every lit primitive of the scene: sky and ground
# light, a soft key light from the upper left and a faint rim. intensity
# scales it, and "none" leaves only what materials emit.
scene.geometry.lighting_3d("studio", intensity=1.0)


def swatch(zone, material):
    """A tilted cube and a sphere side by side in ``zone``, both of ``material``."""
    left, right = zone.split(Zones.columns(2, gap="24px"))
    side = min(left.width, left.height)
    cube = scene.geometry.cube(side * 0.6, material=material).move_to(*left.center).rotate_to_3d(*TILT)
    sphere = scene.geometry.sphere(side * 0.45, material=material).move_to(*right.center)
    return [cube, sphere]


def reveal(shapes):
    """Grow ``shapes`` together, then hold them."""
    scene.play([shape.animate.create() for shape in shapes], duration=DRAW)
    scene.wait(HOLD)


def gallery(variants):
    """Two columns of (label, material) pairs, each swatch above its label.

    The second column is wider, for the longer labels.
    """
    grid = scene.layout.zones(Zones.grid(rows=2, columns=["1fr", "1.4fr"], gap="48px", padding="page_padding"))
    shapes = []
    for zone, (label, material) in zip(grid, variants):
        art, caption = zone.split(Zones.rows(["1fr", 0.5]))
        scene.text(label, role="code").place(caption)
        shapes += swatch(art, material)
    reveal(shapes)


def matrix(rows, columns, build, label_track):
    """One sphere per (row, column) pair, labelled by its row on the left and its column above.

    ``rows`` and ``columns`` are (label, value) pairs; ``build(row, column)``
    makes the cell's material. ``label_track`` is the width of the label column.
    """
    grid = scene.layout.zones(
        Zones.grid(
            rows=[0.5] + ["1fr"] * len(rows),
            columns=[label_track] + ["1fr"] * len(columns),
            row_gap="24px",
            column_gap="48px",
            padding="page_padding",
        )
    )
    width = len(columns) + 1
    for index, (label, _) in enumerate(columns, start=1):
        scene.text(label, role="code").place(grid[index])
    shapes = []
    for row_index, (label, row) in enumerate(rows, start=1):
        scene.text(label, role="code").place(grid[row_index * width], anchor="right")
        for index, (_, column) in enumerate(columns, start=1):
            cell = grid[row_index * width + index]
            radius = min(cell.width, cell.height) * 0.45
            shapes.append(scene.geometry.sphere(radius, material=build(row, column)).move_to(*cell.center))
    reveal(shapes)


# Presets: matte, polished metal, and a material that glows in its own color.
scene.segment("presets")
gallery([
    ("Material3D.matte(accent)", Material3D.matte(accent)),
    ("Material3D.metal(accent)", Material3D.metal(accent)),
    ("Material3D.emissive(accent)", Material3D.emissive(accent)),
    ("Material3D.emissive(accent, strength=2)", Material3D.emissive(accent, strength=2)),
])

# The constructor sets each channel: Material3D(accent, roughness=0.1, metallic=0.5).
# Low roughness gives a sharp highlight; metals reflect the sky instead of
# scattering light.
scene.segment("finish")
matrix(
    [("roughness=0.1", 0.1), ("roughness=0.5", 0.5), ("roughness=0.9", 0.9)],
    [("metallic=0", 0.0), ("metallic=0.5", 0.5), ("metallic=1", 1.0)],
    lambda roughness, metallic: Material3D(accent, roughness=roughness, metallic=metallic),
    "2fr",
)

# Emission adds its color on top of the lit surface:
# Material3D(rule, emissive=accent, emissive_strength=0.5).
scene.segment("emission")
matrix(
    [("emissive_strength=0", 0.0), ("emissive_strength=0.5", 0.5), ("emissive_strength=1", 1.0)],
    [("emissive=accent", accent), ("emissive=success", success)],
    lambda strength, color: Material3D(rule, emissive=color, emissive_strength=strength),
    "1fr",
)

# animate.material() blends every channel at once and animate.fill() only the
# base color; .material(...) without animate swaps it at the cursor.
scene.segment("animate")
CHANGES = [
    ("animate.material(Material3D.metal(accent))", lambda shape: shape.animate.material(Material3D.metal(accent))),
    (
        "animate.material(Material3D.emissive(accent))",
        lambda shape: shape.animate.material(Material3D.emissive(accent)),
    ),
    ("animate.fill(success)", lambda shape: shape.animate.fill(success)),
    ("animate.fill(danger)", lambda shape: shape.animate.fill(danger)),
]
grid = scene.layout.zones(
    Zones.grid(rows=len(CHANGES), columns=["2fr", "1fr"], gap="24px", column_gap="48px", padding="page_padding")
)
moves = []
for index, (label, change) in enumerate(CHANGES):
    scene.text(label, role="code").place(grid[2 * index], anchor="right")
    moves += [change(shape) for shape in swatch(grid[2 * index + 1], Material3D.matte(accent))]
scene.wait(HOLD)
scene.play(moves, duration=DURATION)
scene.wait(HOLD)

# Growing and settled in the first segment, settled in the next two, and
# before, during and after the change in the last.
segment = DRAW + HOLD
SEEKS = [0.6, 1.4, segment + 1.4, 2 * segment + 1.4] + [3 * segment + t for t in (0.4, 1.6, 3.0)]
if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, SEEKS)
else:
    scene.render()

Transforms 3d

Turning, moving and scaling drawables in depth with the _3d methods, about their center or a pivot.

Transforms 3d
View on GitHubgaanim examples/3d/transforms_3d.py
Code · 126 lines
"""3D transforms: turning, moving and scaling drawables in depth with the _3d methods.

Each variant animates an extruded L, whose shape tells every turn apart, away
from the pose a faint copy keeps, and is labelled with the call chained on
``shape.animate``. A perspective camera frames the z = 0 plane exactly like
the 2D layout, so the zones place the shapes and depth shows as size.
"""

import math
import os

from gaanim import Scene, Zones

DURATION = 1.6
HOLD = 0.6
# The L's outline, a unit tall; extruded, it becomes a solid.
L_SHAPE = [(0, 0), (0.8, 0), (0.8, 0.28), (0.28, 0.28), (0.28, 1), (0, 1)]
# A slight turn about x and y, so the L's depth shows before it moves.
TILT = (0.35, -0.45, 0)

scene = Scene()

# At DISTANCE from the z = 0 plane, a vertical field of view that spans the
# frame's height makes that plane line up with the frame.
frame = scene.layout.zones(Zones.rows(1))[0]
DISTANCE = 20
scene.camera.perspective(fov_y=2 * math.atan(frame.height / 2 / DISTANCE))
scene.camera.look_at(eye=(0, 0, DISTANCE), target=(0, 0, 0))


def solid(zone):
    """An extruded L filling most of ``zone``'s height, centered in it and tilted."""
    size = zone.height * 0.75
    outline = scene.geometry.polygon(L_SHAPE).scale_to(size).move_to(*zone.center)
    return scene.geometry.extrude(outline, depth=size * 0.3, bevel=size * 0.03).rotate_to_3d(*TILT)


def pose(zone):
    """A solid L that moves, over a faint copy that keeps its starting pose."""
    solid(zone).opacity(0.2)
    return solid(zone)


def play(moves):
    """Hold the starting poses, play ``moves`` together, then hold the result."""
    scene.wait(HOLD)
    scene.play(moves, duration=DURATION)
    scene.wait(HOLD)


def table(entries):
    """One row per (label, change) entry, its code to the left of its L.

    ``change(shape, zone)`` returns the animation of the row's L.
    """
    grid = scene.layout.zones(
        Zones.grid(rows=len(entries), columns=["1fr", "1fr"], gap="24px", column_gap="48px", padding="page_padding")
    )
    moves = []
    for index, (label, change) in enumerate(entries):
        scene.text(label, role="code", text_align="right").place(grid[2 * index], anchor="right")
        zone = grid[2 * index + 1]
        moves.append(change(pose(zone), zone))
    play(moves)


def gallery(entries):
    """One column per (label, change) entry, its code under its L."""
    columns = scene.layout.zones(Zones.columns(len(entries), gap="48px", padding="page_padding"))
    moves = []
    for column, (label, change) in zip(columns, entries):
        # The L sits in a band above the middle, with room to grow toward the camera.
        _, art, _, caption = column.split(Zones.rows(["1fr", 2.6, "1fr", 0.5]))
        scene.text(label, role="code").place(caption)
        moves.append(change(pose(art), art))
    play(moves)


# A turn about one of the scene's axes.
scene.segment("axes")
table([
    ('rotate_by_3d("x", math.pi)', lambda shape, zone: shape.animate.rotate_by_3d("x", math.pi)),
    ('rotate_by_3d("y", math.pi)', lambda shape, zone: shape.animate.rotate_by_3d("y", math.pi)),
    ('rotate_by_3d("z", math.pi / 2)', lambda shape, zone: shape.animate.rotate_by_3d("z", math.pi / 2)),
])


# rotate_to_3d sets absolute angles about x, y and z. with_pivot_3d, called
# on the shape before the move, sets the scene point turns go about: here the
# foot of the L, which tips it over onto its base.
def about_foot(shape, zone):
    x, y = zone.center
    foot = (x, y - zone.height * 0.375)
    return shape.with_pivot_3d(*foot, 0).animate.rotate_by_3d("x", -math.pi / 2)


scene.segment("orient")
table([
    ("rotate_to_3d(0, 0, 0)", lambda shape, zone: shape.animate.rotate_to_3d(0, 0, 0)),
    ("rotate_to_3d(0, 1.2, 0.6)", lambda shape, zone: shape.animate.rotate_to_3d(0, 1.2, 0.6)),
    ('with_pivot_3d(*foot, 0)\nrotate_by_3d("x", -math.pi / 2)', about_foot),
])

# Positions in depth: toward the camera a shape grows and drifts away from the
# frame's center, away from it it shrinks toward the center.
scene.segment("move")
gallery([
    ("shift_by_3d(0, 0, -20)", lambda shape, zone: shape.animate.shift_by_3d(0, 0, -20)),
    ("move_to_3d(x, y, 6)", lambda shape, zone: shape.animate.move_to_3d(*zone.center, 6)),
    ("shift_by_3d(-2, 0, 5)", lambda shape, zone: shape.animate.shift_by_3d(-2, 0, 5)),
])

# Per-axis scale, z included: scaling z deepens the extrusion.
scene.segment("scale")
table([
    ("scale_by_3d(1, 1, 4)", lambda shape, zone: shape.animate.scale_by_3d(1, 1, 4)),
    ("scale_to_3d(1.6, 0.6, 1)", lambda shape, zone: shape.animate.scale_to_3d(1.6, 0.6, 1)),
    ("scale_by_3d(0.5, 0.5, 3)", lambda shape, zone: shape.animate.scale_by_3d(0.5, 0.5, 3)),
])

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    # Mid-move and settled, in each of the four segments.
    scene.snapshots(snapshots, [(DURATION + 2 * HOLD) * index + t for index in range(4) for t in (1.4, 2.7)])
else:
    scene.render()

Deform 3d

A displacement field that bends a whole model: nodes, the 3D lines between them, slabs and a wall that curves, eased into a structural mode or swayed by a parameter.

Deform 3d
View on GitHubgaanim examples/3d/deform_3d.py
Code · 89 lines
"""Deform 3D: a displacement field that bends a whole model, eased in or swayed by a parameter.

``drawable.deform(field)`` and ``drawable.animate.deform(field)`` displace a
group and everything in it by ``field(x, y, z) -> (dx, dy, dz)``, read in the
world: the nodes move, the columns drawn as ``line_3d`` between them follow,
the slabs move with their floor and the wall, a subdivided ``plane``, bends
vertex by vertex. Here the field is a structure's first mode, a quarter sine
up its height. Each label is the code that deforms the model.
"""

import math
import os

from gaanim import Material3D, Scene, Zones

scene = Scene()
accent = scene.colors.accent
success = scene.colors.success
muted = scene.colors.muted
foreground = scene.colors.foreground

HEIGHT = 6.0
FLOORS = (0.0, 3.0, 6.0)
CORNERS = [(x, z) for x in (-2.0, 2.0) for z in (-1.5, 1.5)]


def mode(x, y, z):
    """The first mode: x moves with a quarter sine of the height."""
    return (math.sin(math.pi * y / (2 * HEIGHT)), 0.0, 0.0)


def frame(label):
    """A two-storey frame, its label pinned at the top, under a 3D camera."""
    zones = scene.layout.zones(Zones.rows(["120px", "1fr"], padding="page_padding"))
    scene.text(label, role="code").hud().place(zones[0], anchor="left")
    scene.camera.to(scene.camera.state_3d(eye=(9, 7, 13), target=(0, 2.6, 0), fov_y=0.7, screen_offset=(0, -0.6)))
    nodes = {
        (x, y, z): scene.geometry.sphere(0.12, material=Material3D.matte(accent)).move_to_3d(x, y, z)
        for x, z in CORNERS
        for y in FLOORS
    }
    columns = [
        scene.geometry.line_3d(nodes[(x, low, z)], nodes[(x, high, z)], 0.08, material=Material3D.matte(muted))
        for x, z in CORNERS
        for low, high in zip(FLOORS, FLOORS[1:])
    ]
    slabs = [
        scene.geometry.cube(1.0, material=Material3D.matte(foreground)).scale_to_3d(4.4, 0.15, 3.4).move_to_3d(0, y, 0)
        for y in FLOORS[1:]
    ]
    # A wall standing in y/z on the left side, subdivided so it can bend.
    wall = scene.geometry.plane(HEIGHT, 3.0, subdivisions=(12, 4), material=Material3D.matte(success))
    # Turned so its lit side faces in, toward the camera.
    wall.rotate_to_3d(0, 0, -math.pi / 2).move_to_3d(-2.0, HEIGHT / 2, 0)
    floor = scene.geometry.plane(7.0, 5.0, material=Material3D.matte(muted)).move_to_3d(0, -0.01, 0)
    return scene.geometry.group(*nodes.values(), *columns, *slabs, wall), floor


shown = []

# animate.deform eases the model into the field, and deform(None) back.
scene.segment("mode")
model, _ = frame("model.animate.deform(mode)")
scene.wait(0.4)
scene.play(model.animate.deform(mode).duration(1.5))
shown.append(scene.cursor - 0.1)
scene.wait(0.4)
scene.play(model.animate.deform(None).duration(1.0))
scene.wait(0.3)

# With amount= a parameter, the field scales with it: animating the
# parameter sways the model and damps it.
scene.segment("sway")
model, _ = frame("model.deform(mode, amount=sway)")
sway = scene.viz.parameter(0.0)
model.deform(mode, amount=sway)
scene.wait(0.3)
for value in (0.9, -0.7, 0.45, -0.25, 0.0):
    scene.play(sway.animate.set(value).duration(0.45))
    if value == -0.7:
        shown.append(scene.cursor - 0.02)
scene.wait(0.3)

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    # The mode reached, and the sway at its far side.
    scene.snapshots(snapshots, shown)
else:
    scene.render()

Extrusion

Text, equations, SVGs, shapes with holes and groups extruded into lit solids, with depth, bevel, tolerance and materials.

Extrusion
View on GitHubgaanim examples/3d/extrusion.py
Code · 127 lines
"""Extrusion: turning the area a 2D drawable fills into a lit 3D solid.

``scene.geometry.extrude(source)`` reads the outline of text, equations,
imported SVGs, shapes and groups, keeps their holes, and builds a closed mesh
in the source's fill color, facing the camera. Each solid then turns so its
depth shows. Segments cover the sources, the depth and bevel of the mesh, and
its remaining options.
"""

import os

from gaanim import Material3D, Scene, Zones

DRAW = 1.0
TURN = 1.4
HOLD = 0.6
# The pose every solid turns to, about x and y.
TILT = (0.4, -0.7, 0)

scene = Scene()
accent = scene.colors.accent
foreground = scene.colors.foreground


def show(solids):
    """Grow ``solids`` facing the camera, turn them so their depth shows, then hold."""
    scene.play([solid.animate.create() for solid in solids], duration=DRAW)
    scene.play([solid.animate.rotate_to_3d(*TILT) for solid in solids], duration=TURN)
    scene.wait(HOLD)


def table(entries):
    """One row per (label, build) entry, its code to the left: ``build(zone)`` returns the row's solid."""
    grid = scene.layout.zones(
        Zones.grid(rows=len(entries), columns=["5fr", "4fr"], gap="24px", column_gap="48px", padding="page_padding")
    )
    solids = []
    for index, (label, build) in enumerate(entries):
        scene.text(label, role="code").place(grid[2 * index], anchor="right")
        solids.append(build(grid[2 * index + 1]))
    show(solids)


def extrude(source):
    """Scale ``source`` to fill its zone, with room to turn, and extrude it half a unit deep."""
    return lambda zone: scene.geometry.extrude(
        source.place(zone.inset(zone.height * 0.08), fit="contain"), depth=0.5, bevel=0.04
    )


# Each label is the source passed to scene.geometry.extrude(source, depth=0.5, bevel=0.04).
# Text and equations keep the holes of their letters; an SVG becomes one solid
# in the color of its fill.
scene.segment("outlines")
table([
    ('scene.text("Bg8")', extrude(scene.text("Bg8"))),
    ('scene.text.equation("e^(i pi)")', extrude(scene.text.equation("e^(i pi)"))),
    ('scene.media.svg("assets/icon.svg")', extrude(scene.media.svg("assets/icon.svg"))),
])

# Shapes fill with the nonzero rule, so an annulus keeps its hole and a group
# extrudes as the union of its members.
disc = scene.geometry.circle(1).move_to(-0.7, 0)
block = scene.geometry.square(1.8).move_to(0.7, 0)
scene.segment("shapes")
table([
    ("scene.geometry.annulus(1, 0.5)", extrude(scene.geometry.annulus(1, 0.5))),
    ("scene.geometry.star(5, 1, 0.4)", extrude(scene.geometry.star(5, 1, 0.4))),
    ("scene.geometry.group([disc, block])", extrude(scene.geometry.group([disc, block]))),
])


# depth is the solid's thickness, centered on z = 0; bevel cuts a 45° chamfer
# that wide around both caps and must stay under half the depth:
# scene.geometry.extrude(star, depth=0.6, bevel=0.05).
def star_solid(depth, bevel):
    return lambda zone: scene.geometry.extrude(
        scene.geometry.star(5, zone.height * 0.48, zone.height * 0.22).place(zone), depth=depth, bevel=bevel
    )


scene.segment("depth")
DEPTHS = [("depth=0.3", 0.3), ("depth=0.6", 0.6), ("depth=1.2", 1.2)]
BEVELS = [("bevel=0", 0.0), ("bevel=0.07", 0.07), ("bevel=0.14", 0.14)]
grid = scene.layout.zones(
    Zones.grid(rows=[0.5, "1fr", "1fr", "1fr"], columns=["1fr", "2fr", "2fr", "2fr"], gap="24px", padding="page_padding")
)
for index, (label, _) in enumerate(BEVELS, start=1):
    scene.text(label, role="code").place(grid[index])
solids = []
for row, (label, depth) in enumerate(DEPTHS, start=1):
    scene.text(label, role="code").place(grid[4 * row], anchor="right")
    for column, (_, bevel) in enumerate(BEVELS, start=1):
        solids.append(star_solid(depth, bevel)(grid[4 * row + column]))
show(solids)

# Each label is an option of scene.geometry.extrude(circle, depth=0.5, ...):
# tolerance sets how finely curves flatten, keep_source keeps the 2D source
# visible over the solid (2D always draws over 3D), and material replaces
# the matte fill color.
def disc_solid(**options):
    return lambda zone: scene.geometry.extrude(
        scene.geometry.circle(zone.height * 0.42).place(zone), depth=0.5, **options
    )


def kept_outline(zone):
    """A solid whose kept source, outlined and faded, stays flat over it."""
    circle = scene.geometry.circle(zone.height * 0.42).place(zone)
    solid = scene.geometry.extrude(circle, depth=0.5, keep_source=True)
    circle.stroke(foreground, 0.05).opacity(0.4)
    return solid


scene.segment("options")
table([
    ("tolerance=0.25", disc_solid(tolerance=0.25)),
    ("keep_source=True", kept_outline),
    ("material=Material3D.metal(accent)", disc_solid(material=Material3D.metal(accent))),
])

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    # Facing the camera, turning and turned, in each of the four segments.
    scene.snapshots(snapshots, [(DRAW + TURN + HOLD) * index + t for index in range(4) for t in (0.9, 1.7, 2.8)])
else:
    scene.render()

3D morphs

A mesh morphing into another with transform_to: spheres, tori and planes matched by their texture coordinates, cubes, cylinders and cones by rays from their center, and one mesh morphing through three targets in turn.

3D morphs
View on GitHubgaanim examples/3d/morph_3d.py
Code · 117 lines
"""3D morphs: animate.transform_to turns one mesh into another where that one stands.

Both meshes are sampled on one grid, and each grid point moves from one to the
other. A mesh whose texture coordinates cover it once (a sphere, a torus, a
revolved profile) is sampled by them, so a sphere opens its poles into a
torus's hole and a vase rounds into a sphere along its profile; any other (a
cube, a capped cylinder or cone)
by rays from its center, so a sphere swells into a cube point by point. The
target is a template that stays hidden: the morphing mesh also takes its
place, turn, size and material. Each label is the call that plays the morph,
and before and after it every mesh is drawn exactly as built.
"""

import os

from gaanim import Material3D, Scene, Zones

DRAW = 0.8
MORPH = 2.0
HOLD = 0.8
# Turn every mesh about x to show its top and about y to show a side.
TILT = (0.45, -0.6, 0)
# A vase's (r, y) profile, from the axis at its foot up to the axis at its
# mouth, in fractions of its zone around its middle.
VASE = [(0, -0.3), (0.2, -0.3), (0.25, -0.12), (0.12, 0.12), (0.16, 0.3), (0, 0.3)]
SEEKS = []

scene = Scene()
accent = Material3D.matte(scene.colors.accent)
success = Material3D.matte(scene.colors.success)
danger = Material3D.matte(scene.colors.danger)


def morph(plays):
    """Play ``plays`` together and hold the result, noting the instants to capture."""
    SEEKS.append(scene.cursor + MORPH / 2)
    scene.play(plays, duration=MORPH)
    SEEKS.append(scene.cursor + HOLD / 2)
    scene.wait(HOLD)


def morphs(variants):
    """Morph each (label, source, target) pair in its own column, above its label.

    A pair's meshes stand in the same zone, sized to it by ``build(side)``;
    the sources grow in, then morph together.
    """
    columns = scene.layout.zones(Zones.columns(len(variants), gap="48px", padding="page_padding"))
    sources = []
    plays = []
    for zone, (label, build_source, build_target) in zip(columns, variants):
        art, caption = zone.split(Zones.rows(["1fr", 0.4]))
        side = min(art.width, art.height)
        source = build_source(side).move_to(*art.center).rotate_to_3d(*TILT)
        target = build_target(side).move_to(*art.center).rotate_to_3d(*TILT)
        scene.text(label, role="code").place(caption)
        sources.append(source)
        plays.append(source.animate.transform_to(target))
    scene.play([source.animate.create() for source in sources], duration=DRAW)
    SEEKS.append(scene.cursor)
    morph(plays)


# Spheres, tori and revolved profiles are sampled by their texture coordinates.
scene.segment("coordinates")
morphs([
    ("ball.animate.transform_to(ring)",
     lambda side: scene.geometry.sphere(side * 0.3, material=accent),
     lambda side: scene.geometry.torus(side * 0.28, side * 0.11, material=success)),
    ("vase.animate.transform_to(ball)",
     lambda side: scene.geometry.revolve(
         [(r * side, y * side) for r, y in VASE], material=accent,
     ),
     lambda side: scene.geometry.sphere(side * 0.28, material=success)),
])

# Cubes and capped cylinders and cones are sampled by rays from their center.
scene.segment("rays")
morphs([
    ("ball.animate.transform_to(box)",
     lambda side: scene.geometry.sphere(side * 0.3, material=accent),
     lambda side: scene.geometry.cube(side * 0.46, material=success)),
    ("can.animate.transform_to(cone)",
     lambda side: scene.geometry.cylinder(side * 0.24, side * 0.56, material=accent),
     lambda side: scene.geometry.cone(side * 0.3, side * 0.56, material=danger)),
])

# One mesh morphs through three targets in turn, each from the last: it moves
# to where each one stands and takes its turn, size and material. The caption
# below names each call as it plays.
scene.segment("chain")
page = scene.layout.zones(Zones.rows(["1fr", "80px"]))
stops = page[0].inset("page_padding").split(Zones.columns(3, gap="48px"))
strip = page[1].inset((0, "page_padding"))
side = min(stops[0].width, stops[0].height)
ball = scene.geometry.sphere(side * 0.3, material=accent).move_to(*stops[0].center).rotate_to_3d(*TILT)
calls = [
    ("ball.animate.transform_to(box)",
     scene.geometry.cube(side * 0.46, material=success).move_to(*stops[1].center).rotate_to_3d(0.6, 0.5, 0)),
    ("ball.animate.transform_to(ring)",
     scene.geometry.torus(side * 0.28, side * 0.11, material=danger).move_to(*stops[2].center).rotate_to_3d(1.1, 0, 0)),
    ("ball.animate.transform_to(home)",
     scene.geometry.sphere(side * 0.3, material=accent).move_to(*stops[0].center)),
]
captions = [scene.text(label, role="code").place(strip, anchor="left").hidden() for label, _ in calls]
scene.play([ball.animate.create()], duration=DRAW)
for index, (_, target) in enumerate(calls):
    swap = [captions[index].animate.fade_in().duration(0.2)]
    if index:
        swap.append(captions[index - 1].animate.fade_out().duration(0.15))
    morph(swap + [ball.animate.transform_to(target).duration(MORPH)])

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, SEEKS)
else:
    scene.render()

3D point clouds and copies

One drawable that draws one mesh at many points: spheres at each point of a cloud, colored or not, voxels and an arrow field copied from a primitive, and clouds and fields moving copy by copy into another set with transform_to.

3D point clouds and copies
View on GitHubgaanim examples/3d/points_3d.py
Code · 189 lines
"""Point clouds and copies of a mesh: one drawable draws one mesh at many points.

geometry.points_3d puts a lit sphere at each point, and geometry.instances
copies a primitive's mesh and material to each position, scaled, turned and
colored copy by copy. The mesh uploads once and every copy draws in one
instanced draw, so thousands of points stay one drawable that moves, turns
and is lit as a whole. create() grows the copies in one after another, in
the order given, and transform_to moves each copy to the copy at its place in
another set of as many. Each label is the call that builds or plays its
variant.
"""

import math
import os

from gaanim import ColorMap, Material3D, Scene, Zones

DRAW = 1.6
MOVE = 2.0
HOLD = 0.8
# Turn every drawable about x to show its top and about y to show a side.
TILT = (0.45, -0.6, 0)
GOLDEN = math.pi * (3 - math.sqrt(5))
SEEKS = []

scene = Scene()
accent = scene.colors.accent
success = scene.colors.success
blend = ColorMap.from_colors([accent, success])


def ball(count, radius):
    """``count`` points spread evenly over a sphere of ``radius``, from bottom to top."""
    points = []
    for k in range(count):
        y = 2 * (k + 0.5) / count - 1
        ring = math.sqrt(1 - y * y)
        angle = k * GOLDEN
        points.append((radius * ring * math.cos(angle), radius * y, radius * ring * math.sin(angle)))
    return points


def helix(count, radius, height):
    """Two strands of ``count`` points each, interleaved from bottom to top."""
    points = []
    for k in range(count):
        t = k / (count - 1)
        for strand in (0, math.pi):
            angle = 4 * math.pi * t + strand
            points.append((radius * math.cos(angle), height * (t - 0.5), radius * math.sin(angle)))
    return points


def lattice(per_side, side):
    """A cube of ``per_side``³ points ``side`` across, from bottom to top."""
    step = side / (per_side - 1)
    return [
        (x * step - side / 2, y * step - side / 2, z * step - side / 2)
        for y in range(per_side)
        for z in range(per_side)
        for x in range(per_side)
    ]


def field(per_side, side, swirl):
    """Arrows on a ``per_side``² grid ``side`` across: their places, turns and lengths.

    Each arrow points away from the middle, turned ``swirl`` radians towards
    going around it; its length grows away from the middle.
    """
    step = side / (per_side - 1)
    places, turns, lengths = [], [], []
    for row in range(per_side):
        for column in range(per_side):
            x, y = column * step - side / 2, row * step - side / 2
            out = math.atan2(-x, y) if (x, y) != (0, 0) else 0.0
            places.append((x, y, 0))
            turns.append((0, 0, out + swirl))
            lengths.append(0.5 + math.hypot(x, y) / side)
    return places, turns, lengths


def columns(count):
    """The art and caption zones of ``count`` columns side by side."""
    zones = scene.layout.zones(Zones.columns(count, gap="48px", padding="page_padding"))
    return [zone.split(Zones.rows(["1fr", 0.4])) for zone in zones]


def place(build, art):
    """``build(side)`` sized to ``art`` and placed in it, turned by TILT to show its depth."""
    return build(min(art.width, art.height)).move_to(*art.center).rotate_to_3d(*TILT)


def variants(pairs):
    """Build each (label, build) pair in its own column, above its label, which shrinks to fit."""
    built = []
    for (art, caption), (label, build) in zip(columns(len(pairs)), pairs):
        built.append(place(build, art))
        scene.text(label, role="code").place(caption, fit="scale_down")
    return built


def grow(drawables):
    """Grow ``drawables`` in together and hold them, noting the instants to capture."""
    SEEKS.append(scene.cursor + DRAW / 2)
    scene.play([drawable.animate.create() for drawable in drawables], duration=DRAW)
    SEEKS.append(scene.cursor + HOLD / 2)
    scene.wait(HOLD)


# A sphere at each point, in the material's color or one color per point.
scene.segment("points")
grow(variants([
    ("points_3d(ball, radius=...)",
     lambda side: scene.geometry.points_3d(
         ball(1200, side * 0.36), radius=side * 0.012, material=Material3D.matte(accent),
     )),
    ("points_3d(helix, colors=shades)",
     lambda side: scene.geometry.points_3d(
         helix(240, side * 0.2, side * 0.7), radius=side * 0.016,
         colors=[blend.sample(k % 2) for k in range(480)],
     )),
]))


def voxels(side):
    """The cells of a ball on a grid, from the middle out, shaded by height."""
    cube = scene.geometry.cube(side * 0.07, material=Material3D.matte(accent))
    step = side * 0.08
    cells = [
        (x * step, y * step, z * step)
        for x in range(-4, 5) for y in range(-4, 5) for z in range(-4, 5)
        if x * x + y * y + z * z <= 18
    ]
    cells.sort(key=lambda cell: cell[0] ** 2 + cell[1] ** 2 + cell[2] ** 2)
    shades = [blend.sample(0.5 + y / (8 * step)) for _, y, _ in cells]
    return scene.geometry.instances(cube, cells, colors=shades)


def arrows(side, swirl, scaled):
    """An arrow field across the art, each arrow turned by ``swirl`` from pointing out.

    The arrows are all as long unless ``scaled``.
    """
    arrow = scene.geometry.arrow_3d((0, -side * 0.04, 0), (0, side * 0.04, 0), material=Material3D.matte(success))
    places, turns, lengths = field(7, side * 0.7, swirl)
    if scaled:
        return scene.geometry.instances(arrow, places, rotations=turns, scales=lengths)
    return scene.geometry.instances(arrow, places, rotations=turns)


# Copies of a primitive's mesh, each colored, turned or scaled.
scene.segment("copies")
grow(variants([
    ("instances(cube, cells, colors=shades)", voxels),
    ("instances(arrow, places, rotations=turns)", lambda side: arrows(side, 0, scaled=False)),
]))

# Each copy moves to the copy at its place in another set of as many: points
# move along straight lines, and arrows turn the shorter way round and take
# the lengths of the swirl's.
scene.segment("transform")
cloud, spread = variants([
    ("cloud.animate.transform_to(globe)",
     lambda side: scene.geometry.points_3d(
         lattice(9, side * 0.5), radius=side * 0.014, material=Material3D.matte(accent),
     )),
    ("spread.animate.transform_to(swirl)", lambda side: arrows(side, 0, scaled=False)),
])
# The targets are templates in the same places, which stay hidden.
(cloud_art, _), (spread_art, _) = columns(2)
globe = place(
    lambda side: scene.geometry.points_3d(
        ball(729, side * 0.32), radius=side * 0.014, material=Material3D.matte(success),
    ),
    cloud_art,
)
swirl = place(lambda side: arrows(side, math.pi / 2, scaled=True), spread_art)
grow([cloud, spread])
SEEKS.append(scene.cursor + MOVE / 2)
scene.play([cloud.animate.transform_to(globe), spread.animate.transform_to(swirl)], duration=MOVE)
SEEKS.append(scene.cursor + HOLD / 2)
scene.wait(HOLD)

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, SEEKS)
else:
    scene.render()

Shapes 3d

Tori, arrows between two points, tubes along open, creased and closed paths, flat sheets of text, equations and shapes, and lit lines between points or the drawables they follow.

Shapes 3d
View on GitHubgaanim examples/3d/shapes_3d.py
Code · 216 lines
"""3D shapes from points and outlines: tori, arrows, tubes, flat sheets and lines.

Arrows run between two world-space points and tubes along a list of them;
each sits at the center of its points, so it turns and grows about it there.
A 3D line runs between two ends, points or drawables it follows.
A flat sheet is the area a 2D drawable fills, like an extrusion with no
depth, with a face on each side. All of them are lit, closed meshes that
appear with ``create()``. The default camera is orthographic and looks down
the z axis, so the z = 0 plane lines up with the layout zones; each label is
the ``scene.geometry`` call that builds the variant.
"""

import math
import os

from gaanim import Material3D, Scene, Zones

DRAW = 1.2
TURN = 1.4
HOLD = 0.8
# Turn tori about x to look into their hole, and tubes about x and y to show
# their depth.
TIP = (0.9, 0.3, 0)
TILT = (0.45, -0.6, 0)

scene = Scene()
accent = scene.colors.accent
success = scene.colors.success
# Times worth a snapshot: while shapes grow, and once each move settles.
moments = []


def reveal(shapes, turns=()):
    """Grow ``shapes``, turn them through each pose of ``turns``, then hold."""
    moments.append(scene.cursor + DRAW / 2)
    scene.play([shape.animate.create() for shape in shapes], duration=DRAW)
    moments.append(scene.cursor)
    for turn in turns:
        scene.play([shape.animate.rotate_to_3d(*turn) for shape in shapes], duration=TURN)
        moments.append(scene.cursor)
    scene.wait(HOLD)


def gallery(variants, turns=()):
    """Two columns of (label, build) variants, each shape above its label, then reveal them.

    ``build(zone)`` returns the variant's shape for its zone.
    """
    rows = math.ceil(len(variants) / 2)
    grid = scene.layout.zones(Zones.grid(rows=rows, columns=2, gap="48px", padding="page_padding"))
    shapes = []
    for cell, (label, build) in zip(grid, variants):
        art, caption = cell.split(Zones.rows(["1fr", 0.5]))
        scene.text(label, role="code").place(caption)
        shapes.append(build(art))
    reveal(shapes, turns)


def centered(zone, points):
    """``points`` around the origin moved to the center of ``zone``, at the same depth."""
    x, y = zone.center
    return [(x + px, y + py, pz) for px, py, pz in points]


def torus(*args, **options):
    """A torus built by ``scene.geometry.torus(*args, **options)``, moved to its zone and tipped."""
    return lambda zone: scene.geometry.torus(*args, **options).move_to(*zone.center).rotate_to_3d(*TIP)


# A torus lies flat in x and z, like a plane: major_radius is the circle its
# tube runs around and minor_radius the tube. segments divide the circle and
# rings the tube, so few of either facet the ring one way or the other.
scene.segment("tori")
gallery([
    ("torus(1.1, 0.35)", torus(1.1, 0.35)),
    ("torus(1.1, 0.12)", torus(1.1, 0.12)),
    ("torus(1.1, 0.35, segments=10)", torus(1.1, 0.35, segments=10)),
    ("torus(1.1, 0.35, rings=5)", torus(1.1, 0.35, rings=5)),
])


def arrow(**options):
    """An arrow across its zone, from the lower left at the back to the upper right at the front."""

    def build(zone):
        a, b = centered(zone, [(-2.6, -0.6, -1.2), (2.6, 0.6, 1.2)])
        return scene.geometry.arrow_3d(a, b, **options)

    return build


# arrow_3d(a, b) points from a to b in world space. Its shaft radius, head
# radius and head length follow its length unless given in scene units, and
# segments sets how many sides shaft and head have.
scene.segment("arrows")
gallery([
    ("arrow_3d(a, b)", arrow()),
    ("arrow_3d(a, b, shaft_radius=0.06)", arrow(shaft_radius=0.06)),
    ("arrow_3d(a, b, head_length=1.6)", arrow(head_length=1.6)),
    ("arrow_3d(a, b, segments=6)", arrow(segments=6)),
])

# Paths for the tubes, around the origin: a zigzag with sharp corners, a coil
# sampled finely enough to stay smooth, a trefoil knot that closes on itself,
# and a hook whose ends point at the camera.
CORNERS = [(-2.4, -0.7, 0), (-1.2, 0.7, 0.6), (0, -0.7, -0.6), (1.2, 0.7, 0.6), (2.4, -0.7, 0)]
COIL = [(t / 16 - 2.4, 0.7 * math.cos(t / 4), 0.7 * math.sin(t / 4)) for t in range(77)]
KNOT = [
    (
        0.38 * (math.sin(t) + 2 * math.sin(2 * t)),
        0.38 * (math.cos(t) - 2 * math.cos(2 * t)),
        -0.38 * math.sin(3 * t),
    )
    for t in (k * math.tau / 120 for k in range(120))
]
HOOK = [(-1.6, 0.5, 1.2), (-1.6, 0.5, -0.8), (1.6, -0.5, -0.8), (1.6, -0.5, 1.2)]


def tube(points, radius, **options):
    """A tube along ``points``, moved to the center of its zone."""
    return lambda zone: scene.geometry.tube(centered(zone, points), radius, **options)


# tube(points, radius) follows a polyline without twisting: corners keep the
# radius and crease, sampled curves stay smooth, closed=True joins the last
# point to the first, and caps=False leaves the ends open. Lit meshes hide
# the faces turned away from the viewer, so an open end shows a ring.
scene.segment("tubes")
gallery(
    [
        ("tube(corners, 0.15)", tube(CORNERS, 0.15)),
        ("tube(coil, 0.08)", tube(COIL, 0.08, material=Material3D.matte(accent))),
        ("tube(knot, 0.16, closed=True)", tube(KNOT, 0.16, closed=True, material=Material3D.metal(success))),
        ("tube(hook, 0.3, caps=False)", tube(HOOK, 0.3, caps=False)),
    ],
    turns=[TILT],
)


# Each label is the source passed to scene.geometry.flat_3d(source), which
# lays the area it fills flat in 3D, in its fill color, keeping the holes of
# letters and rings. The sheets face the camera, lie back like a sign on the
# floor, then turn round: from behind they read mirrored.
def sheet(source):
    """A flat sheet of ``source``, scaled to fill its zone with room to turn."""
    return lambda zone: scene.geometry.flat_3d(source.place(zone.inset(zone.height * 0.12), fit="contain"))


scene.segment("sheets")
entries = [
    ('scene.text("Bg8")', sheet(scene.text("Bg8"))),
    ('scene.text.equation("e^(i pi)")', sheet(scene.text.equation("e^(i pi)"))),
    ("scene.geometry.annulus(1, 0.5)", sheet(scene.geometry.annulus(1, 0.5))),
]
table = scene.layout.zones(
    Zones.grid(rows=len(entries), columns=["5fr", "4fr"], gap="24px", column_gap="48px", padding="page_padding")
)
sheets = []
for index, (label, build) in enumerate(entries):
    scene.text(label, role="code").place(table[2 * index], anchor="right")
    sheets.append(build(table[2 * index + 1]))
reveal(sheets, turns=[(-1.0, 0, 0), (0.2, 2.6, 0)])


def line(*args, **options):
    """A line across its zone, from the lower left at the back to the upper right at the front."""

    def build(zone):
        a, b = centered(zone, [(-2.4, -0.5, -1.0), (2.4, 0.5, 1.0)])
        return scene.geometry.line_3d(a, b, *args, **options)

    return build


# line_3d(start, end, thickness) runs a lit cylinder between two ends that
# keeps its thickness, and create() grows it from start. segments sets how
# many sides it has. An end may be a drawable: the line follows it as it
# moves, like a bond between two atoms, so these two balls drag theirs along.
scene.segment("lines")
grid = scene.layout.zones(Zones.grid(rows=2, columns=2, gap="48px", padding="page_padding"))
lines, balls, moves = [], [], []
for cell, (label, build) in zip(
    grid,
    [
        ("line_3d(a, b)", line()),
        ("line_3d(a, b, 0.2)", line(0.2)),
        ("line_3d(a, b, 0.3, segments=5)", line(0.3, segments=5)),
        ("line_3d(left, right, 0.12)", None),
    ],
):
    art, caption = cell.split(Zones.rows(["1fr", 0.5]))
    scene.text(label, role="code").place(caption)
    if build:
        lines.append(build(art))
        continue
    ends = centered(art, [(-2.2, 0, 0), (2.2, 0, 0)])
    left, right = (
        scene.geometry.sphere(0.35, material=Material3D.matte(color)).move_to_3d(*end)
        for end, color in zip(ends, (accent, success))
    )
    balls += [left, right]
    lines.append(scene.geometry.line_3d(left, right, 0.12))
    to_left, to_right = centered(art, [(-1.6, 0.8, 1.2), (2.0, -0.7, -1.2)])
    moves += [left.animate.move_to_3d(*to_left), right.animate.move_to_3d(*to_right)]
moments.append(scene.cursor + DRAW / 2)
scene.play([shape.animate.create() for shape in balls + lines], duration=DRAW)
moments.append(scene.cursor)
scene.play(moves, duration=TURN)
moments.append(scene.cursor)
scene.wait(HOLD)

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, moments)
else:
    scene.render()

2D drawables in 3D

Text, equations and shapes placed in the 3D world with in_3d(): turned, written, tilted by perspective, hidden by meshes and lit, beside billboard().

2D drawables in 3D
View on GitHubgaanim examples/3d/drawables_in_3d.py
Code · 92 lines
"""2D drawables placed in the 3D world with in_3d(), keeping their animations and colors.

``drawable.in_3d()`` hands a 2D drawable to the 3D pass, which draws it from
its outlines in its own plane: ``move_to_3d`` and ``rotate_to_3d`` place and
turn it like a 3D primitive, perspective tilts it, and meshes in front of it
hide it pixel by pixel, while its edges stay sharp at any size. It keeps what
it is in 2D: text, equations and shapes, fills and strokes, and animations
such as ``write`` or a change of color. It casts shadows as a mesh does,
and ``in_3d(material)`` lights it, and shadows fall on it, as on a surface.
``billboard()`` instead keeps a label facing the camera, above the 3D
content, and ``hud()`` pins it to the frame.
"""

import math
import os

from gaanim import Material3D, Scene, Zones

DRAW = 1.2
TURN = 1.4
HOLD = 0.8
# The poses the drawables turn to in the first segment: lying back, then
# turned aside.
TURNS = [(-1.0, 0, 0), (0.3, 1.0, 0)]

scene = Scene()
accent = scene.colors.accent
success = scene.colors.success
rule = scene.colors.rule
foreground = scene.colors.foreground
# Times worth a snapshot: while drawables are written, and once each move settles.
moments = []


# The default camera is orthographic and looks down the z axis, so the z = 0
# plane lines up with the layout zones. Each label is the source drawable,
# which is placed in its zone, then put in the 3D world with .in_3d(),
# written, and turned: it foreshortens like a card, its stroke and fill
# turning with it.
scene.segment("turned")
sources = [
    ('scene.text("Hola")', lambda: scene.text("Hola")),
    ('scene.text.equation("e^(i pi)")', lambda: scene.text.equation("e^(i pi)")),
    ("scene.geometry.star(5, 1, 0.4)", lambda: scene.geometry.star(5, 1, 0.4)),
    ("scene.geometry.circle(1).stroke(success, 0.1)", lambda: scene.geometry.circle(1).stroke(success, 0.1)),
]
table = scene.layout.zones(
    Zones.grid(rows=len(sources), columns=["2fr", "1fr"], gap="24px", column_gap="48px", padding="page_padding")
)
placed = []
for index, (label, build) in enumerate(sources):
    scene.text(label, role="code").place(table[2 * index], anchor="right")
    art = table[2 * index + 1]
    placed.append(build().place(art.inset(art.height * 0.2), fit="contain").in_3d())
moments.append(scene.cursor + DRAW / 2)
scene.play([drawable.animate.write() for drawable in placed], duration=DRAW)
moments.append(scene.cursor)
for turn in TURNS:
    scene.play([drawable.animate.rotate_to_3d(*turn) for drawable in placed], duration=TURN)
    moments.append(scene.cursor)
scene.wait(HOLD)

# Under a perspective camera, a sign stands through a sphere, which hides
# part of it pixel by pixel, and casts its shadow on the sphere and the
# floor; a line lies on the floor, lit and in the sphere's shadow; and a
# billboard label stays facing the camera as it
# orbits, drawn above the 3D content. The text of each is the code that
# places it. The sign then changes color, as it would in 2D.
scene.segment("world")
scene.camera.to(scene.camera.state_3d(eye=(0, 2.2, 9), target=(0, -0.2, 0), fov_y=0.7))
# From above and behind, so the sphere's shadow falls toward the camera.
scene.geometry.light_3d("directional").move_to_3d(0, 6, -3)
scene.geometry.plane(12, 8, material=Material3D.matte(rule)).move_to_3d(0, -1.5, 0)
scene.geometry.sphere(1.0, material=Material3D.matte(accent)).move_to_3d(0.8, -0.3, 0)
sign = scene.text("text.in_3d()", role="code", size=0.7).in_3d().move_to_3d(0, 0.4, 0)
floor = scene.text("text.in_3d(material)", role="code", size=0.45).in_3d(Material3D.matte(foreground))
floor.rotate_to_3d(-math.pi / 2, 0, 0).move_to_3d(0.6, -1.49, 1.0)
label = scene.text("text.billboard()", role="code", size=0.35).move_to_3d(2.6, -0.2, -1.2).billboard()
moments.append(scene.cursor + DRAW / 2)
scene.play([sign.animate.write(), floor.animate.write(), label.animate.write()], duration=DRAW)
moments.append(scene.cursor)
scene.play([scene.camera.animate.orbit(delta_yaw=0.7, delta_pitch=0.15)], duration=TURN)
moments.append(scene.cursor)
scene.play([sign.animate.fill(success)], duration=DRAW / 2)
moments.append(scene.cursor)
scene.wait(HOLD)

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, moments)
else:
    scene.render()

glTF models

A glTF model imported with scene.media.gltf: its rest pose, its animations played one after another with fades, and loops, speeds and reversed plays.

glTF models
View on GitHubgaanim examples/3d/models_3d.py
Code · 100 lines
"""glTF models: importing one with scene.media.gltf and playing its animations, with fades, loops, speeds and reversal.

A wolf stands in its rest pose, then eats, walks and runs, each animation
fading from the one before, and three copies show the ways a play runs.
Each label is the call that plays the wolf above or beside it.
"""

import os

from gaanim import Scene, Zones

FADE = 0.6
HOLD = 0.6
WALKS = 3.0

scene = Scene()
accent = scene.colors.accent
muted = scene.colors.muted

# The wolf's size in its file, in its units: about 1.8 tall and, seen in
# three-quarter view, 2.3 long. Its origin lies between its feet.
WOLF_HEIGHT = 1.8
WOLF_LENGTH = 2.3
# A three-quarter view: turned toward the right, seen from a little above.
TURN = (0.25, 0.9, 0.0)


def wolf_on(zone, share=0.85):
    """A wolf standing on the bottom of ``zone``, as large as ``share`` of it allows."""
    scale = share * min(zone.height / WOLF_HEIGHT, zone.width / WOLF_LENGTH)
    return scene.media.gltf("Wolf.glb").scale_to(scale).rotate_to_3d(*TURN).move_to(*zone.point("bottom"))


# A model arrives in its rest pose, in the file's units: scale_to brings it
# to the scene, and move_to places its origin.
scene.segment("import")
stage, caption = scene.layout.zones(Zones.rows(["1fr", 0.6], gap="24px", padding="page_padding"))
wolf = wolf_on(stage)
scene.text('scene.media.gltf("Wolf.glb")', role="code").place(caption)
scene.play(wolf.animate.fade_in(), duration=FADE)
scene.wait(HOLD)

# animations() lists the file's animations and animation(name) plays one;
# transition fades from the animation before it, which keeps running.
scene.segment("animations")
stage, *rows = scene.layout.zones(Zones.rows(["1fr", 0.5, 0.5, 0.5], gap="12px", padding="page_padding"))
wolf = wolf_on(stage)
PLAYS = [
    ('wolf.animation("Idle_Eating")', wolf.animation("Idle_Eating"), None),
    ('wolf.animation("Walk", loop=True, transition=0.4)', wolf.animation("Walk", loop=True, transition=0.4), 2.0),
    ('wolf.animation("Run", loop=True, transition=0.3)', wolf.animation("Run", loop=True, transition=0.3), 2.0),
]
labels = [scene.text(call, role="code").fill(muted).place(row) for (call, _, _), row in zip(PLAYS, rows)]
scene.play(wolf.animate.fade_in(), duration=FADE)
for label, (_, play, duration) in zip(labels, PLAYS):
    scene.play([play, label.animate.fill(accent)], duration=duration)
    label.fill(muted)
scene.wait(HOLD)

# A play runs once by default; loop wraps it, speed scales its time and
# reverse runs it backwards.
scene.segment("plays")
VARIANTS = [
    ('animation("Walk", loop=True)', {"loop": True}),
    ('animation("Walk", loop=True, speed=0.5)', {"loop": True, "speed": 0.5}),
    ('animation("Walk", loop=True, reverse=True)', {"loop": True, "reverse": True}),
]
grid = scene.layout.zones(
    Zones.grid(rows=len(VARIANTS), columns=["1.6fr", "1fr"], gap="12px", column_gap="48px", padding="page_padding")
)
wolves = []
for index, (call, _) in enumerate(VARIANTS):
    scene.text(call, role="code").place(grid[2 * index], anchor="right")
    wolves.append(wolf_on(grid[2 * index + 1]))
scene.play([wolf.animate.fade_in() for wolf in wolves], duration=FADE)
scene.play(
    [wolf.animation("Walk", **options) for wolf, (_, options) in zip(wolves, VARIANTS)],
    duration=WALKS,
)
scene.wait(HOLD)

# The rest pose; the wolf eating, fading into its walk, walking and running;
# and the three plays, twice apart.
EATING = 10 / 3
animations = FADE + HOLD
plays = animations + FADE + EATING + 4.0 + HOLD
SEEKS = [
    FADE + 0.2,
    animations + FADE + 1.5,
    animations + FADE + EATING + 0.2,
    animations + FADE + EATING + 1.5,
    animations + FADE + EATING + 3.0,
    plays + FADE + 0.9,
    plays + FADE + 2.2,
]
if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, SEEKS)
else:
    scene.render()

glTF morph targets

A glTF model's morph targets, its shape keys: weights set with morph, mixed and pushed past either end, animated with animate.morph, and moved by the file's own animations.

glTF morph targets
View on GitHubgaanim examples/3d/morph_targets_3d.py
Code · 109 lines
"""glTF morph targets: setting their weights with morph, animating them with animate.morph, and the file's animations that move them.

A clay ball modelled in a 3D editor carries three shapes beside its own,
its morph targets: Squash, Spikes and Lean. A weight of 0 shows the ball as
modelled and 1 the shape in full; weights mix and may go past either end.
Each label is the call that sets the ball above it, or that animates the
ball beside it.
"""

import os

from gaanim import Scene, Zones

FADE = 0.6
HOLD = 0.8
MORPH = 1.2
LOOPS = 4.8

scene = Scene()
accent = scene.colors.accent
muted = scene.colors.muted

# The ball in its file: 2 units across about its origin. Its spikes reach
# out 0.6 more, and its lean takes its top 0.7 aside.
BALL_SIZE = 3.2
# Seen from a little above, so that its spikes show their depth.
TILT = (0.3, 0.4, 0.0)


def ball_in(zone, share=0.9):
    """A ball in the middle of ``zone``, as large as ``share`` of it allows."""
    scale = share * min(zone.width, zone.height) / BALL_SIZE
    return scene.media.gltf("Blob.glb").scale_to(scale).rotate_to_3d(*TILT).move_to(*zone.center)


# morph(name, weight) sets a target's weight; declared, it is the weight the
# ball starts with. morph_targets() lists the names the file gives them.
scene.segment("targets")
VARIANTS = [
    ('gltf("Blob.glb")', []),
    ('morph("Squash", 1.0)', [("Squash", 1.0)]),
    ('morph("Spikes", 1.0)', [("Spikes", 1.0)]),
    ('morph("Lean", 1.0)', [("Lean", 1.0)]),
    ('morph("Lean", -1.0)', [("Lean", -1.0)]),
    ('morph("Spikes", 0.4)', [("Spikes", 0.4)]),
]
grid = scene.layout.zones(Zones.grid(rows=2, columns=3, gap="24px", padding="page_padding"))
balls = []
for zone, (label, weights) in zip(grid, VARIANTS):
    art, caption = zone.split(Zones.rows(["1fr", 0.4]))
    ball = ball_in(art)
    for name, weight in weights:
        ball.morph(name, weight)
    balls.append(ball)
    scene.text(label, role="code").place(caption, fit="scale_down")
scene.play([ball.animate.fade_in() for ball in balls], duration=FADE)
scene.wait(HOLD)

# animate.morph animates a weight, alone or with other targets; the
# targets it leaves out keep theirs.
scene.segment("animate")
stage, *rows = scene.layout.zones(Zones.rows(["1fr", 0.45, 0.45, 0.45], gap="12px", padding="page_padding"))
ball = ball_in(stage)
PLAYS = [
    ('ball.animate.morph("Spikes", 1.0)', ball.animate.morph("Spikes", 1.0)),
    ('ball.animate.morph("Spikes", 0.0).morph("Squash", 0.8)', ball.animate.morph("Spikes", 0.0).morph("Squash", 0.8)),
    ('ball.animate.morph("Lean", 1.0)', ball.animate.morph("Lean", 1.0)),
]
labels = [scene.text(call, role="code").fill(muted).place(row, fit="scale_down") for (call, _), row in zip(PLAYS, rows)]
scene.play(ball.animate.fade_in(), duration=FADE)
for label, (_, play) in zip(labels, PLAYS):
    scene.play([play, label.animate.fill(accent)], duration=MORPH)
    label.fill(muted)
scene.wait(HOLD)

# The file's own animations move the weights too: Bounce squashes the ball
# where it lands, and Wobble grows its spikes as it sways. Smaller, the
# ball has room to hop.
scene.segment("animations")
art, captions = scene.layout.zones(Zones.rows(["1fr", 0.45], gap="12px", padding="page_padding"))
CLIPS = ["Bounce", "Wobble"]
columns = Zones.columns(len(CLIPS), gap="48px")
balls = []
for zone, caption, clip in zip(art.split(columns), captions.split(columns), CLIPS):
    balls.append(ball_in(zone, share=0.6))
    scene.text(f'animation("{clip}", loop=True)', role="code").place(caption, fit="scale_down")
scene.play([ball.animate.fade_in() for ball in balls], duration=FADE)
scene.play([ball.animation(clip, loop=True) for ball, clip in zip(balls, CLIPS)], duration=LOOPS)
scene.wait(HOLD)

# The six balls; the ball grown spikes, then squashed, then squashed and
# leaning; and the two animations as the ball tops its hop, as the other
# grows its spikes in full and as the ball lands.
animate = FADE + HOLD
animations = animate + FADE + 3 * MORPH + HOLD
SEEKS = [
    FADE + 0.4,
    animate + FADE + MORPH,
    animate + FADE + 2 * MORPH,
    animate + FADE + 3 * MORPH,
    animations + FADE + 0.6,
    animations + FADE + 1.0,
    animations + FADE + 1.2,
]
if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, SEEKS)
else:
    scene.render()

glTF normal maps

A flat brick panel whose normal map gives it the relief of its bricks under a passing light and as it turns, beside the same panel without the map.

glTF normal maps
View on GitHubgaanim examples/3d/normal_maps_3d.py
Code · 77 lines
"""glTF normal maps: a brick panel whose normal map gives its flat face the relief of its bricks, beside the same panel without one.

The file holds the panel in two scenes, both with the same color texture,
with and without the normal map; each label is the call that imports the
panel above it. A normal map tilts
the shading of each pixel as its texture says, so the bricks catch a light
that moves and a panel that turns, though the face stays flat.
"""

import os

from gaanim import Scene, Zones

FADE = 0.6
HOLD = 0.8
SWEEP = 3.0
TURN = 2.4

scene = Scene()

# The panel in its file: a square 2 units on a side, centered on its
# origin and facing the camera.
PANEL_SIZE = 2.0
SCENES = ["Plain", "NormalMap"]


def panels(share=0.9):
    """The two panels side by side, each above its label, and the zone they share."""
    art, captions = scene.layout.zones(Zones.rows(["1fr", 0.45], gap="12px", padding="page_padding"))
    columns = Zones.columns(len(SCENES), gap="48px")
    shown = []
    for zone, caption, name in zip(art.split(columns), captions.split(columns), SCENES):
        scale = share * min(zone.width, zone.height) / PANEL_SIZE
        shown.append(scene.media.gltf("Bricks.glb", scene=name).scale_to(scale).move_to(*zone.center))
        scene.text(f'gltf("Bricks.glb", scene="{name}")', role="code").place(caption, fit="scale_down")
    return art, shown


# A point light passing close in front of the panels, along their top,
# lights the upper and left sides of each brick, then its upper and right
# sides; without the map, the face only brightens and dims as a whole.
scene.segment("light")
art, shown = panels()
left_x, top_y = art.point("top_left")
right_x, _ = art.point("top_right")
DEPTH = 0.25 * art.height
lamp = scene.geometry.light_3d("point", intensity=1.6).move_to_3d(left_x, top_y, DEPTH)
scene.play([panel.animate.fade_in() for panel in shown], duration=FADE)
scene.play(lamp.animate.move_to_3d(right_x, top_y, DEPTH), duration=SWEEP)
scene.wait(HOLD)

# Under the studio light, the bricks of the mapped panel shade as the
# panel turns.
scene.segment("turn")
art, shown = panels(share=0.8)
for panel in shown:
    panel.rotate_to_3d(0.0, -0.7, 0.0)
scene.play([panel.animate.fade_in() for panel in shown], duration=FADE)
scene.play([panel.animate.rotate_to_3d(0.0, 0.7, 0.0) for panel in shown], duration=TURN)
scene.wait(HOLD)

# The light at the left, the middle and the right; the panels turned one
# way, facing the camera and turned the other way.
turn = FADE + SWEEP + HOLD
SEEKS = [
    FADE + 0.1,
    FADE + SWEEP / 2,
    FADE + SWEEP,
    turn + FADE,
    turn + FADE + TURN / 2,
    turn + FADE + TURN,
]
if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, SEEKS)
else:
    scene.render()

Glow on 3D content

A halo around what the camera sees of a sphere, a 3D line and a walking glTF model, grown and faded with animate.glow, and hidden where a solid in front covers it.

Glow on 3D content
View on GitHubgaanim examples/3d/glow_3d.py
Code · 101 lines
"""Glow on 3D content: a halo around what the camera sees of primitives, 3D lines and glTF models.

glow() gives a 3D drawable a halo in scene units, as it gives a 2D one, and
animate.glow() grows and fades it. The halo surrounds the visible silhouette
and lies under the drawable and under what lies in front of it: the part of
the sphere the cube hides does not glow, and the cube covers the rest of the
halo. Each label is the call that gives the variant its glow.
"""

import math
import os

from gaanim import Scene, Zones

DRAW = 1.0
WALK = 2.0
HOLD = 0.6
# Turn the solids about x to show their top and about y to show a side.
TILT = (0.45, -0.6, 0)

scene = Scene()
accent = scene.colors.accent
success = scene.colors.success
rule = scene.colors.rule


def cells(count):
    """``count`` columns, each an area for the drawable above a caption."""
    columns = scene.layout.zones(Zones.columns(count, gap="48px", padding="page_padding"))
    return [column.split(Zones.rows(["1fr", 0.5])) for column in columns]


def helix_points(zone):
    """Points of a helix of three turns that fills ``zone``."""
    x, y = zone.center
    radius, height = zone.width * 0.25, zone.height * 0.7
    points = []
    for k in range(181):
        t = k / 180
        angle = 6 * math.pi * t
        points.append((x + radius * math.cos(angle), y + height * (t - 0.5), radius * math.sin(angle)))
    return points


# The glow of a primitive and of a 3D line.
scene.segment("glow")
(sphere_art, sphere_caption), (helix_art, helix_caption) = cells(2)
sphere = scene.geometry.sphere(min(sphere_art.width, sphere_art.height) * 0.3)
sphere.move_to(*sphere_art.center).glow(accent, 0.3, 2.0)
helix = scene.geometry.polyline_3d(helix_points(helix_art), rule).stroke(rule, 0.05).glow(accent, 0.25, 2.0)
scene.text("sphere.glow(accent, 0.3, 2.0)", role="code").place(sphere_caption)
scene.text("helix.glow(accent, 0.25, 2.0)", role="code").place(helix_caption)
scene.play([shape.animate.fade_in() for shape in (sphere, helix)], duration=DRAW)
scene.wait(HOLD)

# An imported model keeps its glow while its animation deforms it.
scene.segment("model")
((wolf_art, wolf_caption),) = cells(1)
# The wolf is about 1.8 tall and, in three-quarter view, 2.3 long.
scale = 0.8 * min(wolf_art.height / 1.8, wolf_art.width / 2.3)
wolf = scene.media.gltf("Wolf.glb").scale_to(scale).rotate_to_3d(0.25, 0.9, 0)
wolf.move_to(*wolf_art.point("bottom")).glow(accent, 0.2, 2.0)
scene.text("wolf.glow(accent, 0.2, 2.0)", role="code").place(wolf_caption)
scene.play(wolf.animate.fade_in(), duration=DRAW)
scene.play(wolf.animation("Walk", loop=True), duration=WALK)
scene.wait(HOLD)

# animate.glow grows a halo and glow(None) fades it; a drawable in front
# hides the part it covers, which does not glow.
scene.segment("animate")
(cube_art, cube_caption), (hidden_art, hidden_caption) = cells(2)
size = min(cube_art.width, cube_art.height) * 0.4
cube = scene.geometry.cube(size).move_to(*cube_art.center).rotate_to_3d(*TILT)
behind = scene.geometry.sphere(size * 0.6).move_to(*hidden_art.center).shift_by(-size * 0.35, 0)
behind.glow(accent, 0.3, 2.0)
front = scene.geometry.cube(size * 0.8).move_to(*hidden_art.center).shift_by(size * 0.35, 0)
front.rotate_to_3d(*TILT).shift_by_3d(0, 0, size)
scene.text("cube.animate.glow(success, 0.5, 3.0)", role="code").place(cube_caption)
scene.text("behind.glow(accent, 0.3, 2.0)", role="code").place(hidden_caption)
scene.play([shape.animate.fade_in() for shape in (cube, behind, front)], duration=DRAW)
scene.play(cube.animate.glow(success, 0.5, 3.0), duration=DRAW)
scene.wait(HOLD)
scene.play(cube.animate.glow(None), duration=DRAW)
scene.wait(HOLD)

# The sphere's and the helix's glows, the wolf walking, and the cube's halo
# growing, whole and faded out.
model = DRAW + HOLD
animate = model + DRAW + WALK + HOLD
SEEKS = [
    DRAW + 0.2,
    model + DRAW + 1.3,
    animate + DRAW + 0.5,
    animate + 2 * DRAW + 0.3,
    animate + 3 * DRAW + HOLD + 0.3,
]
if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, SEEKS)
else:
    scene.render()

Shadows and blurs on 3D content

Drop shadows cast by a sphere and by a text placed in 3D, a blurred cube that the timeline sharpens, and a blurred ring that a sharp solid in front of it hides.

Shadows and blurs on 3D content
View on GitHubgaanim examples/3d/soft_effects_3d.py
Code · 80 lines
"""Drop shadows and blurs on 3D content, as on 2D drawables.

shadow() casts a drop shadow from what the camera sees of a primitive, or of a
drawable placed with in_3d(), moved by its offset and blurred in scene units;
blur() blurs the drawable over what lies behind it, and animate.blur()
sharpens or blurs it on the timeline. A solid in front hides both, as a 2D
drawable drawn after them covers them. Each label is the call that gives the
variant its effect.
"""

import os

from gaanim import Material3D, Scene, Zones

DRAW = 1.0
FOCUS = 1.6
HOLD = 0.6
# Turn the solids about x to show their top and about y to show a side.
TILT = (0.45, -0.6, 0)
SEEKS = []

scene = Scene()
accent = scene.colors.accent
success = scene.colors.success
panel = scene.colors.panel
shade = scene.colors.shadow


def cells(count):
    """``count`` columns, each an area for the drawable above a caption."""
    columns = scene.layout.zones(Zones.columns(count, gap="48px", padding="page_padding"))
    return [column.split(Zones.rows(["1fr", 0.4])) for column in columns]


# A shadow moved down and right, on a solid and on a text in the 3D world,
# over a panel behind them that it falls on.
scene.segment("shadow")
shadowed = []
for (art, caption), (label, build) in zip(cells(2), [
    ("ball.shadow(shade, 0.2, -0.2, 0.1)",
     lambda side: scene.geometry.sphere(side * 0.3, material=Material3D.matte(accent))
     .shadow(shade, 0.2, -0.2, 0.1)),
    ("word.shadow(shade, 0.1, -0.1, 0.05)",
     lambda side: scene.text("Hola", size=side * 0.3).in_3d().rotate_to_3d(-0.5, 0.4, 0)
     .shadow(shade, 0.1, -0.1, 0.05)),
]):
    side = min(art.width, art.height)
    scene.geometry.rect(art.width, art.height).fill(panel).no_stroke().in_3d().move_to(*art.center)
    shadowed.append(build(side).move_to_3d(*art.center, side * 0.4))
    scene.text(label, role="code").place(caption, fit="scale_down")
SEEKS.append(scene.cursor + DRAW / 2)
scene.play([drawable.animate.fade_in() for drawable in shadowed], duration=DRAW)
SEEKS.append(scene.cursor + HOLD / 2)
scene.wait(HOLD)

# A blur that the timeline sharpens, and one behind a sharp solid, which
# hides the blur where it stands in front.
scene.segment("blur")
(focus_art, focus_caption), (behind_art, behind_caption) = cells(2)
side = min(focus_art.width, focus_art.height)
cube = scene.geometry.cube(side * 0.45, material=Material3D.matte(accent)).move_to(*focus_art.center).rotate_to_3d(*TILT)
cube.blur(0.3)
scene.text("cube.animate.blur(0)", role="code").place(focus_caption, fit="scale_down")
side = min(behind_art.width, behind_art.height)
ring = scene.geometry.torus(side * 0.3, side * 0.1, material=Material3D.matte(success)).move_to(*behind_art.center).rotate_to_3d(1.1, 0, 0)
ring.blur(0.2)
scene.geometry.cube(side * 0.25, material=Material3D.matte(accent)).move_to_3d(behind_art.center[0], behind_art.center[1], side * 0.4).rotate_to_3d(*TILT)
scene.text("ring.blur(0.2)", role="code").place(behind_caption, fit="scale_down")
scene.wait(HOLD / 2)
SEEKS.append(scene.cursor)
scene.play([cube.animate.blur(0)], duration=FOCUS)
SEEKS.append(scene.cursor - FOCUS / 2)
SEEKS.append(scene.cursor + HOLD / 2)
scene.wait(HOLD)

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, SEEKS)
else:
    scene.render()

Order-independent transparency

Translucent panels that cross, a ball passing through a panel, nested shells, a ring in a box, a knot and a Möbius strip, each surface blended in the order it lies at each pixel.

Order-independent transparency
View on GitHubgaanim examples/3d/transparency_3d.py
Code · 155 lines
"""Order-independent transparency: translucent solids and surfaces that cross, nest and fold blend in the order they lie.

transparency_3d("order_independent") blends every translucent surface in
its depth order at each pixel, up to layers surfaces deep, where the
default draws each translucent drawable as one layer and blends the
drawables from back to front. Panels that cross show the nearer one over
the other on each side of where they cross, a ball passing through a panel
shows where it pierces it, nested shells show each one inside the last,
and a knot or a twisted strip shows its far side through its near one.
Each label is the call that builds the drawables beside it.
"""

import math
import os

from gaanim import Material3D, Scene, Zones

FADE = 0.6
MOVE = 2.4
HOLD = 0.6
SEEKS = []

scene = Scene()
scene.geometry.transparency_3d("order_independent", layers=6)
accent = scene.colors.accent
success = scene.colors.success
warning = scene.colors.warning


def cells(count):
    """``count`` columns, each an area for the drawables above a caption."""
    columns = scene.layout.zones(Zones.columns(count, gap="48px", padding="page_padding"))
    return [column.split(Zones.rows(["1fr", 0.4])) for column in columns]


def panel(side, color):
    """A square ``side`` units wide facing the camera, lit on its front."""
    half = side / 2
    return scene.geometry.mesh(
        [(-half, -half, 0), (half, -half, 0), (half, half, 0), (-half, half, 0)],
        [(0, 1, 2), (0, 2, 3)],
        material=Material3D.matte(color),
    )


def knot(size, segments=240):
    """A trefoil knot about the origin, ``size`` units across."""
    scale = size / 6
    return [
        (
            scale * (math.sin(t) + 2 * math.sin(2 * t)),
            scale * (math.cos(t) - 2 * math.cos(2 * t)),
            scale * -math.sin(3 * t),
        )
        for t in (math.tau * step / segments for step in range(segments))
    ]


def strip(radius, width, segments=96):
    """A Möbius strip about the origin, half ``accent`` and half ``success``
    along its length; each face has vertices of its own, so that it is lit
    on its own side."""
    side = []
    for step in range(segments + 1):
        u = math.tau * step / segments
        for v in (-width / 2, width / 2):
            r = radius + v * math.cos(u / 2)
            side.append((r * math.cos(u), v * math.sin(u / 2), r * math.sin(u)))
    back = len(side)
    triangles = []
    for step in range(segments):
        a, b, c, d = 2 * step, 2 * step + 1, 2 * step + 2, 2 * step + 3
        triangles += [(a, c, b), (b, c, d), (back + a, back + b, back + c), (back + b, back + d, back + c)]
    colors = [accent if step < segments / 2 else success for step in range(segments + 1) for _ in range(2)]
    return scene.geometry.mesh(side + side, triangles, colors=colors + colors)


def show(drawables, label, caption):
    """Fade ``drawables`` in, captioned by the call that builds them."""
    scene.text(label, role="code").place(caption, fit="scale_down")
    return [drawable.opacity(0.5) for drawable in drawables]


# Two panels that cross, turning together, and a ball that passes through a
# panel from behind it to in front of it.
scene.segment("crossing")
(cross_art, cross_caption), (pierce_art, pierce_caption) = cells(2)
side = min(cross_art.width, cross_art.height) * 0.7
crossed = show(
    [
        panel(side, color).move_to(*cross_art.center).rotate_to_3d(0, angle, 0)
        for color, angle in ((accent, -0.9), (success, 0.3))
    ],
    "panel(side).opacity(0.5) twice, crossing",
    cross_caption,
)
side = min(pierce_art.width, pierce_art.height) * 0.7
wall = panel(side, accent).move_to(*pierce_art.center)
ball = scene.geometry.sphere(side * 0.3, material=Material3D.matte(success))
ball.move_to_3d(*pierce_art.center, -side * 0.4)
pierced = show([wall, ball], "sphere(r).opacity(0.5) through a panel", pierce_caption)
scene.play([drawable.animate.fade_in() for drawable in crossed + pierced], duration=FADE)
# The ball half through the panel, and through it.
SEEKS += [scene.cursor + MOVE * 0.4, scene.cursor + MOVE * 0.8]
scene.play(
    [crossed[0].animate.rotate_to_3d(0, -0.3, 0), crossed[1].animate.rotate_to_3d(0, 0.9, 0)]
    + [ball.animate.move_to_3d(*pierce_art.center, side * 0.4)],
    duration=MOVE,
)
scene.wait(HOLD)

# Three shells, each inside the last, and a ring inside a box, turning.
scene.segment("nested")
(shell_art, shell_caption), (box_art, box_caption) = cells(2)
radius = min(shell_art.width, shell_art.height) * 0.4
shells = show(
    [
        scene.geometry.sphere(radius * share, material=Material3D.matte(color)).move_to(*shell_art.center)
        for share, color in ((1.0, accent), (0.65, success), (0.3, warning))
    ],
    "sphere(r * k).opacity(0.5) for k in (1, 0.65, 0.3)",
    shell_caption,
)
side = min(box_art.width, box_art.height) * 0.62
box = scene.geometry.cube(side, material=Material3D.matte(accent)).move_to(*box_art.center)
ring = scene.geometry.torus(side * 0.3, side * 0.09, material=Material3D.matte(success)).move_to(*box_art.center)
held = show([box, ring], "torus(...) in cube(side), both opacity(0.5)", box_caption)
for drawable in held:
    drawable.rotate_to_3d(0.5, -0.6, 0)
scene.play([drawable.animate.fade_in() for drawable in shells + held], duration=FADE)
SEEKS += [scene.cursor + MOVE * 0.5]
scene.play([box.animate.rotate_to_3d(0.5, 0.6, 0), ring.animate.rotate_to_3d(1.6, 0.6, 0)], duration=MOVE)
SEEKS += [scene.cursor]
scene.wait(HOLD)

# A knot, whose strands pass in front of and behind each other, and a
# twisted strip, whose two faces fold over each other.
scene.segment("folds")
(knot_art, knot_caption), (strip_art, strip_caption) = cells(2)
size = min(knot_art.width, knot_art.height) * 0.85
tube = scene.geometry.tube(knot(size), size * 0.06, closed=True, material=Material3D.matte(warning))
folded = show([tube.move_to(*knot_art.center).rotate_to_3d(0.9, 0, 0)], "tube(knot, r, closed=True).opacity(0.5)", knot_caption)
size = min(strip_art.width, strip_art.height)
twisted = show([strip(size * 0.3, size * 0.22).move_to(*strip_art.center).rotate_to_3d(0.6, 0, 0)], "mesh(möbius).opacity(0.5)", strip_caption)
scene.play([drawable.animate.fade_in() for drawable in folded + twisted], duration=FADE)
SEEKS += [scene.cursor + MOVE * 0.4]
scene.play([drawable.animate.rotate_to_3d(0.9 - 0.6, 1.2, 0) for drawable in folded + twisted], duration=MOVE)
SEEKS += [scene.cursor]
scene.wait(HOLD)

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, SEEKS)
else:
    scene.render()

Z up

A world with z up and the plan in x/y, as engineering models are written: orbits about z, upright columns, and plans and walls laid on the planes of the model with in_3d(plane=, origin=).

Z up
View on GitHubgaanim examples/3d/z_up.py
Code · 64 lines
"""Z up: a world with z up and the plan in x/y, and drawings laid on the planes of a model.

``Scene(up="z")`` reads 3D coordinates as engineering models write them:
camera orbits turn about z from the -y front, cylinders stand along z,
planes lie on the x/y floor and the key light shines from above. With
``in_3d(plane=, origin=)`` a 2D drawing lands on a plane of the model, its
scene origin at ``origin``: a slab drawn as a plan lies in x/y at its
height, and a wall drawn in (y, z) stands in y/z. The label is the code that
builds the model.
"""

import math
import os

from gaanim import Material3D, Scene, Zones

scene = Scene(up="z")
accent = scene.colors.accent
success = scene.colors.success
muted = scene.colors.muted
foreground = scene.colors.foreground

zones = scene.layout.zones(Zones.rows(["150px", "1fr"], padding="page_padding"))
scene.text(
    'scene = Scene(up="z")\n'
    'slab.in_3d(plane="xy", origin=(0, 0, 3))\n'
    'wall.in_3d(plane="yz", origin=(-3.2, -2, 0))',
    role="code",
).hud().place(zones[0], anchor="left")

# The model sits below the label.
low = (0.0, -0.8)
front = scene.camera.state_orbit((0, 0, 1.5), math.radians(30), math.radians(25), distance=15, screen_offset=low)
side = scene.camera.state_orbit((0, 0, 1.5), math.radians(120), math.radians(35), distance=15, screen_offset=low)
scene.camera.to(front)

# The floor lies in x/y and the columns stand along z, three units high.
floor = scene.geometry.plane(8, 6, material=Material3D.matte(foreground))
columns = [
    scene.geometry.cylinder(0.25, 3.0, material=Material3D.matte(muted)).move_to_3d(x, y, 1.5)
    for x in (-3, 3)
    for y in (-2, 2)
]
# A plan drawn in x/y lies on top of them; a wall drawn in (y, z) stands on
# the left side.
slab = scene.geometry.rect(6.4, 4.4).fill(accent).in_3d(plane="xy", origin=(0, 0, 3.0))
wall = scene.geometry.polygon([(0, 0), (4, 0), (4, 3), (0, 3)]).fill(success).in_3d(
    plane="yz", origin=(-3.2, -2.0, 0.0)
)
scene.play([floor.animate.create(), *[column.animate.create() for column in columns]], duration=1.0)
scene.play([slab.animate.fade_in(), wall.animate.fade_in()], duration=0.6)
built = scene.cursor
scene.wait(0.4)

# The orbit turns about z, from the front to the side.
scene.play([scene.camera.animate.to(side, path="orbit")], duration=2.0)
scene.wait(0.5)

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    # The model built, the orbit halfway and at the side.
    scene.snapshots(snapshots, [built + 0.2, built + 1.4, built + 2.6])
else:
    scene.render()

Spot lights

Cones of light of three widths and three softnesses over a cube, a sphere and a cone, and a spot that sweeps across the stage while the shadows turn away from it.

Spot lights
View on GitHubgaanim examples/3d/spot_lights_3d.py
Code · 85 lines
"""Spot lights: cones of light aimed at a point, as wide and as soft as asked, that sweep across a stage and cast shadows.

light_3d("spot", target=..., angle=..., softness=...) shines from where the
light stands toward target, in a cone angle radians wide on each side,
fading out over the outer softness of that angle. A spot keeps aiming at
its target as it moves, so moving it sweeps its cone across the stage, and
the solids it lights cast their shadows away from it. The label, pinned to
the frame, is the code that makes the spots of the segment.
"""

import os

from gaanim import Material3D, Scene, Zones

FADE = 0.6
SWEEP = 3.0
HOLD = 0.6
SEEKS = []

scene = Scene()
accent = scene.colors.accent
success = scene.colors.success
danger = scene.colors.danger
rule = scene.colors.rule
# Dim the sky and ground light, so that the spots shape the stage.
scene.geometry.lighting_3d("studio", intensity=0.25)
HOME = scene.camera.state_3d(eye=(0, 6, 11), target=(0, -0.5, 0), fov_y=0.7)
# Where the three solids stand on the floor.
SPOTS = [(-3.2, -1, 0), (0, -1, 0), (3.2, -1, 0)]


def stage(name, label):
    """Start segment ``name`` on the stage, captioned by ``label``."""
    scene.segment(name)
    scene.camera.to(HOME)
    band = scene.layout.zones(Zones.rows(["1fr", 0.5], padding="page_padding"))[1]
    scene.text(label, role="code").hud().place(band, fit="scale_down")
    scene.geometry.plane(12, 7, subdivisions=(48, 28), material=Material3D.matte(rule)).move_to_3d(0, -1, 0)
    for (x, y, z), solid in zip(SPOTS, ("cube", "sphere", "cone")):
        build = {
            "cube": lambda: scene.geometry.cube(1.2, material=Material3D.matte(accent)),
            "sphere": lambda: scene.geometry.sphere(0.7, material=Material3D.matte(success)),
            "cone": lambda: scene.geometry.cone(0.6, 1.4, material=Material3D.matte(danger)),
        }[solid]
        build().move_to_3d(x, y + 0.6, z)


def light_up(lights):
    """Switch ``lights`` on, and hold."""
    for light in lights:
        light.hidden()
    scene.play([light.animate.fade_in() for light in lights], duration=FADE)
    SEEKS.append(scene.cursor + HOLD / 2)
    scene.wait(HOLD)


# Three spots straight above the three solids, each cone wider.
stage("angle", 'light_3d("spot", target=solid, angle=a) for a in (0.15, 0.3, 0.45)')
light_up([
    scene.geometry.light_3d("spot", target=target, angle=angle, intensity=1.6).move_to_3d(target[0], 4, target[2])
    for target, angle in zip(SPOTS, (0.15, 0.3, 0.45))
])

# The same cone with a hard edge, half faded and faded from its middle.
stage("softness", 'light_3d("spot", angle=0.35, softness=s) for s in (0, 0.5, 1)')
light_up([
    scene.geometry.light_3d("spot", target=target, angle=0.35, softness=softness, intensity=1.6).move_to_3d(target[0], 4, target[2])
    for target, softness in zip(SPOTS, (0.0, 0.5, 1.0))
])

# One spot aimed at the middle solid sweeps from the left to the right, and
# the shadows of the solids turn away from it.
stage("sweep", 'light_3d("spot", target=(0, -1, 0)).animate.move_to_3d(5, 3, 2)')
spot = scene.geometry.light_3d("spot", target=(0, -1, 0), angle=0.5, intensity=1.8).move_to_3d(-5, 3, 2)
light_up([spot])
SEEKS.append(scene.cursor + SWEEP / 2)
scene.play([spot.animate.move_to_3d(5, 3, 2)], duration=SWEEP)
SEEKS.append(scene.cursor + HOLD / 2)
scene.wait(HOLD)

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, SEEKS)
else:
    scene.render()

Depth of field in 3D

A row of solids going away from the camera, blurred by their distance from the focus as it racks from the nearest to the farthest, as the aperture opens and as the blur is capped.

Depth of field in 3D
View on GitHubgaanim examples/3d/depth_of_field_3d.py
Code · 77 lines
"""Depth of field of 3D content: a row of solids going away from the camera, blurred by their distance from the focus.

camera.depth_of_field(focus, aperture=..., max_blur=...) blurs each pixel of
the 3D content by its circle of confusion, aperture * |1 - focus / depth|
scene units at most max_blur, where depth is its distance along the view
in units of the camera's distance to its look_at target: focus=1 keeps the
target sharp. animate.focus_to racks the focus to a nearer or farther
depth, and animate.depth_of_field opens the aperture or caps the blur. The
label, pinned to the frame, is the code of the segment.
"""

import os

from gaanim import Material3D, Scene, Zones

MOVE = 1.6
HOLD = 0.6
SEEKS = []

scene = Scene()
accent = scene.colors.accent
success = scene.colors.success
danger = scene.colors.danger
chart = scene.colors.chart
rule = scene.colors.rule
# The camera stands about 9 units from its target, the third solid.
HOME = scene.camera.state_3d(eye=(2.6, 3.2, 9.0), target=(0, -0.6, 0), fov_y=0.62)
# The solids from near to far: at depths of about 0.6, 0.8, 1, 1.3 and 1.7.
ROW = [(-1.6, 3.6), (-0.8, 1.8), (0.0, 0.0), (0.8, -2.8), (1.6, -6.4)]


def stage(name, label):
    """Start segment ``name`` with the row of solids, captioned by ``label``."""
    scene.segment(name)
    scene.camera.to(HOME)
    band = scene.layout.zones(Zones.rows(["1fr", 0.5], padding="page_padding"))[1]
    scene.text(label, role="code").hud().place(band, fit="scale_down")
    scene.geometry.plane(10, 18, subdivisions=(20, 36), material=Material3D.matte(rule)).move_to_3d(0, -0.8, -2)
    colors = [accent, success, danger, chart, accent]
    for index, ((x, z), color) in enumerate(zip(ROW, colors)):
        if index % 2:
            scene.geometry.sphere(0.6, material=Material3D.matte(color)).move_to_3d(x, -0.2, z)
        else:
            scene.geometry.cube(1.1, material=Material3D.matte(color)).move_to_3d(x, -0.25, z).rotate_to_3d(0, 0.5, 0)


def move(animation):
    """Play ``animation``, and hold where it ends."""
    SEEKS.append(scene.cursor + MOVE / 2)
    scene.play([animation], duration=MOVE)
    SEEKS.append(scene.cursor + HOLD / 2)
    scene.wait(HOLD)


# Rack the focus from the target to the nearest solid, then to the farthest.
stage("focus", "scene.camera.animate.focus_to(0.6), then focus_to(1.7)")
scene.camera.depth_of_field(focus=1.0, aperture=0.12, max_blur=0.5)
SEEKS.append(scene.cursor + HOLD / 2)
scene.wait(HOLD)
move(scene.camera.animate.focus_to(0.6))
move(scene.camera.animate.focus_to(1.7))

# Open the aperture: what lies away from the focus blurs more.
stage("aperture", "scene.camera.animate.depth_of_field(aperture=0.3)")
scene.camera.depth_of_field(focus=1.0, aperture=0.03, max_blur=0.5)
move(scene.camera.animate.depth_of_field(aperture=0.3))

# Cap the blur: past it, nothing blurs more.
stage("max_blur", "scene.camera.animate.depth_of_field(max_blur=0.02)")
scene.camera.depth_of_field(focus=1.0, aperture=0.3, max_blur=0.5)
move(scene.camera.animate.depth_of_field(max_blur=0.02))

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, SEEKS)
else:
    scene.render()

Isosurfaces and volumes

The surface of three balls of charge, a gyroid the box cuts open, one level of a field morphing into another, and a field drawn whole as a glowing cloud, alone and with a solid ring passing through it.

Isosurfaces and volumes
View on GitHubgaanim examples/3d/fields_3d.py
Code · 98 lines
"""Scalar fields in 3D: the surfaces where a field takes one value, and the field drawn whole as a glowing cloud.

isosurface(field, level, ...) samples field(x, y, z) on a grid over a box
and draws the smooth, lit surface where it equals level, facing out; a
surface the box cuts open is lit on both sides. volume(field, ...) draws
the whole field as a cloud: each value glows in the color a color map gives
it and is as opaque as opacity says, and each pixel gathers the cloud along
its ray up to what is opaque, so a solid inside it shows through. Each
label is the call that builds the drawable above it.
"""

import math
import os

from gaanim import Material3D, Scene, Zones

FADE = 0.8
TURN = 3.0
HOLD = 0.6
SEEKS = []

scene = Scene()
accent = scene.colors.accent
success = scene.colors.success
warning = scene.colors.warning
TILT = (0.5, -0.5, 0.0)

# Three balls of charge: the field is the sum of their pulls, and its
# surfaces at higher values hug the balls closer.
CENTERS = [(-0.45, -0.2, 0.0), (0.45, -0.2, 0.0), (0.0, 0.5, 0.15)]


def blobs(x, y, z):
    return sum(0.18 / ((x - cx) ** 2 + (y - cy) ** 2 + (z - cz) ** 2 + 1e-3) for cx, cy, cz in CENTERS)


def gyroid(x, y, z):
    return math.sin(x) * math.cos(y) + math.sin(y) * math.cos(z) + math.sin(z) * math.cos(x)


def cloud(x, y, z):
    """A soft ball, densest at its middle, rippled outward."""
    r = math.sqrt(x * x + y * y + z * z)
    return math.exp(-2.5 * r * r) * (0.75 + 0.25 * math.cos(9.0 * r))


def cells(count):
    """``count`` columns, each an area for a drawable above its caption."""
    columns = scene.layout.zones(Zones.columns(count, gap="48px", padding="page_padding"))
    return [column.split(Zones.rows(["1fr", 0.4])) for column in columns]


def fit(drawable, art, extent):
    """Scale ``drawable``, ``extent`` units across, into ``art``."""
    return drawable.scale_to(0.8 * min(art.width, art.height) / extent).move_to(*art.center).rotate_to_3d(*TILT)


def turn(drawables):
    """Fade ``drawables`` in and turn them a half turn about y."""
    scene.play([drawable.animate.fade_in() for drawable in drawables], duration=FADE)
    SEEKS.append(scene.cursor + TURN / 2)
    scene.play([drawable.animate.rotate_to_3d(TILT[0], TILT[1] + math.pi, 0) for drawable in drawables], duration=TURN)
    SEEKS.append(scene.cursor + HOLD / 2)
    scene.wait(HOLD)


# The surface of three balls of charge, a gyroid the box cuts open, and the
# balls' surface at a higher level, which parts them.
scene.segment("isosurfaces")
(blob_art, blob_caption), (gyroid_art, gyroid_caption), (level_art, level_caption) = cells(3)
box = dict(x_range=(-1.2, 1.2), y_range=(-1.2, 1.2), z_range=(-1.2, 1.2), resolution=40)
blob = fit(scene.geometry.isosurface(blobs, 2.2, material=Material3D.matte(accent), **box), blob_art, 2.4)
scene.text("isosurface(blobs, 2.2)", role="code").place(blob_caption, fit="scale_down")
cell = dict(x_range=(-math.pi, math.pi), y_range=(-math.pi, math.pi), z_range=(-math.pi, math.pi), resolution=40)
sponge = fit(scene.geometry.isosurface(gyroid, 0.0, material=Material3D.matte(success), **cell), gyroid_art, 2 * math.pi)
scene.text("isosurface(gyroid, 0)", role="code").place(gyroid_caption, fit="scale_down")
parted = fit(scene.geometry.isosurface(blobs, 4.0, material=Material3D.matte(warning), **box), level_art, 2.4)
scene.text("isosurface(blobs, 4.0)", role="code").place(level_caption, fit="scale_down")
turn([blob, sponge, parted])

# A cloud lit by every value, and the same cloud showing only its densest
# half, with a solid ring passing through it.
scene.segment("volumes")
(soft_art, soft_caption), (dense_art, dense_caption) = cells(2)
ball = dict(x_range=(-1, 1), y_range=(-1, 1), z_range=(-1, 1), resolution=48)
soft = fit(scene.geometry.volume(cloud, color_map="magma", opacity=(0.0, 0.1, 1.0), density=3.0, **ball), soft_art, 2.0)
scene.text('volume(cloud, color_map="magma", opacity=(0, 0.1, 1))', role="code").place(soft_caption, fit="scale_down")
dense = fit(scene.geometry.volume(cloud, color_map="viridis", opacity=(0.0, 0.0, 1.0), density=12.0, **ball), dense_art, 2.0)
side = 0.8 * min(dense_art.width, dense_art.height)
ring = scene.geometry.torus(side * 0.2, side * 0.035, material=Material3D.matte(accent)).move_to(*dense_art.center).rotate_to_3d(1.2, 0, 0)
scene.text("volume(cloud, opacity=(0, 0, 1)) and a ring", role="code").place(dense_caption, fit="scale_down")
turn([soft, dense, ring])

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, SEEKS)
else:
    scene.render()

Images and Lottie in 3D

An image and a Lottie scene placed in the 3D world with in_3d(), and an image kept facing the camera with billboard(), each hidden pixel by pixel by a ball passing in front.

Images and Lottie in 3D
View on GitHubgaanim examples/3d/media_in_3d.py
Code · 58 lines
"""Images and Lottie scenes in the 3D world, which meshes in front hide pixel by pixel.

An image or a Lottie scene placed with in_3d() is drawn by the 3D pass in its
own plane, as text and shapes are: it turns and tilts with the scene, and a
mesh passing in front hides it pixel by pixel, where a 2D drawable would be
drawn over the mesh. A Lottie scene keeps playing on the timeline. One kept
facing the camera with billboard() is hidden the same way. Each label is the
call that places the variant.
"""

import os

from gaanim import Material3D, Scene, Zones

BANNER = "assets/banner.png"
BADGE = "assets/badge.png"
TOGGLE = "assets/toggle.lottie"  # animations idle and active
SWEEP = 2.4
HOLD = 0.6
# Turn the flat drawables about y to show they lie in the 3D world.
TURN = (0, 0.5, 0)
SEEKS = []

scene = Scene()
accent = scene.colors.accent
columns = scene.layout.zones(Zones.columns(3, gap="48px", padding="page_padding"))
cells = [column.split(Zones.rows(["1fr", 0.4])) for column in columns]
variants = [
    ("image(BANNER).in_3d()",
     lambda side: scene.media.image(BANNER, width=side * 0.9).in_3d().rotate_to_3d(*TURN)),
    ("lottie(TOGGLE).in_3d()",
     lambda side: scene.media.lottie(TOGGLE, width=side * 0.8, height=side * 0.8).in_3d().rotate_to_3d(*TURN)),
    ("image(BADGE).billboard()",
     lambda side: scene.media.image(BADGE, height=side * 0.6).billboard()),
]
# A ball sweeps in front of each variant, across most of its zone.
sweeps = []
media = []
for (art, caption), (label, build) in zip(cells, variants):
    side = min(art.width, art.height)
    media.append(build(side).move_to(*art.center))
    scene.text(label, role="code").place(caption, fit="scale_down")
    x, y = art.center
    reach = art.width * 0.4
    ball = scene.geometry.sphere(side * 0.16, material=Material3D.matte(accent)).move_to_3d(x - reach, y, side * 0.5)
    sweeps.append(ball.animate.move_to_3d(x + reach, y, side * 0.5))

scene.wait(HOLD)
SEEKS.extend(scene.cursor + SWEEP * share for share in (0.3, 0.5, 0.7))
scene.play([media[1]] + sweeps, duration=SWEEP)
scene.wait(HOLD)
SEEKS.append(scene.cursor)

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, SEEKS)
else:
    scene.render()

Lines 3d

Polylines through 3D points with solid colors and color maps, and paths traced behind moving objects that fade, cap or thin.

Lines 3d
View on GitHubgaanim examples/3d/lines_3d.py
Code · 141 lines
"""3D lines: polylines through 3D points and paths traced behind moving objects.

``scene.geometry.polyline_3d`` draws a line strip through world points in
one color, one color per point or a colormap; ``traced_path_3d`` records
where a moving drawable has been. A distant perspective camera looks at
every line from the front right with z pointing up.
"""

import math
import os

from gaanim import ColorMap, Material3D, Scene, Zones

DRAW = 1.4
HOLD = 0.8
TRACE = 3.0

scene = Scene()
accent = scene.colors.accent
danger = scene.colors.danger
foreground = scene.colors.foreground

# The camera looks at the origin from AZIMUTH radians around z and ELEVATION
# radians above the floor, with z up. From DISTANCE away, a field of view as
# tall as the frame draws the plane through the origin that faces the camera
# at the layout's scale, so on_screen() finds the 3D point under a zone.
AZIMUTH, ELEVATION, DISTANCE = 0.65, 0.45, 40
RIGHT = (math.cos(AZIMUTH), math.sin(AZIMUTH), 0)
ABOVE = (-math.sin(AZIMUTH) * math.sin(ELEVATION), math.cos(AZIMUTH) * math.sin(ELEVATION), math.cos(ELEVATION))
TOWARD_EYE = (math.sin(AZIMUTH) * math.cos(ELEVATION), -math.cos(AZIMUTH) * math.cos(ELEVATION), math.sin(ELEVATION))
frame = scene.layout.zones(Zones.rows(1))[0]
scene.camera.perspective(fov_y=2 * math.atan(frame.height / 2 / DISTANCE))
scene.camera.look_at(eye=tuple(DISTANCE * c for c in TOWARD_EYE), target=(0, 0, 0), up=(0, 0, 1))


def on_screen(zone):
    """The 3D point the camera draws at the center of ``zone``."""
    x, y = zone.center
    return tuple(x * right + y * above for right, above in zip(RIGHT, ABOVE))


def helix(center, radius, height, t):
    """The point at ``t`` (0 to 1) of a three-turn helix around ``center``, rising along z."""
    cx, cy, cz = center
    angle = 3 * math.tau * t
    return cx + radius * math.cos(angle), cy + radius * math.sin(angle), cz + height * (t - 0.5)


def columns(variants, build):
    """One column per (label, value) variant, its label below; ``build(value, zone)`` draws in it."""
    zones = scene.layout.zones(Zones.columns(len(variants), gap="48px", padding="page_padding"))
    drawn = []
    for zone, (label, value) in zip(zones, variants):
        art, caption = zone.split(Zones.rows(["1fr", 0.5]))
        scene.text(label, role="code").place(caption)
        drawn.append(build(value, art))
    return drawn


# Each helix is a list of 3D points: points = [helix(center, ...) for t in ...].
def strip(zone):
    center = on_screen(zone)
    return [helix(center, zone.width * 0.3, zone.height * 0.75, k / 120) for k in range(121)]


# A uniform color, or one color per point: here a ramp from a ColorMap.
scene.segment("colors")
lines = columns(
    [
        ("polyline_3d(points, accent)", lambda points: scene.geometry.polyline_3d(points, accent)),
        (
            "polyline_3d(points, colors=ramp)",
            lambda points: scene.geometry.polyline_3d(
                points, colors=ColorMap.from_colors([accent, danger]).colors(len(points))
            ),
        ),
    ],
    lambda line, zone: line(strip(zone)),
)
scene.play([line.animate.create() for line in lines], duration=DRAW)
scene.wait(HOLD)

# Or a colormap from the start of the line to its end:
# scene.geometry.polyline_3d(points, colormap="inferno").
scene.segment("colormaps")
lines = columns(
    [('colormap="inferno"', "inferno"), ('colormap="viridis"', "viridis"), ('colormap="plasma"', "plasma")],
    lambda colormap, zone: scene.geometry.polyline_3d(strip(zone), colormap=colormap),
)
scene.play([line.animate.create() for line in lines], duration=DRAW)
scene.wait(HOLD)


# traced_path_3d follows a drawable's 3D position as it moves, here a small
# sphere that an updater drives along a helix: each label is the options of
# scene.geometry.traced_path_3d(pen, ...).
def traced(options, zone):
    center = on_screen(zone)
    pen = scene.geometry.sphere(0.12, material=Material3D.emissive(foreground)).move_to_3d(
        *helix(center, zone.width * 0.3, zone.height * 0.75, 0)
    )
    pen.add_updater_fn(lambda position, dt, elapsed: helix(center, zone.width * 0.3, zone.height * 0.75, elapsed / TRACE))
    return scene.geometry.traced_path_3d(pen, **options)


scene.segment("traces")
trails = columns(
    [
        ("traced_path_3d(pen)", {}),
        ('colormap="viridis"', {"colormap": "viridis"}),
        ('colormap="plasma"', {"colormap": "plasma"}),
    ],
    traced,
)
scene.play([trail.animate.fade_in() for trail in trails], duration=0.1)
scene.wait(TRACE)

# Samples older than dissipating_time seconds fade away, max_points keeps
# only the newest samples, and min_distance skips samples closer than that
# to the last one.
scene.segment("samples")
trails = columns(
    [
        ("dissipating_time=0.8", {"dissipating_time": 0.8}),
        ("max_points=40", {"max_points": 40}),
        ("min_distance=0.6", {"min_distance": 0.6}),
    ],
    traced,
)
scene.play([trail.animate.fade_in() for trail in trails], duration=0.1)
scene.wait(TRACE)

segment = DRAW + HOLD
trace = 0.1 + TRACE
seeks = [0.7, segment - 0.2, segment + 0.7, 2 * segment - 0.2]
seeks += [2 * segment + t for t in (1.2, trace - 0.2)] + [2 * segment + trace + t for t in (1.2, trace - 0.2)]
if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, seeks)
else:
    scene.render()

Axes 3d

3D axes with their grid planes, box sizes, linear, log, symlog and power scales, layers that animate apart, and planes and axes that take the sides the camera shows.

Axes 3d
View on GitHubgaanim examples/3d/axes_3d.py
Code · 165 lines
"""3D axes: scene.viz.cartesian_3d with its grid planes, box sizes, axis scales, layers and sides.

A distant perspective camera looks at every space from the front right with
z pointing up. Segments cover which planes and axes a space draws, the size
of its box, the scales of its axes, animating its layers one by one, and the
sides of the box its planes and axes take as it turns.
"""

import math
import os

from gaanim import Axis, Easing, Scene, Zones

DRAW = 1.4
HOLD = 0.8
TURN = 6.0

X = Axis.linear(-2, 2).ticks(1).label("x")
Y = Axis.linear(-2, 2).ticks(1).label("y")
Z = Axis.linear(-2, 2).ticks(1).label("z")

scene = Scene()
accent = scene.colors.accent

# The camera looks at the origin from AZIMUTH radians around z and ELEVATION
# radians above the floor, with z up. From DISTANCE away, a field of view as
# tall as the frame draws the plane through the origin that faces the camera
# at the layout's scale, so on_screen() finds the 3D point under a zone.
AZIMUTH, ELEVATION, DISTANCE = 0.65, 0.45, 40
RIGHT = (math.cos(AZIMUTH), math.sin(AZIMUTH), 0)
ABOVE = (-math.sin(AZIMUTH) * math.sin(ELEVATION), math.cos(AZIMUTH) * math.sin(ELEVATION), math.cos(ELEVATION))
TOWARD_EYE = (math.sin(AZIMUTH) * math.cos(ELEVATION), -math.cos(AZIMUTH) * math.cos(ELEVATION), math.sin(ELEVATION))
frame = scene.layout.zones(Zones.rows(1))[0]
scene.camera.perspective(fov_y=2 * math.atan(frame.height / 2 / DISTANCE))
scene.camera.look_at(eye=tuple(DISTANCE * c for c in TOWARD_EYE), target=(0, 0, 0), up=(0, 0, 1))


def on_screen(zone):
    """The 3D point the camera draws at the center of ``zone``."""
    x, y = zone.center
    return tuple(x * right + y * above for right, above in zip(RIGHT, ABOVE))


def gallery(variants, rows=2):
    """Lay out (label, build) pairs in a grid, each space above its label.

    ``build()`` returns a new space, which moves under its zone. Returns
    the spaces.
    """
    columns = -(-len(variants) // rows)
    grid = scene.layout.zones(Zones.grid(rows=rows, columns=columns, gap="48px", padding="page_padding"))
    spaces = []
    for zone, (label, build) in zip(grid, variants):
        art, caption = zone.split(Zones.rows(["1fr", 0.5 * (label.count("\n") + 1)], gap="96px"))
        scene.text(label, role="code").place(caption)
        spaces.append(build().move_to_3d(*on_screen(art)))
    scene.play([space.animate.create() for space in spaces], duration=DRAW)
    scene.wait(HOLD)
    return spaces


def space(size=(2.2, 2.2, 1.5), **options):
    """A space of X, Y and Z in a box of ``size``, with ``options``."""
    return lambda: scene.viz.cartesian_3d(X, Y, Z, size=size, **options)


# Each label is the options passed to scene.viz.cartesian_3d(X, Y, Z, size=(2.2, 2.2, 1.5), ...).
# grid switches the three planes at once; xy_grid, xz_grid and yz_grid
# override it for one plane.
scene.segment("planes")
gallery([
    ("grid=True", space()),
    ("xy_grid=False", space(xy_grid=False)),
    ("xz_grid=False, yz_grid=False", space(xz_grid=False, yz_grid=False)),
    ("xy_grid=False, yz_grid=False", space(xy_grid=False, yz_grid=False)),
])

# axes switches the three axis lines, which run along edges of the box's
# outline; x_axis, y_axis and z_axis override it for one line.
scene.segment("axes")
gallery(
    [
        ("grid=False", space((2.6, 2.6, 1.8), grid=False)),
        ("grid=False,\nz_axis=False", space((2.6, 2.6, 1.8), grid=False, z_axis=False)),
        ("axes=False", space((2.6, 2.6, 1.8), axes=False)),
    ],
    rows=1,
)

# size is the box's extent along x, y and z in scene units, whatever the
# data ranges: the same axes stretch to fill it.
scene.segment("size")
gallery(
    [
        ("size=(2.8, 2.8, 1)", space((2.8, 2.8, 1), xz_grid=False)),
        ("size=(1.8, 1.8, 3.4)", space((1.8, 1.8, 3.4), xz_grid=False)),
        ("size=(3.4, 1.7, 1.2)", space((3.4, 1.7, 1.2), xz_grid=False)),
    ],
    rows=1,
)


# Any Axis scale works on any axis; here x changes and y and z stay linear,
# so the grid lines across x show how each scale spaces its ticks.
def scaled(x_axis):
    return lambda: scene.viz.cartesian_3d(x_axis, Y, Z, size=(3, 1.8, 1.4), yz_grid=False)


scene.segment("scales")
gallery([
    ("Axis.linear(0, 1000).ticks(250)", scaled(Axis.linear(0, 1000).ticks(250))),
    ("Axis.log(1, 1000)", scaled(Axis.log(1, 1000))),
    ("Axis.symlog(-100, 100).ticks(100)", scaled(Axis.symlog(-100, 100).ticks(100))),
    ("Axis.power(0, 100, 0.5).ticks(50)", scaled(Axis.power(0, 100, 0.5).ticks(50))),
])

# Every space keeps its parts in layers that animate on their own: "grid",
# "axes", "ticks", "numbers" and "labels". Axis.style colors the axis lines
# and their ticks. The axes draw edges of the box's outline, so they come first.
scene.segment("layers")
label_column, stage = scene.layout.zones(Zones.columns(["4fr", "3fr"], gap="120px", padding="page_padding"))
styled = [axis.style(color=accent, tick_color=accent) for axis in (X, Y, Z)]
world = scene.viz.cartesian_3d(*styled, size=(3.2, 3.2, 2.2)).move_to_3d(*on_screen(stage))
steps = [
    ('world.layer("axes").animate.create()', world.layer("axes").animate.create()),
    ('world.layer("grid").animate.fade_in()', world.layer("grid").animate.fade_in()),
    ('world.layer("ticks").animate.create()', world.layer("ticks").animate.create()),
    ('world.layer("numbers").animate.fade_in()', world.layer("numbers").animate.fade_in()),
    ('world.layer("labels").animate.fade_in()', world.layer("labels").animate.fade_in()),
]
rows = label_column.split(Zones.rows(len(steps), gap="24px"))
for row, (label, _) in zip(rows, steps):
    scene.text(label, role="code").place(row, anchor="right")
for _, step in steps:
    scene.play([step], duration=DRAW / 2)
scene.wait(HOLD)

# sides chooses where the planes and axes sit on the box. "view", the
# default, puts each plane on the face behind the box's content and each axis
# on an edge of the box's outline, as the camera sees it; "fixed" keeps them
# at the box's lowest corner. Both boxes turn a full turn about z.
scene.segment("sides")
turning = gallery(
    [
        ('sides="view"', space((2.8, 2.8, 1.9), sides="view")),
        ('sides="fixed"', space((2.8, 2.8, 1.9), sides="fixed")),
    ],
    rows=1,
)
scene.play([turn.animate.rotate_by_3d("z", math.tau) for turn in turning], duration=TURN, easing=Easing.LINEAR)
scene.wait(HOLD)

# Drawing and settled in the first four segments, then each layer step.
segment = DRAW + HOLD
seeks = [segment * index + t for index in range(4) for t in (0.6, DRAW + 0.4)]
seeks += [4 * segment + DRAW / 2 * step + 0.6 for step in range(len(steps))]
seeks += [4 * segment + DRAW / 2 * len(steps) + 0.4]
# Each box drawn, then turned to each quarter.
sides_start = 4 * segment + DRAW / 2 * len(steps) + HOLD
seeks += [sides_start + DRAW + HOLD + TURN * eighth / 8 for eighth in (1, 3, 5, 7)]
if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, seeks)
else:
    scene.render()

Plots 3d

Surfaces, parametric curves and vector fields in a 3D space, static and driven by parameters.

Plots 3d
View on GitHubgaanim examples/3d/plots_3d.py
Code · 157 lines
"""3D plots: surfaces, parametric curves and vector fields drawn in a cartesian_3d space.

Each row draws one plot in its own space, seen by a distant perspective
camera with z pointing up, and is labelled with the call on the space that
builds it; the functions it plots are defined above each segment, and
curves are stroked with the accent.
Segments cover surfaces z = f(x, y), plots that follow animated inputs,
parametric curves, the arrows and streamlines of a 3D vector field, and
surfaces lit by a material.
"""

import math
import os

from gaanim import Axis, Material3D, Scene, Zones

DRAW = 1.4
HOLD = 0.8

X = Axis.linear(-3, 3).ticks(1)
Y = Axis.linear(-3, 3).ticks(1)
Z = Axis.linear(-2, 2).ticks(1)

scene = Scene()
accent = scene.colors.accent

# The camera looks at the origin from AZIMUTH radians around z and ELEVATION
# radians above the floor, with z up. From DISTANCE away, a field of view as
# tall as the frame draws the plane through the origin that faces the camera
# at the layout's scale, so on_screen() finds the 3D point under a zone.
AZIMUTH, ELEVATION, DISTANCE = 0.65, 0.45, 40
RIGHT = (math.cos(AZIMUTH), math.sin(AZIMUTH), 0)
ABOVE = (-math.sin(AZIMUTH) * math.sin(ELEVATION), math.cos(AZIMUTH) * math.sin(ELEVATION), math.cos(ELEVATION))
TOWARD_EYE = (math.sin(AZIMUTH) * math.cos(ELEVATION), -math.cos(AZIMUTH) * math.cos(ELEVATION), math.sin(ELEVATION))
frame = scene.layout.zones(Zones.rows(1))[0]
scene.camera.perspective(fov_y=2 * math.atan(frame.height / 2 / DISTANCE))
scene.camera.look_at(eye=tuple(DISTANCE * c for c in TOWARD_EYE), target=(0, 0, 0), up=(0, 0, 1))


def on_screen(zone):
    """The 3D point the camera draws at the center of ``zone``."""
    x, y = zone.center
    return tuple(x * right + y * above for right, above in zip(RIGHT, ABOVE))


def pair(variants):
    """Draw two (label, plot) variants in rows, the code to the left of a fresh space.

    ``plot(space)`` draws in the space and returns what to reveal.
    """
    grid = scene.layout.zones(
        Zones.grid(rows=len(variants), columns=["5fr", "2fr"], gap="24px", column_gap="48px", padding="page_padding")
    )
    reveals = []
    for index, (label, plot) in enumerate(variants):
        scene.text(label, role="code").place(grid[2 * index], anchor="right")
        space = scene.viz.cartesian_3d(X, Y, Z, size=(2.8, 2.8, 1.9), xz_grid=False)
        space.move_to_3d(*on_screen(grid[2 * index + 1]))
        reveals += [space.animate.create(), plot(space).animate.create()]
    scene.play(reveals, duration=DRAW)


# A surface samples z = f(x, y) on a grid of resolution points and colors
# it by height; fewer points give a coarser mesh.
def wave(x, y):
    return math.sin(x) * math.cos(y)


def bowl(x, y):
    return (x * x + y * y) / 6 - 1.5


scene.segment("surfaces")
pair([
    ("space.surface(wave)", lambda space: space.surface(wave)),
    ("space.surface(bowl, resolution=(7, 7))", lambda space: space.surface(bowl, resolution=(7, 7))),
])
scene.wait(HOLD)


# Plots take extra arguments from inputs, reactive values such as a
# parameter, and redraw whenever they change: here phase and turns animate.
def travel(x, y, phase):
    return math.sin(x + phase) * 0.8 * math.cos(y / 2)


def coil(t, turns):
    angle = turns * math.tau * t
    return 2.4 * math.cos(angle), 2.4 * math.sin(angle), 3.6 * t - 1.8


scene.segment("inputs")
phase = scene.viz.parameter(0.0)
turns = scene.viz.parameter(0.5)
pair([
    ("space.surface(travel, inputs=[phase])", lambda space: space.surface(travel, inputs=[phase])),
    (
        "space.parametric(coil, (0, 1), inputs=[turns])",
        lambda space: space.parametric(coil, (0, 1), inputs=[turns]).stroke(accent, 0.04),
    ),
])
scene.play([phase.animate.set(math.tau), turns.animate.set(3)], duration=2.4)
scene.wait(HOLD)


# A parametric curve maps t over its domain to (x, y, z); samples sets how
# many points trace it.
def helix(t):
    return 2.2 * math.cos(t), 2.2 * math.sin(t), t / 4 - 1.6


scene.segment("curves")
pair([
    ("space.parametric(helix, (0, 12.6))", lambda space: space.parametric(helix, (0, 12.6)).stroke(accent, 0.04)),
    (
        "space.parametric(helix, (0, 12.6), samples=16)",
        lambda space: space.parametric(helix, (0, 12.6), samples=16).stroke(accent, 0.04),
    ),
])
scene.wait(HOLD)


# A field maps (x, y, z) to a vector: field = space.field(swirl). Its arrows
# sample it on a 3D grid and its streamlines follow it from seed points,
# both colored by magnitude.
def swirl(x, y, z):
    return -y, x, 0.6


scene.segment("fields")
pair([
    ("field.arrows(resolution=(6, 6, 4))", lambda space: space.field(swirl).arrows(resolution=(6, 6, 4))),
    ("field.streamlines(seeds=(3, 3, 2))", lambda space: space.field(swirl).streamlines(seeds=(3, 3, 2))),
])
scene.wait(HOLD)


# A material lights a surface on both sides, keeping its colors, so its
# relief shows in light and shadow: matte = Material3D.matte() and
# metal = Material3D.metal(), under a low light from the camera's left.
matte = Material3D.matte()
metal = Material3D.metal()

scene.segment("lighting")
scene.geometry.light_3d("directional").move_to_3d(-9, -3, 5)
pair([
    ("space.surface(wave, material=matte)", lambda space: space.surface(wave, material=matte)),
    ("space.surface(bowl, material=metal)", lambda space: space.surface(bowl, material=metal)),
])
scene.wait(HOLD)

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    # Drawing and drawn plots; the inputs segment also as its inputs animate.
    scene.snapshots(snapshots, [1.0, 2.0, 3.0, 4.6, 5.6, 6.6, 7.6, 8.7, 9.6, 10.9, 11.8, 13.1])
else:
    scene.render()

Axonometric

A 3D model drawn as flat shapes from isometric, dimetric, plan, front and side views, turned and morphed between views.

Axonometric
View on GitHubgaanim examples/3d/axonometric.py
Code · 164 lines
"""Axonometric drawings: a 3D model drawn as flat shapes from isometric, dimetric, plan and other views.

``scene.geometry.axonometric(view)`` returns a projection whose polygons,
polylines and lines take model points (z up) and draw ordinary 2D shapes,
which ``depth_sort`` orders like a painter. Segments cover the named views,
custom angles, animating a drawing from one view to another, and the kinds
of drawing a projection makes.
"""

import os

from gaanim import Scene, Zones

DRAW = 1.2
MOVE = 1.6
HOLD = 0.8

scene = Scene()
accent = scene.colors.accent
rule = scene.colors.rule
muted = scene.colors.muted
chart = scene.colors.chart
ink = scene.colors.background
foreground = scene.colors.foreground

# A small building, in model units: a floor, walls (the front one with a
# door), an L-shaped roof slab, three columns and a beam above it.
WIDTH, DEPTH, HEIGHT = 4, 3, 2.4
CENTER = (WIDTH / 2, DEPTH / 2, HEIGHT / 2)
SCALE = 0.72


def face(projection, points, color):
    return projection.polygon(points).fill(color).stroke(ink, 0.03)


def building(projection):
    """Draw the building with ``projection`` and return its drawings."""
    w, d, h = WIDTH, DEPTH, HEIGHT
    top = h + 0.6
    drawings = [
        face(projection, [(0, 0, 0), (w, 0, 0), (w, d, 0), (0, d, 0)], muted),
        face(projection, [(0, d, 0), (w, d, 0), (w, d, h), (0, d, h)], accent),
        face(projection, [(0, 0, 0), (0, d, 0), (0, d, h), (0, 0, h)], rule),
        face(projection, [(0, 0, 0), (1.5, 0, 0), (1.5, 0, h), (0, 0, h)], accent),
        face(projection, [(2.5, 0, 0), (w, 0, 0), (w, 0, h), (2.5, 0, h)], accent),
        face(projection, [(0, 0, h), (w, 0, h), (w, 1.5, h), (2, 1.5, h), (2, d, h), (0, d, h)], chart),
    ]
    drawings += [projection.line((x, y, 0), (x, y, top)).stroke(foreground, 0.05) for x, y in [(w, d), (w, 1.5), (2, d)]]
    drawings.append(projection.polyline([(2, d, top), (w, d, top), (w, 1.5, top)]).no_fill().stroke(foreground, 0.05))
    return drawings


def centered(zone, view="isometric", **angles):
    """A projection with ``view`` that draws the building's center at the center of ``zone``."""
    x, y = scene.geometry.axonometric(view, scale=SCALE, **angles).point(*CENTER)
    cx, cy = zone.center
    return scene.geometry.axonometric(view, origin=(cx - x, cy - y), scale=SCALE, **angles)


def gallery(variants):
    """One column per (label, view, angles) variant, the building above its label."""
    columns = scene.layout.zones(Zones.columns(len(variants), gap="48px", padding="page_padding"))
    drawings = []
    for column, (label, view, angles) in zip(columns, variants):
        art, caption = column.split(Zones.rows(["1fr", 0.5]))
        scene.text(label, role="code").place(caption)
        projection = centered(art, view, **angles)
        parts = building(projection)
        projection.depth_sort(parts, z_index=10)
        drawings += parts
    scene.play([drawing.animate.create() for drawing in drawings], duration=DRAW)
    scene.wait(HOLD)


# Each label is the view of scene.geometry.axonometric(view, origin=..., scale=0.72).
# Isometric keeps the three axes at full length; dimetric is the 2:1
# drawing, whose receding axes rise one unit every two.
scene.segment("views")
gallery([('"isometric"', "isometric", {}), ('"dimetric"', "dimetric", {}), ('"plan"', "plan", {})])

# Elevations look straight along an axis: front along +y, side from +x.
scene.segment("elevations")
gallery([('"front"', "front", {}), ('"side"', "side", {})])

# azimuth (radians about z from the front view) and elevation (radians above
# the horizon) replace a view's angles: axonometric("isometric", elevation=-0.5)
# looks from below.
scene.segment("angles")
gallery([
    ("azimuth=0.3", "isometric", {"azimuth": 0.3}),
    ("elevation=1.2", "isometric", {"elevation": 1.2}),
    ("elevation=-0.5", "isometric", {"elevation": -0.5}),
])

# animate_to moves every drawing of a projection to another view, vertex by
# vertex. depth_sort(view=...) orders the drawings for the view they end in.
scene.segment("animate_to")
columns = scene.layout.zones(Zones.columns(2, gap="48px", padding="page_padding"))
moves = []
for column, (label, start, end) in zip(
    columns,
    [("iso.animate_to(plan)", {}, {"view": "plan"}), ("front.animate_to(iso)", {"view": "front"}, {})],
):
    art, caption = column.split(Zones.rows(["1fr", 0.5]))
    scene.text(label, role="code").place(caption)
    projection, target = centered(art, **start), centered(art, **end)
    parts = building(projection)
    projection.depth_sort(parts, z_index=10, view=target)
    moves.append(projection.animate_to(target).defaults(duration=MOVE))
scene.wait(HOLD)
scene.play(moves)
scene.wait(HOLD)

# A projection draws polygons, open or closed polylines and lines through
# model points; point() returns where a model point lands, to place labels.
STEPS = [(0, 0, 0), (0, 0, 0.7), (1, 0, 0.7), (1, 0, 1.4), (2, 0, 1.4), (2, 0, 2.1), (3, 0, 2.1), (3, 0, 0)]
WALL = [(0, 2, 0), (3, 2, 0), (3, 2, 2), (0, 2, 2)]
scene.segment("drawings")
grid = scene.layout.zones(Zones.grid(rows=2, columns=2, gap="48px", padding="page_padding"))


def floor_grid(projection):
    """Faint lines on the floor, three units square, to show the projection's axes."""
    lines = [projection.line((k, 0, 0), (k, 3, 0)) for k in range(4)]
    lines += [projection.line((0, k, 0), (3, k, 0)) for k in range(4)]
    return [line.stroke(rule, 0.02) for line in lines]


VARIANTS = [
    ("iso.polygon(WALL)", lambda iso: [iso.polygon(WALL).fill(accent)]),
    ("iso.polyline(STEPS)", lambda iso: [iso.polyline(STEPS).no_fill().stroke(accent, 0.06)]),
    ("iso.polyline(STEPS, closed=True)", lambda iso: [iso.polyline(STEPS, closed=True).no_fill().stroke(accent, 0.06)]),
    (
        "iso.line((3, 3, 0), (3, 3, 2))",
        lambda iso: [
            iso.line((3, 3, 0), (3, 3, 2)).stroke(accent, 0.06),
            scene.text("(3, 3, 2)", role="code").move_to(*iso.point(3, 3, 2.4)),
        ],
    ),
]
drawings = []
for zone, (label, draw) in zip(grid, VARIANTS):
    art, caption = zone.split(Zones.rows(["1fr", 0.5]))
    scene.text(label, role="code").place(caption)
    x, y = scene.geometry.axonometric(scale=0.62).point(1.5, 1.5, 1)
    cx, cy = art.center
    iso = scene.geometry.axonometric(origin=(cx - x, cy - y), scale=0.62)
    drawings += floor_grid(iso) + draw(iso)
scene.play([drawing.animate.create() for drawing in drawings], duration=DRAW)
scene.wait(HOLD)

# Drawn views in the first three segments, the move from view to view,
# and the drawings.
segment = DRAW + HOLD
move = 3 * segment
seeks = [segment * index + t for index in range(3) for t in (0.6, DRAW + 0.4)]
seeks += [move + HOLD - 0.2, move + HOLD + MOVE / 2, move + HOLD + MOVE + 0.4]
seeks += [move + 2 * HOLD + MOVE + t for t in (0.6, DRAW + 0.4)]
if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, seeks)
else:
    scene.render()

Camera 3d

The 3D camera: look_at, orbit, dolly and dolly zoom, perspective and orthographic lenses, saved poses, state_3d, bind_3d, a camera and an inset that follow a moving sphere, a camera that turns to follow it, a snapshot of the inset, and a view with a 3D camera of its own.

Camera 3d
View on GitHubgaanim examples/3d/camera_3d.py
Code · 187 lines
"""3D camera: aiming, orbiting, dollying, lenses, saved poses, bindings, follows, snapshots and views of their own.

Every segment starts from the same perspective pose over a few lit
primitives on a floor and plays one camera move. The label, pinned to the
frame with ``hud()`` so the camera never moves it, is the code of the move.
"""

import os

from gaanim import Anchor, Material3D, Scene, Zones

HOLD = 0.5
MOVE = 1.6

scene = Scene()
accent = scene.colors.accent
success = scene.colors.success
danger = scene.colors.danger
chart = scene.colors.chart
rule = scene.colors.rule

# A camera state is a reusable pose: where the eye is, what it looks at and
# its vertical field of view in radians. to() cuts to it; animate.to() moves.
HOME = scene.camera.state_3d(eye=(7, 5, 10), target=(0, -1, 0), fov_y=0.75)
OVERHEAD = scene.camera.state_3d(eye=(0, 13, 5), target=(0, -0.5, 0), fov_y=0.6)


def stage():
    """A floor with a cube, a sphere, a cone and a cylinder; returns the sphere."""
    scene.geometry.plane(11, 7, material=Material3D.matte(rule)).move_to_3d(0, -1, 0)
    scene.geometry.cube(2, material=Material3D.matte(accent)).move_to_3d(-3, 0, -0.5)
    scene.geometry.cone(1.1, 2.6, material=Material3D.matte(danger)).move_to_3d(2.6, 0.3, -1.2)
    scene.geometry.cylinder(0.7, 1.6, material=Material3D.metal(chart)).move_to_3d(3.2, -0.2, 1.8)
    return scene.geometry.sphere(1.1, material=Material3D.matte(success)).move_to_3d(-0.2, 0.1, 1.2)


def shot(name, label):
    """Start segment ``name`` at the home pose, with its stage and its label; returns the sphere."""
    scene.segment(name)
    scene.camera.to(HOME)
    band = scene.layout.zones(Zones.rows(["1fr", 0.5], padding="page_padding"))[1]
    scene.text(label, role="code", text_align="left").hud().place(band, anchor="left")
    sphere = stage()
    scene.wait(HOLD)
    return sphere


def move(animation):
    """Play one camera move, then hold where it ends."""
    scene.play([animation.duration(MOVE)])
    scene.wait(HOLD)


# Aim the camera from a new eye at a new target.
shot("look_at", "scene.camera.animate.look_at(eye=(0, 9, 9), target=(0, -1, 0))")
move(scene.camera.animate.look_at(eye=(0, 9, 9), target=(0, -1, 0)))

# Circle the target: yaw turns about the vertical, pitch raises or lowers the eye.
shot("orbit", "scene.camera.animate.orbit(delta_yaw=1.2, delta_pitch=0.25)")
move(scene.camera.animate.orbit(delta_yaw=1.2, delta_pitch=0.25))

# Move the eye along its line of sight: below 1 closer, above 1 farther.
shot("dolly", "scene.camera.animate.dolly(0.55)")
move(scene.camera.animate.dolly(0.55))

# Change the lens: a narrower field of view zooms in without moving the eye.
shot("perspective", "scene.camera.animate.perspective(0.35)")
move(scene.camera.animate.perspective(0.35))

# Dolly in while the lens widens, so the target keeps its size and the depth
# stretches: the vertigo shot. Above 1 the eye backs away and depth flattens.
shot("dolly_zoom", "scene.camera.animate.dolly_zoom(0.4)")
move(scene.camera.animate.dolly_zoom(0.4))

# Move to a stored state, then back to a pose saved under a name.
shot("states", 'scene.camera.save("home")\nscene.camera.animate.to(OVERHEAD)\nscene.camera.animate.restore("home")')
scene.camera.save("home")
move(scene.camera.animate.to(OVERHEAD))
move(scene.camera.animate.restore("home"))

# Bind the camera to drawables and reactive values until the binding is
# disabled: here its target follows the sphere and its field of view a
# parameter.
ball = shot("bind_3d", "follow = scene.camera.bind_3d(target=ball, fov_y=lens)")
lens = scene.viz.parameter(0.75)
follow = scene.camera.bind_3d(target=ball, fov_y=lens)
scene.play([ball.animate.move_to_3d(-3.5, 0.1, 2.5), lens.animate.set(0.5)], duration=MOVE)
scene.play([ball.animate.move_to_3d(3.5, 0.1, 2.5)], duration=MOVE)
scene.wait(HOLD)
follow.disable()

# Switch to a parallel projection at once; an orbit then turns the same view
# without perspective.
shot("orthographic", "scene.camera.orthographic()\nscene.camera.animate.orbit(delta_yaw=1.2, delta_pitch=0)")
scene.camera.orthographic()
move(scene.camera.animate.orbit(delta_yaw=1.2, delta_pitch=0))

# Back to the default 2D camera: orthographic, looking down the z axis.
shot("reset", "scene.camera.animate.reset()")
move(scene.camera.animate.reset())

# Follow the sphere as it rises and moves away: the camera moves with it,
# without turning, and keeps it at the center as it framed the target; with
# a lag it catches up. Unlike bind_3d, the eye moves too.
ball = shot("follow", "scene.camera.animate.follow(ball, lag=0.3)")
scene.play(
    [
        scene.camera.animate.follow(ball, lag=0.3).duration(2 * MOVE),
        ball.animate.move_to_3d(3, 1.5, -2).duration(2 * MOVE),
    ]
)
scene.wait(HOLD)

# A second camera follows the sphere too: the inset's frame stays where the
# main camera draws it, and the screen shows it enlarged.
ball = shot("inset", "scene.camera.inset(ball, zoom=3, follow=True)")
view = scene.camera.inset(ball, zoom=3, at=Anchor.TOP_RIGHT, follow=True)
scene.play([view.animate.pop_out().duration(MOVE)])
scene.play([ball.animate.move_to_3d(3, 1.5, -2).duration(2 * MOVE)])
scene.wait(HOLD)

# view.snapshot() keeps what the inset shows at one instant, the 3D content
# drawn as the main camera drew it then, while the inset goes on following
# the sphere.
ball = shot("snapshot", "photo = view.snapshot()")
view = scene.camera.inset(ball, zoom=2, at=Anchor.TOP_RIGHT, follow=True)
page = scene.layout.zones(Zones.rows(["1fr", 0.5], padding="page_padding"))[0]
scene.play([view.animate.pop_out().duration(MOVE)])
photo = view.snapshot()
scene.play(
    [
        photo.animate.scale_to(0.5).duration(MOVE),
        photo.animate.place(page, anchor="bottom_right").duration(MOVE),
        ball.animate.move_to_3d(3, 1.5, -2).duration(2 * MOVE),
    ]
)
scene.wait(HOLD)

# With turn=True the camera stays where it is and turns to keep the sphere
# at the center, as on a tripod, and ends looking at it.
ball = shot("turn", "scene.camera.animate.follow(ball, turn=True)")
scene.play(
    [
        scene.camera.animate.follow(ball, turn=True).duration(2 * MOVE),
        ball.animate.move_to_3d(3, 1.5, -2).duration(2 * MOVE),
    ]
)
scene.wait(HOLD)

# A view with a 3D camera of its own shows the stage from another angle:
# from overhead, keeping the sphere at its center as it moves.
ball = shot("view_3d", "view = screen.camera_view_3d(eye=(0, 12, 0.5), target=ball)")
corner = scene.layout.zones(Zones.grid(rows=2, columns=2, padding="page_padding"))[1]
top = scene.geometry.rounded_rect(4.8, 2.7, 0.15).stroke(accent, 0.04).hud().place(corner, anchor="top_right")
top.camera_view_3d(eye=(0, 12, 0.5), target=ball, fov_y=0.6, up=(0, 0, -1))
scene.play([ball.animate.move_to_3d(3, 1.5, -2).duration(2 * MOVE)])
scene.wait(HOLD)

# Before and after each move. Segments last one move, except the states
# segment (two moves) and the bind_3d segment (two moves of the sphere).
one = 2 * HOLD + MOVE
states = 5 * one
bind = states + HOLD + 2 * (MOVE + HOLD)
last = bind + 2 * (HOLD + MOVE)
seeks = [start + t for start in (0, one, 2 * one, 3 * one, 4 * one, last, last + one) for t in (0.3, one - 0.2)]
seeks += [states + 0.3, states + HOLD + MOVE + 0.2, bind - 0.2]
seeks += [bind + HOLD + MOVE, last - 0.2, last + one + HOLD + MOVE / 2]
# Halfway through the follow and once it holds; the inset as it opens,
# halfway through the sphere's move and at its end.
follow = last + 2 * one
inset = follow + 2 * (HOLD + MOVE)
seeks += [follow + HOLD + MOVE, follow + HOLD + 2 * MOVE + HOLD / 2]
seeks += [inset + HOLD + MOVE / 2, inset + HOLD + 2 * MOVE, inset + HOLD + 3 * MOVE + HOLD / 2]
# The snapshot as it leaves the inset, and both once the sphere has moved.
snapshot = inset + 2 * HOLD + 3 * MOVE
seeks += [snapshot + HOLD + MOVE + MOVE / 2, snapshot + HOLD + 3 * MOVE + HOLD / 2]
# Halfway through the turning follow and once it holds.
turn = snapshot + 2 * HOLD + 3 * MOVE
seeks += [turn + HOLD + MOVE, turn + HOLD + 2 * MOVE + HOLD / 2]
# The view from overhead as the sphere starts and once it has moved.
view_3d = turn + 2 * HOLD + 2 * MOVE
seeks += [view_3d + HOLD + MOVE / 4, view_3d + HOLD + 2 * MOVE + HOLD / 2]
if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, sorted(seeks))
else:
    scene.render()

Framing 3d

A portal frame kept beside a panel of steps by screen_offset while the camera orbits and dollies, labels pinned above its points with billboard(offset=, anchor=), and a camera bound to coordinates computed from a parameter.

Framing 3d
View on GitHubgaanim examples/3d/framing_3d.py
Code · 100 lines
"""Framing 3D content beside a panel: a lens shift that keeps a model aside, labels pinned above its points, and a camera driven by parameters.

A portal frame of two columns and a beam stands on a floor, with the steps
of its analysis on a panel at the right. screen_offset shifts the lens, so
the frame shows in the left zone while the camera orbits and dollies around
it, without turning. billboard(offset=, anchor=) keeps a label a fixed
distance above a 3D point on screen, however far it is. bind_3d takes
coordinates made of parameters, with no auxiliary points. The label at the
bottom is the code of each segment.
"""

import math
import os

from gaanim import Material3D, Scene, Zones, computed

HOLD = 0.6
MOVE = 2.0
SEEKS = []

scene = Scene()
accent = scene.colors.accent
rule = scene.colors.rule
success = scene.colors.success

page = scene.layout.zones(Zones.rows(["1fr", 0.5], padding="page_padding"))
model_zone, panel_zone = page[0].split(Zones.columns(["3fr", "2fr"], gap="32px"))
band = page[1]
# Where the frame's middle shows: the middle of the left zone, from the
# middle of the frame.
ASIDE = model_zone.center

HOME = scene.camera.state_3d(eye=(6, 4, 10), target=(0, 1.5, 0), fov_y=0.7)
# Points on top of the beam: its two nodes and its middle, where a load goes.
POINTS = {"B": (-2, 3.2, 0), "w": (0, 3.2, 0), "C": (2, 3.2, 0)}


def portal():
    """A floor, two columns and a beam between the nodes."""
    scene.geometry.plane(7, 4.5, material=Material3D.matte(rule))
    for x in (-2, 2):
        scene.geometry.cube(1, material=Material3D.matte(accent)).scale_to_3d(0.3, 3, 0.3).move_to_3d(x, 1.5, 0)
    scene.geometry.cube(1, material=Material3D.matte(success)).scale_to_3d(4.3, 0.35, 0.35).move_to_3d(0, 3, 0)


def panel():
    """The steps of the analysis, on the right."""
    rows = panel_zone.split(Zones.rows(3, gap="16px"))
    for step, row in zip(("1  Geometry", "2  Loads", "3  Deformed shape"), rows):
        scene.text(step, size=0.32).hud().place(row, anchor="left", fit="scale_down")


def shot(name, label):
    """Start segment ``name`` at the home pose, with the frame, the panel and the code label."""
    scene.segment(name)
    scene.camera.to(HOME)
    scene.text(label, role="code", text_align="left").hud().place(band, anchor="left")
    portal()
    panel()
    scene.wait(HOLD)


def move(animations):
    """Play camera moves together, then hold where they end."""
    SEEKS.append(scene.cursor + MOVE / 2)
    scene.play(animations, duration=MOVE)
    SEEKS.append(scene.cursor + HOLD / 2)
    scene.wait(HOLD)


# The lens shifts the frame into the left zone; then the camera orbits and
# dollies around it while it stays there.
shot("screen_offset", f"scene.camera.animate.screen_offset({ASIDE[0]:.1f}, {ASIDE[1]:.1f})")
move([scene.camera.animate.screen_offset(*ASIDE)])
move([scene.camera.animate.orbit(-1.1, 0.15, dolly=0.8)])

# Labels a fixed distance above their points on screen, near or far.
shot("billboard", 'text.billboard(offset=(0, 0.2), anchor="bottom")')
scene.camera.screen_offset(*ASIDE)
for name, point in POINTS.items():
    scene.text(name, size=0.4).move_to_3d(*point).billboard(offset=(0, 0.2), anchor="bottom")
move([scene.camera.animate.orbit(1.2, 0.2)])

# The eye's coordinates are computed from a yaw parameter: animating it
# circles the camera, with the lens still shifted.
shot("bind_3d", "scene.camera.bind_3d(eye=(computed(...), 4, computed(...)), screen_offset=...)")
yaw = scene.viz.parameter(0.55)
eye = (
    computed(lambda angle: 11 * math.sin(angle), inputs=[yaw]),
    4.0,
    computed(lambda angle: 11 * math.cos(angle), inputs=[yaw]),
)
scene.camera.bind_3d(eye=eye, target=(0, 1.5, 0), screen_offset=ASIDE)
move([yaw.animate.set(-0.9)])

if snapshots := os.environ.get("GAANIM_SNAPSHOTS"):
    scene.snapshots(snapshots, SEEKS)
else:
    scene.render()