File: examples.xml

package info (click to toggle)
clanlib 0.5.4-1-6
  • links: PTS
  • area: main
  • in suites: woody
  • size: 10,320 kB
  • ctags: 10,893
  • sloc: cpp: 76,056; xml: 3,281; sh: 2,961; perl: 1,204; asm: 837; makefile: 775
file content (768 lines) | stat: -rw-r--r-- 29,811 bytes parent folder | download
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
<xml>
<head>
<title> ClanLib tutorial: The first steps </title>
</head>
<body>

<a href="advanced.html"><img src="Images/prev.gif"></a>
<a href="index.html"><img src="Images/toc.gif"></a>
<a href="index.html"><img src="Images/next.gif"></a>

<h3>THIS TUTORIAL IS OUTDATED, PLEASE DO NOT USE!</h3>

<h1> The first steps </h1>

Here I will describe some simple examples of programs. Finally, code! 
The programs are divided into the following categories:
  <ul>
    <li> <a href="#2dgraphics">2D Graphics</a><br>
         How to work with displays, surfaces and other 2d-graphics.
    <li> <a href="#resourcemanager">The ResourceManager</a><br>
         Working with resources, the ResourceManager and the datafile_compiler.
    <li> <a href="#input">Handling input</a><br>
         How to read keyboard, mouse and joystick input.
    <li> <a href="#sound">Sound</a><br>
         How to use network support.
  </ul> 

But first a note on compiling the code. You'll need a c++ compiler which
can handle exceptions. If it starts whining about reserved words like
'catch', 'throw' and 'try' you probably need to upgrade your compiler. On
Linux/Unix systems, you'll need to link the clanlib libraries. If you only
use layer1 stuff from ClanLib you need to link the <i>clan</i> library. If
you use layer2 classes, you'll also need to link <i>clanlayer2</i>.<br>
The commandline I use looks like this: 

<pre><code>
  g++ -lclan -lclanlayer2 -I ../ClanLib kwirk.cpp -o kwirk
</code></pre>

Use the -I to indicate where the ClanLib headerfiles reside. This way, you
can use <code>#include &lt;clanlib.h&gt;</code> and so make a clear
distinction between your own code, and the libraries you use. Note that in
the 0.3.x serie you don't need to specify the -I as the headerfiles are
copied into <code>/usr/local/include/ClanLib</code>. Remember that you
need to <code>#include &lt;ClanLib/core.h&gt;</code> instead of
<code>#include &lt;clanlib.h&gt;</code>.
 
<br> 
<p>
When you want to use the 0.3.x serie, you'll need to change the libs you compile to and the include files.
In 0.3.x you only link with what you need, so make your choice:
<ul>
  <li> libclanCore<br>
       Basic stuff, you'll need this one.
  <li> libclanGL<br>
       OpenGL support (Windows and Unix)
  <li> libclanMikMod<br>
       Soundmodules support (.xm, .mod, etc)
  <li> libclanPNG<br>
       PNG files support
  <li> libclanLua<br>
       Lua scripting language support
  <li> libclanCMPEG<br>
       MPEG player support
</ul>
All these files are by default installed in <code>/usr/local/lib/</code>.
<p>
The include files are installed in <code>/usr/local/ClanLib/</code> and are divided too.
<ul>
  <li> #include &lt;ClanLib/core.h&gt;<br>
       Basic stuff, you'll need this one.
  <li> #include &lt;ClanLib/gl.h&gt;<br>
       OpenGL support (Windows and Unix)
  <li> #include &lt;ClanLib/mikmod.h&gt;<br>
       Soundmodules support (.xm, .mod, etc)
  <li> #include &lt;ClanLib/png.h&gt;<br>
       PNG files support
  <li> #include &lt;ClanLib/lua.h&gt;<br>
       Lua scripting language support
  <li> #include &lt;ClanLib/cmpeg.h&gt;<br>
       MPEG player support
  <li> #include &lt;ClanLib/stl&gt;<br>
       Support for STL 
