Controller Tester.

Reads a game controller directly, every frame, and draws what it reports: both sticks as a crosshair in a circle, the analogue triggers as fill bars and every standard button as a dot that lights while it is held.

▶ Run in browser

Tags: input controller touch polling

A game normally binds actions and never touches a pad directly. Reading the pad itself is for what a binding cannot say: which pad a local co-op player is holding, what to print on a button prompt, or a tester like this one.

Input.controllers maps an engine id to a ControllerDevice for every pad readable right now, so plugging a pad in or pulling it out shows up at once. The readout follows the pad with the lowest id. Each pad answers for itself:

  • pad.stick(Controller.LEFT_STICK, deadzone=0.15) is a Vec2, each axis -1 to 1 with +y down the screen, zeroed inside a radial deadzone (the small circle in each stick).

  • pad.axis(Controller.LEFT_TRIGGER) is one raw axis; a trigger reads 0 released and 1 fully pulled.

  • pad.pressed(Controller.A) is whether a button is held.

  • pad.name, pad.source and pad.family describe the pad, and pad.label(button) is what that family prints on the button, so the dots read “Cross” on a PlayStation pad where an Xbox pad reads “A”.

These named controls exist only on a pad a controller database recognised (pad.recognised). Any other device has only Controller.button(i) and Controller.axis(i), and asking it for Controller.A raises, so the tester reports such a pad’s button and axis counts instead of the readout.

A TouchController along the bottom is a pad as well: while it is on screen it is listed in Input.controllers with source ControllerSource.VIRTUAL, so the readout has something to show with no controller in the room. Its two sticks and Start answer to fingers, and it leaves the screen the moment a real pad is used.

Source

  1# /// simvx
  2# tags = ["input", "controller", "touch", "polling"]
  3# web = { width = 960, height = 540, responsive = true }
  4# ///
  5"""Controller Tester.
  6
  7Reads a game controller directly, every frame, and draws what it reports: both
  8sticks as a crosshair in a circle, the analogue triggers as fill bars and every
  9standard button as a dot that lights while it is held.
 10
 11A game normally binds actions and never touches a pad directly. Reading the pad
 12itself is for what a binding cannot say: which pad a local co-op player is
 13holding, what to print on a button prompt, or a tester like this one.
 14
 15`Input.controllers` maps an engine id to a `ControllerDevice` for every pad
 16readable right now, so plugging a pad in or pulling it out shows up at once.
 17The readout follows the pad with the lowest id. Each pad answers for itself:
 18
 19- `pad.stick(Controller.LEFT_STICK, deadzone=0.15)` is a `Vec2`, each axis -1
 20  to 1 with +y down the screen, zeroed inside a radial deadzone (the small
 21  circle in each stick).
 22- `pad.axis(Controller.LEFT_TRIGGER)` is one raw axis; a trigger reads 0
 23  released and 1 fully pulled.
 24- `pad.pressed(Controller.A)` is whether a button is held.
 25- `pad.name`, `pad.source` and `pad.family` describe the pad, and
 26  `pad.label(button)` is what that family prints on the button, so the dots
 27  read "Cross" on a PlayStation pad where an Xbox pad reads "A".
 28
 29These named controls exist only on a pad a controller database recognised
 30(`pad.recognised`). Any other device has only `Controller.button(i)` and
 31`Controller.axis(i)`, and asking it for `Controller.A` raises, so the tester
 32reports such a pad's button and axis counts instead of the readout.
 33
 34A `TouchController` along the bottom is a pad as well: while it is on screen it
 35is listed in `Input.controllers` with source `ControllerSource.VIRTUAL`, so the
 36readout has something to show with no controller in the room. Its two sticks
 37and Start answer to fingers, and it leaves the screen the moment a real pad is
 38used.
 39"""
 40
 41from simvx.core import Controller, DeviceAxis, DeviceStick, Input, Node2D
 42from simvx.core.ui import TouchController, TouchControllerLayout
 43
 44#: Every button on a standard controller, drawn as a dot with its label under it.
 45BUTTONS = (
 46    Controller.A, Controller.B, Controller.X, Controller.Y,
 47    Controller.LEFT_BUMPER, Controller.RIGHT_BUMPER, Controller.LEFT_THUMB, Controller.RIGHT_THUMB,
 48    Controller.BACK, Controller.START, Controller.GUIDE,
 49    Controller.DPAD_UP, Controller.DPAD_DOWN, Controller.DPAD_LEFT, Controller.DPAD_RIGHT,
 50)  # fmt: skip
 51
 52#: The narrowest gap between two dots, wide enough for the longest label ("D-Pad Down").
 53BUTTON_PITCH = 110.0
 54
 55#: The vertical distance between two rows of dots.
 56ROW_PITCH = 64.0
 57
 58#: The radial deadzone the sticks are read with.
 59DEADZONE = 0.15
 60
 61#: How much of the window the readout takes; the drawn pad has the rest.
 62READOUT_BAND = 0.64
 63
 64DIM = (0.42, 0.45, 0.52, 1.0)
 65BRIGHT = (0.90, 0.93, 1.00, 1.0)
 66ACTIVE = (0.30, 0.85, 0.45, 1.0)
 67MARKER = (1.00, 0.75, 0.20, 1.0)
 68WARN = (1.00, 0.65, 0.25, 1.0)
 69
 70
 71class ControllerTester(Node2D):
 72    """Live readout of one controller, read through its ControllerDevice every frame."""
 73
 74    dynamic = True  # every reading can change every frame
 75
 76    def on_ready(self):
 77        # Two sticks and Start; no face buttons, which leaves the readout room.
 78        self.add_child(TouchController(layout=TouchControllerLayout.TWIN_STICK, buttons=()))
 79
 80    def on_draw(self, renderer):
 81        width, height = self.viewport_size
 82        renderer.text("Controller Tester", (20, 14), fill=BRIGHT, scale=2)
 83
 84        pads = Input.controllers
 85        if not pads:
 86            renderer.text("no controller connected: plug one in", (width / 2, 48), fill=WARN, align="centre")
 87            return
 88        pad = pads[min(pads)]
 89        ids = ", ".join(str(i) for i in sorted(pads))
 90        # Two short lines rather than one long one, so a phone held upright shows all of it.
 91        renderer.text(f"pad {pad.id}: {pad.name or 'unnamed'}", (width / 2, 50), fill=ACTIVE, align="centre")
 92        details = f"{pad.family}, {pad.source}   connected ids: {ids}"
 93        renderer.text(details, (width / 2, 68), fill=ACTIVE, align="centre")
 94        if not pad.recognised:
 95            # No database laid this pad out, so it has no Controller.A to ask about, only numbered controls.
 96            note = f"not recognised: {len(pad.buttons)} buttons and {len(pad.axes)} axes, read by number"
 97            renderer.text(note, (width / 2, 96), fill=WARN, align="centre")
 98            return
 99
