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