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