handanim.core Package

handanim.core.scene

class handanim.core.scene.Scene(width=1280, height=720, fps=24, background_color=(1, 1, 1), viewport=None, narration=None, audio=None, background_music=None, music_volume=0.18, music_loop=True, sketch_sound=False, sketch_sound_volume=0.25, sketch_sound_style='chalk', eraser_sound=False, eraser_sound_volume=0.45, transition_sound=False, transition_sound_volume=0.45)[source]

Bases: object

A Scene represents an animation composition where drawables and events are managed.

Handles the creation, timeline, and rendering of animated graphics with configurable viewport, background, and frame settings. Supports creating snapshots and full video renders of animated sequences.

Parameters:
width

Width of the rendering surface in pixels.

Type:

int

height

Height of the rendering surface in pixels.

Type:

int

fps

Frames per second for video rendering.

Type:

int

background_color

RGB color for scene background.

Type:

tuple

viewport

Defines coordinate mapping between world and screen space.

Type:

Viewport

set_viewport_to_identity()[source]

Resets the viewport to an identity transformation, mapping world coordinates directly to screen coordinates.

get_viewport_bounds()[source]

Retrieves the viewport’s boundaries in world coordinates.

Returns:

A tuple containing (x_min, x_max, y_min, y_max) representing the viewport’s world coordinate boundaries.

Return type:

Tuple[float, float, float, float]

add(event, drawable=None, *, overlay=False, background=False)[source]

Adds an animation event to a drawable primitive in the scene.

Handles different scenarios including: - Self-driving drawables such as Captions, CountdownTimer, ProgressBar, or TimeDrivenDrawable - Swap(a, b, t) events (e.g. scene.add(Swap(a, b, t))) - Composite animation events (recursively adding sub-events) - Drawable groups with parallel or sequential event distribution - Single event and drawable cases

Manages event tracking, drawable caching, and object timelines.

Parameters:
  • event (AnimationEvent | Drawable) – The animation event (or self-driving drawable) to be added.

  • drawable (Drawable, optional) – The drawable primitive to apply the event to.

  • overlay (bool, optional) – If True, renders the drawable in the camera-independent foreground overlay layer.

  • background (bool, optional) – If True, renders the drawable in the camera-independent background layer.

swap(source, target, start_time=0.0, duration=0.0, easing_fun=None, *, overlay=False, background=False)[source]

Atomically hide source and show target at start_time (or cross-fade if duration > 0).

Parameters:
Return type:

None

get_current_time()[source]

Returns the end time of the latest event or beat cursor in the scene, or 0.0 if empty.

Return type:

float

wait(duration)[source]

Insert a pause of duration seconds after the current last event.

Returns the time at which the next event should start.

Usage:

scene.add(SketchAnimation(start_time=0, duration=2), rect)
t = scene.wait(1.0)  # t = 3.0
scene.add(SketchAnimation(start_time=t, duration=2), circle)
Parameters:

duration (float)

Return type:

float

beat(name='', narration=None, duration=None, start_time=None, pad_before=0.0, pad_after=0.3, transition_on_exit=None)[source]

Open a voice-driven BeatContext block for relative timeline authoring.

Usage:

with scene.beat("Intro", narration=clip1, pad_after=0.4) as b:
    b.sketch(title, at=0.0, duration=1.0)
    b.sketch(diagram, word="triangle", duration=1.5, clear_on_exit=True)
Parameters:
get_stitched_narration(output_path=None)[source]

Stitch all narration AudioClip`s attached to `scene.beat(…) blocks into a single master AudioClip.

Parameters:

output_path (str | Path | None)

add_beat_captions(**caption_kwargs)[source]

Create and attach a Captions drawable on scene.overlay from all scene.beat() narrations.

Parameters:

caption_kwargs (Any)

static place_relative(target, reference, target_anchor='center', reference_anchor='center', offset=(0.0, 0.0))[source]

Position target so that its anchor aligns with a reference drawable’s anchor.

Returns the translated target — does not mutate the original (consistent with the immutability invariant).

Parameters:
  • target (Drawable) – The drawable to reposition.

  • reference (Drawable) – The drawable to align against.

  • target_anchor (str) – Anchor name on the target (e.g. “top_left”, “center”).

  • reference_anchor (str) – Anchor name on the reference.

  • offset (tuple[float, float]) – Additional (dx, dy) offset after alignment.

Return type:

Drawable

Usage:

label = Text("hello", position=(0, 0))
label = Scene.place_relative(label, rect, "top", "bottom", offset=(0, -20))
add_camera(event)[source]

Register a CameraAnimation that controls the viewport over time.

Camera events are kept separate from drawable events and are applied per-frame in the render loop without touching any drawable’s OpsSet.

Parameters:

event – A CameraAnimation instance (or any object with an apply_to_viewport(viewport, progress) method).

Return type:

None

add_transition(transition)[source]

Register a SceneTransition (such as PageTurnTransition or PaperCrumpleTransition).

