aboutsummaryrefslogtreecommitdiff
path: root/src/sky.cpp
blob: b739fe1ad0cdb955b7b16d0065aebd3af072f3af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
#include "sky.h"
#include "IVideoDriver.h"
#include "ISceneManager.h"
#include "ICameraSceneNode.h"
#include "S3DVertex.h"
#include "client/tile.h"
#include "noise.h"  // easeCurve
#include "profiler.h"
#include "util/numeric.h"
#include <cmath>
#include "settings.h"
#include "camera.h"  // CameraModes


Sky::Sky(scene::ISceneNode* parent, scene::ISceneManager* mgr, s32 id,
		ITextureSource *tsrc):
		scene::ISceneNode(parent, mgr, id),
		m_visible(true),
		m_fallback_bg_color(255, 255, 255, 255),
		m_first_update(true),
		m_brightness(0.5),
		m_cloud_brightness(0.5),
		m_bgcolor_bright_f(1, 1, 1, 1),
		m_skycolor_bright_f(1, 1, 1, 1),
		m_cloudcolor_bright_f(1, 1, 1, 1)
{
	setAutomaticCulling(scene::EAC_OFF);
	m_box.MaxEdge.set(0, 0, 0);
	m_box.MinEdge.set(0, 0, 0);

	// Create material

	video::SMaterial mat;
	mat.Lighting = false;
	mat.ZBuffer = video::ECFN_NEVER;
	mat.ZWriteEnable = false;
	mat.AntiAliasing = 0;
	mat.TextureLayer[0].TextureWrapU = video::ETC_CLAMP_TO_EDGE;
	mat.TextureLayer[0].TextureWrapV = video::ETC_CLAMP_TO_EDGE;
	mat.BackfaceCulling = false;

	m_materials[0] = mat;

	m_materials[1] = mat;
	//m_materials[1].MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
	m_materials[1].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;

	m_materials[2] = mat;
	m_materials[2].setTexture(0, tsrc->getTextureForMesh("sunrisebg.png"));
	m_materials[2].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
	//m_materials[2].MaterialType = video::EMT_TRANSPARENT_ADD_COLOR;

	m_sun_texture = tsrc->isKnownSourceImage("sun.png") ?
		tsrc->getTextureForMesh("sun.png") : NULL;
	m_moon_texture = tsrc->isKnownSourceImage("moon.png") ?
		tsrc->getTextureForMesh("moon.png") : NULL;
	m_sun_tonemap = tsrc->isKnownSourceImage("sun_tonemap.png") ?
		tsrc->getTexture("sun_tonemap.png") : NULL;
	m_moon_tonemap = tsrc->isKnownSourceImage("moon_tonemap.png") ?
		tsrc->getTexture("moon_tonemap.png") : NULL;

	if (m_sun_texture) {
		m_materials[3] = mat;
		m_materials[3].setTexture(0, m_sun_texture);
		m_materials[3].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
		if (m_sun_tonemap)
			m_materials[3].Lighting = true;
	}

	if (m_moon_texture) {
		m_materials[4] = mat;
		m_materials[4].setTexture(0, m_moon_texture);
		m_materials[4].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
		if (m_moon_tonemap)
			m_materials[4].Lighting = true;
	}

	for (u32 i = 0; i < SKY_STAR_COUNT; i++) {
		m_stars[i] = v3f(
			myrand_range(-10000, 10000),
			myrand_range(-10000, 10000),
			myrand_range(-10000, 10000)
		);
		m_stars[i].normalize();
	}

	m_directional_colored_fog = g_settings->getBool("directional_colored_fog");

	m_clouds_enabled = true;
}


void Sky::OnRegisterSceneNode()
{
	if (IsVisible)
		SceneManager->registerNodeForRendering(this, scene::ESNRP_SKY_BOX);

	scene::ISceneNode::OnRegisterSceneNode();
}


