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