summaryrefslogtreecommitdiff
path: root/src/client/shadows/dynamicshadowsrender.cpp
blob: 07dc6daf265595b6bcba690b9f976bf2c5d77687 (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
/*
Minetest
Copyright (C) 2021 Liso <anlismon@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.
*/

#include <cstring>
#include <cmath>
#include "client/shadows/dynamicshadowsrender.h"
#include "client/shadows/shadowsScreenQuad.h"
#include "client/shadows/shadowsshadercallbacks.h"
#include "settings.h"
#include "filesys.h"
#include "util/string.h"
#include "client/shader.h"
#include "client/client.h"
#include "client/clientmap.h"
#include "profiler.h"

ShadowRenderer::ShadowRenderer(IrrlichtDevice *device, Client *client) :
		m_smgr(device->getSceneManager()), m_driver(device->getVideoDriver()),
		m_client(client), m_current_frame(0),
		m_perspective_bias_xy(0.8), m_perspective_bias_z(0.5)
{
	(void) m_client;

	m_shadows_supported = true; // assume shadows supported. We will check actual support in initialize
	m_shadows_enabled = true;

	m_shadow_strength_gamma = g_settings->getFloat("shadow_strength_gamma");
	if (std::isnan(m_shadow_strength_gamma))
		m_shadow_strength_gamma = 1.0f;
	m_shadow_strength_gamma = core::clamp(m_shadow_strength_gamma, 0.1f, 10.0f);

	m_shadow_map_max_distance = g_settings->getFloat("shadow_map_max_distance");

	m_shadow_map_texture_size = g_settings->getFloat("shadow_map_texture_size");

	m_shadow_map_texture_32bit = g_settings->getBool("shadow_map_texture_32bit");
	m_shadow_map_colored = g_settings->getBool("shadow_map_color");
	m_shadow_samples = g_settings->getS32("shadow_filters");
	m_map_shadow_update_frames = g_settings->getS16("shadow_update_frames");
}

ShadowRenderer::~ShadowRenderer()
{
	// call to disable releases dynamically allocated resources
	disable();

	if (m_shadow_depth_cb)
		delete m_shadow_depth_cb;
	if (m_shadow_depth_entity_cb)
		delete m_shadow_depth_entity_cb;
	if (m_shadow_depth_trans_cb)
		delete m_shadow_depth_trans_cb;
	if (m_shadow_mix_cb)
		delete m_shadow_mix_cb;
	m_shadow_node_array.clear();
	m_light_list.clear();

	if (shadowMapTextureDynamicObjects)
		m_driver->removeTexture(shadowMapTextureDynamicObjects);

	if (shadowMapTextureFinal)
		m_driver->removeTexture(shadowMapTextureFinal);

	if (shadowMapTextureColors)
		m_driver->removeTexture(shadowMapTextureColors);

	if (shadowMapClientMap)
		m_driver->removeTexture(shadowMapClientMap);

	if (shadowMapClientMapFuture)
		m_driver->removeTexture(shadowMapClientMapFuture);
}

void ShadowRenderer::disable()
{
	m_shadows_enabled = false;
	if (shadowMapTextureFinal) {
		m_driver->setRenderTarget(shadowMapTextureFinal, true, true,
			video::SColor(255, 255, 255, 255));
		m_driver->setRenderTarget(0, true, true);
	}
}

void ShadowRenderer::initialize()
{
	auto *gpu = m_driver->getGPUProgrammingServices();

	// we need glsl
	if (m_shadows_supported && gpu && m_driver->queryFeature(video::EVDF_ARB_GLSL)) {
		createShaders();
	} else {
		m_shadows_supported = false;

		warningstream << "Shadows: GLSL Shader not supported on this system."
			<< std::endl;
		return;
	}

	m_texture_format = m_shadow_map_texture_32bit
					   ? video::ECOLOR_FORMAT::ECF_R32F
					   : video::ECOLOR_FORMAT::ECF_R16F;

	m_texture_format_color = m_shadow_map_texture_32bit
						 ? video::ECOLOR_FORMAT::ECF_G32R32F
						 : video::ECOLOR_FORMAT::ECF_G16R16F;
	
	m_shadows_enabled &= m_shadows_supported;
}


size_t ShadowRenderer::addDirectionalLight()
{
	m_light_list.emplace_back(m_shadow_map_texture_size,
			v3f(0.f, 0.f, 0.f),
			video::SColor(255, 255, 255, 255), m_shadow_map_max_distance);
	return m_light_list.size() - 1;
}

DirectionalLight &ShadowRenderer::getDirectionalLight(u32 index)
{
	return m_light_list[index];
}

size_t ShadowRenderer::getDirectionalLightCount() const
{
	return m_light_list.size();
}

f32 ShadowRenderer::getMaxShadowFar() const
{
	if (!m_light_list.empty()) {
		float zMax = m_light_list[0].getFarValue();
		return zMax;
	}
	return 0.0f;
}

void ShadowRenderer::setShadowIntensity(float shadow_intensity)
{
	m_shadow_strength = pow(shadow_intensity, 1.0f / m_shadow_strength_gamma);
	if (m_shadow_strength > 1E-2)
		enable();
	else
		disable();
}

void ShadowRenderer::addNodeToShadowList(
		scene::ISceneNode *node, E_SHADOW_MODE shadowMode)
{
	m_shadow_node_array.emplace_back(NodeToApply(node, shadowMode));
}

void ShadowRenderer::removeNodeFromShadowList(scene::ISceneNode *node)
{
	for (auto it = m_shadow_node_array.begin(); it != m_shadow_node_array.end();) {
		if (it->node == node) {
			it = m_shadow_node_array.erase(it);
			break;
		} else {
			++it;
		}
	}
}

void ShadowRenderer::updateSMTextures()
{
	if (!m_shadows_enabled || m_smgr->getActiveCamera() == nullptr) {
		return;
	}

	if (!shadowMapTextureDynamicObjects) {

		shadowMapTextureDynamicObjects = getSMTexture(
			std::string("shadow_dynamic_") + itos(m_shadow_map_texture_size),
			m_texture_format, true);
		assert(shadowMapTextureDynamicObjects != nullptr);
	}

	if (!shadowMapClientMap) {

		shadowMapClientMap = getSMTexture(
			std::string("shadow_clientmap_") + itos(m_shadow_map_texture_size),
			m_shadow_map_colored ? m_texture_format_color : m_texture_format,
			true);
		assert(shadowMapClientMap != nullptr);
	}

	if (!shadowMapClientMapFuture && m_map_shadow_update_frames > 1) {
		shadowMapClientMapFuture = getSMTexture(
			std::string("shadow_clientmap_bb_") + itos(m_shadow_map_texture_size),
			m_shadow_map_colored ? m_texture_format_color : m_texture_format,
			true);
		assert(shadowMapClientMapFuture != nullptr);
	}

	if (m_shadow_map_colored && !shadowMapTextureColors) {
		shadowMapTextureColors = getSMTexture(
			std::string("shadow_colored_") + itos(m_shadow_map_texture_size),
			m_shadow_map_colored ? m_texture_format_color : m_texture_format,
			true);
		assert(shadowMapTextureColors != nullptr);
	}

	// The merge all shadowmaps texture
	if (!shadowMapTextureFinal) {
		video::ECOLOR_FORMAT frt;
		if (m_shadow_map_texture_32bit) {
			if (m_shadow_map_colored)
				frt = video::ECOLOR_FORMAT::ECF_A32B32G32R32F;
			else
				frt = video::ECOLOR_FORMAT::ECF_R32F;
		} else {
			if (m_shadow_map_colored)
				frt = video::ECOLOR_FORMAT::ECF_A16B16G16R16F;
			else
				frt = video::ECOLOR_FORMAT::ECF_R16F;
		}
		shadowMapTextureFinal = getSMTexture(
			std::string("shadowmap_final_") + itos(m_shadow_map_texture_size),
			frt, true);
		assert(shadowMapTextureFinal != nullptr);
	}

	if (!m_shadow_node_array.empty() && !m_light_list.empty()) {
		bool reset_sm_texture = false;

		// detect if SM should be regenerated
		for (DirectionalLight &light : m_light_list) {
			if (light.should_update_map_shadow) {
				light.should_update_map_shadow = false;
				m_current_frame = 0;
				reset_sm_texture = true;
			}
		}

		video::ITexture* shadowMapTargetTexture = shadowMapClientMapFuture;
		if (shadowMapTargetTexture == nullptr)
			shadowMapTargetTexture = shadowMapClientMap;

		// Update SM incrementally:
		for (DirectionalLight &light : m_light_list) {
			// Static shader values.
			for (auto cb : {m_shadow_depth_cb, m_shadow_depth_entity_cb, m_shadow_depth_trans_cb})
				if (cb) {
					cb->MapRes = (f32)m_shadow_map_texture_size;
					cb->MaxFar = (f32)m_shadow_map_max_distance * BS;
					cb->PerspectiveBiasXY = getPerspectiveBiasXY();
					cb->PerspectiveBiasZ = getPerspectiveBiasZ();
					cb->CameraPos = light.getFuturePlayerPos();
				}
			
			// set the Render Target
			// right now we can only render in usual RTT, not
			// Depth texture is available in irrlicth maybe we
			// should put some gl* fn here


			if (m_current_frame < m_map_shadow_update_frames) {
				m_driver->setRenderTarget(shadowMapTargetTexture, reset_sm_texture, true,
						video::SColor(255, 255, 255, 255));
				renderShadowMap(shadowMapTargetTexture, light);

				// Render transparent part in one pass.
				// This is also handled in ClientMap.
				if (m_current_frame == m_map_shadow_update_frames - 1) {
					if (m_shadow_map_colored) {
						m_driver->setRenderTarget(0, false, false);
						m_driver->setRenderTarget(shadowMapTextureColors,
								true, false, video::SColor(255, 255, 255, 255));
					}
					renderShadowMap(shadowMapTextureColors, light,
							scene::ESNRP_TRANSPARENT);
				}
				m_driver->setRenderTarget(0, false, false);
			}

			reset_sm_texture = false;
		} // end for lights

		// move to the next section
		if (m_current_frame <= m_map_shadow_update_frames)
			++m_current_frame;

		// pass finished, swap textures and commit light changes
		if (m_current_frame == m_map_shadow_update_frames) {
			if (shadowMapClientMapFuture != nullptr)
				std::swap(shadowMapClientMapFuture, shadowMapClientMap);

			// Let all lights know that maps are updated
			for (DirectionalLight &light : m_light_list)
				light.commitFrustum();
		}
	}
}

void ShadowRenderer::update(video::ITexture *outputTarget)
{
	if (!m_shadows_enabled || m_smgr->getActiveCamera() == nullptr) {
		return;
	}

	updateSMTextures();

	if (shadowMapTextureFinal == nullptr) {
		return;
	}

	if (!m_shadow_node_array.empty() && !m_light_list.empty()) {

		for (DirectionalLight &light : m_light_list) {
			// Static shader values for entities are set in updateSMTextures
			// SM texture for entities is not updated incrementally and 
			// must by updated using current player position.
			m_shadow_depth_entity_cb->CameraPos = light.getPlayerPos();

			// render shadows for the n0n-map objects.
			m_driver->setRenderTarget(shadowMapTextureDynamicObjects, true,
					true, video::SColor(255, 255, 255, 255));
			renderShadowObjects(shadowMapTextureDynamicObjects, light);
			// clear the Render Target
			m_driver->setRenderTarget(0, false, false);

			// in order to avoid too many map shadow renders,
			// we should make a second pass to mix clientmap shadows and
			// entities shadows :(
			m_screen_quad->getMaterial().setTexture(0, shadowMapClientMap);
			// dynamic objs shadow texture.
			if (m_shadow_map_colored)
				m_screen_quad->getMaterial().setTexture(1, shadowMapTextureColors);
			m_screen_quad->getMaterial().setTexture(2, shadowMapTextureDynamicObjects);

			m_driver->setRenderTarget(shadowMapTextureFinal, false, false,
					video::SColor(255, 255, 255, 255));
			m_screen_quad->render(m_driver);
			m_driver->setRenderTarget(0, false, false);

		} // end for lights
	}
}

void ShadowRenderer::drawDebug()
{
	/* this code just shows shadows textures in screen and in ONLY for debugging*/
	#if 0
	// this is debug, ignore for now.
	if (shadowMapTextureFinal)
		m_driver->draw2DImage(shadowMapTextureFinal,
				core::rect<s32>(0, 50, 128, 128 + 50),
				core::rect<s32>({0, 0}, shadowMapTextureFinal->getSize()));

	if (shadowMapClientMap)
		m_driver->draw2DImage(shadowMapClientMap,
				core::rect<s32>(0, 50 + 128, 128, 128 + 50 + 128),
				core::rect<s32>({0, 0}, shadowMapTextureFinal->getSize()));
	
	if (shadowMapTextureDynamicObjects)
		m_driver->draw2DImage(shadowMapTextureDynamicObjects,
				core::rect<s32>(0, 128 + 50 + 128, 128,
						128 + 50 + 128 + 128),
				core::rect<s32>({0, 0}, shadowMapTextureDynamicObjects->getSize()));

	if (m_shadow_map_colored && shadowMapTextureColors) {

		m_driver->draw2DImage(shadowMapTextureColors,
				core::rect<s32>(128,128 + 50 + 128 + 128,
						128 + 128, 128 + 50 + 128 + 128 + 128),
				core::rect<s32>({0, 0}, shadowMapTextureColors->getSize()));
	}
	#endif
}


video::ITexture *ShadowRenderer::getSMTexture(const std::string &shadow_map_name,
		video::ECOLOR_FORMAT texture_format, bool force_creation)
{
	if (force_creation) {
		return m_driver->addRenderTargetTexture(
				core::dimension2du(m_shadow_map_texture_size,
						m_shadow_map_texture_size),
				shadow_map_name.c_str(), texture_format);
	}

	return m_driver->getTexture(shadow_map_name.c_str());
}

void ShadowRenderer::renderShadowMap(video::ITexture *target,
		DirectionalLight &light, scene::E_SCENE_NODE_RENDER_PASS pass)
{
	m_driver->setTransform(video::ETS_VIEW, light.getFutureViewMatrix());
	m_driver->setTransform(video::ETS_PROJECTION, light.getFutureProjectionMatrix());

	// Operate on the client map
	for (const auto &shadow_node : m_shadow_node_array) {
		if (strcmp(shadow_node.node->getName(), "ClientMap") != 0)
			continue;

		ClientMap *map_node = static_cast<ClientMap *>(shadow_node.node);

		video::SMaterial material;
		if (map_node->getMaterialCount() > 0) {
			// we only want the first material, which is the one with the albedo info
			material = map_node->getMaterial(0);
		}

		material.BackfaceCulling = false;
		material.FrontfaceCulling = true;

		if (m_shadow_map_colored && pass != scene::ESNRP_SOLID) {
			material.MaterialType = (video::E_MATERIAL_TYPE) depth_shader_trans;
		}
		else {
			material.MaterialType = (video::E_MATERIAL_TYPE) depth_shader;
			material.BlendOperation = video::EBO_MIN;
		}

		m_driver->setTransform(video::ETS_WORLD,
				map_node->getAbsoluteTransformation());

		map_node->renderMapShadows(m_driver, material, pass, m_current_frame, m_map_shadow_update_frames);
		break;
	}
}

void ShadowRenderer::renderShadowObjects(
		video::ITexture *target, DirectionalLight &light)
{
	m_driver->setTransform(video::ETS_VIEW, light.getViewMatrix());
	m_driver->setTransform(video::ETS_PROJECTION, light.getProjectionMatrix());

	for (const auto &shadow_node : m_shadow_node_array) {
		// we only take care of the shadow casters
		if (shadow_node.shadowMode == ESM_RECEIVE ||
				strcmp(shadow_node.node->getName(), "ClientMap") == 0)
			continue;

		// render other objects
		u32 n_node_materials = shadow_node.node->getMaterialCount();
		std::vector<s32> BufferMaterialList;
		std::vector<std::pair<bool, bool>> BufferMaterialCullingList;
		std::vector<video::E_BLEND_OPERATION> BufferBlendOperationList;
		BufferMaterialList.reserve(n_node_materials);
		BufferMaterialCullingList.reserve(n_node_materials);
		BufferBlendOperationList.reserve(n_node_materials);

		// backup materialtype for each material
		// (aka shader)
		// and replace it by our "depth" shader
		for (u32 m = 0; m < n_node_materials; m++) {
			auto &current_mat = shadow_node.node->getMaterial(m);

			BufferMaterialList.push_back(current_mat.MaterialType);
			current_mat.MaterialType =
					(video::E_MATERIAL_TYPE)depth_shader_entities;

			BufferMaterialCullingList.emplace_back(
				(bool)current_mat.BackfaceCulling, (bool)current_mat.FrontfaceCulling);
			BufferBlendOperationList.push_back(current_mat.BlendOperation);

			current_mat.BackfaceCulling = true;
			current_mat.FrontfaceCulling = false;
		}

		m_driver->setTransform(video::ETS_WORLD,
				shadow_node.node->getAbsoluteTransformation());
		shadow_node.node->render();

		// restore the material.

		for (u32 m = 0; m < n_node_materials; m++) {
			auto &current_mat = shadow_node.node->getMaterial(m);

			current_mat.MaterialType = (video::E_MATERIAL_TYPE) BufferMaterialList[m];

			current_mat.BackfaceCulling = BufferMaterialCullingList[m].first;
			current_mat.FrontfaceCulling = BufferMaterialCullingList[m].second;
			current_mat.BlendOperation = BufferBlendOperationList[m];
		}

	} // end for caster shadow nodes
}

void ShadowRenderer::mixShadowsQuad()
{
}

/*
 * @Liso's disclaimer ;) This function loads the Shadow Mapping Shaders.
 * I used a custom loader because I couldn't figure out how to use the base
 * Shaders system with custom IShaderConstantSetCallBack without messing up the
 * code too much. If anyone knows how to integrate this with the standard MT
 * shaders, please feel free to change it.
 */

void ShadowRenderer::createShaders()
{
	video::IGPUProgrammingServices *gpu = m_driver->getGPUProgrammingServices();

	if (depth_shader == -1) {
		std::string depth_shader_vs = getShaderPath("shadow_shaders", "pass1_vertex.glsl");
		if (depth_shader_vs.empty()) {
			m_shadows_supported = false;
			errorstream << "Error shadow mapping vs shader not found." << std::endl;
			return;
		}
		std::string depth_shader_fs = getShaderPath("shadow_shaders", "pass1_fragment.glsl");
		if (depth_shader_fs.empty()) {
			m_shadows_supported = false;
			errorstream << "Error shadow mapping fs shader not found." << std::endl;
			return;
		}
		m_shadow_depth_cb = new ShadowDepthShaderCB();

		depth_shader = gpu->addHighLevelShaderMaterial(
				readShaderFile(depth_shader_vs).c_str(), "vertexMain",
				video::EVST_VS_1_1,
				readShaderFile(depth_shader_fs).c_str(), "pixelMain",
				video::EPST_PS_1_2, m_shadow_depth_cb, video::EMT_ONETEXTURE_BLEND);

		if (depth_shader == -1) {
			// upsi, something went wrong loading shader.
			delete m_shadow_depth_cb;
			m_shadow_depth_cb = nullptr;
			m_shadows_enabled = false;
			m_shadows_supported = false;
			errorstream << "Error compiling shadow mapping shader." << std::endl;
			return;
		}

		// HACK, TODO: investigate this better
		// Grab the material renderer once more so minetest doesn't crash
		// on exit
		m_driver->getMaterialRenderer(depth_shader)->grab();
	}

	// This creates a clone of depth_shader with base material set to EMT_SOLID,
	// because entities won't render shadows with base material EMP_ONETEXTURE_BLEND
	if (depth_shader_entities == -1) {
		std::string depth_shader_vs = getShaderPath("shadow_shaders", "pass1_vertex.glsl");
		if (depth_shader_vs.empty()) {
			m_shadows_supported = false;
			errorstream << "Error shadow mapping vs shader not found." << std::endl;
			return;
		}
		std::string depth_shader_fs = getShaderPath("shadow_shaders", "pass1_fragment.glsl");
		if (depth_shader_fs.empty()) {
			m_shadows_supported = false;
			errorstream << "Error shadow mapping fs shader not found." << std::endl;
			return;
		}
		m_shadow_depth_entity_cb = new ShadowDepthShaderCB();

		depth_shader_entities = gpu->addHighLevelShaderMaterial(
				readShaderFile(depth_shader_vs).c_str(), "vertexMain",
				video::EVST_VS_1_1,
				readShaderFile(depth_shader_fs).c_str(), "pixelMain",
				video::EPST_PS_1_2, m_shadow_depth_entity_cb);

		if (depth_shader_entities == -1) {
			// upsi, something went wrong loading shader.
			delete m_shadow_depth_entity_cb;
			m_shadow_depth_entity_cb = nullptr;
			m_shadows_enabled = false;
			m_shadows_supported = false;
			errorstream << "Error compiling shadow mapping shader (dynamic)." << std::endl;
			return;
		}

		// HACK, TODO: investigate this better
		// Grab the material renderer once more so minetest doesn't crash
		// on exit
		m_driver->getMaterialRenderer(depth_shader_entities)->grab();
	}

	if (mixcsm_shader == -1) {
		std::string depth_shader_vs = getShaderPath("shadow_shaders", "pass2_vertex.glsl");
		if (depth_shader_vs.empty()) {
			m_shadows_supported = false;
			errorstream << "Error cascade shadow mapping fs shader not found." << std::endl;
			return;
		}

		std::string depth_shader_fs = getShaderPath("shadow_shaders", "pass2_fragment.glsl");
		if (depth_shader_fs.empty()) {
			m_shadows_supported = false;
			errorstream << "Error cascade shadow mapping fs shader not found." << std::endl;
			return;
		}
		m_shadow_mix_cb = new shadowScreenQuadCB();
		m_screen_quad = new shadowScreenQuad();
		mixcsm_shader = gpu->addHighLevelShaderMaterial(
				readShaderFile(depth_shader_vs).c_str(), "vertexMain",
				video::EVST_VS_1_1,
				readShaderFile(depth_shader_fs).c_str(), "pixelMain",
				video::EPST_PS_1_2, m_shadow_mix_cb);

		m_screen_quad->getMaterial().MaterialType =
				(video::E_MATERIAL_TYPE)mixcsm_shader;

		if (mixcsm_shader == -1) {
			// upsi, something went wrong loading shader.
			delete m_shadow_mix_cb;
			delete m_screen_quad;
			m_shadows_supported = false;
			errorstream << "Error compiling cascade shadow mapping shader." << std::endl;
			return;
		}

		// HACK, TODO: investigate this better
		// Grab the material renderer once more so minetest doesn't crash
		// on exit
		m_driver->getMaterialRenderer(mixcsm_shader)->grab();
	}

	if (m_shadow_map_colored && depth_shader_trans == -1) {
		std::string depth_shader_vs = getShaderPath("shadow_shaders", "pass1_trans_vertex.glsl");
		if (depth_shader_vs.empty()) {
			m_shadows_supported = false;
			errorstream << "Error shadow mapping vs shader not found." << std::endl;
			return;
		}
		std::string depth_shader_fs = getShaderPath("shadow_shaders", "pass1_trans_fragment.glsl");
		if (depth_shader_fs.empty()) {
			m_shadows_supported = false;
			errorstream << "Error shadow mapping fs shader not found." << std::endl;
			return;
		}
		m_shadow_depth_trans_cb = new ShadowDepthShaderCB();

		depth_shader_trans = gpu->addHighLevelShaderMaterial(
				readShaderFile(depth_shader_vs).c_str(), "vertexMain",
				video::EVST_VS_1_1,
				readShaderFile(depth_shader_fs).c_str(), "pixelMain",
				video::EPST_PS_1_2, m_shadow_depth_trans_cb);

		if (depth_shader_trans == -1) {
			// upsi, something went wrong loading shader.
			delete m_shadow_depth_trans_cb;
			m_shadow_depth_trans_cb = nullptr;
			m_shadow_map_colored = false;
			m_shadows_supported = false;
			errorstream << "Error compiling colored shadow mapping shader." << std::endl;
			return;
		}

		// HACK, TODO: investigate this better
		// Grab the material renderer once more so minetest doesn't crash
		// on exit
		m_driver->getMaterialRenderer(depth_shader_trans)->grab();
	}
}

std::string ShadowRenderer::readShaderFile(const std::string &path)
{
	std::string prefix;
	if (m_shadow_map_colored)
		prefix.append("#define COLORED_SHADOWS 1\n");

	std::string content;
	fs::ReadFile(path, content);

	return prefix + content;
}