Transitions fold or crumple all world-space drawables created before transition.start_time, revealing a fresh page underneath and automatically deactivating the previous page’s world drawables once transition.end_time is reached. Overlay drawables (scene.overlay) remain unaffected.

Return type:

None

get_active_objects(t)[source]

Determines the list of object IDs that are active at a specific time point.

Calculates object visibility by toggling their active status based on their timeline. An object becomes active when its timeline reaches a time point, and its status alternates with each subsequent time point. World-space objects whose latest creation preceded a completed SceneTransition (last_shown_time < tr.start_time and t >= tr.end_time) are automatically deactivated.

Parameters:

t (float) – The time point (in seconds) to check object activity.

Returns:

A list of object IDs that are active at the given time point.

Return type:

List[str]

find_key_frames()[source]

Find the key frames that we need to calculate for the animation Key frames are the frames where an object is created or deleted

Return type:

tuple[list[float], dict[str, list[AnimationEvent]]]

get_object_event_and_progress(object_id, t, drawable_events_mapping)[source]
Parameters:
Return type:

list[tuple[AnimationEvent, float]]

get_animated_opsset_at_time(drawable_id, t, event_and_progress, drawable_events_mapping)[source]
Parameters:
Return type:

OpsSet

create_event_timeline(max_length=None)[source]

Creates a timeline of animation events and calculates the OpsSet for each frame.

This method processes all drawable events, determines active objects at each frame, and generates a list of OpsSet operations representing the animation progression.

Parameters:
  • fps (int, optional) – Frames per second for the animation. Defaults to 30.

  • max_length (Optional[float], optional) – Maximum duration of the animation. Defaults to None.

  • verbose (bool, optional) – If True, provides detailed logging during animation calculation. Defaults to False.

Returns:

A list of OpsSet operations for each frame in the animation.

Return type:

List[OpsSet]

introspect(max_length=None, safe_zone=None, check_overlaps=True)[source]

Analyze the scene layout, active drawable collisions, and platform safe zones without rendering frames.

Performs headless static inspection: - Calculates bounding boxes for all registered drawables. - Identifies objects placed outside the visible world viewport. - Checks platform UI safe zones when safe_zone=”youtube_shorts” or “youtube_landscape” is specified. - Detects unintended bounding-box overlaps between simultaneously active drawables at keyframe timestamps. - Audits event timing (creation, duration, deletion) and active intervals. - Reports warnings and errors in a machine-readable dictionary suitable for AI agents.

Returns:

dict containing duration, viewport, objects, overlaps, safe_zone_violations, warnings, and errors.

Parameters:
  • max_length (float | None)

  • safe_zone (str | None)

  • check_overlaps (bool)

Return type:

dict

render_frame(t, output_path=None, opsset=None)[source]

Render a single frame at time t (seconds) and return an (H, W, 3) uint8 RGB numpy array.

Evaluates only the requested timestamp t (unless a precomputed opsset is provided), avoiding full timeline computation for single stills. If output_path is provided, also writes the frame to disk (.png, .svg, or .pdf).

Parameters:
Return type:

ndarray

render_snapshot(output_path, frame_in_seconds, max_length=None)[source]

Render a snapshot of the animation at a specific time point as an SVG, PNG, or PDF file.

Evaluates only the requested timestamp frame_in_seconds rather than computing all frames across the full video timeline.

Parameters:
  • output_path (str) – Path to the output file (.svg, .png, or .pdf).

  • frame_in_seconds (float) – The exact time point (in seconds) to render.

  • max_length (Optional[float], optional) – Total duration of the animation. Defaults to None.

render_contact_sheet(output_path, timestamps=None, n_frames=6, cols=3, cell_width=360, safe_zone=None, max_length=None)[source]

Render multiple timestamp snapshots into a single annotated PNG grid image.

Ideal for fast LLM visual review of an entire storyboard in one image call.

Parameters:
Return type:

str

export_storyboard(n_frames, output_dir, format='svg', max_length=None)[source]

Export evenly-spaced keyframes as a storyboard.

Parameters:
  • n_frames (int) – Number of frames to export.

  • output_dir (str) – Directory to write output files.

  • format (str) – “svg” or “pdf”.

  • max_length (float | None) – Total animation duration override.

Returns:

List of output file paths.

Return type:

list[str]

render_keyframes(times, output_dir, format='svg', prefix='frame', max_length=None)[source]

Batch export snapshots at multiple timestamps.

Computes the event timeline once, then renders each requested frame.

Parameters:
  • times (list[float]) – List of timestamps (in seconds) to export.

  • output_dir (str) – Directory to write output files.

  • format (str) – “svg” or “pdf”.

  • prefix (str) – Filename prefix; files are named {prefix}_{i:03d}_{time:.2f}.{format}.

  • max_length (float | None) – Total animation duration override.

Returns:

List of output file paths.

Return type:

list[str]

