aboutsummaryrefslogtreecommitdiff
path: root/docs/input.org
blob: 809994f0a4394b0eaab90956b500bc3731839d08 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
#+TITLE: Input

Downstroke's input system is *action-based*. Your game never asks "is
the =W= key held?" — it asks "is the =up= action held?". A single
=input-config= record decides which raw SDL events (keyboard keys,
joystick buttons, controller buttons, analog axes) map to which
abstract action symbols, so the same update loop works on keyboard,
joystick, and game controller without changes.

Each frame, the engine collects pending SDL events, folds them into a
fresh =input-state= record (current + previous action alists), and
stores it on the =game= struct. Your =update:= hook reads that state
through =game-input=.

* The minimum you need

#+begin_src scheme
(import (downstroke engine)
        (downstroke input)
        (downstroke world)
        (downstroke entity))

(game-run!
 (make-game
  title: "Move a Square" width: 320 height: 240

  create: (lambda (game)
            (game-scene-set! game
              (make-sprite-scene
               entities: (list (plist->alist
                                (list #:type 'player
                                      #:x 150 #:y 100
                                      #:width 32 #:height 32
                                      #:color '(100 160 255)))))))

  update: (lambda (game dt)
            (let* ((scene  (game-scene game))
                   (input  (game-input game))
                   (player (car (scene-entities scene)))
                   (dx (cond ((input-held? input 'left)  -2)
                             ((input-held? input 'right)  2)
                             (else 0))))
              (game-scene-set! game
                (update-scene scene
                  entities: (list (entity-set player #:x
                                    (+ (entity-ref player #:x 0) dx))))))) ))
#+end_src

No =input-config:= keyword is passed, so =*default-input-config*= is
used: arrow keys, WASD, =j=/=z= for =a=, =k=/=x= for =b=, =return= for
=start=, =escape= for =quit=, plus a standard game-controller mapping.

* Core concepts

** Actions vs raw keys

An *action* is a symbol that names something the game cares about
(=up=, =a=, =start=). A *key binding* (or button/axis binding) maps a
raw hardware event to an action. Game code only ever reads actions —
raw SDL keysyms never leak into your =update:= hook.

The default action list, defined in =*default-input-config*=, is:

#+begin_src scheme
'(up down left right a b start select quit)
#+end_src

These map loosely to a generic two-button gamepad: a D-pad (=up=,
=down=, =left=, =right=), two face buttons (=a=, =b=), two system
buttons (=start=, =select=), and a synthetic =quit= action the engine
uses to terminate =game-run!= (the default loop exits when =quit= is
held).

You are free to add or rename actions when you build a custom
=input-config= — the action list is just the set of symbols your game
agrees to recognise.

** The default input config

=*default-input-config*= is a =input-config= record bound at module
load time in =input.scm=. Its contents:

*Keyboard map* (SDL keysym → action):

| Keys             | Action  |
|------------------+---------|
| =w=, =up=        | =up=    |
| =s=, =down=      | =down=  |
| =a=, =left=      | =left=  |
| =d=, =right=     | =right= |
| =j=, =z=         | =a=     |
| =k=, =x=         | =b=     |
| =return=         | =start= |
| =escape=         | =quit=  |

*Joystick button map* (SDL joy button id → action). These ids suit a
generic USB pad in the "SNES-ish" layout:

| Button id | Action   |
|-----------+----------|
| =0=       | =a=      |
| =1=       | =b=      |
| =7=       | =start=  |
| =6=       | =select= |

*Game-controller button map* (SDL =SDL_GameController= symbol →
action). This is the "Xbox-style" API SDL2 exposes for known
controllers:

| Button       | Action   |
|--------------+----------|
| =a=          | =a=      |
| =b=          | =b=      |
| =start=      | =start=  |
| =back=       | =select= |
| =dpad-up=    | =up=     |
| =dpad-down=  | =down=   |
| =dpad-left=  | =left=   |
| =dpad-right= | =right=  |

*Analog axis bindings.* Each binding is =(axis positive-action
negative-action)= — when the axis value exceeds the deadzone, the
positive action is held; when it drops below the negated deadzone, the
negative action is held.

- Joystick: =(0 right left)= and =(1 down up)= (X and Y axes).
- Controller: =(left-x right left)= and =(left-y down up)= (left
  analog stick).

*Deadzone* is =8000= (SDL axis values range −32768 to 32767).

All of these are accessible via =input-config-keyboard-map=,
=input-config-joy-button-map=, and so on, but you generally won't
touch them directly — you pass a whole replacement record via
=make-input-config= (see below).

** Querying input each frame

The engine calls =input-state-update= once per frame with the SDL
events it has just collected. That produces a new =input-state= record
and stores it on the game via =game-input-set!=. Your =update:= hook
reads it with =(game-input game)=:

#+begin_src scheme
(update: (lambda (game dt)
           (let ((input (game-input game)))
             ...)))
#+end_src

Three predicates live on an =input-state=:

- =(input-held? state action)= — ~#t~ while the action is currently
  active (key/button down, axis past deadzone).
- =(input-pressed? state action)= — ~#t~ for exactly one frame: the
  frame on which the action transitioned from not-held to held.
- =(input-released? state action)= — ~#t~ for exactly one frame: the
  frame on which the action transitioned from held to not-held.

Press / release are derived from the record itself: =input-state=
carries both a =current= and =previous= alist of =(action . bool)=
pairs, and =input-state-update= rolls the previous snapshot forward
each frame. You do not need to maintain any input history yourself.

A fourth convenience, =(input-any-pressed? state config)=, returns
~#t~ if /any/ action in the config's action list transitioned to
pressed this frame — useful for "press any key to continue" screens.

The call shape throughout the demos is:

#+begin_src scheme
(input-held?     (game-input game) 'left)
(input-pressed?  (game-input game) 'a)
(input-released? (game-input game) 'start)
#+end_src

** Customising the input config

Build a replacement config with =make-input-config= and pass it to
=make-game= via the =input-config:= keyword:

#+begin_src scheme
(define my-input
  (make-input-config
    actions: '(up down left right fire pause quit)
    keyboard-map: '((up    . up)     (w . up)
                    (down  . down)   (s . down)
                    (left  . left)   (a . left)
                    (right . right)  (d . right)
                    (space . fire)
                    (p     . pause)
                    (escape . quit))
    joy-button-map:          '()
    controller-button-map:   '()
    joy-axis-bindings:       '()
    controller-axis-bindings: '()
    deadzone: 8000))

(make-game
  title: "Custom Controls"
  input-config: my-input
  ...)
#+end_src

All seven slots are required, but any of the map/binding slots can be
empty (~'()~) if you don't want that input type. The =actions= list
determines which symbols =input-any-pressed?= sweeps, and seeds the
initial =input-state= with an entry per action.

If you want to *extend* the defaults instead of replacing them, pull
each slot off =*default-input-config*= and cons your extra entries:

#+begin_src scheme
(define my-input
  (make-input-config
    actions: (input-config-actions *default-input-config*)
    keyboard-map: (cons '(space . a)
                        (input-config-keyboard-map *default-input-config*))
    joy-button-map: (input-config-joy-button-map *default-input-config*)
    controller-button-map: (input-config-controller-button-map *default-input-config*)
    joy-axis-bindings: (input-config-joy-axis-bindings *default-input-config*)
    controller-axis-bindings: (input-config-controller-axis-bindings *default-input-config*)
    deadzone: (input-config-deadzone *default-input-config*)))
#+end_src

* Common patterns

** Arrow-key movement

Straight from =demo/getting-started.scm=: test each horizontal and
vertical direction independently, pick a signed step, and write back
the updated position.

#+begin_src scheme
(define +speed+ 2)

(define (move-player player input)
  (let* ((x  (entity-ref player #:x 0))
         (y  (entity-ref player #:y 0))
         (dx (cond ((input-held? input 'left)  (- +speed+))
                   ((input-held? input 'right)    +speed+)
                   (else 0)))
         (dy (cond ((input-held? input 'up)    (- +speed+))
                   ((input-held? input 'down)     +speed+)
                   (else 0))))
    (entity-set (entity-set player #:x (+ x dx)) #:y (+ y dy))))
#+end_src

** Jump on press vs move while held

The platformer distinguishes a /continuous/ action (running left/right
while =left=/=right= are held) from an /edge-triggered/ action
(jumping exactly once when =a= is first pressed):

#+begin_src scheme
(define (player-vx input)
  (cond ((input-held? input 'left)  -3)
        ((input-held? input 'right)  3)
        (else 0)))

(define (update-player player input)
  (let* ((jump? (and (input-pressed? input 'a)
                     (entity-ref player #:on-ground? #f)))
         (player (entity-set player #:vx (player-vx input))))
    (if jump?
        (entity-set player #:ay (- *jump-force*))
        player)))
#+end_src

Using =input-pressed?= instead of =input-held?= prevents the player
from "spamming" the jump simply by keeping =a= depressed — the action
must be released and re-pressed to fire again.

The same pattern shows up in =demo/shmup.scm= for firing bullets:

#+begin_src scheme
(if (input-pressed? input 'a)
    (values updated (list (make-bullet ...)))
    (values updated '()))
#+end_src

** Controller + keyboard simultaneously

The default config registers bindings for keyboard, joystick, /and/
game controller at the same time — no configuration switch, no "input
device" concept. Whichever device fires an event first on a given
frame sets the corresponding action, and the next frame reflects it.
You get controller support for free as long as you keep the default
config (or carry its =joy-*= / =controller-*= slots forward into your
custom config).

=game-run!= opens every connected game controller at startup, and
=handle-controller-device= opens any controller hot-plugged during the
session, so no extra wiring is needed.

** Remapping a single action

To let players press =space= for =start= instead of =return=, override
just the keyboard map (keeping the rest of the defaults):

#+begin_src scheme
(define my-input
  (make-input-config
    actions: (input-config-actions *default-input-config*)
    keyboard-map:
      '((w . up) (up . up)
        (s . down) (down . down)
        (a . left) (left . left)
        (d . right) (right . right)
        (j . a) (z . a)
        (k . b) (x . b)
        (space . start)         ;; was (return . start)
        (escape . quit))
    joy-button-map:          (input-config-joy-button-map *default-input-config*)
    controller-button-map:   (input-config-controller-button-map *default-input-config*)
    joy-axis-bindings:       (input-config-joy-axis-bindings *default-input-config*)
    controller-axis-bindings: (input-config-controller-axis-bindings *default-input-config*)
    deadzone:                (input-config-deadzone *default-input-config*)))

(make-game
  title: "Remapped Start"
  input-config: my-input
  ...)
#+end_src

Multiple keys can map to the same action (the defaults already do
this: both =w= and =up= trigger =up=), so another approach is to add
=(space . start)= /alongside/ the existing =(return . start)= entry
instead of replacing it.

* Demos

- [[https://git.etenil.net/downstroke/tree/demo/getting-started.scm][Getting started]] (=bin/demo-getting-started=) — arrow-key movement with =input-held?=.
- [[https://git.etenil.net/downstroke/tree/demo/platformer.scm][Platformer]] (=bin/demo-platformer=) — mixes =input-held?= for running with =input-pressed?= for jumping.
- [[https://git.etenil.net/downstroke/tree/demo/shmup.scm][Shmup]] (=bin/demo-shmup=) — uses =input-pressed?= on =a= to fire bullets exactly once per button press.

* See also

- [[file:guide.org][Getting-started guide]] — the full walkthrough that
  builds the minimal input example above.
- [[file:entities.org][Entities]] — the =#:input-map= entity key and
  =apply-input-to-entity= hook for data-driven movement.
- [[file:physics.org][Physics]] — how velocities set by input feed into
  the built-in physics pipeline.
- [[file:scenes.org][Scenes]] — how =game-input= fits alongside
  =game-scene= in the =update:= hook.