indentation for docs
[sdlgit/SDL-Site.git] / pages / SDL-Cookbook-PDL.html-inc
CommitLineData
162a0989 1<div class="pod">
2<!-- INDEX START -->
3<h3 id="TOP">Index</h3>
4
5<ul><li><a href="#Old_SDL_interface">Old SDL interface</a></li>
6<li><a href="#Perl_s_SDL_in_a_nutshell">Perl's SDL in a nutshell</a></li>
7<li><a href="#SDL_power_through_simplicity">SDL - power through simplicity</a></li>
8<li><a href="#Example_1_Model_of_a_2_D_Noninteract">Example 1: Model of a 2-D Noninteracting Gas</a>
9<ul><li><a href="#Computational_Logic">Computational Logic</a></li>
10<li><a href="#Animation_Logic">Animation Logic</a></li>
11<li><a href="#Disappearing_Particles_Some_of_the_p">Disappearing Particles!
12Some of the particles can drift off the screen. This is no good. What's causing this problem?</a></li>
13<li><a href="#Disappearing_Particles_take_2">Disappearing Particles, take 2</a></li>
14</ul>
15</li>
16<li><a href="#What_s_in_a_Name_Pesky_conflicts_wit">What's in a Name? Pesky conflicts with main::in()</a>
17<ul><li><a href="#Solution_1_Explicit_scoping_using_pa">Solution 1: Explicit scoping using packages</a></li>
18<li><a href="#Solution_2_Removing_SDL_s_in_or_PDL_">Solution 2: Removing SDL's in or PDL's in from the symbol table</a></li>
19</ul>
20</li>
21<li><a href="#Making_the_simulation_interactive">Making the simulation interactive</a>
22<ul><li><a href="#Present_state_of_the_code">Present state of the code</a></li>
23<li><a href="#Listening_to_Events">Listening to Events</a></li>
24<li><a href="#Responding_to_events">Responding to events</a></li>
25<li><a href="#Final_State_of_the_Code">Final State of the Code</a></li>
26</ul>
27</li>
28<li><a href="#Directions_for_future_work">Directions for future work</a>
29</li>
30</ul><hr />
31<!-- INDEX END -->
32
33<p>PDL provides great number crunching capabilities to Perl and SDL provides game-developer quality real-time bitmapping and sound. You can use PDL and SDL ''together'' to create real-time, responsive animations and simulations. In this section we will go through the pleasures and pitfalls of working with both powerhouse libraries.</p>
34<h1 id="Old_SDL_interface">Old SDL interface</h1><p><a href="#TOP" class="toplink">Top</a></p>
35<div id="Old_SDL_interface_CONTENT">
36
37
38
39
40<p>Please be aware that much of the code in this example uses SDL Perl v 2.2.4. The SDL Perl developers are hard at work rewriting SDL, to be released as SDL 3.0 soon. The new version of SDL is not backwards compatible. Check back with this page after SDL 3.0 has been released to get the updated commands.</p>
41
42</div>
43<h1 id="Perl_s_SDL_in_a_nutshell">Perl's SDL in a nutshell</h1><p><a href="#TOP" class="toplink">Top</a></p>
44<div id="Perl_s_SDL_in_a_nutshell_CONTENT">
45
46
47
48
49<p>SDL stands for Simple DirectMedia Layer. It's a cross-platform library written in C that's meant to handle all of the low-level graphics and sound stuff. You can read more about SDL here: http://www.libsdl.org/. Because SDL is focused on game programming, it has a raw but clean feel to it. We will focus for now on using SDL to handle images for us. Handling sound may some day be the focus of another chapter.</p>
50<p>We will be using Perl's SDL module, not SDL directly. Fortunately, Perl's SDL module has a small collection of very simple tutorials that perfectly introduce basic usage. You can find them here: http://sdl.perl.org/tutorials/. Another excellent and very substantial introduction can be found here: http://arstechnica.com/gaming/news/2006/02/games-perl.ars</p>
51<p>SDL is not a Perl core module, so you'll need to install it before moving forward. Before moving on, go through some of the tutorials and play around with SDL a little bit. Continue on once you think you've got the hang of it.</p>
52
53</div>
54<h1 id="SDL_power_through_simplicity">SDL - power through simplicity</h1><p><a href="#TOP" class="toplink">Top</a></p>
55<div id="SDL_power_through_simplicity_CONTENT">
56<p>One of the first questions you're bound to ask when you begin using SDL for your own work is, &quot;How do I draw a line?&quot; As it turns out, you don't! SDL's pixmap capabilities are just that - pixmap capabilities. If you want to draw a line, you'll have to do it manually.</p>
57<p>For example, here is a very poorly implemented hack (read - don't do this at home) that will draw a simple sine-wave graph:</p>
58<pre> #!/usr/bin/perl
59 use warnings;
60 use strict;
61
62 use SDL;
63 use SDL::App;
64 use SDL::Rect;
65 use SDL::Color;
66
67 # User defined pen-nib size.
68 my $nib_size = 3;
69
70 # Create the SDL App
71 my $app = SDL::App-&gt;new(
72 -width =&gt; 640,
73 -height =&gt; 480,
74 -depth =&gt; 16,
75 -title =&gt; &quot;Hello, World!&quot;,
76 );
77
78 # our nib will be white
79 my $nib_color = SDL::Color-&gt;new(
80 -r =&gt; 0xff,
81 -g =&gt; 0xff,
82 -b =&gt; 0xff,
83 );
84
85 # and our nib will be represented by a rectangle
86 # (Alternatively, you could use an image, which would allow
87 # for pretty anti-aliasing if you created it in GIMP with
88 # antialiasing)
89 my $nib = SDL::Rect-&gt;new(
90 -height =&gt; $nib_size,
91 -width =&gt; $nib_size,
92 );
93
94 # now draw a sine wave (wthout covering up previously drawn rectangles)
95 my $t = 0;
96 my $t_step = 2**-4;
97 for($t = 0; $t &lt; 50; $t += $t_step) {
98 $nib-&gt;x( $t * 8 );
99 $nib-&gt;y( sin($t) * 80 + 240 );
100
101 $app-&gt;fill( $nib, $nib_color );
102 }
103
104 # Generally use the update command, but if you want to update the whole
105 # surface, use flip
106 $app-&gt;flip()
107
108 sleep 5;
109
110</pre>
111<p>Wait a second, you say, this doesn't seem either powerful or simple! You're right, but that's not because SDL is a poor tool. Rather, this example targets SDL's weaknesses rather than its strenghts.</p>
112<p>If you need to make a plot, use PLplot or PGPLOT. If you need to make something move, use SDL.</p>
113
114</div>
115<h1 id="Example_1_Model_of_a_2_D_Noninteract">Example 1: Model of a 2-D Noninteracting Gas</h1><p><a href="#TOP" class="toplink">Top</a></p>
116<div id="Example_1_Model_of_a_2_D_Noninteract-2">
117<p>In this section we'll develop a fully working animation/simulation. We'll start with something quite simple for now and expand it as we go along. The goal of this example is for it to work, not to be well-designed. For a discussion of making your simulations well-designed, read below.</p>
118<p>We will separate our program into two parts: the computational logic and the animation logic. Here's the introduction and the computational part:</p>
119
120</div>
121<h2 id="Computational_Logic">Computational Logic</h2>
122<div id="Computational_Logic_CONTENT">
123<pre>
124
125
126 #!/usr/bin/perl
127 # A simple simulation
128 use warnings;
129 use strict;
130 use PDL;
131
132 # Set up the system parameters, including random positions and velocities.
133 my $d_t = 2**-3;
134 my $side_length = 200;
135 my $numb_of_atoms = 100;
136 my $positions = random(2, $numb_of_atoms) * $side_length;
137 my $velocities = random(2, $numb_of_atoms) * 6;
138
139 sub compute {
140 $positions += $d_t * $velocities;
141 }
142
143</pre>
144<p>If you've ever written a simulation, you'll probably object that we don't have any iteration over time. You're right, but it turns out that the timing works much better in SDL's event loop than in our computational logic. The purpose of the computational logic is to let us focus on encoding our systems dynamics without having to worry about the application logic. In this case, the computational logic simply updates the positions of the particles according to their velocities.</p>
145
146</div>
147<h2 id="Animation_Logic">Animation Logic</h2>
148<div id="Animation_Logic_CONTENT">
149<p>We next need to figure out how the application is actually going to run and display anything. We'll do this in two stages, the application intialization and the run loop.</p>
150<p>Here's some initialization code to get started; put this below the code already supplied above:</p>
151<pre> use SDL;
152 use SDL::App;
153 use SDL::Rect;
154 use SDL::Color;
155
156 # Create the SDL App
157 my $app = SDL::App-&gt;new( -width =&gt; $side_length, -height =&gt; $side_length,
158 -title =&gt; &quot;Simple Simulation!&quot;, -depth =&gt; 16, );
159
160 # white particles on a black background
161 my $particle_color = SDL::Color-&gt;new( -r =&gt; 0xff, -g =&gt; 0xff, -b =&gt; 0xff, );
162 my $bg_color = SDL::Color-&gt;new( -r =&gt; 0x00, -g =&gt; 0x00, -b =&gt; 0x00, );
163
164 # rectangles for the particles and the background
165 my $particle = SDL::Rect-&gt;new( -height =&gt; 5, -width =&gt; 5, );
166 my $bg = SDL::Rect-&gt;new( -height =&gt; $side_length, -width =&gt; $side_length, );
167
168</pre>
169<p>Hopefully this is straightforward code. We pull in our library dependencies and then create a few objects with the necessary properties. Finally, we get to the actual application loop:</p>
170<pre> # Run the simulation by (1) computing the updated positions, clearing the canvas, drawing the
171 # new particles, updating the visual display, and pausing before continuing:
172 for(my $t = 0; $t &lt; 20; $t += $d_t) {
173 compute();
174
175 # Clean the canvas
176 $app-&gt;fill( $bg, $bg_color);
177 for(my $i = 0; $i &lt; $numb_of_atoms; $i++) {
178 $particle-&gt;x( $positions-&gt;at(0,$i) );
179 $particle-&gt;y( $positions-&gt;at(1,$i) );
180 $app-&gt;fill( $particle, $particle_color );
181 }
182 $app-&gt;flip();
183 $app-&gt;delay(10);
184 }
185
186</pre>
187<p>When you run this code (combined with the code already supplied), you should get a bunch of particles slowly drifting down and to the right. Not all that interesting, but then again, we have a simulation up and working! Cool!.</p>
188
189</div>
190<h2 id="Disappearing_Particles_Some_of_the_p">Disappearing Particles!
191Some of the particles can drift off the screen. This is no good. What's causing this problem?</h2>
192<div id="Disappearing_Particles_Some_of_the_p-2">
193<p>The root of the problem is that our computational code is, well, rather dumb, it doesn't check to see if the particle is about to go off the screen. So, we need to update our computational code to look like this:</p>
194<pre> sub compute {
195 $positions += $d_t * $velocities;
196
197 # Find all particles that are 'outside' the box, place them back in
198 # box, and reverse their directions
199 my ($bad_pos, $bad_vel)
200 = where($positions, $velocities, $positions &gt; $side_length);
201 $bad_vel *= -1;
202 $bad_pos .= 2 * $side_length - $bad_pos;
203 }
204
205</pre>
206<p>With this change to the code, you should get particles that 'bounce' when the reach the far edge. This is far from satisfactory, however, because the compute code is adjusting the particle's ''left'' edge, not its center, so the particles nearly go off the screen before they bounce. To fix this, we work with an effective side length instead:</p>
207<pre> my $effective_length = $side_length - 5;
208 sub compute {
209 $positions += $d_t * $velocities;
210
211 # Find all particles that are 'outside' the box and push them back in the
212 # opposite direction, reversing their directions, too.
213 my ($bad_pos, $bad_vel)
214 = where($positions, $velocities, $positions &gt; $effective_length);
215 $bad_vel *= -1;
216 $bad_pos .= 2 * $effective_length - $bad_pos;
217 }
218
219</pre>
220<p>So far I've been carrying that explicit constant of 5 to represent the size of the particles. We should put that in a variable somewhere so that it's a bitcode&gt; and put it near the top. Also, the velocities are rather silly - we don't have any negative velocities. Let's try using &lt;code&gt;grandom&lt;/code&gt; instead. Now your variable initialization code should look something like this:</p>
221<pre> # Set up the system parameters, including random positions and velocities.
222 my $d_t = 2**-3;
223 my $side_length = 200;
224 my $particle_size = 5;
225 my $numb_of_atoms = 100;
226 my $positions = random(2, $numb_of_atoms) * $side_length;
227 my $velocities = grandom(2, $numb_of_atoms) * 5;
228
229</pre>
230
231</div>
232<h2 id="Disappearing_Particles_take_2">Disappearing Particles, take 2</h2>
233<div id="Disappearing_Particles_take_2_CONTEN">
234<p>Unless you experience an unusual circumstance, all of the particles will quickly shrivel up and disappear! What's going on? It turns out we have a problem with our computational logic again, but we are also running into strange behavior from SDL. We'll take a look at SDL's weird behavior first.</p>
235<p>Clearly the particle rectangle's size is not supposed to change, but somehow it does. To confince yourself of this, modify the &lt;code&gt;for&lt;/code&gt; loop in the application loop so it looks more like this, which explicitly sets the particle size for every particle that's drawn:</p>
236<pre> for(my $i = 0; $i &lt; $numb_of_atoms; $i++) {
237 $particle-&gt;x( $positions-&gt;at(0,$i) );
238 $particle-&gt;y( $positions-&gt;at(1,$i) );
239 $particle-&gt;height( $particle_size );
240 $particle-&gt;width( $particle_size );
241 $app-&gt;fill( $particle, $particle_color );
242 }
243
244</pre>
245<p>Now it's clear that although we still have particles flying off the screen up and to the left, they are no longer shriveling away. This strange behavior is due to SDL's response to a negative position for a rectangle - it just resizes the rectangle so that it only the portion of the rectangle that's in positive territory remains. The upshot is that you must always be careful about how you handle drawing positons.</p>
246<p>Now that the particles are no longer disappearing, it's clear that we forgot to set up a physical boundary condition for our particles on the uppper and left edges. To fix that, we modify the compute function:</p>
247<pre> sub compute {
248 $positions += $d_t * $velocities;
249
250 # Find all particles that are 'outside' the box and push them back in the
251 # opposite direction, reversing their directions, too.
252 my ($bad_pos, $bad_vel)
253 = where($positions, $velocities, $positions &gt; $effective_length);
254 $bad_vel *= -1;
255 $bad_pos .= 2 * $effective_length - $bad_pos;
256
257 ($bad_pos, $bad_vel) = where($positions, $velocities, $positions &lt; 0);
258 $bad_vel *= -1;
259 $bad_pos *= -1;
260 }
261
262</pre>
263<p>You can also remove the explicit particle-sizing that we put in before, because it's no longer a problem.</p>
264<p>And there you have it! We have a fully fledged simulation of noninteracting particles in a box!</p>
265
266</div>
267<h1 id="What_s_in_a_Name_Pesky_conflicts_wit">What's in a Name? Pesky conflicts with main::in()</h1><p><a href="#TOP" class="toplink">Top</a></p>
268<div id="What_s_in_a_Name_Pesky_conflicts_wit-2">
269<p>If you've been running your simulations along with the demo, you'll almost certainly have noticed an error looking something like this:</p>
270<pre> Prototype mismatch: sub main::in (;@) vs none at ./sdlsandbox.pl line 36
271
272</pre>
273<p>This is the unfortunate consequence of both SDL and PDL exporting their &lt;code&gt;in&lt;/code&gt; function to their enclosing namespace. The standard solution to this is to have modify one of your &lt;code&gt;use&lt;/code&gt; lines so it looks like </p>
274<pre> use PDL qw( !in );
275
276</pre>
277<p>Unfortunately, PDL doesn't listen you what you say when it imports functions into the namespace. As far as I can tell, neither does SDL. The best way to fix this problem is to encapsulate one of the two pieces of code into its own package. We'll do that with the MyComputation package.</p>
278
279</div>
280<h2 id="Solution_1_Explicit_scoping_using_pa">Solution 1: Explicit scoping using packages</h2>
281<div id="Solution_1_Explicit_scoping_using_pa-2">
282<p>Tweak your code a bit so that you call <code>use PDL;</code> within the MyCompute package, and place all of the piddles within that package space:</p>
283<pre> package MyCompute;
284 use PDL;
285 my $positions = random(2, $numb_of_atoms) * $side_length;
286
287 # ... and later
288 package main;
289 use SDL;
290
291 # ... and later, tweak the application loop
292 for(my $t = 0; $t &lt; 20; $t += $d_t) {
293 MyCompute::compute();
294
295</pre>
296<p>And now everything should run fine, without any more warnings!</p>
297
298</div>
299<h2 id="Solution_2_Removing_SDL_s_in_or_PDL_">Solution 2: Removing SDL's in or PDL's in from the symbol table</h2>
300<div id="Solution_2_Removing_SDL_s_in_or_PDL_-2">
301<p>Sometimes you have to mix your animation code with computational code, in which case the above solution doesn't solve your problem. If you find that you don't need to use one of PDL's or SDL's &lt;code&gt;in&lt;/code&gt; function in your own code, go ahead and remove it from the main symbol table. You can always get back to it later by fully qualifying the function call. To remove SDL's &lt;code&gt;in&lt;/code&gt; function, use code like this:</p>
302<pre> # use SDL, but remove SDL's in function before loading PDL
303 use SDL;
304 BEGIN {
305 delete $main::{in};
306 }
307 use PDL;
308
309</pre>
310<p>If you would rather have SDL's <code>in</code> function in your main symbol table, reverse the placement of &lt;code&gt;use SD<a href="#code">code</a> and &lt;code&gt;use PD<a href="#code">code</a> in the previous example:</p>
311<pre> # use PDL, but remove its 'in' function before loading SDL
312 use PDL;
313 BEGIN {
314 delete $main::{in};
315 }
316 use SDL;
317
318</pre>
319
320</div>
321<h1 id="Making_the_simulation_interactive">Making the simulation interactive</h1><p><a href="#TOP" class="toplink">Top</a></p>
322<div id="Making_the_simulation_interactive_CO">
323<p>As the closing portion of this chapter, we'll consider how to make the simulation interactive. SDL captures keyboard and mouse behavior, so putting this into our simulator is straightforward.</p>
324
325</div>
326<h2 id="Present_state_of_the_code">Present state of the code</h2>
327<div id="Present_state_of_the_code_CONTENT">
328<p>Before moving into getting user interaction, I first want to be sure we're working with the same code. In particular, I've made a couple of important modifications so that this code is slightly different from what we were working with above. I'll point out those differences as we come to them. Here's the program as it stands, from top to bottom:</p>
329<pre> #!/usr/bin/perl
330 # A simple simulation
331 use warnings;
332 use strict;
333
334 ## Global Variables ##
335
336 # Set up the system parameters, including random positions and velocities.
337 my $d_t = 2**-3;
338 my $side_length = 200;
339 my $particle_size = 5;
340 my $numb_of_atoms = 100;
341
342 ## Computational Stuff ##
343
344 package MyCompute;
345 use PDL;
346 my $positions = random(2, $numb_of_atoms) * $side_length;
347 my $velocities = grandom(2, $numb_of_atoms) * 6;
348 my $effective_length;
349
350 sub compute {
351 my $effective_length = $side_length - $particle_size;
352
353 # update the a real simulation, this is the interesting part
354 $positions += $d_t * $velocities;
355
356 # Check boundary conditions. Find all particles that are 'outside' the box,
357 # place them back in the box, and reverse their directions
358 my ($bad_pos, $bad_vel)
359 = where($positions, $velocities, $positions &gt; $effective_length);
360 $bad_vel *= -1;
361 $bad_pos .= 2 * $effective_length - $bad_pos;
362
363 ($bad_pos, $bad_vel) = where($positions, $velocities, $positions &lt; 0);
364 $bad_vel *= -1;
365 $bad_pos *= -1;
366 }
367
368
369
370
371 ## Animation Code ##
372
373 package main;
374
375 use SDL;
376 use SDL::App;
377 use SDL::Rect;
378 use SDL::Color;
379
380 # Create the SDL App
381 my $app = SDL::App-&gt;new( -width =&gt; $side_length, -height =&gt; $side_length,
382 -title =&gt; &quot;Simple Simulation!&quot;, -depth =&gt; 16, );
383
384 # white particles on a black background
385 my $particle_color = SDL::Color-&gt;new( -r =&gt; 0xff, -g =&gt; 0xff, -b =&gt; 0xff, );
386 my $bg_color = SDL::Color-&gt;new( -r =&gt; 0x00, -g =&gt; 0x00, -b =&gt; 0x00, );
387
388 # rectangles for the particles and the background
389 my $particle = SDL::Rect-&gt;new( -height =&gt; 5, -width =&gt; 5, );
390 my $bg = SDL::Rect-&gt;new( -height =&gt; $side_length, -width =&gt; $side_length, );
391
392 # Run the simulation
393 for(my $t = 0; $t &lt; 20; $t += $d_t) {
394 MyCompute::compute();
395
396 # Clean the canvas
397 $app-&gt;fill( $bg, $bg_color);
398 for(my $i = 0; $i &lt; $numb_of_atoms; $i++) {
399 $particle-&gt;x( $positions-&gt;at(0,$i) );
400 $particle-&gt;y( $positions-&gt;at(1,$i) );
401 $app-&gt;fill( $particle, $particle_color );
402 }
403 $app-&gt;flip();
404 $app-&gt;delay(10);
405 }
406
407</pre>
408<p>So there it is, top to bottom, in about 75 lines.</p>
409
410</div>
411<h2 id="Listening_to_Events">Listening to Events</h2>
412<div id="Listening_to_Events_CONTENT">
413<p>To respond to user interactions, we have to listen to user events using an SDL::Event object. So first, add this line with our other use statements:</p>
414<pre> use SDL::Event;
415
416</pre>
417<p>and then be sure to create an event object amongst the animation initialization code:</p>
418<pre> my $event = new SDL::Event;
419
420</pre>
421<p>Finally, we need to update the application loop so that it examines and responds to events. Replace the current application loop with this code:</p>
422<pre> # Run the simulation
423 while(1) {
424 MyCompute::compute();
425
426 # Clean the canvas
427 $app-&gt;fill( $bg, $bg_color);
428 for(my $i = 0; $i &lt; $numb_of_atoms; $i++) {
429 $particle-&gt;x( $positions-&gt;at(0,$i) );
430 $particle-&gt;y( $positions-&gt;at(1,$i) );
431 $app-&gt;fill( $particle, $particle_col10);
432
433 while($event-&gt;poll()) {
434 if($event-&gt;type() =head1 SDL_QUIT) {
435 exit;
436 }
437 }
438 }
439
440</pre>
441<p>Now the animator will run indefinitely, until you explicitly tell it to close. (You may have noticed before that the application would not close even if you told it to close. Now we've fixed that.)</p>
442
443</div>
444<h2 id="Responding_to_events">Responding to events</h2>
445<div id="Responding_to_events_CONTENT">
446<p>When SDL gets a mouse response or a keyboard key press, it tells you with an event. The naive way to process these event is with a series of if statements. Don't do that.</p>
447<p>Instead, create a dispatch table, which is nothing more than a hash whose values are the subroutines you want to have run when an event happens. Replace the application loop with the following code:</p>
448<pre> # event dispatch table
449 my $keyname_dispatch_table = {
450 'up' =&gt; \&amp;incr_particle_size, # up key makes particles larger
451 'down' =&gt; \&amp;decr_particle_size, # down key makes particles smaller
452 'space' =&gt; sub { $d_t = -$d_t }, # space-bar reverses time
453 '.' =&gt; sub { $d_t *= 1.1 }, # right-angle-bracket fast-forwards
454 ',' =&gt; sub { $d_t /= 1.1 }, # left-angle-bracket slows down
455 'q' =&gt; sub { exit; }, # q exits
456 };
457
458 sub incr_particle_size {
459 $particle_size++;
460 $particle-&gt;height($particle_size);
461 $particle-&gt;width($particle_size);
462 }
463
464 sub decr_particle_size {
465 $particle_size-- if $particle_size &gt; 1;
466 $particle-&gt;height($particle_size);
467 $particle-&gt;width($particle_size);
468 }
469
470
471
472
473 # Run the simulation
474 while(1) {
475 MyCompute::compute();
476
477 # Clean the canvas
478 $app-&gt;fill( $bg, $bg_color);
479 for(my $i = 0; $i &lt; $numb_of_atoms; $i++) {
480 $particle-&gt;x( $positions-&gt;at(0,$i) );
481 $particle-&gt;y( $positions-&gt;at(1,$i) );
482 $app-&gt;fill( $particle, $particle_color );
483 }
484 $app-&gt;flip();
485 $app-&gt;delay(10);
486
487 while($event-&gt;poll()) {
488 if($event-&gt;type() =head1 SDL_QUIT) {
489 exit;
490 } elsif($event-&gt;type() =head1 SDL_KEYDOWN) {
491 if(exists $keyname_dispatch_table-&gt;{$event-&gt;key_name()}) {
492 $keyname_dispatch_table-&gt;{$event-&gt;key_name()}-&gt;();
493 }
494 }
495 }
496 }
497
498</pre>
499<p>Dispatch tables allow for powerful methods of abstracting your program logic. Now adding a new event handler is as easy as updating the dispatch table!</p>
500<p>As written, you can now increase or decrease the particle size using the up and down arrow keys, you can increase ory using the right or left angle-brackets, you can reverse time using the space bar, or you can quit by pressing q.</p>
501
502</div>
503<h2 id="Final_State_of_the_Code">Final State of the Code</h2>
504<div id="Final_State_of_the_Code_CONTENT">
505<p>Just so that you've got a complete working example, here is the final state of the code, clocking in at a mere 115 lines:</p>
506<pre> #!/usr/bin/perl
507 # A simple simulation
508 use warnings;
509 use strict;
510
511 ## Global Variables ##
512
513 # Set up the system parameters, including random positions and velocities.
514 my $d_t = 2**-3;
515 my $side_length = 200;
516 my $particle_size = 5;
517 my $numb_of_atoms = 100;
518
519 ## Computational Stuff ##
520
521 package MyCompute;
522 use PDL;
523 my $positions = random(2, $numb_of_atoms) * $side_length;
524 my $velocities = grandom(2, $numb_of_atoms) * 6;
525 my $effective_length;
526
527 sub compute {
528 my $effective_length = $side_length - $particle_size;
529
530 # update the positions. For a real simulation, this is the interesting part
531 $positions += $d_t * $velocities;
532
533 # Check boundary conditions. Find all particles that are 'outside' the box,
534 # place them back in the box, and reverse their directions
535 my ($bad_pos, $bad_vel)
536 = where($positions, $velocities, $positions &gt; $effective_length);
537 $bad_vel *= -1;
538 $bad_pos .= 2 * $effective_length - $bad_pos;
539
540 ($bad_pos, $bad_vel) = where($positions, $velocities, $positions &lt; 0);
541 $bad_vel *= -1;
542 $bad_pos *= -1;
543 }
544
545
546
547
548 ## Animation Code ##
549
550 package main;
551
552 use SDL;
553 use SDL::App;
554 use SDL::Rect;
555 use SDL::Color;
556 use SDL::Event;
557
558 # Create the SDL App
559 my $app = SDL::App-&gt;new( -width =&gt; $side_length, -height =&gt; $side_length,
560 -title =&gt; &quot;Simple Simulation!&quot;, -depth =&gt; 16, );
561
562 # white particles on a black background
563 my $particle_color = SDL::Color-&gt;new( -r =&gt; 0xff, -g =&gt; 0xff, -b =&gt; 0xff, );
564 my $bg_color = SDL::Color-&gt;new( -r =&gt; 0x00, -g =&gt; 0x00, -b =&gt; 0x00, );
565
566 # rectangles for the particles and the background
567 my $particle = SDL::Rect-&gt;new( -height =&gt; 5, -width =&gt; 5, );
568 my $bg = SDL::Rect-&gt;new( -height =&gt; $side_length, -width =&gt; $side_length, );
569
570 # event listener
571 my $event = new SDL::Event;
572
573 # event dispatch table
574 my $keyname_dispatch_table = {
575 'up' =&gt; \&amp;incr_particle_size, # up key makes particles large
576 'down' =&gt; \&amp;decr_particle_size, # up key makes particles large
577 'space' =&gt; sub { $d_t = -$d_t },
578 '.' =&gt; sub { $d_t *= 1.1 }, # right-arrow fast-forwards
579 ',' =&gt; sub { $d_t /= 1.1 }, # left-arrow slows down
580 'q' =&gt; sub { exit; }, # q exits
581 };
582
583 sub incr_particle_size {
584 $particle_size++;
585 $particle-&gt;height($particle_size);
586 $particle-&gt;width($particle_size);
587 }
588
589 sub decr_particle_size {
590 $particle_size-- if $particle_size &gt; 1;
591 $particle-&gt;height($particle_size);
592 $particle-&gt;width($particle_size);
593 }
594
595
596
597
598 # Run the simulation
599 while(1) {
600 MyCompute::compute();
601
602 # Clean the canvas
603 $app-&gt;fill( $bg, $bg_color);
604 for(my $i = 0; $i &lt; $numb_of_atoms; $i++) {
605 $particle-&gt;x( $positions-&gt;at(0,$i) );
606 $particle-&gt;y( $positions-&gt;at(1,$i) );
607 $app-&gt;fill( $particle, $particle_color );
608 }
609 $app-&gt;flip();
610 $app-&gt;delay(10);
611
612 while($event-&gt;poll()) {
613 if($event-&gt;type() =head1 SDL_QUIT) {
614 exit;
615 } elsif($event-&gt;type() =head1 SDL_KEYDOWN) {
616 if(exists $keyname_dispatch_table-&gt;{$event-&gt;key_name()}) {
617 $keyname_dispatch_table-&gt;{$event-&gt;key_name()}-&gt;();
618 }
619 }
620 }
621 }
622
623</pre>
624<p>Next, if you want to model interactions among particles, you could write code in the compute function to handle that for you. If you wanted to use little balls instead of the boxes we've used here, you could create your own images and use an SDL::Surface to load the image. You can't resize an image using SDL, but then you'd probably be working with real interactions anyway, like a Coulomb force, in which case you'd really be adjusting the interaction strength, not the particle size.</p>
625
626</div>
627<h1 id="Directions_for_future_work">Directions for future work</h1><p><a href="#TOP" class="toplink">Top</a></p>
628<div id="Directions_for_future_work_CONTENT">
629<p>I have a couple of ideas for future work combining PDL and SDL.</p>
630<dl>
631 <dt>PLplot driver thingy that creates plots that can be blitted onto an app. This way, having a graph plotting along side your simulation would be straightforward.
632=item Write a function to convert SDL::Surface to a collection of rgba piddles. We might even be able to convince the piddle to work directly with the memory allocated for the SDL::Survace object for super-fast PDL-based image manipulations. As an added bonus, you'd be able to slice and dice!</dt>
633</dl>
634
635</div>
636</div>