</ul>
So, if you want to compile these examples for 0.3.x you'll need to change the 
<code> #include </code> statements and pray the API hasn't changed too much ;).
<p>
If you want to compile under Windows, you'll need to link all the
libraries found in the distribution. This can be done somewhere in the
menu of your favourite compiler. Also see the README.TXT in the package.
<br> <font color=red>Correct me if I am
wrong here... I don't have a C++ compiler for windows... <font color=black> <p>
ClanLib supports several display targets. If you're running under
Linux/Unix than ClanLib will ask you which display target it should use.
Currently the following display-targets are used: svga, mesa, x11, ggi and
fbdev. You can make a ~/.clanlib file in which you can set a line
containing <code>target = &ltdisplaytarget&gt</code>. ClanLib will search
for this file and use the target which is specified herein.<br> Under
Windows, ClanLib will use DirectX (3 or better). In the new 0.3.x branche there is a configuration tool 
which allows you to choose between DirectX, PTC or OpenGL. Work is still in progress here. 

<a name="2dgraphics"></a> 
<h2> 2D Graphics </h2>

<a name="showingapicture"></a>
<h3> Showing a picture </h3>
The classic way of starting a tutorial is by saying "hello world!". Well,
I assume you already know how to do this with C/C++.
So, let's start with showing a picture with these famous words
in it. The program:
<a href="code/demo1.cpp">demo1.cpp</a>, and the picture 
<a href="code/image1.tga">image1.tga</a>.<br>
As you can see, quite a lot happens here. I'll walk you through it, step 
by step. <br>

<pre><code>
#include &lt;clanlib.h&gt;    
#include &lt;clanlayer2.h&gt; 
</code></pre>

These are the headerfiles that include the classdefinitions of ClanLib. The
first describes all Layer 1 files, the second the Layer 2. In this example
we use the CL_TargaProvider so we need the Layer 2 headerfile.
<p>

<pre><code>
class TDemo1 : public CL_ClanApplication
{
   ...
} app;
</code></pre>

As you can see, we create a new class derived from CL_ClanApplication and
create an instance called app. This is the way you make a ClanLib program.
<br>
If you make a new application you need to supply at least two functions:

<pre><code>
  virtual char *get_title()
  { return "Demo1: image viewing"; }

  virtual int main(int, char**)
  {
    ...
  }
</code></pre>

The get_title() is used when your program runs under X or Windows to show in 
the titlebar. <br>
The main() is exactly the same as the main() in a normal C/C++ program. 
<p>
Now, on to the more interesting parts.

<pre><code>
    CL_System::init_display();
    CL_Display::set_videomode(320, 200, 16);
</code></pre>

First, a call to <code>CL_System::init_display()</code> is done. This is needed to detect 
all videocards and set up some internal variables. Then, we call
<code>CL_Display::setvideomode(width,height,bpp)</code> to specify in which mode we should run.
In X or Windows the width and height will specify how large the window will be.
The bpp (or bits per pixel) specifies in which colormode it should run. Note 
that I use the CL_Display rather than CL_DisplayCard because I want to use
the default (primary) videocard. 

<pre><code>
    CL_Surface *image = CL_TargaProvider::create("helloworld.tga",NULL);
</code></pre>

This creates the surface which contains the image. Note that CL_TargaProvider 
actually is a CL_SurfaceProvider. The <code>::create()</code> is merely a handy
function which creates a surface with a surfaceprovider of the CL_TargaProvider type.
This is actually equivalent with: 
<pre><code>
  CL_Surface *image = CL_Surface::create( new CL_TargaProvider("helloworld.tga",NULL), true );
</code></pre>
Note that, again, we use a static function <code>::create</code>. The contructor
for CL_Surface (and many other classes) are not public. This is because several
other things have to be done before the actual Surface can be created. Therefor
the constructor is wrapped into a function. And it's easier. Now, if you are
out of memory or for another reason the CL_Surface can't be created, ClanLib
will assert and prevent possible NULL-pointer exceptions this way. 

<pre><code>
    image->put_screen(0,0);
    CL_Display::flip_display();
</code></pre>

The first line gives the surface the command to draw itself onto the backbuffer.
It is not yet shown, see "Buffering" in 
<a href="part2.html#2dgraphics_buffering">Basics</a> 
for a brief discussion why. The second line gives the Display the order to
show the surface on the backbuffer on the screen. This will actually show the
picture.

<pre><code>
    while (CL_Keyboard::get_keycode(CL_Keyboard::KEY_ESCAPE) == 0)
      CL_System::keep_alive();
