Simulation

DeskBot provides a headless simulation driver that composes face rendering, body pose, and a servo overlay without requiring physical hardware.

Use:

make simulate

or the installed deskbot-simulate command.

Simulation is intended for development, visual checks, and CI-friendly experimentation.

robot.simulation

Simulation mode.

The :class:SimulationDriver runs the same :class:FaceAnimator and :class:BodyLanguageEngine used in hardware mode, but renders the face to a virtual display and draws a stick-figure visualisation of the four servos on top.

The virtual display is a :class:MockDisplay (in-memory RGB888 buffer). The servo overlay is drawn directly into the face framebuffer by :class:ServoOverlay so the simulation output is a single image per frame.

Driver

robot.simulation.driver

Simulation driver: face + body + servo overlay, no hardware required.

The driver wires the same :class:FaceAnimator and :class:BodyLanguageEngine used in production into a 30 FPS loop that composites the face with a stick-figure servo visualisation and displays the result.

DEFAULT_CALIBRATION = {SERVO_HEAD_PAN: ServoCalibration(SERVO_HEAD_PAN, 30.0, 150.0, 90.0), SERVO_HEAD_TILT: ServoCalibration(SERVO_HEAD_TILT, 45.0, 135.0, 90.0), SERVO_LEFT_ARM: ServoCalibration(SERVO_LEFT_ARM, 20.0, 160.0, 90.0), SERVO_RIGHT_ARM: ServoCalibration(SERVO_RIGHT_ARM, 20.0, 160.0, 90.0)} module-attribute

__all__ = ['SimulationDriver'] module-attribute

_log = get_logger('simulation.driver') module-attribute

BodyLanguageEngine dataclass

Drive the four servos with high-level body-language requests.

Source code in src/robot/body_language/engine.py
@dataclass(slots=True)
class BodyLanguageEngine:
    """Drive the four servos with high-level body-language requests."""

    servo_controller: ServoController
    clock: Clock
    calibration: dict[str, ServoCalibration] = field(
        default_factory=lambda: dict(DEFAULT_CALIBRATION)
    )

    _current: Pose = field(default_factory=Pose, init=False)
    _busy: bool = field(default=False, init=False)

    def set_calibration(self, calibration: dict[str, ServoCalibration]) -> None:
        self.calibration = calibration

    def snapshot(self) -> Pose:
        """Current pose - used by the simulation overlay."""
        return self._current

    def apply_hint(self, hint: object) -> Pose:
        """Translate a :class:`BodyLanguageHint` into a Pose (no servo moves)."""
        pose = hint_to_pose(hint)
        self._current = pose
        return pose

    async def perform(self, request: BodyRequest) -> None:
        """Play a request on the servos."""
        if self._busy:
            # Another request is already in flight - log the dropped request
            # so it's visible rather than silently lost.
            _log.warning(
                "body_language.request_dropped", request=getattr(request, "name", "unknown")
            )
            return
        self._busy = True
        try:
            for frame in request.frames():
                await self._play_frame(frame)
        finally:
            self._busy = False

    def perform_sync(self, request: BodyRequest) -> None:
        """Synchronous version (for tests and the simulation CLI)."""
        for frame in request.frames():
            self._play_frame_sync(frame)

    async def play_frames(self, frames: Iterable[ServoFrame]) -> None:
        async for _ in self._aiter_frames(frames):
            pass

    async def _aiter_frames(self, frames: Iterable[ServoFrame]) -> AsyncIterator[None]:
        for frame in frames:
            await self._play_frame(frame)
            yield

    async def _play_frame(self, frame: ServoFrame) -> None:
        if not frame.targets:
            await self.clock.sleep(frame.duration_s)
            return
        # Compute the per-servo interpolation start positions
        start_targets = {name: self._current.get(name, 90.0) for name in frame.targets}
        steps = max(1, int(frame.duration_s * 30))
        step_s = frame.duration_s / steps
        for step in range(1, steps + 1):
            t = step / steps
            eased = t * t * (3.0 - 2.0 * t)
            targets: dict[str, float] = {}
            for name, target in frame.targets.items():
                start = start_targets[name]
                targets[name] = self._calibrate(name, start + (target - start) * eased)
            # Apply every servo in this slice
            await self._apply_targets(targets)
            self._current = Pose(targets={**self._current.targets, **targets})
            await self.clock.sleep(step_s)

    def _play_frame_sync(self, frame: ServoFrame) -> None:
        if not frame.targets:
            return
        # Apply each servo's calibrated target directly (sync mode jumps
        # to the target without interpolation).
        new_targets = dict(self._current.targets)
        for name, target in frame.targets.items():
            calibrated = self._calibrate(name, target)
            new_targets[name] = calibrated
        self._current = Pose(targets=new_targets)

    async def _apply_targets(self, targets: dict[str, float]) -> None:
        for name, angle in targets.items():
            servo = self._get_servo(name)
            if servo is not None:
                with contextlib.suppress(Exception):
                    await servo.move_to(angle, duration_s=0.0)

    def _apply_targets_sync(self, targets: dict[str, float]) -> None:
        for name, angle in targets.items():
            servo = self._get_servo(name)
            if servo is not None:
                # The sync method is used by the simulator CLI and the tests.
                # It updates the snapshot but does not call the async
                # ``servo.move_to`` (that would require a running loop).
                self._current = Pose(
                    targets={**self._current.targets, name: self._calibrate(name, angle)}
                )

    def _get_servo(self, name: str) -> Servo | None:
        try:
            return self.servo_controller.get(name)
        except Exception:
            return None

    def _calibrate(self, name: str, angle: float) -> float:
        cal = self.calibration.get(name)
        if cal is None:
            return max(0.0, min(180.0, angle))
        return cal.clamp(angle)

calibration = field(default_factory=lambda: dict(DEFAULT_CALIBRATION)) class-attribute instance-attribute

clock instance-attribute

servo_controller instance-attribute

__init__(servo_controller, clock, calibration=(lambda: dict(DEFAULT_CALIBRATION))())

apply_hint(hint)

Translate a :class:BodyLanguageHint into a Pose (no servo moves).

Source code in src/robot/body_language/engine.py
def apply_hint(self, hint: object) -> Pose:
    """Translate a :class:`BodyLanguageHint` into a Pose (no servo moves)."""
    pose = hint_to_pose(hint)
    self._current = pose
    return pose

perform(request) async

Play a request on the servos.

Source code in src/robot/body_language/engine.py
async def perform(self, request: BodyRequest) -> None:
    """Play a request on the servos."""
    if self._busy:
        # Another request is already in flight - log the dropped request
        # so it's visible rather than silently lost.
        _log.warning(
            "body_language.request_dropped", request=getattr(request, "name", "unknown")
        )
        return
    self._busy = True
    try:
        for frame in request.frames():
            await self._play_frame(frame)
    finally:
        self._busy = False

perform_sync(request)

Synchronous version (for tests and the simulation CLI).

Source code in src/robot/body_language/engine.py
def perform_sync(self, request: BodyRequest) -> None:
    """Synchronous version (for tests and the simulation CLI)."""
    for frame in request.frames():
        self._play_frame_sync(frame)

play_frames(frames) async

Source code in src/robot/body_language/engine.py
async def play_frames(self, frames: Iterable[ServoFrame]) -> None:
    async for _ in self._aiter_frames(frames):
        pass

set_calibration(calibration)

Source code in src/robot/body_language/engine.py
def set_calibration(self, calibration: dict[str, ServoCalibration]) -> None:
    self.calibration = calibration

snapshot()

Current pose - used by the simulation overlay.

Source code in src/robot/body_language/engine.py
def snapshot(self) -> Pose:
    """Current pose - used by the simulation overlay."""
    return self._current

Clock

Bases: Protocol

Minimal time abstraction.

Source code in src/robot/utils/clock.py
class Clock(Protocol):
    """Minimal time abstraction."""

    def now(self) -> datetime:
        """Return the current wall-clock time (UTC)."""

    def monotonic(self) -> float:
        """Return a strictly monotonic time in seconds."""

    async def sleep(self, seconds: float) -> None:
        """Sleep for the given number of seconds."""

monotonic()

Return a strictly monotonic time in seconds.

Source code in src/robot/utils/clock.py
def monotonic(self) -> float:
    """Return a strictly monotonic time in seconds."""

now()

Return the current wall-clock time (UTC).

Source code in src/robot/utils/clock.py
def now(self) -> datetime:
    """Return the current wall-clock time (UTC)."""

sleep(seconds) async

Sleep for the given number of seconds.

Source code in src/robot/utils/clock.py
async def sleep(self, seconds: float) -> None:
    """Sleep for the given number of seconds."""

Display

Bases: Protocol

A single display the eye engine can render to.

Source code in src/robot/interfaces/display.py
@runtime_checkable
class Display(Protocol):
    """A single display the eye engine can render to."""

    @property
    def width(self) -> int:
        """Width of the framebuffer in pixels."""

    @property
    def height(self) -> int:
        """Height of the framebuffer in pixels."""

    async def show(self, frame: EyeFrame) -> None:
        """Push a frame to the panel."""

    async def fill(self, color: tuple[int, int, int]) -> None:
        """Fill the entire panel with a single RGB color."""

    async def clear(self) -> None:
        """Reset the panel to black."""

    async def close(self) -> None:
        """Release hardware resources."""

height property

Height of the framebuffer in pixels.

width property

Width of the framebuffer in pixels.

clear() async

Reset the panel to black.

Source code in src/robot/interfaces/display.py
async def clear(self) -> None:
    """Reset the panel to black."""

close() async

Release hardware resources.

Source code in src/robot/interfaces/display.py
async def close(self) -> None:
    """Release hardware resources."""

fill(color) async

Fill the entire panel with a single RGB color.

Source code in src/robot/interfaces/display.py
async def fill(self, color: tuple[int, int, int]) -> None:
    """Fill the entire panel with a single RGB color."""

show(frame) async

Push a frame to the panel.

Source code in src/robot/interfaces/display.py
async def show(self, frame: EyeFrame) -> None:
    """Push a frame to the panel."""

EmotionEngine

Produces :class:FaceModel + :class:BodyLanguageHint from an emotion.

Source code in src/robot/face/emotions.py
class EmotionEngine:
    """Produces :class:`FaceModel` + :class:`BodyLanguageHint` from an emotion."""

    def __init__(
        self, palette: FacePalette | None = None, width: int = 240, height: int = 240
    ) -> None:
        self._palette = palette or FacePalette()
        self._width = width
        self._height = height

    def set_dimensions(self, width: int, height: int) -> None:
        self._width = width
        self._height = height

    def available(self) -> list[str]:
        return list(EMOTION_DEFS.keys())

    def get(self, name: str) -> _EmotionDef:
        try:
            return EMOTION_DEFS[name]
        except KeyError as exc:
            raise KeyError(
                f"unknown emotion {name!r}; available: {sorted(EMOTION_DEFS.keys())}"
            ) from exc

    def build(self, name: str) -> FaceModel:
        """Build the :class:`FaceModel` for ``name`` with default geometry."""
        d = self.get(name)
        left_eye, right_eye = d.eyes
        left_brow, right_brow = d.eyebrows
        return FaceModel(
            width=self._width,
            height=self._height,
            left_eye=left_eye,
            right_eye=right_eye,
            eyelids=d.eyelids,
            left_eyebrow=left_brow,
            right_eyebrow=right_brow,
            mouth=d.mouth,
            cheeks=d.cheeks,
            overlay=d.overlay,
            palette=self._palette,
            body_hint=d.body_hint,
        )

    def register(self, name: str, definition: _EmotionDef) -> None:
        """Register a new emotion or override an existing one."""
        EMOTION_DEFS[name] = definition

__init__(palette=None, width=240, height=240)

Source code in src/robot/face/emotions.py
def __init__(
    self, palette: FacePalette | None = None, width: int = 240, height: int = 240
) -> None:
    self._palette = palette or FacePalette()
    self._width = width
    self._height = height

available()

Source code in src/robot/face/emotions.py
def available(self) -> list[str]:
    return list(EMOTION_DEFS.keys())

build(name)

Build the :class:FaceModel for name with default geometry.

Source code in src/robot/face/emotions.py
def build(self, name: str) -> FaceModel:
    """Build the :class:`FaceModel` for ``name`` with default geometry."""
    d = self.get(name)
    left_eye, right_eye = d.eyes
    left_brow, right_brow = d.eyebrows
    return FaceModel(
        width=self._width,
        height=self._height,
        left_eye=left_eye,
        right_eye=right_eye,
        eyelids=d.eyelids,
        left_eyebrow=left_brow,
        right_eyebrow=right_brow,
        mouth=d.mouth,
        cheeks=d.cheeks,
        overlay=d.overlay,
        palette=self._palette,
        body_hint=d.body_hint,
    )

get(name)

Source code in src/robot/face/emotions.py
def get(self, name: str) -> _EmotionDef:
    try:
        return EMOTION_DEFS[name]
    except KeyError as exc:
        raise KeyError(
            f"unknown emotion {name!r}; available: {sorted(EMOTION_DEFS.keys())}"
        ) from exc

register(name, definition)

Register a new emotion or override an existing one.

Source code in src/robot/face/emotions.py
def register(self, name: str, definition: _EmotionDef) -> None:
    """Register a new emotion or override an existing one."""
    EMOTION_DEFS[name] = definition

set_dimensions(width, height)

Source code in src/robot/face/emotions.py
def set_dimensions(self, width: int, height: int) -> None:
    self._width = width
    self._height = height

EyeFrame dataclass

An RGB888 image to push to the display.

Attributes

width, height: Pixel dimensions. pixels: Row-major RGB888 buffer of length width * height * 3.

Source code in src/robot/interfaces/display.py
@dataclass(slots=True, frozen=True)
class EyeFrame:
    """An RGB888 image to push to the display.

    Attributes
    ----------
    width, height:
        Pixel dimensions.
    pixels:
        Row-major RGB888 buffer of length ``width * height * 3``.
    """

    width: int
    height: int
    pixels: bytes

height instance-attribute

pixels instance-attribute

width instance-attribute

__init__(width, height, pixels)

FaceAnimator dataclass

Drive a single circular face display at 30 FPS.

