license stuff
[oweals/minetest.git] / src / test.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "test.h"
21 #include "common_irrlicht.h"
22 #include "debug.h"
23 #include "map.h"
24 #include "player.h"
25 #include "main.h"
26 #include "heightmap.h"
27 #include "socket.h"
28 #include "connection.h"
29 #include "utility.h"
30 #include "serialization.h"
31 #include "voxel.h"
32 #include <sstream>
33
34 #ifdef _WIN32
35         #include <windows.h>
36         #define sleep_ms(x) Sleep(x)
37 #else
38         #include <unistd.h>
39         #define sleep_ms(x) usleep(x*1000)
40 #endif
41
42 /*
43         Asserts that the exception occurs
44 */
45 #define EXCEPTION_CHECK(EType, code)\
46 {\
47         bool exception_thrown = false;\
48         try{ code; }\
49         catch(EType &e) { exception_thrown = true; }\
50         assert(exception_thrown);\
51 }
52
53 struct TestUtilities
54 {
55         void Run()
56         {
57                 /*dstream<<"wrapDegrees(100.0) = "<<wrapDegrees(100.0)<<std::endl;
58                 dstream<<"wrapDegrees(720.5) = "<<wrapDegrees(720.5)<<std::endl;
59                 dstream<<"wrapDegrees(-0.5) = "<<wrapDegrees(-0.5)<<std::endl;*/
60                 assert(fabs(wrapDegrees(100.0) - 100.0) < 0.001);
61                 assert(fabs(wrapDegrees(720.5) - 0.5) < 0.001);
62                 assert(fabs(wrapDegrees(-0.5) - (-0.5)) < 0.001);
63                 assert(fabs(wrapDegrees(-365.5) - (-5.5)) < 0.001);
64                 assert(lowercase("Foo bAR") == "foo bar");
65                 assert(is_yes("YeS") == true);
66                 assert(is_yes("") == false);
67                 assert(is_yes("FAlse") == false);
68         }
69 };
70                 
71 struct TestCompress
72 {
73         void Run()
74         {
75                 SharedBuffer<u8> fromdata(4);
76                 fromdata[0]=1;
77                 fromdata[1]=5;
78                 fromdata[2]=5;
79                 fromdata[3]=1;
80                 
81                 std::ostringstream os(std::ios_base::binary);
82                 compress(fromdata, os, 0);
83
84                 std::string str_out = os.str();
85                 
86                 dstream<<"str_out.size()="<<str_out.size()<<std::endl;
87                 dstream<<"TestCompress: 1,5,5,1 -> ";
88                 for(u32 i=0; i<str_out.size(); i++)
89                 {
90                         dstream<<(u32)str_out[i]<<",";
91                 }
92                 dstream<<std::endl;
93
94                 assert(str_out.size() == 10);
95
96                 assert(str_out[0] == 0);
97                 assert(str_out[1] == 0);
98                 assert(str_out[2] == 0);
99                 assert(str_out[3] == 4);
100                 assert(str_out[4] == 0);
101                 assert(str_out[5] == 1);
102                 assert(str_out[6] == 1);
103                 assert(str_out[7] == 5);
104                 assert(str_out[8] == 0);
105                 assert(str_out[9] == 1);
106
107                 std::istringstream is(str_out, std::ios_base::binary);
108                 std::ostringstream os2(std::ios_base::binary);
109
110                 decompress(is, os2, 0);
111                 std::string str_out2 = os2.str();
112
113                 dstream<<"decompress: ";
114                 for(u32 i=0; i<str_out2.size(); i++)
115                 {
116                         dstream<<(u32)str_out2[i]<<",";
117                 }
118                 dstream<<std::endl;
119
120                 assert(str_out2.size() == fromdata.getSize());
121
122                 for(u32 i=0; i<str_out2.size(); i++)
123                 {
124                         assert(str_out2[i] == fromdata[i]);
125                 }
126         }
127 };
128
129 struct TestMapNode
130 {
131         void Run()
132         {
133                 MapNode n;
134
135                 // Default values
136                 assert(n.d == MATERIAL_AIR);
137                 assert(n.getLight() == 0);
138                 
139                 // Transparency
140                 n.d = MATERIAL_AIR;
141                 assert(n.light_propagates() == true);
142                 n.d = 0;
143                 assert(n.light_propagates() == false);
144         }
145 };
146
147 struct TestVoxelManipulator
148 {
149         void Run()
150         {
151                 VoxelArea a(v3s16(-1,-1,-1), v3s16(1,1,1));
152                 assert(a.index(0,0,0) == 1*3*3 + 1*3 + 1);
153                 assert(a.index(-1,-1,-1) == 0);
154
155                 VoxelManipulator v;
156
157                 v.print(dstream);
158
159                 dstream<<"*** Setting (-1,0,-1)=2 ***"<<std::endl;
160
161                 //v[v3s16(-1,0,-1)] = MapNode(2);
162                 v[v3s16(-1,0,-1)].d = 2;
163
164                 v.print(dstream);
165
166                 assert(v[v3s16(-1,0,-1)].d == 2);
167
168                 dstream<<"*** Reading from inexistent (0,0,-1) ***"<<std::endl;
169
170                 assert(v[v3s16(0,0,-1)].d == MATERIAL_IGNORE);
171
172                 v.print(dstream);
173
174                 dstream<<"*** Adding area ***"<<std::endl;
175
176                 v.addArea(a);
177                 
178                 v.print(dstream);
179
180                 assert(v[v3s16(-1,0,-1)].d == 2);
181                 assert(v[v3s16(0,1,1)].d == MATERIAL_IGNORE);
182                 
183         }
184 };
185
186 struct TestMapBlock
187 {
188         class TC : public NodeContainer
189         {
190         public:
191
192                 MapNode node;
193                 bool position_valid;
194                 core::list<v3s16> validity_exceptions;
195
196                 TC()
197                 {
198                         position_valid = true;
199                 }
200
201                 virtual bool isValidPosition(v3s16 p)
202                 {
203                         //return position_valid ^ (p==position_valid_exception);
204                         bool exception = false;
205                         for(core::list<v3s16>::Iterator i=validity_exceptions.begin();
206                                         i != validity_exceptions.end(); i++)
207                         {
208                                 if(p == *i)
209                                 {
210                                         exception = true;
211                                         break;
212                                 }
213                         }
214                         return exception ? !position_valid : position_valid;
215                 }
216
217                 virtual MapNode getNode(v3s16 p)
218                 {
219                         if(isValidPosition(p) == false)
220                                 throw InvalidPositionException();
221                         return node;
222                 }
223
224                 virtual void setNode(v3s16 p, MapNode & n)
225                 {
226                         if(isValidPosition(p) == false)
227                                 throw InvalidPositionException();
228                 };
229
230                 virtual u16 nodeContainerId() const
231                 {
232                         return 666;
233                 }
234         };
235
236         void Run()
237         {
238                 TC parent;
239                 
240                 MapBlock b(&parent, v3s16(1,1,1));
241                 v3s16 relpos(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
242
243                 assert(b.getPosRelative() == relpos);
244
245                 assert(b.getBox().MinEdge.X == MAP_BLOCKSIZE);
246                 assert(b.getBox().MaxEdge.X == MAP_BLOCKSIZE*2-1);
247                 assert(b.getBox().MinEdge.Y == MAP_BLOCKSIZE);
248                 assert(b.getBox().MaxEdge.Y == MAP_BLOCKSIZE*2-1);
249                 assert(b.getBox().MinEdge.Z == MAP_BLOCKSIZE);
250                 assert(b.getBox().MaxEdge.Z == MAP_BLOCKSIZE*2-1);
251                 
252                 assert(b.isValidPosition(v3s16(0,0,0)) == true);
253                 assert(b.isValidPosition(v3s16(-1,0,0)) == false);
254                 assert(b.isValidPosition(v3s16(-1,-142,-2341)) == false);
255                 assert(b.isValidPosition(v3s16(-124,142,2341)) == false);
256                 assert(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
257                 assert(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE,MAP_BLOCKSIZE-1)) == false);
258
259                 /*
260                         TODO: this method should probably be removed
261                         if the block size isn't going to be set variable
262                 */
263                 /*assert(b.getSizeNodes() == v3s16(MAP_BLOCKSIZE,
264                                 MAP_BLOCKSIZE, MAP_BLOCKSIZE));*/
265                 
266                 // Changed flag should be initially set
267                 assert(b.getChangedFlag() == true);
268                 b.resetChangedFlag();
269                 assert(b.getChangedFlag() == false);
270
271                 // All nodes should have been set to
272                 // .d=MATERIAL_AIR and .getLight() = 0
273                 for(u16 z=0; z<MAP_BLOCKSIZE; z++)
274                         for(u16 y=0; y<MAP_BLOCKSIZE; y++)
275                                 for(u16 x=0; x<MAP_BLOCKSIZE; x++){
276                                         assert(b.getNode(v3s16(x,y,z)).d == MATERIAL_AIR);
277                                         assert(b.getNode(v3s16(x,y,z)).getLight() == 0);
278                                 }
279                 
280                 /*
281                         Parent fetch functions
282                 */
283                 parent.position_valid = false;
284                 parent.node.d = 5;
285
286                 MapNode n;
287                 
288                 // Positions in the block should still be valid
289                 assert(b.isValidPositionParent(v3s16(0,0,0)) == true);
290                 assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
291                 n = b.getNodeParent(v3s16(0,MAP_BLOCKSIZE-1,0));
292                 assert(n.d == MATERIAL_AIR);
293
294                 // ...but outside the block they should be invalid
295                 assert(b.isValidPositionParent(v3s16(-121,2341,0)) == false);
296                 assert(b.isValidPositionParent(v3s16(-1,0,0)) == false);
297                 assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == false);
298                 
299                 {
300                         bool exception_thrown = false;
301                         try{
302                                 // This should throw an exception
303                                 MapNode n = b.getNodeParent(v3s16(0,0,-1));
304                         }
305                         catch(InvalidPositionException &e)
306                         {
307                                 exception_thrown = true;
308                         }
309                         assert(exception_thrown);
310                 }
311
312                 parent.position_valid = true;
313                 // Now the positions outside should be valid
314                 assert(b.isValidPositionParent(v3s16(-121,2341,0)) == true);
315                 assert(b.isValidPositionParent(v3s16(-1,0,0)) == true);
316                 assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == true);
317                 n = b.getNodeParent(v3s16(0,0,MAP_BLOCKSIZE));
318                 assert(n.d == 5);
319
320                 /*
321                         Set a node
322                 */
323                 v3s16 p(1,2,0);
324                 n.d = 4;
325                 b.setNode(p, n);
326                 assert(b.getNode(p).d == 4);
327                 assert(b.getNodeMaterial(p) == 4);
328                 assert(b.getNodeMaterial(v3s16(-1,-1,0)) == 5);
329                 
330                 /*
331                         propagateSunlight()
332                 */
333                 // Set lighting of all nodes to 0
334                 for(u16 z=0; z<MAP_BLOCKSIZE; z++){
335                         for(u16 y=0; y<MAP_BLOCKSIZE; y++){
336                                 for(u16 x=0; x<MAP_BLOCKSIZE; x++){
337                                         MapNode n = b.getNode(v3s16(x,y,z));
338                                         n.setLight(0);
339                                         b.setNode(v3s16(x,y,z), n);
340                                 }
341                         }
342                 }
343                 {
344                         /*
345                                 Check how the block handles being a lonely sky block
346                         */
347                         parent.position_valid = true;
348                         b.setIsUnderground(false);
349                         parent.node.d = MATERIAL_AIR;
350                         parent.node.setLight(LIGHT_SUN);
351                         core::map<v3s16, bool> light_sources;
352                         // The bottom block is invalid, because we have a shadowing node
353                         assert(b.propagateSunlight(light_sources) == false);
354                         assert(b.getNode(v3s16(1,4,0)).getLight() == LIGHT_SUN);
355                         assert(b.getNode(v3s16(1,3,0)).getLight() == LIGHT_SUN);
356                         assert(b.getNode(v3s16(1,2,0)).getLight() == 0);
357                         assert(b.getNode(v3s16(1,1,0)).getLight() == 0);
358                         assert(b.getNode(v3s16(1,0,0)).getLight() == 0);
359                         assert(b.getNode(v3s16(1,2,3)).getLight() == LIGHT_SUN);
360                         assert(b.getFaceLight(p, v3s16(0,1,0)) == LIGHT_SUN);
361                         assert(b.getFaceLight(p, v3s16(0,-1,0)) == 0);
362                         // According to MapBlock::getFaceLight,
363                         // The face on the z+ side should have double-diminished light
364                         assert(b.getFaceLight(p, v3s16(0,0,1)) == diminish_light(diminish_light(LIGHT_MAX)));
365                 }
366                 /*
367                         Check how the block handles being in between blocks with some non-sunlight
368                         while being underground
369                 */
370                 {
371                         // Make neighbours to exist and set some non-sunlight to them
372                         parent.position_valid = true;
373                         b.setIsUnderground(true);
374                         parent.node.setLight(LIGHT_MAX/2);
375                         core::map<v3s16, bool> light_sources;
376                         // The block below should be valid because there shouldn't be
377                         // sunlight in there either
378                         assert(b.propagateSunlight(light_sources) == true);
379                         // Should not touch nodes that are not affected (that is, all of them)
380                         //assert(b.getNode(v3s16(1,2,3)).getLight() == LIGHT_SUN);
381                         // Should set light of non-sunlighted blocks to 0.
382                         assert(b.getNode(v3s16(1,2,3)).getLight() == 0);
383                 }
384                 /*
385                         Set up a situation where:
386                         - There is only air in this block
387                         - There is a valid non-sunlighted block at the bottom, and
388                         - Invalid blocks elsewhere.
389                         - the block is not underground.
390
391                         This should result in bottom block invalidity
392                 */
393                 {
394                         b.setIsUnderground(false);
395                         // Clear block
396                         for(u16 z=0; z<MAP_BLOCKSIZE; z++){
397                                 for(u16 y=0; y<MAP_BLOCKSIZE; y++){
398                                         for(u16 x=0; x<MAP_BLOCKSIZE; x++){
399                                                 MapNode n;
400                                                 n.d = MATERIAL_AIR;
401                                                 n.setLight(0);
402                                                 b.setNode(v3s16(x,y,z), n);
403                                         }
404                                 }
405                         }
406                         // Make neighbours invalid
407                         parent.position_valid = false;
408                         // Add exceptions to the top of the bottom block
409                         for(u16 x=0; x<MAP_BLOCKSIZE; x++)
410                         for(u16 z=0; z<MAP_BLOCKSIZE; z++)
411                         {
412                                 parent.validity_exceptions.push_back(v3s16(MAP_BLOCKSIZE+x, MAP_BLOCKSIZE-1, MAP_BLOCKSIZE+z));
413                         }
414                         // Lighting value for the valid nodes
415                         parent.node.setLight(LIGHT_MAX/2);
416                         core::map<v3s16, bool> light_sources;
417                         // Bottom block is not valid
418                         assert(b.propagateSunlight(light_sources) == false);
419                 }
420         }
421 };
422
423 struct TestMapSector
424 {
425         class TC : public NodeContainer
426         {
427         public:
428
429                 MapNode node;
430                 bool position_valid;
431
432                 TC()
433                 {
434                         position_valid = true;
435                 }
436
437                 virtual bool isValidPosition(v3s16 p)
438                 {
439                         return position_valid;
440                 }
441
442                 virtual MapNode getNode(v3s16 p)
443                 {
444                         if(position_valid == false)
445                                 throw InvalidPositionException();
446                         return node;
447                 }
448
449                 virtual void setNode(v3s16 p, MapNode & n)
450                 {
451                         if(position_valid == false)
452                                 throw InvalidPositionException();
453                 };
454                 
455                 virtual u16 nodeContainerId() const
456                 {
457                         return 666;
458                 }
459         };
460         
461         void Run()
462         {
463                 TC parent;
464                 parent.position_valid = false;
465                 
466                 // Create one with no heightmaps
467                 ServerMapSector sector(&parent, v2s16(1,1), 0);
468                 //ConstantGenerator *dummyheightmap = new ConstantGenerator();
469                 //sector->setHeightmap(dummyheightmap);
470                 
471                 EXCEPTION_CHECK(InvalidPositionException, sector.getBlockNoCreate(0));
472                 EXCEPTION_CHECK(InvalidPositionException, sector.getBlockNoCreate(1));
473
474                 MapBlock * bref = sector.createBlankBlock(-2);
475                 
476                 EXCEPTION_CHECK(InvalidPositionException, sector.getBlockNoCreate(0));
477                 assert(sector.getBlockNoCreate(-2) == bref);
478                 
479                 //TODO: Check for AlreadyExistsException
480
481                 /*bool exception_thrown = false;
482                 try{
483                         sector.getBlock(0);
484                 }
485                 catch(InvalidPositionException &e){
486                         exception_thrown = true;
487                 }
488                 assert(exception_thrown);*/
489
490         }
491 };
492
493 struct TestHeightmap
494 {
495         void TestSingleFixed()
496         {
497                 const s16 BS1 = 4;
498                 OneChildHeightmap hm1(BS1);
499                 
500                 // Test that it is filled with < GROUNDHEIGHT_VALID_MINVALUE
501                 for(s16 y=0; y<=BS1; y++){
502                         for(s16 x=0; x<=BS1; x++){
503                                 v2s16 p(x,y);
504                                 assert(hm1.m_child.getGroundHeight(p)
505                                         < GROUNDHEIGHT_VALID_MINVALUE);
506                         }
507                 }
508
509                 hm1.m_child.setGroundHeight(v2s16(1,0), 2.0);
510                 //hm1.m_child.print();
511                 assert(fabs(hm1.getGroundHeight(v2s16(1,0))-2.0)<0.001);
512                 hm1.setGroundHeight(v2s16(0,1), 3.0);
513                 assert(fabs(hm1.m_child.getGroundHeight(v2s16(0,1))-3.0)<0.001);
514                 
515                 // Fill with -1.0
516                 for(s16 y=0; y<=BS1; y++){
517                         for(s16 x=0; x<=BS1; x++){
518                                 v2s16 p(x,y);
519                                 hm1.m_child.setGroundHeight(p, -1.0);
520                         }
521                 }
522
523                 f32 corners[] = {0.0, 0.0, 1.0, 1.0};
524                 hm1.m_child.generateContinued(0.0, 0.0, corners);
525                 
526                 hm1.m_child.print();
527                 assert(fabs(hm1.m_child.getGroundHeight(v2s16(1,0))-0.2)<0.05);
528                 assert(fabs(hm1.m_child.getGroundHeight(v2s16(4,3))-0.7)<0.05);
529                 assert(fabs(hm1.m_child.getGroundHeight(v2s16(4,4))-1.0)<0.05);
530         }
531
532         void TestUnlimited()
533         {
534                 //g_heightmap_debugprint = true;
535                 const s16 BS1 = 4;
536                 UnlimitedHeightmap hm1(BS1,
537                                 new ConstantGenerator(0.0),
538                                 new ConstantGenerator(0.0),
539                                 new ConstantGenerator(5.0));
540                 // Go through it so it generates itself
541                 for(s16 y=0; y<=BS1; y++){
542                         for(s16 x=0; x<=BS1; x++){
543                                 v2s16 p(x,y);
544                                 hm1.getGroundHeight(p);
545                         }
546                 }
547                 // Print it
548                 dstream<<"UnlimitedHeightmap hm1:"<<std::endl;
549                 hm1.print();
550                 
551                 dstream<<"testing UnlimitedHeightmap set/get"<<std::endl;
552                 v2s16 p1(0,3);
553                 f32 v1(234.01);
554                 // Get first heightmap and try setGroundHeight
555                 FixedHeightmap * href = hm1.getHeightmap(v2s16(0,0));
556                 href->setGroundHeight(p1, v1);
557                 // Read from UnlimitedHeightmap
558                 assert(fabs(hm1.getGroundHeight(p1)-v1)<0.001);
559         }
560         
561         void Random()
562         {
563                 dstream<<"Running random code (get a human to check this)"<<std::endl;
564                 dstream<<"rand() values: ";
565                 for(u16 i=0; i<5; i++)
566                         dstream<<(u16)rand()<<" ";
567                 dstream<<std::endl;
568
569                 const s16 BS1 = 8;
570                 UnlimitedHeightmap hm1(BS1,
571                                 new ConstantGenerator(10.0),
572                                 new ConstantGenerator(0.3),
573                                 new ConstantGenerator(0.0));
574
575                 // Force hm1 to generate a some heightmap
576                 hm1.getGroundHeight(v2s16(0,0));
577                 hm1.getGroundHeight(v2s16(0,BS1));
578                 /*hm1.getGroundHeight(v2s16(BS1,-1));
579                 hm1.getGroundHeight(v2s16(BS1-1,-1));*/
580                 hm1.print();
581
582                 // Get the (0,0) and (1,0) heightmaps
583                 /*FixedHeightmap * hr00 = hm1.getHeightmap(v2s16(0,0));
584                 FixedHeightmap * hr01 = hm1.getHeightmap(v2s16(1,0));
585                 f32 corners[] = {1.0, 1.0, 1.0, 1.0};
586                 hr00->generateContinued(0.0, 0.0, corners);
587                 hm1.print();*/
588
589                 //assert(0);
590         }
591
592         void Run()
593         {
594                 //srand(7); // Get constant random
595                 srand(time(0)); // Get better random
596
597                 TestSingleFixed();
598                 TestUnlimited();
599                 Random();
600         }
601 };
602
603 struct TestSocket
604 {
605         void Run()
606         {
607                 const int port = 30003;
608                 UDPSocket socket;
609                 socket.Bind(port);
610
611                 const char sendbuffer[] = "hello world!";
612                 socket.Send(Address(127,0,0,1,port), sendbuffer, sizeof(sendbuffer));
613
614                 sleep_ms(50);
615
616                 char rcvbuffer[256];
617                 memset(rcvbuffer, 0, sizeof(rcvbuffer));
618                 Address sender;
619                 for(;;)
620                 {
621                         int bytes_read = socket.Receive(sender, rcvbuffer, sizeof(rcvbuffer));
622                         if(bytes_read < 0)
623                                 break;
624                 }
625                 //FIXME: This fails on some systems
626                 assert(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer))==0);
627                 assert(sender.getAddress() == Address(127,0,0,1, 0).getAddress());
628         }
629 };
630
631 struct TestConnection
632 {
633         void TestHelpers()
634         {
635                 /*
636                         Test helper functions
637                 */
638
639                 // Some constants for testing
640                 u32 proto_id = 0x12345678;
641                 u16 peer_id = 123;
642                 u8 channel = 2;
643                 SharedBuffer<u8> data1(1);
644                 data1[0] = 100;
645                 Address a(127,0,0,1, 10);
646                 u16 seqnum = 34352;
647
648                 con::BufferedPacket p1 = con::makePacket(a, data1,
649                                 proto_id, peer_id, channel);
650                 /*
651                         We should now have a packet with this data:
652                         Header:
653                                 [0] u32 protocol_id
654                                 [4] u16 sender_peer_id
655                                 [6] u8 channel
656                         Data:
657                                 [7] u8 data1[0]
658                 */
659                 assert(readU32(&p1.data[0]) == proto_id);
660                 assert(readU16(&p1.data[4]) == peer_id);
661                 assert(readU8(&p1.data[6]) == channel);
662                 assert(readU8(&p1.data[7]) == data1[0]);
663                 
664                 //dstream<<"initial data1[0]="<<((u32)data1[0]&0xff)<<std::endl;
665
666                 SharedBuffer<u8> p2 = con::makeReliablePacket(data1, seqnum);
667
668                 /*dstream<<"p2.getSize()="<<p2.getSize()<<", data1.getSize()="
669                                 <<data1.getSize()<<std::endl;
670                 dstream<<"readU8(&p2[3])="<<readU8(&p2[3])
671                                 <<" p2[3]="<<((u32)p2[3]&0xff)<<std::endl;
672                 dstream<<"data1[0]="<<((u32)data1[0]&0xff)<<std::endl;*/
673
674                 assert(p2.getSize() == 3 + data1.getSize());
675                 assert(readU8(&p2[0]) == TYPE_RELIABLE);
676                 assert(readU16(&p2[1]) == seqnum);
677                 assert(readU8(&p2[3]) == data1[0]);
678         }
679
680         struct Handler : public con::PeerHandler
681         {
682                 Handler(const char *a_name)
683                 {
684                         count = 0;
685                         last_id = 0;
686                         name = a_name;
687                 }
688                 void peerAdded(con::Peer *peer)
689                 {
690                         dstream<<"Handler("<<name<<")::peerAdded(): "
691                                         "id="<<peer->id<<std::endl;
692                         last_id = peer->id;
693                         count++;
694                 }
695                 void deletingPeer(con::Peer *peer, bool timeout)
696                 {
697                         dstream<<"Handler("<<name<<")::deletingPeer(): "
698                                         "id="<<peer->id
699                                         <<", timeout="<<timeout<<std::endl;
700                         last_id = peer->id;
701                         count--;
702                 }
703
704                 s32 count;
705                 u16 last_id;
706                 const char *name;
707         };
708
709         void Run()
710         {
711                 DSTACK("TestConnection::Run");
712
713                 TestHelpers();
714
715                 /*
716                         Test some real connections
717                 */
718                 u32 proto_id = 0xad26846a;
719
720                 Handler hand_server("server");
721                 Handler hand_client("client");
722                 
723                 dstream<<"** Creating server Connection"<<std::endl;
724                 con::Connection server(proto_id, 512, 5.0, &hand_server);
725                 server.Serve(30001);
726                 
727                 dstream<<"** Creating client Connection"<<std::endl;
728                 con::Connection client(proto_id, 512, 5.0, &hand_client);
729
730                 assert(hand_server.count == 0);
731                 assert(hand_client.count == 0);
732                 
733                 sleep_ms(50);
734                 
735                 Address server_address(127,0,0,1, 30001);
736                 dstream<<"** running client.Connect()"<<std::endl;
737                 client.Connect(server_address);
738
739                 sleep_ms(50);
740                 
741                 // Client should have added server now
742                 assert(hand_client.count == 1);
743                 assert(hand_client.last_id == 1);
744                 // But server should not have added client
745                 assert(hand_server.count == 0);
746
747                 try
748                 {
749                         u16 peer_id;
750                         u8 data[100];
751                         dstream<<"** running server.Receive()"<<std::endl;
752                         u32 size = server.Receive(peer_id, data, 100);
753                         dstream<<"** Server received: peer_id="<<peer_id
754                                         <<", size="<<size
755                                         <<std::endl;
756                 }
757                 catch(con::NoIncomingDataException &e)
758                 {
759                         // No actual data received, but the client has
760                         // probably been connected
761                 }
762                 
763                 // Client should be the same
764                 assert(hand_client.count == 1);
765                 assert(hand_client.last_id == 1);
766                 // Server should have the client
767                 assert(hand_server.count == 1);
768                 assert(hand_server.last_id == 2);
769                 
770                 //sleep_ms(50);
771
772                 while(client.Connected() == false)
773                 {
774                         try
775                         {
776                                 u16 peer_id;
777                                 u8 data[100];
778                                 dstream<<"** running client.Receive()"<<std::endl;
779                                 u32 size = client.Receive(peer_id, data, 100);
780                                 dstream<<"** Client received: peer_id="<<peer_id
781                                                 <<", size="<<size
782                                                 <<std::endl;
783                         }
784                         catch(con::NoIncomingDataException &e)
785                         {
786                         }
787                         sleep_ms(50);
788                 }
789
790                 sleep_ms(50);
791                 
792                 try
793                 {
794                         u16 peer_id;
795                         u8 data[100];
796                         dstream<<"** running server.Receive()"<<std::endl;
797                         u32 size = server.Receive(peer_id, data, 100);
798                         dstream<<"** Server received: peer_id="<<peer_id
799                                         <<", size="<<size
800                                         <<std::endl;
801                 }
802                 catch(con::NoIncomingDataException &e)
803                 {
804                 }
805
806                 {
807                         /*u8 data[] = "Hello World!";
808                         u32 datasize = sizeof(data);*/
809                         SharedBuffer<u8> data = SharedBufferFromString("Hello World!");
810
811                         dstream<<"** running client.Send()"<<std::endl;
812                         client.Send(PEER_ID_SERVER, 0, data, true);
813
814                         sleep_ms(50);
815
816                         u16 peer_id;
817                         u8 recvdata[100];
818                         dstream<<"** running server.Receive()"<<std::endl;
819                         u32 size = server.Receive(peer_id, recvdata, 100);
820                         dstream<<"** Server received: peer_id="<<peer_id
821                                         <<", size="<<size
822                                         <<", data="<<*data
823                                         <<std::endl;
824                         assert(memcmp(*data, recvdata, data.getSize()) == 0);
825                 }
826                 
827                 u16 peer_id_client = 2;
828
829                 {
830                         /*
831                                 Send consequent packets in different order
832                         */
833                         //u8 data1[] = "hello1";
834                         //u8 data2[] = "hello2";
835                         SharedBuffer<u8> data1 = SharedBufferFromString("hello1");
836                         SharedBuffer<u8> data2 = SharedBufferFromString("Hello2");
837
838                         Address client_address =
839                                         server.GetPeer(peer_id_client)->address;
840                         
841                         dstream<<"*** Sending packets in wrong order (2,1,2)"
842                                         <<std::endl;
843                         
844                         u8 chn = 0;
845                         con::Channel *ch = &server.GetPeer(peer_id_client)->channels[chn];
846                         u16 sn = ch->next_outgoing_seqnum;
847                         ch->next_outgoing_seqnum = sn+1;
848                         server.Send(peer_id_client, chn, data2, true);
849                         ch->next_outgoing_seqnum = sn;
850                         server.Send(peer_id_client, chn, data1, true);
851                         ch->next_outgoing_seqnum = sn+1;
852                         server.Send(peer_id_client, chn, data2, true);
853
854                         sleep_ms(50);
855
856                         dstream<<"*** Receiving the packets"<<std::endl;
857
858                         u16 peer_id;
859                         u8 recvdata[20];
860                         u32 size;
861
862                         dstream<<"** running client.Receive()"<<std::endl;
863                         peer_id = 132;
864                         size = client.Receive(peer_id, recvdata, 20);
865                         dstream<<"** Client received: peer_id="<<peer_id
866                                         <<", size="<<size
867                                         <<", data="<<recvdata
868                                         <<std::endl;
869                         assert(size == data1.getSize());
870                         assert(memcmp(*data1, recvdata, data1.getSize()) == 0);
871                         assert(peer_id == PEER_ID_SERVER);
872                         
873                         dstream<<"** running client.Receive()"<<std::endl;
874                         peer_id = 132;
875                         size = client.Receive(peer_id, recvdata, 20);
876                         dstream<<"** Client received: peer_id="<<peer_id
877                                         <<", size="<<size
878                                         <<", data="<<recvdata
879                                         <<std::endl;
880                         assert(size == data2.getSize());
881                         assert(memcmp(*data2, recvdata, data2.getSize()) == 0);
882                         assert(peer_id == PEER_ID_SERVER);
883                         
884                         bool got_exception = false;
885                         try
886                         {
887                                 dstream<<"** running client.Receive()"<<std::endl;
888                                 peer_id = 132;
889                                 size = client.Receive(peer_id, recvdata, 20);
890                                 dstream<<"** Client received: peer_id="<<peer_id
891                                                 <<", size="<<size
892                                                 <<", data="<<recvdata
893                                                 <<std::endl;
894                         }
895                         catch(con::NoIncomingDataException &e)
896                         {
897                                 dstream<<"** No incoming data for client"<<std::endl;
898                                 got_exception = true;
899                         }
900                         assert(got_exception);
901                 }
902                 {
903                         //u8 data1[1100];
904                         SharedBuffer<u8> data1(1100);
905                         for(u16 i=0; i<1100; i++){
906                                 data1[i] = i/4;
907                         }
908
909                         dstream<<"Sending data (size="<<1100<<"):";
910                         for(int i=0; i<1100 && i<20; i++){
911                                 if(i%2==0) printf(" ");
912                                 printf("%.2X", ((int)((const char*)*data1)[i])&0xff);
913                         }
914                         if(1100>20)
915                                 dstream<<"...";
916                         dstream<<std::endl;
917                         
918                         server.Send(peer_id_client, 0, data1, true);
919
920                         sleep_ms(50);
921                         
922                         u8 recvdata[2000];
923                         dstream<<"** running client.Receive()"<<std::endl;
924                         u16 peer_id = 132;
925                         u16 size = client.Receive(peer_id, recvdata, 2000);
926                         dstream<<"** Client received: peer_id="<<peer_id
927                                         <<", size="<<size
928                                         <<std::endl;
929
930                         dstream<<"Received data (size="<<size<<"):";
931                         for(int i=0; i<size && i<20; i++){
932                                 if(i%2==0) printf(" ");
933                                 printf("%.2X", ((int)((const char*)recvdata)[i])&0xff);
934                         }
935                         if(size>20)
936                                 dstream<<"...";
937                         dstream<<std::endl;
938
939                         assert(memcmp(*data1, recvdata, data1.getSize()) == 0);
940                         assert(peer_id == PEER_ID_SERVER);
941                 }
942                 
943                 // Check peer handlers
944                 assert(hand_client.count == 1);
945                 assert(hand_client.last_id == 1);
946                 assert(hand_server.count == 1);
947                 assert(hand_server.last_id == 2);
948                 
949                 //assert(0);
950         }
951 };
952
953 #define TEST(X)\
954 {\
955         X x;\
956         dstream<<"Running " #X <<std::endl;\
957         x.Run();\
958 }
959
960 void run_tests()
961 {
962         DSTACK(__FUNCTION_NAME);
963         dstream<<"run_tests() started"<<std::endl;
964         TEST(TestUtilities);
965         TEST(TestCompress);
966         TEST(TestMapNode);
967         TEST(TestVoxelManipulator);
968         TEST(TestMapBlock);
969         TEST(TestMapSector);
970         TEST(TestHeightmap);
971         if(INTERNET_SIMULATOR == false){
972                 TEST(TestSocket);
973                 dout_con<<"=== BEGIN RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl;
974                 TEST(TestConnection);
975                 dout_con<<"=== END RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl;
976         }
977         dstream<<"run_tests() passed"<<std::endl;
978 }
979