</code></pre>

The CL_Keyboard is here used to check if the Escape-key is pressed. It does 
this in a loop and doing so, it halts the entire program, not allowing ClanLib
to do anything. Therefor you need to call CL_System::keep_alive() once in a 
while. This refreshes the keyboardbuffer and does many other things.

<pre><code>
    delete image;
</code></pre>

Yeps, just like your mammy always says. CLEAN UP AFTER YOU'RE DONE WITH IT.
Ah well, has nothing to do with ClanLib. It is just good coding to 
clean up your own mess. (Except in Java that is ;)
<p>
So, there you have it. Your first ClanLib program. Nothing to it, is there?

<a name="layers"></a>
<h3> Working with layers and alpha-channels </h3>

So, now let's do something more difficult. Let's work with two pictures, in two 
different layers moving over each other without getting mixed up. And,
let's do some alpha-channeling at the same time. (See 
<a href="part2.html#2dgraphics_aboutcolors">Basics</a> for more details).
The picture I used before (<a href="code/image1.tga">image1.tga</a>) 
has an alphachannel.
<a href="code/demo2.cpp">Here</a> is the code. I'll walk you through it again.
<p>
I'll skip the things I've mentioned before. So, let's look at some of the new
parts:

<pre><code>
    cout &lt;&lt; "Creating LayerManager" &lt;&lt; endl;
    CL_LayerManager *layerm = new CL_LayerManager( 2 );
    layerm-&gt;put_screen( image1, 0, 0, 0, 0 );
    layerm-&gt;put_screen( image2, 100, 100, 0, 1 );
</code></pre>

As you can see, the CL_LayerManager is created with two layers. Nope, no
fancy <code>::create</code> here. I believe the LayerManager is a bit of
an ugly duck in the family, as it has no high priority. Nevertheless, it
is pretty usefull as it is. Now, the <code>put_screen()</code> function
loads the image into the layer. The first parameter is the image, the
second and third give the image an initial position in the layer. The
fourth parameter is the index of the sprite which is to be used (in this
case 0, the surface has only one picture). The last indicates the number
of the layer. So, image1 is loaded on layer 0, and image2 is loaded on
layer 1.

<pre><code>
    layerm-&gt;show_layers();
    layerm-&gt;select_layer( 1 );
</code></pre>

The <code>show_layers()</code> well, erhm shows the layers :). it draws them 
on the backbuffer. Remember this, all drawing occurs onto the backbuffer, so
if you want to actually show something you'll have to use 
<code>CL_Display::flip_display()</code>.<br>
The <code>select_layer(<i>layer</i>)</code> selects a default layer. It was in
this demo for a reason I forgot. It is here now, because I forgot to take it 
out :). It is useful if you do a lot with one particular frame. 

<pre><code>
      CL_Display::clear_display( 0, 0, 0, 1 );
</code></pre>

This sets the display to the color specified by the first three arguments.
The first specifies the red component, the second green, third blue. The fourth
value is the alpha component to use. Remember, if it is 0 it pretty much
does nothing, 1 is default. If you do not set it to 1, the display is not
completely cleared because the original display is mixed with the specified
color. I like black for a background color, and I don't want the images to
leave a track behind. So, I'll fill in 0,0,0 for the color and 1 for the 
alpha-component. Note that I could have left the fourth digit away, as it 
is the default value.

<pre><code>
      layerm-&gt;move_layer( layer_a, d, d );
      layerm-&gt;move_layer( layer_b, -d, -d );
</code></pre>

This <code>move_layer( <i>layer</i>,<i>delta_x</i>,<i>delta_y</i> )</code>
shifts the surfaces in the specified layer with (delta_x,delta_y).

<pre><code>
        layerm-&gt;swap_layers( layer_a, layer_b );
</code></pre>

<code>swap_layers( <i>layer1</i>, <i>layer2</i> )</code> swaps the surfaces
in layer1 and layer2. Nothing more, nothing less.
<p>
So, that's all. All the alpha-blending is done without you having to do
anything. 

<a name="resourcemanager"</a>
<h2> Working with resources </h2>