void Sky::render()
{
	if (!m_visible)
		return;

	video::IVideoDriver* driver = SceneManager->getVideoDriver();
	scene::ICameraSceneNode* camera = SceneManager->getActiveCamera();

	if (!camera || !driver)
		return;
	
	ScopeProfiler sp(g_profiler, "Sky::render()", SPT_AVG);

	// Draw perspective skybox

	core::matrix4 translate(AbsoluteTransformation);
	translate.setTranslation(camera->getAbsolutePosition());

	// Draw the sky box between the near and far clip plane
	const f32 viewDistance = (camera->getNearValue() + camera->getFarValue()) * 0.5f;
	core::matrix4 scale;
	scale.setScale(core::vector3df(viewDistance, viewDistance, viewDistance));

	driver->setTransform(video::ETS_WORLD, translate * scale);

	if (m_sunlight_seen) {
		float sunsize = 0.07;
		video::SColorf suncolor_f(1, 1, 0, 1);
		suncolor_f.r = 1;
		suncolor_f.g = MYMAX(0.3, MYMIN(1.0, 0.7 + m_time_brightness * 0.5));
		suncolor_f.b = MYMAX(0.0, m_brightness * 0.95);
		video::SColorf suncolor2_f(1, 1, 1, 1);
		suncolor_f.r = 1;
		suncolor_f.g = MYMAX(0.3, MYMIN(1.0, 0.85 + m_time_brightness * 0.5));
		suncolor_f.b = MYMAX(0.0, m_brightness);

		float moonsize = 0.04;
		video::SColorf mooncolor_f(0.50, 0.57, 0.65, 1);
		video::SColorf mooncolor2_f(0.85, 0.875, 0.9, 1);
		
		float nightlength = 0.415;
		float wn = nightlength / 2;
		float wicked_time_of_day = 0;
		if (m_time_of_day > wn && m_time_of_day < 1.0 - wn)
			wicked_time_of_day = (m_time_of_day - wn) / (1.0 - wn * 2) * 0.5 + 0.25;
		else if (m_time_of_day < 0.5)
			wicked_time_of_day = m_time_of_day / wn * 0.25;
		else
			wicked_time_of_day = 1.0 - ((1.0 - m_time_of_day) / wn * 0.25);
		/*std::cerr<<"time_of_day="<<m_time_of_day<<" -> "
				<<"wicked_time_of_day="<<wicked_time_of_day<<std::endl;*/

		video::SColor suncolor = suncolor_f.toSColor();
		video::SColor suncolor2 = suncolor2_f.toSColor();
		video::SColor mooncolor = mooncolor_f.toSColor();
		video::SColor mooncolor2 = mooncolor2_f.toSColor();

		// Calculate offset normalized to the X dimension of a 512x1 px tonemap
		float offset = (1.0 - fabs(sin((m_time_of_day - 0.5) * irr::core::PI))) * 511;

		if (m_sun_tonemap) {
			u8 * texels = (u8 *)m_sun_tonemap->lock();
			video::SColor* texel = (video::SColor *)(texels + (u32)offset * 4);
			video::SColor texel_color (255, texel->getRed(),
				texel->getGreen(), texel->getBlue());
			m_sun_tonemap->unlock();
			m_materials[3].EmissiveColor = texel_color;
		}

		if (m_moon_tonemap) {
			u8 * texels = (u8 *)m_moon_tonemap->lock();
			video::SColor* texel = (video::SColor *)(texels + (u32)offset * 4);
			video::SColor texel_color (255, texel->getRed(),
				texel->getGreen(), texel->getBlue());
			m_moon_tonemap->unlock();
			m_materials[4].EmissiveColor = texel_color;
		}

		const f32 t = 1.0f;
		const f32 o = 0.0f;
		static const u16 indices[4] = {0, 1, 2, 3};
		video::S3DVertex vertices[4];
		
		driver->setMaterial(m_materials[1]);
		
		video::SColor cloudyfogcolor = m_bgcolor;
		
		// Draw far cloudy fog thing blended with skycolor
		for (u32 j = 0; j < 4; j++) {
			video::SColor c = cloudyfogcolor.getInterpolated(m_skycolor, 0.45);
			vertices[0] = video::S3DVertex(-1, 0.08, -1, 0, 0, 1, c, t, t);
			vertices[1] = video::S3DVertex( 1, 0.08, -1, 0, 0, 1, c, o, t);
			vertices[2] = video::S3DVertex( 1, 0.12, -1, 0, 0, 1, c, o, o);
			vertices[3] = video::S3DVertex(-1, 0.12, -1, 0, 0, 1, c, t, o);
			for (u32 i = 0; i < 4; i++) {
				if (j == 0)
					// Don't switch
					{}
				else if (j == 1)
					// Switch from -Z (south) to +X (east)
					vertices[i].Pos.rotateXZBy(90);
				else if (j == 2)
					// Switch from -Z (south) to -X (west)
					vertices[i].Pos.rotateXZBy(-90);
				else
					// Switch from -Z (south) to +Z (north)
					vertices[i].Pos.rotateXZBy(-180);
			}
			driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);
		}

		// Draw far cloudy fog thing
		for (u32 j = 0; j < 4; j++) {
			video::SColor c = cloudyfogcolor;
			vertices[0] = video::S3DVertex(-1, -1.0, -1, 0, 0, 1, c, t, t);
			vertices[1] = video::S3DVertex( 1, -1.0, -1, 0, 0, 1, c, o, t);
			vertices[2] = video::S3DVertex( 1, 0.08, -1, 0, 0, 1, c, o, o);
			vertices[3] = video::S3DVertex(-1, 0.08, -1, 0, 0, 1, c, t, o);
			for (u32 i = 0; i < 4; i++) {
				if (j == 0)
					// Don't switch
					{}
				else if (j == 1)
					// Switch from -Z (south) to +X (east)
					vertices[i].Pos.rotateXZBy(90);
				else if (j == 2)
					// Switch from -Z (south) to -X (west)
					vertices[i].Pos.rotateXZBy(-90);
				else
					// Switch from -Z (south) to +Z (north)
					vertices[i].Pos.rotateXZBy(-180);
			}
			driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);
		}

		// Draw bottom far cloudy fog thing
		video::SColor c = cloudyfogcolor;
		vertices[0] = video::S3DVertex(-1, -1.0, -1, 0, 1, 0, c, t, t);
		vertices[1] = video::S3DVertex( 1, -1.0, -1, 0, 1, 0, c, o, t);
		vertices[2] = video::S3DVertex( 1, -1.0, 1, 0, 1, 0, c, o, o);
		vertices[3] = video::S3DVertex(-1, -1.0, 1, 0, 1, 0, c, t, o);
		driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);

		driver->setMaterial(m_materials[2]);

		// Draw sunrise/sunset horizon glow texture (textures/base/pack/sunrisebg.png)
		{
			float mid1 = 0.25;
			float mid = wicked_time_of_day < 0.5 ? mid1 : (1.0 - mid1);
			float a_ = 1.0 - fabs(wicked_time_of_day - mid) * 35.0;
			float a = easeCurve(MYMAX(0, MYMIN(1, a_)));
			//std::cerr<<"a_="<<a_<<" a="<<a<<std::endl;
			video::SColor c(255, 255, 255, 255);
			float y = -(1.0 - a) * 0.22;
			vertices[0] = video::S3DVertex(-1, -0.05 + y, -1, 0, 0, 1, c, t, t);
			vertices[1] = video::S3DVertex( 1, -0.05 + y, -1, 0, 0, 1, c, o, t);
			vertices[2] = video::S3DVertex( 1,   0.2 + y, -1, 0, 0, 1, c, o, o);
			vertices[3] = video::S3DVertex(-1,   0.2 + y, -1, 0, 0, 1, c, t, o);
			for (u32 i = 0; i < 4; i++) {
				if (wicked_time_of_day < 0.5)
					// Switch from -Z (south) to +X (east)
					vertices[i].Pos.rotateXZBy(90);
				else
					// Switch from -Z (south) to -X (west)
					vertices[i].Pos.rotateXZBy(-90);
			}
			driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);
		}

		// Draw sun
		if (wicked_time_of_day > 0.15 && wicked_time_of_day < 0.85) {
			if (!m_sun_texture) {
				driver->setMaterial(m_materials[1]);
				float d = sunsize * 1.7;
				video::SColor c = suncolor;
				c.setAlpha(0.05 * 255);
				vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, c, t, t);
				vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, c, o, t);
				vertices[2] = video::S3DVertex( d,  d, -1, 0, 0, 1, c, o, o);
				vertices[3] = video::S3DVertex(-d,  d, -1, 0, 0, 1, c, t, o);
				for (u32 i = 0; i < 4; i++) {
					// Switch from -Z (south) to +X (east)
					vertices[i].Pos.rotateXZBy(90);
					vertices[i].Pos.rotateXYBy(wicked_time_of_day * 360 - 90);
				}
				driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);

				d = sunsize * 1.2;
				c = suncolor;
				c.setAlpha(0.15 * 255);
				vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, c, t, t);
				vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, c, o, t);
				vertices[2] = video::S3DVertex( d,  d, -1, 0, 0, 1, c, o, o);
				vertices[3] = video::S3DVertex(-d,  d, -1, 0, 0, 1, c, t, o);
				for (u32 i = 0; i < 4; i++) {
					// Switch from -Z (south) to +X (east)
					vertices[i].Pos.rotateXZBy(90);
					vertices[i].Pos.rotateXYBy(wicked_time_of_day * 360 - 90);
				}
				driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);

				d = sunsize;
				vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, suncolor, t, t);
				vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, suncolor, o, t);
				vertices[2] = video::S3DVertex( d,  d, -1, 0, 0, 1, suncolor, o, o);
				vertices[3] = video::S3DVertex(-d,  d, -1, 0, 0, 1, suncolor, t, o);
				for (u32 i = 0; i < 4; i++) {
					// Switch from -Z (south) to +X (east)
					vertices[i].Pos.rotateXZBy(90);
					vertices[i].Pos.rotateXYBy(wicked_time_of_day * 360 - 90);
				}
				driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);

				d = sunsize * 0.7;
				vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, suncolor2, t, t);
				vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, suncolor2, o, t);
				vertices[2] = video::S3DVertex( d,  d, -1, 0, 0, 1, suncolor2, o, o);
				vertices[3] = video::S3DVertex(-d,  d, -1, 0, 0, 1, suncolor2, t, o);
				for (u32 i = 0; i < 4; i++) {
					// Switch from -Z (south) to +X (east)
					vertices[i].Pos.rotateXZBy(90);
					vertices[i].Pos.rotateXYBy(wicked_time_of_day * 360 - 90);
				}
				driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);
			} else {
				driver->setMaterial(m_materials[3]);
				float d = sunsize * 1.7;
				video::SColor c;
				if (m_sun_tonemap)
					c = video::SColor (0, 0, 0, 0);
				else
					c = video::SColor (255, 255, 255, 255);
				vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, c, t, t);
				vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, c, o, t);
				vertices[2] = video::S3DVertex( d,  d, -1, 0, 0, 1, c, o, o);
				vertices[3] = video::S3DVertex(-d,  d, -1, 0, 0, 1, c, t, o);
				for(u32 i = 0; i < 4; i++) {
					// Switch from -Z (south) to +X (east)
					vertices[i].Pos.rotateXZBy(90);
					vertices[i].Pos.rotateXYBy(wicked_time_of_day * 360 - 90);
				}
				driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);
			}
		}

		// Draw moon
		if (wicked_time_of_day < 0.3 || wicked_time_of_day > 0.7) {
			if (!m_moon_texture) {
				driver->setMaterial(m_materials[1]);
				float d = moonsize * 1.9;
				video::SColor c = mooncolor;
				c.setAlpha(0.05 * 255);
				vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, c, t, t);
				vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, c, o, t);
				vertices[2] = video::S3DVertex( d,  d, -1, 0, 0, 1, c, o, o);
				vertices[3] = video::S3DVertex(-d,  d, -1, 0, 0, 1, c, t, o);
				for (u32 i = 0; i < 4; i++) {
					// Switch from -Z (south) to -X (west)
					vertices[i].Pos.rotateXZBy(-90);
					vertices[i].Pos.rotateXYBy(wicked_time_of_day * 360 - 90);
				}
				driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);
			
				d = moonsize * 1.3;
				c = mooncolor;
				c.setAlpha(0.15 * 255);
				vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, c, t, t);
				vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, c, o, t);
				vertices[2] = video::S3DVertex( d,  d, -1, 0, 0, 1, c, o, o);
				vertices[3] = video::S3DVertex(-d,  d, -1, 0, 0, 1, c, t, o);
				for (u32 i = 0; i < 4; i++) {
					// Switch from -Z (south) to -X (west)
					vertices[i].Pos.rotateXZBy(-90);
					vertices[i].Pos.rotateXYBy(wicked_time_of_day * 360 - 90);
				}
				driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);

				d = moonsize;
				vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, mooncolor, t, t);
				vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, mooncolor, o, t);
				vertices[2] = video::S3DVertex( d,  d, -1, 0, 0, 1, mooncolor, o, o);
				vertices[3] = video::S3DVertex(-d,  d, -1, 0, 0, 1, mooncolor, t, o);
				for (u32 i = 0; i < 4; i++) {
					// Switch from -Z (south) to -X (west)
					vertices[i].Pos.rotateXZBy(-90);
					vertices[i].Pos.rotateXYBy(wicked_time_of_day * 360 - 90);
				}
				driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);

				float d2 = moonsize * 0.6;
				vertices[0] = video::S3DVertex(-d, -d,  -1, 0, 0, 1, mooncolor2, t, t);
				vertices[1] = video::S3DVertex( d2,-d,  -1, 0, 0, 1, mooncolor2, o, t);
				vertices[2] = video::S3DVertex( d2, d2, -1, 0, 0, 1, mooncolor2, o, o);
				vertices[3] = video::S3DVertex(-d,  d2, -1, 0, 0, 1, mooncolor2, t, o);
				for (u32 i = 0; i < 4; i++) {
					// Switch from -Z (south) to -X (west)
					vertices[i].Pos.rotateXZBy(-90);
					vertices[i].Pos.rotateXYBy(wicked_time_of_day * 360 - 90);
				}
				driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);
			} else {
				driver->setMaterial(m_materials[4]);
				float d = moonsize * 1.9;
				video::SColor c;
				if (m_moon_tonemap)
					c = video::SColor (0, 0, 0, 0);
				else
					c = video::SColor (255, 255, 255, 255);
				vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, c, t, t);
				vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, c, o, t);
				vertices[2] = video::S3DVertex( d,  d, -1, 0, 0, 1, c, o, o);
				vertices[3] = video::S3DVertex(-d,  d, -1, 0, 0, 1, c, t, o);
				for (u32 i = 0; i < 4; i++) {
					// Switch from -Z (south) to -X (west)
					vertices[i].Pos.rotateXZBy(-90);
					vertices[i].Pos.rotateXYBy(wicked_time_of_day * 360 - 90);
				}
				driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);
			}
		}

		// Draw stars
		driver->setMaterial(m_materials[1]);
		do {
			float starbrightness = MYMAX(0, MYMIN(1,
				(0.285 - fabs(wicked_time_of_day < 0.5 ?
				wicked_time_of_day : (1.0 - wicked_time_of_day))) * 10));
			float f = starbrightness;
			float d = 0.007;
			video::SColor starcolor(255, f * 90, f * 90, f * 90);
			if (starcolor.getBlue() < m_skycolor.getBlue())
				break;
			u16 indices[SKY_STAR_COUNT * 4];
			video::S3DVertex vertices[SKY_STAR_COUNT * 4];
			for (u32 i = 0; i < SKY_STAR_COUNT; i++) {
				indices[i * 4 + 0] = i * 4 + 0;
				indices[i * 4 + 1] = i * 4 + 1;
				indices[i * 4 + 2] = i * 4 + 2;
				indices[i * 4 + 3] = i * 4 + 3;
				v3f p = m_stars[i];
				core::CMatrix4<f32> a;
				a.buildRotateFromTo(v3f(0, 1, 0), v3f(d, 1 + d / 2, 0));
				v3f p1 = p;
				a.rotateVect(p1);
				a.buildRotateFromTo(v3f(0, 1, 0), v3f(d, 1, d));
				v3f p2 = p;
				a.rotateVect(p2);
				a.buildRotateFromTo(v3f(0, 1, 0), v3f(0, 1 - d / 2, d));
				v3f p3 = p;
				a.rotateVect(p3);
				p.rotateXYBy(wicked_time_of_day * 360 - 90);
				p1.rotateXYBy(wicked_time_of_day * 360 - 90);
				p2.rotateXYBy(wicked_time_of_day * 360 - 90);
				p3.rotateXYBy(wicked_time_of_day * 360 - 90);
				vertices[i * 4 + 0].Pos = p;
				vertices[i * 4 + 0].Color = starcolor;
				vertices[i * 4 + 1].Pos = p1;
				vertices[i * 4 + 1].Color = starcolor;
				vertices[i * 4 + 2].Pos = p2;
				vertices[i * 4 + 2].Color = starcolor;
				vertices[i * 4 + 3].Pos = p3;
				vertices[i * 4 + 3].Color = starcolor;
			}
			driver->drawVertexPrimitiveList(vertices, SKY_STAR_COUNT * 4,
				indices, SKY_STAR_COUNT, video::EVT_STANDARD,
				scene::EPT_QUADS, video::EIT_16BIT);
		} while(0);
		
		// Draw far cloudy fog thing below east and west horizons
		for (u32 j = 0; j < 2; j++) {
			video::SColor c = cloudyfogcolor;
			vertices[0] = video::S3DVertex(-1, -1.0,  -1, 0, 0, 1, c, t, t);
			vertices[1] = video::S3DVertex( 1, -1.0,  -1, 0, 0, 1, c, o, t);
			vertices[2] = video::S3DVertex( 1, -0.02, -1, 0, 0, 1, c, o, o);
			vertices[3] = video::S3DVertex(-1, -0.02, -1, 0, 0, 1, c, t, o);
			for (u32 i = 0; i < 4; i++) {
				//if (wicked_time_of_day < 0.5)
				if (j == 0)
					// Switch from -Z (south) to +X (east)
					vertices[i].Pos.rotateXZBy(90);
				else
					// Switch from -Z (south) to -X (west)
					vertices[i].Pos.rotateXZBy(-90);
			}
			driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);
		}
	}
}