render_handout(output_path, n_frames=6, times=None, max_length=None)[source]

Render a single multi-page PDF with one animation frame per page.

Either provide explicit times or let n_frames evenly-spaced keyframes be chosen automatically.

Parameters:
  • output_path (str) – Path to the output PDF file.

  • n_frames (int) – Number of evenly-spaced frames (ignored if times is given).

  • times (list[float] | None) – Explicit list of timestamps (in seconds) to render.

  • max_length (float | None) – Total animation duration override.

Returns:

The output file path.

Return type:

str

render_tikz(output_path, time=0.0, target_width_cm=12.0, max_length=None)[source]

Render a single animation frame as a standalone TikZ/LaTeX file.

Parameters:
  • output_path (str) – Path to write the .tex file.

  • time (float) – Timestamp (in seconds) to render.

  • target_width_cm (float) – Width of the tikzpicture in centimetres.

  • max_length (float | None) – Total animation duration override.

Returns:

The output file path.

Return type:

str

export_beamer(output_dir, n_frames=6, times=None, title='Handanim Slides', max_length=None, backend='cairo', target_width_cm=12.0)[source]

Export animation keyframes as a compilable Beamer/LaTeX slide deck.

Each keyframe becomes one overlay on a single frame, so the slides animate forward when presented.

With backend="cairo" (default), each keyframe is rendered as a Cairo PDF and embedded via \includegraphics.

With backend="tikz", keyframes are emitted as inline TikZ drawing commands — native LaTeX vector graphics, no external files.

Parameters:
  • output_dir (str) – Directory to write output files and the .tex file.

  • n_frames (int) – Number of evenly-spaced keyframes (ignored if times given).

  • times (list[float] | None) – Explicit list of timestamps to render.

  • title (str) – Title shown on the Beamer title page.

  • max_length (float | None) – Total animation duration override.

  • backend (str) – "cairo" for PDF-image overlays, "tikz" for native TikZ.

  • target_width_cm (float) – Width of tikzpicture (only used with backend="tikz").

Returns:

Path to the generated .tex file.

Return type:

str

set_background_music(music='marimba', volume=0.18, loop=True)[source]

Configure background theme music or audio to play (and optionally loop) in rendered videos.

Parameters:
  • music (Any) – Theme preset (“marimba”, “calm”, “upbeat”), True, AudioClip, or path to a WAV/MP3 file.

  • volume (float) – Volume multiplier for the music track (default 0.18).

  • loop (bool) – If True (default), repeats the background music across the full video duration.

Return type:

None

enable_sketch_sound(enabled=True, volume=None, style=None)[source]

Turn on/off or adjust chalk / sketch-pen drawing sounds during SketchAnimation events.

Parameters:
  • enabled (bool | float) – True / False to toggle sketch sound on or off, or a float volume multiplier (e.g. 0.15 to enable at volume 0.15, or 0.0 to turn off).

  • volume (float | None) – Optional volume multiplier (0.0 to 1.0, default 0.25). Setting volume=0 turns sound off.

  • style (str | None) – Optional drawing sound style (“chalk” or “pen”).

Return type:

None

disable_sketch_sound()[source]

Turn off automatic chalk / sketch-pen drawing sounds.

Return type:

None

set_sketch_sound(enabled=True, volume=None, style=None)[source]

Configure or toggle automatic sketch sound (alias for enable_sketch_sound).

Parameters:
Return type:

None

enable_eraser_sound(enabled=True, volume=None)[source]

Automatically play board/paper erasing sounds during Eraser animations.

Parameters:
Return type:

None

disable_eraser_sound()[source]

Turn off automatic eraser sounds.

Return type:

None

enable_transition_sound(enabled=True, volume=None)[source]

Automatically play page-turn and paper-crumple sounds during SceneTransition animations.

Parameters:
Return type:

None

disable_transition_sound()[source]

Turn off automatic scene transition sounds.

Return type:

None

extract_auto_sfx_events(include_sketch=None, include_eraser=None, include_transition=None, sketch_volume=None, sketch_style=None, eraser_volume=None, transition_volume=None)[source]

Extract non-overlapping chalk sketch, eraser, and transition SFX intervals from the scene timeline.

Parameters:
  • include_sketch (bool | float | None)

  • include_eraser (bool | float | None)

  • include_transition (bool | float | None)

  • sketch_volume (float | None)

  • sketch_style (str | None)

  • eraser_volume (float | None)

  • transition_volume (float | None)

Return type:

list[dict[str, Any]]

render(output_path, max_length=None, narration=None, background_music=None, music_volume=None, music_loop=None, sketch_sound=None, sketch_sound_volume=None, sketch_sound_style=None, eraser_sound=None, eraser_sound_volume=None, transition_sound=None, transition_sound_volume=None, sfx_events=None, *, crf=None, preset=None, tune=None, workers=1)[source]

Render the animation as a video file, optionally mixing narration, repeating background theme music, and automatic chalk/eraser/transition sound effects.