Clanlib has a very powerful toy for resourcemanagement. A game often consist
of many levels, graphics and sounds and to manage these the CL_ResourceManager
is created. As explained in the previous chapter, you can create a datafile
which contains all information your game needs. 
First I'll describe an example of the scripting language, then how to use
the compiled datafile in your program.<br>
Let's take the previous program as an example. I'll put the image we use in
the datafile, as well as an integer indicating how many loops it should make.
<a href="code/demo3.scr">Here</a> is the scriptfile. You can compile this with
<code>datafile_compiler demo3.scr demo3.dat</code>. The first argument is the
scriptfile, the second the datafile to output. So, let's look at the scriptfile:

<pre><code>
// the demo3 script file

// location = datafile("demo3.dat");
</code></pre>

Lines starting with <code>//</code> or <code>#</code> are considered comment.
The ResourceManager has currently two ways of reading its data. Directly from 
the original files, or from the compiled datafile. The location line was used
to specify which datafile to use if you omitted it in the constructor for the
ResourceManager. This is obsolete now, so don't use it anymore.

<br>


<pre><code>
section Demo3
{
        image1  = image1.tga    (type=surface);
        image2  = image1.tga    (type=surface);
        n_loops = 100           (type=integer, base=10);
}
</code></pre>

As you can see, a scriptfile is divided into sections. Sections can be
nested. Inside a section you can specify fields. Each field has a name and
a value assigned to it. The name is used to identify the resource. For example:
to name the image1 one should use "Demo3/image1". For nested sections:
"Demo3/nested_section1/nested_section2/name".<br>

Most of the time, the value is a filename, but for
strings and integers, this is the value you want the field to have.
Between the brackets you can specify options. One important option is
'type' which indicates which type of resource this field is. If you ommit
the type, ClanLib will try to figure out the type itself. It is
recommended to specify the type because it will not always be right...
You can also specify other options, depending on the type of resource. For
example: the integer-resource has a 'base' option, specifying which base the 
number given is based on. With a surface-resource you can specify which 
section of the image to use, amongst other options.<br>
Currently the following resources are supported: 
<ul>
  <li> integer
  <li> string
  <li> boolean
  <li> surface
  <li> palette
  <li> font
  <li> sample
  <li> raw 
</ul>

Now you have a datafile, but how do you use it in a game? Quite simpel.
Let's look at an <a href="code/demo3.cpp">example</a>.
It's almost the same as the previous demo, but now it loads the picture from 
a resourcefile, and a integer named n_loops which should indicate how often the
demo should loop.<br>
Some of the more interesting changes:

<pre><code>
    cout << "Loading resources" << endl;
    CL_ResourceManager *resources = new CL_ResourceManager( "demo3.dat", true );

    assert( resources!=NULL );
</code></pre>

First, we need to create the resourcemanager. This is done pretty easy,
just use a constructor. Here I just the most common constructor with the
datafile as the first argument, and as a second argument a bool indicating
if you want to read from a datafile or scriptfile. If you don't want to
recompile the datafile each time you want to test it, you'll need to tell
the ResourceManager that you want it to use the scriptfile. You could use
the following constructor:

<pre><code>
    CL_ResourceManager *resources = new CL_ResourceManager( "demo3.scr", false );
</code></pre>

The first argument is now the scriptfile, the second indicates that the 
ResourceManager should use the original sources instead of the datafile.
  
<br>

<pre><code>
    CL_Surface *image1 = CL_Res_Surface::load("Demo3/image1", *resources);
    CL_Surface *image2 = CL_Res_Surface::load("Demo3/image2", *resources);
</code></pre>

To load a resource from the ResourceManager, use the <code>::load</code> 
function for the appropriate resource. In this case a CL_Res_Surface. The
first argument is the name of the resource, the second the resourcemanager to
use. It is as simple as that.

<pre><code>
    int n_loops = CL_Res_Integer::load("Demo3/n_loops", *resources, -1 );
</code></pre>

The two resources for constants (CL_Res_Integer, CL_Res_Boolean and CL_Res_String) can accept a
third argument. This is the default value. If the specified name does not
exist in the resourcefile, this value is used. Ofcourse, you can leave the 
third parameter away. The ResourceManager then asserts if the name does not
exist.

