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