Parameters:
  • output_path (str) – Path to save the output video file.

  • max_length (Optional[float], optional) – Maximum duration of the animation. Defaults to None.

  • narration (Optional[Any], optional) – An AudioClip instance from voiceanim or path to a WAV/MP3 file.

  • background_music (Optional[Any], optional) – Theme preset (“marimba”, “calm”, “upbeat”), True, AudioClip, or path to a music file. Defaults to self.background_music.

  • music_volume (Optional[float], optional) – Background music volume multiplier.

  • music_loop (Optional[bool], optional) – Whether to repeat background music for the whole video.

  • sketch_sound (Optional[bool | float], optional) – True/False to turn automatic chalk sound on/off during SketchAnimation, or a float volume multiplier (e.g. 0.15 for quiet sketch sound, 0.0 to mute).

  • sketch_sound_volume (Optional[float], optional) – Volume multiplier (0.0 to 1.0) for sketch sounds.

  • sketch_sound_style (Optional[str], optional) – Style of sketch sound (“chalk” or “pen”).

  • eraser_sound (Optional[bool | float], optional) – If True (or positive float), adds erasing sound during Eraser.

  • eraser_sound_volume (Optional[float], optional) – Volume multiplier for eraser sounds.

  • transition_sound (Optional[bool | float], optional) – If True (or positive float), adds page-turn/crumple sound.

  • transition_sound_volume (Optional[float], optional) – Volume multiplier for transition sounds.

  • sfx_events (Optional[Sequence], optional) – Extra custom sound effect events to mix in.

  • crf (int | None)

  • preset (str | None)

  • tune (str | None)

  • workers (int)

handanim.core.drawable

class handanim.core.drawable.Drawable(stroke_style=<handanim.core.styles.StrokeStyle object>, sketch_style=<handanim.core.styles.SketchStyle object>, fill_style=None, glow_dot_hint=None, id=None, *args, **kwargs)[source]

Bases: object

A base class representing a drawable object with drawing, transformation, and styling capabilities.

This class provides a standard interface for creating drawable objects that can be drawn on a canvas. Subclasses must implement the draw() method to define specific drawing operations.

Parameters:
id

A unique hexadecimal identifier for the drawable object.

Type:

str

stroke_style

Defines the stroke styling for the drawable.

Type:

StrokeStyle

sketch_style

Defines the sketch styling for the drawable.

Type:

SketchStyle

fill_style

Optional fill style for the drawable.

Type:

Optional[FillStyle]

glow_dot_hint

Optional configuration for glow dot rendering.

Type:

Dict

draw()[source]

Abstract method to generate drawing operations.

Return type:

OpsSet

translate()[source]

Creates a translated version of the drawable.

Parameters:
Return type:

TransformedDrawable

scale()[source]

Creates a scaled version of the drawable.

Parameters:
Return type:

TransformedDrawable

rotate()[source]

Creates a rotated version of the drawable.

Parameters:

angle (float)

Return type:

TransformedDrawable

draw()[source]

Provides the list of operations to be performed to draw this particular drawable object on the canvas

Return type:

OpsSet

translate(offset_x, offset_y)[source]

Translates the drawable object by the given offset

Parameters:
Return type:

TransformedDrawable

scale(scale_x, scale_y)[source]

Scales the drawable object by the given scale factors

Parameters:
Return type:

TransformedDrawable

rotate(angle)[source]

Rotates the drawable object by the given angle

Parameters:

angle (float)

Return type:

TransformedDrawable

get_bbox()[source]
Return type:

BoundingBox

anchor(position='center')[source]

Return a named anchor point in world coordinates.

Parameters:

position (str) – One of “center”, “top_left”, “top_right”, “bottom_left”, “bottom_right”, “top”, “bottom”, “left”, “right”.

Return type:

tuple[float, float]

align_to(x, y, anchor='center')[source]

Return a translated copy whose named anchor is placed at (x, y).

Parameters:
Return type:

TransformedDrawable

center_at(x, y)[source]

Return a translated copy whose bounding-box center is placed at (x, y).

Parameters:
Return type:

TransformedDrawable

centred(x, y)[source]

Alias for center_at(x, y).

Parameters:
Return type:

TransformedDrawable

class handanim.core.drawable.TransformedDrawable(base_drawable, transformation_function, transformation_args=None, **kwargs)[source]

Bases: Drawable

A drawable object that applies a transformation to a base drawable.

Allows dynamic transformation of drawable objects by applying a specified transformation function to the base drawable’s operation set.

base_drawable

The original drawable object to be transformed

Type:

Drawable

transformation_function

Name of the transformation method to apply

Type:

callable

transformation_args

Arguments for the transformation method

Type:

dict

Raises:

ValueError – If the transformation function is invalid or not callable

Parameters:
  • base_drawable (Drawable)

  • transformation_function (str)

  • transformation_args (dict | None)

