Package: panda3d-keybindings
panda3d-keybindingsPanda3D comes with a nice API suite to work with input devices. In
particular, it has one for USB HIDs, and one for mouse and keyboard.
What it does not have is a mechanism to build an abstraction over these
devices, so that a developer can define them in terms of a set of
buttons and axes, and it is a matter of configuration how actual inputs
on devices are mapped to those abstract inputs. A game's logic should
not be concerned with details like...whether a 2D axis gets its values from a gamepad's stick or its four
buttons, from WASD, or a dance pad.how the player wants the inputs from the devices combined. There may
be a different list of priorities for different abstract inputs with
regard what devices should be checked. A player may prefer to control
character movement on a gamepad, but functions like invoking and
working in menus with the keyboard.how input is preprocessed. Badly manufactured sticks create noise near
the center, and may require a dead zone. An axis' amplitude may need
to be scaled or squared.devices connecting or disconnecting. From a game developer's
perspective, these events should be dealt with under the hood.how devices are identified. A player may use two flight sticks for a
space simulator. If they're of different makes, they can be identified
"uniquely", and should be mappable independent of one another. Even
with two identical sticks, there should be a way to check which is
which ("Press trigger on left stick"), and label them accordingly.
NOTE: Not implemented yet. May currently be impossible to do cleanly.
Uncleanly, Vendor/Product IDs could be used for devices of different
makes.providing an interface to work with the mappings.
NOTE: Menu to display the current configuration exists, and
functionality to save the current configuration back to file. The
DeviceListener's API to change bindings, and menu functionality to do
so, are missing. Seeexamples/menu/.if the state, when polled at different times during a frame, is still
the same; It just should be. This is quite an edge case, but may cause
hard to reproduce bugs.StatusThis project's state is alpha, as features are still being added and its
specifications are liable to change. That being said, it is close to
reaching beta.Installationpip install panda3d-keybindingsConceptsAvirtual inputis an input with a semantic to the game, like
jumping, turning around moving, etc.; It hasa type, which is one ofbutton:Trueif the button is pressed,Falseotherwise.trigger:Truefor the frame in which the button is pressed.repeater:Truewhenever its interval elapses and the button is
still pressed.axis: Afloat.axis2d:panda3d.core.Vec2.axis3d:panda3d.core.Vec3.a list of mappings ordered by priority in which they are checked for
their device being present, and whether they have a non-zero / False
input value.a sensor definition for each mapping. This defines the buttons /
axes used, and specifies post-processing that is to be done on them.Acontextis a set ofvirtual inputs that is read together. It is
an organizational unit to make it easy for the application to activate
or deactivate parts of the user input interface. For example, opening
the game's ingame menu may activate themenucontext, and deactivate
thecharacter_movementone.When a device is connected, it is assigned to aplayer, or kept
unassigned for the time being. Players will only be able to read data
from devices assigned to them.
NOTE: Currently only single-player assigners exist off-the-shelf.There's a configuration file that defines for eachplayerand eachcontextthevirtual_inputsand in what order to read their
mappings. If no readable device is present for avirtual_input, its
value will beNone, otherwise the first mapping with a value other
than a zero value orFalsedetermines the final value. If all
devices have a value of zero orFalse, that will be returned.
In other words, the highest-priority mapping that the player uses is
used.
NOTE: Currently no concept of players exists in the config file.ExampleSetting up an application for use with this module is easy:from direct.showbase.ShowBase import ShowBase
from keybindings.device_listener import add_device_listener
from keybindings.device_listener import SinglePlayerAssigner

ShowBase()
add_device_listener(
    assigner=SinglePlayerAssigner(),
)Now there is abase.device_listener. It assumes that the configuration
file is namedkeybindings.configand is present in the application'sbase.main_dir, and it creates a task atsort=-10that freezes this
frame's input state. Other names file names and ways to handle freezing
can be configured.
NOTE: Don't remember off the top of my head how true that is.A keybinding configuration could look like this:context demo_context
  button demo_button
    gamepad         face_a
    flight_stick    trigger
    keyboard        qWhen the contextdemo_contextis read, ...base.device_listener.read_context('demo_context')...the result may look like this:{'demo_button': False}This means that due to the config snippet above, the device listener has
checked whether a gamepad is connected; If so, the state offace_ais
used, if not, theflight_stickis tested next, and so on. In this
example, a device has been found and the button has not been pressed.Configuration File in DetailAs mentioned above, this is a simple configuration file:context demo_context
  button demo_button
    gamepad         face_a
    flight_stick    trigger
    keyboard        qThecontextheader indicates the name of the context.The virtual input header below it defines both its type and name. As
