dd26919473292b11f67c4eeea9f07c3a5384205f
[oweals/minetest.git] / src / test.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 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 "irrlichttypes_extrabloated.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 "collision.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 #include "util/string.h"
39 #include "filesys.h"
40 #include "voxelalgorithms.h"
41 #include "inventory.h"
42 #include "util/numeric.h"
43 #include "util/serialize.h"
44 #include "noise.h" // PseudoRandom used for random data for compression
45 #include "clientserver.h" // LATEST_PROTOCOL_VERSION
46 #include <algorithm>
47
48 /*
49         Asserts that the exception occurs
50 */
51 #define EXCEPTION_CHECK(EType, code)\
52 {\
53         bool exception_thrown = false;\
54         try{ code; }\
55         catch(EType &e) { exception_thrown = true; }\
56         UASSERT(exception_thrown);\
57 }
58
59 #define UTEST(x, fmt, ...)\
60 {\
61         if(!(x)){\
62                 LOGLINEF(LMT_ERROR, "Test (%s) failed: " fmt, #x, ##__VA_ARGS__);\
63                 test_failed = true;\
64         }\
65 }
66
67 #define UASSERT(x) UTEST(x, "UASSERT")
68
69 /*
70         A few item and node definitions for those tests that need them
71 */
72
73 static content_t CONTENT_STONE;
74 static content_t CONTENT_GRASS;
75 static content_t CONTENT_TORCH;
76
77 void define_some_nodes(IWritableItemDefManager *idef, IWritableNodeDefManager *ndef)
78 {
79         ItemDefinition itemdef;
80         ContentFeatures f;
81
82         /*
83                 Stone
84         */
85         itemdef = ItemDefinition();
86         itemdef.type = ITEM_NODE;
87         itemdef.name = "default:stone";
88         itemdef.description = "Stone";
89         itemdef.groups["cracky"] = 3;
90         itemdef.inventory_image = "[inventorycube"
91                 "{default_stone.png"
92                 "{default_stone.png"
93                 "{default_stone.png";
94         f = ContentFeatures();
95         f.name = itemdef.name;
96         for(int i = 0; i < 6; i++)
97                 f.tiledef[i].name = "default_stone.png";
98         f.is_ground_content = true;
99         idef->registerItem(itemdef);
100         CONTENT_STONE = ndef->set(f.name, f);
101
102         /*
103                 Grass
104         */
105         itemdef = ItemDefinition();
106         itemdef.type = ITEM_NODE;
107         itemdef.name = "default:dirt_with_grass";
108         itemdef.description = "Dirt with grass";
109         itemdef.groups["crumbly"] = 3;
110         itemdef.inventory_image = "[inventorycube"
111                 "{default_grass.png"
112                 "{default_dirt.png&default_grass_side.png"
113                 "{default_dirt.png&default_grass_side.png";
114         f = ContentFeatures();
115         f.name = itemdef.name;
116         f.tiledef[0].name = "default_grass.png";
117         f.tiledef[1].name = "default_dirt.png";
118         for(int i = 2; i < 6; i++)
119                 f.tiledef[i].name = "default_dirt.png^default_grass_side.png";
120         f.is_ground_content = true;
121         idef->registerItem(itemdef);
122         CONTENT_GRASS = ndef->set(f.name, f);
123
124         /*
125                 Torch (minimal definition for lighting tests)
126         */
127         itemdef = ItemDefinition();
128         itemdef.type = ITEM_NODE;
129         itemdef.name = "default:torch";
130         f = ContentFeatures();
131         f.name = itemdef.name;
132         f.param_type = CPT_LIGHT;
133         f.light_propagates = true;
134         f.sunlight_propagates = true;
135         f.light_source = LIGHT_MAX-1;
136         idef->registerItem(itemdef);
137         CONTENT_TORCH = ndef->set(f.name, f);
138 }
139
140 struct TestBase
141 {
142         bool test_failed;
143         TestBase():
144                 test_failed(false)
145         {}
146 };
147
148 struct TestUtilities: public TestBase
149 {
150         void Run()
151         {
152                 /*infostream<<"wrapDegrees(100.0) = "<<wrapDegrees(100.0)<<std::endl;
153                 infostream<<"wrapDegrees(720.5) = "<<wrapDegrees(720.5)<<std::endl;
154                 infostream<<"wrapDegrees(-0.5) = "<<wrapDegrees(-0.5)<<std::endl;*/
155                 UASSERT(fabs(wrapDegrees(100.0) - 100.0) < 0.001);
156                 UASSERT(fabs(wrapDegrees(720.5) - 0.5) < 0.001);
157                 UASSERT(fabs(wrapDegrees(-0.5) - (-0.5)) < 0.001);
158                 UASSERT(fabs(wrapDegrees(-365.5) - (-5.5)) < 0.001);
159                 UASSERT(lowercase("Foo bAR") == "foo bar");
160                 UASSERT(trim("\n \t\r  Foo bAR  \r\n\t\t  ") == "Foo bAR");
161                 UASSERT(trim("\n \t\r    \r\n\t\t  ") == "");
162                 UASSERT(is_yes("YeS") == true);
163                 UASSERT(is_yes("") == false);
164                 UASSERT(is_yes("FAlse") == false);
165                 UASSERT(is_yes("-1") == true);
166                 UASSERT(is_yes("0") == false);
167                 UASSERT(is_yes("1") == true);
168                 UASSERT(is_yes("2") == true);
169                 const char *ends[] = {"abc", "c", "bc", NULL};
170                 UASSERT(removeStringEnd("abc", ends) == "");
171                 UASSERT(removeStringEnd("bc", ends) == "b");
172                 UASSERT(removeStringEnd("12c", ends) == "12");
173                 UASSERT(removeStringEnd("foo", ends) == "");
174                 UASSERT(urlencode("\"Aardvarks lurk, OK?\"")
175                                 == "%22Aardvarks%20lurk%2C%20OK%3F%22");
176                 UASSERT(urldecode("%22Aardvarks%20lurk%2C%20OK%3F%22")
177                                 == "\"Aardvarks lurk, OK?\"");
178         }
179 };
180
181 struct TestPath: public TestBase
182 {
183         // adjusts a POSIX path to system-specific conventions
184         // -> changes '/' to DIR_DELIM
185         // -> absolute paths start with "C:\\" on windows
186         std::string p(std::string path)
187         {
188                 for(size_t i = 0; i < path.size(); ++i){
189                         if(path[i] == '/'){
190                                 path.replace(i, 1, DIR_DELIM);
191                                 i += std::string(DIR_DELIM).size() - 1; // generally a no-op
192                         }
193                 }
194
195                 #ifdef _WIN32
196                 if(path[0] == '\\')
197                         path = "C:" + path;
198                 #endif
199
200                 return path;
201         }
202
203         void Run()
204         {
205                 std::string path, result, removed;
206
207                 /*
208                         Test fs::IsDirDelimiter
209                 */
210                 UASSERT(fs::IsDirDelimiter('/') == true);
211                 UASSERT(fs::IsDirDelimiter('A') == false);
212                 UASSERT(fs::IsDirDelimiter(0) == false);
213                 #ifdef _WIN32
214                 UASSERT(fs::IsDirDelimiter('\\') == true);
215                 #else
216                 UASSERT(fs::IsDirDelimiter('\\') == false);
217                 #endif
218
219                 /*
220                         Test fs::PathStartsWith
221                 */
222                 {
223                         const int numpaths = 12;
224                         std::string paths[numpaths] = {
225                                 "",
226                                 p("/"),
227                                 p("/home/user/minetest"),
228                                 p("/home/user/minetest/bin"),
229                                 p("/home/user/.minetest"),
230                                 p("/tmp/dir/file"),
231                                 p("/tmp/file/"),
232                                 p("/tmP/file"),
233                                 p("/tmp"),
234                                 p("/tmp/dir"),
235                                 p("/home/user2/minetest/worlds"),
236                                 p("/home/user2/minetest/world"),
237                         };
238                         /*
239                                 expected fs::PathStartsWith results
240                                 0 = returns false
241                                 1 = returns true
242                                 2 = returns false on windows, false elsewhere
243                                 3 = returns true on windows, true elsewhere
244                                 4 = returns true if and only if
245                                     FILESYS_CASE_INSENSITIVE is true
246                         */
247                         int expected_results[numpaths][numpaths] = {
248                                 {1,2,0,0,0,0,0,0,0,0,0,0},
249                                 {1,1,0,0,0,0,0,0,0,0,0,0},
250                                 {1,1,1,0,0,0,0,0,0,0,0,0},
251                                 {1,1,1,1,0,0,0,0,0,0,0,0},
252                                 {1,1,0,0,1,0,0,0,0,0,0,0},
253                                 {1,1,0,0,0,1,0,0,1,1,0,0},
254                                 {1,1,0,0,0,0,1,4,1,0,0,0},
255                                 {1,1,0,0,0,0,4,1,4,0,0,0},
256                                 {1,1,0,0,0,0,0,0,1,0,0,0},
257                                 {1,1,0,0,0,0,0,0,1,1,0,0},
258                                 {1,1,0,0,0,0,0,0,0,0,1,0},
259                                 {1,1,0,0,0,0,0,0,0,0,0,1},
260                         };
261
262                         for (int i = 0; i < numpaths; i++)
263                         for (int j = 0; j < numpaths; j++){
264                                 /*verbosestream<<"testing fs::PathStartsWith(\""
265                                         <<paths[i]<<"\", \""
266                                         <<paths[j]<<"\")"<<std::endl;*/
267                                 bool starts = fs::PathStartsWith(paths[i], paths[j]);
268                                 int expected = expected_results[i][j];
269                                 if(expected == 0){
270                                         UASSERT(starts == false);
271                                 }
272                                 else if(expected == 1){
273                                         UASSERT(starts == true);
274                                 }
275                                 #ifdef _WIN32
276                                 else if(expected == 2){
277                                         UASSERT(starts == false);
278                                 }
279                                 else if(expected == 3){
280                                         UASSERT(starts == true);
281                                 }
282                                 #else
283                                 else if(expected == 2){
284                                         UASSERT(starts == true);
285                                 }
286                                 else if(expected == 3){
287                                         UASSERT(starts == false);
288                                 }
289                                 #endif
290                                 else if(expected == 4){
291                                         UASSERT(starts == (bool)FILESYS_CASE_INSENSITIVE);
292                                 }
293                         }
294                 }
295
296                 /*
297                         Test fs::RemoveLastPathComponent
298                 */
299                 UASSERT(fs::RemoveLastPathComponent("") == "");
300                 path = p("/home/user/minetest/bin/..//worlds/world1");
301                 result = fs::RemoveLastPathComponent(path, &removed, 0);
302                 UASSERT(result == path);
303                 UASSERT(removed == "");
304                 result = fs::RemoveLastPathComponent(path, &removed, 1);
305                 UASSERT(result == p("/home/user/minetest/bin/..//worlds"));
306                 UASSERT(removed == p("world1"));
307                 result = fs::RemoveLastPathComponent(path, &removed, 2);
308                 UASSERT(result == p("/home/user/minetest/bin/.."));
309                 UASSERT(removed == p("worlds/world1"));
310                 result = fs::RemoveLastPathComponent(path, &removed, 3);
311                 UASSERT(result == p("/home/user/minetest/bin"));
312                 UASSERT(removed == p("../worlds/world1"));
313                 result = fs::RemoveLastPathComponent(path, &removed, 4);
314                 UASSERT(result == p("/home/user/minetest"));
315                 UASSERT(removed == p("bin/../worlds/world1"));
316                 result = fs::RemoveLastPathComponent(path, &removed, 5);
317                 UASSERT(result == p("/home/user"));
318                 UASSERT(removed == p("minetest/bin/../worlds/world1"));
319                 result = fs::RemoveLastPathComponent(path, &removed, 6);
320                 UASSERT(result == p("/home"));
321                 UASSERT(removed == p("user/minetest/bin/../worlds/world1"));
322                 result = fs::RemoveLastPathComponent(path, &removed, 7);
323                 #ifdef _WIN32
324                 UASSERT(result == "C:");
325                 #else
326                 UASSERT(result == "");
327                 #endif
328                 UASSERT(removed == p("home/user/minetest/bin/../worlds/world1"));
329
330                 /*
331                         Now repeat the test with a trailing delimiter
332                 */
333                 path = p("/home/user/minetest/bin/..//worlds/world1/");
334                 result = fs::RemoveLastPathComponent(path, &removed, 0);
335                 UASSERT(result == path);
336                 UASSERT(removed == "");
337                 result = fs::RemoveLastPathComponent(path, &removed, 1);
338                 UASSERT(result == p("/home/user/minetest/bin/..//worlds"));
339                 UASSERT(removed == p("world1"));
340                 result = fs::RemoveLastPathComponent(path, &removed, 2);
341                 UASSERT(result == p("/home/user/minetest/bin/.."));
342                 UASSERT(removed == p("worlds/world1"));
343                 result = fs::RemoveLastPathComponent(path, &removed, 3);
344                 UASSERT(result == p("/home/user/minetest/bin"));
345                 UASSERT(removed == p("../worlds/world1"));
346                 result = fs::RemoveLastPathComponent(path, &removed, 4);
347                 UASSERT(result == p("/home/user/minetest"));
348                 UASSERT(removed == p("bin/../worlds/world1"));
349                 result = fs::RemoveLastPathComponent(path, &removed, 5);
350                 UASSERT(result == p("/home/user"));
351                 UASSERT(removed == p("minetest/bin/../worlds/world1"));
352                 result = fs::RemoveLastPathComponent(path, &removed, 6);
353                 UASSERT(result == p("/home"));
354                 UASSERT(removed == p("user/minetest/bin/../worlds/world1"));
355                 result = fs::RemoveLastPathComponent(path, &removed, 7);
356                 #ifdef _WIN32
357                 UASSERT(result == "C:");
358                 #else
359                 UASSERT(result == "");
360                 #endif
361                 UASSERT(removed == p("home/user/minetest/bin/../worlds/world1"));
362
363                 /*
364                         Test fs::RemoveRelativePathComponent
365                 */
366                 path = p("/home/user/minetest/bin");
367                 result = fs::RemoveRelativePathComponents(path);
368                 UASSERT(result == path);
369                 path = p("/home/user/minetest/bin/../worlds/world1");
370                 result = fs::RemoveRelativePathComponents(path);
371                 UASSERT(result == p("/home/user/minetest/worlds/world1"));
372                 path = p("/home/user/minetest/bin/../worlds/world1/");
373                 result = fs::RemoveRelativePathComponents(path);
374                 UASSERT(result == p("/home/user/minetest/worlds/world1"));
375                 path = p(".");
376                 result = fs::RemoveRelativePathComponents(path);
377                 UASSERT(result == "");
378                 path = p("./subdir/../..");
379                 result = fs::RemoveRelativePathComponents(path);
380                 UASSERT(result == "");
381                 path = p("/a/b/c/.././../d/../e/f/g/../h/i/j/../../../..");
382                 result = fs::RemoveRelativePathComponents(path);
383                 UASSERT(result == p("/a/e"));
384         }
385 };
386
387 struct TestSettings: public TestBase
388 {
389         void Run()
390         {
391                 Settings s;
392                 // Test reading of settings
393                 s.parseConfigLine("leet = 1337");
394                 s.parseConfigLine("leetleet = 13371337");
395                 s.parseConfigLine("leetleet_neg = -13371337");
396                 s.parseConfigLine("floaty_thing = 1.1");
397                 s.parseConfigLine("stringy_thing = asd /( Â¤%&(/\" BLÖÄRP");
398                 s.parseConfigLine("coord = (1, 2, 4.5)");
399                 UASSERT(s.getS32("leet") == 1337);
400                 UASSERT(s.getS16("leetleet") == 32767);
401                 UASSERT(s.getS16("leetleet_neg") == -32768);
402                 // Not sure if 1.1 is an exact value as a float, but doesn't matter
403                 UASSERT(fabs(s.getFloat("floaty_thing") - 1.1) < 0.001);
404                 UASSERT(s.get("stringy_thing") == "asd /( Â¤%&(/\" BLÖÄRP");
405                 UASSERT(fabs(s.getV3F("coord").X - 1.0) < 0.001);
406                 UASSERT(fabs(s.getV3F("coord").Y - 2.0) < 0.001);
407                 UASSERT(fabs(s.getV3F("coord").Z - 4.5) < 0.001);
408                 // Test the setting of settings too
409                 s.setFloat("floaty_thing_2", 1.2);
410                 s.setV3F("coord2", v3f(1, 2, 3.3));
411                 UASSERT(s.get("floaty_thing_2").substr(0,3) == "1.2");
412                 UASSERT(fabs(s.getFloat("floaty_thing_2") - 1.2) < 0.001);
413                 UASSERT(fabs(s.getV3F("coord2").X - 1.0) < 0.001);
414                 UASSERT(fabs(s.getV3F("coord2").Y - 2.0) < 0.001);
415                 UASSERT(fabs(s.getV3F("coord2").Z - 3.3) < 0.001);
416         }
417 };
418
419 struct TestSerialization: public TestBase
420 {
421         // To be used like this:
422         //   mkstr("Some\0string\0with\0embedded\0nuls")
423         // since std::string("...") doesn't work as expected in that case.
424         template<size_t N> std::string mkstr(const char (&s)[N])
425         {
426                 return std::string(s, N - 1);
427         }
428
429         void Run()
430         {
431                 // Tests some serialization primitives
432
433                 UASSERT(serializeString("") == mkstr("\0\0"));
434                 UASSERT(serializeWideString(L"") == mkstr("\0\0"));
435                 UASSERT(serializeLongString("") == mkstr("\0\0\0\0"));
436                 UASSERT(serializeJsonString("") == "\"\"");
437                 
438                 std::string teststring = "Hello world!";
439                 UASSERT(serializeString(teststring) ==
440                         mkstr("\0\14Hello world!"));
441                 UASSERT(serializeWideString(narrow_to_wide(teststring)) ==
442                         mkstr("\0\14\0H\0e\0l\0l\0o\0 \0w\0o\0r\0l\0d\0!"));
443                 UASSERT(serializeLongString(teststring) ==
444                         mkstr("\0\0\0\14Hello world!"));
445                 UASSERT(serializeJsonString(teststring) ==
446                         "\"Hello world!\"");
447
448                 std::string teststring2;
449                 std::wstring teststring2_w;
450                 std::string teststring2_w_encoded;
451                 {
452                         std::ostringstream tmp_os;
453                         std::wostringstream tmp_os_w;
454                         std::ostringstream tmp_os_w_encoded;
455                         for(int i = 0; i < 256; i++)
456                         {
457                                 tmp_os<<(char)i;
458                                 tmp_os_w<<(wchar_t)i;
459                                 tmp_os_w_encoded<<(char)0<<(char)i;
460                         }
461                         teststring2 = tmp_os.str();
462                         teststring2_w = tmp_os_w.str();
463                         teststring2_w_encoded = tmp_os_w_encoded.str();
464                 }
465                 UASSERT(serializeString(teststring2) ==
466                         mkstr("\1\0") + teststring2);
467                 UASSERT(serializeWideString(teststring2_w) ==
468                         mkstr("\1\0") + teststring2_w_encoded);
469                 UASSERT(serializeLongString(teststring2) ==
470                         mkstr("\0\0\1\0") + teststring2);
471                 // MSVC fails when directly using "\\\\"
472                 std::string backslash = "\\";
473                 UASSERT(serializeJsonString(teststring2) ==
474                         mkstr("\"") +
475                         "\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007" +
476                         "\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f" +
477                         "\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017" +
478                         "\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f" +
479                         " !\\\"" + teststring2.substr(0x23, 0x2f-0x23) +
480                         "\\/" + teststring2.substr(0x30, 0x5c-0x30) +
481                         backslash + backslash + teststring2.substr(0x5d, 0x7f-0x5d) + "\\u007f" +
482                         "\\u0080\\u0081\\u0082\\u0083\\u0084\\u0085\\u0086\\u0087" +
483                         "\\u0088\\u0089\\u008a\\u008b\\u008c\\u008d\\u008e\\u008f" +
484                         "\\u0090\\u0091\\u0092\\u0093\\u0094\\u0095\\u0096\\u0097" +
485                         "\\u0098\\u0099\\u009a\\u009b\\u009c\\u009d\\u009e\\u009f" +
486                         "\\u00a0\\u00a1\\u00a2\\u00a3\\u00a4\\u00a5\\u00a6\\u00a7" +
487                         "\\u00a8\\u00a9\\u00aa\\u00ab\\u00ac\\u00ad\\u00ae\\u00af" +
488                         "\\u00b0\\u00b1\\u00b2\\u00b3\\u00b4\\u00b5\\u00b6\\u00b7" +
489                         "\\u00b8\\u00b9\\u00ba\\u00bb\\u00bc\\u00bd\\u00be\\u00bf" +
490                         "\\u00c0\\u00c1\\u00c2\\u00c3\\u00c4\\u00c5\\u00c6\\u00c7" +
491                         "\\u00c8\\u00c9\\u00ca\\u00cb\\u00cc\\u00cd\\u00ce\\u00cf" +
492                         "\\u00d0\\u00d1\\u00d2\\u00d3\\u00d4\\u00d5\\u00d6\\u00d7" +
493                         "\\u00d8\\u00d9\\u00da\\u00db\\u00dc\\u00dd\\u00de\\u00df" +
494                         "\\u00e0\\u00e1\\u00e2\\u00e3\\u00e4\\u00e5\\u00e6\\u00e7" +
495                         "\\u00e8\\u00e9\\u00ea\\u00eb\\u00ec\\u00ed\\u00ee\\u00ef" +
496                         "\\u00f0\\u00f1\\u00f2\\u00f3\\u00f4\\u00f5\\u00f6\\u00f7" +
497                         "\\u00f8\\u00f9\\u00fa\\u00fb\\u00fc\\u00fd\\u00fe\\u00ff" +
498                         "\"");
499
500                 {
501                         std::istringstream is(serializeString(teststring2), std::ios::binary);
502                         UASSERT(deSerializeString(is) == teststring2);
503                         UASSERT(!is.eof());
504                         is.get();
505                         UASSERT(is.eof());
506                 }
507                 {
508                         std::istringstream is(serializeWideString(teststring2_w), std::ios::binary);
509                         UASSERT(deSerializeWideString(is) == teststring2_w);
510                         UASSERT(!is.eof());
511                         is.get();
512                         UASSERT(is.eof());
513                 }
514                 {
515                         std::istringstream is(serializeLongString(teststring2), std::ios::binary);
516                         UASSERT(deSerializeLongString(is) == teststring2);
517                         UASSERT(!is.eof());
518                         is.get();
519                         UASSERT(is.eof());
520                 }
521                 {
522                         std::istringstream is(serializeJsonString(teststring2), std::ios::binary);
523                         //dstream<<serializeJsonString(deSerializeJsonString(is));
524                         UASSERT(deSerializeJsonString(is) == teststring2);
525                         UASSERT(!is.eof());
526                         is.get();
527                         UASSERT(is.eof());
528                 }
529         }
530 };
531
532 struct TestNodedefSerialization: public TestBase
533 {
534         void Run()
535         {
536                 ContentFeatures f;
537                 f.name = "default:stone";
538                 for(int i = 0; i < 6; i++)
539                         f.tiledef[i].name = "default_stone.png";
540                 f.is_ground_content = true;
541                 std::ostringstream os(std::ios::binary);
542                 f.serialize(os, LATEST_PROTOCOL_VERSION);
543                 verbosestream<<"Test ContentFeatures size: "<<os.str().size()<<std::endl;
544                 std::istringstream is(os.str(), std::ios::binary);
545                 ContentFeatures f2;
546                 f2.deSerialize(is);
547                 UASSERT(f.walkable == f2.walkable);
548                 UASSERT(f.node_box.type == f2.node_box.type);
549         }
550 };
551
552 struct TestCompress: public TestBase
553 {
554         void Run()
555         {
556                 { // ver 0
557
558                 SharedBuffer<u8> fromdata(4);
559                 fromdata[0]=1;
560                 fromdata[1]=5;
561                 fromdata[2]=5;
562                 fromdata[3]=1;
563                 
564                 std::ostringstream os(std::ios_base::binary);
565                 compress(fromdata, os, 0);
566
567                 std::string str_out = os.str();
568                 
569                 infostream<<"str_out.size()="<<str_out.size()<<std::endl;
570                 infostream<<"TestCompress: 1,5,5,1 -> ";
571                 for(u32 i=0; i<str_out.size(); i++)
572                 {
573                         infostream<<(u32)str_out[i]<<",";
574                 }
575                 infostream<<std::endl;
576
577                 UASSERT(str_out.size() == 10);
578
579                 UASSERT(str_out[0] == 0);
580                 UASSERT(str_out[1] == 0);
581                 UASSERT(str_out[2] == 0);
582                 UASSERT(str_out[3] == 4);
583                 UASSERT(str_out[4] == 0);
584                 UASSERT(str_out[5] == 1);
585                 UASSERT(str_out[6] == 1);
586                 UASSERT(str_out[7] == 5);
587                 UASSERT(str_out[8] == 0);
588                 UASSERT(str_out[9] == 1);
589
590                 std::istringstream is(str_out, std::ios_base::binary);
591                 std::ostringstream os2(std::ios_base::binary);
592
593                 decompress(is, os2, 0);
594                 std::string str_out2 = os2.str();
595
596                 infostream<<"decompress: ";
597                 for(u32 i=0; i<str_out2.size(); i++)
598                 {
599                         infostream<<(u32)str_out2[i]<<",";
600                 }
601                 infostream<<std::endl;
602
603                 UASSERT(str_out2.size() == fromdata.getSize());
604
605                 for(u32 i=0; i<str_out2.size(); i++)
606                 {
607                         UASSERT(str_out2[i] == fromdata[i]);
608                 }
609
610                 }
611
612                 { // ver HIGHEST
613
614                 SharedBuffer<u8> fromdata(4);
615                 fromdata[0]=1;
616                 fromdata[1]=5;
617                 fromdata[2]=5;
618                 fromdata[3]=1;
619                 
620                 std::ostringstream os(std::ios_base::binary);
621                 compress(fromdata, os, SER_FMT_VER_HIGHEST_READ);
622
623                 std::string str_out = os.str();
624                 
625                 infostream<<"str_out.size()="<<str_out.size()<<std::endl;
626                 infostream<<"TestCompress: 1,5,5,1 -> ";
627                 for(u32 i=0; i<str_out.size(); i++)
628                 {
629                         infostream<<(u32)str_out[i]<<",";
630                 }
631                 infostream<<std::endl;
632
633                 std::istringstream is(str_out, std::ios_base::binary);
634                 std::ostringstream os2(std::ios_base::binary);
635
636                 decompress(is, os2, SER_FMT_VER_HIGHEST_READ);
637                 std::string str_out2 = os2.str();
638
639                 infostream<<"decompress: ";
640                 for(u32 i=0; i<str_out2.size(); i++)
641                 {
642                         infostream<<(u32)str_out2[i]<<",";
643                 }
644                 infostream<<std::endl;
645
646                 UASSERT(str_out2.size() == fromdata.getSize());
647
648                 for(u32 i=0; i<str_out2.size(); i++)
649                 {
650                         UASSERT(str_out2[i] == fromdata[i]);
651                 }
652
653                 }
654
655                 // Test zlib wrapper with large amounts of data (larger than its
656                 // internal buffers)
657                 {
658                         infostream<<"Test: Testing zlib wrappers with a large amount "
659                                         <<"of pseudorandom data"<<std::endl;
660                         u32 size = 50000;
661                         infostream<<"Test: Input size of large compressZlib is "
662                                         <<size<<std::endl;
663                         std::string data_in;
664                         data_in.resize(size);
665                         PseudoRandom pseudorandom(9420);
666                         for(u32 i=0; i<size; i++)
667                                 data_in[i] = pseudorandom.range(0,255);
668                         std::ostringstream os_compressed(std::ios::binary);
669                         compressZlib(data_in, os_compressed);
670                         infostream<<"Test: Output size of large compressZlib is "
671                                         <<os_compressed.str().size()<<std::endl;
672                         std::istringstream is_compressed(os_compressed.str(), std::ios::binary);
673                         std::ostringstream os_decompressed(std::ios::binary);
674                         decompressZlib(is_compressed, os_decompressed);
675                         infostream<<"Test: Output size of large decompressZlib is "
676                                         <<os_decompressed.str().size()<<std::endl;
677                         std::string str_decompressed = os_decompressed.str();
678                         UTEST(str_decompressed.size() == data_in.size(), "Output size not"
679                                         " equal (output: %u, input: %u)",
680                                         (unsigned int)str_decompressed.size(), (unsigned int)data_in.size());
681                         for(u32 i=0; i<size && i<str_decompressed.size(); i++){
682                                 UTEST(str_decompressed[i] == data_in[i],
683                                                 "index out[%i]=%i differs from in[%i]=%i",
684                                                 i, str_decompressed[i], i, data_in[i]);
685                         }
686                 }
687         }
688 };
689
690 struct TestMapNode: public TestBase
691 {
692         void Run(INodeDefManager *nodedef)
693         {
694                 MapNode n;
695
696                 // Default values
697                 UASSERT(n.getContent() == CONTENT_AIR);
698                 UASSERT(n.getLight(LIGHTBANK_DAY, nodedef) == 0);
699                 UASSERT(n.getLight(LIGHTBANK_NIGHT, nodedef) == 0);
700                 
701                 // Transparency
702                 n.setContent(CONTENT_AIR);
703                 UASSERT(nodedef->get(n).light_propagates == true);
704                 n.setContent(LEGN(nodedef, "CONTENT_STONE"));
705                 UASSERT(nodedef->get(n).light_propagates == false);
706         }
707 };
708
709 struct TestVoxelManipulator: public TestBase
710 {
711         void Run(INodeDefManager *nodedef)
712         {
713                 /*
714                         VoxelArea
715                 */
716
717                 VoxelArea a(v3s16(-1,-1,-1), v3s16(1,1,1));
718                 UASSERT(a.index(0,0,0) == 1*3*3 + 1*3 + 1);
719                 UASSERT(a.index(-1,-1,-1) == 0);
720                 
721                 VoxelArea c(v3s16(-2,-2,-2), v3s16(2,2,2));
722                 // An area that is 1 bigger in x+ and z-
723                 VoxelArea d(v3s16(-2,-2,-3), v3s16(3,2,2));
724                 
725                 std::list<VoxelArea> aa;
726                 d.diff(c, aa);
727                 
728                 // Correct results
729                 std::vector<VoxelArea> results;
730                 results.push_back(VoxelArea(v3s16(-2,-2,-3),v3s16(3,2,-3)));
731                 results.push_back(VoxelArea(v3s16(3,-2,-2),v3s16(3,2,2)));
732
733                 UASSERT(aa.size() == results.size());
734                 
735                 infostream<<"Result of diff:"<<std::endl;
736                 for(std::list<VoxelArea>::const_iterator
737                                 i = aa.begin(); i != aa.end(); ++i)
738                 {
739                         i->print(infostream);
740                         infostream<<std::endl;
741                         
742                         std::vector<VoxelArea>::iterator j = std::find(results.begin(), results.end(), *i);
743                         UASSERT(j != results.end());
744                         results.erase(j);
745                 }
746
747
748                 /*
749                         VoxelManipulator
750                 */
751                 
752                 VoxelManipulator v;
753
754                 v.print(infostream, nodedef);
755
756                 infostream<<"*** Setting (-1,0,-1)=2 ***"<<std::endl;
757                 
758                 v.setNodeNoRef(v3s16(-1,0,-1), MapNode(CONTENT_GRASS));
759
760                 v.print(infostream, nodedef);
761
762                 UASSERT(v.getNode(v3s16(-1,0,-1)).getContent() == CONTENT_GRASS);
763
764                 infostream<<"*** Reading from inexistent (0,0,-1) ***"<<std::endl;
765
766                 EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,0,-1)));
767
768                 v.print(infostream, nodedef);
769
770                 infostream<<"*** Adding area ***"<<std::endl;
771
772                 v.addArea(a);
773                 
774                 v.print(infostream, nodedef);
775
776                 UASSERT(v.getNode(v3s16(-1,0,-1)).getContent() == CONTENT_GRASS);
777                 EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,1,1)));
778         }
779 };
780
781 struct TestVoxelAlgorithms: public TestBase
782 {
783         void Run(INodeDefManager *ndef)
784         {
785                 /*
786                         voxalgo::propagateSunlight
787                 */
788                 {
789                         VoxelManipulator v;
790                         for(u16 z=0; z<3; z++)
791                         for(u16 y=0; y<3; y++)
792                         for(u16 x=0; x<3; x++)
793                         {
794                                 v3s16 p(x,y,z);
795                                 v.setNodeNoRef(p, MapNode(CONTENT_AIR));
796                         }
797                         VoxelArea a(v3s16(0,0,0), v3s16(2,2,2));
798                         {
799                                 std::set<v3s16> light_sources;
800                                 voxalgo::setLight(v, a, 0, ndef);
801                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
802                                                 v, a, true, light_sources, ndef);
803                                 //v.print(dstream, ndef, VOXELPRINT_LIGHT_DAY);
804                                 UASSERT(res.bottom_sunlight_valid == true);
805                                 UASSERT(v.getNode(v3s16(1,1,1)).getLight(LIGHTBANK_DAY, ndef)
806                                                 == LIGHT_SUN);
807                         }
808                         v.setNodeNoRef(v3s16(0,0,0), MapNode(CONTENT_STONE));
809                         {
810                                 std::set<v3s16> light_sources;
811                                 voxalgo::setLight(v, a, 0, ndef);
812                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
813                                                 v, a, true, light_sources, ndef);
814                                 UASSERT(res.bottom_sunlight_valid == true);
815                                 UASSERT(v.getNode(v3s16(1,1,1)).getLight(LIGHTBANK_DAY, ndef)
816                                                 == LIGHT_SUN);
817                         }
818                         {
819                                 std::set<v3s16> light_sources;
820                                 voxalgo::setLight(v, a, 0, ndef);
821                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
822                                                 v, a, false, light_sources, ndef);
823                                 UASSERT(res.bottom_sunlight_valid == true);
824                                 UASSERT(v.getNode(v3s16(2,0,2)).getLight(LIGHTBANK_DAY, ndef)
825                                                 == 0);
826                         }
827                         v.setNodeNoRef(v3s16(1,3,2), MapNode(CONTENT_STONE));
828                         {
829                                 std::set<v3s16> light_sources;
830                                 voxalgo::setLight(v, a, 0, ndef);
831                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
832                                                 v, a, true, light_sources, ndef);
833                                 UASSERT(res.bottom_sunlight_valid == true);
834                                 UASSERT(v.getNode(v3s16(1,1,2)).getLight(LIGHTBANK_DAY, ndef)
835                                                 == 0);
836                         }
837                         {
838                                 std::set<v3s16> light_sources;
839                                 voxalgo::setLight(v, a, 0, ndef);
840                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
841                                                 v, a, false, light_sources, ndef);
842                                 UASSERT(res.bottom_sunlight_valid == true);
843                                 UASSERT(v.getNode(v3s16(1,0,2)).getLight(LIGHTBANK_DAY, ndef)
844                                                 == 0);
845                         }
846                         {
847                                 MapNode n(CONTENT_AIR);
848                                 n.setLight(LIGHTBANK_DAY, 10, ndef);
849                                 v.setNodeNoRef(v3s16(1,-1,2), n);
850                         }
851                         {
852                                 std::set<v3s16> light_sources;
853                                 voxalgo::setLight(v, a, 0, ndef);
854                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
855                                                 v, a, true, light_sources, ndef);
856                                 UASSERT(res.bottom_sunlight_valid == true);
857                         }
858                         {
859                                 std::set<v3s16> light_sources;
860                                 voxalgo::setLight(v, a, 0, ndef);
861                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
862                                                 v, a, false, light_sources, ndef);
863                                 UASSERT(res.bottom_sunlight_valid == true);
864                         }
865                         {
866                                 MapNode n(CONTENT_AIR);
867                                 n.setLight(LIGHTBANK_DAY, LIGHT_SUN, ndef);
868                                 v.setNodeNoRef(v3s16(1,-1,2), n);
869                         }
870                         {
871                                 std::set<v3s16> light_sources;
872                                 voxalgo::setLight(v, a, 0, ndef);
873                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
874                                                 v, a, true, light_sources, ndef);
875                                 UASSERT(res.bottom_sunlight_valid == false);
876                         }
877                         {
878                                 std::set<v3s16> light_sources;
879                                 voxalgo::setLight(v, a, 0, ndef);
880                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
881                                                 v, a, false, light_sources, ndef);
882                                 UASSERT(res.bottom_sunlight_valid == false);
883                         }
884                         v.setNodeNoRef(v3s16(1,3,2), MapNode(CONTENT_IGNORE));
885                         {
886                                 std::set<v3s16> light_sources;
887                                 voxalgo::setLight(v, a, 0, ndef);
888                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
889                                                 v, a, true, light_sources, ndef);
890                                 UASSERT(res.bottom_sunlight_valid == true);
891                         }
892                 }
893                 /*
894                         voxalgo::clearLightAndCollectSources
895                 */
896                 {
897                         VoxelManipulator v;
898                         for(u16 z=0; z<3; z++)
899                         for(u16 y=0; y<3; y++)
900                         for(u16 x=0; x<3; x++)
901                         {
902                                 v3s16 p(x,y,z);
903                                 v.setNode(p, MapNode(CONTENT_AIR));
904                         }
905                         VoxelArea a(v3s16(0,0,0), v3s16(2,2,2));
906                         v.setNodeNoRef(v3s16(0,0,0), MapNode(CONTENT_STONE));
907                         v.setNodeNoRef(v3s16(1,1,1), MapNode(CONTENT_TORCH));
908                         {
909                                 MapNode n(CONTENT_AIR);
910                                 n.setLight(LIGHTBANK_DAY, 1, ndef);
911                                 v.setNode(v3s16(1,1,2), n);
912                         }
913                         {
914                                 std::set<v3s16> light_sources;
915                                 std::map<v3s16, u8> unlight_from;
916                                 voxalgo::clearLightAndCollectSources(v, a, LIGHTBANK_DAY,
917                                                 ndef, light_sources, unlight_from);
918                                 //v.print(dstream, ndef, VOXELPRINT_LIGHT_DAY);
919                                 UASSERT(v.getNode(v3s16(0,1,1)).getLight(LIGHTBANK_DAY, ndef)
920                                                 == 0);
921                                 UASSERT(light_sources.find(v3s16(1,1,1)) != light_sources.end());
922                                 UASSERT(light_sources.size() == 1);
923                                 UASSERT(unlight_from.find(v3s16(1,1,2)) != unlight_from.end());
924                                 UASSERT(unlight_from.size() == 1);
925                         }
926                 }
927         }
928 };
929
930 struct TestInventory: public TestBase
931 {
932         void Run(IItemDefManager *idef)
933         {
934                 std::string serialized_inventory =
935                 "List 0 32\n"
936                 "Width 3\n"
937                 "Empty\n"
938                 "Empty\n"
939                 "Empty\n"
940                 "Empty\n"
941                 "Empty\n"
942                 "Empty\n"
943                 "Empty\n"
944                 "Empty\n"
945                 "Empty\n"
946                 "Item default:cobble 61\n"
947                 "Empty\n"
948                 "Empty\n"
949                 "Empty\n"
950                 "Empty\n"
951                 "Empty\n"
952                 "Empty\n"
953                 "Item default:dirt 71\n"
954                 "Empty\n"
955                 "Empty\n"
956                 "Empty\n"
957                 "Empty\n"
958                 "Empty\n"
959                 "Empty\n"
960                 "Empty\n"
961                 "Item default:dirt 99\n"
962                 "Item default:cobble 38\n"
963                 "Empty\n"
964                 "Empty\n"
965                 "Empty\n"
966                 "Empty\n"
967                 "Empty\n"
968                 "Empty\n"
969                 "EndInventoryList\n"
970                 "EndInventory\n";
971                 
972                 std::string serialized_inventory_2 =
973                 "List main 32\n"
974                 "Width 5\n"
975                 "Empty\n"
976                 "Empty\n"
977                 "Empty\n"
978                 "Empty\n"
979                 "Empty\n"
980                 "Empty\n"
981                 "Empty\n"
982                 "Empty\n"
983                 "Empty\n"
984                 "Item default:cobble 61\n"
985                 "Empty\n"
986                 "Empty\n"
987                 "Empty\n"
988                 "Empty\n"
989                 "Empty\n"
990                 "Empty\n"
991                 "Item default:dirt 71\n"
992                 "Empty\n"
993                 "Empty\n"
994                 "Empty\n"
995                 "Empty\n"
996                 "Empty\n"
997                 "Empty\n"
998                 "Empty\n"
999                 "Item default:dirt 99\n"
1000                 "Item default:cobble 38\n"
1001                 "Empty\n"
1002                 "Empty\n"
1003                 "Empty\n"
1004                 "Empty\n"
1005                 "Empty\n"
1006                 "Empty\n"
1007                 "EndInventoryList\n"
1008                 "EndInventory\n";
1009                 
1010                 Inventory inv(idef);
1011                 std::istringstream is(serialized_inventory, std::ios::binary);
1012                 inv.deSerialize(is);
1013                 UASSERT(inv.getList("0"));
1014                 UASSERT(!inv.getList("main"));
1015                 inv.getList("0")->setName("main");
1016                 UASSERT(!inv.getList("0"));
1017                 UASSERT(inv.getList("main"));
1018                 UASSERT(inv.getList("main")->getWidth() == 3);
1019                 inv.getList("main")->setWidth(5);
1020                 std::ostringstream inv_os(std::ios::binary);
1021                 inv.serialize(inv_os);
1022                 UASSERT(inv_os.str() == serialized_inventory_2);
1023         }
1024 };
1025
1026 /*
1027         NOTE: These tests became non-working then NodeContainer was removed.
1028               These should be redone, utilizing some kind of a virtual
1029                   interface for Map (IMap would be fine).
1030 */
1031 #if 0
1032 struct TestMapBlock: public TestBase
1033 {
1034         class TC : public NodeContainer
1035         {
1036         public:
1037
1038                 MapNode node;
1039                 bool position_valid;
1040                 core::list<v3s16> validity_exceptions;
1041
1042                 TC()
1043                 {
1044                         position_valid = true;
1045                 }
1046
1047                 virtual bool isValidPosition(v3s16 p)
1048                 {
1049                         //return position_valid ^ (p==position_valid_exception);
1050                         bool exception = false;
1051                         for(core::list<v3s16>::Iterator i=validity_exceptions.begin();
1052                                         i != validity_exceptions.end(); i++)
1053                         {
1054                                 if(p == *i)
1055                                 {
1056                                         exception = true;
1057                                         break;
1058                                 }
1059                         }
1060                         return exception ? !position_valid : position_valid;
1061                 }
1062
1063                 virtual MapNode getNode(v3s16 p)
1064                 {
1065                         if(isValidPosition(p) == false)
1066                                 throw InvalidPositionException();
1067                         return node;
1068                 }
1069
1070                 virtual void setNode(v3s16 p, MapNode & n)
1071                 {
1072                         if(isValidPosition(p) == false)
1073                                 throw InvalidPositionException();
1074                 };
1075
1076                 virtual u16 nodeContainerId() const
1077                 {
1078                         return 666;
1079                 }
1080         };
1081
1082         void Run()
1083         {
1084                 TC parent;
1085                 
1086                 MapBlock b(&parent, v3s16(1,1,1));
1087                 v3s16 relpos(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
1088
1089                 UASSERT(b.getPosRelative() == relpos);
1090
1091                 UASSERT(b.getBox().MinEdge.X == MAP_BLOCKSIZE);
1092                 UASSERT(b.getBox().MaxEdge.X == MAP_BLOCKSIZE*2-1);
1093                 UASSERT(b.getBox().MinEdge.Y == MAP_BLOCKSIZE);
1094                 UASSERT(b.getBox().MaxEdge.Y == MAP_BLOCKSIZE*2-1);
1095                 UASSERT(b.getBox().MinEdge.Z == MAP_BLOCKSIZE);
1096                 UASSERT(b.getBox().MaxEdge.Z == MAP_BLOCKSIZE*2-1);
1097                 
1098                 UASSERT(b.isValidPosition(v3s16(0,0,0)) == true);
1099                 UASSERT(b.isValidPosition(v3s16(-1,0,0)) == false);
1100                 UASSERT(b.isValidPosition(v3s16(-1,-142,-2341)) == false);
1101                 UASSERT(b.isValidPosition(v3s16(-124,142,2341)) == false);
1102                 UASSERT(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
1103                 UASSERT(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE,MAP_BLOCKSIZE-1)) == false);
1104
1105                 /*
1106                         TODO: this method should probably be removed
1107                         if the block size isn't going to be set variable
1108                 */
1109                 /*UASSERT(b.getSizeNodes() == v3s16(MAP_BLOCKSIZE,
1110                                 MAP_BLOCKSIZE, MAP_BLOCKSIZE));*/
1111                 
1112                 // Changed flag should be initially set
1113                 UASSERT(b.getModified() == MOD_STATE_WRITE_NEEDED);
1114                 b.resetModified();
1115                 UASSERT(b.getModified() == MOD_STATE_CLEAN);
1116
1117                 // All nodes should have been set to
1118                 // .d=CONTENT_IGNORE and .getLight() = 0
1119                 for(u16 z=0; z<MAP_BLOCKSIZE; z++)
1120                 for(u16 y=0; y<MAP_BLOCKSIZE; y++)
1121                 for(u16 x=0; x<MAP_BLOCKSIZE; x++)
1122                 {
1123                         //UASSERT(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_AIR);
1124                         UASSERT(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_IGNORE);
1125                         UASSERT(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_DAY) == 0);
1126                         UASSERT(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_NIGHT) == 0);
1127                 }
1128                 
1129                 {
1130                         MapNode n(CONTENT_AIR);
1131                         for(u16 z=0; z<MAP_BLOCKSIZE; z++)
1132                         for(u16 y=0; y<MAP_BLOCKSIZE; y++)
1133                         for(u16 x=0; x<MAP_BLOCKSIZE; x++)
1134                         {
1135                                 b.setNode(v3s16(x,y,z), n);
1136                         }
1137                 }
1138                         
1139                 /*
1140                         Parent fetch functions
1141                 */
1142                 parent.position_valid = false;
1143                 parent.node.setContent(5);
1144
1145                 MapNode n;
1146                 
1147                 // Positions in the block should still be valid
1148                 UASSERT(b.isValidPositionParent(v3s16(0,0,0)) == true);
1149                 UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
1150                 n = b.getNodeParent(v3s16(0,MAP_BLOCKSIZE-1,0));
1151                 UASSERT(n.getContent() == CONTENT_AIR);
1152
1153                 // ...but outside the block they should be invalid
1154                 UASSERT(b.isValidPositionParent(v3s16(-121,2341,0)) == false);
1155                 UASSERT(b.isValidPositionParent(v3s16(-1,0,0)) == false);
1156                 UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == false);
1157                 
1158                 {
1159                         bool exception_thrown = false;
1160                         try{
1161                                 // This should throw an exception
1162                                 MapNode n = b.getNodeParent(v3s16(0,0,-1));
1163                         }
1164                         catch(InvalidPositionException &e)
1165                         {
1166                                 exception_thrown = true;
1167                         }
1168                         UASSERT(exception_thrown);
1169                 }
1170
1171                 parent.position_valid = true;
1172                 // Now the positions outside should be valid
1173                 UASSERT(b.isValidPositionParent(v3s16(-121,2341,0)) == true);
1174                 UASSERT(b.isValidPositionParent(v3s16(-1,0,0)) == true);
1175                 UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == true);
1176                 n = b.getNodeParent(v3s16(0,0,MAP_BLOCKSIZE));
1177                 UASSERT(n.getContent() == 5);
1178
1179                 /*
1180                         Set a node
1181                 */
1182                 v3s16 p(1,2,0);
1183                 n.setContent(4);
1184                 b.setNode(p, n);
1185                 UASSERT(b.getNode(p).getContent() == 4);
1186                 //TODO: Update to new system
1187                 /*UASSERT(b.getNodeTile(p) == 4);
1188                 UASSERT(b.getNodeTile(v3s16(-1,-1,0)) == 5);*/
1189                 
1190                 /*
1191                         propagateSunlight()
1192                 */
1193                 // Set lighting of all nodes to 0
1194                 for(u16 z=0; z<MAP_BLOCKSIZE; z++){
1195                         for(u16 y=0; y<MAP_BLOCKSIZE; y++){
1196                                 for(u16 x=0; x<MAP_BLOCKSIZE; x++){
1197                                         MapNode n = b.getNode(v3s16(x,y,z));
1198                                         n.setLight(LIGHTBANK_DAY, 0);
1199                                         n.setLight(LIGHTBANK_NIGHT, 0);
1200                                         b.setNode(v3s16(x,y,z), n);
1201                                 }
1202                         }
1203                 }
1204                 {
1205                         /*
1206                                 Check how the block handles being a lonely sky block
1207                         */
1208                         parent.position_valid = true;
1209                         b.setIsUnderground(false);
1210                         parent.node.setContent(CONTENT_AIR);
1211                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_SUN);
1212                         parent.node.setLight(LIGHTBANK_NIGHT, 0);
1213                         core::map<v3s16, bool> light_sources;
1214                         // The bottom block is invalid, because we have a shadowing node
1215                         UASSERT(b.propagateSunlight(light_sources) == false);
1216                         UASSERT(b.getNode(v3s16(1,4,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
1217                         UASSERT(b.getNode(v3s16(1,3,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
1218                         UASSERT(b.getNode(v3s16(1,2,0)).getLight(LIGHTBANK_DAY) == 0);
1219                         UASSERT(b.getNode(v3s16(1,1,0)).getLight(LIGHTBANK_DAY) == 0);
1220                         UASSERT(b.getNode(v3s16(1,0,0)).getLight(LIGHTBANK_DAY) == 0);
1221                         UASSERT(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
1222                         UASSERT(b.getFaceLight2(1000, p, v3s16(0,1,0)) == LIGHT_SUN);
1223                         UASSERT(b.getFaceLight2(1000, p, v3s16(0,-1,0)) == 0);
1224                         UASSERT(b.getFaceLight2(0, p, v3s16(0,-1,0)) == 0);
1225                         // According to MapBlock::getFaceLight,
1226                         // The face on the z+ side should have double-diminished light
1227                         //UASSERT(b.getFaceLight(p, v3s16(0,0,1)) == diminish_light(diminish_light(LIGHT_MAX)));
1228                         // The face on the z+ side should have diminished light
1229                         UASSERT(b.getFaceLight2(1000, p, v3s16(0,0,1)) == diminish_light(LIGHT_MAX));
1230                 }
1231                 /*
1232                         Check how the block handles being in between blocks with some non-sunlight
1233                         while being underground
1234                 */
1235                 {
1236                         // Make neighbours to exist and set some non-sunlight to them
1237                         parent.position_valid = true;
1238                         b.setIsUnderground(true);
1239                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2);
1240                         core::map<v3s16, bool> light_sources;
1241                         // The block below should be valid because there shouldn't be
1242                         // sunlight in there either
1243                         UASSERT(b.propagateSunlight(light_sources, true) == true);
1244                         // Should not touch nodes that are not affected (that is, all of them)
1245                         //UASSERT(b.getNode(v3s16(1,2,3)).getLight() == LIGHT_SUN);
1246                         // Should set light of non-sunlighted blocks to 0.
1247                         UASSERT(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == 0);
1248                 }
1249                 /*
1250                         Set up a situation where:
1251                         - There is only air in this block
1252                         - There is a valid non-sunlighted block at the bottom, and
1253                         - Invalid blocks elsewhere.
1254                         - the block is not underground.
1255
1256                         This should result in bottom block invalidity
1257                 */
1258                 {
1259                         b.setIsUnderground(false);
1260                         // Clear block
1261                         for(u16 z=0; z<MAP_BLOCKSIZE; z++){
1262                                 for(u16 y=0; y<MAP_BLOCKSIZE; y++){
1263                                         for(u16 x=0; x<MAP_BLOCKSIZE; x++){
1264                                                 MapNode n;
1265                                                 n.setContent(CONTENT_AIR);
1266                                                 n.setLight(LIGHTBANK_DAY, 0);
1267                                                 b.setNode(v3s16(x,y,z), n);
1268                                         }
1269                                 }
1270                         }
1271                         // Make neighbours invalid
1272                         parent.position_valid = false;
1273                         // Add exceptions to the top of the bottom block
1274                         for(u16 x=0; x<MAP_BLOCKSIZE; x++)
1275                         for(u16 z=0; z<MAP_BLOCKSIZE; z++)
1276                         {
1277                                 parent.validity_exceptions.push_back(v3s16(MAP_BLOCKSIZE+x, MAP_BLOCKSIZE-1, MAP_BLOCKSIZE+z));
1278                         }
1279                         // Lighting value for the valid nodes
1280                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2);
1281                         core::map<v3s16, bool> light_sources;
1282                         // Bottom block is not valid
1283                         UASSERT(b.propagateSunlight(light_sources) == false);
1284                 }
1285         }
1286 };
1287
1288 struct TestMapSector: public TestBase
1289 {
1290         class TC : public NodeContainer
1291         {
1292         public:
1293
1294                 MapNode node;
1295                 bool position_valid;
1296
1297                 TC()
1298                 {
1299                         position_valid = true;
1300                 }
1301
1302                 virtual bool isValidPosition(v3s16 p)
1303                 {
1304                         return position_valid;
1305                 }
1306
1307                 virtual MapNode getNode(v3s16 p)
1308                 {
1309                         if(position_valid == false)
1310                                 throw InvalidPositionException();
1311                         return node;
1312                 }
1313
1314                 virtual void setNode(v3s16 p, MapNode & n)
1315                 {
1316                         if(position_valid == false)
1317                                 throw InvalidPositionException();
1318                 };
1319                 
1320                 virtual u16 nodeContainerId() const
1321                 {
1322                         return 666;
1323                 }
1324         };
1325         
1326         void Run()
1327         {
1328                 TC parent;
1329                 parent.position_valid = false;
1330                 
1331                 // Create one with no heightmaps
1332                 ServerMapSector sector(&parent, v2s16(1,1));
1333                 
1334                 UASSERT(sector.getBlockNoCreateNoEx(0) == 0);
1335                 UASSERT(sector.getBlockNoCreateNoEx(1) == 0);
1336
1337                 MapBlock * bref = sector.createBlankBlock(-2);
1338                 
1339                 UASSERT(sector.getBlockNoCreateNoEx(0) == 0);
1340                 UASSERT(sector.getBlockNoCreateNoEx(-2) == bref);
1341                 
1342                 //TODO: Check for AlreadyExistsException
1343
1344                 /*bool exception_thrown = false;
1345                 try{
1346                         sector.getBlock(0);
1347                 }
1348                 catch(InvalidPositionException &e){
1349                         exception_thrown = true;
1350                 }
1351                 UASSERT(exception_thrown);*/
1352
1353         }
1354 };
1355 #endif
1356
1357 struct TestCollision: public TestBase
1358 {
1359         void Run()
1360         {
1361                 /*
1362                         axisAlignedCollision
1363                 */
1364
1365                 for(s16 bx = -3; bx <= 3; bx++)
1366                 for(s16 by = -3; by <= 3; by++)
1367                 for(s16 bz = -3; bz <= 3; bz++)
1368                 {
1369                         // X-
1370                         {
1371                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1372                                 aabb3f m(bx-2, by, bz, bx-1, by+1, bz+1);
1373                                 v3f v(1, 0, 0);
1374                                 f32 dtime = 0;
1375                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1376                                 UASSERT(fabs(dtime - 1.000) < 0.001);
1377                         }
1378                         {
1379                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1380                                 aabb3f m(bx-2, by, bz, bx-1, by+1, bz+1);
1381                                 v3f v(-1, 0, 0);
1382                                 f32 dtime = 0;
1383                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1);
1384                         }
1385                         {
1386                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1387                                 aabb3f m(bx-2, by+1.5, bz, bx-1, by+2.5, bz-1);
1388                                 v3f v(1, 0, 0);
1389                                 f32 dtime;
1390                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1);
1391                         }
1392                         {
1393                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1394                                 aabb3f m(bx-2, by-1.5, bz, bx-1.5, by+0.5, bz+1);
1395                                 v3f v(0.5, 0.1, 0);
1396                                 f32 dtime;
1397                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1398                                 UASSERT(fabs(dtime - 3.000) < 0.001);
1399                         }
1400                         {
1401                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1402                                 aabb3f m(bx-2, by-1.5, bz, bx-1.5, by+0.5, bz+1);
1403                                 v3f v(0.5, 0.1, 0);
1404                                 f32 dtime;
1405                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1406                                 UASSERT(fabs(dtime - 3.000) < 0.001);
1407                         }
1408
1409                         // X+
1410                         {
1411                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1412                                 aabb3f m(bx+2, by, bz, bx+3, by+1, bz+1);
1413                                 v3f v(-1, 0, 0);
1414                                 f32 dtime;
1415                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1416                                 UASSERT(fabs(dtime - 1.000) < 0.001);
1417                         }
1418                         {
1419                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1420                                 aabb3f m(bx+2, by, bz, bx+3, by+1, bz+1);
1421                                 v3f v(1, 0, 0);
1422                                 f32 dtime;
1423                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1);
1424                         }
1425                         {
1426                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1427                                 aabb3f m(bx+2, by, bz+1.5, bx+3, by+1, bz+3.5);
1428                                 v3f v(-1, 0, 0);
1429                                 f32 dtime;
1430                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1);
1431                         }
1432                         {
1433                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1434                                 aabb3f m(bx+2, by-1.5, bz, bx+2.5, by-0.5, bz+1);
1435                                 v3f v(-0.5, 0.2, 0);
1436                                 f32 dtime;
1437                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 1);  // Y, not X!
1438                                 UASSERT(fabs(dtime - 2.500) < 0.001);
1439                         }
1440                         {
1441                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1442                                 aabb3f m(bx+2, by-1.5, bz, bx+2.5, by-0.5, bz+1);
1443                                 v3f v(-0.5, 0.3, 0);
1444                                 f32 dtime;
1445                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1446                                 UASSERT(fabs(dtime - 2.000) < 0.001);
1447                         }
1448
1449                         // TODO: Y-, Y+, Z-, Z+
1450
1451                         // misc
1452                         {
1453                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1454                                 aabb3f m(bx+2.3, by+2.29, bz+2.29, bx+4.2, by+4.2, bz+4.2);
1455                                 v3f v(-1./3, -1./3, -1./3);
1456                                 f32 dtime;
1457                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1458                                 UASSERT(fabs(dtime - 0.9) < 0.001);
1459                         }
1460                         {
1461                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1462                                 aabb3f m(bx+2.29, by+2.3, bz+2.29, bx+4.2, by+4.2, bz+4.2);
1463                                 v3f v(-1./3, -1./3, -1./3);
1464                                 f32 dtime;
1465                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 1);
1466                                 UASSERT(fabs(dtime - 0.9) < 0.001);
1467                         }
1468                         {
1469                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1470                                 aabb3f m(bx+2.29, by+2.29, bz+2.3, bx+4.2, by+4.2, bz+4.2);
1471                                 v3f v(-1./3, -1./3, -1./3);
1472                                 f32 dtime;
1473                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 2);
1474                                 UASSERT(fabs(dtime - 0.9) < 0.001);
1475                         }
1476                         {
1477                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1478                                 aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.3, by-2.29, bz-2.29);
1479                                 v3f v(1./7, 1./7, 1./7);
1480                                 f32 dtime;
1481                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1482                                 UASSERT(fabs(dtime - 16.1) < 0.001);
1483                         }
1484                         {
1485                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1486                                 aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.29, by-2.3, bz-2.29);
1487                                 v3f v(1./7, 1./7, 1./7);
1488                                 f32 dtime;
1489                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 1);
1490                                 UASSERT(fabs(dtime - 16.1) < 0.001);
1491                         }
1492                         {
1493                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1494                                 aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.29, by-2.29, bz-2.3);
1495                                 v3f v(1./7, 1./7, 1./7);
1496                                 f32 dtime;
1497                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 2);
1498                                 UASSERT(fabs(dtime - 16.1) < 0.001);
1499                         }
1500                 }
1501         }
1502 };
1503
1504 struct TestSocket: public TestBase
1505 {
1506         void Run()
1507         {
1508                 const int port = 30003;
1509                 Address address(0,0,0,0, port);
1510                 Address address6((IPv6AddressBytes*) NULL, port);
1511
1512                 // IPv6 socket test
1513                 {
1514                         UDPSocket socket6(true);
1515                         socket6.Bind(address6);
1516
1517                         const char sendbuffer[] = "hello world!";
1518                         IPv6AddressBytes bytes;
1519                         bytes.bytes[15] = 1;
1520                         socket6.Send(Address(&bytes, port), sendbuffer, sizeof(sendbuffer));
1521
1522                         sleep_ms(50);
1523
1524                         char rcvbuffer[256];
1525                         memset(rcvbuffer, 0, sizeof(rcvbuffer));
1526                         Address sender;
1527                         for(;;)
1528                         {
1529                                 int bytes_read = socket6.Receive(sender, rcvbuffer, sizeof(rcvbuffer));
1530                                 if(bytes_read < 0)
1531                                         break;
1532                         }
1533                         //FIXME: This fails on some systems
1534                         UASSERT(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer))==0);
1535                         UASSERT(memcmp(sender.getAddress6().sin6_addr.s6_addr, Address(&bytes, 0).getAddress6().sin6_addr.s6_addr, 16) == 0);
1536                 }
1537
1538                 // IPv4 socket test
1539                 {
1540                         UDPSocket socket(false);
1541                         socket.Bind(address);
1542
1543                         const char sendbuffer[] = "hello world!";
1544                         socket.Send(Address(127,0,0,1,port), sendbuffer, sizeof(sendbuffer));
1545
1546                         sleep_ms(50);
1547
1548                         char rcvbuffer[256];
1549                         memset(rcvbuffer, 0, sizeof(rcvbuffer));
1550                         Address sender;
1551                         for(;;)
1552                         {
1553                                 int bytes_read = socket.Receive(sender, rcvbuffer, sizeof(rcvbuffer));
1554                                 if(bytes_read < 0)
1555                                         break;
1556                         }
1557                         //FIXME: This fails on some systems
1558                         UASSERT(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer))==0);
1559                         UASSERT(sender.getAddress().sin_addr.s_addr == Address(127,0,0,1, 0).getAddress().sin_addr.s_addr);
1560                 }
1561         }
1562 };
1563
1564 struct TestConnection: public TestBase
1565 {
1566         void TestHelpers()
1567         {
1568                 /*
1569                         Test helper functions
1570                 */
1571
1572                 // Some constants for testing
1573                 u32 proto_id = 0x12345678;
1574                 u16 peer_id = 123;
1575                 u8 channel = 2;
1576                 SharedBuffer<u8> data1(1);
1577                 data1[0] = 100;
1578                 Address a(127,0,0,1, 10);
1579                 u16 seqnum = 34352;
1580
1581                 con::BufferedPacket p1 = con::makePacket(a, data1,
1582                                 proto_id, peer_id, channel);
1583                 /*
1584                         We should now have a packet with this data:
1585                         Header:
1586                                 [0] u32 protocol_id
1587                                 [4] u16 sender_peer_id
1588                                 [6] u8 channel
1589                         Data:
1590                                 [7] u8 data1[0]
1591                 */
1592                 UASSERT(readU32(&p1.data[0]) == proto_id);
1593                 UASSERT(readU16(&p1.data[4]) == peer_id);
1594                 UASSERT(readU8(&p1.data[6]) == channel);
1595                 UASSERT(readU8(&p1.data[7]) == data1[0]);
1596                 
1597                 //infostream<<"initial data1[0]="<<((u32)data1[0]&0xff)<<std::endl;
1598
1599                 SharedBuffer<u8> p2 = con::makeReliablePacket(data1, seqnum);
1600
1601                 /*infostream<<"p2.getSize()="<<p2.getSize()<<", data1.getSize()="
1602                                 <<data1.getSize()<<std::endl;
1603                 infostream<<"readU8(&p2[3])="<<readU8(&p2[3])
1604                                 <<" p2[3]="<<((u32)p2[3]&0xff)<<std::endl;
1605                 infostream<<"data1[0]="<<((u32)data1[0]&0xff)<<std::endl;*/
1606
1607                 UASSERT(p2.getSize() == 3 + data1.getSize());
1608                 UASSERT(readU8(&p2[0]) == TYPE_RELIABLE);
1609                 UASSERT(readU16(&p2[1]) == seqnum);
1610                 UASSERT(readU8(&p2[3]) == data1[0]);
1611         }
1612
1613         struct Handler : public con::PeerHandler
1614         {
1615                 Handler(const char *a_name)
1616                 {
1617                         count = 0;
1618                         last_id = 0;
1619                         name = a_name;
1620                 }
1621                 void peerAdded(con::Peer *peer)
1622                 {
1623                         infostream<<"Handler("<<name<<")::peerAdded(): "
1624                                         "id="<<peer->id<<std::endl;
1625                         last_id = peer->id;
1626                         count++;
1627                 }
1628                 void deletingPeer(con::Peer *peer, bool timeout)
1629                 {
1630                         infostream<<"Handler("<<name<<")::deletingPeer(): "
1631                                         "id="<<peer->id
1632                                         <<", timeout="<<timeout<<std::endl;
1633                         last_id = peer->id;
1634                         count--;
1635                 }
1636
1637                 s32 count;
1638                 u16 last_id;
1639                 const char *name;
1640         };
1641
1642         void Run()
1643         {
1644                 DSTACK("TestConnection::Run");
1645
1646                 TestHelpers();
1647
1648                 /*
1649                         Test some real connections
1650
1651                         NOTE: This mostly tests the legacy interface.
1652                 */
1653
1654                 u32 proto_id = 0xad26846a;
1655
1656                 Handler hand_server("server");
1657                 Handler hand_client("client");
1658                 
1659                 infostream<<"** Creating server Connection"<<std::endl;
1660                 con::Connection server(proto_id, 512, 5.0, false, &hand_server);
1661                 Address address(0,0,0,0, 30001);
1662                 server.Serve(address);
1663                 
1664                 infostream<<"** Creating client Connection"<<std::endl;
1665                 con::Connection client(proto_id, 512, 5.0, false, &hand_client);
1666                 
1667                 UASSERT(hand_server.count == 0);
1668                 UASSERT(hand_client.count == 0);
1669                 
1670                 sleep_ms(50);
1671                 
1672                 Address server_address(127,0,0,1, 30001);
1673                 infostream<<"** running client.Connect()"<<std::endl;
1674                 client.Connect(server_address);
1675
1676                 sleep_ms(50);
1677                 
1678                 // Client should not have added client yet
1679                 UASSERT(hand_client.count == 0);
1680                 
1681                 try
1682                 {
1683                         u16 peer_id;
1684                         SharedBuffer<u8> data;
1685                         infostream<<"** running client.Receive()"<<std::endl;
1686                         u32 size = client.Receive(peer_id, data);
1687                         infostream<<"** Client received: peer_id="<<peer_id
1688                                         <<", size="<<size
1689                                         <<std::endl;
1690                 }
1691                 catch(con::NoIncomingDataException &e)
1692                 {
1693                 }
1694
1695                 // Client should have added server now
1696                 UASSERT(hand_client.count == 1);
1697                 UASSERT(hand_client.last_id == 1);
1698                 // Server should not have added client yet
1699                 UASSERT(hand_server.count == 0);
1700                 
1701                 sleep_ms(100);
1702
1703                 try
1704                 {
1705                         u16 peer_id;
1706                         SharedBuffer<u8> data;
1707                         infostream<<"** running server.Receive()"<<std::endl;
1708                         u32 size = server.Receive(peer_id, data);
1709                         infostream<<"** Server received: peer_id="<<peer_id
1710                                         <<", size="<<size
1711                                         <<std::endl;
1712                 }
1713                 catch(con::NoIncomingDataException &e)
1714                 {
1715                         // No actual data received, but the client has
1716                         // probably been connected
1717                 }
1718                 
1719                 // Client should be the same
1720                 UASSERT(hand_client.count == 1);
1721                 UASSERT(hand_client.last_id == 1);
1722                 // Server should have the client
1723                 UASSERT(hand_server.count == 1);
1724                 UASSERT(hand_server.last_id == 2);
1725                 
1726                 //sleep_ms(50);
1727
1728                 while(client.Connected() == false)
1729                 {
1730                         try
1731                         {
1732                                 u16 peer_id;
1733                                 SharedBuffer<u8> data;
1734                                 infostream<<"** running client.Receive()"<<std::endl;
1735                                 u32 size = client.Receive(peer_id, data);
1736                                 infostream<<"** Client received: peer_id="<<peer_id
1737                                                 <<", size="<<size
1738                                                 <<std::endl;
1739                         }
1740                         catch(con::NoIncomingDataException &e)
1741                         {
1742                         }
1743                         sleep_ms(50);
1744                 }
1745
1746                 sleep_ms(50);
1747                 
1748                 try
1749                 {
1750                         u16 peer_id;
1751                         SharedBuffer<u8> data;
1752                         infostream<<"** running server.Receive()"<<std::endl;
1753                         u32 size = server.Receive(peer_id, data);
1754                         infostream<<"** Server received: peer_id="<<peer_id
1755                                         <<", size="<<size
1756                                         <<std::endl;
1757                 }
1758                 catch(con::NoIncomingDataException &e)
1759                 {
1760                 }
1761 #if 1
1762                 /*
1763                         Simple send-receive test
1764                 */
1765                 {
1766                         /*u8 data[] = "Hello World!";
1767                         u32 datasize = sizeof(data);*/
1768                         SharedBuffer<u8> data = SharedBufferFromString("Hello World!");
1769
1770                         infostream<<"** running client.Send()"<<std::endl;
1771                         client.Send(PEER_ID_SERVER, 0, data, true);
1772
1773                         sleep_ms(50);
1774
1775                         u16 peer_id;
1776                         SharedBuffer<u8> recvdata;
1777                         infostream<<"** running server.Receive()"<<std::endl;
1778                         u32 size = server.Receive(peer_id, recvdata);
1779                         infostream<<"** Server received: peer_id="<<peer_id
1780                                         <<", size="<<size
1781                                         <<", data="<<*data
1782                                         <<std::endl;
1783                         UASSERT(memcmp(*data, *recvdata, data.getSize()) == 0);
1784                 }
1785 #endif
1786                 u16 peer_id_client = 2;
1787 #if 0
1788                 /*
1789                         Send consequent packets in different order
1790                         Not compatible with new Connection, thus commented out.
1791                 */
1792                 {
1793                         //u8 data1[] = "hello1";
1794                         //u8 data2[] = "hello2";
1795                         SharedBuffer<u8> data1 = SharedBufferFromString("hello1");
1796                         SharedBuffer<u8> data2 = SharedBufferFromString("Hello2");
1797
1798                         Address client_address =
1799                                         server.GetPeerAddress(peer_id_client);
1800                         
1801                         infostream<<"*** Sending packets in wrong order (2,1,2)"
1802                                         <<std::endl;
1803                         
1804                         u8 chn = 0;
1805                         con::Channel *ch = &server.getPeer(peer_id_client)->channels[chn];
1806                         u16 sn = ch->next_outgoing_seqnum;
1807                         ch->next_outgoing_seqnum = sn+1;
1808                         server.Send(peer_id_client, chn, data2, true);
1809                         ch->next_outgoing_seqnum = sn;
1810                         server.Send(peer_id_client, chn, data1, true);
1811                         ch->next_outgoing_seqnum = sn+1;
1812                         server.Send(peer_id_client, chn, data2, true);
1813
1814                         sleep_ms(50);
1815
1816                         infostream<<"*** Receiving the packets"<<std::endl;
1817
1818                         u16 peer_id;
1819                         SharedBuffer<u8> recvdata;
1820                         u32 size;
1821
1822                         infostream<<"** running client.Receive()"<<std::endl;
1823                         peer_id = 132;
1824                         size = client.Receive(peer_id, recvdata);
1825                         infostream<<"** Client received: peer_id="<<peer_id
1826                                         <<", size="<<size
1827                                         <<", data="<<*recvdata
1828                                         <<std::endl;
1829                         UASSERT(size == data1.getSize());
1830                         UASSERT(memcmp(*data1, *recvdata, data1.getSize()) == 0);
1831                         UASSERT(peer_id == PEER_ID_SERVER);
1832                         
1833                         infostream<<"** running client.Receive()"<<std::endl;
1834                         peer_id = 132;
1835                         size = client.Receive(peer_id, recvdata);
1836                         infostream<<"** Client received: peer_id="<<peer_id
1837                                         <<", size="<<size
1838                                         <<", data="<<*recvdata
1839                                         <<std::endl;
1840                         UASSERT(size == data2.getSize());
1841                         UASSERT(memcmp(*data2, *recvdata, data2.getSize()) == 0);
1842                         UASSERT(peer_id == PEER_ID_SERVER);
1843                         
1844                         bool got_exception = false;
1845                         try
1846                         {
1847                                 infostream<<"** running client.Receive()"<<std::endl;
1848                                 peer_id = 132;
1849                                 size = client.Receive(peer_id, recvdata);
1850                                 infostream<<"** Client received: peer_id="<<peer_id
1851                                                 <<", size="<<size
1852                                                 <<", data="<<*recvdata
1853                                                 <<std::endl;
1854                         }
1855                         catch(con::NoIncomingDataException &e)
1856                         {
1857                                 infostream<<"** No incoming data for client"<<std::endl;
1858                                 got_exception = true;
1859                         }
1860                         UASSERT(got_exception);
1861                 }
1862 #endif
1863 #if 0
1864                 /*
1865                         Send large amounts of packets (infinite test)
1866                         Commented out because of infinity.
1867                 */
1868                 {
1869                         infostream<<"Sending large amounts of packets (infinite test)"<<std::endl;
1870                         int sendcount = 0;
1871                         for(;;){
1872                                 int datasize = myrand_range(0,5)==0?myrand_range(100,10000):myrand_range(0,100);
1873                                 infostream<<"datasize="<<datasize<<std::endl;
1874                                 SharedBuffer<u8> data1(datasize);
1875                                 for(u16 i=0; i<datasize; i++)
1876                                         data1[i] = i/4;
1877                                 
1878                                 int sendtimes = myrand_range(1,10);
1879                                 for(int i=0; i<sendtimes; i++){
1880                                         server.Send(peer_id_client, 0, data1, true);
1881                                         sendcount++;
1882                                 }
1883                                 infostream<<"sendcount="<<sendcount<<std::endl;
1884                                 
1885                                 //int receivetimes = myrand_range(1,20);
1886                                 int receivetimes = 20;
1887                                 for(int i=0; i<receivetimes; i++){
1888                                         SharedBuffer<u8> recvdata;
1889                                         u16 peer_id = 132;
1890                                         u16 size = 0;
1891                                         bool received = false;
1892                                         try{
1893                                                 size = client.Receive(peer_id, recvdata);
1894                                                 received = true;
1895                                         }catch(con::NoIncomingDataException &e){
1896                                         }
1897                                 }
1898                         }
1899                 }
1900 #endif
1901                 /*
1902                         Send a large packet
1903                 */
1904                 {
1905                         const int datasize = 30000;
1906                         SharedBuffer<u8> data1(datasize);
1907                         for(u16 i=0; i<datasize; i++){
1908                                 data1[i] = i/4;
1909                         }
1910
1911                         infostream<<"Sending data (size="<<datasize<<"):";
1912                         for(int i=0; i<datasize && i<20; i++){
1913                                 if(i%2==0) infostream<<" ";
1914                                 char buf[10];
1915                                 snprintf(buf, 10, "%.2X", ((int)((const char*)*data1)[i])&0xff);
1916                                 infostream<<buf;
1917                         }
1918                         if(datasize>20)
1919                                 infostream<<"...";
1920                         infostream<<std::endl;
1921                         
1922                         server.Send(peer_id_client, 0, data1, true);
1923
1924                         //sleep_ms(3000);
1925                         
1926                         SharedBuffer<u8> recvdata;
1927                         infostream<<"** running client.Receive()"<<std::endl;
1928                         u16 peer_id = 132;
1929                         u16 size = 0;
1930                         bool received = false;
1931                         u32 timems0 = porting::getTimeMs();
1932                         for(;;){
1933                                 if(porting::getTimeMs() - timems0 > 5000 || received)
1934                                         break;
1935                                 try{
1936                                         size = client.Receive(peer_id, recvdata);
1937                                         received = true;
1938                                 }catch(con::NoIncomingDataException &e){
1939                                 }
1940                                 sleep_ms(10);
1941                         }
1942                         UASSERT(received);
1943                         infostream<<"** Client received: peer_id="<<peer_id
1944                                         <<", size="<<size
1945                                         <<std::endl;
1946
1947                         infostream<<"Received data (size="<<size<<"): ";
1948                         for(int i=0; i<size && i<20; i++){
1949                                 if(i%2==0) infostream<<" ";
1950                                 char buf[10];
1951                                 snprintf(buf, 10, "%.2X", ((int)(recvdata[i]))&0xff);
1952                                 infostream<<buf;
1953                         }
1954                         if(size>20)
1955                                 infostream<<"...";
1956                         infostream<<std::endl;
1957
1958                         UASSERT(memcmp(*data1, *recvdata, data1.getSize()) == 0);
1959                         UASSERT(peer_id == PEER_ID_SERVER);
1960                 }
1961                 
1962                 // Check peer handlers
1963                 UASSERT(hand_client.count == 1);
1964                 UASSERT(hand_client.last_id == 1);
1965                 UASSERT(hand_server.count == 1);
1966                 UASSERT(hand_server.last_id == 2);
1967                 
1968                 //assert(0);
1969         }
1970 };
1971
1972 #define TEST(X)\
1973 {\
1974         X x;\
1975         infostream<<"Running " #X <<std::endl;\
1976         x.Run();\
1977         tests_run++;\
1978         tests_failed += x.test_failed ? 1 : 0;\
1979 }
1980
1981 #define TESTPARAMS(X, ...)\
1982 {\
1983         X x;\
1984         infostream<<"Running " #X <<std::endl;\
1985         x.Run(__VA_ARGS__);\
1986         tests_run++;\
1987         tests_failed += x.test_failed ? 1 : 0;\
1988 }
1989
1990 void run_tests()
1991 {
1992         DSTACK(__FUNCTION_NAME);
1993
1994         int tests_run = 0;
1995         int tests_failed = 0;
1996         
1997         // Create item and node definitions
1998         IWritableItemDefManager *idef = createItemDefManager();
1999         IWritableNodeDefManager *ndef = createNodeDefManager();
2000         define_some_nodes(idef, ndef);
2001
2002         infostream<<"run_tests() started"<<std::endl;
2003         TEST(TestUtilities);
2004         TEST(TestPath);
2005         TEST(TestSettings);
2006         TEST(TestCompress);
2007         TEST(TestSerialization);
2008         TEST(TestNodedefSerialization);
2009         TESTPARAMS(TestMapNode, ndef);
2010         TESTPARAMS(TestVoxelManipulator, ndef);
2011         TESTPARAMS(TestVoxelAlgorithms, ndef);
2012         TESTPARAMS(TestInventory, idef);
2013         //TEST(TestMapBlock);
2014         //TEST(TestMapSector);
2015         TEST(TestCollision);
2016         if(INTERNET_SIMULATOR == false){
2017                 TEST(TestSocket);
2018                 dout_con<<"=== BEGIN RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl;
2019                 TEST(TestConnection);
2020                 dout_con<<"=== END RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl;
2021         }
2022
2023         delete idef;
2024         delete ndef;
2025
2026         if(tests_failed == 0){
2027                 infostream<<"run_tests(): "<<tests_failed<<" / "<<tests_run<<" tests failed."<<std::endl;
2028                 infostream<<"run_tests() passed."<<std::endl;
2029                 return;
2030         } else {
2031                 errorstream<<"run_tests(): "<<tests_failed<<" / "<<tests_run<<" tests failed."<<std::endl;
2032                 errorstream<<"run_tests() aborting."<<std::endl;
2033                 abort();
2034         }
2035 }
2036