aboutsummaryrefslogtreecommitdiff
path: root/src/porting.cpp
blob: 64a51c7f50527505a4ec883eccf802da09d91909 (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
698
699
700
701
702
703
704
705
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

/*
	Random portability stuff

	See comments in porting.h
*/

#include "porting.h"

#if defined(__FreeBSD__)
	#include <sys/types.h>
	#include <sys/sysctl.h>
#elif defined(_WIN32)
	#include <algorithm>
#endif
#if !defined(_WIN32)
	#include <unistd.h>
	#include <sys/utsname.h>
#endif

#if !defined(_WIN32) && !defined(__APPLE__) && \
	!defined(__ANDROID__) && !defined(SERVER)
	#define XORG_USED
#endif

#ifdef XORG_USED
	#include <X11/Xlib.h>
	#include <X11/Xutil.h>
#endif

#include "config.h"
#include "debug.h"
#include "filesys.h"
#include "log.h"
#include "util/string.h"
#include "main.h"
#include "settings.h"
#include <list>

namespace porting
{

/*
	Signal handler (grabs Ctrl-C on POSIX systems)
*/

bool g_killed = false;

bool * signal_handler_killstatus(void)
{
	return &g_killed;
}

#if !defined(_WIN32) // POSIX
	#include <signal.h>

void sigint_handler(int sig)
{
	if(g_killed == false)
	{
		dstream<<DTIME<<"INFO: sigint_handler(): "
				<<"Ctrl-C pressed, shutting down."<<std::endl;

		// Comment out for less clutter when testing scripts
		/*dstream<<DTIME<<"INFO: sigint_handler(): "
				<<"Printing debug stacks"<<std::endl;
		debug_stacks_print();*/

		g_killed = true;
	}
	else
	{
		(void)signal(SIGINT, SIG_DFL);
	}
}

void signal_handler_init(void)
{
	(void)signal(SIGINT, sigint_handler);
}

#else // _WIN32
	#include <signal.h>

	BOOL WINAPI event_handler(DWORD sig)
	{
		switch(sig)
		{
		case CTRL_C_EVENT:
		case CTRL_CLOSE_EVENT:
		case CTRL_LOGOFF_EVENT:
		case CTRL_SHUTDOWN_EVENT:

			if(g_killed == false)
			{
				dstream<<DTIME<<"INFO: event_handler(): "
						<<"Ctrl+C, Close Event, Logoff Event or Shutdown Event, shutting down."<<std::endl;
				// Comment out for less clutter when testing scripts
				/*dstream<<DTIME<<"INFO: event_handler(): "
						<<"Printing debug stacks"<<std::endl;
				debug_stacks_print();*/

				g_killed = true;
			}
			else
			{
				(void)signal(SIGINT, SIG_DFL);
			}

			break;
		case CTRL_BREAK_EVENT:
			break;
		}

		return TRUE;
	}

void signal_handler_init(void)
{
	SetConsoleCtrlHandler( (PHANDLER_ROUTINE)event_handler,TRUE);
}

#endif


/*
	Multithreading support
*/
int getNumberOfProcessors() {
#if defined(_SC_NPROCESSORS_ONLN)

	return sysconf(_SC_NPROCESSORS_ONLN);

#elif defined(__FreeBSD__) || defined(__APPLE__)

	unsigned int len, count;
	len = sizeof(count);
	return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);

#elif defined(_GNU_SOURCE)

	return get_nprocs();

#elif defined(_WIN32)

	SYSTEM_INFO sysinfo;
	GetSystemInfo(&sysinfo);
	return sysinfo.dwNumberOfProcessors;

#elif defined(PTW32_VERSION) || defined(__hpux)

	return pthread_num_processors_np();

#else

	return 1;

#endif
}


#ifndef __ANDROID__
bool threadBindToProcessor(threadid_t tid, int pnumber) {
#if defined(_WIN32)

	HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
	if (!hThread)
		return false;

	bool success = SetThreadAffinityMask(hThread, 1 << pnumber) != 0;

	CloseHandle(hThread);
	return success;

#elif (defined(__FreeBSD__) && (__FreeBSD_version >= 702106)) \
	|| defined(__linux) || defined(linux)

	cpu_set_t cpuset;

	CPU_ZERO(&cpuset);
	CPU_SET(pnumber, &cpuset);
	return pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset) == 0;

#elif defined(__sun) || defined(sun)

	return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(tid),
						pnumber, NULL) == 0;

#elif defined(_AIX)

	return bindprocessor(BINDTHREAD, (tid_t)tid, pnumber) == 0;

#elif defined(__hpux) || defined(hpux)

	pthread_spu_t answer;

	return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
									&answer, pnumber, tid) == 0;

#elif defined(__APPLE__)

	struct thread_affinity_policy tapol;

	thread_port_t threadport = pthread_mach_thread_np(tid);
	tapol.affinity_tag = pnumber + 1;
	return thread_policy_set(threadport, THREAD_AFFINITY_POLICY,
			(thread_policy_t)&tapol, THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS;

#else

	return false;

#endif
}
#endif

bool threadSetPriority(threadid_t tid, int prio) {
#if defined(_WIN32)

	HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
	if (!hThread)
		return false;

	bool success = SetThreadPriority(hThread, prio) != 0;

	CloseHandle(hThread);
	return success;

#else

	struct sched_param sparam;
	int policy;

	if (pthread_getschedparam(tid, &policy, &sparam) != 0)
		return false;

	int min = sched_get_priority_min(policy);
	int max = sched_get_priority_max(policy);

	sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
	return pthread_setschedparam(tid, policy, &sparam) == 0;

#endif
}


/*
	Path mangler
*/

// Default to RUN_IN_PLACE style relative paths
std::string path_share = "..";
std::string path_user = "..";

std::string getDataPath(const char *subpath)
{
	return path_share + DIR_DELIM + subpath;
}

void pathRemoveFile(char *path, char delim)
{
	// Remove filename and path delimiter
	int i;
	for(i = strlen(path)-1; i>=0; i--)
	{
		if(path[i] == delim)
			break;
	}
	path[i] = 0;
}

