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