]> git.lizzy.rs Git - minetest.git/blob - src/client/sky.cpp
Provide fallback star color for GLES 2 with MT shaders disabled
[minetest.git] / src / client / sky.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2020 numzero, Lobachevskiy Vitaliy <numzer0@yandex.ru>
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "sky.h"
22 #include "ITexture.h"
23 #include "IVideoDriver.h"
24 #include "ISceneManager.h"
25 #include "ICameraSceneNode.h"
26 #include "S3DVertex.h"
27 #include "client/tile.h"
28 #include "noise.h" // easeCurve
29 #include "profiler.h"
30 #include "util/numeric.h"
31 #include <cmath>
32 #include "client/renderingengine.h"
33 #include "settings.h"
34 #include "camera.h" // CameraModes
35 #include "config.h"
36 using namespace irr::core;
37
38 static video::SMaterial baseMaterial() {
39         video::SMaterial mat;
40         mat.Lighting = false;
41 #if ENABLE_GLES
42         mat.ZBuffer = video::ECFN_DISABLED;
43 #else
44         mat.ZBuffer = video::ECFN_NEVER;
45 #endif
46         mat.ZWriteEnable = false;
47         mat.AntiAliasing = 0;
48         mat.TextureLayer[0].TextureWrapU = video::ETC_CLAMP_TO_EDGE;
49         mat.TextureLayer[0].TextureWrapV = video::ETC_CLAMP_TO_EDGE;
50         mat.BackfaceCulling = false;
51         return mat;
52 };
53
54 Sky::Sky(s32 id, ITextureSource *tsrc, IShaderSource *ssrc) :
55                 scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(),
56                         RenderingEngine::get_scene_manager(), id)
57 {
58         setAutomaticCulling(scene::EAC_OFF);
59         m_box.MaxEdge.set(0, 0, 0);
60         m_box.MinEdge.set(0, 0, 0);
61
62         m_enable_shaders = g_settings->getBool("enable_shaders");
63
64         // Create materials
65
66         m_materials[0] = baseMaterial();
67         m_materials[0].MaterialType = ssrc->getShaderInfo(ssrc->getShader("stars_shader", TILE_MATERIAL_ALPHA, 0)).material;
68         m_materials[0].Lighting = true;
69         m_materials[0].ColorMaterial = video::ECM_NONE;
70
71         m_materials[1] = baseMaterial();
72         //m_materials[1].MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
73         m_materials[1].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
74
75         m_materials[2] = baseMaterial();
76         m_materials[2].setTexture(0, tsrc->getTextureForMesh("sunrisebg.png"));
77         m_materials[2].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
78         //m_materials[2].MaterialType = video::EMT_TRANSPARENT_ADD_COLOR;
79
80         // Ensures that sun and moon textures and tonemaps are correct.
81         setSkyDefaults();
82         m_sun_texture = tsrc->isKnownSourceImage(m_sun_params.texture) ?
83                 tsrc->getTextureForMesh(m_sun_params.texture) : NULL;
84         m_moon_texture = tsrc->isKnownSourceImage(m_moon_params.texture) ?
85                 tsrc->getTextureForMesh(m_moon_params.texture) : NULL;
86         m_sun_tonemap = tsrc->isKnownSourceImage(m_sun_params.tonemap) ?
87                 tsrc->getTexture(m_sun_params.tonemap) : NULL;
88         m_moon_tonemap = tsrc->isKnownSourceImage(m_moon_params.tonemap) ?
89                 tsrc->getTexture(m_moon_params.tonemap) : NULL;
90
91         if (m_sun_texture) {
92                 m_materials[3] = baseMaterial();
93                 m_materials[3].setTexture(0, m_sun_texture);
94                 m_materials[3].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
95                 // Disables texture filtering
96                 m_materials[3].setFlag(video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false);
97                 m_materials[3].setFlag(video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false);
98                 m_materials[3].setFlag(video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false);
99                 // Use tonemaps if available
100                 if (m_sun_tonemap)
101                         m_materials[3].Lighting = true;
102         }
103         if (m_moon_texture) {
104                 m_materials[4] = baseMaterial();
105                 m_materials[4].setTexture(0, m_moon_texture);
106                 m_materials[4].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
107                 // Disables texture filtering
108                 m_materials[4].setFlag(video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false);
109                 m_materials[4].setFlag(video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false);
110                 m_materials[4].setFlag(video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false);
111                 // Use tonemaps if available
112                 if (m_moon_tonemap)
113                         m_materials[4].Lighting = true;
114         }
115
116         for (int i = 5; i < 11; i++) {
117                 m_materials[i] = baseMaterial();
118                 m_materials[i].Lighting = true;
119                 m_materials[i].MaterialType = video::EMT_SOLID;
120         }
121         m_directional_colored_fog = g_settings->getBool("directional_colored_fog");
122         setStarCount(1000, true);
123 }
124
125 void Sky::OnRegisterSceneNode()
126 {
127         if (IsVisible)
128                 SceneManager->registerNodeForRendering(this, scene::ESNRP_SKY_BOX);
129
130         scene::ISceneNode::OnRegisterSceneNode();
131 }
132
133 void Sky::render()
134 {
135         video::IVideoDriver *driver = SceneManager->getVideoDriver();
136         scene::ICameraSceneNode *camera = SceneManager->getActiveCamera();
137
138         if (!camera || !driver)
139                 return;
140
141         ScopeProfiler sp(g_profiler, "Sky::render()", SPT_AVG);
142
143         // Draw perspective skybox
144
145         core::matrix4 translate(AbsoluteTransformation);
146         translate.setTranslation(camera->getAbsolutePosition());
147
148         // Draw the sky box between the near and far clip plane
149         const f32 viewDistance = (camera->getNearValue() + camera->getFarValue()) * 0.5f;
150         core::matrix4 scale;
151         scale.setScale(core::vector3df(viewDistance, viewDistance, viewDistance));
152
153         driver->setTransform(video::ETS_WORLD, translate * scale);
154
155         if (m_sunlight_seen) {
156                 float sunsize = 0.07;
157                 video::SColorf suncolor_f(1, 1, 0, 1);
158                 //suncolor_f.r = 1;
159                 //suncolor_f.g = MYMAX(0.3, MYMIN(1.0, 0.7 + m_time_brightness * 0.5));
160                 //suncolor_f.b = MYMAX(0.0, m_brightness * 0.95);
161                 video::SColorf suncolor2_f(1, 1, 1, 1);
162                 // The values below were probably meant to be suncolor2_f instead of a
163                 // reassignment of suncolor_f. However, the resulting colour was chosen
164                 // and is our long-running classic colour. So preserve, but comment-out
165                 // the unnecessary first assignments above.
166                 suncolor_f.r = 1;
167                 suncolor_f.g = MYMAX(0.3, MYMIN(1.0, 0.85 + m_time_brightness * 0.5));
168                 suncolor_f.b = MYMAX(0.0, m_brightness);
169
170                 float moonsize = 0.04;
171                 video::SColorf mooncolor_f(0.50, 0.57, 0.65, 1);
172                 video::SColorf mooncolor2_f(0.85, 0.875, 0.9, 1);
173
174                 float nightlength = 0.415;
175                 float wn = nightlength / 2;
176                 float wicked_time_of_day = 0;
177                 if (m_time_of_day > wn && m_time_of_day < 1.0 - wn)
178                         wicked_time_of_day = (m_time_of_day - wn) / (1.0 - wn * 2) * 0.5 + 0.25;
179                 else if (m_time_of_day < 0.5)
180                         wicked_time_of_day = m_time_of_day / wn * 0.25;
181                 else
182                         wicked_time_of_day = 1.0 - ((1.0 - m_time_of_day) / wn * 0.25);
183                 /*std::cerr<<"time_of_day="<<m_time_of_day<<" -> "
184                                 <<"wicked_time_of_day="<<wicked_time_of_day<<std::endl;*/
185
186                 video::SColor suncolor = suncolor_f.toSColor();
187                 video::SColor suncolor2 = suncolor2_f.toSColor();
188                 video::SColor mooncolor = mooncolor_f.toSColor();
189                 video::SColor mooncolor2 = mooncolor2_f.toSColor();
190
191                 // Calculate offset normalized to the X dimension of a 512x1 px tonemap
192                 float offset = (1.0 - fabs(sin((m_time_of_day - 0.5) * irr::core::PI))) * 511;
193
194                 if (m_sun_tonemap) {
195                         u8 * texels = (u8 *)m_sun_tonemap->lock();
196                         video::SColor* texel = (video::SColor *)(texels + (u32)offset * 4);
197                         video::SColor texel_color (255, texel->getRed(),
198                                 texel->getGreen(), texel->getBlue());
199                         m_sun_tonemap->unlock();
200                         m_materials[3].EmissiveColor = texel_color;
201                 }
202
203                 if (m_moon_tonemap) {
204                         u8 * texels = (u8 *)m_moon_tonemap->lock();
205                         video::SColor* texel = (video::SColor *)(texels + (u32)offset * 4);
206                         video::SColor texel_color (255, texel->getRed(),
207                                 texel->getGreen(), texel->getBlue());
208                         m_moon_tonemap->unlock();
209                         m_materials[4].EmissiveColor = texel_color;
210                 }
211
212                 const f32 t = 1.0f;
213                 const f32 o = 0.0f;
214                 static const u16 indices[6] = {0, 1, 2, 0, 2, 3};
215                 video::S3DVertex vertices[4];
216
217                 driver->setMaterial(m_materials[1]);
218
219                 video::SColor cloudyfogcolor = m_bgcolor;
220
221                 // Abort rendering if we're in the clouds.
222                 // Stops rendering a pure white hole in the bottom of the skybox.
223                 if (m_in_clouds)
224                         return;
225
226                 // Draw the six sided skybox,
227                 if (m_sky_params.textures.size() == 6) {
228                         for (u32 j = 5; j < 11; j++) {
229                                 video::SColor c(255, 255, 255, 255);
230                                 driver->setMaterial(m_materials[j]);
231                                 // Use 1.05 rather than 1.0 to avoid colliding with the
232                                 // sun, moon and stars, as this is a background skybox.
233                                 vertices[0] = video::S3DVertex(-1.05, -1.05, -1.05, 0, 0, 1, c, t, t);
234                                 vertices[1] = video::S3DVertex( 1.05, -1.05, -1.05, 0, 0, 1, c, o, t);
235                                 vertices[2] = video::S3DVertex( 1.05,  1.05, -1.05, 0, 0, 1, c, o, o);
236                                 vertices[3] = video::S3DVertex(-1.05,  1.05, -1.05, 0, 0, 1, c, t, o);
237                                 for (video::S3DVertex &vertex : vertices) {
238                                         if (j == 5) { // Top texture
239                                                 vertex.Pos.rotateYZBy(90);
240                                                 vertex.Pos.rotateXZBy(90);
241                                         } else if (j == 6) { // Bottom texture
242                                                 vertex.Pos.rotateYZBy(-90);
243                                                 vertex.Pos.rotateXZBy(90);
244                                         } else if (j == 7) { // Left texture
245                                                 vertex.Pos.rotateXZBy(90);
246                                         } else if (j == 8) { // Right texture
247                                                 vertex.Pos.rotateXZBy(-90);
248                                         } else if (j == 9) { // Front texture, do nothing
249                                                 // Irrlicht doesn't like it when vertexes are left
250                                                 // alone and not rotated for some reason.
251                                                 vertex.Pos.rotateXZBy(0);
252                                         } else {// Back texture
253                                                 vertex.Pos.rotateXZBy(180);
254                                         }
255                                 }
256                                 driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
257                         }
258                 }
259
260                 // Draw far cloudy fog thing blended with skycolor
261                 if (m_visible) {
262                         driver->setMaterial(m_materials[1]);
263                         for (u32 j = 0; j < 4; j++) {
264                                 vertices[0] = video::S3DVertex(-1, -0.02, -1, 0, 0, 1, m_bgcolor, t, t);
265                                 vertices[1] = video::S3DVertex( 1, -0.02, -1, 0, 0, 1, m_bgcolor, o, t);
266                                 vertices[2] = video::S3DVertex( 1, 0.45, -1, 0, 0, 1, m_skycolor, o, o);
267                                 vertices[3] = video::S3DVertex(-1, 0.45, -1, 0, 0, 1, m_skycolor, t, o);
268                                 for (video::S3DVertex &vertex : vertices) {
269                                         if (j == 0)
270                                                 // Don't switch
271                                                 {}
272                                         else if (j == 1)
273                                                 // Switch from -Z (south) to +X (east)
274                                                 vertex.Pos.rotateXZBy(90);
275                                         else if (j == 2)
276                                                 // Switch from -Z (south) to -X (west)
277                                                 vertex.Pos.rotateXZBy(-90);
278                                         else
279                                                 // Switch from -Z (south) to +Z (north)
280                                                 vertex.Pos.rotateXZBy(-180);
281                                 }
282                                 driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
283                         }
284                 }
285
286                 // Draw stars before sun and moon to be behind them
287                 if (m_star_params.visible)
288                         draw_stars(driver, wicked_time_of_day);
289
290                 // Draw sunrise/sunset horizon glow texture
291                 // (textures/base/pack/sunrisebg.png)
292                 if (m_sun_params.sunrise_visible) {
293                         driver->setMaterial(m_materials[2]);
294                         float mid1 = 0.25;
295                         float mid = wicked_time_of_day < 0.5 ? mid1 : (1.0 - mid1);
296                         float a_ = 1.0f - std::fabs(wicked_time_of_day - mid) * 35.0f;
297                         float a = easeCurve(MYMAX(0, MYMIN(1, a_)));
298                         //std::cerr<<"a_="<<a_<<" a="<<a<<std::endl;
299                         video::SColor c(255, 255, 255, 255);
300                         float y = -(1.0 - a) * 0.22;
301                         vertices[0] = video::S3DVertex(-1, -0.05 + y, -1, 0, 0, 1, c, t, t);
302                         vertices[1] = video::S3DVertex( 1, -0.05 + y, -1, 0, 0, 1, c, o, t);
303                         vertices[2] = video::S3DVertex( 1,   0.2 + y, -1, 0, 0, 1, c, o, o);
304                         vertices[3] = video::S3DVertex(-1,   0.2 + y, -1, 0, 0, 1, c, t, o);
305                         for (video::S3DVertex &vertex : vertices) {
306                                 if (wicked_time_of_day < 0.5)
307                                         // Switch from -Z (south) to +X (east)
308                                         vertex.Pos.rotateXZBy(90);
309                                 else
310                                         // Switch from -Z (south) to -X (west)
311                                         vertex.Pos.rotateXZBy(-90);
312                         }
313                         driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
314                 }
315
316                 // Draw sun
317                 if (m_sun_params.visible)
318                         draw_sun(driver, sunsize, suncolor, suncolor2, wicked_time_of_day);
319
320                 // Draw moon
321                 if (m_moon_params.visible)
322                         draw_moon(driver, moonsize, mooncolor, mooncolor2, wicked_time_of_day);
323
324                 // Draw far cloudy fog thing below all horizons in front of sun, moon
325                 // and stars.
326                 if (m_visible) {
327                         driver->setMaterial(m_materials[1]);
328
329                         for (u32 j = 0; j < 4; j++) {
330                                 video::SColor c = cloudyfogcolor;
331                                 vertices[0] = video::S3DVertex(-1, -1.0,  -1, 0, 0, 1, c, t, t);
332                                 vertices[1] = video::S3DVertex( 1, -1.0,  -1, 0, 0, 1, c, o, t);
333                                 vertices[2] = video::S3DVertex( 1, -0.02, -1, 0, 0, 1, c, o, o);
334                                 vertices[3] = video::S3DVertex(-1, -0.02, -1, 0, 0, 1, c, t, o);
335                                 for (video::S3DVertex &vertex : vertices) {
336                                         if (j == 0)
337                                                 // Don't switch
338                                                 {}
339                                         else if (j == 1)
340                                                 // Switch from -Z (south) to +X (east)
341                                                 vertex.Pos.rotateXZBy(90);
342                                         else if (j == 2)
343                                                 // Switch from -Z (south) to -X (west)
344                                                 vertex.Pos.rotateXZBy(-90);
345                                         else
346                                                 // Switch from -Z (south) to +Z (north)
347                                                 vertex.Pos.rotateXZBy(-180);
348                                 }
349                                 driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
350                         }
351
352                         // Draw bottom far cloudy fog thing in front of sun, moon and stars
353                         video::SColor c = cloudyfogcolor;
354                         vertices[0] = video::S3DVertex(-1, -1.0, -1, 0, 1, 0, c, t, t);
355                         vertices[1] = video::S3DVertex( 1, -1.0, -1, 0, 1, 0, c, o, t);
356                         vertices[2] = video::S3DVertex( 1, -1.0, 1, 0, 1, 0, c, o, o);
357                         vertices[3] = video::S3DVertex(-1, -1.0, 1, 0, 1, 0, c, t, o);
358                         driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
359                 }
360         }
361 }
362
363 void Sky::update(float time_of_day, float time_brightness,
364         float direct_brightness, bool sunlight_seen,
365         CameraMode cam_mode, float yaw, float pitch)
366 {
367         // Stabilize initial brightness and color values by flooding updates
368         if (m_first_update) {
369                 /*dstream<<"First update with time_of_day="<<time_of_day
370                                 <<" time_brightness="<<time_brightness
371                                 <<" direct_brightness="<<direct_brightness
372                                 <<" sunlight_seen="<<sunlight_seen<<std::endl;*/
373                 m_first_update = false;
374                 for (u32 i = 0; i < 100; i++) {
375                         update(time_of_day, time_brightness, direct_brightness,
376                                         sunlight_seen, cam_mode, yaw, pitch);
377                 }
378                 return;
379         }
380
381         m_time_of_day = time_of_day;
382         m_time_brightness = time_brightness;
383         m_sunlight_seen = sunlight_seen;
384         m_in_clouds = false;
385
386         bool is_dawn = (time_brightness >= 0.20 && time_brightness < 0.35);
387
388         /*
389         Development colours
390
391         video::SColorf bgcolor_bright_normal_f(170. / 255, 200. / 255, 230. / 255, 1.0);
392         video::SColorf bgcolor_bright_dawn_f(0.666, 200. / 255 * 0.7, 230. / 255 * 0.5, 1.0);
393         video::SColorf bgcolor_bright_dawn_f(0.666, 0.549, 0.220, 1.0);
394         video::SColorf bgcolor_bright_dawn_f(0.666 * 1.2, 0.549 * 1.0, 0.220 * 1.0, 1.0);
395         video::SColorf bgcolor_bright_dawn_f(0.666 * 1.2, 0.549 * 1.0, 0.220 * 1.2, 1.0);
396
397         video::SColorf cloudcolor_bright_dawn_f(1.0, 0.591, 0.4);
398         video::SColorf cloudcolor_bright_dawn_f(1.0, 0.65, 0.44);
399         video::SColorf cloudcolor_bright_dawn_f(1.0, 0.7, 0.5);
400         */
401
402         video::SColorf bgcolor_bright_normal_f = m_sky_params.sky_color.day_horizon;
403         video::SColorf bgcolor_bright_indoor_f = m_sky_params.sky_color.indoors;
404         video::SColorf bgcolor_bright_dawn_f = m_sky_params.sky_color.dawn_horizon;
405         video::SColorf bgcolor_bright_night_f = m_sky_params.sky_color.night_horizon;
406
407         video::SColorf skycolor_bright_normal_f = m_sky_params.sky_color.day_sky;
408         video::SColorf skycolor_bright_dawn_f = m_sky_params.sky_color.dawn_sky;
409         video::SColorf skycolor_bright_night_f = m_sky_params.sky_color.night_sky;
410
411         video::SColorf cloudcolor_bright_normal_f = m_cloudcolor_day_f;
412         video::SColorf cloudcolor_bright_dawn_f = m_cloudcolor_dawn_f;
413
414         float cloud_color_change_fraction = 0.95;
415         if (sunlight_seen) {
416                 if (std::fabs(time_brightness - m_brightness) < 0.2f) {
417                         m_brightness = m_brightness * 0.95 + time_brightness * 0.05;
418                 } else {
419                         m_brightness = m_brightness * 0.80 + time_brightness * 0.20;
420                         cloud_color_change_fraction = 0.0;
421                 }
422         } else {
423                 if (direct_brightness < m_brightness)
424                         m_brightness = m_brightness * 0.95 + direct_brightness * 0.05;
425                 else
426                         m_brightness = m_brightness * 0.98 + direct_brightness * 0.02;
427         }
428
429         m_clouds_visible = true;
430         float color_change_fraction = 0.98f;
431         if (sunlight_seen) {
432                 if (is_dawn) { // Dawn
433                         m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated(
434                                 bgcolor_bright_dawn_f, color_change_fraction);
435                         m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated(
436                                 skycolor_bright_dawn_f, color_change_fraction);
437                         m_cloudcolor_bright_f = m_cloudcolor_bright_f.getInterpolated(
438                                 cloudcolor_bright_dawn_f, color_change_fraction);
439                 } else {
440                         if (time_brightness < 0.13f) { // Night
441                                 m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated(
442                                         bgcolor_bright_night_f, color_change_fraction);
443                                 m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated(
444                                         skycolor_bright_night_f, color_change_fraction);
445                         } else { // Day
446                                 m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated(
447                                         bgcolor_bright_normal_f, color_change_fraction);
448                                 m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated(
449                                         skycolor_bright_normal_f, color_change_fraction);
450                         }
451
452                         m_cloudcolor_bright_f = m_cloudcolor_bright_f.getInterpolated(
453                                 cloudcolor_bright_normal_f, color_change_fraction);
454                 }
455         } else {
456                 m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated(
457                         bgcolor_bright_indoor_f, color_change_fraction);
458                 m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated(
459                         bgcolor_bright_indoor_f, color_change_fraction);
460                 m_cloudcolor_bright_f = m_cloudcolor_bright_f.getInterpolated(
461                         cloudcolor_bright_normal_f, color_change_fraction);
462                 m_clouds_visible = false;
463         }
464
465         video::SColor bgcolor_bright = m_bgcolor_bright_f.toSColor();
466         m_bgcolor = video::SColor(
467                 255,
468                 bgcolor_bright.getRed() * m_brightness,
469                 bgcolor_bright.getGreen() * m_brightness,
470                 bgcolor_bright.getBlue() * m_brightness
471         );
472
473         video::SColor skycolor_bright = m_skycolor_bright_f.toSColor();
474         m_skycolor = video::SColor(
475                 255,
476                 skycolor_bright.getRed() * m_brightness,
477                 skycolor_bright.getGreen() * m_brightness,
478                 skycolor_bright.getBlue() * m_brightness
479         );
480
481         // Horizon coloring based on sun and moon direction during sunset and sunrise
482         video::SColor pointcolor = video::SColor(m_bgcolor.getAlpha(), 255, 255, 255);
483         if (m_directional_colored_fog) {
484                 if (m_horizon_blend() != 0) {
485                         // Calculate hemisphere value from yaw, (inverted in third person front view)
486                         s8 dir_factor = 1;
487                         if (cam_mode > CAMERA_MODE_THIRD)
488                                 dir_factor = -1;
489                         f32 pointcolor_blend = wrapDegrees_0_360(yaw * dir_factor + 90);
490                         if (pointcolor_blend > 180)
491                                 pointcolor_blend = 360 - pointcolor_blend;
492                         pointcolor_blend /= 180;
493                         // Bound view angle to determine where transition starts and ends
494                         pointcolor_blend = rangelim(1 - pointcolor_blend * 1.375, 0, 1 / 1.375) *
495                                 1.375;
496                         // Combine the colors when looking up or down, otherwise turning looks weird
497                         pointcolor_blend += (0.5 - pointcolor_blend) *
498                                 (1 - MYMIN((90 - std::fabs(pitch)) / 90 * 1.5, 1));
499                         // Invert direction to match where the sun and moon are rising
500                         if (m_time_of_day > 0.5)
501                                 pointcolor_blend = 1 - pointcolor_blend;
502                         // Horizon colors of sun and moon
503                         f32 pointcolor_light = rangelim(m_time_brightness * 3, 0.2, 1);
504
505                         video::SColorf pointcolor_sun_f(1, 1, 1, 1);
506                         // Use tonemap only if default sun/moon tinting is used
507                         // which keeps previous behaviour.
508                         if (m_sun_tonemap && m_default_tint) {
509                                 pointcolor_sun_f.r = pointcolor_light *
510                                         (float)m_materials[3].EmissiveColor.getRed() / 255;
511                                 pointcolor_sun_f.b = pointcolor_light *
512                                         (float)m_materials[3].EmissiveColor.getBlue() / 255;
513                                 pointcolor_sun_f.g = pointcolor_light *
514                                         (float)m_materials[3].EmissiveColor.getGreen() / 255;
515                         } else if (!m_default_tint) {
516                                 pointcolor_sun_f = m_sky_params.fog_sun_tint;
517                         } else {
518                                 pointcolor_sun_f.r = pointcolor_light * 1;
519                                 pointcolor_sun_f.b = pointcolor_light *
520                                         (0.25 + (rangelim(m_time_brightness, 0.25, 0.75) - 0.25) * 2 * 0.75);
521                                 pointcolor_sun_f.g = pointcolor_light * (pointcolor_sun_f.b * 0.375 +
522                                         (rangelim(m_time_brightness, 0.05, 0.15) - 0.05) * 10 * 0.625);
523                         }
524
525                         video::SColorf pointcolor_moon_f;
526                         if (m_default_tint) {
527                                 pointcolor_moon_f = video::SColorf(
528                                         0.5 * pointcolor_light,
529                                         0.6 * pointcolor_light,
530                                         0.8 * pointcolor_light,
531                                         1
532                                 );
533                         } else {
534                                 pointcolor_moon_f = video::SColorf(
535                                         (m_sky_params.fog_moon_tint.getRed() / 255) * pointcolor_light,
536                                         (m_sky_params.fog_moon_tint.getGreen() / 255) * pointcolor_light,
537                                         (m_sky_params.fog_moon_tint.getBlue() / 255) * pointcolor_light,
538                                         1
539                                 );
540                         }
541                         if (m_moon_tonemap && m_default_tint) {
542                                 pointcolor_moon_f.r = pointcolor_light *
543                                         (float)m_materials[4].EmissiveColor.getRed() / 255;
544                                 pointcolor_moon_f.b = pointcolor_light *
545                                         (float)m_materials[4].EmissiveColor.getBlue() / 255;
546                                 pointcolor_moon_f.g = pointcolor_light *
547                                         (float)m_materials[4].EmissiveColor.getGreen() / 255;
548                         }
549
550                         video::SColor pointcolor_sun = pointcolor_sun_f.toSColor();
551                         video::SColor pointcolor_moon = pointcolor_moon_f.toSColor();
552                         // Calculate the blend color
553                         pointcolor = m_mix_scolor(pointcolor_moon, pointcolor_sun, pointcolor_blend);
554                 }
555                 m_bgcolor = m_mix_scolor(m_bgcolor, pointcolor, m_horizon_blend() * 0.5);
556                 m_skycolor = m_mix_scolor(m_skycolor, pointcolor, m_horizon_blend() * 0.25);
557         }
558
559         float cloud_direct_brightness = 0.0f;
560         if (sunlight_seen) {
561                 if (!m_directional_colored_fog) {
562                         cloud_direct_brightness = time_brightness;
563                         // Boost cloud brightness relative to sky, at dawn, dusk and at night
564                         if (time_brightness < 0.7f)
565                                 cloud_direct_brightness *= 1.3f;
566                 } else {
567                         cloud_direct_brightness = std::fmin(m_horizon_blend() * 0.15f +
568                                 m_time_brightness, 1.0f);
569                         // Set the same minimum cloud brightness at night
570                         if (time_brightness < 0.5f)
571                                 cloud_direct_brightness = std::fmax(cloud_direct_brightness,
572                                         time_brightness * 1.3f);
573                 }
574         } else {
575                 cloud_direct_brightness = direct_brightness;
576         }
577
578         m_cloud_brightness = m_cloud_brightness * cloud_color_change_fraction +
579                 cloud_direct_brightness * (1.0 - cloud_color_change_fraction);
580         m_cloudcolor_f = video::SColorf(
581                 m_cloudcolor_bright_f.r * m_cloud_brightness,
582                 m_cloudcolor_bright_f.g * m_cloud_brightness,
583                 m_cloudcolor_bright_f.b * m_cloud_brightness,
584                 1.0
585         );
586         if (m_directional_colored_fog) {
587                 m_cloudcolor_f = m_mix_scolorf(m_cloudcolor_f,
588                         video::SColorf(pointcolor), m_horizon_blend() * 0.25);
589         }
590 }
591
592 void Sky::draw_sun(video::IVideoDriver *driver, float sunsize, const video::SColor &suncolor,
593         const video::SColor &suncolor2, float wicked_time_of_day)
594         /* Draw sun in the sky.
595          * driver: Video driver object used to draw
596          * sunsize: the default size of the sun
597          * suncolor: main sun color
598          * suncolor2: second sun color
599          * wicked_time_of_day: current time of day, to know where should be the sun in the sky
600          */
601 {
602         static const u16 indices[] = {0, 1, 2, 0, 2, 3};
603         std::array<video::S3DVertex, 4> vertices;
604         if (!m_sun_texture) {
605                 driver->setMaterial(m_materials[1]);
606                 const float sunsizes[4] = {
607                         (sunsize * 1.7f) * m_sun_params.scale,
608                         (sunsize * 1.2f) * m_sun_params.scale,
609                         (sunsize) * m_sun_params.scale,
610                         (sunsize * 0.7f) * m_sun_params.scale
611                 };
612                 video::SColor c1 = suncolor;
613                 video::SColor c2 = suncolor;
614                 c1.setAlpha(0.05 * 255);
615                 c2.setAlpha(0.15 * 255);
616                 const video::SColor colors[4] = {c1, c2, suncolor, suncolor2};
617                 for (int i = 0; i < 4; i++) {
618                         draw_sky_body(vertices, -sunsizes[i], sunsizes[i], colors[i]);
619                         place_sky_body(vertices, 90, wicked_time_of_day * 360 - 90);
620                         driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
621                 }
622         } else {
623                 driver->setMaterial(m_materials[3]);
624                 float d = (sunsize * 1.7) * m_sun_params.scale;
625                 video::SColor c;
626                 if (m_sun_tonemap)
627                         c = video::SColor(0, 0, 0, 0);
628                 else
629                         c = video::SColor(255, 255, 255, 255);
630                 draw_sky_body(vertices, -d, d, c);
631                 place_sky_body(vertices, 90, wicked_time_of_day * 360 - 90);
632                 driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
633         }
634 }
635
636
637 void Sky::draw_moon(video::IVideoDriver *driver, float moonsize, const video::SColor &mooncolor,
638         const video::SColor &mooncolor2, float wicked_time_of_day)
639 /*
640         * Draw moon in the sky.
641         * driver: Video driver object used to draw
642         * moonsize: the default size of the moon
643         * mooncolor: main moon color
644         * mooncolor2: second moon color
645         * wicked_time_of_day: current time of day, to know where should be the moon in
646         * the sky
647         */
648 {
649         static const u16 indices[] = {0, 1, 2, 0, 2, 3};
650         std::array<video::S3DVertex, 4> vertices;
651         if (!m_moon_texture) {
652                 driver->setMaterial(m_materials[1]);
653                 const float moonsizes_1[4] = {
654                         (-moonsize * 1.9f) * m_moon_params.scale,
655                         (-moonsize * 1.3f) * m_moon_params.scale,
656                         (-moonsize) * m_moon_params.scale,
657                         (-moonsize) * m_moon_params.scale
658                 };
659                 const float moonsizes_2[4] = {
660                         (moonsize * 1.9f) * m_moon_params.scale,
661                         (moonsize * 1.3f) * m_moon_params.scale,
662                         (moonsize) *m_moon_params.scale,
663                         (moonsize * 0.6f) * m_moon_params.scale
664                 };
665                 video::SColor c1 = mooncolor;
666                 video::SColor c2 = mooncolor;
667                 c1.setAlpha(0.05 * 255);
668                 c2.setAlpha(0.15 * 255);
669                 const video::SColor colors[4] = {c1, c2, mooncolor, mooncolor2};
670                 for (int i = 0; i < 4; i++) {
671                         draw_sky_body(vertices, moonsizes_1[i], moonsizes_2[i], colors[i]);
672                         place_sky_body(vertices, -90, wicked_time_of_day * 360 - 90);
673                         driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
674                 }
675         } else {
676                 driver->setMaterial(m_materials[4]);
677                 float d = (moonsize * 1.9) * m_moon_params.scale;
678                 video::SColor c;
679                 if (m_moon_tonemap)
680                         c = video::SColor(0, 0, 0, 0);
681                 else
682                         c = video::SColor(255, 255, 255, 255);
683                 draw_sky_body(vertices, -d, d, c);
684                 place_sky_body(vertices, -90, wicked_time_of_day * 360 - 90);
685                 driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
686         }
687 }
688
689 void Sky::draw_stars(video::IVideoDriver * driver, float wicked_time_of_day)
690 {
691         // Tune values so that stars first appear just after the sun
692         // disappears over the horizon, and disappear just before the sun
693         // appears over the horizon.
694         // Also tune so that stars are at full brightness from time 20000
695         // to time 4000.
696
697         float tod = wicked_time_of_day < 0.5f ? wicked_time_of_day : (1.0f - wicked_time_of_day);
698         float starbrightness = (0.25f - fabsf(tod)) * 20.0f;
699         m_star_color = m_star_params.starcolor;
700         m_star_color.a = clamp(starbrightness * m_star_color.a, 0.0f, 1.0f);
701         if (m_star_color.a <= 0.0f) // Stars are only drawn when not fully transparent
702                 return;
703         m_materials[0].DiffuseColor = m_materials[0].EmissiveColor = m_star_color.toSColor();
704         auto sky_rotation = core::matrix4().setRotationAxisRadians(2.0f * M_PI * (wicked_time_of_day - 0.25f), v3f(0.0f, 0.0f, 1.0f));
705         auto world_matrix = driver->getTransform(video::ETS_WORLD);
706         driver->setTransform(video::ETS_WORLD, world_matrix * sky_rotation);
707         driver->setMaterial(m_materials[0]);
708         driver->drawMeshBuffer(m_stars.get());
709         driver->setTransform(video::ETS_WORLD, world_matrix);
710 }
711
712 void Sky::draw_sky_body(std::array<video::S3DVertex, 4> &vertices, float pos_1, float pos_2, const video::SColor &c)
713 {
714         /*
715         * Create an array of vertices with the dimensions specified.
716         * pos_1, pos_2: position of the body's vertices
717         * c: color of the body
718         */
719
720         const f32 t = 1.0f;
721         const f32 o = 0.0f;
722         vertices[0] = video::S3DVertex(pos_1, pos_1, -1, 0, 0, 1, c, t, t);
723         vertices[1] = video::S3DVertex(pos_2, pos_1, -1, 0, 0, 1, c, o, t);
724         vertices[2] = video::S3DVertex(pos_2, pos_2, -1, 0, 0, 1, c, o, o);
725         vertices[3] = video::S3DVertex(pos_1, pos_2, -1, 0, 0, 1, c, t, o);
726 }
727
728
729 void Sky::place_sky_body(
730         std::array<video::S3DVertex, 4> &vertices, float horizon_position, float day_position)
731         /*
732         * Place body in the sky.
733         * vertices: The body as a rectangle of 4 vertices
734         * horizon_position: turn the body around the Y axis
735         * day_position: turn the body around the Z axis, to place it depending of the time of the day
736         */
737 {
738         for (video::S3DVertex &vertex : vertices) {
739                 // Body is directed to -Z (south) by default
740                 vertex.Pos.rotateXZBy(horizon_position);
741                 vertex.Pos.rotateXYBy(day_position);
742         }
743 }
744
745 void Sky::setSunTexture(std::string sun_texture,
746                 std::string sun_tonemap, ITextureSource *tsrc)
747 {
748         // Ignore matching textures (with modifiers) entirely,
749         // but lets at least update the tonemap before hand.
750         m_sun_params.tonemap = sun_tonemap;
751         m_sun_tonemap = tsrc->isKnownSourceImage(m_sun_params.tonemap) ?
752                 tsrc->getTexture(m_sun_params.tonemap) : NULL;
753         m_materials[3].Lighting = !!m_sun_tonemap;
754
755         if (m_sun_params.texture == sun_texture)
756                 return;
757         m_sun_params.texture = sun_texture;
758
759         if (sun_texture != "") {
760                 // We want to ensure the texture exists first.
761                 m_sun_texture = tsrc->getTextureForMesh(m_sun_params.texture);
762
763                 if (m_sun_texture) {
764                         m_materials[3] = baseMaterial();
765                         m_materials[3].setTexture(0, m_sun_texture);
766                         m_materials[3].MaterialType = video::
767                                 EMT_TRANSPARENT_ALPHA_CHANNEL;
768                         // Disables texture filtering
769                         m_materials[3].setFlag(
770                                 video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false);
771                         m_materials[3].setFlag(
772                                 video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false);
773                         m_materials[3].setFlag(
774                                 video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false);
775                 }
776         } else {
777                 m_sun_texture = nullptr;
778         }
779 }
780
781 void Sky::setSunriseTexture(std::string sunglow_texture,
782                 ITextureSource* tsrc)
783 {
784         // Ignore matching textures (with modifiers) entirely.
785         if (m_sun_params.sunrise == sunglow_texture)
786                 return;
787         m_sun_params.sunrise = sunglow_texture;
788         m_materials[2].setTexture(0, tsrc->getTextureForMesh(
789                 sunglow_texture.empty() ? "sunrisebg.png" : sunglow_texture)
790         );
791 }
792
793 void Sky::setMoonTexture(std::string moon_texture,
794                 std::string moon_tonemap, ITextureSource *tsrc)
795 {
796         // Ignore matching textures (with modifiers) entirely,
797         // but lets at least update the tonemap before hand.
798         m_moon_params.tonemap = moon_tonemap;
799         m_moon_tonemap = tsrc->isKnownSourceImage(m_moon_params.tonemap) ?
800                 tsrc->getTexture(m_moon_params.tonemap) : NULL;
801         m_materials[4].Lighting = !!m_moon_tonemap;
802
803         if (m_moon_params.texture == moon_texture)
804                 return;
805         m_moon_params.texture = moon_texture;
806
807         if (moon_texture != "") {
808                 // We want to ensure the texture exists first.
809                 m_moon_texture = tsrc->getTextureForMesh(m_moon_params.texture);
810
811                 if (m_moon_texture) {
812                         m_materials[4] = baseMaterial();
813                         m_materials[4].setTexture(0, m_moon_texture);
814                         m_materials[4].MaterialType = video::
815                                 EMT_TRANSPARENT_ALPHA_CHANNEL;
816                         // Disables texture filtering
817                         m_materials[4].setFlag(
818                                 video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false);
819                         m_materials[4].setFlag(
820                                 video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false);
821                         m_materials[4].setFlag(
822                                 video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false);
823                 }
824         } else {
825                 m_moon_texture = nullptr;
826         }
827 }
828
829 void Sky::setStarCount(u16 star_count, bool force_update)
830 {
831         // Allow force updating star count at game init.
832         if (m_star_params.count != star_count || force_update) {
833                 m_star_params.count = star_count;
834                 m_seed = (u64)myrand() << 32 | myrand();
835                 updateStars();
836         }
837 }
838
839 void Sky::updateStars() {
840         m_stars.reset(new scene::SMeshBuffer());
841         // Stupid IrrLicht doesn’t allow non-indexed rendering, and indexed quad
842         // rendering is slow due to lack of hardware support. So as indices are
843         // 16-bit and there are 4 vertices per star... the limit is 2^16/4 = 0x4000.
844         // That should be well enough actually.
845         if (m_star_params.count > 0x4000) {
846                 warningstream << "Requested " << m_star_params.count << " stars but " << 0x4000 << " is the max\n";
847                 m_star_params.count = 0x4000;
848         }
849         m_stars->Vertices.reallocate(4 * m_star_params.count);
850         m_stars->Indices.reallocate(6 * m_star_params.count);
851
852         video::SColor fallback_color = m_star_params.starcolor; // used on GLES 2 “without shaders”
853         PcgRandom rgen(m_seed);
854         float d = (0.006 / 2) * m_star_params.scale;
855         for (u16 i = 0; i < m_star_params.count; i++) {
856                 v3f r = v3f(
857                         rgen.range(-10000, 10000),
858                         rgen.range(-10000, 10000),
859                         rgen.range(-10000, 10000)
860                 );
861                 core::CMatrix4<f32> a;
862                 a.buildRotateFromTo(v3f(0, 1, 0), r);
863                 v3f p = v3f(-d, 1, -d);
864                 v3f p1 = v3f(d, 1, -d);
865                 v3f p2 = v3f(d, 1, d);
866                 v3f p3 = v3f(-d, 1, d);
867                 a.rotateVect(p);
868                 a.rotateVect(p1);
869                 a.rotateVect(p2);
870                 a.rotateVect(p3);
871                 m_stars->Vertices.push_back(video::S3DVertex(p, {}, fallback_color, {}));
872                 m_stars->Vertices.push_back(video::S3DVertex(p1, {}, fallback_color, {}));
873                 m_stars->Vertices.push_back(video::S3DVertex(p2, {}, fallback_color, {}));
874                 m_stars->Vertices.push_back(video::S3DVertex(p3, {}, fallback_color, {}));
875         }
876         for (u16 i = 0; i < m_star_params.count; i++) {
877                 m_stars->Indices.push_back(i * 4 + 0);
878                 m_stars->Indices.push_back(i * 4 + 1);
879                 m_stars->Indices.push_back(i * 4 + 2);
880                 m_stars->Indices.push_back(i * 4 + 2);
881                 m_stars->Indices.push_back(i * 4 + 3);
882                 m_stars->Indices.push_back(i * 4 + 0);
883         }
884         m_stars->setHardwareMappingHint(scene::EHM_STATIC);
885 }
886
887 void Sky::setSkyColors(const SkyColor &sky_color)
888 {
889         m_sky_params.sky_color = sky_color;
890 }
891
892 void Sky::setHorizonTint(video::SColor sun_tint, video::SColor moon_tint,
893                 std::string use_sun_tint)
894 {
895         // Change sun and moon tinting:
896         m_sky_params.fog_sun_tint = sun_tint;
897         m_sky_params.fog_moon_tint = moon_tint;
898         // Faster than comparing strings every rendering frame
899         if (use_sun_tint == "default")
900                 m_default_tint = true;
901         else if (use_sun_tint == "custom")
902                 m_default_tint = false;
903         else
904                 m_default_tint = true;
905 }
906
907 void Sky::addTextureToSkybox(std::string texture, int material_id,
908                 ITextureSource *tsrc)
909 {
910         // Sanity check for more than six textures.
911         if (material_id + 5 >= SKY_MATERIAL_COUNT)
912                 return;
913         // Keep a list of texture names handy.
914         m_sky_params.textures.emplace_back(texture);
915         video::ITexture *result = tsrc->getTextureForMesh(texture);
916         m_materials[material_id+5] = baseMaterial();
917         m_materials[material_id+5].setTexture(0, result);
918         m_materials[material_id+5].MaterialType = video::EMT_SOLID;
919 }
920
921 // To be called once at game init to setup default values.
922 void Sky::setSkyDefaults()
923 {
924         SkyboxDefaults sky_defaults;
925         m_sky_params.sky_color = sky_defaults.getSkyColorDefaults();
926         m_sun_params = sky_defaults.getSunDefaults();
927         m_moon_params = sky_defaults.getMoonDefaults();
928         m_star_params = sky_defaults.getStarDefaults();
929 }