mentioned above, valid types arebutton,trigger,axis,axis2d,
andaxis3d. There is alsorepeater, which takes two additional
arguments, separated by:characters. The first is the initial
cooldown, the second the repeating cooldown. When its button is pressed,
and then kept pressed, it will returnTruein the first frame, then
again for one frame after the initial cooldown has passed, and
thereafter whenever the repeating cooldown has passed. For example, a
repeater that fires after one second, and then every half second, would
readrepeater:1.0:0.5.The mapping lines each start with a device name as managed by the
assigner (by default Panda3D's device type names are used, pluscallback, see below), and then has one sensor for each dimension of
the input.button,trigger,repeater, andaxisare
one-dimensional, andaxis2dandaxis3dare two- and
three-dimensional respectively. However, in the case of axes, pairs of
buttons can be used instead. For example:context demo_context
  axis turning
    gamepad         right_x
    keyboard        arrow_left arrow_rightThe arrow buttons will now be read, and their combined value of -1, 0,
or 1 will be determined.Sensor names are as provided by Panda3D. Access to the mouse is given
via the sensorsmouse_x,mouse_y,mouse_x_delta, andmouse_y_delta, with the two latter tracking frame-to-frame changes
(without respect to frame time). For keyboard keys, raw keys may be
accessed by prefixing the name withraw-. NOTE: Raw keys will be
supported in Panda3D1.11.Each sensor may also be post-processed after being read. Each such step
is indicated with a flag, some of which may bear a numeric argument, and
they are again separated by:characters. For example,right_x:flipwould invert the axis (multiplying it with -1), whileright_x:deadzone=0.02would turn all results between -0.02 and 0.02 to
0.0.flipmultiplies an axis value (float) with -1, and has no argument.scalemultiplies an axis value with its argument.button<andbutton>turn axis values into button values (boolean),
returning True if the axis value is greater / smaller or equal to the
argument; e.g.right_x:button>=0.75will trigger when the stick is
pressed far enough to the right.expmagnifies the magnitude to the power of the argument. For
exampleright_x:exp=2would square the axis value, but preserve its
sign; -0.5 would be turned into -0.25, while -1, 0, and 1 are
preserved.deadzone, as explained above, turns axis values within the
argument's range into 0.0. Without this, a stick could read at a very
low value, but still be the final value, while the player actually
wants to use a lower-priority device.Controlling the ReadThere are two aspects about reading and freezing the state: When it is
done, and how much time it should assume to have passed.By default, a task is created atsort=-10. If you want to want to use
another value, you can pass a dict or arguments toadd_device_listenerto be passed on to the task creation.add_device_listener(task_args=dict(sort=-1, priority=1))If you want instead to control yourself when the input is frozen, you
can passtask=False, and then callbase.device_listener.read()yourself.Either way by defaultglobalClock.dtwill be used to determine how
much time has elapsed. If you want to determine that by yourself as well
(which I would warn against; We're talking about inputs here, not the
game world's clock), youwillhave to use your own call as described
above, and pass adtargument indicating the elapsed time. For a
trivial example, seeexamples/minimal/main_2_manual_task.py.CallbacksSo that's all fine and dandy for typical input devices. What if you want
to treat something else entirely as an input device? As long as you can
provide a function that takes no arguments, and returns a valid axis or
button state, we have you covered.You can pass a dict with name -> function entries during startup:add_device_listener(
    callbacks=dict(
	    my_sensor=read_sensors_value,
),
)...or you can add and remove them at runtime:base.device_listener.set_callback('my_sensor', read_sensors_value)
base.device_listener.del_callback('my_sensor')Then in the keybindings.config, usecallbackas device type, e.g.:context demo_context
  button my_weird_button
    callback        my_sensorIf no function is currently provided for a sensor, it will be treated
like a disconnected device.An example showing how DirectGui widgets can be used as sensors is
provided inexamples/callbacks/.TODOdoubleclickandmulticlickvirtual input typesspeed/acceleration-based postprocessors. Click if axis changes fast
enough.Click-and-drag support for mouseUniquely identifying devices, and remove the NOTE aboveChanging bindings at run timeUpdate DeviceListener / Assigner APIAdd menu functionalityRemove the NOTE aboveSphinx documentationThrow eventssetup.py: Go overpackages=again.Multiplayer; Might need a full refactor.Assignerconfig fileRemove the NOTEs above