bool detectMSVCBuildDir(char *c_path)
{
	std::string path(c_path);
	const char *ends[] = {
		"bin\\Release",
		"bin\\Debug",
		"bin\\Build",
		NULL};
	return (removeStringEnd(path, ends) != "");
}

std::string get_sysinfo()
{
#ifdef _WIN32
	OSVERSIONINFO osvi;
	std::ostringstream oss;
	std::string tmp;
	ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
	GetVersionEx(&osvi);
	tmp = osvi.szCSDVersion;
	std::replace(tmp.begin(), tmp.end(), ' ', '_');

	oss << "Windows/" << osvi.dwMajorVersion << "."
		<< osvi.dwMinorVersion;
	if(osvi.szCSDVersion[0])
		oss << "-" << tmp;
	oss << " ";
	#ifdef _WIN64
	oss << "x86_64";
	#else
	BOOL is64 = FALSE;
	if(IsWow64Process(GetCurrentProcess(), &is64) && is64)
		oss << "x86_64"; // 32-bit app on 64-bit OS
	else
		oss << "x86";
	#endif

	return oss.str();
#else
	struct utsname osinfo;
	uname(&osinfo);
	return std::string(osinfo.sysname) + "/"
		+ osinfo.release + " " + osinfo.machine;
#endif
}

void initializePaths()
{
#if RUN_IN_PLACE
	/*
		Use relative paths if RUN_IN_PLACE
	*/

	infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl;

	/*
		Windows
	*/
	#if defined(_WIN32)

	const DWORD buflen = 1000;
	char buf[buflen];
	DWORD len;

	// Find path of executable and set path_share relative to it
	len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
	assert(len < buflen);
	pathRemoveFile(buf, '\\');

	if(detectMSVCBuildDir(buf)){
		infostream<<"MSVC build directory detected"<<std::endl;
		path_share = std::string(buf) + "\\..\\..";
		path_user = std::string(buf) + "\\..\\..";
	}
	else{
		path_share = std::string(buf) + "\\..";
		path_user = std::string(buf) + "\\..";
	}

	/*
		Linux
	*/
	#elif defined(linux)

	char buf[BUFSIZ];
	memset(buf, 0, BUFSIZ);
	// Get path to executable
	FATAL_ERROR_IF(readlink("/proc/self/exe", buf, BUFSIZ-1) == -1, "Failed to get cwd");

	pathRemoveFile(buf, '/');

	path_share = std::string(buf) + "/..";
	path_user = std::string(buf) + "/..";

	/*
		OS X
	*/
	#elif defined(__APPLE__)

	//https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dyld.3.html
	//TODO: Test this code
	char buf[BUFSIZ];
	uint32_t len = sizeof(buf);
	FATAL_ERROR_IF(_NSGetExecutablePath(buf, &len) == -1, "");

	pathRemoveFile(buf, '/');

	path_share = std::string(buf) + "/..";
	path_user = std::string(buf) + "/..";

	/*
		FreeBSD
	*/
	#elif defined(__FreeBSD__)

	int mib[4];
	char buf[BUFSIZ];
	size_t len = sizeof(buf);

	mib[0] = CTL_KERN;
	mib[1] = KERN_PROC;
	mib[2] = KERN_PROC_PATHNAME;
	mib[3] = -1;
	FATAL_ERROR_IF(sysctl(mib, 4, buf, &len, NULL, 0) == -1, "");

	pathRemoveFile(buf, '/');

	path_share = std::string(buf) + "/..";
	path_user = std::string(buf) + "/..";

	#else

	//TODO: Get path of executable. This assumes working directory is bin/
	dstream<<"WARNING: Relative path not properly supported on this platform"
			<<std::endl;

	/* scriptapi no longer allows paths that start with "..", so assuming that
	   the current working directory is bin/, strip off the last component. */
	char *cwd = getcwd(NULL, 0);
	pathRemoveFile(cwd, '/');
	path_share = std::string(cwd);
	path_user = std::string(cwd);

	#endif

#else // RUN_IN_PLACE

	/*
		Use platform-specific paths otherwise
	*/

	infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;

	/*
		Windows
	*/
	#if defined(_WIN32)

	const DWORD buflen = 1000; // FIXME: Surely there is a better way to do this
	char buf[buflen];
	DWORD len;

	// Find path of executable and set path_share relative to it
	len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
	FATAL_ERROR_IF(len >= buflen, "Overlow");
	pathRemoveFile(buf, '\\');

	// Use ".\bin\.."
	path_share = std::string(buf) + "\\..";

	// Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
	len = GetEnvironmentVariable("APPDATA", buf, buflen);
	FATAL_ERROR_IF(len >= buflen, "Overlow");
	path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;

	/*
		Linux
	*/
	#elif defined(linux)

	// Get path to executable
	std::string bindir = "";
	{
		char buf[BUFSIZ];
		memset(buf, 0, BUFSIZ);
		if (readlink("/proc/self/exe", buf, BUFSIZ-1) == -1) {
			errorstream << "Unable to read bindir "<< std::endl;
#ifndef __ANDROID__
			FATAL_ERROR("Unable to read bindir");
#endif
		} else {
			pathRemoveFile(buf, '/');
			bindir = buf;
		}
	}

	// Find share directory from these.
	// It is identified by containing the subdirectory "builtin".
	std::list<std::string> trylist;
	std::string static_sharedir = STATIC_SHAREDIR;
	if(static_sharedir != "" && static_sharedir != ".")
		trylist.push_back(static_sharedir);
	trylist.push_back(
			bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + PROJECT_NAME);
	trylist.push_back(bindir + DIR_DELIM + "..");
#ifdef __ANDROID__
	trylist.push_back(path_user);
#endif

	for(std::list<std::string>::const_iterator i = trylist.begin();
			i != trylist.end(); i++)
	{
		const std::string &trypath = *i;
		if(!fs::PathExists(trypath) || !fs::PathExists(trypath + DIR_DELIM + "builtin")){
			dstream<<"WARNING: system-wide share not found at \""
					<<trypath<<"\""<<std::endl;
			continue;
		}
		// Warn if was not the first alternative
		if(i != trylist.begin()){
			dstream<<"WARNING: system-wide share found at \""
					<<trypath<<"\""<<std::endl;
		}
		path_share = trypath;
		break;
	}
#ifndef __ANDROID__
	path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
#endif

	/*
		OS X
	*/
	#elif defined(__APPLE__)

	// Code based on
	// http://stackoverflow.com/questions/516200/relative-paths-not-working-in-xcode-c
	CFBundleRef main_bundle = CFBundleGetMainBundle();
	CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
	char path[PATH_MAX];
	if(CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX))
	{
		dstream<<"Bundle resource path: "<<path<<std::endl;
		//chdir(path);
		path_share = std::string(path) + DIR_DELIM + STATIC_SHAREDIR;
	}
	else
	{
		// error!
		dstream<<"WARNING: Could not determine bundle resource path"<<std::endl;
	}
	CFRelease(resources_url);

	path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + PROJECT_NAME;

	#else // FreeBSD, and probably many other POSIX-like systems.

	path_share = STATIC_SHAREDIR;
	path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;

	#endif