void Sky::update(float time_of_day, float time_brightness,
		float direct_brightness, bool sunlight_seen,
		CameraMode cam_mode, float yaw, float pitch)
{
	// Stabilize initial brightness and color values by flooding updates
	if (m_first_update) {
		/*dstream<<"First update with time_of_day="<<time_of_day
				<<" time_brightness="<<time_brightness
				<<" direct_brightness="<<direct_brightness
				<<" sunlight_seen="<<sunlight_seen<<std::endl;*/
		m_first_update = false;
		for (u32 i = 0; i < 100; i++) {
			update(time_of_day, time_brightness, direct_brightness,
				sunlight_seen, cam_mode, yaw, pitch);
		}
		return;
	}

	m_time_of_day = time_of_day;
	m_time_brightness = time_brightness;
	m_sunlight_seen = sunlight_seen;
	
	bool is_dawn = (time_brightness >= 0.20 && time_brightness < 0.35);

	/*
	Development colours

	video::SColorf bgcolor_bright_normal_f(170. / 255, 200. / 255, 230. / 255, 1.0);
	video::SColorf bgcolor_bright_dawn_f(0.666, 200. / 255 * 0.7, 230. / 255 * 0.5, 1.0);
	video::SColorf bgcolor_bright_dawn_f(0.666, 0.549, 0.220, 1.0);
	video::SColorf bgcolor_bright_dawn_f(0.666 * 1.2, 0.549 * 1.0, 0.220 * 1.0, 1.0);
	video::SColorf bgcolor_bright_dawn_f(0.666 * 1.2, 0.549 * 1.0, 0.220 * 1.2, 1.0);

	video::SColorf cloudcolor_bright_dawn_f(1.0, 0.591, 0.4);
	video::SColorf cloudcolor_bright_dawn_f(1.0, 0.65, 0.44);
	video::SColorf cloudcolor_bright_dawn_f(1.0, 0.7, 0.5);
	*/

	video::SColorf bgcolor_bright_normal_f = video::SColor(255, 155, 193, 240);
	video::SColorf bgcolor_bright_indoor_f = video::SColor(255, 100, 100, 100);
	video::SColorf bgcolor_bright_dawn_f = video::SColor(255, 186, 193, 240);
	video::SColorf bgcolor_bright_night_f = video::SColor(255, 64, 144, 255);

	video::SColorf skycolor_bright_normal_f = video::SColor(255, 140, 186, 250);
	video::SColorf skycolor_bright_dawn_f = video::SColor(255, 180, 186, 250);
	video::SColorf skycolor_bright_night_f = video::SColor(255, 0, 107, 255);
	
	// pure white: becomes "diffuse light component" for clouds
	video::SColorf cloudcolor_bright_normal_f = video::SColor(255, 255, 255, 255);
	// dawn-factoring version of pure white (note: R is above 1.0)
	video::SColorf cloudcolor_bright_dawn_f(255.0f/240.0f, 223.0f/240.0f, 191.0f/255.0f);

	float cloud_color_change_fraction = 0.95;
	if (sunlight_seen) {
		if (fabs(time_brightness - m_brightness) < 0.2) {
			m_brightness = m_brightness * 0.95 + time_brightness * 0.05;
		} else {
			m_brightness = m_brightness * 0.80 + time_brightness * 0.20;
			cloud_color_change_fraction = 0.0;
		}
	} else {
		if (direct_brightness < m_brightness)
			m_brightness = m_brightness * 0.95 + direct_brightness * 0.05;
		else
			m_brightness = m_brightness * 0.98 + direct_brightness * 0.02;
	}
	
	m_clouds_visible = true;
	float color_change_fraction = 0.98;
	if (sunlight_seen) {
		if (is_dawn) {  // Dawn
			m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated(
				bgcolor_bright_dawn_f, color_change_fraction);
			m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated(
				skycolor_bright_dawn_f, color_change_fraction);
			m_cloudcolor_bright_f = m_cloudcolor_bright_f.getInterpolated(
				cloudcolor_bright_dawn_f, color_change_fraction);
		} else {
			if (time_brightness < 0.07) {  // Night
				m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated(
					bgcolor_bright_night_f, color_change_fraction);
				m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated(
					skycolor_bright_night_f, color_change_fraction);
			} else {  // Day
				m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated(
					bgcolor_bright_normal_f, color_change_fraction);
				m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated(
					skycolor_bright_normal_f, color_change_fraction);
			}

			m_cloudcolor_bright_f = m_cloudcolor_bright_f.getInterpolated(
				cloudcolor_bright_normal_f, color_change_fraction);
		}
	} else {
		m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated(
			bgcolor_bright_indoor_f, color_change_fraction);
		m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated(
			bgcolor_bright_indoor_f, color_change_fraction);
		m_cloudcolor_bright_f = m_cloudcolor_bright_f.getInterpolated(
			cloudcolor_bright_normal_f, color_change_fraction);
		m_clouds_visible = false;
	}

	video::SColor bgcolor_bright = m_bgcolor_bright_f.toSColor();
	m_bgcolor = video::SColor(
		255,
		bgcolor_bright.getRed() * m_brightness,
		bgcolor_bright.getGreen() * m_brightness,
		bgcolor_bright.getBlue() * m_brightness
	);

	video::SColor skycolor_bright = m_skycolor_bright_f.toSColor();
	m_skycolor = video::SColor(
		255,
		skycolor_bright.getRed() * m_brightness,
		skycolor_bright.getGreen() * m_brightness,
		skycolor_bright.getBlue() * m_brightness
	);

	// Horizon coloring based on sun and moon direction during sunset and sunrise
	video::SColor pointcolor = video::SColor(m_bgcolor.getAlpha(), 255, 255, 255);
	if (m_directional_colored_fog) {
		if (m_horizon_blend() != 0) {
			// Calculate hemisphere value from yaw, (inverted in third person front view)
			s8 dir_factor = 1;
			if (cam_mode > CAMERA_MODE_THIRD)
				dir_factor = -1;
			f32 pointcolor_blend = wrapDegrees_0_360(yaw * dir_factor + 90);
			if (pointcolor_blend > 180)
				pointcolor_blend = 360 - pointcolor_blend;
			pointcolor_blend /= 180;
			// Bound view angle to determine where transition starts and ends
			pointcolor_blend = rangelim(1 - pointcolor_blend * 1.375, 0, 1 / 1.375) *
				1.375;
			// Combine the colors when looking up or down, otherwise turning looks weird
			pointcolor_blend += (0.5 - pointcolor_blend) *
				(1 - MYMIN((90 - std::fabs(pitch)) / 90 * 1.5, 1));
			// Invert direction to match where the sun and moon are rising
			if (m_time_of_day > 0.5)
				pointcolor_blend = 1 - pointcolor_blend;
			// Horizon colors of sun and moon
			f32 pointcolor_light = rangelim(m_time_brightness * 3, 0.2, 1);

			video::SColorf pointcolor_sun_f(1, 1, 1, 1);
			if (m_sun_tonemap) {
				pointcolor_sun_f.r = pointcolor_light *
					(float)m_materials[3].EmissiveColor.getRed() / 255;
				pointcolor_sun_f.b = pointcolor_light *
					(float)m_materials[3].EmissiveColor.getBlue() / 255;
				pointcolor_sun_f.g = pointcolor_light *
					(float)m_materials[3].EmissiveColor.getGreen() / 255;
			} else {
				pointcolor_sun_f.r = pointcolor_light * 1;
				pointcolor_sun_f.b = pointcolor_light *
					(0.25 + (rangelim(m_time_brightness, 0.25, 0.75) - 0.25) * 2 * 0.75);
				pointcolor_sun_f.g = pointcolor_light * (pointcolor_sun_f.b * 0.375 +
					(rangelim(m_time_brightness, 0.05, 0.15) - 0.05) * 10 * 0.625);
			}

			video::SColorf pointcolor_moon_f(0.5 * pointcolor_light,
				0.6 * pointcolor_light, 0.8 * pointcolor_light, 1);
			if (m_moon_tonemap) {
				pointcolor_moon_f.r = pointcolor_light *
					(float)m_materials[4].EmissiveColor.getRed() / 255;
				pointcolor_moon_f.b = pointcolor_light *
					(float)m_materials[4].EmissiveColor.getBlue() / 255;
				pointcolor_moon_f.g = pointcolor_light *
					(float)m_materials[4].EmissiveColor.getGreen() / 255;
			}

			video::SColor pointcolor_sun = pointcolor_sun_f.toSColor();
			video::SColor pointcolor_moon = pointcolor_moon_f.toSColor();
			// Calculate the blend color
			pointcolor = m_mix_scolor(pointcolor_moon, pointcolor_sun, pointcolor_blend);
		}
		m_bgcolor = m_mix_scolor(m_bgcolor, pointcolor, m_horizon_blend() * 0.5);
		m_skycolor = m_mix_scolor(m_skycolor, pointcolor, m_horizon_blend() * 0.25);
	}

	float cloud_direct_brightness = 0;
	if (sunlight_seen) {
		if (!m_directional_colored_fog) {
			cloud_direct_brightness = time_brightness;
			if (time_brightness >= 0.2 && time_brightness < 0.7)
				cloud_direct_brightness *= 1.3;
		} else {
			cloud_direct_brightness = MYMIN(m_horizon_blend() * 0.15 +
				m_time_brightness, 1);
		}
	} else {
		cloud_direct_brightness = direct_brightness;
	}

	m_cloud_brightness = m_cloud_brightness * cloud_color_change_fraction +
		cloud_direct_brightness * (1.0 - cloud_color_change_fraction);
	m_cloudcolor_f = video::SColorf(
		m_cloudcolor_bright_f.r * m_cloud_brightness,
		m_cloudcolor_bright_f.g * m_cloud_brightness,
		m_cloudcolor_bright_f.b * m_cloud_brightness,
		1.0
	);
	if (m_directional_colored_fog) {
		m_cloudcolor_f = m_mix_scolorf(m_cloudcolor_f,
			video::SColorf(pointcolor), m_horizon_blend() * 0.25);
	}
}
/span> verbosestream<<"Test ContentFeatures size: "<<os.str().size()<<std::endl; std::istringstream is(os.str(), std::ios::binary); ContentFeatures f2; f2.deSerialize(is); UASSERT(f.walkable == f2.walkable); UASSERT(f.node_box.type == f2.node_box.type); } }; struct TestCompress: public TestBase { void Run() { { // ver 0 SharedBuffer<u8> fromdata(4); fromdata[0]=1; fromdata[1]=5; fromdata[2]=5; fromdata[3]=1; std::ostringstream os(std::ios_base::binary); compress(fromdata, os, 0); std::string str_out = os.str(); infostream<<"str_out.size()="<<str_out.size()<<std::endl; infostream<<"TestCompress: 1,5,5,1 -> "; for(u32 i=0; i<str_out.size(); i++) { infostream<<(u32)str_out[i]<<","; } infostream<<std::endl; UASSERT(str_out.size() == 10); UASSERT(str_out[0] == 0); UASSERT(str_out[1] == 0); UASSERT(str_out[2] == 0); UASSERT(str_out[3] == 4); UASSERT(str_out[4] == 0); UASSERT(str_out[5] == 1); UASSERT(str_out[6] == 1); UASSERT(str_out[7] == 5); UASSERT(str_out[8] == 0); UASSERT(str_out[9] == 1); std::istringstream is(str_out, std::ios_base::binary); std::ostringstream os2(std::ios_base::binary); decompress(is, os2, 0); std::string str_out2 = os2.str(); infostream<<"decompress: "; for(u32 i=0; i<str_out2.size(); i++) { infostream<<(u32)str_out2[i]<<","; } infostream<<std::endl; UASSERT(str_out2.size() == fromdata.getSize()); for(u32 i=0; i<str_out2.size(); i++) { UASSERT(str_out2[i] == fromdata[i]); } } { // ver HIGHEST SharedBuffer<u8> fromdata(4); fromdata[0]=1; fromdata[1]=5; fromdata[2]=5; fromdata[3]=1; std::ostringstream os(std::ios_base::binary); compress(fromdata, os, SER_FMT_VER_HIGHEST_READ); std::string str_out = os.str(); infostream<<"str_out.size()="<<str_out.size()<<std::endl; infostream<<"TestCompress: 1,5,5,1 -> "; for(u32 i=0; i<str_out.size(); i++) { infostream<<(u32)str_out[i]<<","; } infostream<<std::endl; std::istringstream is(str_out, std::ios_base::binary); std::ostringstream os2(std::ios_base::binary); decompress(is, os2, SER_FMT_VER_HIGHEST_READ); std::string str_out2 = os2.str(); infostream<<"decompress: "; for(u32 i=0; i<str_out2.size(); i++) { infostream<<(u32)str_out2[i]<<","; } infostream<<std::endl; UASSERT(str_out2.size() == fromdata.getSize()); for(u32 i=0; i<str_out2.size(); i++) { UASSERT(str_out2[i] == fromdata[i]); } } // Test zlib wrapper with large amounts of data (larger than its // internal buffers) { infostream<<"Test: Testing zlib wrappers with a large amount " <<"of pseudorandom data"<<std::endl; u32 size = 50000; infostream<<"Test: Input size of large compressZlib is " <<size<<std::endl; std::string data_in; data_in.resize(size); PseudoRandom pseudorandom(9420); for(u32 i=0; i<size; i++) data_in[i] = pseudorandom.range(0,255); std::ostringstream os_compressed(std::ios::binary); compressZlib(data_in, os_compressed); infostream<<"Test: Output size of large compressZlib is " <<os_compressed.str().size()<<std::endl; std::istringstream is_compressed(os_compressed.str(), std::ios::binary); std::ostringstream os_decompressed(std::ios::binary); decompressZlib(is_compressed, os_decompressed); infostream<<"Test: Output size of large decompressZlib is " <<os_decompressed.str().size()<<std::endl; std::string str_decompressed = os_decompressed.str(); UTEST(str_decompressed.size() == data_in.size(), "Output size not" " equal (output: %u, input: %u)", (unsigned int)str_decompressed.size(), (unsigned int)data_in.size()); for(u32 i=0; i<size && i<str_decompressed.size(); i++){ UTEST(str_decompressed[i] == data_in[i], "index out[%i]=%i differs from in[%i]=%i", i, str_decompressed[i], i, data_in[i]); } } } }; struct TestMapNode: public TestBase { void Run(INodeDefManager *nodedef) { MapNode n; // Default values UASSERT(n.getContent() == CONTENT_AIR); UASSERT(n.getLight(LIGHTBANK_DAY, nodedef) == 0); UASSERT(n.getLight(LIGHTBANK_NIGHT, nodedef) == 0); // Transparency n.setContent(CONTENT_AIR); UASSERT(nodedef->get(n).light_propagates == true); n.setContent(LEGN(nodedef, "CONTENT_STONE")); UASSERT(nodedef->get(n).light_propagates == false); } }; struct TestVoxelManipulator: public TestBase { void Run(INodeDefManager *nodedef) { /* VoxelArea */ VoxelArea a(v3s16(-1,-1,-1), v3s16(1,1,1)); UASSERT(a.index(0,0,0) == 1*3*3 + 1*3 + 1); UASSERT(a.index(-1,-1,-1) == 0); VoxelArea c(v3s16(-2,-2,-2), v3s16(2,2,2)); // An area that is 1 bigger in x+ and z- VoxelArea d(v3s16(-2,-2,-3), v3s16(3,2,2)); std::list<VoxelArea> aa; d.diff(c, aa); // Correct results std::vector<VoxelArea> results; results.push_back(VoxelArea(v3s16(-2,-2,-3),v3s16(3,2,-3))); results.push_back(VoxelArea(v3s16(3,-2,-2),v3s16(3,2,2))); UASSERT(aa.size() == results.size()); infostream<<"Result of diff:"<<std::endl; for(std::list<VoxelArea>::const_iterator i = aa.begin(); i != aa.end(); ++i) { i->print(infostream); infostream<<std::endl; std::vector<VoxelArea>::iterator j = std::find(results.begin(), results.end(), *i); UASSERT(j != results.end()); results.erase(j); } /* VoxelManipulator */ VoxelManipulator v; v.print(infostream, nodedef); infostream<<"*** Setting (-1,0,-1)=2 ***"<<std::endl; v.setNodeNoRef(v3s16(-1,0,-1), MapNode(CONTENT_GRASS)); v.print(infostream, nodedef); UASSERT(v.getNode(v3s16(-1,0,-1)).getContent() == CONTENT_GRASS); infostream<<"*** Reading from inexistent (0,0,-1) ***"<<std::endl; EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,0,-1))); v.print(infostream, nodedef); infostream<<"*** Adding area ***"<<std::endl; v.addArea(a); v.print(infostream, nodedef); UASSERT(v.getNode(v3s16(-1,0,-1)).getContent() == CONTENT_GRASS); EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,1,1))); } }; struct TestVoxelAlgorithms: public TestBase { void Run(INodeDefManager *ndef) { /* voxalgo::propagateSunlight */ { VoxelManipulator v; for(u16 z=0; z<3; z++) for(u16 y=0; y<3; y++) for(u16 x=0; x<3; x++) { v3s16 p(x,y,z); v.setNodeNoRef(p, MapNode(CONTENT_AIR)); } VoxelArea a(v3s16(0,0,0), v3s16(2,2,2)); { std::set<v3s16> light_sources; voxalgo::setLight(v, a, 0, ndef); voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight( v, a, true, light_sources, ndef); //v.print(dstream, ndef, VOXELPRINT_LIGHT_DAY); UASSERT(res.bottom_sunlight_valid == true); UASSERT(v.getNode(v3s16(1,1,1)).getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN); } v.setNodeNoRef(v3s16(0,0,0), MapNode(CONTENT_STONE)); { std::set<v3s16> light_sources; voxalgo::setLight(v, a, 0, ndef); voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight( v, a, true, light_sources, ndef); UASSERT(res.bottom_sunlight_valid == true); UASSERT(v.getNode(v3s16(1,1,1)).getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN); } { std::set<v3s16> light_sources; voxalgo::setLight(v, a, 0, ndef); voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight( v, a, false, light_sources, ndef); UASSERT(res.bottom_sunlight_valid == true); UASSERT(v.getNode(v3s16(2,0,2)).getLight(LIGHTBANK_DAY, ndef) == 0); } v.setNodeNoRef(v3s16(1,3,2), MapNode(CONTENT_STONE)); { std::set<v3s16> light_sources; voxalgo::setLight(v, a, 0, ndef); voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight( v, a, true, light_sources, ndef); UASSERT(res.bottom_sunlight_valid == true); UASSERT(v.getNode(v3s16(1,1,2)).getLight(LIGHTBANK_DAY, ndef) == 0); } { std::set<v3s16> light_sources; voxalgo::setLight(v, a, 0, ndef); voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight( v, a, false, light_sources, ndef); UASSERT(res.bottom_sunlight_valid == true); UASSERT(v.getNode(v3s16(1,0,2)).getLight(LIGHTBANK_DAY, ndef) == 0); } { MapNode n(CONTENT_AIR); n.setLight(LIGHTBANK_DAY, 10, ndef); v.setNodeNoRef(v3s16(1,-1,2), n); } { std::set<v3s16> light_sources; voxalgo::setLight(v, a, 0, ndef); voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight( v, a, true, light_sources, ndef); UASSERT(res.bottom_sunlight_valid == true); } { std::set<v3s16> light_sources; voxalgo::setLight(v, a, 0, ndef); voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight( v, a, false, light_sources, ndef); UASSERT(res.bottom_sunlight_valid == true); } { MapNode n(CONTENT_AIR); n.setLight(LIGHTBANK_DAY, LIGHT_SUN, ndef); v.setNodeNoRef(v3s16(1,-1,2), n); } { std::set<v3s16> light_sources; voxalgo::setLight(v, a, 0, ndef); voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight( v, a, true, light_sources, ndef); UASSERT(res.bottom_sunlight_valid == false); } { std::set<v3s16> light_sources; voxalgo::setLight(v, a, 0, ndef); voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight( v, a, false, light_sources, ndef); UASSERT(res.bottom_sunlight_valid == false); } v.setNodeNoRef(v3s16(1,3,2), MapNode(CONTENT_IGNORE)); { std::set<v3s16> light_sources; voxalgo::setLight(v, a, 0, ndef); voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight( v, a, true, light_sources, ndef); UASSERT(res.bottom_sunlight_valid == true); } } /* voxalgo::clearLightAndCollectSources */ { VoxelManipulator v; for(u16 z=0; z<3; z++) for(u16 y=0; y<3; y++) for(u16 x=0; x<3; x++) { v3s16 p(x,y,z); v.setNode(p, MapNode(CONTENT_AIR)); } VoxelArea a(v3s16(0,0,0), v3s16(2,2,2)); v.setNodeNoRef(v3s16(0,0,0), MapNode(CONTENT_STONE)); v.setNodeNoRef(v3s16(1,1,1), MapNode(CONTENT_TORCH)); { MapNode n(CONTENT_AIR); n.setLight(LIGHTBANK_DAY, 1, ndef); v.setNode(v3s16(1,1,2), n); } { std::set<v3s16> light_sources; std::map<v3s16, u8> unlight_from; voxalgo::clearLightAndCollectSources(v, a, LIGHTBANK_DAY, ndef, light_sources, unlight_from); //v.print(dstream, ndef, VOXELPRINT_LIGHT_DAY); UASSERT(v.getNode(v3s16(0,1,1)).getLight(LIGHTBANK_DAY, ndef) == 0); UASSERT(light_sources.find(v3s16(1,1,1)) != light_sources.end()); UASSERT(light_sources.size() == 1); UASSERT(unlight_from.find(v3s16(1,1,2)) != unlight_from.end()); UASSERT(unlight_from.size() == 1); } } } }; struct TestInventory: public TestBase { void Run(IItemDefManager *idef) { std::string serialized_inventory = "List 0 32\n" "Width 3\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Item default:cobble 61\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Item default:dirt 71\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Item default:dirt 99\n" "Item default:cobble 38\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "EndInventoryList\n" "EndInventory\n"; std::string serialized_inventory_2 = "List main 32\n" "Width 5\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Item default:cobble 61\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Item default:dirt 71\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Item default:dirt 99\n" "Item default:cobble 38\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "EndInventoryList\n" "EndInventory\n"; Inventory inv(idef); std::istringstream is(serialized_inventory, std::ios::binary); inv.deSerialize(is); UASSERT(inv.getList("0")); UASSERT(!inv.getList("main")); inv.getList("0")->setName("main"); UASSERT(!inv.getList("0")); UASSERT(inv.getList("main")); UASSERT(inv.getList("main")->getWidth() == 3); inv.getList("main")->setWidth(5); std::ostringstream inv_os(std::ios::binary); inv.serialize(inv_os); UASSERT(inv_os.str() == serialized_inventory_2); } }; /* NOTE: These tests became non-working then NodeContainer was removed. These should be redone, utilizing some kind of a virtual interface for Map (IMap would be fine). */ #if 0 struct TestMapBlock: public TestBase { class TC : public NodeContainer { public: MapNode node; bool position_valid; core::list<v3s16> validity_exceptions; TC() { position_valid = true; } virtual bool isValidPosition(v3s16 p) { //return position_valid ^ (p==position_valid_exception); bool exception = false; for(core::list<v3s16>::Iterator i=validity_exceptions.begin(); i != validity_exceptions.end(); i++) { if(p == *i) { exception = true; break; } } return exception ? !position_valid : position_valid; } virtual MapNode getNode(v3s16 p) { if(isValidPosition(p) == false) throw InvalidPositionException(); return node; } virtual void setNode(v3s16 p, MapNode & n) { if(isValidPosition(p) == false) throw InvalidPositionException(); }; virtual u16 nodeContainerId() const { return 666; } }; void Run() { TC parent; MapBlock b(&parent, v3s16(1,1,1)); v3s16 relpos(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE); UASSERT(b.getPosRelative() == relpos); UASSERT(b.getBox().MinEdge.X == MAP_BLOCKSIZE); UASSERT(b.getBox().MaxEdge.X == MAP_BLOCKSIZE*2-1); UASSERT(b.getBox().MinEdge.Y == MAP_BLOCKSIZE); UASSERT(b.getBox().MaxEdge.Y == MAP_BLOCKSIZE*2-1); UASSERT(b.getBox().MinEdge.Z == MAP_BLOCKSIZE); UASSERT(b.getBox().MaxEdge.Z == MAP_BLOCKSIZE*2-1); UASSERT(b.isValidPosition(v3s16(0,0,0)) == true); UASSERT(b.isValidPosition(v3s16(-1,0,0)) == false); UASSERT(b.isValidPosition(v3s16(-1,-142,-2341)) == false); UASSERT(b.isValidPosition(v3s16(-124,142,2341)) == false); UASSERT(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true); UASSERT(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE,MAP_BLOCKSIZE-1)) == false); /* TODO: this method should probably be removed if the block size isn't going to be set variable */ /*UASSERT(b.getSizeNodes() == v3s16(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE));*/ // Changed flag should be initially set UASSERT(b.getModified() == MOD_STATE_WRITE_NEEDED); b.resetModified(); UASSERT(b.getModified() == MOD_STATE_CLEAN); // All nodes should have been set to // .d=CONTENT_IGNORE and .getLight() = 0 for(u16 z=0; z<MAP_BLOCKSIZE; z++) for(u16 y=0; y<MAP_BLOCKSIZE; y++) for(u16 x=0; x<MAP_BLOCKSIZE; x++) { //UASSERT(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_AIR); UASSERT(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_IGNORE); UASSERT(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_DAY) == 0); UASSERT(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_NIGHT) == 0); } { MapNode n(CONTENT_AIR); for(u16 z=0; z<MAP_BLOCKSIZE; z++) for(u16 y=0; y<MAP_BLOCKSIZE; y++) for(u16 x=0; x<MAP_BLOCKSIZE; x++) { b.setNode(v3s16(x,y,z), n); } } /* Parent fetch functions */ parent.position_valid = false; parent.node.setContent(5); MapNode n; // Positions in the block should still be valid UASSERT(b.isValidPositionParent(v3s16(0,0,0)) == true); UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true); n = b.getNodeParent(v3s16(0,MAP_BLOCKSIZE-1,0)); UASSERT(n.getContent() == CONTENT_AIR); // ...but outside the block they should be invalid UASSERT(b.isValidPositionParent(v3s16(-121,2341,0)) == false); UASSERT(b.isValidPositionParent(v3s16(-1,0,0)) == false); UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == false); { bool exception_thrown = false; try{ // This should throw an exception MapNode n = b.getNodeParent(v3s16(0,0,-1)); } catch(InvalidPositionException &e) { exception_thrown = true; } UASSERT(exception_thrown); } parent.position_valid = true; // Now the positions outside should be valid UASSERT(b.isValidPositionParent(v3s16(-121,2341,0)) == true); UASSERT(b.isValidPositionParent(v3s16(-1,0,0)) == true); UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == true); n = b.getNodeParent(v3s16(0,0,MAP_BLOCKSIZE)); UASSERT(n.getContent() == 5); /* Set a node */ v3s16 p(1,2,0); n.setContent(4); b.setNode(p, n); UASSERT(b.getNode(p).getContent() == 4); //TODO: Update to new system /*UASSERT(b.getNodeTile(p) == 4); UASSERT(b.getNodeTile(v3s16(-1,-1,0)) == 5);*/ /* propagateSunlight() */ // Set lighting of all nodes to 0 for(u16 z=0; z<MAP_BLOCKSIZE; z++){ for(u16 y=0; y<MAP_BLOCKSIZE; y++){ for(u16 x=0; x<MAP_BLOCKSIZE; x++){ MapNode n = b.getNode(v3s16(x,y,z)); n.setLight(LIGHTBANK_DAY, 0); n.setLight(LIGHTBANK_NIGHT, 0); b.setNode(v3s16(x,y,z), n); } } } { /* Check how the block handles being a lonely sky block */ parent.position_valid = true; b.setIsUnderground(false); parent.node.setContent(CONTENT_AIR); parent.node.setLight(LIGHTBANK_DAY, LIGHT_SUN); parent.node.setLight(LIGHTBANK_NIGHT, 0); core::map<v3s16, bool> light_sources; // The bottom block is invalid, because we have a shadowing node UASSERT(b.propagateSunlight(light_sources) == false); UASSERT(b.getNode(v3s16(1,4,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN); UASSERT(b.getNode(v3s16(1,3,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN); UASSERT(b.getNode(v3s16(1,2,0)).getLight(LIGHTBANK_DAY) == 0); UASSERT(b.getNode(v3s16(1,1,0)).getLight(LIGHTBANK_DAY) == 0); UASSERT(b.getNode(v3s16(1,0,0)).getLight(LIGHTBANK_DAY) == 0); UASSERT(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == LIGHT_SUN); UASSERT(b.getFaceLight2(1000, p, v3s16(0,1,0)) == LIGHT_SUN); UASSERT(b.getFaceLight2(1000, p, v3s16(0,-1,0)) == 0); UASSERT(b.getFaceLight2(0, p, v3s16(0,-1,0)) == 0); // According to MapBlock::getFaceLight, // The face on the z+ side should have double-diminished light //UASSERT(b.getFaceLight(p, v3s16(0,0,1)) == diminish_light(diminish_light(LIGHT_MAX))); // The face on the z+ side should have diminished light UASSERT(b.getFaceLight2(1000, p, v3s16(0,0,1)) == diminish_light(LIGHT_MAX)); } /* Check how the block handles being in between blocks with some non-sunlight while being underground */ { // Make neighbours to exist and set some non-sunlight to them parent.position_valid = true; b.setIsUnderground(true); parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2); core::map<v3s16, bool> light_sources; // The block below should be valid because there shouldn't be // sunlight in there either UASSERT(b.propagateSunlight(light_sources, true) == true); // Should not touch nodes that are not affected (that is, all of them) //UASSERT(b.getNode(v3s16(1,2,3)).getLight() == LIGHT_SUN); // Should set light of non-sunlighted blocks to 0. UASSERT(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == 0); } /* Set up a situation where: - There is only air in this block - There is a valid non-sunlighted block at the bottom, and - Invalid blocks elsewhere. - the block is not underground. This should result in bottom block invalidity */ { b.setIsUnderground(false); // Clear block for(u16 z=0; z<MAP_BLOCKSIZE; z++){ for(u16 y=0; y<MAP_BLOCKSIZE; y++){ for(u16 x=0; x<MAP_BLOCKSIZE; x++){ MapNode n; n.setContent(CONTENT_AIR); n.setLight(LIGHTBANK_DAY, 0); b.setNode(v3s16(x,y,z), n); } } } // Make neighbours invalid parent.position_valid = false; // Add exceptions to the top of the bottom block for(u16 x=0; x<MAP_BLOCKSIZE; x++) for(u16 z=0; z<MAP_BLOCKSIZE; z++) { parent.validity_exceptions.push_back(v3s16(MAP_BLOCKSIZE+x, MAP_BLOCKSIZE-1, MAP_BLOCKSIZE+z)); } // Lighting value for the valid nodes parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2); core::map<v3s16, bool> light_sources; // Bottom block is not valid UASSERT(b.propagateSunlight(light_sources) == false); } } }; struct TestMapSector: public TestBase { class TC : public NodeContainer { public: MapNode node; bool position_valid; TC() { position_valid = true; } virtual bool isValidPosition(v3s16 p) { return position_valid; } virtual MapNode getNode(v3s16 p) { if(position_valid == false) throw InvalidPositionException(); return node; } virtual void setNode(v3s16 p, MapNode & n) { if(position_valid == false) throw InvalidPositionException(); }; virtual u16 nodeContainerId() const { return 666; } }; void Run() { TC parent; parent.position_valid = false; // Create one with no heightmaps ServerMapSector sector(&parent, v2s16(1,1)); UASSERT(sector.getBlockNoCreateNoEx(0) == 0); UASSERT(sector.getBlockNoCreateNoEx(1) == 0); MapBlock * bref = sector.createBlankBlock(-2); UASSERT(sector.getBlockNoCreateNoEx(0) == 0); UASSERT(sector.getBlockNoCreateNoEx(-2) == bref); //TODO: Check for AlreadyExistsException /*bool exception_thrown = false; try{ sector.getBlock(0); } catch(InvalidPositionException &e){ exception_thrown = true; } UASSERT(exception_thrown);*/ } }; #endif struct TestCollision: public TestBase { void Run() { /* axisAlignedCollision */ for(s16 bx = -3; bx <= 3; bx++) for(s16 by = -3; by <= 3; by++) for(s16 bz = -3; bz <= 3; bz++) { // X- { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx-2, by, bz, bx-1, by+1, bz+1); v3f v(1, 0, 0); f32 dtime = 0; UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0); UASSERT(fabs(dtime - 1.000) < 0.001); } { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx-2, by, bz, bx-1, by+1, bz+1); v3f v(-1, 0, 0); f32 dtime = 0; UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1); } { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx-2, by+1.5, bz, bx-1, by+2.5, bz-1); v3f v(1, 0, 0); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1); } { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx-2, by-1.5, bz, bx-1.5, by+0.5, bz+1); v3f v(0.5, 0.1, 0); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0); UASSERT(fabs(dtime - 3.000) < 0.001); } { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx-2, by-1.5, bz, bx-1.5, by+0.5, bz+1); v3f v(0.5, 0.1, 0); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0); UASSERT(fabs(dtime - 3.000) < 0.001); } // X+ { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx+2, by, bz, bx+3, by+1, bz+1); v3f v(-1, 0, 0); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0); UASSERT(fabs(dtime - 1.000) < 0.001); } { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx+2, by, bz, bx+3, by+1, bz+1); v3f v(1, 0, 0); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1); } { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx+2, by, bz+1.5, bx+3, by+1, bz+3.5); v3f v(-1, 0, 0); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1); } { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx+2, by-1.5, bz, bx+2.5, by-0.5, bz+1); v3f v(-0.5, 0.2, 0); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 1); // Y, not X! UASSERT(fabs(dtime - 2.500) < 0.001); } { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx+2, by-1.5, bz, bx+2.5, by-0.5, bz+1); v3f v(-0.5, 0.3, 0); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0); UASSERT(fabs(dtime - 2.000) < 0.001); } // TODO: Y-, Y+, Z-, Z+ // misc { aabb3f s(bx, by, bz, bx+2, by+2, bz+2); aabb3f m(bx+2.3, by+2.29, bz+2.29, bx+4.2, by+4.2, bz+4.2); v3f v(-1./3, -1./3, -1./3); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0); UASSERT(fabs(dtime - 0.9) < 0.001); } { aabb3f s(bx, by, bz, bx+2, by+2, bz+2); aabb3f m(bx+2.29, by+2.3, bz+2.29, bx+4.2, by+4.2, bz+4.2); v3f v(-1./3, -1./3, -1./3); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 1); UASSERT(fabs(dtime - 0.9) < 0.001); } { aabb3f s(bx, by, bz, bx+2, by+2, bz+2); aabb3f m(bx+2.29, by+2.29, bz+2.3, bx+4.2, by+4.2, bz+4.2); v3f v(-1./3, -1./3, -1./3); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 2); UASSERT(fabs(dtime - 0.9) < 0.001); } { aabb3f s(bx, by, bz, bx+2, by+2, bz+2); aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.3, by-2.29, bz-2.29); v3f v(1./7, 1./7, 1./7); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0); UASSERT(fabs(dtime - 16.1) < 0.001); } { aabb3f s(bx, by, bz, bx+2, by+2, bz+2); aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.29, by-2.3, bz-2.29); v3f v(1./7, 1./7, 1./7); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 1); UASSERT(fabs(dtime - 16.1) < 0.001); } { aabb3f s(bx, by, bz, bx+2, by+2, bz+2); aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.29, by-2.29, bz-2.3); v3f v(1./7, 1./7, 1./7); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 2); UASSERT(fabs(dtime - 16.1) < 0.001); } } } }; struct TestSocket: public TestBase { void Run() { const int port = 30003; // IPv6 socket test { UDPSocket socket6(true); socket6.Bind(port); const char sendbuffer[] = "hello world!"; IPv6AddressBytes bytes; bytes.bytes[15] = 1; socket6.Send(Address(&bytes, port), sendbuffer, sizeof(sendbuffer)); sleep_ms(50); char rcvbuffer[256]; memset(rcvbuffer, 0, sizeof(rcvbuffer)); Address sender; for(;;) { int bytes_read = socket6.Receive(sender, rcvbuffer, sizeof(rcvbuffer)); if(bytes_read < 0) break; } //FIXME: This fails on some systems UASSERT(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer))==0); UASSERT(memcmp(sender.getAddress6().sin6_addr.s6_addr, Address(&bytes, 0).getAddress6().sin6_addr.s6_addr, 16) == 0); } // IPv4 socket test { UDPSocket socket(false); socket.Bind(port); const char sendbuffer[] = "hello world!"; socket.Send(Address(127,0,0,1,port), sendbuffer, sizeof(sendbuffer)); sleep_ms(50); char rcvbuffer[256]; memset(rcvbuffer, 0, sizeof(rcvbuffer)); Address sender; for(;;) { int bytes_read = socket.Receive(sender, rcvbuffer, sizeof(rcvbuffer)); if(bytes_read < 0) break; } //FIXME: This fails on some systems UASSERT(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer))==0); UASSERT(sender.getAddress().sin_addr.s_addr == Address(127,0,0,1, 0).getAddress().sin_addr.s_addr); } } }; struct TestConnection: public TestBase { void TestHelpers() { /* Test helper functions */ // Some constants for testing u32 proto_id = 0x12345678; u16 peer_id = 123; u8 channel = 2; SharedBuffer<u8> data1(1); data1[0] = 100; Address a(127,0,0,1, 10); u16 seqnum = 34352; con::BufferedPacket p1 = con::makePacket(a, data1, proto_id, peer_id, channel); /* We should now have a packet with this data: Header: [0] u32 protocol_id [4] u16 sender_peer_id [6] u8 channel Data: [7] u8 data1[0] */ UASSERT(readU32(&p1.data[0]) == proto_id); UASSERT(readU16(&p1.data[4]) == peer_id); UASSERT(readU8(&p1.data[6]) == channel); UASSERT(readU8(&p1.data[7]) == data1[0]); //infostream<<"initial data1[0]="<<((u32)data1[0]&0xff)<<std::endl; SharedBuffer<u8> p2 = con::makeReliablePacket(data1, seqnum); /*infostream<<"p2.getSize()="<<p2.getSize()<<", data1.getSize()=" <<data1.getSize()<<std::endl; infostream<<"readU8(&p2[3])="<<readU8(&p2[3]) <<" p2[3]="<<((u32)p2[3]&0xff)<<std::endl; infostream<<"data1[0]="<<((u32)data1[0]&0xff)<<std::endl;*/ UASSERT(p2.getSize() == 3 + data1.getSize()); UASSERT(readU8(&p2[0]) == TYPE_RELIABLE); UASSERT(readU16(&p2[1]) == seqnum); UASSERT(readU8(&p2[3]) == data1[0]); } struct Handler : public con::PeerHandler { Handler(const char *a_name) { count = 0; last_id = 0; name = a_name; } void peerAdded(con::Peer *peer) { infostream<<"Handler("<<name<<")::peerAdded(): " "id="<<peer->id<<std::endl; last_id = peer->id; count++; } void deletingPeer(con::Peer *peer, bool timeout) { infostream<<"Handler("<<name<<")::deletingPeer(): " "id="<<peer->id <<", timeout="<<timeout<<std::endl; last_id = peer->id; count--; } s32 count; u16 last_id; const char *name; }; void Run() { DSTACK("TestConnection::Run"); TestHelpers(); /* Test some real connections NOTE: This mostly tests the legacy interface. */ u32 proto_id = 0xad26846a; Handler hand_server("server"); Handler hand_client("client"); infostream<<"** Creating server Connection"<<std::endl; con::Connection server(proto_id, 512, 5.0, false, &hand_server); server.Serve(30001); infostream<<"** Creating client Connection"<<std::endl; con::Connection client(proto_id, 512, 5.0, false, &hand_client); UASSERT(hand_server.count == 0); UASSERT(hand_client.count == 0); sleep_ms(50); Address server_address(127,0,0,1, 30001); infostream<<"** running client.Connect()"<<std::endl; client.Connect(server_address); sleep_ms(50); // Client should not have added client yet UASSERT(hand_client.count == 0); try { u16 peer_id; SharedBuffer<u8> data; infostream<<"** running client.Receive()"<<std::endl; u32 size = client.Receive(peer_id, data); infostream<<"** Client received: peer_id="<<peer_id <<", size="<<size <<std::endl; } catch(con::NoIncomingDataException &e) { } // Client should have added server now UASSERT(hand_client.count == 1); UASSERT(hand_client.last_id == 1); // Server should not have added client yet UASSERT(hand_server.count == 0); sleep_ms(100); try { u16 peer_id; SharedBuffer<u8> data; infostream<<"** running server.Receive()"<<std::endl; u32 size = server.Receive(peer_id, data); infostream<<"** Server received: peer_id="<<peer_id <<", size="<<size <<std::endl; } catch(con::NoIncomingDataException &e) { // No actual data received, but the client has // probably been connected } // Client should be the same UASSERT(hand_client.count == 1); UASSERT(hand_client.last_id == 1); // Server should have the client UASSERT(hand_server.count == 1); UASSERT(hand_server.last_id == 2); //sleep_ms(50); while(client.Connected() == false) { try { u16 peer_id; SharedBuffer<u8> data; infostream<<"** running client.Receive()"<<std::endl; u32 size = client.Receive(peer_id, data); infostream<<"** Client received: peer_id="<<peer_id <<", size="<<size <<std::endl; } catch(con::NoIncomingDataException &e) { } sleep_ms(50); } sleep_ms(50); try { u16 peer_id; SharedBuffer<u8> data; infostream<<"** running server.Receive()"<<std::endl; u32 size = server.Receive(peer_id, data); infostream<<"** Server received: peer_id="<<peer_id <<", size="<<size <<std::endl; } catch(con::NoIncomingDataException &e) { } #if 1 /* Simple send-receive test */ { /*u8 data[] = "Hello World!"; u32 datasize = sizeof(data);*/ SharedBuffer<u8> data = SharedBufferFromString("Hello World!"); infostream<<"** running client.Send()"<<std::endl; client.Send(PEER_ID_SERVER, 0, data, true); sleep_ms(50); u16 peer_id; SharedBuffer<u8> recvdata; infostream<<"** running server.Receive()"<<std::endl; u32 size = server.Receive(peer_id, recvdata); infostream<<"** Server received: peer_id="<<peer_id <<", size="<<size <<", data="<<*data <<std::endl; UASSERT(memcmp(*data, *recvdata, data.getSize()) == 0); } #endif u16 peer_id_client = 2; #if 0 /* Send consequent packets in different order Not compatible with new Connection, thus commented out. */ { //u8 data1[] = "hello1"; //u8 data2[] = "hello2"; SharedBuffer<u8> data1 = SharedBufferFromString("hello1"); SharedBuffer<u8> data2 = SharedBufferFromString("Hello2"); Address client_address = server.GetPeerAddress(peer_id_client); infostream<<"*** Sending packets in wrong order (2,1,2)" <<std::endl; u8 chn = 0; con::Channel *ch = &server.getPeer(peer_id_client)->channels[chn]; u16 sn = ch->next_outgoing_seqnum; ch->next_outgoing_seqnum = sn+1; server.Send(peer_id_client, chn, data2, true); ch->next_outgoing_seqnum = sn; server.Send(peer_id_client, chn, data1, true); ch->next_outgoing_seqnum = sn+1; server.Send(peer_id_client, chn, data2, true); sleep_ms(50); infostream<<"*** Receiving the packets"<<std::endl; u16 peer_id; SharedBuffer<u8> recvdata; u32 size; infostream<<"** running client.Receive()"<<std::endl; peer_id = 132; size = client.Receive(peer_id, recvdata); infostream<<"** Client received: peer_id="<<peer_id <<", size="<<size <<", data="<<*recvdata <<std::endl; UASSERT(size == data1.getSize()); UASSERT(memcmp(*data1, *recvdata, data1.getSize()) == 0); UASSERT(peer_id == PEER_ID_SERVER); infostream<<"** running client.Receive()"<<std::endl; peer_id = 132; size = client.Receive(peer_id, recvdata); infostream<<"** Client received: peer_id="<<peer_id <<", size="<<size <<", data="<<*recvdata <<std::endl; UASSERT(size == data2.getSize()); UASSERT(memcmp(*data2, *recvdata, data2.getSize()) == 0); UASSERT(peer_id == PEER_ID_SERVER); bool got_exception = false; try { infostream<<"** running client.Receive()"<<std::endl; peer_id = 132; size = client.Receive(peer_id, recvdata); infostream<<"** Client received: peer_id="<<peer_id <<", size="<<size <<", data="<<*recvdata <<std::endl; } catch(con::NoIncomingDataException &e) { infostream<<"** No incoming data for client"<<std::endl; got_exception = true; } UASSERT(got_exception); } #endif #if 0 /* Send large amounts of packets (infinite test) Commented out because of infinity. */ { infostream<<"Sending large amounts of packets (infinite test)"<<std::endl; int sendcount = 0; for(;;){ int datasize = myrand_range(0,5)==0?myrand_range(100,10000):myrand_range(0,100); infostream<<"datasize="<<datasize<<std::endl; SharedBuffer<u8> data1(datasize); for(u16 i=0; i<datasize; i++) data1[i] = i/4; int sendtimes = myrand_range(1,10); for(int i=0; i<sendtimes; i++){ server.Send(peer_id_client, 0, data1, true); sendcount++; } infostream<<"sendcount="<<sendcount<<std::endl; //int receivetimes = myrand_range(1,20); int receivetimes = 20; for(int i=0; i<receivetimes; i++){ SharedBuffer<u8> recvdata; u16 peer_id = 132; u16 size = 0; bool received = false; try{ size = client.Receive(peer_id, recvdata); received = true; }catch(con::NoIncomingDataException &e){ } } } } #endif /* Send a large packet */ { const int datasize = 30000; SharedBuffer<u8> data1(datasize); for(u16 i=0; i<datasize; i++){ data1[i] = i/4; } infostream<<"Sending data (size="<<datasize<<"):"; for(int i=0; i<datasize && i<20; i++){ if(i%2==0) infostream<<" "; char buf[10]; snprintf(buf, 10, "%.2X", ((int)((const char*)*data1)[i])&0xff); infostream<<buf; } if(datasize>20) infostream<<"..."; infostream<<std::endl; server.Send(peer_id_client, 0, data1, true); //sleep_ms(3000); SharedBuffer<u8> recvdata; infostream<<"** running client.Receive()"<<std::endl; u16 peer_id = 132; u16 size = 0; bool received = false; u32 timems0 = porting::getTimeMs(); for(;;){ if(porting::getTimeMs() - timems0 > 5000 || received) break; try{ size = client.Receive(peer_id, recvdata); received = true; }catch(con::NoIncomingDataException &e){ } sleep_ms(10); } UASSERT(received); infostream<<"** Client received: peer_id="<<peer_id <<", size="<<size <<std::endl; infostream<<"Received data (size="<<size<<"): "; for(int i=0; i<size && i<20; i++){ if(i%2==0) infostream<<" "; char buf[10]; snprintf(buf, 10, "%.2X", ((int)(recvdata[i]))&0xff); infostream<<buf; } if(size>20) infostream<<"..."; infostream<<std::endl; UASSERT(memcmp(*data1, *recvdata, data1.getSize()) == 0); UASSERT(peer_id == PEER_ID_SERVER); } // Check peer handlers UASSERT(hand_client.count == 1); UASSERT(hand_client.last_id == 1); UASSERT(hand_server.count == 1); UASSERT(hand_server.last_id == 2); //assert(0); } }; #define TEST(X)\ {\ X x;\ infostream<<"Running " #X <<std::endl;\ x.Run();\ tests_run++;\ tests_failed += x.test_failed ? 1 : 0;\ } #define TESTPARAMS(X, ...)\ {\ X x;\ infostream<<"Running " #X <<std::endl;\ x.Run(__VA_ARGS__);\ tests_run++;\ tests_failed += x.test_failed ? 1 : 0;\ } void run_tests() { DSTACK(__FUNCTION_NAME); int tests_run = 0; int tests_failed = 0; // Create item and node definitions IWritableItemDefManager *idef = createItemDefManager(); IWritableNodeDefManager *ndef = createNodeDefManager(); define_some_nodes(idef, ndef); infostream<<"run_tests() started"<<std::endl; TEST(TestUtilities); TEST(TestPath); TEST(TestSettings); TEST(TestCompress); TEST(TestSerialization); TEST(TestNodedefSerialization); TESTPARAMS(TestMapNode, ndef); TESTPARAMS(TestVoxelManipulator, ndef); TESTPARAMS(TestVoxelAlgorithms, ndef); TESTPARAMS(TestInventory, idef); //TEST(TestMapBlock); //TEST(TestMapSector); TEST(TestCollision); if(INTERNET_SIMULATOR == false){ TEST(TestSocket); dout_con<<"=== BEGIN RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl; TEST(TestConnection); dout_con<<"=== END RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl; } delete idef; delete ndef; if(tests_failed == 0){ infostream<<"run_tests(): "<<tests_failed<<" / "<<tests_run<<" tests failed."<<std::endl; infostream<<"run_tests() passed."<<std::endl; return; } else { errorstream<<"run_tests(): "<<tests_failed<<" / "<<tests_run<<" tests failed."<<std::endl; errorstream<<"run_tests() aborting."<<std::endl; abort(); } }