-
Notifications
You must be signed in to change notification settings - Fork 15
/
SDL_Manual.html
4549 lines (3331 loc) · 151 KB
/
SDL_Manual.html
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<h1>Preface</h1>
<p><i>Simple DirectMedia Layer</i> (or <i>libsdl</i>) is a cross-platform C
library that provides access to several input and output devices. Its most
popular usage is to provide access to the video framebuffer and input
devices for games. SDL also has several extension libraries to provide
features such as text display, sound mixing, image handling, and graphics
effects.</p>
<p>SDL Perl binds several of these libraries together in the
<code>SDL::*</code> namespace. Moreover, SDL Perl provides several
high-level libraries in the <code>SDLx::*</code> namespace that encapsulate
valuable game-writing abstractions.</p>
<h2><code>SDL</code> and <code>SDLx</code></h2>
<p>The main purpose of the <code>SDLx::*</code> layer is to smooth out the
drudgery of using the <code>SDL::*</code> layer directly.</p>
<blockquote>
<p>Don't worry about understanding the details of this code right now.
Compare the complexity and size of the code listings.</p>
</blockquote>
<p>Using the <code>SDL::*</code> layer to draw a blue rectangle looks
something like:</p>
<pre><code> use SDL;
use SDL::Video;
use SDL::Surface;
use SDL::Rect;
# the size of the window box or the screen resolution if fullscreen
my $screen_width = 800;
my $screen_height = 600;
SDL::init(SDL_INIT_VIDEO);
# setting video mode
my $screen_surface = SDL::Video::set_video_mode($screen_width,
$screen_height,
32,
SDL_ANYFORMAT);
# drawing a rectangle with the blue color
my $mapped_color = SDL::Video::map_RGB($screen_surface->format(),
0, 0, 255);
SDL::Video::fill_rect($screen_surface,
SDL::Rect->new($screen_width / 4, $screen_height / 4,
$screen_width / 2, $screen_height / 2),
$mapped_color);
# update an area on the screen so it's visible
SDL::Video::update_rect($screen_surface, 0, 0,
$screen_width, $screen_height);
# just to have time to see it
sleep(5);</code></pre>
<p>... while drawing a blue rectangle in the <code>SDLx::*</code> layer is
as simple as:</p>
<pre><code> use strict;
use warnings;
use SDL;
use SDLx::App;
my $app = SDLx::App->new( width=> 800, height => 600 );
$app->draw_rect([ $app->width / 4, $app->height / 4,
$app->width / 2, $app->height / 2, ],
[ 0, 0, 255, 255] );
$app->update();
sleep(5);</code></pre>
<p>The <code>SDLx::*</code> modules also provide and manage higher-level
concerns for users, such as layers and game loops.</p>
<h2>About the Book</h2>
<p>This book has a two-fold purpose: first, to introduce game development
to Perl programmers, and second, to introduce Modern Perl concepts through
game development. While the examples assume some experience with Perl, no
experience with SDL in Perl or as <code>libsdl</code> itself is
necessary.</p>
<p>The book presents a progression from simple to intermediate examples and
provides suggestions for more advanced endeavors. The chapters of this book
increase progressively in complexity, but each chapter has a singular goal
(such as chapter five's <i>Making Pong</i>) which stands alone as an
individual tutorial. Sources and data files are all available from
http://sdl.perl.org/.</p>
<h2>Installing SDL Perl</h2>
<p>We assume the presence of a recent version of the Perl language (at
least Perl 5.10) and supporting packages. We also assume that you can
install packages from the CPAN, including SDL Perl itself.</p>
<h3>Windows</h3>
<p><code>Alien::SDL</code> will install binaries for 32bit and 64bit so
there is no need to compile anything.</p>
<h3>Mac OS X</h3>
<p>Fink has packages for SDL Perl available. However, they do not support
Pango, a library which provides internalization support for text
handling.</p>
<p>Installing <code>Alien::SDL</code> from the CPAN will compile SDL and
its dependencies, provided you have installed severan necessary
dependencies. We recommend that you install <code>libfreetype6</code>,
<code>libX11</code>, <code>libvorbis</code>, <code>libogg</code>,
<code>libpng</code>, and their headers.</p>
<h3>GNU/Linux</h3>
<p>Most current GNU/Linux distributions include all the parts needed for
this tutorial in the default install and in their package management
system. It is also always possible to install on GNU/Linux using the
available open source code from the proper repositories. The
<code>Alien::SDL</code> perl module automates much of downloading,
compiling, and installing the needed libraries.</p>
<p>You can probably use your distribution's packages. On Ubuntu and Debian
try:</p>
<pre><code> $ sudo apt-get install libsdl-net1.2-dev libsdl-mixer1.2-dev \
libsdl1.2-dev libsdl-image1.2-dev libsdl-ttf2.0-dev \
libsdl-gfx1.2-dev libsdl-pango-dev</code></pre>
<p>To compile from scratch, you must install a compiler, system header
packages, and some libraries are required.</p>
<pre><code> $ sudo apt-get install build-essential xorg-dev libx11-dev libxv-dev \
libpango1.0-dev libfreetype6-dev libvorbis-dev libpng12-dev \
libogg-dev</code></pre>
<h3>CPAN install</h3>
<p>Before installing SDL Perl, ensure that you have the most recent
versions of the modules necessary to build SDL:</p>
<pre><code> $ sudo cpan CPAN
$ sudo cpan YAML Module::Build</code></pre>
<p>After these two steps CPAN will be able to install SDL:</p>
<pre><code> $ sudo cpan SDL</code></pre>
<p>For most platforms a CPAN install will suffice. Supported and tested
platforms are listed at http://pass.cpantesters.org/distro/S/SDL.html.</p>
<h2>Contact</h2>
<p>Hopefully this book answers most of your questions. For additional
assistance, contact the project via:</p>
<ul>
<li><i>the web</i>, by visiting the SDL Perl homepage at
http://sdl.perl.org/.</li>
<li><i>IRC</i>, in the <code>#sdl</code> channel on
<code>irc.perl.org</code>. This is a very active and helpful resource.</li>
<li><i>email</i>, through the <code>sdl-devel@perl.org</code> mailing
list.</li>
</ul>
<h2>Examples</h2>
<p>The code examples in this book are available from
https://github.com/PerlGameDev/SDL_Manual/tree/master/code_listings.</p>
<h2>Acknowledgements</h2>
<p>Thanks to contributors and reviewers from the <code>#sdl</code> channel,
including:</p>
<ul>
<li>Alias
<li>bobross
<li>Blaizer
<li>cfedde
<li>chromatic
<li>FROGGS
<li>garu
<li>jamesw
<li>perlpilot
<li>PerlJam
<li>Pip
<li>waxhead
<li>and many more
<pre><code> (Apologies if I have missed you; let me know and I will add you.)</code></pre>
</ul>
<h1>The Screen</h1>
<p> </p>
<p>SDL's primary purpose is to display graphics. It does so by providing an
abstraction called a <i>screen</i>, which represents a <i>video device</i>.
This video device is an interface provided by your operating system, such
as X11 or DirectX. Before you can display anything, you must create a
screen. The <code>SDLx::App</code> class does so for you:</p>
<pre><code> use strict;
use warnings;
use SDL;
use SDLx::App;
my $app = SDLx::App->new();
sleep( 2 );</code></pre>
<p>This example causes an empty window to appear on the desktop. Most
systems will fill that window with the color black. Other systems might
display a transparent window. SDL's default behavior is to fill the screen
with black. To enforce this behavior on all systems, you must
<code>update()</code> the app to draw to the window:</p>
<pre><code> $app->update();</code></pre>
<h2><code>SDLx::App</code> Options</h2>
<p><code>SDLx::App</code> allows you to specify several options for the
screen and your application. First are the physical dimensions of the
screen itself. To make the screen of the <code>SDLx::App</code> window a
400×400 pixel square, change the initialization line to:</p>
<pre><code> my $app = SDLx::App->new( width => 400, height => 400 );</code></pre>
<p>Another important option is the window's title. Some systems display the
path to the running program. Others leave the title blank. You can change
the displayed title with another argument to the <code>SDLx::App</code>
constructor:</p>
<pre><code> my $app = SDLx::App->new( width => 400,
height => 400,
title => 'Pong - A clone' );</code></pre>
<p>At this point your screen will be:</p>
<p>\includegraphics[width=0.5\textwidth]{../src/images/first.png}
\caption{Your first SDL screen!} \label{fig:first_screen}</p>
<h3>Shortcuts</h3>
<p>Abbreviations for these parameters are available. Instead of
<code>width</code>, <code>height</code>, and <code>title</code>, you may
use <code>w</code>, <code>h</code>, and <code>t</code> respectively. The
previous example could also be written:</p>
<pre><code> my $app = SDLx::App->new( w => 400,
h => 400,
t => 'Pong - A clone' );</code></pre>
<h1>Drawing</h1>
<p>SDL provides several ways to draw graphical elements on the screen in
three general categories: primitives, images, and text. All drawing occurs
on a surface, represented by the <code>SDLx::Surface</code> class. Even the
<code>SDLx::App</code> is an <code>SDLx::Surface</code>. Though this means
it's possible to draw directly to the app's surface, there are several
advantages to drawing on multiple surfaces.</p>
<h2>Coordinates</h2>
<p>SDL's surface coordinate system has its origin (where both the x and y
coordinates have the value of zero) in the upper left corner. As the value
of x increases, the position moves to the right of the origin. As the value
of y increases, the position moves downward from the origin. The API always
lists coordinates in x, y order.</p>
<blockquote>
<p>The SDL library documentation has an extended discussion on coordinates:
http://sdltutorials.com/sdl-coordinates-and-blitting.</p>
</blockquote>
<h2>Drawing with SDL</h2>
<p>You can produce original pictures knowing little more than how to draw
to a surface with SDL:</p>
<p>\includegraphics[width=0.5\textwidth]{../src/images/flower.png}
\caption{A field of flowers} \label{fig:flowers}</p>
<h3>Surface Drawing Methods</h3>
<p>As mentioned earlier, all drawing in SDL requires a surface. The
<code>SDLx::Surface</code> object provides access to methods in the form
of:</p>
<pre><code> $surface->draw_{something}( .... );</code></pre>
<p>Parameters to these methods are generally coordinates and colors,
provided as array references.</p>
<h4>Rectangular Parameters</h4>
<p>Some parameters are sets of coordinate positions and dimensions. For
example, parameters to describe a rectangle of <code>40x40</code> pixels
placed at <code>(20, 20)</code> pixel units on the screen make a
four-element array reference of x, y, width, height:</p>
<pre><code> my $rect = [20, 20, 40, 40];</code></pre>
<h4>Color</h4>
<p></p>
<p>Need to document what the magnitude of the color and transparency values
mean.</p>
<p>SDL color parameters require four-element array references. The first
three numbers define the Red, Green, and Blue intensity of the color. The
final number defines the transparency of the color.</p>
<pre><code> my $color = [255, 255, 255, 255];</code></pre>
<p>The magnitude of each color value determines how much of that color
component will be mixed into the resulting color. A 0 value specifies that
none of the color channel should be used while 255 specifies a maximum
intensity for a particular channel. The first value corresponds with the
Red channel, so a higher number there means more red will be mixed into the
resulting color. It is a common practice to achieve a grayscale of varying
intensity by specifying the same value for each of the Red, Green, and Blue
color channels. The fourth and final value designates the transparency (or
Alpha channel) where a 0 value makes the resulting color fully transparent
and 255 makes it entirely opaque. A transparency value somewhere in between
will allow underlying (pixel data of surfaces below the current one) colors
to be blended with the specified RGB values into the final color
output.</p>
<p>You may also represent a color as hexadecimal values, where the values
of the numbers range from 0-255 for 32 bit depth in RGBA format:</p>
<pre><code> my $color = 0xFFFFFFFF;
my $white = 0xFFFFFFFF;
my $black = 0x000000FF;
my $red = 0xFF0000FF;
my $green = 0x00FF00FF;
my $blue = 0x0000FFFF;</code></pre>
<p>... or as four-byte hexadecimal values, where each two-digit byte
encodes the same RGBA values:</p>
<pre><code> my $goldenrod = 0xDAA520FF;</code></pre>
<blockquote>
<h5>NOTE: Depth of Surface</h5>
<p>The color depth of the surface--how many bits are available to describe
colors--is a property of the relevant <code>SDLx::Surface</code> or
<code>SDLx::App</code>. Set it in its constructor:</p>
<pre><code> my $app = SDLx::App->new( depth => 32 );</code></pre>
<p>The default bit depth is 32, such that each color component has 256
possible values. Other options are 24, 16, and 8.</p>
</blockquote>
<h3>Pixels</h3>
<p>All <code>SDLx::Surface</code>s are collections of pixels. You can read
from and write to these pixels by treating the surface as an array
reference:</p>
<pre><code> $app->[$x][$y] = $color;</code></pre>
<p>... where <code>$color</code> is an unsigned integer value using the
hexadecimal format (<code>0xRRGGBBAA</code>) <i>or</i> an anonymous array
of the form <code>[$red, $green, $blue, $alpha]</code>.</p>
<h3>Primitives</h3>
<p></p>
<p>Drawing primitives are simple shapes that SDL supports natively.</p>
<p>\includegraphics[width=0.5\textwidth]{../src/images/draw-1.png}
\caption{Drawing a line} \label{fig:draw_line}</p>
<h4>Lines</h4>
<p>A line is a series of contiguous pixels between two points. The
<code>draw_line</code> method causes SDL to draw a line to a surface:</p>
<pre><code> $app->draw_line( [200, 20], [20, 200], [255, 255, 0, 255] );</code></pre>
<p>This will draw a yellow line from positions <code>(200, 20)</code> to
<code>(20, 200)</code>.</p>
<p>\includegraphics[width=0.5\textwidth]{../src/images/draw-2.png}
\caption{Drawing a Rectangle} \label{fig:draw_rect}</p>
<h4>Rectangles</h4>
<p></p>
<p>A rectangle is a four-sided, filled polygon. Rectangles are a common
building block for games. In SDL, rectangles are the most cost effective of
the primitives to draw. The <code>draw_rect</code> method draws a rectangle
on a surface:</p>
<pre><code> $app->draw_rect( [10, 20, 40, 40 ], [255, 255, 255,255] );</code></pre>
<p>This draws a white square of size <code>40x40</code> onto the screen at
the position <code>(10,20)</code>.</p>
<p>\includegraphics[width=0.5\textwidth]{../src/images/draw-3.png}
\caption{Drawing a Circle} \label{fig:draw_circle}</p>
<p>\includegraphics[width=0.5\textwidth]{../src/images/draw-4.png}
\caption{Drawing a filled Circle} \label{fig:draw_filled_circle}</p>
<h4>Circles</h4>
<p></p>
<p>A circle is a primitive a fixed radius around a given point. Circles may
be filled or unfilled. The <code>draw_circle</code> and
<code>draw_circle_filled</code> methods draw these to a surface:</p>
<pre><code> $app->draw_circle( [100, 100], 20, [255, 0, 0, 255] );
$app->draw_circle_filled( [100, 100], 19, [0, 0, 255, 255] );</code></pre>
<p>These draw an unfilled red circle and a filled blue circle.</p>
<p>SDL provides more complex primitives in
<code>SDL::GFX::Primitives</code>.</p>
<h3>Drawing with Primitives</h3>
<p>It's easy to combine several primitives to draw an interesting
images.</p>
<pre><code> use strict;
use warnings;
use SDL;
use SDLx::App;
my $app = SDLx::App->new(
w => 500,
h => 500,
d => 32,
title => 'Pretty Flowers'
);
# Add the blue skies
$app->draw_rect( [ 0, 0, 500, 500 ], [ 20, 50, 170, 255 ] );
# Draw a green field
$app->draw_rect( [ 0, 400, 500, 100 ], [ 50, 170, 20, 100 ] );
# Make a surface for the flower
my $flower = SDLx::Surface->new( width => 50, height => 100 );
# With a black background
$flower->draw_rect( [ 0, 0, 50, 100 ], [ 0, 0, 0, 0 ] );
# Draw a pretty green stem
$flower->draw_rect( [ 23, 30, 4, 100 ], [ 0, 255, 0, 255 ] );
# And a simple flower bud
$flower->draw_circle_filled( [ 25, 25 ], 10, [ 150, 0, 0, 255 ] );
$flower->draw_circle( [ 25, 25 ], 10, [ 255, 0, 0, 255 ] );
# Draw flower on $app
$flower->blit( $app, [ 0, 0, 50, 100 ] );
$app->update();
sleep(1);</code></pre>
<p>\includegraphics[width=0.5\textwidth]{../src/images/flower-1.png}
\caption{Looks so lonely there all alone} \label{fig:draw_flower_lone}</p>
<h2>Drawing on Multiple Surfaces</h2>
<p>The examples so far have drawn on only a single surface, the display.
SDL makes it possible to write on multiple surfaces. These other surfaces
exist only in memory until you draw them to the display.</p>
<h3>Creating Surfaces</h3>
<p>There are several ways to create an <code>SDLx::Surface</code> for use.
The most common is to create one manually with a constructor call:</p>
<pre><code> $surface = SDLx::Surface->new( width => $width, height => $height );</code></pre>
<p><code>SDL::Image</code> and <code>SDL::Video</code> can load images as
surfaces too. <code>SDL::Image</code> provides support for all types of
images, provided that the underlying <code>SDL_image</code> library
supports the image type you want to load. For example,
<code>SDL_image</code> must support PNG images to use:</p>
<pre><code> $surface = SDL::Image::load( 'picture.png' );</code></pre>
<p>In the event that the desired <code>SDL_image</code> library is
unavailable, you can fallback to the built-in support for the
<code>.bmp</code> format.</p>
<pre><code> $surface = SDL::Video::load_BMP( 'picture.bmp' );</code></pre>
<p>The <code>SDLx::Sprite</code> module provides another option to
manipulate surfaces.</p>
<h2>Lots of Flowers but One Seed</h2>
<p>The flower example used a method called <code>blit</code> to draw a
surface to the display. This method copies data from one surface to
another. It's a fundamental operation, but it's a low level operation.
<code>SDLx::Sprite</code> provides higher level options. Besides making
drawing simpler, <code>SDLx::Sprite</code> adds several other features
useful for moving images. Here's a revised example using
<code>SDLx::Sprite</code> for flowers:</p>
<pre><code> use strict;
use warnings;
use SDL;
use SDLx::App;
use SDLx::Sprite;
my $app = SDLx::App->new(
w => 500,
h => 500,
d => 32,
title => 'Pretty Flowers'
);
# Adding blue skies
$app->draw_rect( [ 0, 0, 500, 500 ], [ 20, 50, 170, 255 ] );
# Draw a green field
$app->draw_rect( [ 0, 400, 500, 100 ], [ 50, 170, 20, 100 ] );
my $flower = SDLx::Sprite->new( width => 50, height => 100 );
# Use ->surface() to access a sprite's SDLx::Surface
# Make the background black
$flower->surface->draw_rect( [ 0, 0, 50, 100 ], [ 0, 0, 0, 0 ] );
# Now for a pretty green stem
$flower->surface->draw_rect( [ 23, 30, 4, 100 ], [ 0, 255, 0, 255 ] );
# Add the simple flower bud
$flower->surface->draw_circle_filled( [ 25, 25 ], 10, [ 150, 0, 0, 255 ] );
$flower->surface->draw_circle( [ 25, 25 ], 10, [ 255, 0, 0, 255 ] );
$flower->draw_xy( $app, 0, 0 );
$app->update();
sleep(1);</code></pre>
<p>Flowers usually don't grow in the sky. Flowers make more sense on the
ground. It's easy to insert plenty of identical flowers from a single
sprite. Replace the line:</p>
<pre><code> $flower->draw_xy( $app, 0, 0 );</code></pre>
<p>... with:</p>
<pre><code> for (0 .. 500) {
my $y = 425 - rand( 50);
$flower->draw_xy( $app, rand(500) - 20, $y );
}</code></pre>
<p>... to make an entire field of flowers.</p>
<p>Probably don't need this.</p>
<h1>Handling Events</h1>
<p></p>
<p>The cornerstone of an SDL application is event handling. The user
presses a key or moves the mouse. The operating system switches the focus
of the active window. The user selects the quit option from the menu or the
operating system. These are all events. How do you handle them?</p>
<p> </p>
<p>SDL provides an event queue which holds all events that occur until they
are removed. Every time an event occurs, SDL places it into the queue. The
<code>SDL::Event</code> object represents this queue in Perl, allowing you
to add and remove events constantly:</p>
<pre><code> use strict;
use warnings;
use SDL;
use SDL::Event;
use SDL::Events;
use SDLx::App;
my $app = SDLx::App->new( w => 200, h => 200 );
my $event = SDL::Event->new();
my $quit = 0;
while (!$quit) {
# Updates the queue to recent events
SDL::Events::pump_events();
# process all available events
while ( SDL::Events::poll_event($event) ) {
# check by Event type
do_key() if $event->type == SDL_KEYDOWN;
}
}
sub do_key { $quit = 1 }</code></pre>
<p> </p>
<p>Every event has an associated type which represents the category of the
event. The previous example looks for a keypress event (footnote: SDL
separates the event of pressing a key from the event of releasing a key,
which allows you to identify combinations of keypresses, such as Ctrl + P
to print.). The SDL library defines several types of events, and SDL_perl
makes them available as constants with names such as
<code>SDL_KEYDOWN</code> and <code>SDL_QUIT</code>. See <code>perldoc
SDL::Events</code> for a list of all event types.</p>
<p></p>
<p>Checking for every possible event type within that event loop can be
tedious. The <code>SDLx::Controller</code> available from the
<code>SDLx::App</code> offers the use of event callbacks with which to
handle events. Processing events is a matter of setting up the appropriate
callbacks and letting SDL do the heavy work.</p>
<blockquote>
<p><b>SDL Events Types</b></p>
<p>Additional Event types that can be captured by SDL are:</p>
<ul>
<li>Keyboard
<p><code>SDL_KEYDOWN</code> <code>SDL_KEYUP</code> - Keyboard button
pressed</p>
<li>Mouse
<p><code>SDL_MOUSEMOTION</code> - Mouse motion occured</p>
<p><code>SDL_MOUSEBUTTONDOWN</code> <code>SDL_MOUSEBUTTONUP</code> - Mouse
button pressed</p>
<li>Joystick
<p><code>SDL_JOYAXISMOTION</code> - Joystick axis motion</p>
<p><code>SDL_JOYBALLMOTION</code> - Joystick trackball motion</p>
<p><code>SDL_JOYHATMOTION</code> - Joystick hat position change</p>
<p><code>SDL_JOYBUTTONDOWN</code> <code>SDL_JOYBUTTONUP</code> - Joystick
button pressed</p>
<li>Window & System
<p><code>SDL_ACTIVEEVENT</code> - Application visibility</p>
<p><code>SDL_VIDEORESIZE</code> - Window resized</p>
<p><code>SDL_VIDEOEXPOSE</code> - Window exposed</p>
<p><code>SDL_QUIT</code> - Quit requested</p>
<p><code>SDL_USEREVENT</code> - A user-defined event type</p>
<p><code>SDL_SYSWMEVENT</code> - Platform-dependent window manager
event</p>
</ul>
<p>For more information look at:</p>
<pre><code> perldoc SDL::Event </code></pre>
</blockquote>
<h2>Quitting with Grace</h2>
<p>The example applications so far have not exited cleanly. Handling quit
events is much better:</p>
<pre><code> use strict;
use warnings;
use SDL;
use SDL::Event;
use SDLx::App;
my $app = SDLx::App->new(
w => 200,
h => 200,
d => 32,
title => "Quit Events"
);
$app->add_event_handler( \&quit_event );
$app->run();
sub quit_event
{
# the callback receives the appropriate SDL::Event
my $event = shift;
# ... as well as the calling SDLx::Controller
my $controller = shift;
# stopping the controller will exit $app->run() for us
$controller->stop if $event->type == SDL_QUIT;
}</code></pre>
<p><code>SDLx::App</code> calls the event_handlers, from an internal
<code>SDLx::Controller</code>. When this event handler receives a quit
event, it calls <code>SDLx::Controller::stop()</code> which causes
<code>SDLx::App</code> to exit gracefully.</p>
<h3>Exit on Quit</h3>
<p>Exiting on receiving the <code>SDL_QUIT</code> event is such a common
operation that <code>SDLx::App</code> provides it as a constructor
option:</p>
<pre><code> use strict;
use warnings;
use SDL;
use SDLx::App;
my $app = SDLx::App->new(
w => 200,
h => 200,
d => 32,
title => "Quit Events",
exit_on_quit => 1
);
$app->run();</code></pre>
<h2>Small Paint: Input Devices</h2>
<p>SDL events also allow input handling. Consider a simple paint program.
It will provide a small black window. Moving the mouse draws on this
window. Pressing a number key chooses a paint color. Pressing
<code>q</code> or <code>Q</code> exits the program. Pressing <code>c</code>
or <code>C</code> clears the screen. Pressing <code>Ctrl-S</code> saves the
image to a file named <i>painted.bmp</i>.</p>
<p>\includegraphics[width=0.5\textwidth]{../src/images/painted.png}
\caption{Simple Paint: Smile} \label{fig:Smile}</p>
<h3>Saving the image</h3>
<p>Start by defining the saving function:</p>
<pre><code> sub save_image {
if (SDL::Video::save_BMP( $app, 'painted.bmp' ) == 0
&& -e 'painted.bmp')
{
warn 'Saved painted.bmp to ' . cwd();
}
else
{
warn 'Could not save painted.bmp: ' . SDL::get_errors();
}
}</code></pre>
<h3>Keyboard</h3>
<p>Keyboard handling requires some color data as well as a keypress
callback:</p>
<pre><code> my $brush_color = 0;
sub keyboard_event
{
my $event = shift;
if ( $event->type == SDL_KEYDOWN )
{
# convert the key_symbol (integer) to a keyname
my $key_name = SDL::Events::get_key_name( $event->key_sym );
# if $key_name is a digit, use it as a color
$brush_color = $key_name if $key_name =~ /^\d$/;
# get the keyboard modifier (see perldoc SDL::Events)
my $mod_state = SDL::Events::get_mod_state();
# we are using any CTRL so KMOD_CTRL is fine
save_image() if $key_name =~ /^s$/ && ($mod_state & KMOD_CTRL);
# clear the screen
$app->draw_rect( [ 0, 0, $app->w, $app->h ], 0 )
if $key_name =~ /^c$/;
# exit
$app->stop() if $key_name =~ /^q$/;
}
$app->update();
}
$app->add_event_handler(\&quit_event);
$app->add_event_handler(\&keyboard_event);</code></pre>
<blockquote>
<p><b>NOTE: </b> When adding a callback to <code>SDLx::App</code> which
uses variables declared outside of the function (<code>$brush_color</code>
and <code>@colors</code> in this case), be sure to define them before
declaring the subroutine. Normal Perl scoping and initialization rules
apply.</p>
</blockquote>
<h3>Mouse</h3>
<p>Handling mouse events is almost as straightforward as keyboard events:
=begin programlisting</p>
<pre><code> # track the drawing status
my $drawing = 0;
sub mouse_event {
my $event = shift;
# detect Mouse Button events and check if user is currently drawing
if ($event->type == SDL_MOUSEBUTTONDOWN || $drawing)
{
# set drawing to 1
$drawing = 1;
# get the X and Y values of the mouse
my $x = $event->button_x;
my $y = $event->button_y;
# draw a rectangle at the specified position
$app->draw_rect( [ $x, $y, 2, 2 ], $colors[$brush_color] );
$app->update();
}
# disable drawing when user releases mouse button
$drawing = 0 if ($event->type == SDL_MOUSEBUTTONUP );
}
$app->add_event_handler( \&mouse_event );</code></pre>
<p>This is all of the code necessary to make a simple drawing
application.</p>
<p>Take note of two things. First, SDL_perl invokes the event handlers in
the order of attachment. If the user presses <code>Q</code> and then moves
the mouse, the application will quit before processing the mouse
movement.</p>
<p>Second, the application makes no distinction between right, middle, or
left mouse clicks. SDL provides this information. See the
<code>button_button()</code> method in <code>SDL::Event</code>.</p>
<h2>POD ERRORS</h2>
<p>Hey! <b>The above document had some coding errors, which are explained
below:</b></p>
<ul>
<li>Around line 317:
<p>=end programlisting without matching =begin. (Stack: [empty])</p>
</ul>
<h1>The Game Loop</h1>
<p></p>
<p>Just as an interactive SDL app builds around an event loop, a game
builds around a game loop. The simplest game loop is something like:</p>
<pre><code> while (!$quit)
{
get_events();
calculate_next_positions();
render();
}</code></pre>
<p>The names of the functions called in this loop hint at their purposes,
but the subtleties of even this simple code are important.
<code>get_events()</code> obviously processes events from the relevant
input devices (keyboard, mouse, joystick). Processing events at the start
of every game loop iteration helps to prevent lag.</p>
<p><code>calculate_next_positions</code> updates the game state according
to user input as well as any active animations (a player walking, an
explosion, a cut scene). <code>render()</code> finally updates and displays
the screen.</p>
<h2>A Practical Game Loop</h2>
<p>Consider a game with a moving laser bolt:</p>
<pre><code> use strict;
use warnings;
use SDL;
use SDL::Event;
use SDL::Events;
use SDLx::App;
my $app = SDLx::App->new(
width => 200,
height => 200,
title => 'Pew Pew'
);
my $quit = 0;
# start laser on the left
my $laser = 0;
sub get_events {
my $event = SDL::Event->new();
SDL::Events::pump_events;
while( SDL::Events::poll_event($event) )
{
$quit = 1 if $event->type == SDL_QUIT
}
}
sub calculate_next_positions {
# move the laser
$laser++;
# if the laser goes off the screen, bring it back
$laser = 0 if $laser > $app->w();
}
sub render {
# draw the background first
$app->draw_rect( [ 0, 0, $app->w, $app->h ], 0 );
# draw the laser halfway up the screen
$app->draw_rect( [ $laser, $app->h / 2, 10, 2 ], [ 255, 0, 0, 255 ]);
$app->update();