draw()[source]

Overrides the draw method of the base drawable object

Return type:

OpsSet

class handanim.core.drawable.DrawableFill(bound_box_list, fill_style=<handanim.core.styles.FillStyle object>, sketch_style=<handanim.core.styles.SketchStyle object>)[source]

Bases: object

A class representing a fill style for drawable objects, defining how an area should be filled.

Allows specification of bounding boxes, fill styles, and sketch styles for rendering.

bound_box_list

Defines the bounding boxes for filling

Type:

List[List[Tuple[float, float]]]

fill_style

Specifies the fill style parameters

Type:

FillStyle

sketch_style

Specifies the sketch style parameters

Type:

SketchStyle

Raises:

NotImplementedError – If the fill method is not implemented in a subclass

Parameters:
fill()[source]
Return type:

OpsSet

class handanim.core.drawable.DrawableGroup(elements, grouping_method='parallel', *args, **kwargs)[source]

Bases: Drawable

A drawable group that manages a collection of drawable elements with specified grouping behavior.

Allows applying transformations or animations to multiple drawable objects either in parallel or series.

Parameters:
  • elements (List[Drawable]) – A list of drawable objects to be grouped.

  • grouping_method (str, optional) – Determines how animations are applied. Can be ‘parallel’ (default) or ‘series’. Defaults to ‘parallel’.

elements

The list of drawable elements in the group.

Type:

List[Drawable]

grouping_method

The method used for applying transformations.

Type:

str

draw()[source]

This is useful to apply transformations to the entire group of objects at once

Return type:

OpsSet

handanim.core.draw_ops

class handanim.core.draw_ops.OpsType(*values)[source]

Bases: Enum

SET_PEN = 'set_pen'
MOVE_TO = 'move_to'
METADATA = 'metadata'
LINE_TO = 'line_to'
CURVE_TO = 'curve_to'
QUAD_CURVE_TO = 'quad_curve_to'
CLOSE_PATH = 'close_path'
DOT = 'dot'
IMAGE = 'image'
PUSH_CLIP = 'push_clip'
POP_CLIP = 'pop_clip'
class handanim.core.draw_ops.Ops(type, data, partial=1.0, meta=None)[source]

Bases: object

Represents a drawing operation to be performed in the animation system.

Parameters:
SETUP_OPS_TYPES

Types of operations considered setup operations.

Type:

List[OpsType]

type

The type of drawing operation.

Type:

OpsType

data

The data used to perform the drawing operation.

Type:

Any

partial

Fraction of the operation to be performed, defaults to 1.0.

Type:

float, optional

SETUP_OPS_TYPES = [OpsType.SET_PEN, OpsType.MOVE_TO, OpsType.METADATA]
class handanim.core.draw_ops.BoundingBox(min_x, min_y, max_x, max_y)[source]

Bases: object

A simple container representing a bounding box

Parameters:
min_x: float
min_y: float
max_x: float
max_y: float
property width: float
property height: float
property center: tuple[float, float]
property top_left: tuple[float, float]
property bottom_right: tuple[float, float]
class handanim.core.draw_ops.OpsSet(initial_set=None)[source]

Bases: object

Represents a collection of drawing operations with methods for manipulation and rendering.

Provides functionality to: - Add, extend, and manage a list of drawing operations - Calculate bounding box and center of gravity - Perform transformations like translation, scaling, and rotation - Render operations to a Cairo context

Parameters:

initial_set (Sequence[dict[Any, Any] | Ops] | None)

opsset

A list of drawing operations to be performed.

Type:

List[Ops]

add_meta(meta=None)[source]
Parameters:

meta (dict | None)

filter_by_meta_query(meta_key, meta_value)[source]
Parameters:
  • meta_key (str)

  • meta_value (Any)

add(ops)[source]
Parameters:

ops (Ops | dict)

extend(other_opsset)[source]
Parameters:

other_opsset (Any)

get_bbox()[source]

Calculate the bounding box that encompasses all points in the operations set.

Returns:

A tuple of (min_x, min_y, max_x, max_y) representing the coordinates of the bounding box. Returns (0, 0, 0, 0) if the operations set is empty.

Return type:

BoundingBox

Note

Currently supports only list-type point data. Curve calculations are not fully implemented.

get_center_of_gravity()[source]

Calculate the approximate geometric center of the operations set.

Returns:

A tuple of (x, y) coordinates representing the center point, computed as the midpoint of the bounding box.

Return type:

tuple[float, float]

get_last_ops(start_index=0)[source]

Retrieve the last valid operation from the operations set.

Parameters:

start_index (int, optional) – Starting index for searching backwards. Defaults to 0.

Returns:

A tuple containing the index and the last valid operation. Returns (None, None) if no valid operation is found.

Return type:

Tuple[Optional[float], Optional[Ops]]

Note

Valid operations include MOVE_TO, LINE_TO, CURVE_TO, and QUAD_CURVE_TO.

