]> git.lizzy.rs Git - minetest.git/blob - src/test.cpp
6b285e3a46475456b11f8c7d88315c22735a3e48
[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.setNodeNoRef(v3s16(-1,0,-1), MapNode(2));
162
163                 v.print(dstream);
164
165                 assert(v.getNode(v3s16(-1,0,-1)).d == 2);
166
167                 dstream<<"*** Reading from inexistent (0,0,-1) ***"<<std::endl;
168
169                 EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,0,-1)));
170
171                 v.print(dstream);
172
173                 dstream<<"*** Adding area ***"<<std::endl;
174
175                 v.addArea(a);
176                 
177                 v.print(dstream);
178
179                 assert(v.getNode(v3s16(-1,0,-1)).d == 2);
180                 EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,1,1)));
181
182                 /*
183                         Water stuff
184                 */
185
186                 v.clear();
187
188                 const char *content =
189                         "#...######"
190                         "#...##..##"
191                         "#........ "
192                         "##########"
193
194                         "#...######"
195                         "#...##..##"
196                         "#........ "
197                         "##########"
198                 ;
199
200                 v3s16 size(10, 4, 2);
201                 
202                 const char *p = content;
203                 for(s16 z=0; z<size.Z; z++)
204                 for(s16 y=size.Y-1; y>=0; y--)
205                 for(s16 x=0; x<size.X; x++)
206                 {
207                         MapNode n;
208                         n.pressure = size.Y - y;
209                         if(*p == '#')
210                                 n.d = MATERIAL_STONE;
211                         else if(*p == '.')
212                                 n.d = MATERIAL_WATER;
213                         else if(*p == ' ')
214                                 n.d = MATERIAL_AIR;
215                         else
216                                 assert(0);
217                         v.setNode(v3s16(x,y,z), n);
218                         p++;
219                 }
220
221                 v.print(dstream);
222                 
223                 //assert(0);
224         }
225 };
226
227 struct TestMapBlock
228 {
229         class TC : public NodeContainer
230         {
231         public:
232
233                 MapNode node;
234                 bool position_valid;
235                 core::list<v3s16> validity_exceptions;
236
237                 TC()
238                 {
239                         position_valid = true;
240                 }
241
242                 virtual bool isValidPosition(v3s16 p)
243                 {
244                         //return position_valid ^ (p==position_valid_exception);
245                         bool exception = false;
246                         for(core::list<v3s16>::Iterator i=validity_exceptions.begin();
247                                         i != validity_exceptions.end(); i++)
248                         {
249                                 if(p == *i)
250                                 {
251                                         exception = true;
252                                         break;
253                                 }
254                         }
255                         return exception ? !position_valid : position_valid;
256                 }
257
258                 virtual MapNode getNode(v3s16 p)
259                 {
260                         if(isValidPosition(p) == false)
261                                 throw InvalidPositionException();
262                         return node;
263                 }
264
265                 virtual void setNode(v3s16 p, MapNode & n)
266                 {
267                         if(isValidPosition(p) == false)
268                                 throw InvalidPositionException();
269                 };
270
271                 virtual u16 nodeContainerId() const
272                 {
273                         return 666;
274                 }
275         };
276
277         void Run()
278         {
279                 TC parent;
280                 
281                 MapBlock b(&parent, v3s16(1,1,1));
282                 v3s16 relpos(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
283
284                 assert(b.getPosRelative() == relpos);
285
286                 assert(b.getBox().MinEdge.X == MAP_BLOCKSIZE);
287                 assert(b.getBox().MaxEdge.X == MAP_BLOCKSIZE*2-1);
288                 assert(b.getBox().MinEdge.Y == MAP_BLOCKSIZE);
289                 assert(b.getBox().MaxEdge.Y == MAP_BLOCKSIZE*2-1);
290                 assert(b.getBox().MinEdge.Z == MAP_BLOCKSIZE);
291                 assert(b.getBox().MaxEdge.Z == MAP_BLOCKSIZE*2-1);
292                 
293                 assert(b.isValidPosition(v3s16(0,0,0)) == true);
294                 assert(b.isValidPosition(v3s16(-1,0,0)) == false);
295                 assert(b.isValidPosition(v3s16(-1,-142,-2341)) == false);
296                 assert(b.isValidPosition(v3s16(-124,142,2341)) == false);
297                 assert(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
298                 assert(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE,MAP_BLOCKSIZE-1)) == false);
299
300                 /*
301                         TODO: this method should probably be removed
302                         if the block size isn't going to be set variable
303                 */
304                 /*assert(b.getSizeNodes() == v3s16(MAP_BLOCKSIZE,
305                                 MAP_BLOCKSIZE, MAP_BLOCKSIZE));*/
306                 
307                 // Changed flag should be initially set
308                 assert(b.getChangedFlag() == true);
309                 b.resetChangedFlag();
310                 assert(b.getChangedFlag() == false);
311
312                 // All nodes should have been set to
313                 // .d=MATERIAL_AIR and .getLight() = 0
314                 for(u16 z=0; z<MAP_BLOCKSIZE; z++)
315                         for(u16 y=0; y<MAP_BLOCKSIZE; y++)
316                                 for(u16 x=0; x<MAP_BLOCKSIZE; x++){
317                                         assert(b.getNode(v3s16(x,y,z)).d == MATERIAL_AIR);
318                                         assert(b.getNode(v3s16(x,y,z)).getLight() == 0);
319                                 }
320                 
321                 /*
322                         Parent fetch functions
323                 */
324                 parent.position_valid = false;
325                 parent.node.d = 5;
326
327                 MapNode n;
328                 
329                 // Positions in the block should still be valid
330                 assert(b.isValidPositionParent(v3s16(0,0,0)) == true);
331                 assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
332                 n = b.getNodeParent(v3s16(0,MAP_BLOCKSIZE-1,0));
333                 assert(n.d == MATERIAL_AIR);
334
335                 // ...but outside the block they should be invalid
336                 assert(b.isValidPositionParent(v3s16(-121,2341,0)) == false);
337                 assert(b.isValidPositionParent(v3s16(-1,0,0)) == false);
338                 assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == false);
339                 
340                 {
341                         bool exception_thrown = false;
342                         try{
343                                 // This should throw an exception
344                                 MapNode n = b.getNodeParent(v3s16(0,0,-1));
345                         }
346                         catch(InvalidPositionException &e)
347                         {
348                                 exception_thrown = true;
349                         }
350                         assert(exception_thrown);
351                 }
352
353                 parent.position_valid = true;
354                 // Now the positions outside should be valid
355                 assert(b.isValidPositionParent(v3s16(-121,2341,0)) == true);
356                 assert(b.isValidPositionParent(v3s16(-1,0,0)) == true);
357                 assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == true);
358                 n = b.getNodeParent(v3s16(0,0,MAP_BLOCKSIZE));
359                 assert(n.d == 5);
360
361                 /*
362                         Set a node
363                 */
364                 v3s16 p(1,2,0);
365                 n.d = 4;
366                 b.setNode(p, n);
367                 assert(b.getNode(p).d == 4);
368                 assert(b.getNodeMaterial(p) == 4);
369                 assert(b.getNodeMaterial(v3s16(-1,-1,0)) == 5);
370                 
371                 /*
372                         propagateSunlight()
373                 */
374                 // Set lighting of all nodes to 0
375                 for(u16 z=0; z<MAP_BLOCKSIZE; z++){
376                         for(u16 y=0; y<MAP_BLOCKSIZE; y++){
377                                 for(u16 x=0; x<MAP_BLOCKSIZE; x++){
378                                         MapNode n = b.getNode(v3s16(x,y,z));
379                                         n.setLight(0);
380                                         b.setNode(v3s16(x,y,z), n);
381                                 }
382                         }
383                 }
384                 {
385                         /*
386                                 Check how the block handles being a lonely sky block
387                         */
388                         parent.position_valid = true;
389                         b.setIsUnderground(false);
390                         parent.node.d = MATERIAL_AIR;
391                         parent.node.setLight(LIGHT_SUN);
392                         core::map<v3s16, bool> light_sources;
393                         // The bottom block is invalid, because we have a shadowing node
394                         assert(b.propagateSunlight(light_sources) == false);
395                         assert(b.getNode(v3s16(1,4,0)).getLight() == LIGHT_SUN);
396                         assert(b.getNode(v3s16(1,3,0)).getLight() == LIGHT_SUN);
397                         assert(b.getNode(v3s16(1,2,0)).getLight() == 0);
398                         assert(b.getNode(v3s16(1,1,0)).getLight() == 0);
399                         assert(b.getNode(v3s16(1,0,0)).getLight() == 0);
400                         assert(b.getNode(v3s16(1,2,3)).getLight() == LIGHT_SUN);
401                         assert(b.getFaceLight(p, v3s16(0,1,0)) == LIGHT_SUN);
402                         assert(b.getFaceLight(p, v3s16(0,-1,0)) == 0);
403                         // According to MapBlock::getFaceLight,
404                         // The face on the z+ side should have double-diminished light
405                         assert(b.getFaceLight(p, v3s16(0,0,1)) == diminish_light(diminish_light(LIGHT_MAX)));
406                 }
407                 /*
408                         Check how the block handles being in between blocks with some non-sunlight
409                         while being underground
410                 */
411                 {
412                         // Make neighbours to exist and set some non-sunlight to them
413                         parent.position_valid = true;
414                         b.setIsUnderground(true);
415                         parent.node.setLight(LIGHT_MAX/2);
416                         core::map<v3s16, bool> light_sources;
417                         // The block below should be valid because there shouldn't be
418                         // sunlight in there either
419                         assert(b.propagateSunlight(light_sources) == true);
420                         // Should not touch nodes that are not affected (that is, all of them)
421                         //assert(b.getNode(v3s16(1,2,3)).getLight() == LIGHT_SUN);
422                         // Should set light of non-sunlighted blocks to 0.
423                         assert(b.getNode(v3s16(1,2,3)).getLight() == 0);
424                 }
425                 /*
426                         Set up a situation where:
427                         - There is only air in this block
428                         - There is a valid non-sunlighted block at the bottom, and
429                         - Invalid blocks elsewhere.
430                         - the block is not underground.
431
432                         This should result in bottom block invalidity
433                 */
434                 {
435                         b.setIsUnderground(false);
436                         // Clear block
437                         for(u16 z=0; z<MAP_BLOCKSIZE; z++){
438                                 for(u16 y=0; y<MAP_BLOCKSIZE; y++){
439                                         for(u16 x=0; x<MAP_BLOCKSIZE; x++){
440                                                 MapNode n;
441                                                 n.d = MATERIAL_AIR;
442                                                 n.setLight(0);
443                                                 b.setNode(v3s16(x,y,z), n);
444                                         }
445                                 }
446                         }
447                         // Make neighbours invalid
448                         parent.position_valid = false;
449                         // Add exceptions to the top of the bottom block
450                         for(u16 x=0; x<MAP_BLOCKSIZE; x++)
451                         for(u16 z=0; z<MAP_BLOCKSIZE; z++)
452                         {
453                                 parent.validity_exceptions.push_back(v3s16(MAP_BLOCKSIZE+x, MAP_BLOCKSIZE-1, MAP_BLOCKSIZE+z));
454                         }
455                         // Lighting value for the valid nodes
456                         parent.node.setLight(LIGHT_MAX/2);
457                         core::map<v3s16, bool> light_sources;
458                         // Bottom block is not valid
459                         assert(b.propagateSunlight(light_sources) == false);
460                 }
461         }
462 };
463
464 struct TestMapSector
465 {
466         class TC : public NodeContainer
467         {
468         public:
469
470                 MapNode node;
471                 bool position_valid;
472
473                 TC()
474                 {
475                         position_valid = true;
476                 }
477
478                 virtual bool isValidPosition(v3s16 p)
479                 {
480                         return position_valid;
481                 }
482
483                 virtual MapNode getNode(v3s16 p)
484                 {
485                         if(position_valid == false)
486                                 throw InvalidPositionException();
487                         return node;
488                 }
489
490                 virtual void setNode(v3s16 p, MapNode & n)
491                 {
492                         if(position_valid == false)
493                                 throw InvalidPositionException();
494                 };
495                 
496                 virtual u16 nodeContainerId() const
497                 {
498                         return 666;
499                 }
500         };
501         
502         void Run()
503         {
504                 TC parent;
505                 parent.position_valid = false;
506                 
507                 // Create one with no heightmaps
508                 ServerMapSector sector(&parent, v2s16(1,1), 0);
509                 //ConstantGenerator *dummyheightmap = new ConstantGenerator();
510                 //sector->setHeightmap(dummyheightmap);
511                 
512                 EXCEPTION_CHECK(InvalidPositionException, sector.getBlockNoCreate(0));
513                 EXCEPTION_CHECK(InvalidPositionException, sector.getBlockNoCreate(1));
514
515                 MapBlock * bref = sector.createBlankBlock(-2);
516                 
517                 EXCEPTION_CHECK(InvalidPositionException, sector.getBlockNoCreate(0));
518                 assert(sector.getBlockNoCreate(-2) == bref);
519                 
520                 //TODO: Check for AlreadyExistsException
521
522                 /*bool exception_thrown = false;
523                 try{
524                         sector.getBlock(0);
525                 }
526                 catch(InvalidPositionException &e){
527                         exception_thrown = true;
528                 }
529                 assert(exception_thrown);*/
530
531         }
532 };
533
534 struct TestHeightmap
535 {
536         void TestSingleFixed()
537         {
538                 const s16 BS1 = 4;
539                 OneChildHeightmap hm1(BS1);
540                 
541                 // Test that it is filled with < GROUNDHEIGHT_VALID_MINVALUE
542                 for(s16 y=0; y<=BS1; y++){
543                         for(s16 x=0; x<=BS1; x++){
544                                 v2s16 p(x,y);
545                                 assert(hm1.m_child.getGroundHeight(p)
546                                         < GROUNDHEIGHT_VALID_MINVALUE);
547                         }
548                 }
549
550                 hm1.m_child.setGroundHeight(v2s16(1,0), 2.0);
551                 //hm1.m_child.print();
552                 assert(fabs(hm1.getGroundHeight(v2s16(1,0))-2.0)<0.001);
553                 hm1.setGroundHeight(v2s16(0,1), 3.0);
554                 assert(fabs(hm1.m_child.getGroundHeight(v2s16(0,1))-3.0)<0.001);
555                 
556                 // Fill with -1.0
557                 for(s16 y=0; y<=BS1; y++){
558                         for(s16 x=0; x<=BS1; x++){
559                                 v2s16 p(x,y);
560                                 hm1.m_child.setGroundHeight(p, -1.0);
561                         }
562                 }
563
564                 f32 corners[] = {0.0, 0.0, 1.0, 1.0};
565                 hm1.m_child.generateContinued(0.0, 0.0, corners);
566                 
567                 hm1.m_child.print();
568                 assert(fabs(hm1.m_child.getGroundHeight(v2s16(1,0))-0.2)<0.05);
569                 assert(fabs(hm1.m_child.getGroundHeight(v2s16(4,3))-0.7)<0.05);
570                 assert(fabs(hm1.m_child.getGroundHeight(v2s16(4,4))-1.0)<0.05);
571         }
572
573         void TestUnlimited()
574         {
575                 //g_heightmap_debugprint = true;
576                 const s16 BS1 = 4;
577                 UnlimitedHeightmap hm1(BS1,
578                                 new ConstantGenerator(0.0),
579                                 new ConstantGenerator(0.0),
580                                 new ConstantGenerator(5.0));
581                 // Go through it so it generates itself
582                 for(s16 y=0; y<=BS1; y++){
583                         for(s16 x=0; x<=BS1; x++){
584                                 v2s16 p(x,y);
585                                 hm1.getGroundHeight(p);
586                         }
587                 }
588                 // Print it
589                 dstream<<"UnlimitedHeightmap hm1:"<<std::endl;
590                 hm1.print();
591                 
592                 dstream<<"testing UnlimitedHeightmap set/get"<<std::endl;
593                 v2s16 p1(0,3);
594                 f32 v1(234.01);
595                 // Get first heightmap and try setGroundHeight
596                 FixedHeightmap * href = hm1.getHeightmap(v2s16(0,0));
597                 href->setGroundHeight(p1, v1);
598                 // Read from UnlimitedHeightmap
599                 assert(fabs(hm1.getGroundHeight(p1)-v1)<0.001);
600         }
601         
602         void Random()
603         {
604                 dstream<<"Running random code (get a human to check this)"<<std::endl;
605                 dstream<<"rand() values: ";
606                 for(u16 i=0; i<5; i++)
607                         dstream<<(u16)rand()<<" ";
608                 dstream<<std::endl;
609
610                 const s16 BS1 = 8;
611                 UnlimitedHeightmap hm1(BS1,
612                                 new ConstantGenerator(10.0),
613                                 new ConstantGenerator(0.3),
614                                 new ConstantGenerator(0.0));
615
616                 // Force hm1 to generate a some heightmap
617                 hm1.getGroundHeight(v2s16(0,0));
618                 hm1.getGroundHeight(v2s16(0,BS1));
619                 /*hm1.getGroundHeight(v2s16(BS1,-1));
620                 hm1.getGroundHeight(v2s16(BS1-1,-1));*/
621                 hm1.print();
622
623                 // Get the (0,0) and (1,0) heightmaps
624                 /*FixedHeightmap * hr00 = hm1.getHeightmap(v2s16(0,0));
625                 FixedHeightmap * hr01 = hm1.getHeightmap(v2s16(1,0));
626                 f32 corners[] = {1.0, 1.0, 1.0, 1.0};
627                 hr00->generateContinued(0.0, 0.0, corners);
628                 hm1.print();*/
629
630                 //assert(0);
631         }
632
633         void Run()
634         {
635                 //srand(7); // Get constant random
636                 srand(time(0)); // Get better random
637
638                 TestSingleFixed();
639                 TestUnlimited();
640                 Random();
641         }
642 };
643
644 struct TestSocket
645 {
646         void Run()
647         {
648                 const int port = 30003;
649                 UDPSocket socket;
650                 socket.Bind(port);
651
652                 const char sendbuffer[] = "hello world!";
653                 socket.Send(Address(127,0,0,1,port), sendbuffer, sizeof(sendbuffer));
654
655                 sleep_ms(50);
656
657                 char rcvbuffer[256];
658                 memset(rcvbuffer, 0, sizeof(rcvbuffer));
659                 Address sender;
660                 for(;;)
661                 {
662                         int bytes_read = socket.Receive(sender, rcvbuffer, sizeof(rcvbuffer));
663                         if(bytes_read < 0)
664                                 break;
665                 }
666                 //FIXME: This fails on some systems
667                 assert(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer))==0);
668                 assert(sender.getAddress() == Address(127,0,0,1, 0).getAddress());
669         }
670 };
671
672 struct TestConnection
673 {
674         void TestHelpers()
675         {
676                 /*
677                         Test helper functions
678                 */
679
680                 // Some constants for testing
681                 u32 proto_id = 0x12345678;
682                 u16 peer_id = 123;
683                 u8 channel = 2;
684                 SharedBuffer<u8> data1(1);
685                 data1[0] = 100;
686                 Address a(127,0,0,1, 10);
687                 u16 seqnum = 34352;
688
689                 con::BufferedPacket p1 = con::makePacket(a, data1,
690                                 proto_id, peer_id, channel);
691                 /*
692                         We should now have a packet with this data:
693                         Header:
694                                 [0] u32 protocol_id
695                                 [4] u16 sender_peer_id
696                                 [6] u8 channel
697                         Data:
698                                 [7] u8 data1[0]
699                 */
700                 assert(readU32(&p1.data[0]) == proto_id);
701                 assert(readU16(&p1.data[4]) == peer_id);
702                 assert(readU8(&p1.data[6]) == channel);
703                 assert(readU8(&p1.data[7]) == data1[0]);
704                 
705                 //dstream<<"initial data1[0]="<<((u32)data1[0]&0xff)<<std::endl;
706
707                 SharedBuffer<u8> p2 = con::makeReliablePacket(data1, seqnum);
708
709                 /*dstream<<"p2.getSize()="<<p2.getSize()<<", data1.getSize()="
710                                 <<data1.getSize()<<std::endl;
711                 dstream<<"readU8(&p2[3])="<<readU8(&p2[3])
712                                 <<" p2[3]="<<((u32)p2[3]&0xff)<<std::endl;
713                 dstream<<"data1[0]="<<((u32)data1[0]&0xff)<<std::endl;*/
714
715                 assert(p2.getSize() == 3 + data1.getSize());
716                 assert(readU8(&p2[0]) == TYPE_RELIABLE);
717                 assert(readU16(&p2[1]) == seqnum);
718                 assert(readU8(&p2[3]) == data1[0]);
719         }
720
721         struct Handler : public con::PeerHandler
722         {
723                 Handler(const char *a_name)
724                 {
725                         count = 0;
726                         last_id = 0;
727                         name = a_name;
728                 }
729                 void peerAdded(con::Peer *peer)
730                 {
731                         dstream<<"Handler("<<name<<")::peerAdded(): "
732                                         "id="<<peer->id<<std::endl;
733                         last_id = peer->id;
734                         count++;
735                 }
736                 void deletingPeer(con::Peer *peer, bool timeout)
737                 {
738                         dstream<<"Handler("<<name<<")::deletingPeer(): "
739                                         "id="<<peer->id
740                                         <<", timeout="<<timeout<<std::endl;
741                         last_id = peer->id;
742                         count--;
743                 }
744
745                 s32 count;
746                 u16 last_id;
747                 const char *name;
748         };
749
750         void Run()
751         {
752                 DSTACK("TestConnection::Run");
753
754                 TestHelpers();
755
756                 /*
757                         Test some real connections
758                 */
759                 u32 proto_id = 0xad26846a;
760
761                 Handler hand_server("server");
762                 Handler hand_client("client");
763                 
764                 dstream<<"** Creating server Connection"<<std::endl;
765                 con::Connection server(proto_id, 512, 5.0, &hand_server);
766                 server.Serve(30001);
767                 
768                 dstream<<"** Creating client Connection"<<std::endl;
769                 con::Connection client(proto_id, 512, 5.0, &hand_client);
770
771                 assert(hand_server.count == 0);
772                 assert(hand_client.count == 0);
773                 
774                 sleep_ms(50);
775                 
776                 Address server_address(127,0,0,1, 30001);
777                 dstream<<"** running client.Connect()"<<std::endl;
778                 client.Connect(server_address);
779
780                 sleep_ms(50);
781                 
782                 // Client should have added server now
783                 assert(hand_client.count == 1);
784                 assert(hand_client.last_id == 1);
785                 // But server should not have added client
786                 assert(hand_server.count == 0);
787
788                 try
789                 {
790                         u16 peer_id;
791                         u8 data[100];
792                         dstream<<"** running server.Receive()"<<std::endl;
793                         u32 size = server.Receive(peer_id, data, 100);
794                         dstream<<"** Server received: peer_id="<<peer_id
795                                         <<", size="<<size
796                                         <<std::endl;
797                 }
798                 catch(con::NoIncomingDataException &e)
799                 {
800                         // No actual data received, but the client has
801                         // probably been connected
802                 }
803                 
804                 // Client should be the same
805                 assert(hand_client.count == 1);
806                 assert(hand_client.last_id == 1);
807                 // Server should have the client
808                 assert(hand_server.count == 1);
809                 assert(hand_server.last_id == 2);
810                 
811                 //sleep_ms(50);
812
813                 while(client.Connected() == false)
814                 {
815                         try
816                         {
817                                 u16 peer_id;
818                                 u8 data[100];
819                                 dstream<<"** running client.Receive()"<<std::endl;
820                                 u32 size = client.Receive(peer_id, data, 100);
821                                 dstream<<"** Client received: peer_id="<<peer_id
822                                                 <<", size="<<size
823                                                 <<std::endl;
824                         }
825                         catch(con::NoIncomingDataException &e)
826                         {
827                         }
828                         sleep_ms(50);
829                 }
830
831                 sleep_ms(50);
832                 
833                 try
834                 {
835                         u16 peer_id;
836                         u8 data[100];
837                         dstream<<"** running server.Receive()"<<std::endl;
838                         u32 size = server.Receive(peer_id, data, 100);
839                         dstream<<"** Server received: peer_id="<<peer_id
840                                         <<", size="<<size
841                                         <<std::endl;
842                 }
843                 catch(con::NoIncomingDataException &e)
844                 {
845                 }
846
847                 {
848                         /*u8 data[] = "Hello World!";
849                         u32 datasize = sizeof(data);*/
850                         SharedBuffer<u8> data = SharedBufferFromString("Hello World!");
851
852                         dstream<<"** running client.Send()"<<std::endl;
853                         client.Send(PEER_ID_SERVER, 0, data, true);
854
855                         sleep_ms(50);
856
857                         u16 peer_id;
858                         u8 recvdata[100];
859                         dstream<<"** running server.Receive()"<<std::endl;
860                         u32 size = server.Receive(peer_id, recvdata, 100);
861                         dstream<<"** Server received: peer_id="<<peer_id
862                                         <<", size="<<size
863                                         <<", data="<<*data
864                                         <<std::endl;
865                         assert(memcmp(*data, recvdata, data.getSize()) == 0);
866                 }
867                 
868                 u16 peer_id_client = 2;
869
870                 {
871                         /*
872                                 Send consequent packets in different order
873                         */
874                         //u8 data1[] = "hello1";
875                         //u8 data2[] = "hello2";
876                         SharedBuffer<u8> data1 = SharedBufferFromString("hello1");
877                         SharedBuffer<u8> data2 = SharedBufferFromString("Hello2");
878
879                         Address client_address =
880                                         server.GetPeer(peer_id_client)->address;
881                         
882                         dstream<<"*** Sending packets in wrong order (2,1,2)"
883                                         <<std::endl;
884                         
885                         u8 chn = 0;
886                         con::Channel *ch = &server.GetPeer(peer_id_client)->channels[chn];
887                         u16 sn = ch->next_outgoing_seqnum;
888                         ch->next_outgoing_seqnum = sn+1;
889                         server.Send(peer_id_client, chn, data2, true);
890                         ch->next_outgoing_seqnum = sn;
891                         server.Send(peer_id_client, chn, data1, true);
892                         ch->next_outgoing_seqnum = sn+1;
893                         server.Send(peer_id_client, chn, data2, true);
894
895                         sleep_ms(50);
896
897                         dstream<<"*** Receiving the packets"<<std::endl;
898
899                         u16 peer_id;
900                         u8 recvdata[20];
901                         u32 size;
902
903                         dstream<<"** running client.Receive()"<<std::endl;
904                         peer_id = 132;
905                         size = client.Receive(peer_id, recvdata, 20);
906                         dstream<<"** Client received: peer_id="<<peer_id
907                                         <<", size="<<size
908                                         <<", data="<<recvdata
909                                         <<std::endl;
910                         assert(size == data1.getSize());
911                         assert(memcmp(*data1, recvdata, data1.getSize()) == 0);
912                         assert(peer_id == PEER_ID_SERVER);
913                         
914                         dstream<<"** running client.Receive()"<<std::endl;
915                         peer_id = 132;
916                         size = client.Receive(peer_id, recvdata, 20);
917                         dstream<<"** Client received: peer_id="<<peer_id
918                                         <<", size="<<size
919                                         <<", data="<<recvdata
920                                         <<std::endl;
921                         assert(size == data2.getSize());
922                         assert(memcmp(*data2, recvdata, data2.getSize()) == 0);
923                         assert(peer_id == PEER_ID_SERVER);
924                         
925                         bool got_exception = false;
926                         try
927                         {
928                                 dstream<<"** running client.Receive()"<<std::endl;
929                                 peer_id = 132;
930                                 size = client.Receive(peer_id, recvdata, 20);
931                                 dstream<<"** Client received: peer_id="<<peer_id
932                                                 <<", size="<<size
933                                                 <<", data="<<recvdata
934                                                 <<std::endl;
935                         }
936                         catch(con::NoIncomingDataException &e)
937                         {
938                                 dstream<<"** No incoming data for client"<<std::endl;
939                                 got_exception = true;
940                         }
941                         assert(got_exception);
942                 }
943                 {
944                         //u8 data1[1100];
945                         SharedBuffer<u8> data1(1100);
946                         for(u16 i=0; i<1100; i++){
947                                 data1[i] = i/4;
948                         }
949
950                         dstream<<"Sending data (size="<<1100<<"):";
951                         for(int i=0; i<1100 && i<20; i++){
952                                 if(i%2==0) printf(" ");
953                                 printf("%.2X", ((int)((const char*)*data1)[i])&0xff);
954                         }
955                         if(1100>20)
956                                 dstream<<"...";
957                         dstream<<std::endl;
958                         
959                         server.Send(peer_id_client, 0, data1, true);
960
961                         sleep_ms(50);
962                         
963                         u8 recvdata[2000];
964                         dstream<<"** running client.Receive()"<<std::endl;
965                         u16 peer_id = 132;
966                         u16 size = client.Receive(peer_id, recvdata, 2000);
967                         dstream<<"** Client received: peer_id="<<peer_id
968                                         <<", size="<<size
969                                         <<std::endl;
970
971                         dstream<<"Received data (size="<<size<<"):";
972                         for(int i=0; i<size && i<20; i++){
973                                 if(i%2==0) printf(" ");
974                                 printf("%.2X", ((int)((const char*)recvdata)[i])&0xff);
975                         }
976                         if(size>20)
977                                 dstream<<"...";
978                         dstream<<std::endl;
979
980                         assert(memcmp(*data1, recvdata, data1.getSize()) == 0);
981                         assert(peer_id == PEER_ID_SERVER);
982                 }
983                 
984                 // Check peer handlers
985                 assert(hand_client.count == 1);
986                 assert(hand_client.last_id == 1);
987                 assert(hand_server.count == 1);
988                 assert(hand_server.last_id == 2);
989                 
990                 //assert(0);
991         }
992 };
993
994 #define TEST(X)\
995 {\
996         X x;\
997         dstream<<"Running " #X <<std::endl;\
998         x.Run();\
999 }
1000
1001 void run_tests()
1002 {
1003         DSTACK(__FUNCTION_NAME);
1004         dstream<<"run_tests() started"<<std::endl;
1005         TEST(TestUtilities);
1006         TEST(TestCompress);
1007         TEST(TestMapNode);
1008         TEST(TestVoxelManipulator);
1009         TEST(TestMapBlock);
1010         TEST(TestMapSector);
1011         TEST(TestHeightmap);
1012         if(INTERNET_SIMULATOR == false){
1013                 TEST(TestSocket);
1014                 dout_con<<"=== BEGIN RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl;
1015                 TEST(TestConnection);
1016                 dout_con<<"=== END RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl;
1017         }
1018         dstream<<"run_tests() passed"<<std::endl;
1019 }
1020