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