<font color="red">
In the 0.3.x branch resources are loaded using their representative classes. 
For example: <code>CL_Res_Surface</code> does no longer exist. Instead, use
<code>CL_Surface::load(<i>name</i>)</code>. The <code>CL_Res_Boolean</code>, 
<code>CL_Res_String</code> and <code>CL_Res_Integer</code> still exist though. 
This inconsistency is something which we need to work on...
<font color="black">

<p>
The other changes to the file are to implement n_loops and are not very 
interesting (or well coded for that matter ;P ) so I'll skip them.


<a name="input"</a>
<h2> Handling input</h2>

Here I'll discuss how to read input from the keyboard, mouse or joystick.  
In the previous examples I already used the keyboard interface so you
could press the escape-key to quit the program.  This is pretty basic use
of the CL_Keyboard class. 
<pre><code>
if( CL_Keyboard::get_keycode(CL_Keyboard::KEY_LEFT) )
{
  // do something intelligent here
}
</code></pre>

The <code>CL_Keyboard::get_keycode(<i>key</i>)</code> function returns true
if the key is pressed, false if not. As simple as that. Similar you can read
joysticks and the mouse:

<pre><code>
   int x = CL_Mouse::get_x();
   bool pressed = CL_Mouse::left_pressed();
</code></pre>

<p>
As I described in the 
<a href="part3.html#input">previous</a>
chapter, ClanLib supports abstraction from these 
devices. Most games support configurable keys so an abstraction from the actual 
keys is wished. 
Let's look at an example from the ClanLib-examples module: 
<a href="code/input_devices.cpp">input_devices.cpp</a>.

<pre><code>

// Abstract game input from physical input:
CL_InputButton_Group *fire_button = new CL_InputButton_Group;
CL_InputAxis_Group *hori_axis = new CL_InputAxis_Group;
CL_InputAxis_Group *vert_axis = new CL_InputAxis_Group;
 
</pre></code>

Here we create abstract devices for inputhandling. First, a <code>fire_button</code>
is created. In the rest of the game, if we want to know if the player wants to
fire, we'll use this object. As the name already suggests, the 
<code>CL_InputButton_Group</code> can handle a bunch of keys, al with the same 
purpose.<br>
The same way we create a horizontal axis, and a vertical axis 
(<code>hori_axis</code> and <code>vert_axis</code>). <br>
Although mouse support is handled a different way, the mouse can also create a
CL_Axis object. This will be like the mouse-aiming in games as Quake. 

<code><pre>

// Add keyboard input:
fire_button->add(
        CL_Input::keyboards[0]->get_button(CL_Keyboard::KEY_ESCAPE));

fire_button->add(
        CL_Input::keyboards[0]->get_button(CL_Keyboard::KEY_SPACE));

</pre></code>

Here, we hook up the actual keys to the <code>fire_button</code>. For each key
you want <code>fire_key</code> to react to, just call the <code>add( CL_Key )</code>.
Now, for a keyboard, these <code>CL_Key</code>'s are easy to obtain. Just use
the <code>get_button( <i>keyname</i> )</code> function. 

<pre><code>
hori_axis->add(
        new CL_InputButtonToAxis_Analog(
                CL_Input::keyboards[0]->get_button(CL_Keyboard::KEY_LEFT),
                CL_Input::keyboards[0]->get_button(CL_Keyboard::KEY_RIGHT)
                ));

vert_axis->add(
        new CL_InputButtonToAxis_Analog(
                CL_Input::keyboards[0]->get_button(CL_Keyboard::KEY_UP),
                CL_Input::keyboards[0]->get_button(CL_Keyboard::KEY_DOWN)
                ));

</code></pre>
Analogue, we create the axis. For an axis, we need two keys ofcourse.

<pre><code>
// Add joystick input (if available):
if (CL_Input::joysticks[0] != NULL)
{
        fire_button->add(CL_Input::joysticks[0]->get_button(0));
        fire_button->add(CL_Input::joysticks[0]->get_button(1));

        hori_axis->add(CL_Input::joysticks[0]->get_axis(0));
        vert_axis->add(CL_Input::joysticks[0]->get_axis(1));
}
</code></pre>

Now, let's check if any joysticks are detected. 
If <code>CL_Input::joysticks[0]==NULL</code> then there aren't any joysticks.
If there isn't a first, there isn't any... Ah well. It's simple :).
<br>
If you want to use a mouse like this, try the following code:

