3 <h3 id="TOP">Index</h3>
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!
12 Some 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>
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>
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>
28 <li><a href="#Directions_for_future_work">Directions for future work</a>
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">
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>
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">
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>
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, "How do I draw a line?" 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>
67 # User defined pen-nib size.
71 my $app = SDL::App->new(
75 -title => "Hello, World!",
78 # our nib will be white
79 my $nib_color = SDL::Color->new(
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
89 my $nib = SDL::Rect->new(
90 -height => $nib_size,
91 -width => $nib_size,
94 # now draw a sine wave (wthout covering up previously drawn rectangles)
97 for($t = 0; $t < 50; $t += $t_step) {
99 $nib->y( sin($t) * 80 + 240 );
101 $app->fill( $nib, $nib_color );
104 # Generally use the update command, but if you want to update the whole
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>
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>
121 <h2 id="Computational_Logic">Computational Logic</h2>
122 <div id="Computational_Logic_CONTENT">
127 # A simple simulation
132 # Set up the system parameters, including random positions and velocities.
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;
140 $positions += $d_t * $velocities;
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>
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>
157 my $app = SDL::App->new( -width => $side_length, -height => $side_length,
158 -title => "Simple Simulation!", -depth => 16, );
160 # white particles on a black background
161 my $particle_color = SDL::Color->new( -r => 0xff, -g => 0xff, -b => 0xff, );
162 my $bg_color = SDL::Color->new( -r => 0x00, -g => 0x00, -b => 0x00, );
164 # rectangles for the particles and the background
165 my $particle = SDL::Rect->new( -height => 5, -width => 5, );
166 my $bg = SDL::Rect->new( -height => $side_length, -width => $side_length, );
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 < 20; $t += $d_t) {
176 $app->fill( $bg, $bg_color);
177 for(my $i = 0; $i < $numb_of_atoms; $i++) {
178 $particle->x( $positions->at(0,$i) );
179 $particle->y( $positions->at(1,$i) );
180 $app->fill( $particle, $particle_color );
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>
190 <h2 id="Disappearing_Particles_Some_of_the_p">Disappearing Particles!
191 Some 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>
195 $positions += $d_t * $velocities;
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 > $side_length);
202 $bad_pos .= 2 * $side_length - $bad_pos;
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;
209 $positions += $d_t * $velocities;
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 > $effective_length);
216 $bad_pos .= 2 * $effective_length - $bad_pos;
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> and put it near the top. Also, the velocities are rather silly - we don't have any negative velocities. Let's try using <code>grandom</code> instead. Now your variable initialization code should look something like this:</p>
221 <pre> # Set up the system parameters, including random positions and velocities.
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;
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 <code>for</code> 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 < $numb_of_atoms; $i++) {
237 $particle->x( $positions->at(0,$i) );
238 $particle->y( $positions->at(1,$i) );
239 $particle->height( $particle_size );
240 $particle->width( $particle_size );
241 $app->fill( $particle, $particle_color );
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>
248 $positions += $d_t * $velocities;
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 > $effective_length);
255 $bad_pos .= 2 * $effective_length - $bad_pos;
257 ($bad_pos, $bad_vel) = where($positions, $velocities, $positions < 0);
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>
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
273 <p>This is the unfortunate consequence of both SDL and PDL exporting their <code>in</code> function to their enclosing namespace. The standard solution to this is to have modify one of your <code>use</code> lines so it looks like </p>
274 <pre> use PDL qw( !in );
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>
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;
285 my $positions = random(2, $numb_of_atoms) * $side_length;
291 # ... and later, tweak the application loop
292 for(my $t = 0; $t < 20; $t += $d_t) {
293 MyCompute::compute();
296 <p>And now everything should run fine, without any more warnings!</p>
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 <code>in</code> 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 <code>in</code> function, use code like this:</p>
302 <pre> # use SDL, but remove SDL's in function before loading PDL
310 <p>If you would rather have SDL's <code>in</code> function in your main symbol table, reverse the placement of <code>use SD<a href="#code">code</a> and <code>use PD<a href="#code">code</a> in the previous example:</p>
311 <pre> # use PDL, but remove its 'in' function before loading SDL
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>
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
334 ## Global Variables ##
336 # Set up the system parameters, including random positions and velocities.
338 my $side_length = 200;
339 my $particle_size = 5;
340 my $numb_of_atoms = 100;
342 ## Computational Stuff ##
346 my $positions = random(2, $numb_of_atoms) * $side_length;
347 my $velocities = grandom(2, $numb_of_atoms) * 6;
348 my $effective_length;
351 my $effective_length = $side_length - $particle_size;
353 # update the a real simulation, this is the interesting part
354 $positions += $d_t * $velocities;
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 > $effective_length);
361 $bad_pos .= 2 * $effective_length - $bad_pos;
363 ($bad_pos, $bad_vel) = where($positions, $velocities, $positions < 0);
381 my $app = SDL::App->new( -width => $side_length, -height => $side_length,
382 -title => "Simple Simulation!", -depth => 16, );
384 # white particles on a black background
385 my $particle_color = SDL::Color->new( -r => 0xff, -g => 0xff, -b => 0xff, );
386 my $bg_color = SDL::Color->new( -r => 0x00, -g => 0x00, -b => 0x00, );
388 # rectangles for the particles and the background
389 my $particle = SDL::Rect->new( -height => 5, -width => 5, );
390 my $bg = SDL::Rect->new( -height => $side_length, -width => $side_length, );
393 for(my $t = 0; $t < 20; $t += $d_t) {
394 MyCompute::compute();
397 $app->fill( $bg, $bg_color);
398 for(my $i = 0; $i < $numb_of_atoms; $i++) {
399 $particle->x( $positions->at(0,$i) );
400 $particle->y( $positions->at(1,$i) );
401 $app->fill( $particle, $particle_color );
408 <p>So there it is, top to bottom, in about 75 lines.</p>
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;
417 <p>and then be sure to create an event object amongst the animation initialization code:</p>
418 <pre> my $event = new SDL::Event;
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
424 MyCompute::compute();
427 $app->fill( $bg, $bg_color);
428 for(my $i = 0; $i < $numb_of_atoms; $i++) {
429 $particle->x( $positions->at(0,$i) );
430 $particle->y( $positions->at(1,$i) );
431 $app->fill( $particle, $particle_col10);
433 while($event->poll()) {
434 if($event->type() =head1 SDL_QUIT) {
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>
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' => \&incr_particle_size, # up key makes particles larger
451 'down' => \&decr_particle_size, # down key makes particles smaller
452 'space' => sub { $d_t = -$d_t }, # space-bar reverses time
453 '.' => sub { $d_t *= 1.1 }, # right-angle-bracket fast-forwards
454 ',' => sub { $d_t /= 1.1 }, # left-angle-bracket slows down
455 'q' => sub { exit; }, # q exits
458 sub incr_particle_size {
460 $particle->height($particle_size);
461 $particle->width($particle_size);
464 sub decr_particle_size {
465 $particle_size-- if $particle_size > 1;
466 $particle->height($particle_size);
467 $particle->width($particle_size);
475 MyCompute::compute();
478 $app->fill( $bg, $bg_color);
479 for(my $i = 0; $i < $numb_of_atoms; $i++) {
480 $particle->x( $positions->at(0,$i) );
481 $particle->y( $positions->at(1,$i) );
482 $app->fill( $particle, $particle_color );
487 while($event->poll()) {
488 if($event->type() =head1 SDL_QUIT) {
490 } elsif($event->type() =head1 SDL_KEYDOWN) {
491 if(exists $keyname_dispatch_table->{$event->key_name()}) {
492 $keyname_dispatch_table->{$event->key_name()}->();
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>
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
511 ## Global Variables ##
513 # Set up the system parameters, including random positions and velocities.
515 my $side_length = 200;
516 my $particle_size = 5;
517 my $numb_of_atoms = 100;
519 ## Computational Stuff ##
523 my $positions = random(2, $numb_of_atoms) * $side_length;
524 my $velocities = grandom(2, $numb_of_atoms) * 6;
525 my $effective_length;
528 my $effective_length = $side_length - $particle_size;
530 # update the positions. For a real simulation, this is the interesting part
531 $positions += $d_t * $velocities;
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 > $effective_length);
538 $bad_pos .= 2 * $effective_length - $bad_pos;
540 ($bad_pos, $bad_vel) = where($positions, $velocities, $positions < 0);
559 my $app = SDL::App->new( -width => $side_length, -height => $side_length,
560 -title => "Simple Simulation!", -depth => 16, );
562 # white particles on a black background
563 my $particle_color = SDL::Color->new( -r => 0xff, -g => 0xff, -b => 0xff, );
564 my $bg_color = SDL::Color->new( -r => 0x00, -g => 0x00, -b => 0x00, );
566 # rectangles for the particles and the background
567 my $particle = SDL::Rect->new( -height => 5, -width => 5, );
568 my $bg = SDL::Rect->new( -height => $side_length, -width => $side_length, );
571 my $event = new SDL::Event;
573 # event dispatch table
574 my $keyname_dispatch_table = {
575 'up' => \&incr_particle_size, # up key makes particles large
576 'down' => \&decr_particle_size, # up key makes particles large
577 'space' => sub { $d_t = -$d_t },
578 '.' => sub { $d_t *= 1.1 }, # right-arrow fast-forwards
579 ',' => sub { $d_t /= 1.1 }, # left-arrow slows down
580 'q' => sub { exit; }, # q exits
583 sub incr_particle_size {
585 $particle->height($particle_size);
586 $particle->width($particle_size);
589 sub decr_particle_size {
590 $particle_size-- if $particle_size > 1;
591 $particle->height($particle_size);
592 $particle->width($particle_size);
600 MyCompute::compute();
603 $app->fill( $bg, $bg_color);
604 for(my $i = 0; $i < $numb_of_atoms; $i++) {
605 $particle->x( $positions->at(0,$i) );
606 $particle->y( $positions->at(1,$i) );
607 $app->fill( $particle, $particle_color );
612 while($event->poll()) {
613 if($event->type() =head1 SDL_QUIT) {
615 } elsif($event->type() =head1 SDL_KEYDOWN) {
616 if(exists $keyname_dispatch_table->{$event->key_name()}) {
617 $keyname_dispatch_table->{$event->key_name()}->();
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>
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>
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>