100        # The buttons wrap into as many rows as the width needs, the last one ending at the band.
101        margin = max(width * 0.08, BUTTON_PITCH / 2)  # room for half a label beyond the outer dots
102        per_row = max(2, int((width - 2 * margin) // BUTTON_PITCH) + 1)
103        rows = [BUTTONS[i : i + per_row] for i in range(0, len(BUTTONS), per_row)]
104
105        # Top to bottom: sticks and triggers, their readings, then the rows of buttons.
106        top, bottom = 110.0, height * READOUT_BAND
107        buttons_y = bottom - 38 - (len(rows) - 1) * ROW_PITCH
108        # Bounded by width too, so the sticks (0.4w apart) and the edge triggers never meet on a tall window.
109        radius = max(24.0, min(width * 0.13, (buttons_y - top - 64) / 2))
110        stick_y = top + radius
111        self._draw_stick(renderer, pad, Controller.LEFT_STICK, "left", (width * 0.3, stick_y), radius)
112        self._draw_stick(renderer, pad, Controller.RIGHT_STICK, "right", (width * 0.7, stick_y), radius)
113        self._draw_trigger(renderer, pad, Controller.LEFT_TRIGGER, (width * 0.045, top), radius * 2)
114        self._draw_trigger(renderer, pad, Controller.RIGHT_TRIGGER, (width * 0.92, top), radius * 2)
115        self._draw_buttons(renderer, pad, rows, margin, width - 2 * margin, buttons_y)
116
117    def _draw_stick(self, renderer, pad, stick: DeviceStick, side: str, centre, r: float):
118        cx, cy = centre
119        v = pad.stick(stick, deadzone=DEADZONE)
120        renderer.circle((cx, cy), r, stroke=DIM, segments=48)
121        renderer.circle((cx, cy), r * DEADZONE, stroke=DIM, segments=24)
122        renderer.line((cx - r, cy), (cx + r, cy), stroke=DIM)
123        renderer.line((cx, cy - r), (cx, cy + r), stroke=DIM)
124
125        tip = (cx + v.x * r, cy + v.y * r)
126        colour = MARKER if v.length() > 0.0 else BRIGHT
127        renderer.line((cx, cy), tip, stroke=colour, width=2.0)
128        renderer.circle(tip, 7, fill=colour, segments=20)
129        renderer.text(f"{side} stick", (cx, cy + r + 14), fill=BRIGHT, align="centre")
130        renderer.text(f"({v.x:+.2f}, {v.y:+.2f})", (cx, cy + r + 32), fill=DIM, align="centre")
131
132    def _draw_trigger(self, renderer, pad, axis: DeviceAxis, corner, height: float):
133        x, top = corner
134        width = 32.0
135        value = pad.axis(axis)  # already the fill fraction: 0 released, 1 fully pulled
136        renderer.rect((x, top), (width, height), stroke=DIM)
137        if value > 0.0:
138            renderer.rect((x, top + height * (1.0 - value)), (width, height * value), fill=ACTIVE)
139        renderer.text(pad.label(axis), (x + width / 2, top - 22), fill=BRIGHT, align="centre")
140        renderer.text(f"{value:.2f}", (x + width / 2, top + height + 10), fill=DIM, align="centre")
141
142    def _draw_buttons(self, renderer, pad, rows, left: float, span: float, top: float):
143        spacing = span / (max(len(row) for row in rows) - 1)  # every row on the first row's columns
144        for row_index, row in enumerate(rows):
145            y = top + row_index * ROW_PITCH
146            for i, button in enumerate(row):
147                x = left + i * spacing
148                if pad.pressed(button):
149                    renderer.circle((x, y), 12, fill=ACTIVE, segments=24)
150                else:
151                    renderer.circle((x, y), 12, stroke=DIM, segments=24)
152                renderer.text(pad.label(button), (x, y + 16), fill=DIM, align="centre")
153
154
155if __name__ == "__main__":
156    from simvx.graphics import App
157
158    App(title="Controller Tester", width=960, height=540).run(ControllerTester())