get_current_point()[source]

Retrieves the current drawing point from the last operation in the operations set.

Returns:

A tuple (x, y) representing the current drawing point, considering partial operations and different types of drawing operations (move, line, curve, quadratic curve). Returns (0, 0) if no valid point can be determined.

translate(offset_x, offset_y)[source]

Translates all operations in the opsset by a specified (x, y) offset.

Applies the translation relative to the current center of gravity of the operations. Modifies the operations in-place by adding the offset to each point’s coordinates. Non-point operations (like set pen type) are preserved without modification.

Parameters:
  • offset_x (float) – The x-axis translation amount

  • offset_y (float) – The y-axis translation amount

scale(scale_x, scale_y=None)[source]

Scales the operations in the opsset relative to its center of gravity.

Applies uniform or non-uniform scaling to all point-based operations. If only scale_x is provided, the scaling is uniform in both x and y directions. The scaling is performed relative to the current center of gravity of the operations.

Parameters:
  • scale_x (float) – The scaling factor for the x-axis.

  • scale_y (float, optional) – The scaling factor for the y-axis. Defaults to the same value as scale_x for uniform scaling.

rotate(angle, center_of_rotation=None)[source]

Rotates the operations in the opsset by a specified angle around its center of gravity.

Applies a rotation transformation to all point-based operations relative to the current center of gravity. The rotation is performed in degrees and uses a standard 2D rotation matrix.

Parameters:
  • angle (float) – The rotation angle in degrees. Positive values rotate counterclockwise.

  • center_of_rotation (tuple[float, float] | None)

render(ctx, initial_mode='stroke')[source]

Renders the operation set on a Cairo graphics context.

This method iterates through a series of drawing operations and applies them to the provided Cairo context. It supports various operation types including move, line, curve, and quadratic curve drawing, as well as path closing and pen/style configuration.

Parameters:
  • ctx (cairo.Context) – The Cairo graphics context to render operations on.

  • initial_mode (str, optional) – The initial rendering mode, either “stroke” or “fill”. Defaults to “stroke”.

Raises:

NotImplementedError – If an unsupported operation type is encountered.

quick_view(width=800, height=600, background_color=(1, 1, 1), block=True)[source]

Renders the OpsSet to a temporary SVG file and opens it in a web browser for quick viewing.

This is a utility for debugging. It automatically creates a viewport that fits the content.

Parameters:
  • width (int) – The width of the output SVG image.

  • height (int) – The height of the output SVG image.

  • background_color (Tuple[float, float, float]) – The RGB background color. Defaults to white.

  • block (bool) – If True, the script will pause execution until Enter is pressed in the console.

handanim.core.animation

class handanim.core.animation.AnimationEventType(*values)[source]

Bases: Enum

An enumeration representing different types of animation events.

CREATION = 'creation'
MUTATION = 'mutation'
DELETION = 'deletion'
COMPOSITE = 'composite'
class handanim.core.animation.AnimationEvent(type=AnimationEventType.CREATION, start_time=0.0, duration=0.0, easing_fun=None, data=None)[source]

Bases: object

Represents an animation event occurring on a scene with configurable properties.

Parameters:
  • type (AnimationEventType) – The type of animation to be performed.

  • start_time (float, optional) – The starting time point of the animation in seconds. Defaults to 0.

  • duration (float, optional) – The duration of the animation in seconds. Defaults to 0.

  • easing_fun (callable, optional) – An optional easing function to modify animation progression. Defaults to None.

  • data (dict, optional) – Additional configuration data specific to the animation type. Defaults to an empty dict.

data: dict
keep_final_state: bool
apply(opsset, raw_progress)[source]

Public entry point called by Scene. Applies easing (if any) then delegates to _apply(). Do not override in subclasses — implement _apply() instead.

Parameters:
Return type:

OpsSet

subdivide(n_division)[source]

Returns subdivision of an event into n_division segments

Parameters:

n_division (int)

class handanim.core.animation.CompositeAnimationEvent(events, easing_fun=None, data=None)[source]

Bases: AnimationEvent

Represents a composite animation event that combines multiple animation events.

Parameters:
  • events (List[AnimationEvent]) – A list of animation events to be combined.

  • easing_fun (callable, optional) – An optional easing function to apply to the composite event.

  • data (dict, optional) – Additional configuration data for the composite animation event.

events

The list of animation events in the composite event.

Type:

List[AnimationEvent]

handanim.core.styles

class handanim.core.styles.StrokePressure(*values)[source]

Bases: Enum

A class that defines the pressure of the strokes

CONSTANT = 'constant'
PROPORTIONAL = 'proportional'
INVERSE = 'inverse'
class handanim.core.styles.StrokeStyle(**kwargs)[source]

Bases: object

A class that defines the styling configurations for the strokes of the boundaries of the primitives.

Allows customization of stroke appearance including color, width, opacity, and pressure characteristics. Defaults to a black, 1-pixel wide constant pressure stroke with full opacity.