Source code in src/robot/face/animator.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
@dataclass(slots=True)
class FaceAnimator:
    """Drive a single circular face display at 30 FPS."""

    DEFAULT_FPS: ClassVar[int] = 30

    renderer: FaceRenderer
    display: Display
    clock: Clock
    emotions: EmotionEngine
    theme: Theme
    fps: int = DEFAULT_FPS
    bus: InMemoryEventBus | None = None
    width: int = 240
    height: int = 240

    _current: FaceModel = field(init=False)
    _target: FaceModel = field(init=False)
    _eye: EyeAnimator = field(init=False)
    _stopped: bool = field(default=True, init=False)
    _frame_count: int = field(default=0, init=False)
    _anim_time: float = field(default=0.0, init=False)
    _timeline: Timeline | None = field(default=None, init=False)
    _timeline_t: float = field(default=0.0, init=False)
    _timeline_total: float = field(default=0.0, init=False)
    _speaking_animation: SpeakingAnimation | None = field(default=None, init=False)
    _thinking_animation: ThinkingDotsAnimation | None = field(default=None, init=False)
    _wake_animation: WakeAnimation | None = field(default=None, init=False)
    _frame_profiler: FrameProfiler | None = field(default=None, init=False, repr=False)

    def __post_init__(self) -> None:
        if self.fps <= 0:
            raise ValueError("fps must be > 0")
        if self.width <= 0 or self.height <= 0:
            raise ValueError("width and height must be > 0")
        self._eye = EyeAnimator(
            side=EyeSide.LEFT,
            width=self.width,
            height=self.height,
            fps=self.fps,
        )
        self._current = self.emotions.build("neutral")
        self._target = self._current
        if self.bus is not None:
            from robot.events.events import (
                BlinkRequested,
                EmotionChanged,
                LookRequested,
            )

            self.bus.subscribe(EmotionChanged, self._on_emotion)
            self.bus.subscribe(BlinkRequested, self._on_blink)
            self.bus.subscribe(LookRequested, self._on_look)

    # ------------------------------------------------------------------ properties
    @property
    def current(self) -> FaceModel:
        return self._current

    @property
    def frame_count(self) -> int:
        return self._frame_count

    @property
    def is_running(self) -> bool:
        return not self._stopped

    # ------------------------------------------------------------------ public commands
    def set_emotion(self, name: str, intensity: float = 1.0) -> None:
        """Animate to the given emotion over ~0.3s.

        Calling this method clears any running speaking and thinking
        animations (they are interruptible).  The wake animation is
        *not* cleared -- it plays to completion.
        """
        # Clear interruptible animations on emotion change.
        self._speaking_animation = None
        self._thinking_animation = None
        target = self.emotions.build(name)
        # Apply intensity: scale the change in openness, mouth, etc.
        self._timeline = self._build_emotion_timeline(self._current, target, duration_s=0.3)
        self._target = target

    def blink(self) -> None:
        self._eye.blink()

    def double_blink(self) -> None:
        self._eye.double_blink()

    def wink(self) -> None:
        self._eye.wink()

    def look(self, x: float, y: float, duration_s: float = 0.25) -> None:
        self._eye.look(x, y, duration_s)

    def look_left(self, duration_s: float = 0.25) -> None:
        self._eye.look_left(duration_s)

    def look_right(self, duration_s: float = 0.25) -> None:
        self._eye.look_right(duration_s)

    def look_up(self, duration_s: float = 0.25) -> None:
        self._eye.look_up(duration_s)

    def look_down(self, duration_s: float = 0.25) -> None:
        self._eye.look_down(duration_s)

    def look_center(self, duration_s: float = 0.25) -> None:
        self._eye.look_center(duration_s)

    def drift(self, amplitude: float = 0.10, speed: float = 0.6) -> None:
        self._eye.drift(amplitude=amplitude, speed=speed)

    def bounce(self) -> None:
        """Run a one-shot bounce animation (squash & stretch)."""
        tl = self._build_bounce_timeline()
        self._timeline = tl

    def smile_grow(self) -> None:
        """Animate the mouth from NEUTRAL to SMILE over 0.4s."""
        target = self._current.with_mouth(Mouth(shape=MouthShape.SMILE, openness=0.4, width=0.7))
        self._timeline = self._build_mouth_timeline(self._current, target, 0.4)

    def mouth_open(self, duration_s: float = 0.3) -> None:
        target = self._current.with_mouth(Mouth(shape=MouthShape.OPEN, openness=0.6, width=0.6))
        self._start_timeline(self._build_mouth_timeline(self._current, target, duration_s))

    def eyebrow_raise(self, amount: float = 0.6) -> None:
        target = self._current.with_eyebrows(
            left=Eyebrow(shape=EyebrowShape.RAISED, raise_amount=amount),
            right=Eyebrow(shape=EyebrowShape.RAISED, raise_amount=amount),
        )
        self._timeline = self._build_eyebrow_timeline(self._current, target, 0.3)

    # ------------------------------------------------------------------ animation slots
    def set_speaking_animation(self, animation: SpeakingAnimation | None) -> None:
        """Set (or clear) the speaking animation that drives mouth shapes."""
        self._speaking_animation = animation

    def set_thinking_animation(self, animation: ThinkingDotsAnimation | None) -> None:
        """Set (or clear) the thinking animation that drives gaze shifts."""
        self._thinking_animation = animation

    def set_wake_animation(self, animation: WakeAnimation | None) -> None:
        """Set (or clear) the wake animation (highest priority override)."""
        self._wake_animation = animation

    def reset(self) -> None:
        self._current = self.emotions.build("neutral")
        self._target = self._current
        self._timeline = None
        self._speaking_animation = None
        self._thinking_animation = None
        self._wake_animation = None
        self._eye.reset()

    # ------------------------------------------------------------------ bus
    async def _on_emotion(self, event: object) -> None:
        name = getattr(event, "current", None)
        if name is None:
            return
        # The event's ``current`` can be either an ``EmotionName`` enum or
        # a plain string; normalise to a string before looking it up.
        if hasattr(name, "value"):
            name = name.value
        elif not isinstance(name, str):
            return
        self.set_emotion(name)

    async def _on_blink(self, event: object) -> None:
        self.blink()

    async def _on_look(self, event: object) -> None:
        self.look(
            float(getattr(event, "x", 0.0)),
            float(getattr(event, "y", 0.0)),
            duration_s=float(getattr(event, "duration_s", 0.25)),
        )

    # ------------------------------------------------------------------ frame loop
    def step(self, drift: bool = True) -> EyeFrame:
        """Advance one frame and push to the display.

        The rendering pipeline applies overrides in priority order:

        1. Eye drift + blink state (from :class:`EyeAnimator`).
        2. Thinking animation gaze override.
        3. Timeline-based emotion interpolation.
        4. Speaking animation mouth override.
        5. Wake animation full override (highest priority).
        """
        dt = 1.0 / self.fps
        self._frame_count += 1

        if drift:
            self._eye.drift(amplitude=0.10, speed=0.6)
        # Eye state: pull current gaze from the eye animator
        eye_state = self._eye.step()
        # Translate the eye's (gaze, openness) into left/right Eye components
        new_eyes = self._eyes_from_eye_state(eye_state)

        # Thinking animation: override gaze when active.
        if self._thinking_animation is not None:
            gaze = self._thinking_animation.step(dt)
            new_eyes = (
                Eye(
                    gaze=gaze,
                    openness=new_eyes[0].openness,
                    pupil_dilation=new_eyes[0].pupil_dilation,
                    highlight=new_eyes[0].highlight,
                ),
                Eye(
                    gaze=gaze,
                    openness=new_eyes[1].openness,
                    pupil_dilation=new_eyes[1].pupil_dilation,
                    highlight=new_eyes[1].highlight,
                ),
            )

        # Apply timeline (smile, eyebrows, bounce, …) if any
        if self._timeline is not None:
            self._timeline_t += dt
            progress = min(1.0, self._timeline_t / max(0.001, self._timeline_total))
            # Invoke the on_update callbacks directly. Each builder
            # registered a single tween whose callback writes to
            # ``self._current`` (interpolation, bounce, …).
            for animation in self._timeline._items:
                if hasattr(animation, "on_update"):
                    animation.on_update(progress)
            if progress >= 1.0:
                self._timeline = None
                self._timeline_t = 0.0
        # Merge eye state + current body
        merged = self._current.with_eyes(left_eye=new_eyes[0], right_eye=new_eyes[1])
        # Update the current model so a.current reflects the rendered state.
        self._current = merged

        # Speaking animation: override mouth when active.
        if self._speaking_animation is not None:
            viseme = self._speaking_animation.step(dt)
            mouth_shape = MouthShape.OPEN if viseme.openness > 0.1 else MouthShape.NEUTRAL
            self._current = self._current.with_mouth(
                Mouth(shape=mouth_shape, openness=viseme.openness, width=viseme.width)
            )
            if not self._speaking_animation.has_frames:
                self._speaking_animation = None

        # Wake animation: full override (highest priority).
        if self._wake_animation is not None:
            wake_frame = self._wake_animation.step(dt)
            self._current = self._apply_wake_frame(self._current, wake_frame)
            if self._wake_animation.done:
                self._wake_animation = None

        # Apply theme
        themed = self.theme.apply(self._current)
        return self.renderer.render(themed)

    async def _step_async(self, drift: bool = True) -> EyeFrame:
        frame = self.step(drift=drift)
        await self._push(frame)
        return frame

    async def _push(self, frame: EyeFrame) -> None:
        try:
            await self.display.show(frame)
        except Exception:
            _log.exception("face.animator.display_failed")
        if self.bus is not None:
            from robot.events.events import DisplayUpdated

            with contextlib.suppress(Exception):
                await self.bus.publish(DisplayUpdated(display="face"))

    async def run_forever(self) -> None:
        self._stopped = False
        frame_interval = 1.0 / self.fps
        try:
            while not self._stopped:
                start = time.monotonic()
                await self._step_async(drift=True)
                end = time.monotonic()
                if self._frame_profiler is not None and getattr(
                    self._frame_profiler, "enabled", False
                ):
                    self._frame_profiler.record_frame(start, end)
                await self.clock.sleep(frame_interval)
        finally:
            self._stopped = True

    def stop(self) -> None:
        self._stopped = True

    # ------------------------------------------------------------------ timeline helpers
    def _start_timeline(self, timeline: Timeline) -> None:
        self._timeline = timeline
        self._timeline_t = 0.0
        # _timeline_total is set by the builder (so the builder can also do its own work)

    def _build_emotion_timeline(
        self, start: FaceModel, end: FaceModel, duration_s: float
    ) -> Timeline:
        """Build a timeline that interpolates between two FaceModels.

        We don't yet have a generic FaceModel interpolator, so we use a
        sequence of tween callbacks to lerp scalar fields. The
        renderer is what makes the result look smooth.
        """
        tl = Timeline()
        # Tween the mouth shape change discretely (mid-way)
        tl.tween(
            from_value=0.0,
            to_value=1.0,
            duration_s=duration_s,
            on_update=lambda t: self._set_interp(start, end, t),
        )
        self._timeline_total = duration_s
        return tl

    def _build_mouth_timeline(
        self, start: FaceModel, end: FaceModel, duration_s: float
    ) -> Timeline:
        tl = Timeline()
        tl.tween(
            from_value=0.0,
            to_value=1.0,
            duration_s=duration_s,
            on_update=lambda t: self._set_interp(start, end, t),
        )
        self._timeline_total = duration_s
        return tl

    def _build_eyebrow_timeline(
        self, start: FaceModel, end: FaceModel, duration_s: float
    ) -> Timeline:
        tl = Timeline()
        tl.tween(
            from_value=0.0,
            to_value=1.0,
            duration_s=duration_s,
            on_update=lambda t: self._set_interp(start, end, t),
        )
        self._timeline_total = duration_s
        return tl

    def _build_bounce_timeline(self) -> Timeline:
        """One-shot bounce: bounce up, squash on landing, settle.

        Uses the model's ``bounce`` and ``squash`` fields and writes a
        per-frame value through a single tween.
        """
        # Build a sequence of keyframes as a list of (t, bounce, squash)
        keyframes: list[tuple[float, float, float]] = [
            (0.00, 0.0, 1.00),
            (0.10, 0.50, 0.92),  # anticipation squash
            (0.30, 0.85, 1.10),  # jump stretch
            (0.55, 0.00, 0.95),  # impact squash
            (0.75, 0.30, 1.04),  # small bounce
            (1.00, 0.0, 1.00),  # settle
        ]
        duration = 0.6

        class _Bounce:
            def __init__(self) -> None:
                pass

        # Use a simple Tween + linear interp through keyframes
        def _sample(t: float) -> tuple[float, float]:
            for i in range(len(keyframes) - 1):
                t0, b0, s0 = keyframes[i]
                t1, b1, s1 = keyframes[i + 1]
                if t0 <= t <= t1:
                    local = (t - t0) / max(1e-6, t1 - t0)
                    local = _ease_in_out(local)
                    return (b0 + (b1 - b0) * local, s0 + (s1 - s0) * local)
            return keyframes[-1][1], keyframes[-1][2]

        def _apply(t: float) -> None:
            bounce, squash = _sample(t)
            # Apply in-place: store the bounce/squash on the model.
            # We achieve this by replacing self._current with a new model
            # that has the transformed bounce/squash.
            self._current = self._current.with_transform(bounce=bounce, squash=squash)

        tl = Timeline()
        tl.tween(from_value=0.0, to_value=1.0, duration_s=duration, on_update=_apply)
        self._timeline_total = duration
        return tl

    def _apply_timeline_at(self, model: FaceModel, t: float) -> FaceModel:
        """Most timelines write to ``self._current`` directly via tween
        callbacks. This method is the fallback for any future timeline
        that wants to be queryable.
        """
        return model

    def _apply_wake_frame(self, model: FaceModel, frame: WakeFrame) -> FaceModel:
        """Apply a :class:`WakeFrame` override to the model.

        The wake animation has the highest priority and overrides
        eyes, eyelids, mouth, and eyebrows.
        """
        return (
            model.with_eyes(
                left_eye=Eye(
                    gaze=frame.gaze,
                    openness=frame.eye_openness,
                    pupil_dilation=model.left_eye.pupil_dilation,
                    highlight=model.left_eye.highlight,
                ),
                right_eye=Eye(
                    gaze=frame.gaze,
                    openness=frame.eye_openness,
                    pupil_dilation=model.right_eye.pupil_dilation,
                    highlight=model.right_eye.highlight,
                ),
            )
            .with_eyelids(Eyelids(top=frame.eyelid_top, bottom=0.0))
            .with_mouth(
                Mouth(
                    shape=frame.mouth_shape, openness=frame.mouth_openness, width=frame.mouth_width
                )
            )
            .with_eyebrows(
                left=Eyebrow(shape=frame.eyebrow_shape, raise_amount=frame.eyebrow_raise),
                right=Eyebrow(shape=frame.eyebrow_shape, raise_amount=frame.eyebrow_raise),
            )
        )

    def _set_interp(self, start: FaceModel, end: FaceModel, t: float) -> None:
        """Snap-interpolate scalar fields from start to end at progress t."""
        e = _ease_in_out(t)
        left_eye = _interp_eye(start.left_eye, end.left_eye, e)
        right_eye = _interp_eye(start.right_eye, end.right_eye, e)
        eyelids = _interp_eyelids(start.eyelids, end.eyelids, e)
        left_brow = _interp_eyebrow(start.left_eyebrow, end.left_eyebrow, e)
        right_brow = _interp_eyebrow(start.right_eyebrow, end.right_eyebrow, e)
        mouth = _interp_mouth(start.mouth, end.mouth, e)
        cheeks = _interp_cheeks(start.cheeks, end.cheeks, e)
        overlay = end.overlay if e > 0.5 else start.overlay
        body_hint = end.body_hint if e > 0.5 else start.body_hint
        self._current = FaceModel(
            width=start.width,
            height=start.height,
            left_eye=left_eye,
            right_eye=right_eye,
            eyelids=eyelids,
            left_eyebrow=left_brow,
            right_eyebrow=right_brow,
            mouth=mouth,
            cheeks=cheeks,
            overlay=overlay,
            accessory=start.accessory,
            palette=start.palette,
            bounce=start.bounce,
            squash=start.squash,
            body_hint=body_hint,
        )

    def _eyes_from_eye_state(self, state: object) -> tuple[Eye, Eye]:
        """Translate the eye render state into two :class:`Eye` components."""
        # The legacy EyeState has a ``gaze`` field; the new EyeRenderState
        # has separate ``gaze_x`` / ``gaze_y`` floats. Handle both.
        if hasattr(state, "gaze_x"):
            gaze = Gaze(float(getattr(state, "gaze_x", 0.0)), float(getattr(state, "gaze_y", 0.0)))
        else:
            g = getattr(state, "gaze", Gaze())
            gaze = Gaze(float(g.x), float(g.y))
        openness = float(getattr(state, "openness", 1.0))
        dilation = float(getattr(state, "pupil_dilation", 0.5))
        eye = Eye(gaze=gaze, openness=openness, pupil_dilation=dilation, highlight=Gaze(0.3, 0.3))
        return eye, eye

DEFAULT_FPS = 30 class-attribute

bus = None class-attribute instance-attribute

clock instance-attribute

current property

display instance-attribute

emotions instance-attribute

fps = DEFAULT_FPS class-attribute instance-attribute

frame_count property

height = 240 class-attribute instance-attribute

is_running property

renderer instance-attribute

theme instance-attribute

width = 240 class-attribute instance-attribute

__init__(renderer, display, clock, emotions, theme, fps=DEFAULT_FPS, bus=None, width=240, height=240)

__post_init__()

Source code in src/robot/face/animator.py
def __post_init__(self) -> None:
    if self.fps <= 0:
        raise ValueError("fps must be > 0")
    if self.width <= 0 or self.height <= 0:
        raise ValueError("width and height must be > 0")
    self._eye = EyeAnimator(
        side=EyeSide.LEFT,
        width=self.width,
        height=self.height,
        fps=self.fps,
    )
    self._current = self.emotions.build("neutral")
    self._target = self._current
    if self.bus is not None:
        from robot.events.events import (
            BlinkRequested,
            EmotionChanged,
            LookRequested,
        )

        self.bus.subscribe(EmotionChanged, self._on_emotion)
        self.bus.subscribe(BlinkRequested, self._on_blink)
        self.bus.subscribe(LookRequested, self._on_look)
Source code in src/robot/face/animator.py
def blink(self) -> None:
    self._eye.blink()

bounce()

Run a one-shot bounce animation (squash & stretch).

Source code in src/robot/face/animator.py
def bounce(self) -> None:
    """Run a one-shot bounce animation (squash & stretch)."""
    tl = self._build_bounce_timeline()
    self._timeline = tl
Source code in src/robot/face/animator.py
def double_blink(self) -> None:
    self._eye.double_blink()

drift(amplitude=0.1, speed=0.6)