#endif // RUN_IN_PLACE
}

static irr::IrrlichtDevice *device;

void initIrrlicht(irr::IrrlichtDevice *device_)
{
	device = device_;
}

void setXorgClassHint(const video::SExposedVideoData &video_data,
	const std::string &name)
{
#ifdef XORG_USED
	if (video_data.OpenGLLinux.X11Display == NULL)
		return;

	XClassHint *classhint = XAllocClassHint();
	classhint->res_name  = (char *)name.c_str();
	classhint->res_class = (char *)name.c_str();

	XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
		video_data.OpenGLLinux.X11Window, classhint);
	XFree(classhint);
#endif
}

#ifndef SERVER
v2u32 getWindowSize()
{
	return device->getVideoDriver()->getScreenSize();
}


std::vector<core::vector3d<u32> > getVideoModes()
{
	std::vector<core::vector3d<u32> > mlist;
	video::IVideoModeList *modelist = device->getVideoModeList();

	u32 num_modes = modelist->getVideoModeCount();
	for (u32 i = 0; i != num_modes; i++) {
		core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
		s32 mode_depth = modelist->getVideoModeDepth(i);
		mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
	}

	return mlist;
}

std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
{
	std::vector<irr::video::E_DRIVER_TYPE> drivers;

	for (int i = 0; i != irr::video::EDT_COUNT; i++) {
		if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
			drivers.push_back((irr::video::E_DRIVER_TYPE)i);
	}

	return drivers;
}

const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
{
	static const char *driver_ids[] = {
		"null",
		"software",
		"burningsvideo",
		"direct3d8",
		"direct3d9",
		"opengl",
		"ogles1",
		"ogles2",
	};

	return driver_ids[type];
}


const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
{
	static const char *driver_names[] = {
		"NULL Driver",
		"Software Renderer",
		"Burning's Video",
		"Direct3D 8",
		"Direct3D 9",
		"OpenGL",
		"OpenGL ES1",
		"OpenGL ES2",
	};

	return driver_names[type];
}


#ifndef __ANDROID__
#ifdef XORG_USED

static float calcDisplayDensity()
{
	const char* current_display = getenv("DISPLAY");

	if (current_display != NULL) {
			Display * x11display = XOpenDisplay(current_display);

			if (x11display != NULL) {
				/* try x direct */
				float dpi_height =
						floor(DisplayHeight(x11display, 0) /
								(DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
				float dpi_width =
						floor(DisplayWidth(x11display, 0) /
								(DisplayWidthMM(x11display, 0) * 0.039370) +0.5);

				XCloseDisplay(x11display);

				return std::max(dpi_height,dpi_width) / 96.0;
			}
		}

	/* return manually specified dpi */
	return g_settings->getFloat("screen_dpi")/96.0;
}


float getDisplayDensity()
{
	static float cached_display_density = calcDisplayDensity();
	return cached_display_density;
}


#else
float getDisplayDensity()
{
	return g_settings->getFloat("screen_dpi")/96.0;
}
#endif

v2u32 getDisplaySize()
{
	IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);

	core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
	nulldevice -> drop();

	return deskres;
}
#endif
#endif

} //namespace porting