<pre><code>
        hori_axis->add(CL_Input::pointers[0]->get_axis(0));
        veri_axis->add(CL_Input::pointers[0]->get_axis(1));

        CL_InputButton *l_key = CL_Input::pointers[0]->get_button(0);
        CL_InputButton *r_key = CL_Input::pointers[0]->get_button(1);
</code></pre>


<code><pre>
while (fire_button->is_pressed() == false)
{
...
}
</pre></code>

So, here we see how to check when one of the keys is pressed. Just use the
<code>is_pressed()</code> function. 

<code><pre>
int x = CL_Display::get_width()/2 +
  (int) (hori_axis->get_pos()*CL_Display::get_width()/2);

int y = CL_Display::get_height()/2 +
  (int) (vert_axis->get_pos()*CL_Display::get_height()/2);
</pre></code>

Let's see how one can read an axis. The <code>get_pos()</code> returns a
float between 0 and 1. So, multiply this with the height or width of the
field you're working in and you'll get the position. 

<a name="network"</a>
<h2> Using network support </h2>
<font color=red>This stuff isn't tested because I haven't got time for it yet.
It should work though because I ripped the examples from Magnus' network overview ;)
<font color=black><br>

For network support, basically two classes are needed: <code>CL_Network</code>,
for finding and creating a game, and <code>CL_NetGame</code> which represents
an actual network game, and thus handles all data.<br>
As I described in the <a href="part3.html#network">previous</a> part,
there are two ways of communicating data.  First, I'll show how to set up
a network game. 
Second, I'll describe how you can write and 
read to NetChannels manually.
And as a third, I'll use the NetObject way. This is the easiest way
because most things are done for you. (And as such, the tutorial will be
shorter to write :P ). 

<h3> Setting up a network game </h3>

For a network game we need a server and clients. First, the server opens a game
on a certain port. 
<pre><code>
CL_NetGame *netgame = CL_Network::create_game("MyGame", 5555);
</code></pre>

The <code>create_game( <i>name</i>, <i>port</i> ) </code> does exactly
this.  The <i>name</i> is the game_id. Each game should use a different
one so a Quakegame doesn't try to connect to ClanBomber. (Although that would 
be funny...)

<br> Joining a game is just as easy. If you already know the ip or
computername the game will be on, just use:  
<pre><code> 
CL_NetGame *netgame; 
CL_Network::find_game_at("MyGame", "my.server.net", 5555);  
if( CL_Network::peek_game_found() )
	try 
	{
  		netgame = CL_Network::receive_game_found(5000); 
	}
	catch (CL_Error err)
	{
		cout << "Join failed: " << err.message << endl;
	}
else
	cout << "No games found at " << "my.server.net";
</code></pre>

The network game I am going to create is <code>netgame</code>. First we
try to find a game with id <code>MyGame</code> at a server called
<code>my.server.net</code> at portnumber <code>5555</code>. 
If you don't know the servername than you can use:
<pre><code>
  CL_Network::find_games_broadcast("MyGame", 5555);
</code></pre>

Both functions setup ClanLib to do some networking.  The
<code>CL_Network::peek_game_found()</code> returns true if any games are
found.  To actually get a CL_NetGame pointer, you need to call
<code>CL_Network::receive_game_found(<i>timeout</i>)</code>. 
This will get you the first game found on the specified server (or servers
in the second case) or a NULL-pointer or exception if there weren't any
games or some other error occured. If you (or the gamer) aren't satisfied
with this one, just call <code> receive_game_found(<i>timeout</i>)</code>
again and it'll give you the next one. If you have seen all games
available, and decided you actually wanted the first (*sigh*) than just
call <code>CL_Network::clear_games_found()</code> and you can start all
over again.

<h3> Reading and writing to NetChannels </h3>

Data is transferred as a CL_(Out/In)putSource_Memory object. If you write or
read to a NetChannel you must use this class. In it, you can store whatever
you want, see the documentation of the CL_InputSource en CL_OutputSource classes
how these work. (Or read the tutorial about these common classes when I come
around to those). 