Source code in src/robot/face/animator.py
def drift(self, amplitude: float = 0.10, speed: float = 0.6) -> None:
    self._eye.drift(amplitude=amplitude, speed=speed)

eyebrow_raise(amount=0.6)

Source code in src/robot/face/animator.py
def eyebrow_raise(self, amount: float = 0.6) -> None:
    target = self._current.with_eyebrows(
        left=Eyebrow(shape=EyebrowShape.RAISED, raise_amount=amount),
        right=Eyebrow(shape=EyebrowShape.RAISED, raise_amount=amount),
    )
    self._timeline = self._build_eyebrow_timeline(self._current, target, 0.3)

look(x, y, duration_s=0.25)

Source code in src/robot/face/animator.py
def look(self, x: float, y: float, duration_s: float = 0.25) -> None:
    self._eye.look(x, y, duration_s)

look_center(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_center(self, duration_s: float = 0.25) -> None:
    self._eye.look_center(duration_s)

look_down(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_down(self, duration_s: float = 0.25) -> None:
    self._eye.look_down(duration_s)

look_left(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_left(self, duration_s: float = 0.25) -> None:
    self._eye.look_left(duration_s)

look_right(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_right(self, duration_s: float = 0.25) -> None:
    self._eye.look_right(duration_s)

look_up(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_up(self, duration_s: float = 0.25) -> None:
    self._eye.look_up(duration_s)

mouth_open(duration_s=0.3)

Source code in src/robot/face/animator.py
def mouth_open(self, duration_s: float = 0.3) -> None:
    target = self._current.with_mouth(Mouth(shape=MouthShape.OPEN, openness=0.6, width=0.6))
    self._start_timeline(self._build_mouth_timeline(self._current, target, duration_s))

reset()

Source code in src/robot/face/animator.py
def reset(self) -> None:
    self._current = self.emotions.build("neutral")
    self._target = self._current
    self._timeline = None
    self._speaking_animation = None
    self._thinking_animation = None
    self._wake_animation = None
    self._eye.reset()

run_forever() async

Source code in src/robot/face/animator.py
async def run_forever(self) -> None:
    self._stopped = False
    frame_interval = 1.0 / self.fps
    try:
        while not self._stopped:
            start = time.monotonic()
            await self._step_async(drift=True)
            end = time.monotonic()
            if self._frame_profiler is not None and getattr(
                self._frame_profiler, "enabled", False
            ):
                self._frame_profiler.record_frame(start, end)
            await self.clock.sleep(frame_interval)
    finally:
        self._stopped = True

set_emotion(name, intensity=1.0)

Animate to the given emotion over ~0.3s.

Calling this method clears any running speaking and thinking animations (they are interruptible). The wake animation is not cleared -- it plays to completion.

Source code in src/robot/face/animator.py
def set_emotion(self, name: str, intensity: float = 1.0) -> None:
    """Animate to the given emotion over ~0.3s.

    Calling this method clears any running speaking and thinking
    animations (they are interruptible).  The wake animation is
    *not* cleared -- it plays to completion.
    """
    # Clear interruptible animations on emotion change.
    self._speaking_animation = None
    self._thinking_animation = None
    target = self.emotions.build(name)
    # Apply intensity: scale the change in openness, mouth, etc.
    self._timeline = self._build_emotion_timeline(self._current, target, duration_s=0.3)
    self._target = target

set_speaking_animation(animation)

Set (or clear) the speaking animation that drives mouth shapes.

Source code in src/robot/face/animator.py
def set_speaking_animation(self, animation: SpeakingAnimation | None) -> None:
    """Set (or clear) the speaking animation that drives mouth shapes."""
    self._speaking_animation = animation

set_thinking_animation(animation)

Set (or clear) the thinking animation that drives gaze shifts.

Source code in src/robot/face/animator.py
def set_thinking_animation(self, animation: ThinkingDotsAnimation | None) -> None:
    """Set (or clear) the thinking animation that drives gaze shifts."""
    self._thinking_animation = animation

set_wake_animation(animation)

Set (or clear) the wake animation (highest priority override).

Source code in src/robot/face/animator.py
def set_wake_animation(self, animation: WakeAnimation | None) -> None:
    """Set (or clear) the wake animation (highest priority override)."""
    self._wake_animation = animation

smile_grow()

Animate the mouth from NEUTRAL to SMILE over 0.4s.

Source code in src/robot/face/animator.py
def smile_grow(self) -> None:
    """Animate the mouth from NEUTRAL to SMILE over 0.4s."""
    target = self._current.with_mouth(Mouth(shape=MouthShape.SMILE, openness=0.4, width=0.7))
    self._timeline = self._build_mouth_timeline(self._current, target, 0.4)

step(drift=True)

Advance one frame and push to the display.

The rendering pipeline applies overrides in priority order:

  1. Eye drift + blink state (from :class:EyeAnimator).
  2. Thinking animation gaze override.
  3. Timeline-based emotion interpolation.
  4. Speaking animation mouth override.
  5. Wake animation full override (highest priority).
Source code in src/robot/face/animator.py
def step(self, drift: bool = True) -> EyeFrame:
    """Advance one frame and push to the display.

    The rendering pipeline applies overrides in priority order:

    1. Eye drift + blink state (from :class:`EyeAnimator`).
    2. Thinking animation gaze override.
    3. Timeline-based emotion interpolation.
    4. Speaking animation mouth override.
    5. Wake animation full override (highest priority).
    """
    dt = 1.0 / self.fps
    self._frame_count += 1

    if drift:
        self._eye.drift(amplitude=0.10, speed=0.6)
    # Eye state: pull current gaze from the eye animator
    eye_state = self._eye.step()
    # Translate the eye's (gaze, openness) into left/right Eye components
    new_eyes = self._eyes_from_eye_state(eye_state)

    # Thinking animation: override gaze when active.
    if self._thinking_animation is not None:
        gaze = self._thinking_animation.step(dt)
        new_eyes = (
            Eye(
                gaze=gaze,
                openness=new_eyes[0].openness,
                pupil_dilation=new_eyes[0].pupil_dilation,
                highlight=new_eyes[0].highlight,
            ),
            Eye(
                gaze=gaze,
                openness=new_eyes[1].openness,
                pupil_dilation=new_eyes[1].pupil_dilation,
                highlight=new_eyes[1].highlight,
            ),
        )

    # Apply timeline (smile, eyebrows, bounce, …) if any
    if self._timeline is not None:
        self._timeline_t += dt
        progress = min(1.0, self._timeline_t / max(0.001, self._timeline_total))
        # Invoke the on_update callbacks directly. Each builder
        # registered a single tween whose callback writes to
        # ``self._current`` (interpolation, bounce, …).
        for animation in self._timeline._items:
            if hasattr(animation, "on_update"):
                animation.on_update(progress)
        if progress >= 1.0:
            self._timeline = None
            self._timeline_t = 0.0
    # Merge eye state + current body
    merged = self._current.with_eyes(left_eye=new_eyes[0], right_eye=new_eyes[1])
    # Update the current model so a.current reflects the rendered state.
    self._current = merged

    # Speaking animation: override mouth when active.
    if self._speaking_animation is not None:
        viseme = self._speaking_animation.step(dt)
        mouth_shape = MouthShape.OPEN if viseme.openness > 0.1 else MouthShape.NEUTRAL
        self._current = self._current.with_mouth(
            Mouth(shape=mouth_shape, openness=viseme.openness, width=viseme.width)
        )
        if not self._speaking_animation.has_frames:
            self._speaking_animation = None

    # Wake animation: full override (highest priority).
    if self._wake_animation is not None:
        wake_frame = self._wake_animation.step(dt)
        self._current = self._apply_wake_frame(self._current, wake_frame)
        if self._wake_animation.done:
            self._wake_animation = None

    # Apply theme
    themed = self.theme.apply(self._current)
    return self.renderer.render(themed)

stop()

Source code in src/robot/face/animator.py
def stop(self) -> None:
    self._stopped = True

wink()

Source code in src/robot/face/animator.py
def wink(self) -> None:
    self._eye.wink()

FaceRenderer

Render a :class:FaceModel to an RGB888 frame.

Source code in src/robot/face/renderer.py
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
class FaceRenderer:
    """Render a :class:`FaceModel` to an RGB888 frame."""

    def __init__(self, width: int = 240, height: int = 240) -> None:
        if width <= 0 or height <= 0:
            raise ValueError("width and height must be > 0")
        self._width = width
        self._height = height

    @property
    def width(self) -> int:
        return self._width

    @property
    def height(self) -> int:
        return self._height

    # ------------------------------------------------------------------ public
    def render(self, model: FaceModel) -> EyeFrame:
        """Render ``model`` into a new RGB888 frame."""
        if model.width != self._width or model.height != self._height:
            raise ValueError(
                f"model is {model.width}x{model.height}, renderer is {self._width}x{self._height}"
            )
        raster = self._new_raster()
        # Vector mode bypasses the full face stack and renders only the
        # minimalist "two glowing squares + a horizontal line" used by the
        # Anki Vector 2.0 face. Cheeks/eyebrows/iris/sclera are skipped
        # because the Vector palette does not use them.
        if model.palette.mode == PALETTE_MODE_VECTOR:
            self._draw_background(raster, model)
            self._draw_vector_eyes(raster, model)
            self._draw_vector_mouth(raster, model)
            return EyeFrame(width=self._width, height=self._height, pixels=bytes(raster.pixels))
        self._draw_background(raster, model)
        self._draw_cheeks(raster, model)
        self._draw_sclera(raster, model)
        self._draw_eyelids(raster, model)
        self._draw_iris(raster, model)
        self._draw_pupil(raster, model)
        self._draw_highlight(raster, model)
        self._draw_eyebrows(raster, model)
        self._draw_mouth(raster, model)
        self._draw_overlay(raster, model)
        self._draw_accessory(raster, model)
        return EyeFrame(width=self._width, height=self._height, pixels=bytes(raster.pixels))

    # ------------------------------------------------------------------ vector mode
    def _draw_vector_eyes(self, raster: _Raster, model: FaceModel) -> None:
        """Draw two glowing rounded-squares for the eyes (Vector style).

        Each eye follows the model's gaze position so drift and look
        commands produce visible movement.  The mouth still animates
        independently.
        """
        cx, cy, face_radius, _, _ = self._face_geometry(model)
        # Vector eyes sit a bit above the panel centre, like the Anki robot.
        eye_radius = face_radius * 0.18
        eye_y = cy - face_radius * 0.30
        eye_offset_x = face_radius * 0.45
        # Gaze offset - both eyes share the same gaze direction.
        # A multiplier of 0.35 produces a visible (~3-5 px) shift on a
        # 240 px face so that drift and look commands are perceptible.
        gaze_shift_x = face_radius * 0.35 * model.left_eye.gaze.x
        gaze_shift_y = face_radius * 0.35 * model.left_eye.gaze.y
        for sx in (-1, 1):
            ex = cx + sx * eye_offset_x + gaze_shift_x
            ey = eye_y + gaze_shift_y
            self._fill_rounded_square(
                raster,
                ex - eye_radius,
                ey - eye_radius,
                eye_radius * 2,
                eye_radius * 2,
                eye_radius * 0.25,
                model.palette.iris,
            )

    def _draw_vector_mouth(self, raster: _Raster, model: FaceModel) -> None:
        """Draw a thin horizontal bar mouth that morphs with the mouth shape.

        Shape -> visual:
          NEUTRAL / CLOSED  -> straight horizontal bar
          SMILE / GRIN      -> bar curves up at the ends
          FROWN             -> bar curves down at the ends
          OPEN / WIDE_OPEN  -> bar with a gap in the middle (small "o")
          TONGUE            -> bar with a small dot below
        """
        cx, cy, face_radius, _, _ = self._face_geometry(model)
        bar_y = cy + face_radius * 0.45
        bar_half_w = face_radius * 0.32
        bar_thickness = max(2, int(face_radius * 0.08))
        shape = model.mouth.shape
        openness = model.mouth.openness
        color = model.palette.mouth
        if shape in (MouthShape.SMILE, MouthShape.GRIN, MouthShape.SMILE_OPEN, MouthShape.TONGUE):
            # Curve the ends upward (smile).
            curve = -face_radius * 0.18 * (1.0 + openness)
            self._draw_arc(raster, cx, bar_y, bar_half_w, curve, color, bar_thickness)
            if shape is MouthShape.TONGUE:
                # A tiny tongue dot below the mouth line.
                self._fill_circle(
                    raster,
                    cx,
                    bar_y - face_radius * 0.06,
                    face_radius * 0.06,
                    (255, 130, 180),
                )
        elif shape is MouthShape.FROWN:
            # Curve the ends downward.
            curve = face_radius * 0.18
            self._draw_arc(raster, cx, bar_y, bar_half_w, curve, color, bar_thickness)
        elif shape in (MouthShape.OPEN, MouthShape.WIDE_OPEN):
            # Two short bars with a gap = a small "o" shape.
            r = face_radius * (0.04 + 0.06 * openness) * (1.0 if shape is MouthShape.OPEN else 1.6)
            self._fill_circle(raster, cx, bar_y, r, color)
            if shape is MouthShape.WIDE_OPEN:
                self._fill_circle(raster, cx, bar_y, r * 0.6, model.palette.background)
        else:  # NEUTRAL / CLOSED
            self._draw_thick_line(
                raster,
                cx - bar_half_w,
                bar_y,
                cx + bar_half_w,
                bar_y,
                bar_thickness,
                color,
            )

    def _fill_rounded_square(
        self,
        raster: _Raster,
        x0: float,
        y0: float,
        w: float,
        h: float,
        radius: float,
        color: tuple[int, int, int],
    ) -> None:
        """Fill a rounded-square between ``(x0, y0)`` and ``(x0+w, y0+h)``.

        Used for the Vector-style eye. The corners are rounded by
        ``radius`` pixels (clamped to half the smaller side).
        """
        r = max(0.0, min(radius, min(w, h) / 2.0))
        x1 = x0 + w
        y1 = y0 + h
        col = bytes(color) * raster.width
        # Top + bottom strips + middle strips + corner arcs.
        for y in range(round(y0), round(y1)):
            if y < y0 + r or y >= y1 - r:
                # Top/bottom strip between the corners
                self._fill_rect_row(raster, round(x0 + r), y, round(x1 - r) - 1, col)
            else:
                # Full-width row in the middle
                self._fill_rect_row(raster, round(x0), y, round(x1) - 1, col)
        # Quadrant corner fills (4 circles for the rounded corners)
        cr = max(1, round(r))
        for cx_corner, cy_corner in (
            (x0 + r, y0 + r),
            (x1 - r, y0 + r),
            (x0 + r, y1 - r),
            (x1 - r, y1 - r),
        ):
            # Use the existing _fill_circle for each corner quadrant.
            # We restrict to the inside of the square so the result is a
            # smooth rounded corner rather than a full disc.
            self._fill_corner_quadrant(
                raster,
                round(cx_corner),
                round(cy_corner),
                cr,
                color,
                is_top_left=(cx_corner <= x0 + r and cy_corner <= y0 + r),
                is_top_right=(cx_corner >= x1 - r and cy_corner <= y0 + r),
                is_bottom_left=(cx_corner <= x0 + r and cy_corner >= y1 - r),
                is_bottom_right=(cx_corner >= x1 - r and cy_corner >= y1 - r),
            )

    def _fill_rect_row(self, raster: _Raster, x0: int, y: int, x1: int, color_bytes: bytes) -> None:
        """Fill a horizontal strip from ``(x0, y)`` to ``(x1, y)`` inclusive."""
        if x1 < x0 or y < 0 or y >= raster.height:
            return
        x0 = max(0, x0)
        x1 = min(raster.width - 1, x1)
        if x1 < x0:
            return
        start = (y * raster.width + x0) * 3
        end = (y * raster.width + x1 + 1) * 3
        # Write the 3-byte color (r, g, b) for every pixel in the row.
        i = start
        while i + 3 <= end:
            raster.pixels[i : i + 3] = bytes(color_bytes[:3])
            i += 3

    def _fill_corner_quadrant(
        self,
        raster: _Raster,
        cx: int,
        cy: int,
        r: int,
        color: tuple[int, int, int],
        *,
        is_top_left: bool,
        is_top_right: bool,
        is_bottom_left: bool,
        is_bottom_right: bool,
    ) -> None:
        """Fill the inside-quadrant of a circle of radius ``r`` at (cx, cy).

        Used to round the corners of :meth:`_fill_rounded_square`.
        """
        for dy in range(-r, r + 1):
            for dx in range(-r, r + 1):
                if dx * dx + dy * dy > r * r:
                    continue
                px = cx + dx
                py = cy + dy
                # Only write inside the square.
                inside = True
                if is_top_left and (dx > 0 or dy > 0):
                    inside = False
                if is_top_right and (dx < 0 or dy > 0):
                    inside = False
                if is_bottom_left and (dx > 0 or dy < 0):
                    inside = False
                if is_bottom_right and (dx < 0 or dy < 0):
                    inside = False
                if not inside:
                    continue
                if 0 <= px < raster.width and 0 <= py < raster.height:
                    i = (py * raster.width + px) * 3
                    raster.pixels[i : i + 3] = bytes(color)

    # ------------------------------------------------------------------ helpers
    def _new_raster(self) -> _Raster:
        return _Raster(width=self._width, height=self._height)

    # The model is drawn around a logical centre (cx, cy). The bounce and
    # squash fields are applied here so every layer sees the transformed
    # coordinates.
    def _face_geometry(self, model: FaceModel) -> tuple[float, float, float, float, float]:
        """Return (cx, cy, face_radius, eye_radius, mouth_y) in pixels."""
        cx = self._width / 2.0
        cy = self._height / 2.0
        # Vertical bounce: -1..1 -> -face_radius..+face_radius
        face_radius = min(self._width, self._height) * 0.45
        cy = cy + model.bounce * face_radius * 0.10
        # Horizontal squash: 1.0 = normal, 0.5 = squashed, 1.5 = stretched
        # We model squash as a uniform scale of the face radius (used by
        # sub-elements that respect a "horizontal scale" hint).
        face_radius *= 1.0
        eye_radius = face_radius * 0.30
        mouth_y = cy + face_radius * 0.55
        return cx, cy, face_radius, eye_radius, mouth_y

    def _sclera_radius(self, openness: float, eye_radius: float) -> tuple[float, float]:
        rx = eye_radius
        ry = max(eye_radius * 0.05, eye_radius * openness)
        return rx, ry

    # ------------------------------------------------------------------ layers
    def _draw_background(self, raster: _Raster, model: FaceModel) -> None:
        r, g, b = model.palette.background
        pixel = bytes((r, g, b)) * (raster.width * raster.height)
        raster.pixels[:] = pixel

    def _draw_cheeks(self, raster: _Raster, model: FaceModel) -> None:
        if model.cheeks.state is CheekState.NONE or model.cheeks.intensity <= 0.0:
            return
        cx, cy, face_radius, _, _ = self._face_geometry(model)
        # Cheek positions: left/right of mouth, below eyes
        for sx in (-1, 1):
            x = cx + sx * face_radius * 0.55
            y = cy + face_radius * 0.15
            color = (
                model.palette.blush
                if model.cheeks.state is CheekState.BRIGHT
                else model.palette.cheek
            )
            self._fill_circle_blend(raster, x, y, face_radius * 0.22, color, model.cheeks.intensity)

    def _draw_sclera(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        # Two eyes side by side
        for sx, eye in ((-1, model.left_eye), (1, model.right_eye)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            rx, ry = self._sclera_radius(eye.openness, eye_radius)
            self._fill_ellipse(raster, ex, ey, rx, ry, model.palette.sclera)
            if model.palette.outline != model.palette.sclera:
                self._draw_ellipse_outline(
                    raster,
                    ex,
                    ey,
                    rx,
                    ry,
                    model.palette.outline,
                    1,
                )

    def _draw_eyelids(self, raster: _Raster, model: FaceModel) -> None:
        if model.eyelids.top <= 0.0 and model.eyelids.bottom <= 0.0:
            return
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx in (-1, 1):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            rx, ry = self._sclera_radius(1.0, eye_radius)
            if model.eyelids.top > 0.0:
                self._draw_horizontal_band(
                    raster,
                    ey - ry,
                    ey - ry + 2 * ry * model.eyelids.top,
                    ex,
                    rx,
                    model.palette.eyelid,
                )
            if model.eyelids.bottom > 0.0:
                self._draw_horizontal_band(
                    raster,
                    ey + ry - 2 * ry * model.eyelids.bottom,
                    ey + ry,
                    ex,
                    rx,
                    model.palette.eyelid,
                )

    def _draw_iris(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx, eye in ((-1, model.left_eye), (1, model.right_eye)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            rx, ry = self._sclera_radius(eye.openness, eye_radius)
            if ry <= 1.0:
                continue
            gaze = eye.gaze.clamped()
            ox = gaze.x * self._width * 0.06
            oy = gaze.y * self._height * 0.06
            iris_cx = ex + ox
            iris_cy = ey + oy
            iris_rx = eye_radius * 0.55
            iris_ry = eye_radius * 0.55 * min(1.0, ry / rx) if rx > 0.0 else 0.0
            self._fill_ellipse(raster, iris_cx, iris_cy, iris_rx, iris_ry, model.palette.iris)
            self._draw_ellipse_outline(
                raster,
                iris_cx,
                iris_cy,
                iris_rx,
                iris_ry,
                model.palette.outline,
                1,
            )

    def _draw_pupil(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx, eye in ((-1, model.left_eye), (1, model.right_eye)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            _rx, ry = self._sclera_radius(eye.openness, eye_radius)
            if ry <= 1.0:
                continue
            gaze = eye.gaze.clamped()
            ox = gaze.x * self._width * 0.06
            oy = gaze.y * self._height * 0.06
            iris_cx = ex + ox
            iris_cy = ey + oy
            base = eye_radius * 0.55 * 0.55
            pupil_r = base * (0.6 + 0.6 * eye.pupil_dilation)
            self._fill_circle(raster, iris_cx, iris_cy, pupil_r, model.palette.pupil)

    def _draw_highlight(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx, eye in ((-1, model.left_eye), (1, model.right_eye)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            _rx, ry = self._sclera_radius(eye.openness, eye_radius)
            if ry <= 1.0:
                continue
            gaze = eye.gaze.clamped()
            ox = gaze.x * self._width * 0.06
            oy = gaze.y * self._height * 0.06
            iris_cx = ex + ox
            iris_cy = ey + oy
            hx = iris_cx + eye.highlight.x * eye_radius * 0.30
            hy = iris_cy + eye.highlight.y * eye_radius * 0.30
            self._fill_circle(raster, hx, hy, max(1.0, eye_radius * 0.08), model.palette.highlight)

    def _draw_eyebrows(self, raster: _Raster, model: FaceModel) -> None:
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        for sx, brow in ((-1, model.left_eyebrow), (1, model.right_eyebrow)):
            ex = cx + sx * face_radius * 0.40
            ey = cy - face_radius * 0.18
            base_y = ey - eye_radius * (1.05 + brow.raise_amount)
            # Shape -> vertical offset
            if brow.shape is EyebrowShape.ANGRY:
                outer_y = base_y - 0.05 * face_radius
                inner_y = base_y + 0.10 * face_radius
            elif brow.shape is EyebrowShape.WORRIED:
                outer_y = base_y + 0.05 * face_radius
                inner_y = base_y - 0.10 * face_radius
            elif brow.shape is EyebrowShape.SAD:
                outer_y = base_y + 0.15 * face_radius
                inner_y = base_y - 0.05 * face_radius
            elif brow.shape is EyebrowShape.SLEEPY:
                outer_y = base_y - 0.10 * face_radius
                inner_y = base_y - 0.10 * face_radius
            else:  # NEUTRAL or RAISED
                outer_y = base_y
                inner_y = base_y

            # Add the angle tilt
            tilt = brow.angle * eye_radius * 0.4
            outer_y -= tilt
            inner_y += tilt

            thickness = max(1, int(eye_radius * 0.18))
            length = eye_radius * 0.95
            self._draw_thick_line(
                raster,
                ex - length / 2,
                outer_y,
                ex + length / 2,
                inner_y,
                thickness,
                model.palette.eyebrow,
            )

    def _draw_mouth(self, raster: _Raster, model: FaceModel) -> None:
        cx, _cy, face_radius, _, mouth_y = self._face_geometry(model)
        width = face_radius * 0.45
        shape = model.mouth.shape
        openness = model.mouth.openness
        width_scale = model.mouth.width
        actual_width = width * width_scale
        # Base line at mouth_y
        if shape is MouthShape.SMILE or shape is MouthShape.GRIN:
            curve = -face_radius * 0.10 * (1.0 + openness)
            self._draw_arc(raster, cx, mouth_y, actual_width, curve, model.palette.mouth, 3)
        elif shape is MouthShape.SMILE_OPEN:
            self._draw_arc(
                raster, cx, mouth_y, actual_width, -face_radius * 0.12, model.palette.mouth, 3
            )
            self._fill_circle(
                raster,
                cx,
                mouth_y - face_radius * 0.04,
                face_radius * 0.08 * openness,
                model.palette.background,
            )
        elif shape is MouthShape.FROWN:
            self._draw_arc(
                raster, cx, mouth_y, actual_width, face_radius * 0.10, model.palette.mouth, 3
            )
        elif shape is MouthShape.OPEN or shape is MouthShape.WIDE_OPEN:
            r = face_radius * (0.05 + 0.10 * openness) * (1.0 if shape is MouthShape.OPEN else 1.6)
            self._fill_circle(raster, cx, mouth_y, r, model.palette.mouth)
            if shape is MouthShape.WIDE_OPEN:
                # Inner dark
                self._fill_circle(raster, cx, mouth_y, r * 0.6, model.palette.background)
        elif shape is MouthShape.TONGUE:
            self._draw_arc(
                raster, cx, mouth_y, actual_width, -face_radius * 0.05, model.palette.mouth, 3
            )
            # Pink tongue
            self._fill_circle(
                raster, cx, mouth_y - face_radius * 0.01, face_radius * 0.06, (255, 130, 180)
            )
        else:  # CLOSED or NEUTRAL
            self._draw_arc(raster, cx, mouth_y, actual_width, 0.0, model.palette.mouth, 2)
        if model.mouth.asymmetry != 0.0:
            skew = model.mouth.asymmetry * actual_width * 0.3
            self._draw_arc(raster, cx + skew, mouth_y, actual_width, 0.0, model.palette.mouth, 2)

    def _draw_overlay(self, raster: _Raster, model: FaceModel) -> None:
        ov = model.overlay
        if ov.kind is OverlayKind.NONE:
            return
        cx, cy, face_radius, _, _ = self._face_geometry(model)
        # Position is in normalised face coordinates (-1..1) -> pixels
        x = cx + ov.position.x * face_radius
        y = cy + ov.position.y * face_radius
        size = max(2, int(face_radius * ov.size))
        if ov.kind is OverlayKind.SPARKLE or ov.kind is OverlayKind.STAR:
            # 4-pointed star: a small filled diamond
            self._fill_diamond(raster, x, y, size, ov.color)
        elif ov.kind is OverlayKind.HEART:
            self._fill_heart(raster, x, y, size, ov.color)
        elif ov.kind is OverlayKind.TEAR:
            self._fill_teardrop(raster, x, y, size, (80, 150, 255))
        elif ov.kind is OverlayKind.SWEAT:
            self._fill_teardrop(raster, x, y, size, (130, 200, 255))
        elif ov.kind is OverlayKind.ANGER:
            self._fill_diamond(raster, x, y, size, (255, 50, 50))
        elif ov.kind is OverlayKind.QUESTION:
            self._fill_circle(raster, x, y, size * 0.6, (255, 220, 60))
        elif ov.kind is OverlayKind.EXCLAIM:
            self._fill_circle(raster, x, y, size * 0.6, (255, 80, 80))
        elif ov.kind is OverlayKind.MUSIC:
            self._fill_circle(raster, x, y, size * 0.5, (60, 200, 255))

    def _draw_accessory(self, raster: _Raster, model: FaceModel) -> None:
        acc = model.accessory
        if acc.kind is AccessoryKind.NONE:
            return
        cx, cy, face_radius, eye_radius, _ = self._face_geometry(model)
        if acc.kind is AccessoryKind.GLASSES:
            # Two round rims
            for sx in (-1, 1):
                ex = cx + sx * face_radius * 0.40
                ey = cy - face_radius * 0.18
                self._draw_ellipse_outline(
                    raster, ex, ey, eye_radius * 0.85, eye_radius * 0.65, acc.color, 2
                )
            # Bridge
            self._draw_horizontal_band(
                raster,
                cy - face_radius * 0.20,
                cy - face_radius * 0.16,
                cx,
                face_radius * 0.20,
                acc.color,
            )
        elif acc.kind is AccessoryKind.SUNGLASSES:
            for sx in (-1, 1):
                ex = cx + sx * face_radius * 0.40
                ey = cy - face_radius * 0.18
                self._fill_ellipse(raster, ex, ey, eye_radius * 0.85, eye_radius * 0.55, acc.color)
        elif acc.kind is AccessoryKind.MUSTACHE:
            self._draw_mustache(raster, cx, cy + face_radius * 0.30, face_radius * 0.5, acc.color)
        elif acc.kind is AccessoryKind.BOW_TIE:
            self._draw_bow_tie(
                raster, cx, self._height - face_radius * 0.20, face_radius * 0.4, acc.color
            )
        elif acc.kind is AccessoryKind.HAT:
            # A simple band + brim
            self._draw_horizontal_band(
                raster,
                cy - face_radius,
                cy - face_radius * 0.7,
                cx,
                face_radius,
                acc.color,
            )
            self._draw_horizontal_band(
                raster,
                cy - face_radius * 0.7,
                cy - face_radius * 0.55,
                cx,
                face_radius * 1.1,
                acc.color,
            )
        elif acc.kind is AccessoryKind.CROWN:
            self._draw_crown(raster, cx, cy - face_radius * 0.85, face_radius * 0.9, acc.color)
        elif acc.kind is AccessoryKind.BANDAGE:
            self._draw_horizontal_band(
                raster,
                cy - face_radius * 0.6,
                cy - face_radius * 0.30,
                cx,
                face_radius * 0.9,
                (200, 200, 200),
            )
        elif acc.kind is AccessoryKind.HEART_EYES:
            for sx in (-1, 1):
                ex = cx + sx * face_radius * 0.40
                ey = cy - face_radius * 0.18
                self._fill_heart(raster, ex, ey, eye_radius * 0.7, (255, 80, 120))

    # ------------------------------------------------------------------ primitive stubs
    # (Detailed pixel-art primitives live below.)

    def _fill_circle(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        r: float,
        color: tuple[int, int, int],
    ) -> None:
        if r <= 0:
            return
        self._fill_ellipse(raster, cx, cy, r, r, color)

    def _fill_circle_blend(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        r: float,
        color: tuple[int, int, int],
        alpha: float,
    ) -> None:
        """Fill a circle with alpha-blending onto the background."""
        if r <= 0 or alpha <= 0.0:
            return
        alpha = max(0.0, min(1.0, alpha))
        w, h = raster.width, raster.height
        pr, pg, pb = color
        x0 = max(0, math.floor(cx - r))
        x1 = min(w - 1, math.ceil(cx + r))
        y0 = max(0, math.floor(cy - r))
        y1 = min(h - 1, math.ceil(cy + r))
        r2 = r * r
        for y in range(y0, y1 + 1):
            dy = y - cy
            row = (y * w) * 3
            for x in range(x0, x1 + 1):
                dx = x - cx
                if dx * dx + dy * dy > r2:
                    continue
                idx = row + x * 3
                # Soft falloff at the edge
                edge = 1.0 - (dx * dx + dy * dy) / r2 if r2 > 0.0 else 0.0
                local_alpha = alpha * (0.4 + 0.6 * edge)
                br = raster.pixels[idx]
                bg = raster.pixels[idx + 1]
                bb = raster.pixels[idx + 2]
                raster.pixels[idx] = int(br * (1 - local_alpha) + pr * local_alpha)
                raster.pixels[idx + 1] = int(bg * (1 - local_alpha) + pg * local_alpha)
                raster.pixels[idx + 2] = int(bb * (1 - local_alpha) + pb * local_alpha)

    def _fill_ellipse(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        rx: float,
        ry: float,
        color: tuple[int, int, int],
    ) -> None:
        if rx <= 0 or ry <= 0:
            return
        pr, pg, pb = color
        w, h = raster.width, raster.height
        x0 = max(0, math.floor(cx - rx))
        x1 = min(w - 1, math.ceil(cx + rx))
        y0 = max(0, math.floor(cy - ry))
        y1 = min(h - 1, math.ceil(cy + ry))
        if rx == ry:
            r2 = rx * rx
            for y in range(y0, y1 + 1):
                dy = y - cy
                row = (y * w) * 3
                for x in range(x0, x1 + 1):
                    dx = x - cx
                    if dx * dx + dy * dy <= r2:
                        idx = row + x * 3
                        raster.pixels[idx] = pr
                        raster.pixels[idx + 1] = pg
                        raster.pixels[idx + 2] = pb
            return
        inv_rx2 = 1.0 / (rx * rx) if rx > 0.0 else 0.0
        inv_ry2 = 1.0 / (ry * ry) if ry > 0.0 else 0.0
        for y in range(y0, y1 + 1):
            dy = y - cy
            row = (y * w) * 3
            for x in range(x0, x1 + 1):
                dx = x - cx
                if dx * dx * inv_rx2 + dy * dy * inv_ry2 <= 1.0:
                    idx = row + x * 3
                    raster.pixels[idx] = pr
                    raster.pixels[idx + 1] = pg
                    raster.pixels[idx + 2] = pb

    def _draw_ellipse_outline(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        rx: float,
        ry: float,
        color: tuple[int, int, int],
        width: int,
    ) -> None:
        if rx <= 0 or ry <= 0 or width <= 0:
            return
        for w in range(width):
            self._draw_ellipse(raster, cx, cy, max(0.0, rx - w), max(0.0, ry - w), color)

    def _draw_ellipse(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        rx: float,
        ry: float,
        color: tuple[int, int, int],
    ) -> None:
        if rx == ry:
            self._draw_circle(raster, cx, cy, rx, color)
            return
        pr, pg, pb = color
        w, h = raster.width, raster.height

        def put(px: int, py: int) -> None:
            if 0 <= px < w and 0 <= py < h:
                idx = (py * w + px) * 3
                raster.pixels[idx] = pr
                raster.pixels[idx + 1] = pg
                raster.pixels[idx + 2] = pb

        rx2 = rx * rx
        ry2 = ry * ry
        x = 0.0
        y = ry
        px = 0.0
        py = 2 * rx2 * y
        d1 = ry2 - rx2 * ry + 0.25 * rx2
        while px < py:
            put(int(cx + x), int(cy + y))
            put(int(cx - x), int(cy + y))
            put(int(cx + x), int(cy - y))
            put(int(cx - x), int(cy - y))
            x += 1
            px += 2 * ry2
            if d1 < 0:
                d1 += ry2 + px
            else:
                y -= 1
                py -= 2 * rx2
                d1 += ry2 + px - py
        d2 = ry2 * (x + 0.5) * (x + 0.5) + rx2 * (y - 1) * (y - 1) - rx2 * ry2
        while y > 0:
            put(int(cx + x), int(cy + y))
            put(int(cx - x), int(cy + y))
            put(int(cx + x), int(cy - y))
            put(int(cx - x), int(cy - y))
            y -= 1
            py -= 2 * rx2
            if d2 > 0:
                d2 += rx2 - py
            else:
                x += 1
                px += 2 * ry2
                d2 += rx2 - py + px

    def _draw_circle(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        r: float,
        color: tuple[int, int, int],
    ) -> None:
        if r <= 0:
            return
        pr, pg, pb = color
        w, h = raster.width, raster.height

        def put(px: int, py: int) -> None:
            if 0 <= px < w and 0 <= py < h:
                idx = (py * w + px) * 3
                raster.pixels[idx] = pr
                raster.pixels[idx + 1] = pg
                raster.pixels[idx + 2] = pb

        x = round(r)
        y = 0
        err = 0
        icx, icy = round(cx), round(cy)
        while x >= y:
            put(icx + x, icy + y)
            put(icx + y, icy + x)
            put(icx - y, icy + x)
            put(icx - x, icy + y)
            put(icx - x, icy - y)
            put(icx - y, icy - x)
            put(icx + y, icy - x)
            put(icx + x, icy - y)
            y += 1
            err += 1 + 2 * y
            if 2 * (err - x) + 1 > 0:
                x -= 1
                err += 1 - 2 * x

    def _draw_horizontal_band(
        self,
        raster: _Raster,
        y_top: float,
        y_bottom: float,
        cx: float,
        rx: float,
        color: tuple[int, int, int],
    ) -> None:
        pr, pg, pb = color
        w, h = raster.width, raster.height
        x0 = max(0, math.floor(cx - rx))
        x1 = min(w - 1, math.ceil(cx + rx))
        y0 = max(0, math.ceil(y_top))
        y1 = min(h - 1, math.floor(y_bottom))
        rx2 = rx * rx
        band_cy = (y_top + y_bottom) / 2.0
        for y in range(y0, y1 + 1):
            dy = y - band_cy
            row = (y * w) * 3
            for x in range(x0, x1 + 1):
                dx = x - cx
                if dx * dx + dy * dy > rx2:
                    continue
                idx = row + x * 3
                raster.pixels[idx] = pr
                raster.pixels[idx + 1] = pg
                raster.pixels[idx + 2] = pb

    def _draw_arc(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        width: float,
        curve: float,
        color: tuple[int, int, int],
        thickness: int,
    ) -> None:
        """Draw a smile/frown arc as a thin filled strip.

        ``curve`` is positive for a frown, negative for a smile. The
        arc is sampled at many x positions and a small vertical strip
        of ``thickness`` pixels is drawn.
        """
        if abs(curve) < 0.5:
            # Treat as a horizontal line
            y = int(cy)
            for x in range(int(cx - width / 2), int(cx + width / 2) + 1):
                for t in range(thickness):
                    py = y - thickness // 2 + t
                    if 0 <= x < raster.width and 0 <= py < raster.height:
                        idx = (py * raster.width + x) * 3
                        raster.pixels[idx] = color[0]
                        raster.pixels[idx + 1] = color[1]
                        raster.pixels[idx + 2] = color[2]
            return
        # Parametric arc: y = cy + curve * (1 - ((x-cx) / (width/2)) ** 2)
        steps: int = max(8, round(width))
        half: float = width / 2.0
        if half <= 0.0:
            return
        cx_f: float = float(cx)
        cy_f: float = float(cy)
        curve_f: float = float(curve)
        for i in range(steps + 1):
            x_f: float = cx_f - half + (i / steps) * width
            t_f: float = (x_f - cx_f) / half
            y_f: float = cy_f - curve_f * (1 - t_f * t_f)
            for k in range(-thickness // 2, thickness // 2 + 1):
                px, py = round(x_f), round(y_f + k)
                if 0 <= px < raster.width and 0 <= py < raster.height:
                    idx = (py * raster.width + px) * 3
                    raster.pixels[idx] = color[0]
                    raster.pixels[idx + 1] = color[1]
                    raster.pixels[idx + 2] = color[2]

    def _draw_thick_line(
        self,
        raster: _Raster,
        x0: float,
        y0: float,
        x1: float,
        y1: float,
        thickness: int,
        color: tuple[int, int, int],
    ) -> None:
        # Bresenham with a brush
        steps = max(2, int(max(abs(x1 - x0), abs(y1 - y0)) * 2))
        for i in range(steps + 1):
            t = i / steps
            x = x0 + (x1 - x0) * t
            y = y0 + (y1 - y0) * t
            for dx in range(-thickness // 2, thickness // 2 + 1):
                for dy in range(-thickness // 2, thickness // 2 + 1):
                    px, py = round(x + dx), round(y + dy)
                    if 0 <= px < raster.width and 0 <= py < raster.height:
                        idx = (py * raster.width + px) * 3
                        raster.pixels[idx] = color[0]
                        raster.pixels[idx + 1] = color[1]
                        raster.pixels[idx + 2] = color[2]

    def _fill_diamond(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        size: float,
        color: tuple[int, int, int],
    ) -> None:
        self._fill_ellipse(raster, cx, cy, size * 0.45, size, color)

    def _fill_heart(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        size: float,
        color: tuple[int, int, int],
    ) -> None:
        # Two small circles + a downward triangle
        r = size * 0.45
        self._fill_circle(raster, cx - r * 0.6, cy - r * 0.3, r, color)
        self._fill_circle(raster, cx + r * 0.6, cy - r * 0.3, r, color)
        # Triangle (approximated with a rotated square)
        for y in range(int(cy - r * 0.3), int(cy + size * 0.7) + 1):
            t = (y - (cy - r * 0.3)) / (size + 0.2 * r)
            t = max(0.0, min(1.0, t))
            half = size * 0.6 * (1.0 - t)
            for x in range(int(cx - half), int(cx + half) + 1):
                if 0 <= x < raster.width and 0 <= y < raster.height:
                    idx = (y * raster.width + x) * 3
                    raster.pixels[idx] = color[0]
                    raster.pixels[idx + 1] = color[1]
                    raster.pixels[idx + 2] = color[2]

    def _fill_teardrop(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        size: float,
        color: tuple[int, int, int],
    ) -> None:
        # Circle + triangle pointing down
        r = size * 0.4
        self._fill_circle(raster, cx, cy - size * 0.3, r, color)
        for y in range(int(cy - size * 0.3), int(cy + size * 0.6) + 1):
            t = (y - (cy - size * 0.3)) / (size * 0.9)
            t = max(0.0, min(1.0, t))
            half = size * 0.4 * (1.0 - t)
            for x in range(int(cx - half), int(cx + half) + 1):
                if 0 <= x < raster.width and 0 <= y < raster.height:
                    idx = (y * raster.width + x) * 3
                    raster.pixels[idx] = color[0]
                    raster.pixels[idx + 1] = color[1]
                    raster.pixels[idx + 2] = color[2]

    def _draw_mustache(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        length: float,
        color: tuple[int, int, int],
    ) -> None:
        # Two curves meeting in the middle
        for sx in (-1, 1):
            self._draw_arc(
                raster,
                cx + sx * length * 0.30,
                cy - sx * length * 0.05,
                length * 0.6,
                -length * 0.10 * sx,
                color,
                3,
            )

    def _draw_bow_tie(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        size: float,
        color: tuple[int, int, int],
    ) -> None:
        # Two triangles
        for sx in (-1, 1):
            for y in range(int(cy - size / 2), int(cy + size / 2) + 1):
                t = (y - (cy - size / 2)) / size
                half = size * 0.4 * (1.0 - abs(t - 0.5) * 2)
                x_start = cx + sx * size * 0.05
                x_end = x_start + sx * half
                for x in range(int(min(x_start, x_end)), int(max(x_start, x_end)) + 1):
                    if 0 <= x < raster.width and 0 <= y < raster.height:
                        idx = (y * raster.width + x) * 3
                        raster.pixels[idx] = color[0]
                        raster.pixels[idx + 1] = color[1]
                        raster.pixels[idx + 2] = color[2]

    def _draw_crown(
        self,
        raster: _Raster,
        cx: float,
        cy: float,
        length: float,
        color: tuple[int, int, int],
    ) -> None:
        # Three triangles
        points = [
            (cx - length / 2, cy),
            (cx - length / 4, cy - length / 3),
            (cx, cy),
            (cx + length / 4, cy - length / 3),
            (cx + length / 2, cy),
            (cx + length / 2, cy + length / 6),
            (cx - length / 2, cy + length / 6),
        ]
        for i in range(len(points) - 1):
            self._draw_thick_line(
                raster,
                points[i][0],
                points[i][1],
                points[i + 1][0],
                points[i + 1][1],
                2,
                color,
            )

height property

width property

__init__(width=240, height=240)

Source code in src/robot/face/renderer.py
def __init__(self, width: int = 240, height: int = 240) -> None:
    if width <= 0 or height <= 0:
        raise ValueError("width and height must be > 0")
    self._width = width
    self._height = height

render(model)

Render model into a new RGB888 frame.

Source code in src/robot/face/renderer.py
def render(self, model: FaceModel) -> EyeFrame:
    """Render ``model`` into a new RGB888 frame."""
    if model.width != self._width or model.height != self._height:
        raise ValueError(
            f"model is {model.width}x{model.height}, renderer is {self._width}x{self._height}"
        )
    raster = self._new_raster()
    # Vector mode bypasses the full face stack and renders only the
    # minimalist "two glowing squares + a horizontal line" used by the
    # Anki Vector 2.0 face. Cheeks/eyebrows/iris/sclera are skipped
    # because the Vector palette does not use them.
    if model.palette.mode == PALETTE_MODE_VECTOR:
        self._draw_background(raster, model)
        self._draw_vector_eyes(raster, model)
        self._draw_vector_mouth(raster, model)
        return EyeFrame(width=self._width, height=self._height, pixels=bytes(raster.pixels))
    self._draw_background(raster, model)
    self._draw_cheeks(raster, model)
    self._draw_sclera(raster, model)
    self._draw_eyelids(raster, model)
    self._draw_iris(raster, model)
    self._draw_pupil(raster, model)
    self._draw_highlight(raster, model)
    self._draw_eyebrows(raster, model)
    self._draw_mouth(raster, model)
    self._draw_overlay(raster, model)
    self._draw_accessory(raster, model)
    return EyeFrame(width=self._width, height=self._height, pixels=bytes(raster.pixels))

InMemoryEventBus

An async pub/sub bus for in-process events with handler priority.

Critical handlers have their exceptions propagated; non-critical handlers have their exceptions logged and isolated.

Source code in src/robot/events/bus.py
class InMemoryEventBus:
    """An async pub/sub bus for in-process events with handler priority.

    Critical handlers have their exceptions propagated; non-critical
    handlers have their exceptions logged and isolated.
    """

    def __init__(self) -> None:
        self._subscribers: dict[type, list[_Subscription]] = defaultdict(list)
        self._lock = asyncio.Lock()
        self._sync_lock = threading.Lock()
        self._closed = False

    async def publish(self, event: object) -> None:
        """Publish an event to all subscribers."""
        if self._closed:
            return
        event_type = type(event)
        async with self._lock:
            subs = list(self._subscribers.get(event_type, []))
            if event_type is not object:
                subs.extend(self._subscribers.get(object, []))

        critical_subs = [s for s in subs if s.critical]
        non_critical_subs = [s for s in subs if not s.critical]

        critical_failures: list[HandlerFailedError] = []
        for sub in critical_subs:
            handler = sub.handler
            try:
                result = handler(event)
                if asyncio.iscoroutine(result):
                    await result
            except Exception as exc:
                hf = HandlerFailedError(
                    event_type=event_type.__name__,
                    handler=getattr(handler, "__qualname__", repr(handler)),
                    original=exc,
                )
                critical_failures.append(hf)
                _log.exception(
                    "events.critical_handler_failed",
                    event_type=event_type.__name__,
                    handler=hf.handler,
                )

        for sub in non_critical_subs:
            handler = sub.handler
            try:
                result = handler(event)
                if asyncio.iscoroutine(result):
                    await result
            except Exception:
                _log.exception(
                    "events.handler_failed",
                    event_type=event_type.__name__,
                    handler=getattr(handler, "__qualname__", repr(handler)),
                )

        if critical_failures:
            if len(critical_failures) > 1:
                _log.warning(
                    "events.suppressed_critical_failures",
                    count=len(critical_failures) - 1,
                )
            raise critical_failures[0]

    def subscribe(self, event_type: type, handler: EventHandler) -> None:
        """Subscribe a non-critical handler for events of ``event_type``."""
        sub = _Subscription(handler=handler, critical=False)
        with self._sync_lock:
            if sub in self._subscribers[event_type]:
                return
            self._subscribers[event_type].append(sub)
        _log.debug("events.subscribed", event_type=event_type.__name__, handler=handler.__name__)

    def subscribe_critical(self, event_type: type, handler: EventHandler) -> None:
        """Subscribe a critical handler for events of ``event_type``."""
        sub = _Subscription(handler=handler, critical=True)
        with self._sync_lock:
            self._subscribers[event_type].append(sub)
        _log.debug(
            "events.subscribed_critical",
            event_type=event_type.__name__,
            handler=handler.__name__,
        )

    def unsubscribe(self, event_type: type, handler: EventHandler) -> None:
        """Unsubscribe a previously-registered handler."""
        with self._sync_lock:
            self._subscribers[event_type] = [
                s for s in self._subscribers[event_type] if s.handler != handler
            ]

    async def close(self) -> None:
        self._closed = True
        self._subscribers.clear()

    def __repr__(self) -> str:
        total = sum(len(v) for v in self._subscribers.values())
        return f"InMemoryEventBus(subscribers={total}, closed={self._closed})"

__init__()

Source code in src/robot/events/bus.py
def __init__(self) -> None:
    self._subscribers: dict[type, list[_Subscription]] = defaultdict(list)
    self._lock = asyncio.Lock()
    self._sync_lock = threading.Lock()
    self._closed = False

__repr__()

Source code in src/robot/events/bus.py
def __repr__(self) -> str:
    total = sum(len(v) for v in self._subscribers.values())
    return f"InMemoryEventBus(subscribers={total}, closed={self._closed})"

close() async

Source code in src/robot/events/bus.py
async def close(self) -> None:
    self._closed = True
    self._subscribers.clear()

publish(event) async

Publish an event to all subscribers.

Source code in src/robot/events/bus.py
async def publish(self, event: object) -> None:
    """Publish an event to all subscribers."""
    if self._closed:
        return
    event_type = type(event)
    async with self._lock:
        subs = list(self._subscribers.get(event_type, []))
        if event_type is not object:
            subs.extend(self._subscribers.get(object, []))

    critical_subs = [s for s in subs if s.critical]
    non_critical_subs = [s for s in subs if not s.critical]

    critical_failures: list[HandlerFailedError] = []
    for sub in critical_subs:
        handler = sub.handler
        try:
            result = handler(event)
            if asyncio.iscoroutine(result):
                await result
        except Exception as exc:
            hf = HandlerFailedError(
                event_type=event_type.__name__,
                handler=getattr(handler, "__qualname__", repr(handler)),
                original=exc,
            )
            critical_failures.append(hf)
            _log.exception(
                "events.critical_handler_failed",
                event_type=event_type.__name__,
                handler=hf.handler,
            )

    for sub in non_critical_subs:
        handler = sub.handler
        try:
            result = handler(event)
            if asyncio.iscoroutine(result):
                await result
        except Exception:
            _log.exception(
                "events.handler_failed",
                event_type=event_type.__name__,
                handler=getattr(handler, "__qualname__", repr(handler)),
            )

    if critical_failures:
        if len(critical_failures) > 1:
            _log.warning(
                "events.suppressed_critical_failures",
                count=len(critical_failures) - 1,
            )
        raise critical_failures[0]

subscribe(event_type, handler)

Subscribe a non-critical handler for events of event_type.

Source code in src/robot/events/bus.py
def subscribe(self, event_type: type, handler: EventHandler) -> None:
    """Subscribe a non-critical handler for events of ``event_type``."""
    sub = _Subscription(handler=handler, critical=False)
    with self._sync_lock:
        if sub in self._subscribers[event_type]:
            return
        self._subscribers[event_type].append(sub)
    _log.debug("events.subscribed", event_type=event_type.__name__, handler=handler.__name__)

subscribe_critical(event_type, handler)

Subscribe a critical handler for events of event_type.

Source code in src/robot/events/bus.py
def subscribe_critical(self, event_type: type, handler: EventHandler) -> None:
    """Subscribe a critical handler for events of ``event_type``."""
    sub = _Subscription(handler=handler, critical=True)
    with self._sync_lock:
        self._subscribers[event_type].append(sub)
    _log.debug(
        "events.subscribed_critical",
        event_type=event_type.__name__,
        handler=handler.__name__,
    )

unsubscribe(event_type, handler)

Unsubscribe a previously-registered handler.

Source code in src/robot/events/bus.py
def unsubscribe(self, event_type: type, handler: EventHandler) -> None:
    """Unsubscribe a previously-registered handler."""
    with self._sync_lock:
        self._subscribers[event_type] = [
            s for s in self._subscribers[event_type] if s.handler != handler
        ]

MockDisplay

A :class:Display that stores every frame it receives in memory.

Source code in src/robot/hardware/displays/mock_display.py
class MockDisplay:
    """A :class:`Display` that stores every frame it receives in memory."""

    def __init__(self, width: int = 240, height: int = 240) -> None:
        self._width = width
        self._height = height
        self._last: EyeFrame | None = None
        self._frames_pushed: int = 0
        self._closed = False
        self._all_frames: list[EyeFrame] = []
        self._last_logged_size: tuple[int, int] | None = None

    @property
    def width(self) -> int:
        return self._width

    @property
    def height(self) -> int:
        return self._height

    @property
    def last_frame(self) -> EyeFrame | None:
        return self._last

    @property
    def frames_pushed(self) -> int:
        return self._frames_pushed

    @property
    def frames(self) -> list[EyeFrame]:
        """Every frame the display has received, in order."""
        return list(self._all_frames)

    async def show(self, frame: EyeFrame) -> None:
        if self._closed:
            raise RuntimeError("display is closed")
        self._last = frame
        self._frames_pushed += 1
        self._all_frames.append(frame)
        size = (frame.width, frame.height)
        if size != self._last_logged_size:
            _log.debug(
                "display.show",
                width=frame.width,
                height=frame.height,
            )
            self._last_logged_size = size

    async def fill(self, color: tuple[int, int, int]) -> None:
        r, g, b = color
        self._last = EyeFrame(
            self._width, self._height, bytes((r, g, b)) * (self._width * self._height)
        )
        self._all_frames.append(self._last)

    async def clear(self) -> None:
        await self.fill((0, 0, 0))

    async def close(self) -> None:
        self._closed = True

frames property

Every frame the display has received, in order.

frames_pushed property

height property

last_frame property

width property

__init__(width=240, height=240)

Source code in src/robot/hardware/displays/mock_display.py
def __init__(self, width: int = 240, height: int = 240) -> None:
    self._width = width
    self._height = height
    self._last: EyeFrame | None = None
    self._frames_pushed: int = 0
    self._closed = False
    self._all_frames: list[EyeFrame] = []
    self._last_logged_size: tuple[int, int] | None = None

clear() async

Source code in src/robot/hardware/displays/mock_display.py
async def clear(self) -> None:
    await self.fill((0, 0, 0))

close() async

Source code in src/robot/hardware/displays/mock_display.py
async def close(self) -> None:
    self._closed = True

fill(color) async

Source code in src/robot/hardware/displays/mock_display.py
async def fill(self, color: tuple[int, int, int]) -> None:
    r, g, b = color
    self._last = EyeFrame(
        self._width, self._height, bytes((r, g, b)) * (self._width * self._height)
    )
    self._all_frames.append(self._last)

show(frame) async

Source code in src/robot/hardware/displays/mock_display.py
async def show(self, frame: EyeFrame) -> None:
    if self._closed:
        raise RuntimeError("display is closed")
    self._last = frame
    self._frames_pushed += 1
    self._all_frames.append(frame)
    size = (frame.width, frame.height)
    if size != self._last_logged_size:
        _log.debug(
            "display.show",
            width=frame.width,
            height=frame.height,
        )
        self._last_logged_size = size

MockServo dataclass

Records every move command.

Source code in src/robot/hardware/servos/mock_servo.py
@dataclass(slots=True)
class MockServo:
    """Records every move command."""

    name: str
    min_angle: float = 0.0
    max_angle: float = 180.0
    _angle: float = 90.0
    _released: bool = False
    history: list[tuple[float, float]] = field(default_factory=list)  # (angle, duration_s)

    @property
    def angle(self) -> float:
        return self._angle

    async def move_to(self, angle: float, duration_s: float = 0.4) -> None:
        if not (self.min_angle <= angle <= self.max_angle):
            raise ServoError(f"angle {angle} out of range [{self.min_angle}, {self.max_angle}]")
        self._angle = angle
        self._released = False
        self.history.append((angle, duration_s))
        _log.debug("servo.move_to", name=self.name, angle=angle, duration_s=duration_s)

    async def release(self) -> None:
        self._released = True

angle property

history = field(default_factory=list) class-attribute instance-attribute

max_angle = 180.0 class-attribute instance-attribute

min_angle = 0.0 class-attribute instance-attribute

name instance-attribute

__init__(name, min_angle=0.0, max_angle=180.0, _angle=90.0, _released=False, history=list())

move_to(angle, duration_s=0.4) async

Source code in src/robot/hardware/servos/mock_servo.py
async def move_to(self, angle: float, duration_s: float = 0.4) -> None:
    if not (self.min_angle <= angle <= self.max_angle):
        raise ServoError(f"angle {angle} out of range [{self.min_angle}, {self.max_angle}]")
    self._angle = angle
    self._released = False
    self.history.append((angle, duration_s))
    _log.debug("servo.move_to", name=self.name, angle=angle, duration_s=duration_s)

release() async

Source code in src/robot/hardware/servos/mock_servo.py
async def release(self) -> None:
    self._released = True

MockServoBus

Holds a collection of :class:MockServo instances by logical name.

Source code in src/robot/hardware/servos/mock_servo.py
class MockServoBus:
    """Holds a collection of :class:`MockServo` instances by logical name."""

    def __init__(self, servos: Mapping[str, MockServo] | None = None) -> None:
        self._servos: dict[str, MockServo] = dict(servos or {})

    def add(self, servo: MockServo) -> MockServo:
        self._servos[servo.name] = servo
        return servo

    def get(self, name: str) -> MockServo:
        try:
            return self._servos[name]
        except KeyError as exc:
            raise ServoError(f"servo not found: {name!r}") from exc

    def all(self) -> list[MockServo]:
        return list(self._servos.values())

    def all_angles(self) -> dict[str, float]:
        return {name: s.angle for name, s in self._servos.items()}

    async def release_all(self) -> None:
        for servo in self._servos.values():
            await servo.release()

__init__(servos=None)

Source code in src/robot/hardware/servos/mock_servo.py
def __init__(self, servos: Mapping[str, MockServo] | None = None) -> None:
    self._servos: dict[str, MockServo] = dict(servos or {})

add(servo)

Source code in src/robot/hardware/servos/mock_servo.py
def add(self, servo: MockServo) -> MockServo:
    self._servos[servo.name] = servo
    return servo

all()

Source code in src/robot/hardware/servos/mock_servo.py
def all(self) -> list[MockServo]:
    return list(self._servos.values())

all_angles()

Source code in src/robot/hardware/servos/mock_servo.py
def all_angles(self) -> dict[str, float]:
    return {name: s.angle for name, s in self._servos.items()}

get(name)

Source code in src/robot/hardware/servos/mock_servo.py
def get(self, name: str) -> MockServo:
    try:
        return self._servos[name]
    except KeyError as exc:
        raise ServoError(f"servo not found: {name!r}") from exc

release_all() async

Source code in src/robot/hardware/servos/mock_servo.py
async def release_all(self) -> None:
    for servo in self._servos.values():
        await servo.release()

ServoCalibration dataclass

Per-servo calibration (limits, centre, sign).

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class ServoCalibration:
    """Per-servo calibration (limits, centre, sign)."""

    name: str
    min_angle: float
    max_angle: float
    center_angle: float
    inverted: bool = False

    def clamp(self, angle: float) -> float:
        return max(self.min_angle, min(self.max_angle, angle))

    def normalised(self, angle: float) -> float:
        """Return a value in ``[-1, 1]`` relative to the servo range."""
        half = (self.max_angle - self.min_angle) / 2.0
        if half <= 0:
            return 0.0
        mid = (self.max_angle + self.min_angle) / 2.0
        v = (angle - mid) / half
        return max(-1.0, min(1.0, v))

    def from_normalised(self, value: float) -> float:
        v = max(-1.0, min(1.0, value))
        half = (self.max_angle - self.min_angle) / 2.0
        mid = (self.max_angle + self.min_angle) / 2.0
        if self.inverted:
            v = -v
        return self.clamp(mid + v * half)

center_angle instance-attribute

inverted = False class-attribute instance-attribute

max_angle instance-attribute

min_angle instance-attribute

name instance-attribute

__init__(name, min_angle, max_angle, center_angle, inverted=False)

clamp(angle)

Source code in src/robot/body_language/requests.py
def clamp(self, angle: float) -> float:
    return max(self.min_angle, min(self.max_angle, angle))

from_normalised(value)

Source code in src/robot/body_language/requests.py
def from_normalised(self, value: float) -> float:
    v = max(-1.0, min(1.0, value))
    half = (self.max_angle - self.min_angle) / 2.0
    mid = (self.max_angle + self.min_angle) / 2.0
    if self.inverted:
        v = -v
    return self.clamp(mid + v * half)

normalised(angle)

Return a value in [-1, 1] relative to the servo range.

Source code in src/robot/body_language/requests.py
def normalised(self, angle: float) -> float:
    """Return a value in ``[-1, 1]`` relative to the servo range."""
    half = (self.max_angle - self.min_angle) / 2.0
    if half <= 0:
        return 0.0
    mid = (self.max_angle + self.min_angle) / 2.0
    v = (angle - mid) / half
    return max(-1.0, min(1.0, v))

ServoOverlay

Draw the four-servo stick figure into a face framebuffer.

Source code in src/robot/simulation/overlay.py
class ServoOverlay:
    """Draw the four-servo stick figure into a face framebuffer."""

    def __init__(
        self,
        calibration: dict[str, ServoCalibration],
        config: OverlayConfig | None = None,
    ) -> None:
        self._calibration = calibration
        self._config = config or OverlayConfig()

    def composite(
        self,
        frame_pixels: bytearray,
        width: int,
        height: int,
        pose: Pose,
    ) -> bytearray:
        out = bytearray(frame_pixels)
        body_top = int(height * 0.70)
        self._fill_rect(out, width, height, 0, body_top, width, height, self._config.background)
        cx = width / 2.0
        head_y = body_top + height * 0.04
        neck_y = body_top + height * 0.13
        shoulder_y = body_top + height * 0.18
        waist_y = body_top + height * 0.28
        self._line(out, width, height, cx, head_y, cx, waist_y, self._config.body_color, 4)
        shoulder_half = width * 0.18
        self._line(
            out,
            width,
            height,
            cx - shoulder_half,
            shoulder_y,
            cx + shoulder_half,
            shoulder_y,
            self._config.body_color,
            4,
        )
        pan_target = pose.get(SERVO_HEAD_PAN, 90.0)
        tilt_target = pose.get(SERVO_HEAD_TILT, 90.0)
        left_arm_target = pose.get(SERVO_LEFT_ARM, 90.0)
        right_arm_target = pose.get(SERVO_RIGHT_ARM, 90.0)
        head_tilt = (tilt_target - 90.0) * 0.04
        self._line(out, width, height, cx, neck_y, cx, head_y, self._config.body_color, 4)
        self._circle(out, width, height, cx, head_y, 12, self._config.body_color)
        self._line(
            out,
            width,
            height,
            cx,
            head_y,
            cx + (pan_target - 90.0) * 0.5,
            head_y - 8,
            self._config.pan_color,
            2,
        )
        self._line(
            out,
            width,
            height,
            cx,
            head_y,
            cx,
            head_y - 12 - head_tilt,
            self._config.tilt_color,
            2,
        )
        left_wrist = self._arm_endpoint(
            cx - shoulder_half, shoulder_y, left_arm_target, "left", height * 0.10
        )
        right_wrist = self._arm_endpoint(
            cx + shoulder_half, shoulder_y, right_arm_target, "right", height * 0.10
        )
        self._line(
            out,
            width,
            height,
            cx - shoulder_half,
            shoulder_y,
            *left_wrist,
            self._config.left_arm_color,
            3,
        )
        self._line(
            out,
            width,
            height,
            cx + shoulder_half,
            shoulder_y,
            *right_wrist,
            self._config.right_arm_color,
            3,
        )
        for x, y in (
            (cx - shoulder_half, shoulder_y),
            (cx + shoulder_half, shoulder_y),
            (cx, head_y),
        ):
            self._circle(out, width, height, x, y, 4, self._config.servo_color)
        for name, x, y, color, target in (
            (SERVO_HEAD_PAN, cx, head_y, self._config.pan_color, pan_target),
            (SERVO_HEAD_TILT, cx, head_y, self._config.tilt_color, tilt_target),
            (
                SERVO_LEFT_ARM,
                left_wrist[0],
                left_wrist[1],
                self._config.left_arm_color,
                left_arm_target,
            ),
            (
                SERVO_RIGHT_ARM,
                right_wrist[0],
                right_wrist[1],
                self._config.right_arm_color,
                right_arm_target,
            ),
        ):
            self._draw_target_indicator(
                out, width, height, x, y, target, name in self._calibration, color
            )
        return out

    def _arm_endpoint(
        self, sx: float, sy: float, angle: float, side: str, length: float
    ) -> tuple[float, float]:
        # Left arm extends to the left, right arm to the right.
        # At 90° the arm hangs straight down; higher angles raise it outward.
        sign = -1.0 if side == "left" else 1.0
        rad = math.radians(angle - 90.0)
        dx = sign * length * math.sin(rad)
        dy = length * math.cos(rad)
        return (sx + dx, sy + dy)

    def _draw_target_indicator(
        self,
        out: bytearray,
        width: int,
        height: int,
        x: float,
        y: float,
        target: float,
        calibrated: bool,
        color: tuple[int, int, int],
    ) -> None:
        bar_len = 18
        bar_y = y + 12
        self._line(out, width, height, x - bar_len / 2, bar_y, x + bar_len / 2, bar_y, color, 2)
        if calibrated:
            t = (target - 0.0) / 180.0
            t = max(0.0, min(1.0, t))
            dot_x = x - bar_len / 2 + bar_len * t
            self._circle(out, width, height, dot_x, bar_y, 3, (255, 255, 255))

    def _fill_rect(
        self,
        out: bytearray,
        width: int,
        height: int,
        x0: int,
        y0: int,
        x1: int,
        y1: int,
        color: tuple[int, int, int],
    ) -> None:
        r, g, b = color
        for y in range(max(0, y0), min(height, y1)):
            for x in range(max(0, x0), min(width, x1)):
                idx = (y * width + x) * 3
                out[idx] = r
                out[idx + 1] = g
                out[idx + 2] = b

    def _line(
        self,
        out: bytearray,
        width: int,
        height: int,
        x0: float,
        y0: float,
        x1: float,
        y1: float,
        color: tuple[int, int, int],
        thickness: int = 1,
    ) -> None:
        steps = max(2, int(max(abs(x1 - x0), abs(y1 - y0)) * 2))
        for i in range(steps + 1):
            t = i / steps
            x = x0 + (x1 - x0) * t
            y = y0 + (y1 - y0) * t
            self._dot(out, width, height, x, y, color, thickness)

    def _circle(
        self,
        out: bytearray,
        width: int,
        height: int,
        cx: float,
        cy: float,
        r: float,
        color: tuple[int, int, int],
    ) -> None:
        x0 = max(0, int(cx - r))
        x1 = min(width - 1, int(cx + r))
        y0 = max(0, int(cy - r))
        y1 = min(height - 1, int(cy + r))
        r2 = r * r
        for y in range(y0, y1 + 1):
            for x in range(x0, x1 + 1):
                if (x - cx) ** 2 + (y - cy) ** 2 <= r2:
                    self._set_pixel(out, width, x, y, color)

    def _dot(
        self,
        out: bytearray,
        width: int,
        height: int,
        x: float,
        y: float,
        color: tuple[int, int, int],
        thickness: int = 1,
    ) -> None:
        for dx in range(-thickness // 2, thickness // 2 + 1):
            for dy in range(-thickness // 2, thickness // 2 + 1):
                xx, yy = round(x + dx), round(y + dy)
                if 0 <= xx < width and 0 <= yy < height:
                    self._set_pixel(out, width, xx, yy, color)

    def _set_pixel(
        self,
        out: bytearray,
        width: int,
        x: int,
        y: int,
        color: tuple[int, int, int],
    ) -> None:
        idx = (y * width + x) * 3
        out[idx] = color[0]
        out[idx + 1] = color[1]
        out[idx + 2] = color[2]

__init__(calibration, config=None)

Source code in src/robot/simulation/overlay.py
def __init__(
    self,
    calibration: dict[str, ServoCalibration],
    config: OverlayConfig | None = None,
) -> None:
    self._calibration = calibration
    self._config = config or OverlayConfig()

composite(frame_pixels, width, height, pose)

Source code in src/robot/simulation/overlay.py
def composite(
    self,
    frame_pixels: bytearray,
    width: int,
    height: int,
    pose: Pose,
) -> bytearray:
    out = bytearray(frame_pixels)
    body_top = int(height * 0.70)
    self._fill_rect(out, width, height, 0, body_top, width, height, self._config.background)
    cx = width / 2.0
    head_y = body_top + height * 0.04
    neck_y = body_top + height * 0.13
    shoulder_y = body_top + height * 0.18
    waist_y = body_top + height * 0.28
    self._line(out, width, height, cx, head_y, cx, waist_y, self._config.body_color, 4)
    shoulder_half = width * 0.18
    self._line(
        out,
        width,
        height,
        cx - shoulder_half,
        shoulder_y,
        cx + shoulder_half,
        shoulder_y,
        self._config.body_color,
        4,
    )
    pan_target = pose.get(SERVO_HEAD_PAN, 90.0)
    tilt_target = pose.get(SERVO_HEAD_TILT, 90.0)
    left_arm_target = pose.get(SERVO_LEFT_ARM, 90.0)
    right_arm_target = pose.get(SERVO_RIGHT_ARM, 90.0)
    head_tilt = (tilt_target - 90.0) * 0.04
    self._line(out, width, height, cx, neck_y, cx, head_y, self._config.body_color, 4)
    self._circle(out, width, height, cx, head_y, 12, self._config.body_color)
    self._line(
        out,
        width,
        height,
        cx,
        head_y,
        cx + (pan_target - 90.0) * 0.5,
        head_y - 8,
        self._config.pan_color,
        2,
    )
    self._line(
        out,
        width,
        height,
        cx,
        head_y,
        cx,
        head_y - 12 - head_tilt,
        self._config.tilt_color,
        2,
    )
    left_wrist = self._arm_endpoint(
        cx - shoulder_half, shoulder_y, left_arm_target, "left", height * 0.10
    )
    right_wrist = self._arm_endpoint(
        cx + shoulder_half, shoulder_y, right_arm_target, "right", height * 0.10
    )
    self._line(
        out,
        width,
        height,
        cx - shoulder_half,
        shoulder_y,
        *left_wrist,
        self._config.left_arm_color,
        3,
    )
    self._line(
        out,
        width,
        height,
        cx + shoulder_half,
        shoulder_y,
        *right_wrist,
        self._config.right_arm_color,
        3,
    )
    for x, y in (
        (cx - shoulder_half, shoulder_y),
        (cx + shoulder_half, shoulder_y),
        (cx, head_y),
    ):
        self._circle(out, width, height, x, y, 4, self._config.servo_color)
    for name, x, y, color, target in (
        (SERVO_HEAD_PAN, cx, head_y, self._config.pan_color, pan_target),
        (SERVO_HEAD_TILT, cx, head_y, self._config.tilt_color, tilt_target),
        (
            SERVO_LEFT_ARM,
            left_wrist[0],
            left_wrist[1],
            self._config.left_arm_color,
            left_arm_target,
        ),
        (
            SERVO_RIGHT_ARM,
            right_wrist[0],
            right_wrist[1],
            self._config.right_arm_color,
            right_arm_target,
        ),
    ):
        self._draw_target_indicator(
            out, width, height, x, y, target, name in self._calibration, color
        )
    return out

SimulationDriver dataclass

Run the full robot stack against an in-memory mock display.

Source code in src/robot/simulation/driver.py
@dataclass(slots=True)
class SimulationDriver:
    """Run the full robot stack against an in-memory mock display."""

    DEFAULT_FPS: ClassVar[int] = 30

    bus: InMemoryEventBus = field(default_factory=InMemoryEventBus)
    width: int = 240
    height: int = 320  # extra height for the body diagram
    face_size: int = 240  # the face is square, drawn in the upper portion
    fps: int = DEFAULT_FPS
    clock: Clock = field(default_factory=SystemClock)
    theme: Theme | None = None

    _face: FaceAnimator = field(init=False)
    _body: BodyLanguageEngine = field(init=False)
    _display: MockDisplay = field(init=False)
    _overlay: ServoOverlay = field(init=False)
    _renderer: FaceRenderer = field(init=False)
    _stopped: bool = field(default=True, init=False)
    _servo_bus: MockServoBus | None = field(default=None, init=False)

    def __post_init__(self) -> None:
        if self.fps <= 0:
            raise ValueError("fps must be > 0")
        # The mock display receives the composite (face + overlay) frame
        self._display = MockDisplay(width=self.width, height=self.height)
        # The face engine is told the upper portion is the face
        self._renderer = FaceRenderer(width=self.face_size, height=self.face_size)
        # The mock servo bus is calibrated with the default limits
        self._servo_bus = MockServoBus(
            {
                "pan": MockServo(name="pan", min_angle=30.0, max_angle=150.0, _angle=90.0),
                "tilt": MockServo(name="tilt", min_angle=45.0, max_angle=135.0, _angle=90.0),
                "left_arm": MockServo(
                    name="left_arm", min_angle=20.0, max_angle=160.0, _angle=90.0
                ),
                "right_arm": MockServo(
                    name="right_arm", min_angle=20.0, max_angle=160.0, _angle=90.0
                ),
            }
        )
        servo_controller = wrap_servo_controller(self._servo_bus, backend_name="mock")
        self._body = BodyLanguageEngine(
            servo_controller=servo_controller,
            clock=self.clock,
            calibration=dict(DEFAULT_CALIBRATION),
        )
        # The face animator runs on the (smaller) face panel
        from robot.face.themes.minimal import MinimalTheme

        self._face = FaceAnimator(
            renderer=self._renderer,
            display=MockDisplay(width=self.face_size, height=self.face_size),
            clock=self.clock,
            emotions=EmotionEngine(width=self.face_size, height=self.face_size),
            theme=self.theme or MinimalTheme(),
            fps=self.fps,
            bus=self.bus,
            width=self.face_size,
            height=self.face_size,
        )
        self._overlay = ServoOverlay(calibration=dict(DEFAULT_CALIBRATION))

    # ------------------------------------------------------------------ properties
    @property
    def face(self) -> FaceAnimator:
        return self._face

    @property
    def body(self) -> BodyLanguageEngine:
        return self._body

    @property
    def display(self) -> Display:
        return self._display

    @property
    def is_running(self) -> bool:
        return not self._stopped

    # ------------------------------------------------------------------ public
    def step(self) -> EyeFrame:
        """Advance one frame and return the composite frame."""
        face_frame = self._face.step(drift=True)
        pose = self._body.snapshot()
        # The face is square; composite it into a taller canvas that
        # leaves room for the body diagram below.
        out = bytearray(self.width * self.height * 3)
        # Center the face in the upper portion of the canvas
        x_offset = (self.width - self.face_size) // 2
        for y in range(self.face_size):
            src_start = y * self.face_size * 3
            src_end = src_start + self.face_size * 3
            dst_start = (y * self.width + x_offset) * 3
            out[dst_start : dst_start + self.face_size * 3] = face_frame.pixels[src_start:src_end]
        composite_pixels = self._overlay.composite(out, self.width, self.height, pose)
        return EyeFrame(
            width=self.width,
            height=self.height,
            pixels=bytes(composite_pixels),
        )

    async def _step_async(self) -> EyeFrame:
        frame = self.step()
        await self._display.show(frame)
        return frame

    async def run_forever(self) -> None:
        self._stopped = False
        frame_interval = 1.0 / self.fps
        try:
            while not self._stopped:
                await self._step_async()
                await self.clock.sleep(frame_interval)
        finally:
            self._stopped = True

    def stop(self) -> None:
        self._stopped = True

    def set_calibration(self, calibration: dict[str, ServoCalibration]) -> None:
        self._body.set_calibration(calibration)
        self._overlay = ServoOverlay(calibration=calibration)

DEFAULT_FPS = 30 class-attribute

body property

bus = field(default_factory=InMemoryEventBus) class-attribute instance-attribute

clock = field(default_factory=SystemClock) class-attribute instance-attribute

display property

face property

face_size = 240 class-attribute instance-attribute

fps = DEFAULT_FPS class-attribute instance-attribute

height = 320 class-attribute instance-attribute

is_running property

theme = None class-attribute instance-attribute

width = 240 class-attribute instance-attribute

__init__(bus=InMemoryEventBus(), width=240, height=320, face_size=240, fps=DEFAULT_FPS, clock=SystemClock(), theme=None)

__post_init__()

Source code in src/robot/simulation/driver.py
def __post_init__(self) -> None:
    if self.fps <= 0:
        raise ValueError("fps must be > 0")
    # The mock display receives the composite (face + overlay) frame
    self._display = MockDisplay(width=self.width, height=self.height)
    # The face engine is told the upper portion is the face
    self._renderer = FaceRenderer(width=self.face_size, height=self.face_size)
    # The mock servo bus is calibrated with the default limits
    self._servo_bus = MockServoBus(
        {
            "pan": MockServo(name="pan", min_angle=30.0, max_angle=150.0, _angle=90.0),
            "tilt": MockServo(name="tilt", min_angle=45.0, max_angle=135.0, _angle=90.0),
            "left_arm": MockServo(
                name="left_arm", min_angle=20.0, max_angle=160.0, _angle=90.0
            ),
            "right_arm": MockServo(
                name="right_arm", min_angle=20.0, max_angle=160.0, _angle=90.0
            ),
        }
    )
    servo_controller = wrap_servo_controller(self._servo_bus, backend_name="mock")
    self._body = BodyLanguageEngine(
        servo_controller=servo_controller,
        clock=self.clock,
        calibration=dict(DEFAULT_CALIBRATION),
    )
    # The face animator runs on the (smaller) face panel
    from robot.face.themes.minimal import MinimalTheme

    self._face = FaceAnimator(
        renderer=self._renderer,
        display=MockDisplay(width=self.face_size, height=self.face_size),
        clock=self.clock,
        emotions=EmotionEngine(width=self.face_size, height=self.face_size),
        theme=self.theme or MinimalTheme(),
        fps=self.fps,
        bus=self.bus,
        width=self.face_size,
        height=self.face_size,
    )
    self._overlay = ServoOverlay(calibration=dict(DEFAULT_CALIBRATION))

run_forever() async

Source code in src/robot/simulation/driver.py
async def run_forever(self) -> None:
    self._stopped = False
    frame_interval = 1.0 / self.fps
    try:
        while not self._stopped:
            await self._step_async()
            await self.clock.sleep(frame_interval)
    finally:
        self._stopped = True

set_calibration(calibration)

Source code in src/robot/simulation/driver.py
def set_calibration(self, calibration: dict[str, ServoCalibration]) -> None:
    self._body.set_calibration(calibration)
    self._overlay = ServoOverlay(calibration=calibration)

step()

Advance one frame and return the composite frame.

Source code in src/robot/simulation/driver.py
def step(self) -> EyeFrame:
    """Advance one frame and return the composite frame."""
    face_frame = self._face.step(drift=True)
    pose = self._body.snapshot()
    # The face is square; composite it into a taller canvas that
    # leaves room for the body diagram below.
    out = bytearray(self.width * self.height * 3)
    # Center the face in the upper portion of the canvas
    x_offset = (self.width - self.face_size) // 2
    for y in range(self.face_size):
        src_start = y * self.face_size * 3
        src_end = src_start + self.face_size * 3
        dst_start = (y * self.width + x_offset) * 3
        out[dst_start : dst_start + self.face_size * 3] = face_frame.pixels[src_start:src_end]
    composite_pixels = self._overlay.composite(out, self.width, self.height, pose)
    return EyeFrame(
        width=self.width,
        height=self.height,
        pixels=bytes(composite_pixels),
    )

stop()

Source code in src/robot/simulation/driver.py
def stop(self) -> None:
    self._stopped = True

SystemClock

Production clock backed by :mod:time and :mod:anyio.

Source code in src/robot/utils/clock.py
class SystemClock:
    """Production clock backed by :mod:`time` and :mod:`anyio`."""

    def now(self) -> datetime:
        return datetime.now(tz=UTC)

    def monotonic(self) -> float:
        return time.monotonic()

    async def sleep(self, seconds: float) -> None:
        import anyio

        await anyio.sleep(seconds)

monotonic()

Source code in src/robot/utils/clock.py
def monotonic(self) -> float:
    return time.monotonic()

now()

Source code in src/robot/utils/clock.py
def now(self) -> datetime:
    return datetime.now(tz=UTC)

sleep(seconds) async

Source code in src/robot/utils/clock.py
async def sleep(self, seconds: float) -> None:
    import anyio

    await anyio.sleep(seconds)

Theme

Bases: Protocol

A visual style applied to a :class:FaceModel.

Source code in src/robot/face/themes/base.py
@runtime_checkable
class Theme(Protocol):
    """A visual style applied to a :class:`FaceModel`."""

    @property
    def name(self) -> str:
        """Human-readable theme name."""

    @property
    def palette(self) -> FacePalette:
        """The colour palette the theme uses."""

    def apply(self, model: FaceModel) -> FaceModel:
        """Return ``model`` with the theme's visual style applied."""

name property

Human-readable theme name.

palette property

The colour palette the theme uses.

apply(model)

Return model with the theme's visual style applied.

Source code in src/robot/face/themes/base.py
def apply(self, model: FaceModel) -> FaceModel:
    """Return ``model`` with the theme's visual style applied."""

get_logger(name)

Return a bound logger for the given module name.

The name is prefixed with robot. if it doesn't already start with it, so log records naturally form a hierarchy. The name is also bound into the event context as logger_name so :func:_capture_to_ring_buffer can record it; :func:_strip_logger_name removes it before rendering so the stdout JSON output stays unchanged.

Source code in src/robot/logging.py
def get_logger(name: str) -> structlog.stdlib.BoundLogger:
    """Return a bound logger for the given module name.

    The name is prefixed with ``robot.`` if it doesn't already start with it,
    so log records naturally form a hierarchy. The name is also bound into
    the event context as ``logger_name`` so :func:`_capture_to_ring_buffer`
    can record it; :func:`_strip_logger_name` removes it before rendering so
    the stdout JSON output stays unchanged.
    """
    if not name.startswith("robot."):
        name = f"robot.{name}"
    logger = structlog.get_logger(name).bind(logger_name=name)
    return cast("structlog.stdlib.BoundLogger", logger)

wrap_servo_controller(bus, *, backend_name)

Wrap bus in a :class:ServoController-shaped adapter.

Source code in src/robot/hardware/servos/adapter.py
def wrap_servo_controller(bus: object, *, backend_name: str) -> ServoController:
    """Wrap ``bus`` in a :class:`ServoController`-shaped adapter."""
    return _BusAdapter(bus, backend_name=backend_name)  # type: ignore[arg-type]

Overlay

robot.simulation.overlay

Render a stick-figure visualisation of the four servos.

The overlay draws a simple body diagram (head + neck + two arms) and highlights each servo's current target angle with a coloured line. The result is composited on top of the face framebuffer so a single :class:EyeFrame per frame is enough to drive the simulation display.

SERVO_HEAD_PAN = 'pan' module-attribute

SERVO_HEAD_TILT = 'tilt' module-attribute

SERVO_LEFT_ARM = 'left_arm' module-attribute

SERVO_RIGHT_ARM = 'right_arm' module-attribute

__all__ = ['OverlayConfig', 'ServoOverlay'] module-attribute

OverlayConfig dataclass

Configuration for the stick-figure overlay.

Source code in src/robot/simulation/overlay.py
@dataclass(slots=True, frozen=True)
class OverlayConfig:
    """Configuration for the stick-figure overlay."""

    background: tuple[int, int, int] = (40, 40, 50)
    body_color: tuple[int, int, int] = (220, 220, 230)
    servo_color: tuple[int, int, int] = (255, 180, 60)
    target_color: tuple[int, int, int] = (100, 255, 100)
    pan_color: tuple[int, int, int] = (255, 100, 100)
    tilt_color: tuple[int, int, int] = (100, 100, 255)
    left_arm_color: tuple[int, int, int] = (100, 255, 100)
    right_arm_color: tuple[int, int, int] = (255, 200, 100)

background = (40, 40, 50) class-attribute instance-attribute

body_color = (220, 220, 230) class-attribute instance-attribute

left_arm_color = (100, 255, 100) class-attribute instance-attribute

pan_color = (255, 100, 100) class-attribute instance-attribute

right_arm_color = (255, 200, 100) class-attribute instance-attribute

servo_color = (255, 180, 60) class-attribute instance-attribute

target_color = (100, 255, 100) class-attribute instance-attribute

tilt_color = (100, 100, 255) class-attribute instance-attribute

__init__(background=(40, 40, 50), body_color=(220, 220, 230), servo_color=(255, 180, 60), target_color=(100, 255, 100), pan_color=(255, 100, 100), tilt_color=(100, 100, 255), left_arm_color=(100, 255, 100), right_arm_color=(255, 200, 100))

Pose dataclass

A snapshot of every servo's target angle.

Source code in src/robot/body_language/engine.py
@dataclass(slots=True, frozen=True)
class Pose:
    """A snapshot of every servo's target angle."""

    targets: dict[str, float] = field(default_factory=dict)

    def get(self, name: str, default: float = 90.0) -> float:
        return self.targets.get(name, default)

targets = field(default_factory=dict) class-attribute instance-attribute

__init__(targets=dict())

get(name, default=90.0)

Source code in src/robot/body_language/engine.py
def get(self, name: str, default: float = 90.0) -> float:
    return self.targets.get(name, default)

ServoCalibration dataclass

Per-servo calibration (limits, centre, sign).

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class ServoCalibration:
    """Per-servo calibration (limits, centre, sign)."""

    name: str
    min_angle: float
    max_angle: float
    center_angle: float
    inverted: bool = False

    def clamp(self, angle: float) -> float:
        return max(self.min_angle, min(self.max_angle, angle))

    def normalised(self, angle: float) -> float:
        """Return a value in ``[-1, 1]`` relative to the servo range."""
        half = (self.max_angle - self.min_angle) / 2.0
        if half <= 0:
            return 0.0
        mid = (self.max_angle + self.min_angle) / 2.0
        v = (angle - mid) / half
        return max(-1.0, min(1.0, v))

    def from_normalised(self, value: float) -> float:
        v = max(-1.0, min(1.0, value))
        half = (self.max_angle - self.min_angle) / 2.0
        mid = (self.max_angle + self.min_angle) / 2.0
        if self.inverted:
            v = -v
        return self.clamp(mid + v * half)

center_angle instance-attribute

inverted = False class-attribute instance-attribute

max_angle instance-attribute

min_angle instance-attribute

name instance-attribute

__init__(name, min_angle, max_angle, center_angle, inverted=False)

clamp(angle)

Source code in src/robot/body_language/requests.py
def clamp(self, angle: float) -> float:
    return max(self.min_angle, min(self.max_angle, angle))

from_normalised(value)

Source code in src/robot/body_language/requests.py
def from_normalised(self, value: float) -> float:
    v = max(-1.0, min(1.0, value))
    half = (self.max_angle - self.min_angle) / 2.0
    mid = (self.max_angle + self.min_angle) / 2.0
    if self.inverted:
        v = -v
    return self.clamp(mid + v * half)

normalised(angle)

Return a value in [-1, 1] relative to the servo range.

Source code in src/robot/body_language/requests.py
def normalised(self, angle: float) -> float:
    """Return a value in ``[-1, 1]`` relative to the servo range."""
    half = (self.max_angle - self.min_angle) / 2.0
    if half <= 0:
        return 0.0
    mid = (self.max_angle + self.min_angle) / 2.0
    v = (angle - mid) / half
    return max(-1.0, min(1.0, v))

ServoOverlay

Draw the four-servo stick figure into a face framebuffer.

Source code in src/robot/simulation/overlay.py
class ServoOverlay:
    """Draw the four-servo stick figure into a face framebuffer."""

    def __init__(
        self,
        calibration: dict[str, ServoCalibration],
        config: OverlayConfig | None = None,
    ) -> None:
        self._calibration = calibration
        self._config = config or OverlayConfig()

    def composite(
        self,
        frame_pixels: bytearray,
        width: int,
        height: int,
        pose: Pose,
    ) -> bytearray:
        out = bytearray(frame_pixels)
        body_top = int(height * 0.70)
        self._fill_rect(out, width, height, 0, body_top, width, height, self._config.background)
        cx = width / 2.0
        head_y = body_top + height * 0.04
        neck_y = body_top + height * 0.13
        shoulder_y = body_top + height * 0.18
        waist_y = body_top + height * 0.28
        self._line(out, width, height, cx, head_y, cx, waist_y, self._config.body_color, 4)
        shoulder_half = width * 0.18
        self._line(
            out,
            width,
            height,
            cx - shoulder_half,
            shoulder_y,
            cx + shoulder_half,
            shoulder_y,
            self._config.body_color,
            4,
        )
        pan_target = pose.get(SERVO_HEAD_PAN, 90.0)
        tilt_target = pose.get(SERVO_HEAD_TILT, 90.0)
        left_arm_target = pose.get(SERVO_LEFT_ARM, 90.0)
        right_arm_target = pose.get(SERVO_RIGHT_ARM, 90.0)
        head_tilt = (tilt_target - 90.0) * 0.04
        self._line(out, width, height, cx, neck_y, cx, head_y, self._config.body_color, 4)
        self._circle(out, width, height, cx, head_y, 12, self._config.body_color)
        self._line(
            out,
            width,
            height,
            cx,
            head_y,
            cx + (pan_target - 90.0) * 0.5,
            head_y - 8,
            self._config.pan_color,
            2,
        )
        self._line(
            out,
            width,
            height,
            cx,
            head_y,
            cx,
            head_y - 12 - head_tilt,
            self._config.tilt_color,
            2,
        )
        left_wrist = self._arm_endpoint(
            cx - shoulder_half, shoulder_y, left_arm_target, "left", height * 0.10
        )
        right_wrist = self._arm_endpoint(
            cx + shoulder_half, shoulder_y, right_arm_target, "right", height * 0.10
        )
        self._line(
            out,
            width,
            height,
            cx - shoulder_half,
            shoulder_y,
            *left_wrist,
            self._config.left_arm_color,
            3,
        )
        self._line(
            out,
            width,
            height,
            cx + shoulder_half,
            shoulder_y,
            *right_wrist,
            self._config.right_arm_color,
            3,
        )
        for x, y in (
            (cx - shoulder_half, shoulder_y),
            (cx + shoulder_half, shoulder_y),
            (cx, head_y),
        ):
            self._circle(out, width, height, x, y, 4, self._config.servo_color)
        for name, x, y, color, target in (
            (SERVO_HEAD_PAN, cx, head_y, self._config.pan_color, pan_target),
            (SERVO_HEAD_TILT, cx, head_y, self._config.tilt_color, tilt_target),
            (
                SERVO_LEFT_ARM,
                left_wrist[0],
                left_wrist[1],
                self._config.left_arm_color,
                left_arm_target,
            ),
            (
                SERVO_RIGHT_ARM,
                right_wrist[0],
                right_wrist[1],
                self._config.right_arm_color,
                right_arm_target,
            ),
        ):
            self._draw_target_indicator(
                out, width, height, x, y, target, name in self._calibration, color
            )
        return out

    def _arm_endpoint(
        self, sx: float, sy: float, angle: float, side: str, length: float
    ) -> tuple[float, float]:
        # Left arm extends to the left, right arm to the right.
        # At 90° the arm hangs straight down; higher angles raise it outward.
        sign = -1.0 if side == "left" else 1.0
        rad = math.radians(angle - 90.0)
        dx = sign * length * math.sin(rad)
        dy = length * math.cos(rad)
        return (sx + dx, sy + dy)

    def _draw_target_indicator(
        self,
        out: bytearray,
        width: int,
        height: int,
        x: float,
        y: float,
        target: float,
        calibrated: bool,
        color: tuple[int, int, int],
    ) -> None:
        bar_len = 18
        bar_y = y + 12
        self._line(out, width, height, x - bar_len / 2, bar_y, x + bar_len / 2, bar_y, color, 2)
        if calibrated:
            t = (target - 0.0) / 180.0
            t = max(0.0, min(1.0, t))
            dot_x = x - bar_len / 2 + bar_len * t
            self._circle(out, width, height, dot_x, bar_y, 3, (255, 255, 255))

    def _fill_rect(
        self,
        out: bytearray,
        width: int,
        height: int,
        x0: int,
        y0: int,
        x1: int,
        y1: int,
        color: tuple[int, int, int],
    ) -> None:
        r, g, b = color
        for y in range(max(0, y0), min(height, y1)):
            for x in range(max(0, x0), min(width, x1)):
                idx = (y * width + x) * 3
                out[idx] = r
                out[idx + 1] = g
                out[idx + 2] = b

    def _line(
        self,
        out: bytearray,
        width: int,
        height: int,
        x0: float,
        y0: float,
        x1: float,
        y1: float,
        color: tuple[int, int, int],
        thickness: int = 1,
    ) -> None:
        steps = max(2, int(max(abs(x1 - x0), abs(y1 - y0)) * 2))
        for i in range(steps + 1):
            t = i / steps
            x = x0 + (x1 - x0) * t
            y = y0 + (y1 - y0) * t
            self._dot(out, width, height, x, y, color, thickness)

    def _circle(
        self,
        out: bytearray,
        width: int,
        height: int,
        cx: float,
        cy: float,
        r: float,
        color: tuple[int, int, int],
    ) -> None:
        x0 = max(0, int(cx - r))
        x1 = min(width - 1, int(cx + r))
        y0 = max(0, int(cy - r))
        y1 = min(height - 1, int(cy + r))
        r2 = r * r
        for y in range(y0, y1 + 1):
            for x in range(x0, x1 + 1):
                if (x - cx) ** 2 + (y - cy) ** 2 <= r2:
                    self._set_pixel(out, width, x, y, color)

    def _dot(
        self,
        out: bytearray,
        width: int,
        height: int,
        x: float,
        y: float,
        color: tuple[int, int, int],
        thickness: int = 1,
    ) -> None:
        for dx in range(-thickness // 2, thickness // 2 + 1):
            for dy in range(-thickness // 2, thickness // 2 + 1):
                xx, yy = round(x + dx), round(y + dy)
                if 0 <= xx < width and 0 <= yy < height:
                    self._set_pixel(out, width, xx, yy, color)

    def _set_pixel(
        self,
        out: bytearray,
        width: int,
        x: int,
        y: int,
        color: tuple[int, int, int],
    ) -> None:
        idx = (y * width + x) * 3
        out[idx] = color[0]
        out[idx + 1] = color[1]
        out[idx + 2] = color[2]

__init__(calibration, config=None)

Source code in src/robot/simulation/overlay.py
def __init__(
    self,
    calibration: dict[str, ServoCalibration],
    config: OverlayConfig | None = None,
) -> None:
    self._calibration = calibration
    self._config = config or OverlayConfig()

composite(frame_pixels, width, height, pose)

Source code in src/robot/simulation/overlay.py
def composite(
    self,
    frame_pixels: bytearray,
    width: int,
    height: int,
    pose: Pose,
) -> bytearray:
    out = bytearray(frame_pixels)
    body_top = int(height * 0.70)
    self._fill_rect(out, width, height, 0, body_top, width, height, self._config.background)
    cx = width / 2.0
    head_y = body_top + height * 0.04
    neck_y = body_top + height * 0.13
    shoulder_y = body_top + height * 0.18
    waist_y = body_top + height * 0.28
    self._line(out, width, height, cx, head_y, cx, waist_y, self._config.body_color, 4)
    shoulder_half = width * 0.18
    self._line(
        out,
        width,
        height,
        cx - shoulder_half,
        shoulder_y,
        cx + shoulder_half,
        shoulder_y,
        self._config.body_color,
        4,
    )
    pan_target = pose.get(SERVO_HEAD_PAN, 90.0)
    tilt_target = pose.get(SERVO_HEAD_TILT, 90.0)
    left_arm_target = pose.get(SERVO_LEFT_ARM, 90.0)
    right_arm_target = pose.get(SERVO_RIGHT_ARM, 90.0)
    head_tilt = (tilt_target - 90.0) * 0.04
    self._line(out, width, height, cx, neck_y, cx, head_y, self._config.body_color, 4)
    self._circle(out, width, height, cx, head_y, 12, self._config.body_color)
    self._line(
        out,
        width,
        height,
        cx,
        head_y,
        cx + (pan_target - 90.0) * 0.5,
        head_y - 8,
        self._config.pan_color,
        2,
    )
    self._line(
        out,
        width,
        height,
        cx,
        head_y,
        cx,
        head_y - 12 - head_tilt,
        self._config.tilt_color,
        2,
    )
    left_wrist = self._arm_endpoint(
        cx - shoulder_half, shoulder_y, left_arm_target, "left", height * 0.10
    )
    right_wrist = self._arm_endpoint(
        cx + shoulder_half, shoulder_y, right_arm_target, "right", height * 0.10
    )
    self._line(
        out,
        width,
        height,
        cx - shoulder_half,
        shoulder_y,
        *left_wrist,
        self._config.left_arm_color,
        3,
    )
    self._line(
        out,
        width,
        height,
        cx + shoulder_half,
        shoulder_y,
        *right_wrist,
        self._config.right_arm_color,
        3,
    )
    for x, y in (
        (cx - shoulder_half, shoulder_y),
        (cx + shoulder_half, shoulder_y),
        (cx, head_y),
    ):
        self._circle(out, width, height, x, y, 4, self._config.servo_color)
    for name, x, y, color, target in (
        (SERVO_HEAD_PAN, cx, head_y, self._config.pan_color, pan_target),
        (SERVO_HEAD_TILT, cx, head_y, self._config.tilt_color, tilt_target),
        (
            SERVO_LEFT_ARM,
            left_wrist[0],
            left_wrist[1],
            self._config.left_arm_color,
            left_arm_target,
        ),
        (
            SERVO_RIGHT_ARM,
            right_wrist[0],
            right_wrist[1],
            self._config.right_arm_color,
            right_arm_target,
        ),
    ):
        self._draw_target_indicator(
            out, width, height, x, y, target, name in self._calibration, color
        )
    return out