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