63aa09c0b136ea894188cc88614587d6a14895cf
[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 Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser 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 "serialization.h"
29 #include "voxel.h"
30 #include <sstream>
31 #include "porting.h"
32 #include "content_mapnode.h"
33 #include "nodedef.h"
34 #include "mapsector.h"
35 #include "settings.h"
36 #include "log.h"
37 #include "util/string.h"
38 #include "voxelalgorithms.h"
39 #include "inventory.h"
40 #include "util/numeric.h"
41 #include "util/serialize.h"
42
43 /*
44         Asserts that the exception occurs
45 */
46 #define EXCEPTION_CHECK(EType, code)\
47 {\
48         bool exception_thrown = false;\
49         try{ code; }\
50         catch(EType &e) { exception_thrown = true; }\
51         assert(exception_thrown);\
52 }
53
54 /*
55         A few item and node definitions for those tests that need them
56 */
57
58 #define CONTENT_STONE 0
59 #define CONTENT_GRASS 0x800
60 #define CONTENT_TORCH 100
61
62 void define_some_nodes(IWritableItemDefManager *idef, IWritableNodeDefManager *ndef)
63 {
64         content_t i;
65         ItemDefinition itemdef;
66         ContentFeatures f;
67
68         /*
69                 Stone
70         */
71         i = CONTENT_STONE;
72         itemdef = ItemDefinition();
73         itemdef.type = ITEM_NODE;
74         itemdef.name = "default:stone";
75         itemdef.description = "Stone";
76         itemdef.groups["cracky"] = 3;
77         itemdef.inventory_image = "[inventorycube"
78                 "{default_stone.png"
79                 "{default_stone.png"
80                 "{default_stone.png";
81         f = ContentFeatures();
82         f.name = itemdef.name;
83         for(int i = 0; i < 6; i++)
84                 f.tiledef[i].name = "default_stone.png";
85         f.is_ground_content = true;
86         idef->registerItem(itemdef);
87         ndef->set(i, f);
88
89         /*
90                 Grass
91         */
92         i = CONTENT_GRASS;
93         itemdef = ItemDefinition();
94         itemdef.type = ITEM_NODE;
95         itemdef.name = "default:dirt_with_grass";
96         itemdef.description = "Dirt with grass";
97         itemdef.groups["crumbly"] = 3;
98         itemdef.inventory_image = "[inventorycube"
99                 "{default_grass.png"
100                 "{default_dirt.png&default_grass_side.png"
101                 "{default_dirt.png&default_grass_side.png";
102         f = ContentFeatures();
103         f.name = itemdef.name;
104         f.tiledef[0].name = "default_grass.png";
105         f.tiledef[1].name = "default_dirt.png";
106         for(int i = 2; i < 6; i++)
107                 f.tiledef[i].name = "default_dirt.png^default_grass_side.png";
108         f.is_ground_content = true;
109         idef->registerItem(itemdef);
110         ndef->set(i, f);
111
112         /*
113                 Torch (minimal definition for lighting tests)
114         */
115         i = CONTENT_TORCH;
116         itemdef = ItemDefinition();
117         itemdef.type = ITEM_NODE;
118         itemdef.name = "default:torch";
119         f = ContentFeatures();
120         f.name = itemdef.name;
121         f.param_type = CPT_LIGHT;
122         f.light_propagates = true;
123         f.sunlight_propagates = true;
124         f.light_source = LIGHT_MAX-1;
125         idef->registerItem(itemdef);
126         ndef->set(i, f);
127 }
128
129 struct TestUtilities
130 {
131         void Run()
132         {
133                 /*infostream<<"wrapDegrees(100.0) = "<<wrapDegrees(100.0)<<std::endl;
134                 infostream<<"wrapDegrees(720.5) = "<<wrapDegrees(720.5)<<std::endl;
135                 infostream<<"wrapDegrees(-0.5) = "<<wrapDegrees(-0.5)<<std::endl;*/
136                 assert(fabs(wrapDegrees(100.0) - 100.0) < 0.001);
137                 assert(fabs(wrapDegrees(720.5) - 0.5) < 0.001);
138                 assert(fabs(wrapDegrees(-0.5) - (-0.5)) < 0.001);
139                 assert(fabs(wrapDegrees(-365.5) - (-5.5)) < 0.001);
140                 assert(lowercase("Foo bAR") == "foo bar");
141                 assert(is_yes("YeS") == true);
142                 assert(is_yes("") == false);
143                 assert(is_yes("FAlse") == false);
144                 const char *ends[] = {"abc", "c", "bc", NULL};
145                 assert(removeStringEnd("abc", ends) == "");
146                 assert(removeStringEnd("bc", ends) == "b");
147                 assert(removeStringEnd("12c", ends) == "12");
148                 assert(removeStringEnd("foo", ends) == "");
149         }
150 };
151
152 struct TestSettings
153 {
154         void Run()
155         {
156                 Settings s;
157                 // Test reading of settings
158                 s.parseConfigLine("leet = 1337");
159                 s.parseConfigLine("leetleet = 13371337");
160                 s.parseConfigLine("leetleet_neg = -13371337");
161                 s.parseConfigLine("floaty_thing = 1.1");
162                 s.parseConfigLine("stringy_thing = asd /( ¤%&(/\" BLÖÄRP");
163                 s.parseConfigLine("coord = (1, 2, 4.5)");
164                 assert(s.getS32("leet") == 1337);
165                 assert(s.getS16("leetleet") == 32767);
166                 assert(s.getS16("leetleet_neg") == -32768);
167                 // Not sure if 1.1 is an exact value as a float, but doesn't matter
168                 assert(fabs(s.getFloat("floaty_thing") - 1.1) < 0.001);
169                 assert(s.get("stringy_thing") == "asd /( ¤%&(/\" BLÖÄRP");
170                 assert(fabs(s.getV3F("coord").X - 1.0) < 0.001);
171                 assert(fabs(s.getV3F("coord").Y - 2.0) < 0.001);
172                 assert(fabs(s.getV3F("coord").Z - 4.5) < 0.001);
173                 // Test the setting of settings too
174                 s.setFloat("floaty_thing_2", 1.2);
175                 s.setV3F("coord2", v3f(1, 2, 3.3));
176                 assert(s.get("floaty_thing_2").substr(0,3) == "1.2");
177                 assert(fabs(s.getFloat("floaty_thing_2") - 1.2) < 0.001);
178                 assert(fabs(s.getV3F("coord2").X - 1.0) < 0.001);
179                 assert(fabs(s.getV3F("coord2").Y - 2.0) < 0.001);
180                 assert(fabs(s.getV3F("coord2").Z - 3.3) < 0.001);
181         }
182 };
183
184 struct TestSerialization
185 {
186         // To be used like this:
187         //   mkstr("Some\0string\0with\0embedded\0nuls")
188         // since std::string("...") doesn't work as expected in that case.
189         template<size_t N> std::string mkstr(const char (&s)[N])
190         {
191                 return std::string(s, N - 1);
192         }
193
194         void Run()
195         {
196                 // Tests some serialization primitives
197
198                 assert(serializeString("") == mkstr("\0\0"));
199                 assert(serializeWideString(L"") == mkstr("\0\0"));
200                 assert(serializeLongString("") == mkstr("\0\0\0\0"));
201                 assert(serializeJsonString("") == "\"\"");
202                 
203                 std::string teststring = "Hello world!";
204                 assert(serializeString(teststring) ==
205                         mkstr("\0\14Hello world!"));
206                 assert(serializeWideString(narrow_to_wide(teststring)) ==
207                         mkstr("\0\14\0H\0e\0l\0l\0o\0 \0w\0o\0r\0l\0d\0!"));
208                 assert(serializeLongString(teststring) ==
209                         mkstr("\0\0\0\14Hello world!"));
210                 assert(serializeJsonString(teststring) ==
211                         "\"Hello world!\"");
212
213                 std::string teststring2;
214                 std::wstring teststring2_w;
215                 std::string teststring2_w_encoded;
216                 {
217                         std::ostringstream tmp_os;
218                         std::wostringstream tmp_os_w;
219                         std::ostringstream tmp_os_w_encoded;
220                         for(int i = 0; i < 256; i++)
221                         {
222                                 tmp_os<<(char)i;
223                                 tmp_os_w<<(wchar_t)i;
224                                 tmp_os_w_encoded<<(char)0<<(char)i;
225                         }
226                         teststring2 = tmp_os.str();
227                         teststring2_w = tmp_os_w.str();
228                         teststring2_w_encoded = tmp_os_w_encoded.str();
229                 }
230                 assert(serializeString(teststring2) ==
231                         mkstr("\1\0") + teststring2);
232                 assert(serializeWideString(teststring2_w) ==
233                         mkstr("\1\0") + teststring2_w_encoded);
234                 assert(serializeLongString(teststring2) ==
235                         mkstr("\0\0\1\0") + teststring2);
236                 // MSVC fails when directly using "\\\\"
237                 std::string backslash = "\\";
238                 assert(serializeJsonString(teststring2) ==
239                         mkstr("\"") +
240                         "\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007" +
241                         "\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f" +
242                         "\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017" +
243                         "\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f" +
244                         " !\\\"" + teststring2.substr(0x23, 0x2f-0x23) +
245                         "\\/" + teststring2.substr(0x30, 0x5c-0x30) +
246                         backslash + backslash + teststring2.substr(0x5d, 0x7f-0x5d) + "\\u007f" +
247                         "\\u0080\\u0081\\u0082\\u0083\\u0084\\u0085\\u0086\\u0087" +
248                         "\\u0088\\u0089\\u008a\\u008b\\u008c\\u008d\\u008e\\u008f" +
249                         "\\u0090\\u0091\\u0092\\u0093\\u0094\\u0095\\u0096\\u0097" +
250                         "\\u0098\\u0099\\u009a\\u009b\\u009c\\u009d\\u009e\\u009f" +
251                         "\\u00a0\\u00a1\\u00a2\\u00a3\\u00a4\\u00a5\\u00a6\\u00a7" +
252                         "\\u00a8\\u00a9\\u00aa\\u00ab\\u00ac\\u00ad\\u00ae\\u00af" +
253                         "\\u00b0\\u00b1\\u00b2\\u00b3\\u00b4\\u00b5\\u00b6\\u00b7" +
254                         "\\u00b8\\u00b9\\u00ba\\u00bb\\u00bc\\u00bd\\u00be\\u00bf" +
255                         "\\u00c0\\u00c1\\u00c2\\u00c3\\u00c4\\u00c5\\u00c6\\u00c7" +
256                         "\\u00c8\\u00c9\\u00ca\\u00cb\\u00cc\\u00cd\\u00ce\\u00cf" +
257                         "\\u00d0\\u00d1\\u00d2\\u00d3\\u00d4\\u00d5\\u00d6\\u00d7" +
258                         "\\u00d8\\u00d9\\u00da\\u00db\\u00dc\\u00dd\\u00de\\u00df" +
259                         "\\u00e0\\u00e1\\u00e2\\u00e3\\u00e4\\u00e5\\u00e6\\u00e7" +
260                         "\\u00e8\\u00e9\\u00ea\\u00eb\\u00ec\\u00ed\\u00ee\\u00ef" +
261                         "\\u00f0\\u00f1\\u00f2\\u00f3\\u00f4\\u00f5\\u00f6\\u00f7" +
262                         "\\u00f8\\u00f9\\u00fa\\u00fb\\u00fc\\u00fd\\u00fe\\u00ff" +
263                         "\"");
264
265                 {
266                         std::istringstream is(serializeString(teststring2), std::ios::binary);
267                         assert(deSerializeString(is) == teststring2);
268                         assert(!is.eof());
269                         is.get();
270                         assert(is.eof());
271                 }
272                 {
273                         std::istringstream is(serializeWideString(teststring2_w), std::ios::binary);
274                         assert(deSerializeWideString(is) == teststring2_w);
275                         assert(!is.eof());
276                         is.get();
277                         assert(is.eof());
278                 }
279                 {
280                         std::istringstream is(serializeLongString(teststring2), std::ios::binary);
281                         assert(deSerializeLongString(is) == teststring2);
282                         assert(!is.eof());
283                         is.get();
284                         assert(is.eof());
285                 }
286                 {
287                         std::istringstream is(serializeJsonString(teststring2), std::ios::binary);
288                         //dstream<<serializeJsonString(deSerializeJsonString(is));
289                         assert(deSerializeJsonString(is) == teststring2);
290                         assert(!is.eof());
291                         is.get();
292                         assert(is.eof());
293                 }
294         }
295 };
296
297 struct TestCompress
298 {
299         void Run()
300         {
301                 { // ver 0
302
303                 SharedBuffer<u8> fromdata(4);
304                 fromdata[0]=1;
305                 fromdata[1]=5;
306                 fromdata[2]=5;
307                 fromdata[3]=1;
308                 
309                 std::ostringstream os(std::ios_base::binary);
310                 compress(fromdata, os, 0);
311
312                 std::string str_out = os.str();
313                 
314                 infostream<<"str_out.size()="<<str_out.size()<<std::endl;
315                 infostream<<"TestCompress: 1,5,5,1 -> ";
316                 for(u32 i=0; i<str_out.size(); i++)
317                 {
318                         infostream<<(u32)str_out[i]<<",";
319                 }
320                 infostream<<std::endl;
321
322                 assert(str_out.size() == 10);
323
324                 assert(str_out[0] == 0);
325                 assert(str_out[1] == 0);
326                 assert(str_out[2] == 0);
327                 assert(str_out[3] == 4);
328                 assert(str_out[4] == 0);
329                 assert(str_out[5] == 1);
330                 assert(str_out[6] == 1);
331                 assert(str_out[7] == 5);
332                 assert(str_out[8] == 0);
333                 assert(str_out[9] == 1);
334
335                 std::istringstream is(str_out, std::ios_base::binary);
336                 std::ostringstream os2(std::ios_base::binary);
337
338                 decompress(is, os2, 0);
339                 std::string str_out2 = os2.str();
340
341                 infostream<<"decompress: ";
342                 for(u32 i=0; i<str_out2.size(); i++)
343                 {
344                         infostream<<(u32)str_out2[i]<<",";
345                 }
346                 infostream<<std::endl;
347
348                 assert(str_out2.size() == fromdata.getSize());
349
350                 for(u32 i=0; i<str_out2.size(); i++)
351                 {
352                         assert(str_out2[i] == fromdata[i]);
353                 }
354
355                 }
356
357                 { // ver HIGHEST
358
359                 SharedBuffer<u8> fromdata(4);
360                 fromdata[0]=1;
361                 fromdata[1]=5;
362                 fromdata[2]=5;
363                 fromdata[3]=1;
364                 
365                 std::ostringstream os(std::ios_base::binary);
366                 compress(fromdata, os, SER_FMT_VER_HIGHEST);
367
368                 std::string str_out = os.str();
369                 
370                 infostream<<"str_out.size()="<<str_out.size()<<std::endl;
371                 infostream<<"TestCompress: 1,5,5,1 -> ";
372                 for(u32 i=0; i<str_out.size(); i++)
373                 {
374                         infostream<<(u32)str_out[i]<<",";
375                 }
376                 infostream<<std::endl;
377
378                 /*assert(str_out.size() == 10);
379
380                 assert(str_out[0] == 0);
381                 assert(str_out[1] == 0);
382                 assert(str_out[2] == 0);
383                 assert(str_out[3] == 4);
384                 assert(str_out[4] == 0);
385                 assert(str_out[5] == 1);
386                 assert(str_out[6] == 1);
387                 assert(str_out[7] == 5);
388                 assert(str_out[8] == 0);
389                 assert(str_out[9] == 1);*/
390
391                 std::istringstream is(str_out, std::ios_base::binary);
392                 std::ostringstream os2(std::ios_base::binary);
393
394                 decompress(is, os2, SER_FMT_VER_HIGHEST);
395                 std::string str_out2 = os2.str();
396
397                 infostream<<"decompress: ";
398                 for(u32 i=0; i<str_out2.size(); i++)
399                 {
400                         infostream<<(u32)str_out2[i]<<",";
401                 }
402                 infostream<<std::endl;
403
404                 assert(str_out2.size() == fromdata.getSize());
405
406                 for(u32 i=0; i<str_out2.size(); i++)
407                 {
408                         assert(str_out2[i] == fromdata[i]);
409                 }
410
411                 }
412         }
413 };
414
415 struct TestMapNode
416 {
417         void Run(INodeDefManager *nodedef)
418         {
419                 MapNode n;
420
421                 // Default values
422                 assert(n.getContent() == CONTENT_AIR);
423                 assert(n.getLight(LIGHTBANK_DAY, nodedef) == 0);
424                 assert(n.getLight(LIGHTBANK_NIGHT, nodedef) == 0);
425                 
426                 // Transparency
427                 n.setContent(CONTENT_AIR);
428                 assert(nodedef->get(n).light_propagates == true);
429                 n.setContent(LEGN(nodedef, "CONTENT_STONE"));
430                 assert(nodedef->get(n).light_propagates == false);
431         }
432 };
433
434 struct TestVoxelManipulator
435 {
436         void Run(INodeDefManager *nodedef)
437         {
438                 /*
439                         VoxelArea
440                 */
441
442                 VoxelArea a(v3s16(-1,-1,-1), v3s16(1,1,1));
443                 assert(a.index(0,0,0) == 1*3*3 + 1*3 + 1);
444                 assert(a.index(-1,-1,-1) == 0);
445                 
446                 VoxelArea c(v3s16(-2,-2,-2), v3s16(2,2,2));
447                 // An area that is 1 bigger in x+ and z-
448                 VoxelArea d(v3s16(-2,-2,-3), v3s16(3,2,2));
449                 
450                 core::list<VoxelArea> aa;
451                 d.diff(c, aa);
452                 
453                 // Correct results
454                 core::array<VoxelArea> results;
455                 results.push_back(VoxelArea(v3s16(-2,-2,-3),v3s16(3,2,-3)));
456                 results.push_back(VoxelArea(v3s16(3,-2,-2),v3s16(3,2,2)));
457
458                 assert(aa.size() == results.size());
459                 
460                 infostream<<"Result of diff:"<<std::endl;
461                 for(core::list<VoxelArea>::Iterator
462                                 i = aa.begin(); i != aa.end(); i++)
463                 {
464                         i->print(infostream);
465                         infostream<<std::endl;
466                         
467                         s32 j = results.linear_search(*i);
468                         assert(j != -1);
469                         results.erase(j, 1);
470                 }
471
472
473                 /*
474                         VoxelManipulator
475                 */
476                 
477                 VoxelManipulator v;
478
479                 v.print(infostream, nodedef);
480
481                 infostream<<"*** Setting (-1,0,-1)=2 ***"<<std::endl;
482                 
483                 v.setNodeNoRef(v3s16(-1,0,-1), MapNode(CONTENT_GRASS));
484
485                 v.print(infostream, nodedef);
486
487                 assert(v.getNode(v3s16(-1,0,-1)).getContent() == CONTENT_GRASS);
488
489                 infostream<<"*** Reading from inexistent (0,0,-1) ***"<<std::endl;
490
491                 EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,0,-1)));
492
493                 v.print(infostream, nodedef);
494
495                 infostream<<"*** Adding area ***"<<std::endl;
496
497                 v.addArea(a);
498                 
499                 v.print(infostream, nodedef);
500
501                 assert(v.getNode(v3s16(-1,0,-1)).getContent() == CONTENT_GRASS);
502                 EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,1,1)));
503         }
504 };
505
506 struct TestVoxelAlgorithms
507 {
508         void Run(INodeDefManager *ndef)
509         {
510                 /*
511                         voxalgo::propagateSunlight
512                 */
513                 {
514                         VoxelManipulator v;
515                         for(u16 z=0; z<3; z++)
516                         for(u16 y=0; y<3; y++)
517                         for(u16 x=0; x<3; x++)
518                         {
519                                 v3s16 p(x,y,z);
520                                 v.setNodeNoRef(p, MapNode(CONTENT_AIR));
521                         }
522                         VoxelArea a(v3s16(0,0,0), v3s16(2,2,2));
523                         {
524                                 core::map<v3s16, bool> light_sources;
525                                 voxalgo::setLight(v, a, 0, ndef);
526                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
527                                                 v, a, true, light_sources, ndef);
528                                 //v.print(dstream, ndef, VOXELPRINT_LIGHT_DAY);
529                                 assert(res.bottom_sunlight_valid == true);
530                                 assert(v.getNode(v3s16(1,1,1)).getLight(LIGHTBANK_DAY, ndef)
531                                                 == LIGHT_SUN);
532                         }
533                         v.setNodeNoRef(v3s16(0,0,0), MapNode(CONTENT_STONE));
534                         {
535                                 core::map<v3s16, bool> light_sources;
536                                 voxalgo::setLight(v, a, 0, ndef);
537                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
538                                                 v, a, true, light_sources, ndef);
539                                 assert(res.bottom_sunlight_valid == true);
540                                 assert(v.getNode(v3s16(1,1,1)).getLight(LIGHTBANK_DAY, ndef)
541                                                 == LIGHT_SUN);
542                         }
543                         {
544                                 core::map<v3s16, bool> light_sources;
545                                 voxalgo::setLight(v, a, 0, ndef);
546                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
547                                                 v, a, false, light_sources, ndef);
548                                 assert(res.bottom_sunlight_valid == true);
549                                 assert(v.getNode(v3s16(2,0,2)).getLight(LIGHTBANK_DAY, ndef)
550                                                 == 0);
551                         }
552                         v.setNodeNoRef(v3s16(1,3,2), MapNode(CONTENT_STONE));
553                         {
554                                 core::map<v3s16, bool> light_sources;
555                                 voxalgo::setLight(v, a, 0, ndef);
556                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
557                                                 v, a, true, light_sources, ndef);
558                                 assert(res.bottom_sunlight_valid == true);
559                                 assert(v.getNode(v3s16(1,1,2)).getLight(LIGHTBANK_DAY, ndef)
560                                                 == 0);
561                         }
562                         {
563                                 core::map<v3s16, bool> light_sources;
564                                 voxalgo::setLight(v, a, 0, ndef);
565                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
566                                                 v, a, false, light_sources, ndef);
567                                 assert(res.bottom_sunlight_valid == true);
568                                 assert(v.getNode(v3s16(1,0,2)).getLight(LIGHTBANK_DAY, ndef)
569                                                 == 0);
570                         }
571                         {
572                                 MapNode n(CONTENT_AIR);
573                                 n.setLight(LIGHTBANK_DAY, 10, ndef);
574                                 v.setNodeNoRef(v3s16(1,-1,2), n);
575                         }
576                         {
577                                 core::map<v3s16, bool> light_sources;
578                                 voxalgo::setLight(v, a, 0, ndef);
579                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
580                                                 v, a, true, light_sources, ndef);
581                                 assert(res.bottom_sunlight_valid == true);
582                         }
583                         {
584                                 core::map<v3s16, bool> light_sources;
585                                 voxalgo::setLight(v, a, 0, ndef);
586                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
587                                                 v, a, false, light_sources, ndef);
588                                 assert(res.bottom_sunlight_valid == true);
589                         }
590                         {
591                                 MapNode n(CONTENT_AIR);
592                                 n.setLight(LIGHTBANK_DAY, LIGHT_SUN, ndef);
593                                 v.setNodeNoRef(v3s16(1,-1,2), n);
594                         }
595                         {
596                                 core::map<v3s16, bool> light_sources;
597                                 voxalgo::setLight(v, a, 0, ndef);
598                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
599                                                 v, a, true, light_sources, ndef);
600                                 assert(res.bottom_sunlight_valid == false);
601                         }
602                         {
603                                 core::map<v3s16, bool> light_sources;
604                                 voxalgo::setLight(v, a, 0, ndef);
605                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
606                                                 v, a, false, light_sources, ndef);
607                                 assert(res.bottom_sunlight_valid == false);
608                         }
609                         v.setNodeNoRef(v3s16(1,3,2), MapNode(CONTENT_IGNORE));
610                         {
611                                 core::map<v3s16, bool> light_sources;
612                                 voxalgo::setLight(v, a, 0, ndef);
613                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
614                                                 v, a, true, light_sources, ndef);
615                                 assert(res.bottom_sunlight_valid == true);
616                         }
617                 }
618                 /*
619                         voxalgo::clearLightAndCollectSources
620                 */
621                 {
622                         VoxelManipulator v;
623                         for(u16 z=0; z<3; z++)
624                         for(u16 y=0; y<3; y++)
625                         for(u16 x=0; x<3; x++)
626                         {
627                                 v3s16 p(x,y,z);
628                                 v.setNode(p, MapNode(CONTENT_AIR));
629                         }
630                         VoxelArea a(v3s16(0,0,0), v3s16(2,2,2));
631                         v.setNodeNoRef(v3s16(0,0,0), MapNode(CONTENT_STONE));
632                         v.setNodeNoRef(v3s16(1,1,1), MapNode(CONTENT_TORCH));
633                         {
634                                 MapNode n(CONTENT_AIR);
635                                 n.setLight(LIGHTBANK_DAY, 1, ndef);
636                                 v.setNode(v3s16(1,1,2), n);
637                         }
638                         {
639                                 core::map<v3s16, bool> light_sources;
640                                 core::map<v3s16, u8> unlight_from;
641                                 voxalgo::clearLightAndCollectSources(v, a, LIGHTBANK_DAY,
642                                                 ndef, light_sources, unlight_from);
643                                 //v.print(dstream, ndef, VOXELPRINT_LIGHT_DAY);
644                                 assert(v.getNode(v3s16(0,1,1)).getLight(LIGHTBANK_DAY, ndef)
645                                                 == 0);
646                                 assert(light_sources.find(v3s16(1,1,1)) != NULL);
647                                 assert(light_sources.size() == 1);
648                                 assert(unlight_from.find(v3s16(1,1,2)) != NULL);
649                                 assert(unlight_from.size() == 1);
650                         }
651                 }
652         }
653 };
654
655 struct TestInventory
656 {
657         void Run(IItemDefManager *idef)
658         {
659                 std::string serialized_inventory =
660                 "List 0 32\n"
661                 "Empty\n"
662                 "Empty\n"
663                 "Empty\n"
664                 "Empty\n"
665                 "Empty\n"
666                 "Empty\n"
667                 "Empty\n"
668                 "Empty\n"
669                 "Empty\n"
670                 "Item default:cobble 61\n"
671                 "Empty\n"
672                 "Empty\n"
673                 "Empty\n"
674                 "Empty\n"
675                 "Empty\n"
676                 "Empty\n"
677                 "Item default:dirt 71\n"
678                 "Empty\n"
679                 "Empty\n"
680                 "Empty\n"
681                 "Empty\n"
682                 "Empty\n"
683                 "Empty\n"
684                 "Empty\n"
685                 "Item default:dirt 99\n"
686                 "Item default:cobble 38\n"
687                 "Empty\n"
688                 "Empty\n"
689                 "Empty\n"
690                 "Empty\n"
691                 "Empty\n"
692                 "Empty\n"
693                 "EndInventoryList\n"
694                 "EndInventory\n";
695                 
696                 std::string serialized_inventory_2 =
697                 "List main 32\n"
698                 "Empty\n"
699                 "Empty\n"
700                 "Empty\n"
701                 "Empty\n"
702                 "Empty\n"
703                 "Empty\n"
704                 "Empty\n"
705                 "Empty\n"
706                 "Empty\n"
707                 "Item default:cobble 61\n"
708                 "Empty\n"
709                 "Empty\n"
710                 "Empty\n"
711                 "Empty\n"
712                 "Empty\n"
713                 "Empty\n"
714                 "Item default:dirt 71\n"
715                 "Empty\n"
716                 "Empty\n"
717                 "Empty\n"
718                 "Empty\n"
719                 "Empty\n"
720                 "Empty\n"
721                 "Empty\n"
722                 "Item default:dirt 99\n"
723                 "Item default:cobble 38\n"
724                 "Empty\n"
725                 "Empty\n"
726                 "Empty\n"
727                 "Empty\n"
728                 "Empty\n"
729                 "Empty\n"
730                 "EndInventoryList\n"
731                 "EndInventory\n";
732                 
733                 Inventory inv(idef);
734                 std::istringstream is(serialized_inventory, std::ios::binary);
735                 inv.deSerialize(is);
736                 assert(inv.getList("0"));
737                 assert(!inv.getList("main"));
738                 inv.getList("0")->setName("main");
739                 assert(!inv.getList("0"));
740                 assert(inv.getList("main"));
741                 std::ostringstream inv_os(std::ios::binary);
742                 inv.serialize(inv_os);
743                 assert(inv_os.str() == serialized_inventory_2);
744         }
745 };
746
747 /*
748         NOTE: These tests became non-working then NodeContainer was removed.
749               These should be redone, utilizing some kind of a virtual
750                   interface for Map (IMap would be fine).
751 */
752 #if 0
753 struct TestMapBlock
754 {
755         class TC : public NodeContainer
756         {
757         public:
758
759                 MapNode node;
760                 bool position_valid;
761                 core::list<v3s16> validity_exceptions;
762
763                 TC()
764                 {
765                         position_valid = true;
766                 }
767
768                 virtual bool isValidPosition(v3s16 p)
769                 {
770                         //return position_valid ^ (p==position_valid_exception);
771                         bool exception = false;
772                         for(core::list<v3s16>::Iterator i=validity_exceptions.begin();
773                                         i != validity_exceptions.end(); i++)
774                         {
775                                 if(p == *i)
776                                 {
777                                         exception = true;
778                                         break;
779                                 }
780                         }
781                         return exception ? !position_valid : position_valid;
782                 }
783
784                 virtual MapNode getNode(v3s16 p)
785                 {
786                         if(isValidPosition(p) == false)
787                                 throw InvalidPositionException();
788                         return node;
789                 }
790
791                 virtual void setNode(v3s16 p, MapNode & n)
792                 {
793                         if(isValidPosition(p) == false)
794                                 throw InvalidPositionException();
795                 };
796
797                 virtual u16 nodeContainerId() const
798                 {
799                         return 666;
800                 }
801         };
802
803         void Run()
804         {
805                 TC parent;
806                 
807                 MapBlock b(&parent, v3s16(1,1,1));
808                 v3s16 relpos(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
809
810                 assert(b.getPosRelative() == relpos);
811
812                 assert(b.getBox().MinEdge.X == MAP_BLOCKSIZE);
813                 assert(b.getBox().MaxEdge.X == MAP_BLOCKSIZE*2-1);
814                 assert(b.getBox().MinEdge.Y == MAP_BLOCKSIZE);
815                 assert(b.getBox().MaxEdge.Y == MAP_BLOCKSIZE*2-1);
816                 assert(b.getBox().MinEdge.Z == MAP_BLOCKSIZE);
817                 assert(b.getBox().MaxEdge.Z == MAP_BLOCKSIZE*2-1);
818                 
819                 assert(b.isValidPosition(v3s16(0,0,0)) == true);
820                 assert(b.isValidPosition(v3s16(-1,0,0)) == false);
821                 assert(b.isValidPosition(v3s16(-1,-142,-2341)) == false);
822                 assert(b.isValidPosition(v3s16(-124,142,2341)) == false);
823                 assert(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
824                 assert(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE,MAP_BLOCKSIZE-1)) == false);
825
826                 /*
827                         TODO: this method should probably be removed
828                         if the block size isn't going to be set variable
829                 */
830                 /*assert(b.getSizeNodes() == v3s16(MAP_BLOCKSIZE,
831                                 MAP_BLOCKSIZE, MAP_BLOCKSIZE));*/
832                 
833                 // Changed flag should be initially set
834                 assert(b.getModified() == MOD_STATE_WRITE_NEEDED);
835                 b.resetModified();
836                 assert(b.getModified() == MOD_STATE_CLEAN);
837
838                 // All nodes should have been set to
839                 // .d=CONTENT_IGNORE and .getLight() = 0
840                 for(u16 z=0; z<MAP_BLOCKSIZE; z++)
841                 for(u16 y=0; y<MAP_BLOCKSIZE; y++)
842                 for(u16 x=0; x<MAP_BLOCKSIZE; x++)
843                 {
844                         //assert(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_AIR);
845                         assert(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_IGNORE);
846                         assert(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_DAY) == 0);
847                         assert(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_NIGHT) == 0);
848                 }
849                 
850                 {
851                         MapNode n(CONTENT_AIR);
852                         for(u16 z=0; z<MAP_BLOCKSIZE; z++)
853                         for(u16 y=0; y<MAP_BLOCKSIZE; y++)
854                         for(u16 x=0; x<MAP_BLOCKSIZE; x++)
855                         {
856                                 b.setNode(v3s16(x,y,z), n);
857                         }
858                 }
859                         
860                 /*
861                         Parent fetch functions
862                 */
863                 parent.position_valid = false;
864                 parent.node.setContent(5);
865
866                 MapNode n;
867                 
868                 // Positions in the block should still be valid
869                 assert(b.isValidPositionParent(v3s16(0,0,0)) == true);
870                 assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
871                 n = b.getNodeParent(v3s16(0,MAP_BLOCKSIZE-1,0));
872                 assert(n.getContent() == CONTENT_AIR);
873
874                 // ...but outside the block they should be invalid
875                 assert(b.isValidPositionParent(v3s16(-121,2341,0)) == false);
876                 assert(b.isValidPositionParent(v3s16(-1,0,0)) == false);
877                 assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == false);
878                 
879                 {
880                         bool exception_thrown = false;
881                         try{
882                                 // This should throw an exception
883                                 MapNode n = b.getNodeParent(v3s16(0,0,-1));
884                         }
885                         catch(InvalidPositionException &e)
886                         {
887                                 exception_thrown = true;
888                         }
889                         assert(exception_thrown);
890                 }
891
892                 parent.position_valid = true;
893                 // Now the positions outside should be valid
894                 assert(b.isValidPositionParent(v3s16(-121,2341,0)) == true);
895                 assert(b.isValidPositionParent(v3s16(-1,0,0)) == true);
896                 assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == true);
897                 n = b.getNodeParent(v3s16(0,0,MAP_BLOCKSIZE));
898                 assert(n.getContent() == 5);
899
900                 /*
901                         Set a node
902                 */
903                 v3s16 p(1,2,0);
904                 n.setContent(4);
905                 b.setNode(p, n);
906                 assert(b.getNode(p).getContent() == 4);
907                 //TODO: Update to new system
908                 /*assert(b.getNodeTile(p) == 4);
909                 assert(b.getNodeTile(v3s16(-1,-1,0)) == 5);*/
910                 
911                 /*
912                         propagateSunlight()
913                 */
914                 // Set lighting of all nodes to 0
915                 for(u16 z=0; z<MAP_BLOCKSIZE; z++){
916                         for(u16 y=0; y<MAP_BLOCKSIZE; y++){
917                                 for(u16 x=0; x<MAP_BLOCKSIZE; x++){
918                                         MapNode n = b.getNode(v3s16(x,y,z));
919                                         n.setLight(LIGHTBANK_DAY, 0);
920                                         n.setLight(LIGHTBANK_NIGHT, 0);
921                                         b.setNode(v3s16(x,y,z), n);
922                                 }
923                         }
924                 }
925                 {
926                         /*
927                                 Check how the block handles being a lonely sky block
928                         */
929                         parent.position_valid = true;
930                         b.setIsUnderground(false);
931                         parent.node.setContent(CONTENT_AIR);
932                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_SUN);
933                         parent.node.setLight(LIGHTBANK_NIGHT, 0);
934                         core::map<v3s16, bool> light_sources;
935                         // The bottom block is invalid, because we have a shadowing node
936                         assert(b.propagateSunlight(light_sources) == false);
937                         assert(b.getNode(v3s16(1,4,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
938                         assert(b.getNode(v3s16(1,3,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
939                         assert(b.getNode(v3s16(1,2,0)).getLight(LIGHTBANK_DAY) == 0);
940                         assert(b.getNode(v3s16(1,1,0)).getLight(LIGHTBANK_DAY) == 0);
941                         assert(b.getNode(v3s16(1,0,0)).getLight(LIGHTBANK_DAY) == 0);
942                         assert(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
943                         assert(b.getFaceLight2(1000, p, v3s16(0,1,0)) == LIGHT_SUN);
944                         assert(b.getFaceLight2(1000, p, v3s16(0,-1,0)) == 0);
945                         assert(b.getFaceLight2(0, p, v3s16(0,-1,0)) == 0);
946                         // According to MapBlock::getFaceLight,
947                         // The face on the z+ side should have double-diminished light
948                         //assert(b.getFaceLight(p, v3s16(0,0,1)) == diminish_light(diminish_light(LIGHT_MAX)));
949                         // The face on the z+ side should have diminished light
950                         assert(b.getFaceLight2(1000, p, v3s16(0,0,1)) == diminish_light(LIGHT_MAX));
951                 }
952                 /*
953                         Check how the block handles being in between blocks with some non-sunlight
954                         while being underground
955                 */
956                 {
957                         // Make neighbours to exist and set some non-sunlight to them
958                         parent.position_valid = true;
959                         b.setIsUnderground(true);
960                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2);
961                         core::map<v3s16, bool> light_sources;
962                         // The block below should be valid because there shouldn't be
963                         // sunlight in there either
964                         assert(b.propagateSunlight(light_sources, true) == true);
965                         // Should not touch nodes that are not affected (that is, all of them)
966                         //assert(b.getNode(v3s16(1,2,3)).getLight() == LIGHT_SUN);
967                         // Should set light of non-sunlighted blocks to 0.
968                         assert(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == 0);
969                 }
970                 /*
971                         Set up a situation where:
972                         - There is only air in this block
973                         - There is a valid non-sunlighted block at the bottom, and
974                         - Invalid blocks elsewhere.
975                         - the block is not underground.
976
977                         This should result in bottom block invalidity
978                 */
979                 {
980                         b.setIsUnderground(false);
981                         // Clear block
982                         for(u16 z=0; z<MAP_BLOCKSIZE; z++){
983                                 for(u16 y=0; y<MAP_BLOCKSIZE; y++){
984                                         for(u16 x=0; x<MAP_BLOCKSIZE; x++){
985                                                 MapNode n;
986                                                 n.setContent(CONTENT_AIR);
987                                                 n.setLight(LIGHTBANK_DAY, 0);
988                                                 b.setNode(v3s16(x,y,z), n);
989                                         }
990                                 }
991                         }
992                         // Make neighbours invalid
993                         parent.position_valid = false;
994                         // Add exceptions to the top of the bottom block
995                         for(u16 x=0; x<MAP_BLOCKSIZE; x++)
996                         for(u16 z=0; z<MAP_BLOCKSIZE; z++)
997                         {
998                                 parent.validity_exceptions.push_back(v3s16(MAP_BLOCKSIZE+x, MAP_BLOCKSIZE-1, MAP_BLOCKSIZE+z));
999                         }
1000                         // Lighting value for the valid nodes
1001                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2);
1002                         core::map<v3s16, bool> light_sources;
1003                         // Bottom block is not valid
1004                         assert(b.propagateSunlight(light_sources) == false);
1005                 }
1006         }
1007 };
1008
1009 struct TestMapSector
1010 {
1011         class TC : public NodeContainer
1012         {
1013         public:
1014
1015                 MapNode node;
1016                 bool position_valid;
1017
1018                 TC()
1019                 {
1020                         position_valid = true;
1021                 }
1022
1023                 virtual bool isValidPosition(v3s16 p)
1024                 {
1025                         return position_valid;
1026                 }
1027
1028                 virtual MapNode getNode(v3s16 p)
1029                 {
1030                         if(position_valid == false)
1031                                 throw InvalidPositionException();
1032                         return node;
1033                 }
1034
1035                 virtual void setNode(v3s16 p, MapNode & n)
1036                 {
1037                         if(position_valid == false)
1038                                 throw InvalidPositionException();
1039                 };
1040                 
1041                 virtual u16 nodeContainerId() const
1042                 {
1043                         return 666;
1044                 }
1045         };
1046         
1047         void Run()
1048         {
1049                 TC parent;
1050                 parent.position_valid = false;
1051                 
1052                 // Create one with no heightmaps
1053                 ServerMapSector sector(&parent, v2s16(1,1));
1054                 
1055                 assert(sector.getBlockNoCreateNoEx(0) == 0);
1056                 assert(sector.getBlockNoCreateNoEx(1) == 0);
1057
1058                 MapBlock * bref = sector.createBlankBlock(-2);
1059                 
1060                 assert(sector.getBlockNoCreateNoEx(0) == 0);
1061                 assert(sector.getBlockNoCreateNoEx(-2) == bref);
1062                 
1063                 //TODO: Check for AlreadyExistsException
1064
1065                 /*bool exception_thrown = false;
1066                 try{
1067                         sector.getBlock(0);
1068                 }
1069                 catch(InvalidPositionException &e){
1070                         exception_thrown = true;
1071                 }
1072                 assert(exception_thrown);*/
1073
1074         }
1075 };
1076 #endif
1077
1078 struct TestSocket
1079 {
1080         void Run()
1081         {
1082                 const int port = 30003;
1083                 UDPSocket socket;
1084                 socket.Bind(port);
1085
1086                 const char sendbuffer[] = "hello world!";
1087                 socket.Send(Address(127,0,0,1,port), sendbuffer, sizeof(sendbuffer));
1088
1089                 sleep_ms(50);
1090
1091                 char rcvbuffer[256];
1092                 memset(rcvbuffer, 0, sizeof(rcvbuffer));
1093                 Address sender;
1094                 for(;;)
1095                 {
1096                         int bytes_read = socket.Receive(sender, rcvbuffer, sizeof(rcvbuffer));
1097                         if(bytes_read < 0)
1098                                 break;
1099                 }
1100                 //FIXME: This fails on some systems
1101                 assert(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer))==0);
1102                 assert(sender.getAddress() == Address(127,0,0,1, 0).getAddress());
1103         }
1104 };
1105
1106 struct TestConnection
1107 {
1108         void TestHelpers()
1109         {
1110                 /*
1111                         Test helper functions
1112                 */
1113
1114                 // Some constants for testing
1115                 u32 proto_id = 0x12345678;
1116                 u16 peer_id = 123;
1117                 u8 channel = 2;
1118                 SharedBuffer<u8> data1(1);
1119                 data1[0] = 100;
1120                 Address a(127,0,0,1, 10);
1121                 u16 seqnum = 34352;
1122
1123                 con::BufferedPacket p1 = con::makePacket(a, data1,
1124                                 proto_id, peer_id, channel);
1125                 /*
1126                         We should now have a packet with this data:
1127                         Header:
1128                                 [0] u32 protocol_id
1129                                 [4] u16 sender_peer_id
1130                                 [6] u8 channel
1131                         Data:
1132                                 [7] u8 data1[0]
1133                 */
1134                 assert(readU32(&p1.data[0]) == proto_id);
1135                 assert(readU16(&p1.data[4]) == peer_id);
1136                 assert(readU8(&p1.data[6]) == channel);
1137                 assert(readU8(&p1.data[7]) == data1[0]);
1138                 
1139                 //infostream<<"initial data1[0]="<<((u32)data1[0]&0xff)<<std::endl;
1140
1141                 SharedBuffer<u8> p2 = con::makeReliablePacket(data1, seqnum);
1142
1143                 /*infostream<<"p2.getSize()="<<p2.getSize()<<", data1.getSize()="
1144                                 <<data1.getSize()<<std::endl;
1145                 infostream<<"readU8(&p2[3])="<<readU8(&p2[3])
1146                                 <<" p2[3]="<<((u32)p2[3]&0xff)<<std::endl;
1147                 infostream<<"data1[0]="<<((u32)data1[0]&0xff)<<std::endl;*/
1148
1149                 assert(p2.getSize() == 3 + data1.getSize());
1150                 assert(readU8(&p2[0]) == TYPE_RELIABLE);
1151                 assert(readU16(&p2[1]) == seqnum);
1152                 assert(readU8(&p2[3]) == data1[0]);
1153         }
1154
1155         struct Handler : public con::PeerHandler
1156         {
1157                 Handler(const char *a_name)
1158                 {
1159                         count = 0;
1160                         last_id = 0;
1161                         name = a_name;
1162                 }
1163                 void peerAdded(con::Peer *peer)
1164                 {
1165                         infostream<<"Handler("<<name<<")::peerAdded(): "
1166                                         "id="<<peer->id<<std::endl;
1167                         last_id = peer->id;
1168                         count++;
1169                 }
1170                 void deletingPeer(con::Peer *peer, bool timeout)
1171                 {
1172                         infostream<<"Handler("<<name<<")::deletingPeer(): "
1173                                         "id="<<peer->id
1174                                         <<", timeout="<<timeout<<std::endl;
1175                         last_id = peer->id;
1176                         count--;
1177                 }
1178
1179                 s32 count;
1180                 u16 last_id;
1181                 const char *name;
1182         };
1183
1184         void Run()
1185         {
1186                 DSTACK("TestConnection::Run");
1187
1188                 TestHelpers();
1189
1190                 /*
1191                         Test some real connections
1192
1193                         NOTE: This mostly tests the legacy interface.
1194                 */
1195
1196                 u32 proto_id = 0xad26846a;
1197
1198                 Handler hand_server("server");
1199                 Handler hand_client("client");
1200                 
1201                 infostream<<"** Creating server Connection"<<std::endl;
1202                 con::Connection server(proto_id, 512, 5.0, &hand_server);
1203                 server.Serve(30001);
1204                 
1205                 infostream<<"** Creating client Connection"<<std::endl;
1206                 con::Connection client(proto_id, 512, 5.0, &hand_client);
1207
1208                 assert(hand_server.count == 0);
1209                 assert(hand_client.count == 0);
1210                 
1211                 sleep_ms(50);
1212                 
1213                 Address server_address(127,0,0,1, 30001);
1214                 infostream<<"** running client.Connect()"<<std::endl;
1215                 client.Connect(server_address);
1216
1217                 sleep_ms(50);
1218                 
1219                 // Client should not have added client yet
1220                 assert(hand_client.count == 0);
1221                 
1222                 try
1223                 {
1224                         u16 peer_id;
1225                         SharedBuffer<u8> data;
1226                         infostream<<"** running client.Receive()"<<std::endl;
1227                         u32 size = client.Receive(peer_id, data);
1228                         infostream<<"** Client received: peer_id="<<peer_id
1229                                         <<", size="<<size
1230                                         <<std::endl;
1231                 }
1232                 catch(con::NoIncomingDataException &e)
1233                 {
1234                 }
1235
1236                 // Client should have added server now
1237                 assert(hand_client.count == 1);
1238                 assert(hand_client.last_id == 1);
1239                 // Server should not have added client yet
1240                 assert(hand_server.count == 0);
1241                 
1242                 sleep_ms(50);
1243
1244                 try
1245                 {
1246                         u16 peer_id;
1247                         SharedBuffer<u8> data;
1248                         infostream<<"** running server.Receive()"<<std::endl;
1249                         u32 size = server.Receive(peer_id, data);
1250                         infostream<<"** Server received: peer_id="<<peer_id
1251                                         <<", size="<<size
1252                                         <<std::endl;
1253                 }
1254                 catch(con::NoIncomingDataException &e)
1255                 {
1256                         // No actual data received, but the client has
1257                         // probably been connected
1258                 }
1259                 
1260                 // Client should be the same
1261                 assert(hand_client.count == 1);
1262                 assert(hand_client.last_id == 1);
1263                 // Server should have the client
1264                 assert(hand_server.count == 1);
1265                 assert(hand_server.last_id == 2);
1266                 
1267                 //sleep_ms(50);
1268
1269                 while(client.Connected() == false)
1270                 {
1271                         try
1272                         {
1273                                 u16 peer_id;
1274                                 SharedBuffer<u8> data;
1275                                 infostream<<"** running client.Receive()"<<std::endl;
1276                                 u32 size = client.Receive(peer_id, data);
1277                                 infostream<<"** Client received: peer_id="<<peer_id
1278                                                 <<", size="<<size
1279                                                 <<std::endl;
1280                         }
1281                         catch(con::NoIncomingDataException &e)
1282                         {
1283                         }
1284                         sleep_ms(50);
1285                 }
1286
1287                 sleep_ms(50);
1288                 
1289                 try
1290                 {
1291                         u16 peer_id;
1292                         SharedBuffer<u8> data;
1293                         infostream<<"** running server.Receive()"<<std::endl;
1294                         u32 size = server.Receive(peer_id, data);
1295                         infostream<<"** Server received: peer_id="<<peer_id
1296                                         <<", size="<<size
1297                                         <<std::endl;
1298                 }
1299                 catch(con::NoIncomingDataException &e)
1300                 {
1301                 }
1302 #if 1
1303                 /*
1304                         Simple send-receive test
1305                 */
1306                 {
1307                         /*u8 data[] = "Hello World!";
1308                         u32 datasize = sizeof(data);*/
1309                         SharedBuffer<u8> data = SharedBufferFromString("Hello World!");
1310
1311                         infostream<<"** running client.Send()"<<std::endl;
1312                         client.Send(PEER_ID_SERVER, 0, data, true);
1313
1314                         sleep_ms(50);
1315
1316                         u16 peer_id;
1317                         SharedBuffer<u8> recvdata;
1318                         infostream<<"** running server.Receive()"<<std::endl;
1319                         u32 size = server.Receive(peer_id, recvdata);
1320                         infostream<<"** Server received: peer_id="<<peer_id
1321                                         <<", size="<<size
1322                                         <<", data="<<*data
1323                                         <<std::endl;
1324                         assert(memcmp(*data, *recvdata, data.getSize()) == 0);
1325                 }
1326 #endif
1327                 u16 peer_id_client = 2;
1328 #if 0
1329                 /*
1330                         Send consequent packets in different order
1331                         Not compatible with new Connection, thus commented out.
1332                 */
1333                 {
1334                         //u8 data1[] = "hello1";
1335                         //u8 data2[] = "hello2";
1336                         SharedBuffer<u8> data1 = SharedBufferFromString("hello1");
1337                         SharedBuffer<u8> data2 = SharedBufferFromString("Hello2");
1338
1339                         Address client_address =
1340                                         server.GetPeerAddress(peer_id_client);
1341                         
1342                         infostream<<"*** Sending packets in wrong order (2,1,2)"
1343                                         <<std::endl;
1344                         
1345                         u8 chn = 0;
1346                         con::Channel *ch = &server.getPeer(peer_id_client)->channels[chn];
1347                         u16 sn = ch->next_outgoing_seqnum;
1348                         ch->next_outgoing_seqnum = sn+1;
1349                         server.Send(peer_id_client, chn, data2, true);
1350                         ch->next_outgoing_seqnum = sn;
1351                         server.Send(peer_id_client, chn, data1, true);
1352                         ch->next_outgoing_seqnum = sn+1;
1353                         server.Send(peer_id_client, chn, data2, true);
1354
1355                         sleep_ms(50);
1356
1357                         infostream<<"*** Receiving the packets"<<std::endl;
1358
1359                         u16 peer_id;
1360                         SharedBuffer<u8> recvdata;
1361                         u32 size;
1362
1363                         infostream<<"** running client.Receive()"<<std::endl;
1364                         peer_id = 132;
1365                         size = client.Receive(peer_id, recvdata);
1366                         infostream<<"** Client received: peer_id="<<peer_id
1367                                         <<", size="<<size
1368                                         <<", data="<<*recvdata
1369                                         <<std::endl;
1370                         assert(size == data1.getSize());
1371                         assert(memcmp(*data1, *recvdata, data1.getSize()) == 0);
1372                         assert(peer_id == PEER_ID_SERVER);
1373                         
1374                         infostream<<"** running client.Receive()"<<std::endl;
1375                         peer_id = 132;
1376                         size = client.Receive(peer_id, recvdata);
1377                         infostream<<"** Client received: peer_id="<<peer_id
1378                                         <<", size="<<size
1379                                         <<", data="<<*recvdata
1380                                         <<std::endl;
1381                         assert(size == data2.getSize());
1382                         assert(memcmp(*data2, *recvdata, data2.getSize()) == 0);
1383                         assert(peer_id == PEER_ID_SERVER);
1384                         
1385                         bool got_exception = false;
1386                         try
1387                         {
1388                                 infostream<<"** running client.Receive()"<<std::endl;
1389                                 peer_id = 132;
1390                                 size = client.Receive(peer_id, recvdata);
1391                                 infostream<<"** Client received: peer_id="<<peer_id
1392                                                 <<", size="<<size
1393                                                 <<", data="<<*recvdata
1394                                                 <<std::endl;
1395                         }
1396                         catch(con::NoIncomingDataException &e)
1397                         {
1398                                 infostream<<"** No incoming data for client"<<std::endl;
1399                                 got_exception = true;
1400                         }
1401                         assert(got_exception);
1402                 }
1403 #endif
1404 #if 0
1405                 /*
1406                         Send large amounts of packets (infinite test)
1407                         Commented out because of infinity.
1408                 */
1409                 {
1410                         infostream<<"Sending large amounts of packets (infinite test)"<<std::endl;
1411                         int sendcount = 0;
1412                         for(;;){
1413                                 int datasize = myrand_range(0,5)==0?myrand_range(100,10000):myrand_range(0,100);
1414                                 infostream<<"datasize="<<datasize<<std::endl;
1415                                 SharedBuffer<u8> data1(datasize);
1416                                 for(u16 i=0; i<datasize; i++)
1417                                         data1[i] = i/4;
1418                                 
1419                                 int sendtimes = myrand_range(1,10);
1420                                 for(int i=0; i<sendtimes; i++){
1421                                         server.Send(peer_id_client, 0, data1, true);
1422                                         sendcount++;
1423                                 }
1424                                 infostream<<"sendcount="<<sendcount<<std::endl;
1425                                 
1426                                 //int receivetimes = myrand_range(1,20);
1427                                 int receivetimes = 20;
1428                                 for(int i=0; i<receivetimes; i++){
1429                                         SharedBuffer<u8> recvdata;
1430                                         u16 peer_id = 132;
1431                                         u16 size = 0;
1432                                         bool received = false;
1433                                         try{
1434                                                 size = client.Receive(peer_id, recvdata);
1435                                                 received = true;
1436                                         }catch(con::NoIncomingDataException &e){
1437                                         }
1438                                 }
1439                         }
1440                 }
1441 #endif
1442                 /*
1443                         Send a large packet
1444                 */
1445                 {
1446                         const int datasize = 30000;
1447                         SharedBuffer<u8> data1(datasize);
1448                         for(u16 i=0; i<datasize; i++){
1449                                 data1[i] = i/4;
1450                         }
1451
1452                         infostream<<"Sending data (size="<<datasize<<"):";
1453                         for(int i=0; i<datasize && i<20; i++){
1454                                 if(i%2==0) infostream<<" ";
1455                                 char buf[10];
1456                                 snprintf(buf, 10, "%.2X", ((int)((const char*)*data1)[i])&0xff);
1457                                 infostream<<buf;
1458                         }
1459                         if(datasize>20)
1460                                 infostream<<"...";
1461                         infostream<<std::endl;
1462                         
1463                         server.Send(peer_id_client, 0, data1, true);
1464
1465                         //sleep_ms(3000);
1466                         
1467                         SharedBuffer<u8> recvdata;
1468                         infostream<<"** running client.Receive()"<<std::endl;
1469                         u16 peer_id = 132;
1470                         u16 size = 0;
1471                         bool received = false;
1472                         u32 timems0 = porting::getTimeMs();
1473                         for(;;){
1474                                 if(porting::getTimeMs() - timems0 > 5000 || received)
1475                                         break;
1476                                 try{
1477                                         size = client.Receive(peer_id, recvdata);
1478                                         received = true;
1479                                 }catch(con::NoIncomingDataException &e){
1480                                 }
1481                                 sleep_ms(10);
1482                         }
1483                         assert(received);
1484                         infostream<<"** Client received: peer_id="<<peer_id
1485                                         <<", size="<<size
1486                                         <<std::endl;
1487
1488                         infostream<<"Received data (size="<<size<<"): ";
1489                         for(int i=0; i<size && i<20; i++){
1490                                 if(i%2==0) infostream<<" ";
1491                                 char buf[10];
1492                                 snprintf(buf, 10, "%.2X", ((int)(recvdata[i]))&0xff);
1493                                 infostream<<buf;
1494                         }
1495                         if(size>20)
1496                                 infostream<<"...";
1497                         infostream<<std::endl;
1498
1499                         assert(memcmp(*data1, *recvdata, data1.getSize()) == 0);
1500                         assert(peer_id == PEER_ID_SERVER);
1501                 }
1502                 
1503                 // Check peer handlers
1504                 assert(hand_client.count == 1);
1505                 assert(hand_client.last_id == 1);
1506                 assert(hand_server.count == 1);
1507                 assert(hand_server.last_id == 2);
1508                 
1509                 //assert(0);
1510         }
1511 };
1512
1513 #define TEST(X)\
1514 {\
1515         X x;\
1516         infostream<<"Running " #X <<std::endl;\
1517         x.Run();\
1518 }
1519
1520 #define TESTPARAMS(X, ...)\
1521 {\
1522         X x;\
1523         infostream<<"Running " #X <<std::endl;\
1524         x.Run(__VA_ARGS__);\
1525 }
1526
1527 void run_tests()
1528 {
1529         DSTACK(__FUNCTION_NAME);
1530         
1531         // Create item and node definitions
1532         IWritableItemDefManager *idef = createItemDefManager();
1533         IWritableNodeDefManager *ndef = createNodeDefManager();
1534         define_some_nodes(idef, ndef);
1535
1536         infostream<<"run_tests() started"<<std::endl;
1537         TEST(TestUtilities);
1538         TEST(TestSettings);
1539         TEST(TestCompress);
1540         TEST(TestSerialization);
1541         TESTPARAMS(TestMapNode, ndef);
1542         TESTPARAMS(TestVoxelManipulator, ndef);
1543         TESTPARAMS(TestVoxelAlgorithms, ndef);
1544         TESTPARAMS(TestInventory, idef);
1545         //TEST(TestMapBlock);
1546         //TEST(TestMapSector);
1547         if(INTERNET_SIMULATOR == false){
1548                 TEST(TestSocket);
1549                 dout_con<<"=== BEGIN RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl;
1550                 TEST(TestConnection);
1551                 dout_con<<"=== END RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl;
1552         }
1553         infostream<<"run_tests() passed"<<std::endl;
1554 }
1555