options

Raw keyword arguments passed during initialization

Type:

dict

color

RGB color tuple, defaults to black (0, 0, 0)

Type:

tuple

width

Stroke width in pixels, defaults to 1

Type:

int/float

opacity

Stroke opacity from 0-1, defaults to 1

Type:

float

stroke_pressure

Pressure mode for stroke rendering, defaults to StrokePressure.CONSTANT

Type:

StrokePressure

class handanim.core.styles.FillStyle(**kwargs)[source]

Bases: object

A class that defines the styling configurations for the fills of the primitives.

Allows customization of fill appearance including color, opacity, fill pattern, hachure settings, and fill weight. Defaults to a black fill with full opacity and hachure pattern.

options

Raw keyword arguments passed during initialization

Type:

dict

color

RGB color tuple, defaults to black (0, 0, 0)

Type:

tuple

opacity

Fill opacity from 0-1, defaults to 1

Type:

float

fill_pattern

Pattern for filling, defaults to “hachure”

Type:

str

hachure_angle

Angle of hachure lines in degrees, defaults to 45

Type:

int

hachure_gap

Gap between hachure lines, defaults to 4

Type:

int

hachure_line_width

Width of hachure lines, defaults to 1

Type:

int

zigzag_offset

Offset for zigzag pattern, defaults to -1

Type:

int

fill_weight

Weight/thickness of fill, defaults to 2

Type:

int

class handanim.core.styles.SketchStyle(**kwargs)[source]

Bases: object

A class that defines the styling configurations for sketchy, hand-drawn style renderings.

bowing

Amount of bowing/waviness in lines, defaults to 1

Type:

int

max_random_offset

Maximum random offset for sketch lines, defaults to 2

Type:

int

roughness

Roughness of sketch lines, defaults to 1

Type:

int

curve_tightness

Tightness of curves, defaults to 0

Type:

int

curve_fitting

Curve fitting parameter, defaults to 0.95

Type:

float

curve_step_count

Number of steps for curve rendering, defaults to 9

Type:

int

disable_multi_stroke

Flag to disable multi-stroke rendering, defaults to False

Type:

bool

disable_font_mixture

Flag to disable font mixture, defaults to True

Type:

bool

handanim.core.viewport

class handanim.core.viewport.Viewport(world_xrange, world_yrange, screen_width=1920, screen_height=1080, margin=50)[source]

Bases: object

A viewport that transforms mathematical coordinates to pixel coordinates for rendering.

Handles scaling and translation between world coordinates and screen pixels, ensuring proper mapping and centering within a specified margin.

Parameters:
world_xrange

The x-coordinate range in world space.

Type:

Tuple[float, float]

world_yrange

The y-coordinate range in world space.

Type:

Tuple[float, float]

screen_width

The width of the rendering surface in pixels.

Type:

int

screen_height

The height of the rendering surface in pixels.

Type:

int

margin

The margin around the rendered content.

Type:

int

apply_to_context(ctx)[source]

Apply viewport scaling and translation to a cairo context.

Transforms world coordinates to screen pixels by: 1. Calculating scaling factors to fit content within screen margins 2. Translating the context to account for margins 3. Scaling the context to preserve aspect ratio and fit content

Parameters:

ctx (cairo.Context) – The cairo drawing context to transform

handanim.core.cache

class handanim.core.cache.DrawableCache(background_color=(1, 1, 1))[source]

Bases: object

A cache management class for storing and retrieving drawable objects and their corresponding operation sets. It caches the state of a drawable object after a choice of particular event, or at initialization.

Provides methods to: - Store and retrieve drawable objects and their computed operation sets, at different key frames - Check for existing drawable operation sets - Calculate bounding boxes for multiple drawables

Parameters:

background_color (tuple[float, float, float])

cache

A mapping of drawable IDs to their computed operation sets

Type:

dict[str, OpsSet]

drawables

A mapping of drawable IDs to their drawable objects

Type:

dict[str, Drawable]

get_cachekey(drawable_id, event_id=None)[source]
Parameters:
  • drawable_id (str)

  • event_id (str | None)

set_drawable_opsset(drawable, opsset=None)[source]
Parameters:
set_drawable_event_opsset(drawable_id, event_id, opsset)[source]
Parameters:
get_drawable(drawable_id)[source]
Parameters:

drawable_id (str)

Return type:

Drawable

exists_in_cache(drawable_id, event_id=None)[source]
Parameters:
  • drawable_id (str)

  • event_id (str | None)

Return type:

bool

get_drawable_opsset(drawable_id, event_id=None)[source]
Parameters:
  • drawable_id (str)

  • event_id (str | None)

Return type:

OpsSet

calculate_bounding_box(drawables)[source]

Calculates the bounding box for a list of drawables stored in the cache

Parameters:

drawables (list[Drawable])

class handanim.core.cache.GroupFrameCache[source]

Bases: object

