more musical pong. uhm ping.
[ardour.git] / scripts / _pong.lua
1 ardour {
2         ["type"]    = "dsp",
3         name        = "a-Pong",
4         category    = "Toy",
5         license     = "MIT",
6         author      = "Ardour Lua Task Force",
7         description = [[A console classic for your console]]
8 }
9
10 -- return possible i/o configurations
11 function dsp_ioconfig ()
12         -- -1, -1 = any number of channels as long as input and output count matches
13         return { [1] = { audio_in = -1, audio_out = -1}, }
14 end
15
16 -- control port(s)
17 function dsp_params ()
18         return
19         {
20                 { ["type"] = "input", name = "Bar", min = 0, max = 1, default = 0.5 },
21                 { ["type"] = "input", name = "Reset", min = 0, max = 1, default = 0, toggled = true },
22                 { ["type"] = "input", name = "Difficulty", min = 1, max = 10, default = 3},
23         }
24 end
25
26
27 -- Game State (for this instance)
28 -- NOTE: these variables are for the DSP part (not shared with the GUI instance)
29 local sample_rate -- sample-rate
30 local fps -- audio samples per game-step
31 local game_time -- counts up to fps
32 local game_score
33 local ball_x, ball_y -- ball position [0..1]
34 local dx, dy -- current ball speed
35 local lost_sound -- audio-sample counter for game-over [0..3*fps]
36 local ping_sound -- audio-sample counter for ping-sound [0..fps]
37 local ping_phase -- ping note phase-difference per sample
38 local ping_pitch
39
40 function dsp_init (rate)
41         -- allocate a "shared memory" area to transfer state to the GUI
42         self:shmem ():allocate (3)
43         self:shmem ():clear ()
44         -- initialize some variables
45         sample_rate = rate
46         fps = rate / 25
47         ping_pitch = 752 / rate
48         ball_x = 0.5
49         ball_y = 0
50         dx = 0.00367
51         dy = 0.01063
52         game_score = 0
53         game_time  = fps -- start the ball immediately (notify GUI)
54         ping_sound = fps -- set to end of synth cycle
55         lost_sound = 3 * fps
56 end
57
58 function queue_beep ()
59         -- queue 'ping' sound (unless one is already playing to prevent clicks)
60         if (ping_sound >= fps) then
61                 ping_sound = 0
62                 ping_phase = 0
63                 local midi_note = math.floor (60 + math.random () * 24)
64                 ping_pitch = (440 / 32) * 2^((midi_note - 10.0) / 12.0) / sample_rate
65         end
66 end
67
68 -- callback: process "n_samples" of audio
69 -- ins, outs are http://manual.ardour.org/lua-scripting/class_reference/#C:FloatArray
70 -- pointers to the audio buffers
71 function dsp_run (ins, outs, n_samples)
72         local ctrl = CtrlPorts:array () -- get control port array (read/write)
73
74         local changed = false -- flag to notify GUI on every game-step
75         game_time = game_time + n_samples
76
77         -- reset (allow to write automation from a given start-point)
78         -- ctrl[2] corresponds to the  "Reset" input control
79         if ctrl[2] > 0 then
80                 game_time = 0
81                 ball_x = 0.5
82                 ball_y = 0
83                 dx = 0.00367
84                 dy = 0.01063
85                 game_score = 0
86         end
87
88         -- simple game engine
89         while game_time > fps and ctrl[2] <= 0 do
90                 changed = true
91                 game_time = game_time - fps
92
93                 -- move the ball
94                 ball_x = ball_x + dx * ctrl[3]
95                 ball_y = ball_y + dy * ctrl[3]
96
97                 -- reflect left/right
98                 if ball_x >= 1 or ball_x <= 0 then
99                         dx = -dx
100                         queue_beep ()
101                 end
102
103                 -- single player (reflect top) -- TODO "stereo" version, 2 ctrls :)
104                 if ball_y <= 0 then
105                         dy = - dy y = 0
106                         queue_beep ()
107                 end
108
109                 -- keep the ball in the field at all times
110                 if ball_x >= 1 then ball_x = 1 end
111                 if ball_x <= 0 then ball_x = 0 end
112
113                 -- bottom edge
114                 if ball_y > 1 then
115                         local bar = ctrl[1] -- get bar position
116                         if math.abs (bar - ball_x) < 0.1 then
117                                 -- reflect the ball
118                                 dy = - dy
119                                 ball_y = 1.0
120                                 dx = dx - 0.04 * (bar - ball_x)
121                                 -- make sure it's moving (not stuck on borders)
122                                 if math.abs (dx) < 0.0001 then dx = 0.0001 end
123                                 game_score = game_score + 1
124                                 queue_beep ()
125                         else
126                                 -- game over, reset game
127                                 lost_sound = 0 -- re-start noise
128                                 ball_y = 0
129                                 game_score = 0
130                                 dx = 0.00367
131                         end
132                 end
133         end
134
135         -- forward audio if processing is not in-place
136         for c = 1,#outs do
137                 -- check if output and input buffers for this channel are identical
138                 -- http://manual.ardour.org/lua-scripting/class_reference/#C:FloatArray
139                 if not ins[c]:sameinstance (outs[c]) then
140                         -- fast (accelerated) copy
141                         -- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:DSP
142                         ARDOUR.DSP.copy_vector (out[c], ins[c], n_samples)
143                 end
144         end
145
146         -- simple synth -- TODO Optimize
147         if ping_sound < fps then
148                 -- cache audio data buffers for direct access, later
149                 local abufs = {}
150                 for c = 1,#outs do
151                         abufs[c] = outs[c]:array()
152                 end
153                 -- simple sine synth with a sine-envelope
154                 for s = 1, n_samples do
155                         ping_sound = ping_sound + 1
156                         ping_phase = ping_phase + ping_pitch
157                         local snd = 0.7 * math.sin(6.283185307 * ping_phase) * math.sin (3.141592 * ping_sound / fps)
158                         -- add synthesized sound to all channels
159                         for c = 1,#outs do
160                                 abufs[c][s] = abufs[c][s] + snd
161                         end
162                         -- break out of the loop when the sound finished
163                         if ping_sound >= fps then goto ping_end end
164                 end
165                 ::ping_end::
166         end
167
168         if lost_sound < 3 * fps then
169                 local abufs = {}
170                 for c = 1,#outs do
171                         abufs[c] = outs[c]:array()
172                 end
173                 for s = 1, n_samples do
174                         lost_sound = lost_sound + 1
175                         -- -12dBFS white noise
176                         local snd = 0.5 * (math.random () - 0.5)
177                         for c = 1,#outs do
178                                 abufs[c][s] = abufs[c][s] + snd
179                         end
180                         if lost_sound >= 3 * fps then goto noise_end end
181                 end
182                 ::noise_end::
183         end
184
185         if changed then
186                 -- notify the GUI
187                 local shmem = self:shmem () -- get the shared memory region
188                 local state = shmem:to_float (0):array () -- "cast" into lua-table
189                 -- update data..
190                 state[1] = ball_x
191                 state[2] = ball_y
192                 state[3] = game_score
193                 -- ..and wake up the UI
194                 self:queue_draw ()
195         end
196 end
197
198
199 -------------------------------------------------------------------------------
200 --- inline display
201
202 local txt = nil -- cache font description (in GUI context)
203
204 function render_inline (ctx, w, max_h)
205         local ctrl = CtrlPorts:array () -- control port array
206         local shmem = self:shmem () -- shared memory region (game state from DSP)
207         local state = shmem:to_float (0):array () -- cast to lua-table
208
209         if (w > max_h) then
210                 h = max_h
211         else
212                 h = w
213         end
214
215         -- prepare text rendering
216         if not txt then
217                 -- allocate PangoLayout and set font
218                 --http://manual.ardour.org/lua-scripting/class_reference/#Cairo:PangoLayout
219                 txt = Cairo.PangoLayout (ctx, "Mono 10px")
220         end
221
222         -- ctx is-a http://manual.ardour.org/lua-scripting/class_reference/#Cairo:Context
223         -- 2D vector graphics http://cairographics.org/
224
225         -- clear background
226         ctx:rectangle (0, 0, w, h)
227         ctx:set_source_rgba (.2, .2, .2, 1.0)
228         ctx:fill ()
229
230         -- print the current score
231         if (state[3] > 0) then
232                 txt:set_text (string.format ("%.0f", state[3]));
233                 local tw, th = txt:get_pixel_size ()
234                 ctx:set_source_rgba (1, 1, 1, 1.0)
235                 ctx:move_to (w - tw - 3, 3)
236                 txt:show_in_cairo_context (ctx)
237         end
238
239         -- prepare line and dot rendering
240         ctx:set_line_cap (Cairo.LineCap.Round)
241         ctx:set_line_width (3.0)
242         ctx:set_source_rgba (.8, .8, .8, 1.0)
243
244         -- display bar
245         local bar_width = w * .1
246         local bar_space = w - bar_width
247
248         ctx:move_to (bar_space * ctrl[1], h - 3)
249         ctx:rel_line_to (bar_width, 0)
250         ctx:stroke ()
251
252         -- display ball
253         ctx:move_to (1 + state[1] * (w - 3), state[2] * (h - 5))
254         ctx:close_path ()
255         ctx:stroke ()
256
257         return {w, h}
258 end