You probably want to build a function that checks if the netgame has any data
for you. Remember that it should be called in time, or you'll get a queue of
messages waiting for you, and your game will fall behind.<br>
To find out if the server has any data waiting, use:
<pre><code>
if (netgame->peek(channel_nr)) 
{
  ... // read the data from the netgame here
}
</code></pre>

Here, <code>netgame</code> is the CL_NetGame pointer to the networkgame
you <i>joined</i>.  Remember, we are working on the client side. The <code>channel_nr</code>
is the number of the NetChannel you want to read from. <br>
Now, actually read the data:
<pre><code>
CL_InputSource_Memory updates = netgame->receive(channel_nr);
</code></pre>

As I said before, all data is written and read using CL_(In/Out)putSource_Memory.
A brief example how to extract data from the CL_InputSource_Memory class:
<pre><code>

int n_monsters = updates.read_int32();
for( int i=0; i&ltn_monsters; i++ )
  {
  monster[i].x = updates.read_int32();
  monster[i].y = updates.read_int32();
  }
</code></pre>

Now, let's see how to write to a channel. 
You can send a message to the server, to a specific computer, or to a group of
computers. I'll explain later how to create a group of computers.<br>
First, we create a datablock to send:
<pre><code>
CL_OutputSource_Memory msg;
msg.write_float32( myself.manapoints);
msg.write_float32( myself.hitpoints );
</code></pre>

And now, we send the data to the server:
<pre><code>
netgame->send( channel_nr, netgame->server, msg);
</code></pre>

The first and the last argument should be clear. These are the NetChannel
to which the message is sent, and the message itself. The second might
need some explaining. ClanLib has an easy way of creating NetGroups, a group
of computers (for example: in a team). The second argument is the group
you wish to send to. In this case this is the server and we get the 
server's NetGroup using the pointer <code>server</code> in the netgame object.

<h3> Using NetObjects </h3>

If you have a rather complicated game, you probably don't want each
network-aware to keep track of the networktraffic. An object should not be aware
when it's data is send or received. For this, ClanLib has created the CL_NetObject
class. This class has two abstract functions (
<code>
virtual void serialize_load(CL_InputSource *input)=0;</code> and
<code>virtual void serialize_save(CL_OutputSource *output)=0;</code>)
which you have to inherit to create the data-packages. Tha's all you need for a
network aware object. When the actual data is sent through the network is not
decided by the object, but by the game (or perhaps a CL_NetObjectController).
Another advantage is that there is no distinction if the object is controlled
local or on another computer.<br>

An example:
<pre><code>
class Monster: public CL_NetObject
{
  private:
    int x,y,hp;

  public:
    virtual void serialize_load(CL_InputSource *input)
    {
      x = input->read_int32();      
      y = input->read_int32();      
      hp = input->read_int32();      
    }
    virtual void serialize_save(CL_OutputSource *output)
    {
      output->write_int32(x);      
      output->write_int32(y);      
      output->write_int32(hp);      
    }
};
</code></pre>

If you have very simple objects which has a constant amount of variables
(like only coordinates and hitpoints) it is easier to use a derived class
of CL_NetObject called CL_NetObject_Simple. This class has already
inherited the serialize functions for you. Now you only have to indicate
which variables you wish to be communicated and you're ready to go. This
can be done in the constructor using the supplied add_xxx() functions.

<pre><code>
class Monster: public CL_NetObject_Simple
{
  private:
    int x,y,hp;

  public:
    Monster() 
    {
      add_int32( &x );
      add_int32( &y );
      add_int32( &hp );
    }
};
</code></pre>

Now, when does the actual data get sent? The NetObjects won't know. They 
don't need to know. ClanLib supplies a CL_NetObjectController which does 
most of the work. To this class you can <code>add()</code> a NetObject.
The CL_NetObjectController automatically creates a mirror-NetObject on every 
client so each participating computer can see it. Furthermore, you only have to
call the <code>update(<i>game</i>,<i>channel_nr</i>)</code> and everything else
is handled for you.

<font color=red>Erhm... Some code here would be nice :) Problem is,
I don't know yet how to get a list of all CL_NetObjects...
Will find out soon, just be patient.
<font color=black>

<p> 
<a href="advanced.html"><img src="Images/prev.gif"></a>
<a href="index.html"><img src="Images/toc.gif"></a>
<a href="index.html"><img src="Images/next.gif"></a>

</body>
</xml>