Per-frame cache for group animation transforms. Must be reset at the start of each frame via reset(). Stores two slots per (group, event):

  • pre-transform: the assembled group OpsSet before event.apply()

  • transformed: the result of event.apply(group_opsset, progress)

get_pretransform(group_id, event_id)[source]
Parameters:
  • group_id (str)

  • event_id (str)

Return type:

OpsSet | None

set_pretransform(group_id, event_id, opsset)[source]
Parameters:
get_transformed(group_id, event_id, progress)[source]
Parameters:
Return type:

OpsSet | None

set_transformed(group_id, event_id, progress, opsset)[source]
Parameters:
reset()[source]

handanim.core.tikz_renderer

Convert OpsSet drawing operations to TikZ commands for native LaTeX output.

This module provides a renderer that translates the internal drawing operation stream (OpsSet) into TikZ path commands. The resulting code can be embedded directly in a beamer slide or standalone LaTeX document, producing truly native vector output instead of rasterised PDF images.

Coordinate convention

handanim world space is Y-down (origin at top-left), while TikZ is Y-up. The renderer flips Y and scales world units to centimetres so the picture fits a configurable target width (default 12 cm, matching \textwidth on a 16:9 beamer slide with default margins).

class handanim.core.tikz_renderer.TikZRenderer(viewport, target_width_cm=12.0, background_color=None, precision=4)[source]

Bases: object

Converts an OpsSet into TikZ drawing commands.

Parameters:
  • viewport (Viewport) – The viewport that defines the world coordinate system.

  • target_width_cm (float) – Width of the output tikzpicture in centimetres.

  • background_color (tuple[float, float, float] | None) – Optional RGB background (0-1 range).

  • precision (int) – Decimal digits kept in coordinates and widths.

render_opsset(opsset)[source]

Convert an OpsSet to a list of TikZ drawing command strings.

Returns a list of strings, each a complete TikZ command (\draw[...] ...; or \fill[...] ...;).

Parameters:

opsset (OpsSet)

Return type:

list[str]

render_tikzpicture(opsset)[source]

Return a complete tikzpicture environment string for one frame.

Includes colour definitions, optional background rectangle, and all drawing commands.

Parameters:

opsset (OpsSet)

Return type:

str

reset_colors()[source]

Clear the colour cache between frames to keep definitions local.

handanim.core.tikz_renderer.opsset_to_tikz(opsset, viewport, target_width_cm=12.0, background_color=None)[source]

Convenience: convert a single OpsSet to a tikzpicture string.

Parameters:
Return type:

str

handanim.core.utils

handanim.core.utils.cairo_surface_to_numpy(surface)[source]

Convert a Cairo surface to a numpy array with RGBA color channel ordering.

Transforms the image surface data from Cairo’s ARGB format to a numpy array with RGBA color channels, suitable for further image processing or saving.

Parameters:

surface (cairo.ImageSurface) – The source Cairo image surface to convert

Returns:

A numpy array representing the image with shape (height, width, 4)

and dtype np.uint8, with color channels reordered from BGR to RGB

Return type:

numpy.ndarray

handanim.core.utils.get_bezier_extreme_points(p0, p1, p2, p3)[source]
Parameters:
Return type:

tuple[float, float, float, float]

handanim.core.utils.get_bezier_points_from_quadcurve(p0, q1, q2)[source]

Convert a quadratic Bezier curve to a cubic Bezier curve representation.

Transforms control points from a quadratic curve (with two control points) to an equivalent cubic curve (with three control points) using linear interpolation.

Parameters:
  • p0 (Tuple[float, float]) – Starting point of the quadratic curve

  • q1 (Tuple[float, float]) – Control point of the quadratic curve

  • q2 (Tuple[float, float]) – Ending point of the quadratic curve

Returns:

Intermediate control points for the cubic Bezier curve

Return type:

Tuple[list, list, list]

handanim.core.utils.get_line_slope_angle(p0, p1)[source]

Calculate the angle of the line segment defined by two points.

Parameters:
  • p0 (Tuple[float, float]) – The first point (x0, y0)

  • p1 (Tuple[float, float]) – The second point (x1, y1)

Returns:

The angle in radians of the line segment from p0 to p1

Return type:

float

handanim.core.utils.slice_bezier(p0, p1, p2, p3, t)[source]

Slice a Bezier curve at a given parameter t.

Computes intermediate points along a cubic Bezier curve at a specified interpolation point.

Parameters:
  • p0 (array-like) – Starting point of the Bezier curve

  • p1 (array-like) – First control point

  • p2 (array-like) – Second control point

  • p3 (array-like) – Ending point of the Bezier curve

  • t (float) – Interpolation parameter between 0 and 1

Returns:

A list of three points representing the sliced Bezier curve segment

Return type:

list

handanim.core.utils.solve_quad_eqn(a, b, c, ignore_error=False)[source]
Parameters:
Return type:

tuple[float | None, float | None]