l opt">( current.rel_position, &is_valid_position); const ContentFeatures &f = nodemgr->get(node); // If the node emits light, it behaves like it had a // brighter neighbor. u8 brightest_neighbor_light = f.light_source + 1; for (direction i = 0; i < 6; i++) { //For each neighbor // The node that changed this node has already zero light // and it can't give light to this node if (current.source_direction + i == 5) { continue; } // Get the neighbor's position and block neighbor_rel_pos = current.rel_position; neighbor_block_pos = current.block_position; MapBlock *neighbor_block; if (step_rel_block_pos(i, neighbor_rel_pos, neighbor_block_pos)) { neighbor_block = map->getBlockNoCreateNoEx(neighbor_block_pos); if (neighbor_block == NULL) { current.block->setLightingComplete(bank, i, false); continue; } } else { neighbor_block = current.block; } // Get the neighbor itself MapNode neighbor = neighbor_block->getNodeNoCheck(neighbor_rel_pos, &is_valid_position); const ContentFeatures &neighbor_f = nodemgr->get( neighbor.getContent()); u8 neighbor_light = neighbor.getLightRaw(bank, neighbor_f); // If the neighbor has at least as much light as this node, then // it won't lose its light, since it should have been added to // from_nodes earlier, so its light would be zero. if (neighbor_f.light_propagates && neighbor_light < current_light) { // Unlight, but only if the node has light. if (neighbor_light > 0) { neighbor.setLight(bank, 0, neighbor_f); neighbor_block->setNodeNoCheck(neighbor_rel_pos, neighbor); from_nodes.push(neighbor_light, neighbor_rel_pos, neighbor_block_pos, neighbor_block, i); // The current node was modified earlier, so its block // is in modified_blocks. if (current.block != neighbor_block) { modified_blocks[neighbor_block_pos] = neighbor_block; } } } else { // The neighbor can light up this node. if (neighbor_light < neighbor_f.light_source) { neighbor_light = neighbor_f.light_source; } if (brightest_neighbor_light < neighbor_light) { brightest_neighbor_light = neighbor_light; source_dir = i; } } } // If the brightest neighbor is able to light up this node, // then add this node to the output nodes. if (brightest_neighbor_light > 1 && f.light_propagates) { brightest_neighbor_light--; light_sources.push(brightest_neighbor_light, current.rel_position, current.block_position, current.block, (source_dir == 6) ? 6 : 5 - source_dir /* with opposite direction*/); } } } /* * Spreads light from the specified starting nodes. * * Before calling this procedure, make sure that all ChangingLights * in light_sources have as much light on the map as they have in * light_sources (if the queue contains a node multiple times, the brightest * occurrence counts). * * \param bank the light bank in which the procedure operates * \param light_sources starting nodes * \param modified_blocks output, all modified map blocks are added to this */ void spread_light(Map *map, INodeDefManager *nodemgr, LightBank bank, LightQueue &light_sources, std::map<v3s16, MapBlock*> &modified_blocks) { // The light the current node can provide to its neighbors. u8 spreading_light; // The ChangingLight for the current node. ChangingLight current; // Position of the current neighbor. mapblock_v3 neighbor_block_pos; relative_v3 neighbor_rel_pos; // A dummy boolean. bool is_valid_position; while (light_sources.next(spreading_light, current)) { spreading_light--; for (direction i = 0; i < 6; i++) { // This node can't light up its light source if (current.source_direction + i == 5) { continue; } // Get the neighbor's position and block neighbor_rel_pos = current.rel_position; neighbor_block_pos = current.block_position; MapBlock *neighbor_block; if (step_rel_block_pos(i, neighbor_rel_pos, neighbor_block_pos)) { neighbor_block = map->getBlockNoCreateNoEx(neighbor_block_pos); if (neighbor_block == NULL) { current.block->setLightingComplete(bank, i, false); continue; } } else { neighbor_block = current.block; } // Get the neighbor itself MapNode neighbor = neighbor_block->getNodeNoCheck(neighbor_rel_pos, &is_valid_position); const ContentFeatures &f = nodemgr->get(neighbor.getContent()); if (f.light_propagates) { // Light up the neighbor, if it has less light than it should. u8 neighbor_light = neighbor.getLightRaw(bank, f); if (neighbor_light < spreading_light) { neighbor.setLight(bank, spreading_light, f); neighbor_block->setNodeNoCheck(neighbor_rel_pos, neighbor); light_sources.push(spreading_light, neighbor_rel_pos, neighbor_block_pos, neighbor_block, i); // The current node was modified earlier, so its block // is in modified_blocks. if (current.block != neighbor_block) { modified_blocks[neighbor_block_pos] = neighbor_block; } } } } } } struct SunlightPropagationUnit{ v2s16 relative_pos; bool is_sunlit; SunlightPropagationUnit(v2s16 relpos, bool sunlit): relative_pos(relpos), is_sunlit(sunlit) {} }; struct SunlightPropagationData{ std::vector<SunlightPropagationUnit> data; v3s16 target_block; }; /*! * Returns true if the node gets sunlight from the * node above it. * * \param pos position of the node. */ bool is_sunlight_above(Map *map, v3s16 pos, INodeDefManager *ndef) { bool sunlight = true; mapblock_v3 source_block_pos; relative_v3 source_rel_pos; getNodeBlockPosWithOffset(pos + v3s16(0, 1, 0), source_block_pos, source_rel_pos); // If the node above has sunlight, this node also can get it. MapBlock *source_block = map->getBlockNoCreateNoEx(source_block_pos); if (source_block == NULL) { // But if there is no node above, then use heuristics MapBlock *node_block = map->getBlockNoCreateNoEx(getNodeBlockPos(pos)); if (node_block == NULL) { sunlight = false; } else { sunlight = !node_block->getIsUnderground(); } } else { bool is_valid_position; MapNode above = source_block->getNodeNoCheck(source_rel_pos, &is_valid_position); if (is_valid_position) { if (above.getContent() == CONTENT_IGNORE) { // Trust heuristics if (source_block->getIsUnderground()) { sunlight = false; } } else if (above.getLight(LIGHTBANK_DAY, ndef) != LIGHT_SUN) { // If the node above doesn't have sunlight, this // node is in shadow. sunlight = false; } } } return sunlight; } static const LightBank banks[] = { LIGHTBANK_DAY, LIGHTBANK_NIGHT }; void update_lighting_nodes(Map *map, std::vector<std::pair<v3s16, MapNode> > &oldnodes, std::map<v3s16, MapBlock*> &modified_blocks) { INodeDefManager *ndef = map->getNodeDefManager(); // For node getter functions bool is_valid_position; // Process each light bank separately for (LightBank bank : banks) { UnlightQueue disappearing_lights(256); ReLightQueue light_sources(256); // Nodes that are brighter than the brightest modified node was // won't change, since they didn't get their light from a // modified node. u8 min_safe_light = 0; for (std::vector<std::pair<v3s16, MapNode> >::iterator it = oldnodes.begin(); it < oldnodes.end(); ++it) { u8 old_light = it->second.getLight(bank, ndef); if (old_light > min_safe_light) { min_safe_light = old_light; } } // If only one node changed, even nodes with the same brightness // didn't get their light from the changed node. if (oldnodes.size() > 1) { min_safe_light++; } // For each changed node process sunlight and initialize for (std::vector<std::pair<v3s16, MapNode> >::iterator it = oldnodes.begin(); it < oldnodes.end(); ++it) { // Get position and block of the changed node v3s16 p = it->first; relative_v3 rel_pos; mapblock_v3 block_pos; getNodeBlockPosWithOffset(p, block_pos, rel_pos); MapBlock *block = map->getBlockNoCreateNoEx(block_pos); if (block == NULL || block->isDummy()) { continue; } // Get the new node MapNode n = block->getNodeNoCheck(rel_pos, &is_valid_position); if (!is_valid_position) { break; } // Light of the old node u8 old_light = it->second.getLight(bank, ndef); // Add the block of the added node to modified_blocks modified_blocks[block_pos] = block; // Get new light level of the node u8 new_light = 0; if (ndef->get(n).light_propagates) { if (bank == LIGHTBANK_DAY && ndef->get(n).sunlight_propagates && is_sunlight_above(map, p, ndef)) { new_light = LIGHT_SUN; } else { new_light = ndef->get(n).light_source; for (const v3s16 &neighbor_dir : neighbor_dirs) { v3s16 p2 = p + neighbor_dir; bool is_valid; MapNode n2 = map->getNodeNoEx(p2, &is_valid); if (is_valid) { u8 spread = n2.getLight(bank, ndef); // If it is sure that the neighbor won't be // unlighted, its light can spread to this node. if (spread > new_light && spread >= min_safe_light) { new_light = spread - 1; } } } } } else { // If this is an opaque node, it still can emit light. new_light = ndef->get(n).light_source; } if (new_light > 0) { light_sources.push(new_light, rel_pos, block_pos, block, 6); } if (new_light < old_light) { // The node became opaque or doesn't provide as much // light as the previous one, so it must be unlighted. // Add to unlight queue n.setLight(bank, 0, ndef); block->setNodeNoCheck(rel_pos, n); disappearing_lights.push(old_light, rel_pos, block_pos, block, 6); // Remove sunlight, if there was any if (bank == LIGHTBANK_DAY && old_light == LIGHT_SUN) { for (s16 y = p.Y - 1;; y--) { v3s16 n2pos(p.X, y, p.Z); MapNode n2; n2 = map->getNodeNoEx(n2pos, &is_valid_position); if (!is_valid_position) break; // If this node doesn't have sunlight, the nodes below // it don't have too. if (n2.getLight(LIGHTBANK_DAY, ndef) != LIGHT_SUN) { break; } // Remove sunlight and add to unlight queue. n2.setLight(LIGHTBANK_DAY, 0, ndef); map->setNode(n2pos, n2); relative_v3 rel_pos2; mapblock_v3 block_pos2; getNodeBlockPosWithOffset(n2pos, block_pos2, rel_pos2); MapBlock *block2 = map->getBlockNoCreateNoEx( block_pos2); disappearing_lights.push(LIGHT_SUN, rel_pos2, block_pos2, block2, 4 /* The node above caused the change */); } } } else if (new_light > old_light) { // It is sure that the node provides more light than the previous // one, unlighting is not necessary. // Propagate sunlight if (bank == LIGHTBANK_DAY && new_light == LIGHT_SUN) { for (s16 y = p.Y - 1;; y--) { v3s16 n2pos(p.X, y, p.Z); MapNode n2; n2 = map->getNodeNoEx(n2pos, &is_valid_position); if (!is_valid_position) break; // This should not happen, but if the node has sunlight // then the iteration should stop. if (n2.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN) { break; } // If the node terminates sunlight, stop. if (!ndef->get(n2).sunlight_propagates) { break; } relative_v3 rel_pos2; mapblock_v3 block_pos2; getNodeBlockPosWithOffset(n2pos, block_pos2, rel_pos2); MapBlock *block2 = map->getBlockNoCreateNoEx( block_pos2); // Mark node for lighting. light_sources.push(LIGHT_SUN, rel_pos2, block_pos2, block2, 4); } } } } // Remove lights unspread_light(map, ndef, bank, disappearing_lights, light_sources, modified_blocks); // Initialize light values for light spreading. for (u8 i = 0; i <= LIGHT_SUN; i++) { const std::vector<ChangingLight> &lights = light_sources.lights[i]; for (std::vector<ChangingLight>::const_iterator it = lights.begin(); it < lights.end(); ++it) { MapNode n = it->block->getNodeNoCheck(it->rel_position, &is_valid_position); n.setLight(bank, i, ndef); it->block->setNodeNoCheck(it->rel_position, n); } } // Spread lights. spread_light(map, ndef, bank, light_sources, modified_blocks); } } /*! * Borders of a map block in relative node coordinates. * Compatible with type 'direction'. */ const VoxelArea block_borders[] = { VoxelArea(v3s16(15, 0, 0), v3s16(15, 15, 15)), //X+ VoxelArea(v3s16(0, 15, 0), v3s16(15, 15, 15)), //Y+ VoxelArea(v3s16(0, 0, 15), v3s16(15, 15, 15)), //Z+ VoxelArea(v3s16(0, 0, 0), v3s16(15, 15, 0)), //Z- VoxelArea(v3s16(0, 0, 0), v3s16(15, 0, 15)), //Y- VoxelArea(v3s16(0, 0, 0), v3s16(0, 15, 15)) //X- }; /*! * Returns true if: * -the node has unloaded neighbors * -the node doesn't have light * -the node's light is the same as the maximum of * its light source and its brightest neighbor minus one. * . */ bool is_light_locally_correct(Map *map, INodeDefManager *ndef, LightBank bank, v3s16 pos) { bool is_valid_position; MapNode n = map->getNodeNoEx(pos, &is_valid_position); const ContentFeatures &f = ndef->get(n); if (f.param_type != CPT_LIGHT) { return true; } u8 light = n.getLightNoChecks(bank, &f); assert(f.light_source <= LIGHT_MAX); u8 brightest_neighbor = f.light_source + 1; for (const v3s16 &neighbor_dir : neighbor_dirs) { MapNode n2 = map->getNodeNoEx(pos + neighbor_dir, &is_valid_position); u8 light2 = n2.getLight(bank, ndef); if (brightest_neighbor < light2) { brightest_neighbor = light2; } } assert(light <= LIGHT_SUN); return brightest_neighbor == light + 1; } void update_block_border_lighting(Map *map, MapBlock *block, std::map<v3s16, MapBlock*> &modified_blocks) { INodeDefManager *ndef = map->getNodeDefManager(); bool is_valid_position; for (LightBank bank : banks) { // Since invalid light is not common, do not allocate // memory if not needed. UnlightQueue disappearing_lights(0); ReLightQueue light_sources(0); // Get incorrect lights for (direction d = 0; d < 6; d++) { // For each direction // Get neighbor block v3s16 otherpos = block->getPos() + neighbor_dirs[d]; MapBlock *other = map->getBlockNoCreateNoEx(otherpos); if (other == NULL) { continue; } // Only update if lighting was not completed. if (block->isLightingComplete(bank, d) && other->isLightingComplete(bank, 5 - d)) continue; // Reset flags block->setLightingComplete(bank, d, true); other->setLightingComplete(bank, 5 - d, true); // The two blocks and their connecting surfaces MapBlock *blocks[] = {block, other}; VoxelArea areas[] = {block_borders[d], block_borders[5 - d]}; // For both blocks for (u8 blocknum = 0; blocknum < 2; blocknum++) { MapBlock *b = blocks[blocknum]; VoxelArea a = areas[blocknum]; // For all nodes for (s32 x = a.MinEdge.X; x <= a.MaxEdge.X; x++) for (s32 z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) for (s32 y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) { MapNode n = b->getNodeNoCheck(x, y, z, &is_valid_position); u8 light = n.getLight(bank, ndef); // Sunlight is fixed if (light < LIGHT_SUN) { // Unlight if not correct if (!is_light_locally_correct(map, ndef, bank, v3s16(x, y, z) + b->getPosRelative())) { // Initialize for unlighting n.setLight(bank, 0, ndef); b->setNodeNoCheck(x, y, z, n); modified_blocks[b->getPos()]=b; disappearing_lights.push(light, relative_v3(x, y, z), b->getPos(), b, 6); } } } } } // Remove lights unspread_light(map, ndef, bank, disappearing_lights, light_sources, modified_blocks); // Initialize light values for light spreading. for (u8 i = 0; i <= LIGHT_SUN; i++) { const std::vector<ChangingLight> &lights = light_sources.lights[i]; for (std::vector<ChangingLight>::const_iterator it = lights.begin(); it < lights.end(); ++it) { MapNode n = it->block->getNodeNoCheck(it->rel_position, &is_valid_position); n.setLight(bank, i, ndef); it->block->setNodeNoCheck(it->rel_position, n); } } // Spread lights. spread_light(map, ndef, bank, light_sources, modified_blocks); } } /*! * Resets the lighting of the given VoxelManipulator to * complete darkness and full sunlight. * Operates in one map sector. * * \param offset contains the least x and z node coordinates * of the map sector. * \param light incoming sunlight, light[x][z] is true if there * is sunlight above the voxel manipulator at the given x-z coordinates. * The array's indices are relative node coordinates in the sector. * After the procedure returns, this contains outgoing light at * the bottom of the voxel manipulator. */ void fill_with_sunlight(MMVManip *vm, INodeDefManager *ndef, v2s16 offset, bool light[MAP_BLOCKSIZE][MAP_BLOCKSIZE]) { // Distance in array between two nodes on top of each other. s16 ystride = vm->m_area.getExtent().X; // Cache the ignore node. MapNode ignore = MapNode(CONTENT_IGNORE); // For each column of nodes: for (s16 z = 0; z < MAP_BLOCKSIZE; z++) for (s16 x = 0; x < MAP_BLOCKSIZE; x++) { // Position of the column on the map. v2s16 realpos = offset + v2s16(x, z); // Array indices in the voxel manipulator s32 maxindex = vm->m_area.index(realpos.X, vm->m_area.MaxEdge.Y, realpos.Y); s32 minindex = vm->m_area.index(realpos.X, vm->m_area.MinEdge.Y, realpos.Y); // True if the current node has sunlight. bool lig = light[z][x]; // For each node, downwards: for (s32 i = maxindex; i >= minindex; i -= ystride) { MapNode *n; if (vm->m_flags[i] & VOXELFLAG_NO_DATA) n = &ignore; else n = &vm->m_data[i]; // Ignore IGNORE nodes, these are not generated yet. if(n->getContent() == CONTENT_IGNORE) continue; const ContentFeatures &f = ndef->get(n->getContent()); if (lig && !f.sunlight_propagates) // Sunlight is stopped. lig = false; // Reset light n->setLight(LIGHTBANK_DAY, lig ? 15 : 0, f); n->setLight(LIGHTBANK_NIGHT, 0, f); } // Output outgoing light. light[z][x] = lig; } } /*! * Returns incoming sunlight for one map block. * If block above is not found, it is loaded. * * \param pos position of the map block that gets the sunlight. * \param light incoming sunlight, light[z][x] is true if there * is sunlight above the block at the given z-x relative * node coordinates. */ void is_sunlight_above_block(ServerMap *map, mapblock_v3 pos, INodeDefManager *ndef, bool light[MAP_BLOCKSIZE][MAP_BLOCKSIZE]) { mapblock_v3 source_block_pos = pos + v3s16(0, 1, 0); // Get or load source block. // It might take a while to load, but correcting incorrect // sunlight may be even slower. MapBlock *source_block = map->emergeBlock(source_block_pos, false); // Trust only generated blocks. if (source_block == NULL || source_block->isDummy() || !source_block->isGenerated()) { // But if there is no block above, then use heuristics bool sunlight = true; MapBlock *node_block = map->getBlockNoCreateNoEx(pos); if (node_block == NULL) // This should not happen. sunlight = false; else sunlight = !node_block->getIsUnderground(); for (s16 z = 0; z < MAP_BLOCKSIZE; z++) for (s16 x = 0; x < MAP_BLOCKSIZE; x++) light[z][x] = sunlight; } else { // Dummy boolean, the position is valid. bool is_valid_position; // For each column: for (s16 z = 0; z < MAP_BLOCKSIZE; z++) for (s16 x = 0; x < MAP_BLOCKSIZE; x++) { // Get the bottom block. MapNode above = source_block->getNodeNoCheck(x, 0, z, &is_valid_position); light[z][x] = above.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN; } } } /*! * Propagates sunlight down in a given map block. * * \param data contains incoming sunlight and shadow and * the coordinates of the target block. * \param unlight propagated shadow is inserted here * \param relight propagated sunlight is inserted here * * \returns true if the block was modified, false otherwise. */ bool propagate_block_sunlight(Map *map, INodeDefManager *ndef, SunlightPropagationData *data, UnlightQueue *unlight, ReLightQueue *relight) { bool modified = false; // Get the block. MapBlock *block = map->getBlockNoCreateNoEx(data->target_block); if (block == NULL || block->isDummy()) { // The work is done if the block does not contain data. data->data.clear(); return false; } // Dummy boolean bool is_valid; // For each changing column of nodes: size_t index; for (index = 0; index < data->data.size(); index++) { SunlightPropagationUnit it = data->data[index]; // Relative position of the currently inspected node. relative_v3 current_pos(it.relative_pos.X, MAP_BLOCKSIZE - 1, it.relative_pos.Y); if (it.is_sunlit) { // Propagate sunlight. // For each node downwards: for (; current_pos.Y >= 0; current_pos.Y--) { MapNode n = block->getNodeNoCheck(current_pos, &is_valid); const ContentFeatures &f = ndef->get(n); if (n.getLightRaw(LIGHTBANK_DAY, f) < LIGHT_SUN && f.sunlight_propagates) { // This node gets sunlight. n.setLight(LIGHTBANK_DAY, LIGHT_SUN, f); block->setNodeNoCheck(current_pos, n); modified = true; relight->push(LIGHT_SUN, current_pos, data->target_block, block, 4); } else { // Light already valid, propagation stopped. break; } } } else { // Propagate shadow. // For each node downwards: for (; current_pos.Y >= 0; current_pos.Y--) { MapNode n = block->getNodeNoCheck(current_pos, &is_valid); const ContentFeatures &f = ndef->get(n); if (n.getLightRaw(LIGHTBANK_DAY, f) == LIGHT_SUN) { // The sunlight is no longer valid. n.setLight(LIGHTBANK_DAY, 0, f); block->setNodeNoCheck(current_pos, n); modified = true; unlight->push(LIGHT_SUN, current_pos, data->target_block, block, 4); } else { // Reached shadow, propagation stopped. break; } } } if (current_pos.Y >= 0) { // Propagation stopped, remove from data. data->data[index] = data->data.back(); data->data.pop_back(); index--; } } return modified; } /*! * Borders of a map block in relative node coordinates. * The areas do not overlap. * Compatible with type 'direction'. */ const VoxelArea block_pad[] = { VoxelArea(v3s16(15, 0, 0), v3s16(15, 15, 15)), //X+ VoxelArea(v3s16(1, 15, 0), v3s16(14, 15, 15)), //Y+ VoxelArea(v3s16(1, 1, 15), v3s16(14, 14, 15)), //Z+ VoxelArea(v3s16(1, 1, 0), v3s16(14, 14, 0)), //Z- VoxelArea(v3s16(1, 0, 0), v3s16(14, 0, 15)), //Y- VoxelArea(v3s16(0, 0, 0), v3s16(0, 15, 15)) //X- }; /*! * The common part of bulk light updates - it is always executed. * The procedure takes the nodes that should be unlit, and the * full modified area. * * The procedure handles the correction of all lighting except * direct sunlight spreading. * * \param minblock least coordinates of the changed area in block * coordinates * \param maxblock greatest coordinates of the changed area in block * coordinates * \param unlight the first queue is for day light, the second is for * night light. Contains all nodes on the borders that need to be unlit. * \param relight the first queue is for day light, the second is for * night light. Contains nodes that were not modified, but got sunlight * because the changes. * \param modified_blocks the procedure adds all modified blocks to * this map */ void finish_bulk_light_update(Map *map, mapblock_v3 minblock, mapblock_v3 maxblock, UnlightQueue unlight[2], ReLightQueue relight[2], std::map<v3s16, MapBlock*> *modified_blocks) { INodeDefManager *ndef = map->getNodeDefManager(); // dummy boolean bool is_valid; // --- STEP 1: Do unlighting for (size_t bank = 0; bank < 2; bank++) { LightBank b = banks[bank]; unspread_light(map, ndef, b, unlight[bank], relight[bank], *modified_blocks); } // --- STEP 2: Get all newly inserted light sources // For each block: for (s16 b_x = minblock.X; b_x <= maxblock.X; b_x++) for (s16 b_y = minblock.Y; b_y <= maxblock.Y; b_y++) for (s16 b_z = minblock.Z; b_z <= maxblock.Z; b_z++) { const v3s16 blockpos(b_x, b_y, b_z); MapBlock *block = map->getBlockNoCreateNoEx(blockpos); if (!block || block->isDummy()) // Skip not existing blocks continue; // For each node in the block: for (s32 x = 0; x < MAP_BLOCKSIZE; x++) for (s32 z = 0; z < MAP_BLOCKSIZE; z++) for (s32 y = 0; y < MAP_BLOCKSIZE; y++) { v3s16 relpos(x, y, z); MapNode node = block->getNodeNoCheck(x, y, z, &is_valid); const ContentFeatures &f = ndef->get(node); // For each light bank for (size_t b = 0; b < 2; b++) { LightBank bank = banks[b]; u8 light = f.param_type == CPT_LIGHT ? node.getLightNoChecks(bank, &f): f.light_source; if (light > 1) relight[b].push(light, relpos, blockpos, block, 6); } // end of banks } // end of nodes } // end of blocks // --- STEP 3: do light spreading // For each light bank: for (size_t b = 0; b < 2; b++) { LightBank bank = banks[b]; // Sunlight is already initialized. u8 maxlight = (b == 0) ? LIGHT_MAX : LIGHT_SUN; // Initialize light values for light spreading. for (u8 i = 0; i <= maxlight; i++) { const std::vector<ChangingLight> &lights = relight[b].lights[i]; for (std::vector<ChangingLight>::const_iterator it = lights.begin(); it < lights.end(); ++it) { MapNode n = it->block->getNodeNoCheck(it->rel_position, &is_valid); n.setLight(bank, i, ndef); it->block->setNodeNoCheck(it->rel_position, n); } } // Spread lights. spread_light(map, ndef, bank, relight[b], *modified_blocks); } } void blit_back_with_light(ServerMap *map, MMVManip *vm, std::map<v3s16, MapBlock*> *modified_blocks) { INodeDefManager *ndef = map->getNodeDefManager(); mapblock_v3 minblock = getNodeBlockPos(vm->m_area.MinEdge); mapblock_v3 maxblock = getNodeBlockPos(vm->m_area.MaxEdge); // First queue is for day light, second is for night light. UnlightQueue unlight[] = { UnlightQueue(256), UnlightQueue(256) }; ReLightQueue relight[] = { ReLightQueue(256), ReLightQueue(256) }; // Will hold sunlight data. bool lights[MAP_BLOCKSIZE][MAP_BLOCKSIZE]; SunlightPropagationData data; // Dummy boolean. bool is_valid; // --- STEP 1: reset everything to sunlight // For each map block: for (s16 x = minblock.X; x <= maxblock.X; x++) for (s16 z = minblock.Z; z <= maxblock.Z; z++) { // Extract sunlight above. is_sunlight_above_block(map, v3s16(x, maxblock.Y, z), ndef, lights); v2s16 offset(x, z); offset *= MAP_BLOCKSIZE; // Reset the voxel manipulator. fill_with_sunlight(vm, ndef, offset, lights); // Copy sunlight data data.target_block = v3s16(x, minblock.Y - 1, z); for (s16 z = 0; z < MAP_BLOCKSIZE; z++) for (s16 x = 0; x < MAP_BLOCKSIZE; x++) data.data.emplace_back(v2s16(x, z), lights[z][x]); // Propagate sunlight and shadow below the voxel manipulator. while (!data.data.empty()) { if (propagate_block_sunlight(map, ndef, &data, &unlight[0], &relight[0])) (*modified_blocks)[data.target_block] = map->getBlockNoCreateNoEx(data.target_block); // Step downwards. data.target_block.Y--; } } // --- STEP 2: Get nodes from borders to unlight // In case there are unloaded holes in the voxel manipulator // unlight each block. // For each block: for (s16 b_x = minblock.X; b_x <= maxblock.X; b_x++) for (s16 b_y = minblock.Y; b_y <= maxblock.Y; b_y++) for (s16 b_z = minblock.Z; b_z <= maxblock.Z; b_z++) { v3s16 blockpos(b_x, b_y, b_z); MapBlock *block = map->getBlockNoCreateNoEx(blockpos); if (!block || block->isDummy()) // Skip not existing blocks. continue; v3s16 offset = block->getPosRelative(); // For each border of the block: for (const VoxelArea &a : block_pad) { // For each node of the border: for (s32 x = a.MinEdge.X; x <= a.MaxEdge.X; x++) for (s32 z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) for (s32 y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) { v3s16 relpos(x, y, z); // Get old and new node MapNode oldnode = block->getNodeNoCheck(x, y, z, &is_valid); const ContentFeatures &oldf = ndef->get(oldnode); MapNode newnode = vm->getNodeNoExNoEmerge(relpos + offset); const ContentFeatures &newf = ndef->get(newnode); // For each light bank for (size_t b = 0; b < 2; b++) { LightBank bank = banks[b]; u8 oldlight = oldf.param_type == CPT_LIGHT ? oldnode.getLightNoChecks(bank, &oldf): LIGHT_SUN; // no light information, force unlighting u8 newlight = newf.param_type == CPT_LIGHT ? newnode.getLightNoChecks(bank, &newf): newf.light_source; // If the new node is dimmer, unlight. if (oldlight > newlight) { unlight[b].push( oldlight, relpos, blockpos, block, 6); } } // end of banks } // end of nodes } // end of borders } // end of blocks // --- STEP 3: All information extracted, overwrite vm->blitBackAll(modified_blocks, true); // --- STEP 4: Finish light update finish_bulk_light_update(map, minblock, maxblock, unlight, relight, modified_blocks); } /*! * Resets the lighting of the given map block to * complete darkness and full sunlight. * * \param light incoming sunlight, light[x][z] is true if there * is sunlight above the map block at the given x-z coordinates. * The array's indices are relative node coordinates in the block. * After the procedure returns, this contains outgoing light at * the bottom of the map block. */ void fill_with_sunlight(MapBlock *block, INodeDefManager *ndef, bool light[MAP_BLOCKSIZE][MAP_BLOCKSIZE]) { if (block->isDummy()) return; // dummy boolean bool is_valid; // For each column of nodes: for (s16 z = 0; z < MAP_BLOCKSIZE; z++) for (s16 x = 0; x < MAP_BLOCKSIZE; x++) { // True if the current node has sunlight. bool lig = light[z][x]; // For each node, downwards: for (s16 y = MAP_BLOCKSIZE - 1; y >= 0; y--) { MapNode n = block->getNodeNoCheck(x, y, z, &is_valid); // Ignore IGNORE nodes, these are not generated yet. if (n.getContent() == CONTENT_IGNORE) continue; const ContentFeatures &f = ndef->get(n.getContent()); if (lig && !f.sunlight_propagates) { // Sunlight is stopped. lig = false; } // Reset light n.setLight(LIGHTBANK_DAY, lig ? 15 : 0, f); n.setLight(LIGHTBANK_NIGHT, 0, f); block->setNodeNoCheck(x, y, z, n); } // Output outgoing light. light[z][x] = lig; } } void repair_block_light(ServerMap *map, MapBlock *block, std::map<v3s16, MapBlock*> *modified_blocks) { if (!block || block->isDummy()) return; INodeDefManager *ndef = map->getNodeDefManager(); // First queue is for day light, second is for night light. UnlightQueue unlight[] = { UnlightQueue(256), UnlightQueue(256) }; ReLightQueue relight[] = { ReLightQueue(256), ReLightQueue(256) }; // Will hold sunlight data. bool lights[MAP_BLOCKSIZE][MAP_BLOCKSIZE]; SunlightPropagationData data; // Dummy boolean. bool is_valid; // --- STEP 1: reset everything to sunlight mapblock_v3 blockpos = block->getPos(); (*modified_blocks)[blockpos] = block; // For each map block: // Extract sunlight above. is_sunlight_above_block(map, blockpos, ndef, lights); // Reset the voxel manipulator. fill_with_sunlight(block, ndef, lights); // Copy sunlight data data.target_block = v3s16(blockpos.X, blockpos.Y - 1, blockpos.Z); for (s16 z = 0; z < MAP_BLOCKSIZE; z++) for (s16 x = 0; x < MAP_BLOCKSIZE; x++) { data.data.emplace_back(v2s16(x, z), lights[z][x]); } // Propagate sunlight and shadow below the voxel manipulator. while (!data.data.empty()) { if (propagate_block_sunlight(map, ndef, &data, &unlight[0], &relight[0])) (*modified_blocks)[data.target_block] = map->getBlockNoCreateNoEx(data.target_block); // Step downwards. data.target_block.Y--; } // --- STEP 2: Get nodes from borders to unlight // For each border of the block: for (const VoxelArea &a : block_pad) { // For each node of the border: for (s32 x = a.MinEdge.X; x <= a.MaxEdge.X; x++) for (s32 z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++)