diff --git a/gl/glsl_common.cpp b/gl/glsl_common.cpp index 981d7b05e..799698e3b 100644 --- a/gl/glsl_common.cpp +++ b/gl/glsl_common.cpp @@ -95,6 +95,7 @@ void gl::glsl_common_setup() "#define HEADLIGHT_SHADOW_TEX " + std::to_string(HEADLIGHT_SHADOW_TEX) + "\n" + "#define MAX_HEADLIGHT_SHADOWS " + std::to_string(MAX_HEADLIGHT_SHADOWS) + "U\n" + "#define MAX_CAB_PROBE_LAMPS " + std::to_string(MAX_CAB_PROBE_LAMPS) + "U\n" + + "#define WIPER_PASS_BUCKETS " + std::to_string(WIPER_PASS_BUCKETS) + "\n" + "#define FOG_VOLUME_TEX " + std::to_string(FOG_VOLUME_TEX) + "\n" + "#define CLOUD_SHADOW_TEX " + std::to_string(CLOUD_SHADOW_TEX) + "\n" + "#define CLOUD_TEX " + std::to_string(CLOUD_TEX) + "\n" + diff --git a/gl/ubo.h b/gl/ubo.h index 8f2619f01..5ca886945 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -4,6 +4,7 @@ #include "bindable.h" #include "buffer.h" #include +#include #include #include #include @@ -69,6 +70,9 @@ namespace gl const size_t MAX_HEADLIGHT_SHADOWS = 4; // lights of the occupied cab the probe of the cab is drawn with (gfx::cab_probe, gl::scene_ubs::cab_probe_lamp), at most const size_t MAX_CAB_PROBE_LAMPS = 16; + // the places along the sweep of a blade (dWiperPos 0 .. 1) the rain fallen when it last went over them is kept for + // (gl::scene_ubs::wiper_rain_pass) + const size_t WIPER_PASS_BUCKETS = 64; // weather (opengl46_weather): the fog of the main view (3d, apply_fog.glsl) and the shadows the clouds cast (2d), read by the // shading. bound directly, like the ones above const size_t FOG_VOLUME_TEX = MAX_TEXTURES + HELPER_TEXTURES + 4; @@ -202,9 +206,32 @@ namespace gl // world with them, inv_view and its modelview (the moment of its animation from its place) glm::vec4 camera_hi; glm::vec4 camera_lo; + // the rain the glass meets (mat_rain_windscreen): x the rain fallen so far, in seconds of the heaviest rain standing still (more + // at speed: the glass runs into it); y how wet the glass is, 0 dry .. 1 as full of drops as it gets (it fills with the rain, + // dries when it stops); z how fast the glass fills: the share left to fill goes down as exp(-z x the rain fallen); w unused + glm::vec4 rain_state; + // the rain fallen (rain_state.x) when a blade last went over a place of its sweep: element b for the places b / 64 .. (b + 1) + // / 64 of dWiperPos (the value of the wiper mask of a pixel), x .. w the blades (as wiper_pos); -1 not known. the drops and the + // haze come back with the rain fallen since. (the moments the blades were at the ends of their sweep, which the pixel took + // the one of by the way the blade went, gave the rain of a whole sweep back to the place a blade had just wiped) + glm::vec4 wiper_rain_pass[WIPER_PASS_BUCKETS]; }; - static_assert(sizeof(scene_ubs) == 992 + 80 * MAX_HEADLIGHT_SHADOWS + 96 * MAX_CAB_PROBE_LAMPS, "bad size of ubs"); + static_assert(sizeof(scene_ubs) == 1008 + 16 * WIPER_PASS_BUCKETS + 80 * MAX_HEADLIGHT_SHADOWS + 96 * MAX_CAB_PROBE_LAMPS, "bad size of ubs"); + + // the bucket of scene_ubs::wiper_rain_pass a place of a blade (dWiperPos, 0 .. 1) falls in + inline std::size_t wiper_pass_bucket(double const Position) + { + return std::min(static_cast(std::max(Position, 0.0) * static_cast(WIPER_PASS_BUCKETS)), WIPER_PASS_BUCKETS - 1); + } + + // the places blade Wiper went over from From to To (dWiperPos) get the rain fallen Value (-1: not known) + inline void wiper_pass_mark(scene_ubs &Scene, glm::length_t const Wiper, double const From, double const To, float const Value) + { + auto const last{wiper_pass_bucket(std::max(From, To))}; + for (auto bucket{wiper_pass_bucket(std::min(From, To))}; bucket <= last; ++bucket) + Scene.wiper_rain_pass[bucket][Wiper] = Value; + } // the camera of a pass in the world for the scene block (scene_ubs::camera_hi, camera_lo) inline void set_camera_place(scene_ubs &Ubs, glm::dvec3 const &Place) @@ -736,10 +763,15 @@ namespace gl const size_t WATER_CELLS_OFFSET = WATER_EXTRA_OFFSET + 16 * WATER_SLOT_DROPS; const size_t WATER_CELLS_SIZE = 4 * static_cast(WATER_SLOTS) * WATER_GRID * WATER_GRID * (1 + WATER_CELL_DROPS); const size_t WATER_TRAIL_OFFSET = WATER_CELLS_OFFSET + WATER_CELLS_SIZE; - const size_t WATER_STORAGE_SIZE = WATER_TRAIL_OFFSET + 4 * static_cast(WATER_SLOTS) * WATER_TRAIL * WATER_TRAIL; + // the snow on the glasses (water_snow.comp, mat_snow_windscreen.frag): two maps of every glass, WATER_MAP x WATER_MAP texels of + // two uint each (four halves: the snow, mm; the water, mm; how packed the snow is, 0 .. 1; random 0 .. 1, the shape of its + // flakes), a step reads one and writes the other (the header of the glass says which one is the latest) + const size_t WATER_SNOW_OFFSET = WATER_TRAIL_OFFSET + 4 * static_cast(WATER_SLOTS) * WATER_TRAIL * WATER_TRAIL; + const size_t WATER_SNOW_SIZE = 8 * static_cast(WATER_MAP) * WATER_MAP; + const size_t WATER_STORAGE_SIZE = WATER_SNOW_OFFSET + 2 * WATER_SNOW_SIZE * WATER_SLOTS; // the parts of a glass in the storage: its drops and what the passes keep of them, its map (the axes the second part), its - // cells and its paths, its header and its counts, (offset, size) in bytes - inline std::array, 11> water_slot_parts(size_t const Slot) + // cells and its paths, its header and its counts, its two maps of the snow, (offset, size) in bytes + inline std::array, 13> water_slot_parts(size_t const Slot) { auto const drops{static_cast(WATER_DROPS)}; auto const texels{static_cast(WATER_MAP) * WATER_MAP}; @@ -755,7 +787,9 @@ namespace gl {WATER_CELLS_OFFSET + cells * Slot, cells}, {WATER_TRAIL_OFFSET + trail * Slot, trail}, {WATER_HEADER_OFFSET + 16 * Slot, 16}, - {WATER_COUNTS_OFFSET + 16 * Slot, 16}}}; + {WATER_COUNTS_OFFSET + 16 * Slot, 16}, + {WATER_SNOW_OFFSET + WATER_SNOW_SIZE * Slot, WATER_SNOW_SIZE}, + {WATER_SNOW_OFFSET + WATER_SNOW_SIZE * (WATER_SLOTS + Slot), WATER_SNOW_SIZE}}}; } // layout std140: the step of the simulation of the water on the windscreens (GLSL water_ubo), every vector in the space of the @@ -784,8 +818,14 @@ namespace gl // landings tried at the densest place are all taken), z 1 when it's simulated, w the size of its drops (the param // rain_scale of its material) glm::vec4 slots[WATER_SLOTS]; + // the snow (water_snow.comp): x the flakes coming to a square metre of the ground in a second, y how much warmer than the + // air the glass is (the cab heats it), degrees, z the speed of the vehicle, m/s, w the map of the snow the step reads (0, 1) + glm::vec4 snow; + // every glass: 1 when its snow is simulated + glm::vec4 snow_slots; }; - static_assert(sizeof(water_ubs) == 112 + 16 * WATER_SLOTS, "bad size of water_ubs"); + static_assert(WATER_SLOTS == 4, "snow_slots holds a glass in a component"); + static_assert(sizeof(water_ubs) == 144 + 16 * WATER_SLOTS, "bad size of water_ubs"); // layout std430: a bucket of a scene cell queued in the pass (GLSL: instance_cull_job) struct instance_cull_job diff --git a/rendering/common/windscreenwater.cpp b/rendering/common/windscreenwater.cpp index 9a52eb3fe..f3b51f9c9 100644 --- a/rendering/common/windscreenwater.cpp +++ b/rendering/common/windscreenwater.cpp @@ -20,6 +20,8 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "vehicle/Train.h" +#include + namespace gfx { @@ -38,17 +40,42 @@ double constexpr WIND_SHARE{0.5}; float constexpr LEAST_DROP{0.5f}; // the water a flake of snow brings, mm3 on average (water_spawn.comp: 0.3 .. 2.5) float constexpr FLAKE_WATER{1.4f}; +// how much warmer than the air a glass of the cab is, degrees: the cab is heated (the blowing on the glass isn't simulated), +// less so at speed, when the air cools the glass from the outside (water_snow.comp) +float constexpr GLASS_WARMTH{3.f}; // the most landings tried on a glass in a step std::uint32_t constexpr MOST_TRIES{1024}; // the longest step, seconds: a longer frame slows the water down rather than let it jump double constexpr LONGEST_STEP{0.05}; -// whether the material is a glass: one of mat_rain_windscreen, with a mask of the wipers -bool is_glass(opengl_material const *Material) +// whether the material is a glass of the water: one of mat_rain_windscreen, with a mask of the wipers +bool is_water_glass(opengl_material const *Material) { return (Material != nullptr) && (Material->shader != nullptr) && (Material->shader->texture_conf.count("wipermask") > 0) && (Material->shader->param_conf.count("water_slot") > 0); } +// whether the material is a glass of the snow: one of mat_snow_windscreen, with a mask of the wipers (its param snow_slot is in +// the place of water_slot) +bool is_snow_glass(opengl_material const *Material) +{ + return (Material != nullptr) && (Material->shader != nullptr) && (Material->shader->texture_conf.count("wipermask") > 0) && (Material->shader->param_conf.count("snow_slot") > 0); +} + +// whether the material is a glass, of the water or of the snow +bool is_glass(opengl_material const *Material) +{ + return is_water_glass(Material) || is_snow_glass(Material); +} + +// what a material of the cab with a mask of the wipers is now: 0 no glass, 1 a glass of the water, 2 a glass of the snow (its +// shader goes with the weather) +int glass_kind(opengl_material const *Material) +{ + if (is_snow_glass(Material)) + return 2; + return is_water_glass(Material) ? 1 : 0; +} + // calls Visit for every submodel of the branch, its children and its siblings template void visit_submodels(TSubModel *Submodel, Visit &&Visitor) { @@ -94,6 +121,7 @@ void windscreen_water::release() assign(false); m_glasses = {}; m_glasscount = 0; + m_kinds.clear(); m_vehicle = nullptr; m_cab = nullptr; } @@ -230,6 +258,12 @@ void windscreen_water::build(TModel3d &Cab) } } auto const material{Submodel->m_material}; + if ((material != null_handle) && (material > 0) && (Submodel->eType == GL_TRIANGLES) && std::ranges::none_of(m_kinds, [material](auto const &Kind) { return Kind.first == material; })) + { + // every material with a mask of the wipers, what it is kept: it's a glass of another kind when the weather changes + if (auto const *opengl{m_host.material(material)}; (opengl != nullptr) && (opengl->shader != nullptr) && (opengl->shader->texture_conf.count("wipermask") > 0)) + m_kinds.emplace_back(material, glass_kind(opengl)); + } if ((material != null_handle) && (material > 0) && (Submodel->eType == GL_TRIANGLES) && (std::find(materials.begin(), materials.end(), material) == materials.end()) && is_glass(m_host.material(material))) { materials.push_back(material); @@ -255,6 +289,7 @@ void windscreen_water::build(TModel3d &Cab) glass = windscreen_water::glass{}; glass.material = material; auto const *opengl{m_host.material(material)}; + glass.snow = is_snow_glass(opengl); glass.mask = opengl->textures[opengl->shader->texture_conf.at("wipermask").id]; for (std::size_t texel = 0; texel < texels; ++texel) { @@ -317,7 +352,10 @@ void windscreen_water::update(double const Seconds) } auto const *vehicle{simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr}; auto *cab{vehicle != nullptr ? vehicle->mdKabina : nullptr}; - if ((vehicle != m_vehicle) || (cab != m_cab)) + // a material of the glasses of another kind: the weather changed, the materials have the shaders of the other weather (the + // snow comes with the shader of the snow and goes with it) + auto const changed{std::ranges::any_of(m_kinds, [this](auto const &Kind) { return glass_kind(m_host.material(Kind.first)) != Kind.second; })}; + if ((vehicle != m_vehicle) || (cab != m_cab) || changed) { // another cab: its glasses dry release(); @@ -409,11 +447,15 @@ void windscreen_water::update(double const Seconds) auto const coming{glm::length(air - up * fall)}; std::uint32_t most{0}; m_tries = 0; + bool anysnow{false}; for (std::size_t slot = 0; slot < m_glasscount; ++slot) { auto &glass{m_glasses[slot]}; auto const *material{m_host.material(glass.material)}; - auto const simulated{glass.baked && is_glass(material)}; + auto const snowed{glass.baked && glass.snow && is_snow_glass(material)}; + block.snow_slots[static_cast(slot)] = (snowed ? 1.f : 0.f); + anysnow = anysnow || snowed; + auto const simulated{glass.baked && (false == glass.snow) && is_water_glass(material)}; glass.landings += static_cast(perground / fall * coming * glass.densest) * seconds; auto const whole{std::floor(glass.landings)}; glass.landings -= whole; @@ -432,8 +474,14 @@ void windscreen_water::update(double const Seconds) m_bladesbefore.x < 0.f ? blades.x : m_bladesbefore.x, m_bladesbefore.y < 0.f ? blades.y : m_bladesbefore.y, m_bladesbefore.z < 0.f ? blades.z : m_bladesbefore.z, m_bladesbefore.w < 0.f ? blades.w : m_bladesbefore.w}; block.rain = glm::vec4{LEAST_DROP, lambda, 1.f, 0.f}; block.counts = glm::uvec4{m_step * 2654435761u, most, 0u, 0u}; + block.snow = glm::vec4{snow ? perground : 0.f, GLASS_WARMTH, static_cast(std::abs(vehicle->MoverParameters->V)), static_cast(m_snowmap)}; m_bladesbefore = blades; gpu_step(block, most); + if (anysnow) + { + // the step wrote the other map of the snow + m_snowmap = 1 - m_snowmap; + } } std::string windscreen_water::info() const diff --git a/rendering/common/windscreenwater.h b/rendering/common/windscreenwater.h index 2c09951ba..6a8ce7c17 100644 --- a/rendering/common/windscreenwater.h +++ b/rendering/common/windscreenwater.h @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include @@ -89,6 +90,7 @@ class windscreen_water float area{0.f}; // metres squared of the glass double landings{0.0}; // the share of a landing left over from the steps before bool baked{false}; + bool snow{false}; // a glass of the snow (mat_snow_windscreen), else of the water }; // the glasses of the model of a cab found and set up @@ -102,12 +104,14 @@ class windscreen_water int m_state{0}; // 0: not set up yet, 1: ready, -1: can't be used TDynamicObject const *m_vehicle{nullptr}; TModel3d const *m_cab{nullptr}; + std::vector> m_kinds; // the materials of the cab with a mask of the wipers, what kind of glass they were std::array m_glasses{}; std::size_t m_glasscount{0}; glm::vec4 m_bladesbefore{-1.f}; double m_time{0.0}; // seconds the simulation runs std::uint32_t m_step{0}; std::uint32_t m_tries{0}; // landings tried in the last step, all glasses + int m_snowmap{0}; // the map of the snow of the glasses the next step reads (0, 1) }; } // namespace gfx diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 4edfa838b..87da5bb76 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -1651,6 +1651,9 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) scene_ubs.wiper_timer_return = glm::vec4{-1000.}; scene_ubs.wiper_bugs_out = glm::vec4{-1.}; scene_ubs.wiper_bugs_return = glm::vec4{-1.}; + for (auto &pass : scene_ubs.wiper_rain_pass) + pass = glm::vec4{-1.f}; + m_wiperlastpos.fill(-1.0); m_wiperbugs = 0.0; } // the insects the vehicle meets (mat_bugs_windscreen): none below 20 km/h, above it the more the faster, counted in seconds of @@ -1658,6 +1661,23 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) if (owner != nullptr) m_wiperbugs += Timer::GetDeltaTime() * std::max(std::abs(owner->MoverParameters->V) * 3.6 - 20.0, 0.0) / 80.0; scene_ubs.rain_wind.w = static_cast(m_wiperbugs); + // the rain the glass meets (mat_rain_windscreen): counted in seconds of the heaviest rain standing still, more at speed (the + // glass runs into it). the glass fills with it up to as many drops as it gets (a lighter rain only fills it more slowly), and + // dries when it stops (by half in dry_halflife standing still, faster at speed) + { + constexpr double fill_rate{0.3}; // per second of the heaviest rain: 95% full in 10 s (20 s at cloud cover 1.5) + constexpr double fill_speed{1.5}; // at 100 km/h and more the glass meets x (1 + fill_speed) as much rain + constexpr double dry_halflife{180.0}; // seconds standing still + auto const dt{Timer::GetDeltaTime()}; + auto const speed{(owner != nullptr) ? std::min(std::abs(owner->MoverParameters->V) * 3.6 / 100.0, 1.0) : 0.0}; + auto const meet{static_cast(percipitation_intensity) * (1.0 + fill_speed * speed)}; + m_wiperrain += dt * meet; + if (percipitation_intensity > 0.f) + m_glasswet += (1.0 - m_glasswet) * (1.0 - std::exp(-fill_rate * dt * meet)); + else + m_glasswet *= std::exp(-dt * std::log(2.0) / dry_halflife * (1.0 + 2.0 * speed)); + scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), 0.f}; + } if (owner != nullptr) { auto const cabactive{owner->MoverParameters->CabActive != 0 ? owner->MoverParameters->CabActive : 1}; @@ -1666,6 +1686,10 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) if (i < owner->dWiperPos.size()) { int index = cabactive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; + // the places of its sweep the blade went over since the last frame get the rain fallen now + auto const position{owner->dWiperPos[index]}; + gl::wiper_pass_mark(scene_ubs, i, (m_wiperlastpos[i] < 0.0) ? position : m_wiperlastpos[i], position, static_cast(m_wiperrain)); + m_wiperlastpos[i] = position; scene_ubs.wiper_pos[i] = owner->dWiperPos[index]; if (owner->dWiperPos[index] > 0. && owner->wiperDirection[index]) { @@ -1689,6 +1713,8 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) scene_ubs.wiper_timer_return[i] = -1000.; scene_ubs.wiper_bugs_out[i] = -1.; scene_ubs.wiper_bugs_return[i] = -1.; + gl::wiper_pass_mark(scene_ubs, i, 0.0, 1.0, -1.f); + m_wiperlastpos[i] = -1.0; } } } @@ -1713,7 +1739,8 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) { m_windscreenwater.update(Timer::GetDeltaTime()); // the drops and the rivulets of the glasses with rain, for the time of the block of the scene - m_windscreenwater.update_rain_cells(scene_ubs.time, scene_ubs.rain_params.x); + // (the drops a cell may hold: as many as the glass is wet) + m_windscreenwater.update_rain_cells(scene_ubs.time, (scene_ubs.rain_state.y > 0.001f) ? std::min(scene_ubs.rain_state.y + 0.01f, 1.f) : 0.f); } m_windscreenwater.bind(); diff --git a/rendering/opengl46/opengl46renderer.h b/rendering/opengl46/opengl46renderer.h index d4364b527..a34ccd8b4 100644 --- a/rendering/opengl46/opengl46renderer.h +++ b/rendering/opengl46/opengl46renderer.h @@ -849,6 +849,12 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { TDynamicObject const *m_wipervehicle{nullptr}; // the insects that vehicle met so far: seconds of driving at 100 km/h (scene_ubs.rain_wind.w) double m_wiperbugs{0.0}; + // the place of each blade (dWiperPos) the last frame, -1 not known: the places it went over since get the rain fallen + // (gl::wiper_pass_mark) + std::array m_wiperlastpos{-1.0, -1.0, -1.0, -1.0}; + // the rain the glass met so far and how wet it is (scene_ubs::rain_state) + double m_wiperrain{0.0}; + double m_glasswet{0.0}; gl::light_data light_data; std::unordered_map> m_shaders; diff --git a/rendering/opengl46/opengl46water.cpp b/rendering/opengl46/opengl46water.cpp index 741536b99..0fd1e9d2d 100644 --- a/rendering/opengl46/opengl46water.cpp +++ b/rendering/opengl46/opengl46water.cpp @@ -13,6 +13,8 @@ http://mozilla.org/MPL/2.0/. #include "rendering/renderer.h" #include "utilities/Logs.h" +#include + namespace { @@ -28,7 +30,7 @@ bool opengl46_windscreen_water::gpu_init() try { std::array const names{"water_trail.comp", "water_spawn.comp", "water_move.comp", "water_clear.comp", "water_grid.comp", - "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp"}; + "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp", "water_snow.comp"}; for (std::size_t i = 0; i < names.size(); ++i) { gl::shader shader(names[i]); @@ -139,17 +141,24 @@ void opengl46_windscreen_water::gpu_step(gl::water_ubs const &Block, std::uint32 m_programs[Pass]->dispatch(Groups, slots); ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); }; + // the drops only where a glass of the water is (the glasses of the snow have passes of their own) + auto const water{std::ranges::any_of(Block.slots, [](glm::vec4 const &Slot) { return Slot.z > 0.5f; })}; + auto const drop_groups{water ? drops : 0u}; + auto const cell_groups{water ? cells : 0u}; // the wetted paths the blades went over in the step wiped - if (Block.blades != Block.blades_before) + if (water && (Block.blades != Block.blades_before)) run(pass::trail, groups(static_cast(gl::WATER_TRAIL) * gl::WATER_TRAIL)); - run(pass::spawn, groups(Tries)); - run(pass::move, drops); - run(pass::clear, cells); - run(pass::grid, drops); - run(pass::merge, drops); - run(pass::gather, drops); - run(pass::settle, drops); - run(pass::clear, cells); - run(pass::grid, drops); + run(pass::spawn, water ? groups(Tries) : 0u); + run(pass::move, drop_groups); + run(pass::clear, cell_groups); + run(pass::grid, drop_groups); + run(pass::merge, drop_groups); + run(pass::gather, drop_groups); + run(pass::settle, drop_groups); + run(pass::clear, cell_groups); + run(pass::grid, drop_groups); + // the snow of the glasses of the snow, a texel of their maps a thread + if (Block.snow_slots != glm::vec4{0.f}) + run(pass::snow, groups(static_cast(gl::WATER_MAP) * gl::WATER_MAP)); gl::program::unbind(); } diff --git a/rendering/opengl46/opengl46water.h b/rendering/opengl46/opengl46water.h index 7e5a20d29..ce3c92bae 100644 --- a/rendering/opengl46/opengl46water.h +++ b/rendering/opengl46/opengl46water.h @@ -50,6 +50,7 @@ class opengl46_windscreen_water : public gfx::windscreen_water gather, settle, bake, + snow, count }; std::array, pass::count> m_programs; diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index eb7a4567d..cdf265db1 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1047,7 +1047,8 @@ void vulkan14_renderer::render_scene() // the water on the windscreens of the cab: a step of its simulation once a frame, before the passes which draw the glasses scene.water.update(Timer::GetDeltaTime()); // the drops and the rivulets of the glasses with rain, for the time the block of the scene gets (scene_ubs.time) - scene.water.update_rain_cells(static_cast(Timer::GetTime()), glm::saturate(Global.Overcast - 1.f)); + // (the drops a cell may hold: as many as the glass is wet, a little more, since it's the wetness of the frame before) + scene.water.update_rain_cells(static_cast(Timer::GetTime()), (m_glasswet > 0.001) ? static_cast(std::min(m_glasswet + 0.01, 1.0)) : 0.f); if (scene.targets.size() < m_viewports.size()) { scene.targets.resize(m_viewports.size()); @@ -1505,6 +1506,9 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) scene_ubs.wiper_timer_return = glm::vec4{-1000.}; scene_ubs.wiper_bugs_out = glm::vec4{-1.}; scene_ubs.wiper_bugs_return = glm::vec4{-1.}; + for (auto &pass : scene_ubs.wiper_rain_pass) + pass = glm::vec4{-1.f}; + m_wiperlastpos.fill(-1.0); m_wiperbugs = 0.0; } // the insects the vehicle meets (mat_bugs_windscreen): none below 20 km/h, above it the more the faster, counted in seconds of @@ -1512,6 +1516,23 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) if (owner != nullptr) m_wiperbugs += Timer::GetDeltaTime() * std::max(std::abs(owner->MoverParameters->V) * 3.6 - 20.0, 0.0) / 80.0; scene_ubs.rain_wind.w = static_cast(m_wiperbugs); + // the rain the glass meets (mat_rain_windscreen): counted in seconds of the heaviest rain standing still, more at speed (the + // glass runs into it). the glass fills with it up to as many drops as it gets (a lighter rain only fills it more slowly), and + // dries when it stops (by half in dry_halflife standing still, faster at speed) + { + constexpr double fill_rate{0.3}; // per second of the heaviest rain: 95% full in 10 s (20 s at cloud cover 1.5) + constexpr double fill_speed{1.5}; // at 100 km/h and more the glass meets x (1 + fill_speed) as much rain + constexpr double dry_halflife{180.0}; // seconds standing still + auto const dt{Timer::GetDeltaTime()}; + auto const speed{(owner != nullptr) ? std::min(std::abs(owner->MoverParameters->V) * 3.6 / 100.0, 1.0) : 0.0}; + auto const meet{static_cast(percipitation_intensity) * (1.0 + fill_speed * speed)}; + m_wiperrain += dt * meet; + if (percipitation_intensity > 0.f) + m_glasswet += (1.0 - m_glasswet) * (1.0 - std::exp(-fill_rate * dt * meet)); + else + m_glasswet *= std::exp(-dt * std::log(2.0) / dry_halflife * (1.0 + 2.0 * speed)); + scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), 0.f}; + } if (owner != nullptr) { auto const cabactive{owner->MoverParameters->CabActive != 0 ? owner->MoverParameters->CabActive : 1}; @@ -1520,6 +1541,10 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) if (i < owner->dWiperPos.size()) { int index = cabactive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; + // the places of its sweep the blade went over since the last frame get the rain fallen now + auto const position{owner->dWiperPos[index]}; + gl::wiper_pass_mark(scene_ubs, i, (m_wiperlastpos[i] < 0.0) ? position : m_wiperlastpos[i], position, static_cast(m_wiperrain)); + m_wiperlastpos[i] = position; scene_ubs.wiper_pos[i] = owner->dWiperPos[index]; if (owner->dWiperPos[index] > 0. && owner->wiperDirection[index]) { @@ -1543,6 +1568,8 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) scene_ubs.wiper_timer_return[i] = -1000.; scene_ubs.wiper_bugs_out[i] = -1.; scene_ubs.wiper_bugs_return[i] = -1.; + gl::wiper_pass_mark(scene_ubs, i, 0.0, 1.0, -1.f); + m_wiperlastpos[i] = -1.0; } } } diff --git a/rendering/vulkan14/vulkan14renderer.h b/rendering/vulkan14/vulkan14renderer.h index 68e1ea48f..44d568490 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -536,6 +536,12 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk TDynamicObject const *m_wipervehicle{nullptr}; // the insects that vehicle met so far: seconds of driving at 100 km/h (scene_ubs.rain_wind.w) double m_wiperbugs{0.0}; + // the place of each blade (dWiperPos) the last frame, -1 not known: the places it went over since get the rain fallen + // (gl::wiper_pass_mark) + std::array m_wiperlastpos{-1.0, -1.0, -1.0, -1.0}; + // the rain the glass met so far and how wet it is (scene_ubs::rain_state) + double m_wiperrain{0.0}; + double m_glasswet{0.0}; gl::light_data light_data{}; std::uint32_t m_lightcount{1}; // lights written to light_data // the copies of the light buffer in the ring of the frame since the lights were last written, by the header and the sun diff --git a/rendering/vulkan14/vulkan14shaders.cpp b/rendering/vulkan14/vulkan14shaders.cpp index d1b3a6b4c..152b320eb 100644 --- a/rendering/vulkan14/vulkan14shaders.cpp +++ b/rendering/vulkan14/vulkan14shaders.cpp @@ -898,6 +898,7 @@ std::string binding_preamble(bool const Raytracing) define("MAX_PARAMS", static_cast(gl::MAX_PARAMS), "U"); define("MAX_HEADLIGHT_SHADOWS", static_cast(gl::MAX_HEADLIGHT_SHADOWS), "U"); define("MAX_CAB_PROBE_LAMPS", static_cast(gl::MAX_CAB_PROBE_LAMPS), "U"); + define("WIPER_PASS_BUCKETS", static_cast(gl::WIPER_PASS_BUCKETS)); define("CLUSTER_GRID_X", gl::CLUSTER_GRID_X); define("CLUSTER_GRID_Y", gl::CLUSTER_GRID_Y); define("CLUSTER_GRID_Z", gl::CLUSTER_GRID_Z); diff --git a/rendering/vulkan14/vulkan14water.cpp b/rendering/vulkan14/vulkan14water.cpp index c3aefc748..1ed3b45a2 100644 --- a/rendering/vulkan14/vulkan14water.cpp +++ b/rendering/vulkan14/vulkan14water.cpp @@ -12,6 +12,8 @@ http://mozilla.org/MPL/2.0/. #include "rendering/vulkan14/vulkan14commands.h" #include "utilities/Logs.h" +#include + #include namespace vk14 @@ -99,7 +101,7 @@ bool windscreen_water::gpu_init() try { std::array const names{"water_trail.comp", "water_spawn.comp", "water_move.comp", "water_clear.comp", "water_grid.comp", - "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp"}; + "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp", "water_snow.comp"}; for (std::size_t i = 0; i < names.size(); ++i) { if (false == m_kernels[i].create(m_device, *m_pipelines, m_shaders->get(names[i]), m_passlayout, {}, names[i])) @@ -283,20 +285,29 @@ void windscreen_water::gpu_step(gl::water_ubs const &Block, std::uint32_t const }; auto const drops{groups(gl::WATER_DROPS)}; auto const cells{groups(static_cast(gl::WATER_GRID) * gl::WATER_GRID)}; + // the drops only where a glass of the water is (the glasses of the snow have passes of their own) + auto const water{std::ranges::any_of(Block.slots, [](glm::vec4 const &Slot) { return Slot.z > 0.5f; })}; + auto const drop_groups{water ? drops : 0u}; + auto const cell_groups{water ? cells : 0u}; // the wetted paths the blades went over in the step wiped - if (Block.blades != Block.blades_before) + if (water && (Block.blades != Block.blades_before)) { run(pass::trail, groups(static_cast(gl::WATER_TRAIL) * gl::WATER_TRAIL)); } - run(pass::spawn, groups(Tries)); - run(pass::move, drops); - run(pass::clear, cells); - run(pass::grid, drops); - run(pass::merge, drops); - run(pass::gather, drops); - run(pass::settle, drops); - run(pass::clear, cells); - run(pass::grid, drops); + run(pass::spawn, water ? groups(Tries) : 0u); + run(pass::move, drop_groups); + run(pass::clear, cell_groups); + run(pass::grid, drop_groups); + run(pass::merge, drop_groups); + run(pass::gather, drop_groups); + run(pass::settle, drop_groups); + run(pass::clear, cell_groups); + run(pass::grid, drop_groups); + // the snow of the glasses of the snow, a texel of their maps a thread + if (Block.snow_slots != glm::vec4{0.f}) + { + run(pass::snow, groups(static_cast(gl::WATER_MAP) * gl::WATER_MAP)); + } } } // namespace vk14 diff --git a/rendering/vulkan14/vulkan14water.h b/rendering/vulkan14/vulkan14water.h index 901e241bd..dd42cf72a 100644 --- a/rendering/vulkan14/vulkan14water.h +++ b/rendering/vulkan14/vulkan14water.h @@ -78,6 +78,7 @@ class windscreen_water : public gfx::windscreen_water gather, settle, bake, + snow, count }; // the block of the step in the ring of the frame; empty when the ring is full diff --git a/shaders/ogl46/common.glsl b/shaders/ogl46/common.glsl index 01bdfab85..f3ac47314 100644 --- a/shaders/ogl46/common.glsl +++ b/shaders/ogl46/common.glsl @@ -130,6 +130,12 @@ #define FOG_VOLUME_BIAS 10.000000 #endif +// the places along the sweep of a blade whose rain is kept (gl::WIPER_PASS_BUCKETS): the renderer defines it, an older one doesn't +#ifndef WIPER_PASS_BUCKETS +#define WIPER_PASS_BUCKETS 64 +#endif + + const uint LIGHT_SPOT = 0U; const uint LIGHT_POINT = 1U; const uint LIGHT_DIR = 2U; @@ -375,6 +381,10 @@ layout(std140, binding = SCENE_UBO_BINDING) uniform scene_ubo // the place of the camera of the pass in the world (whole 64 m, the rest), see gl::scene_ubs vec4 camera_hi; vec4 camera_lo; + // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills (mat_rain_windscreen), see gl::scene_ubs + vec4 rain_state; + // the rain fallen when a blade last went over a place of its sweep (the wiper mask / 64), see gl::scene_ubs + vec4 wiper_rain_pass[WIPER_PASS_BUCKETS]; }; #ifdef STAGE_VERTEX diff --git a/shaders/ogl46/mat_rain_windscreen.frag b/shaders/ogl46/mat_rain_windscreen.frag index a7bceccc9..ca68ca98e 100644 --- a/shaders/ogl46/mat_rain_windscreen.frag +++ b/shaders/ogl46/mat_rain_windscreen.frag @@ -78,20 +78,26 @@ layout(binding = 3) uniform sampler2D normalmap; // --- Haze of the wet glass (blur) ------------------------------------------------ // The haze follows the rain and is wiped away by the wipers, as before (fully blurred from a quarter of the haze on). const float blur_amount = 1.0; // strength of the haze: 0 = off, 1 = full -// after the wiper the haze grows with the rain fallen on the glass since (intensity x seconds) from nothing up to its full -// strength, which is the intensity of the rain (cloud cover 1.5 -> 0.5). where no wiper reaches it is as always -const float haze_fill = 12.0; // rain to mist the glass up fully: seconds of the heaviest rain (2x as long at 1.5) +// after the wiper the haze grows with the rain fallen on the glass since (intensity x seconds, more at speed) from nothing up to +// its full strength, in any rain (a lighter rain takes longer). where no wiper reaches it is full +const float haze_fill = 12.0; // rain fallen since the blade to mist the glass up fully: seconds of the heaviest + // rain standing still (2x as long at 1.5; the speed counted in by the game) const float haze_curve = 1.0; // > 1: slow at first, then more and more -const float haze_speed = 1.0; // at speed the haze grows: x (1 + haze_speed) at full speed (see wind_drag_gain) const float WS_BEND_ENC = 60.0; // the drop request in the velocity target; must match rain_windscreen_haze.glsl const float WS_DROP_BIAS = 192.0; const float WS_ENC = 64.0; // the haze request in the velocity target; must match rain_windscreen_haze.glsl +// --- How the water gathers on the glass ------------------------------------------------------------------ +// the game counts the rain the glass meets (rain_state, gl::scene_ubs; more at speed) and how wet the glass is (0 dry .. 1 as full +// of drops as it gets): the glass fills up to the full in any rain, a lighter one only takes longer, and dries when the rain stops. +// the times are in the game (fill_rate, fill_speed, dry_halflife in the setup of the scene block). where a blade went over the glass +// the drops come back with the rain fallen since + // --- Drops (atlas tiles) ------------------------------------------------------ // (how long they live: rain_cells.glsl; the cells of the drops and of the rivulets are worked out once a frame by rain_cells.comp) // --- Micro droplets ------------------------------------------------------------- -const float micro_density = 0.45; // share of micro cells holding a droplet at full rain, 0 = off +const float micro_density = 0.45; // share of micro cells holding a droplet on a full glass, 0 = off const float micro_scale = 3.0; // micro grid = raindrop_grid_size * micro_scale const float micro_size_min = 0.12; // droplet radius in micro cells const float micro_size_max = 0.40; @@ -263,6 +269,14 @@ vec4 wsOver(vec4 over, vec4 under) // =========================================================================== float GetMixFactor(in vec2 co, out float side); +// the rain fallen when each blade last went over the place of its sweep given by the wiper mask (-1: not known), see +// gl::scene_ubs::wiper_rain_pass +vec4 wsWipePass(vec4 mask) +{ + ivec4 b = min(ivec4(max(mask, vec4(0.0)) * float(WIPER_PASS_BUCKETS)), ivec4(WIPER_PASS_BUCKETS - 1)); + return vec4(wiper_rain_pass[b.x].x, wiper_rain_pass[b.y].y, wiper_rain_pass[b.z].z, wiper_rain_pass[b.w].w); +} + uvec2 cellKey(vec2 c); vec2 tileOffset(float choice) @@ -361,7 +375,7 @@ Riv getRiv(vec2 sCell, float sCW, float sCH, float gridSize) { Riv r; uvec4 d = rain_cells[rain_riv_index(wsLayerIndex, ivec2(sCell))]; - r.on = ((float(d.x & 65535u) + 0.5) * (1.0 / 65536.0) < rain_params.x * streak_density * wsLayerDensity); + r.on = ((float(d.x & 65535u) + 0.5) * (1.0 / 65536.0) < streak_density * wsLayerDensity * rain_state.y); // as wet as the glass is r.life = float((d.x >> 16) & 255u) * (1.0 / 255.0); float wr = rain_byte(d.y, 16u); r.width = streak_head * wsLayerHead / gridSize @@ -554,23 +568,16 @@ float wsKept(vec2 cg, float rad, float sCW, float sCH, float gridSize) return kept; } -// seconds since a wiper blade last went over Co (texture UV), from the timers of its strokes as GetMixFactor takes them; -// -1 where no wiper reaches -float wsWipeAge(vec2 co) +// the rain fallen (rain_state.x) since a blade last went over this place (texture UV); -1 where no blade goes or not known +float wsWipeRain(vec2 co) { - vec4 movePhase = wiper_pos; - bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); - movePhase = mix(vec4(2.) - movePhase, movePhase, is_out); vec4 mask = textureLod(wipermask, co, 0.0); - vec4 maskVal = mix(1. - mask, mask, is_out); - vec4 passed = step(maskVal, movePhase); - vec4 sideV = mix(passed, vec4(1.) - passed, is_out); - vec4 ages = vec4(time) - mix(wiper_timer_out, wiper_timer_return, sideV); - float age = -1.0; + vec4 at = wsWipePass(mask); + float fallen = -1.0; for (int i = 0; i < 4; ++i) - if ((mask[i] > 0.001) && ((age < 0.0) || (ages[i] < age))) - age = max(ages[i], 0.0); - return age; + if ((mask[i] > 0.001) && (at[i] >= 0.0)) + fallen = (fallen < 0.0) ? max(rain_state.x - at[i], 0.0) : min(fallen, max(rain_state.x - at[i], 0.0)); + return fallen; } // the tangent frame of the glass (the directions of u and v on it, view space) from the screen-space change of the place and the uv @@ -628,10 +635,6 @@ void main() float wsNight = smoothstep(0.0, drop_dark_lum, sceneLum); // 0 dark night .. 1 daylight dynBright *= wsNight; - // wiper state of this pixel (blur, micro droplets) - float hazeSide; - float wipeVis = GetMixFactor(f_coord, hazeSide); - Hit hit; hit.score = 0.0; hit.cov = 0.0; hit.colA = 0.0; hit.n = vec3(0.0, 0.0, 1.0); hit.offUV = vec2(0.0); hit.radUV = 1.0; hit.isDrop = 1.0; @@ -678,6 +681,10 @@ void main() wsPushT = vec2(dot(wsPush, Tgl), dot(wsPush, Bgl)); wsPushT = (dot(wsPushT, wsPushT) > 1e-10) ? normalize(wsPushT) : vec2(0.0, -1.0); } + + // the wiper state of this pixel (blur, micro droplets) + float hazeSide; + float wipeVis = GetMixFactor(f_coord, hazeSide); // the change of the glass UV (v up) per screen pixel, for the rivulets vec2 wsRd1 = vec2(duv1.x, flipS * duv1.y); vec2 wsRd2 = vec2(duv2.x, flipS * duv2.y); @@ -690,7 +697,7 @@ void main() vec2 sCell = floor(sUVg / vec2(sCW, sCH)); bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0) && (WS_PROFILE != 2); - if ((rain_params.x > 0.001) && (WS_PROFILE != 5)) + if ((rain_state.y > 0.001) && (WS_PROFILE != 5)) { // =================================================================== // 1. drops from the atlas: this cell and its 8 neighbours @@ -708,6 +715,9 @@ void main() reach &= reach - 1u; vec2 nc = cell + vec2(float(bit % 3 - 1), float(bit / 3 - 1)); uvec4 d = rain_cells[rain_drop_index(ivec2(nc))]; + // as many drops as the glass is wet (the cells were sorted out with a little more) + if (rain_byte(d.y, 24u) > min(rain_state.y * drop_density, 0.95)) + continue; float vis = float(d.w >> 24) * (1.0 / 255.0); float spreadF = mix(0.8, 1.0, float((d.y >> 19) & 31u) * (1.0 / 31.0)); // a drop the blades miss: the same drop before and after the stroke, left where it is @@ -781,7 +791,7 @@ void main() float mph = fract(mtt); uint mep = uint(mod(floor(mtt), 65521.0)); uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); - if (RandF(m1) < min(rain_params.x * micro_density, 0.95)) + if (RandF(m1) < min(micro_density * rain_state.y, 0.95)) { uint m2 = Hash(uvec3(mk, mep * 4u + 2u + uint(hazeSide) * 2u)); if (wipeVis >= RandF(m2)) @@ -991,10 +1001,11 @@ void main() // What is seen through the wet glass: the image of the last frame, blurred by the haze, bent by the drops // ----------------------------------------------------------------------- // the haze after the wiper: grows with the rain fallen since, up to the intensity of the rain (as it always was where no wiper reaches) - float wipeAge = wsWipeAge(f_coord); - float hazeBack = (wipeAge < 0.0) ? 1.0 - : min(wipeVis, pow(clamp(wipeAge * rain_params.x / haze_fill, 0.0, 1.0), haze_curve)); - float hazeWeight = min(rain_params.x * hazeBack * (1.0 + haze_speed * wsSpeed), 1.0) * (1.0 - max(alphaOut, coverA)); + float wipeRain = wsWipeRain(f_coord); + float hazeBack = (wipeRain < 0.0) ? rain_state.y + : min(rain_state.y, pow(clamp(wipeRain / haze_fill, 0.0, 1.0), haze_curve)); + // up to the full haze in any rain, as the glass gets wet (a lighter rain only mists it up more slowly), less as it dries + float hazeWeight = hazeBack * (1.0 - max(alphaOut, coverA)); float glassClear = 1.0 - smoothstep(0.5, 0.95, glassA); bool image = ssr_params.x >= 1.0; float background = 0.0; // distance to the scene behind, along the view (0: far / not known) @@ -1094,7 +1105,13 @@ float GetMixFactor(in vec2 co, out float side) { side_v = mix(side_v, vec4(1.) - side_v, is_out); // "regeneration", raindrops gradually returning after wiper pass: - vec4 regenPhase = clamp((vec4(time) - mix(wiper_timer_out, wiper_timer_return, side_v) - vec4(.2)) / vec4(rain_params.y), vec4(0.), vec4(1.)); + // the share of the drops back: the glass fills with the rain fallen since the blade (rain_state), up to as wet as the glass is + // where no blade goes (the drops of a cell are there only up to that share, so the share of those back is the fill over it) + vec4 at = wsWipePass(mask); + vec4 fallen = vec4(rain_state.x) - at; + vec4 known = step(vec4(0.), at); + vec4 filled = mix(vec4(1.), vec4(1.) - exp(-max(fallen, vec4(0.)) * rain_state.z), known); + vec4 regenPhase = clamp(filled / max(rain_state.y, 1e-4), vec4(0.), vec4(1.)); side_v = mix(vec4(0.), vec4(1.) - side_v, areaMask); diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag new file mode 100644 index 000000000..0ca45013c --- /dev/null +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -0,0 +1,779 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +// Windscreen snow: replaces rain_windscreen when it snows - v2 (OpenGL 4.6 / Vulkan 1.4 port of the OpenGL 3.3 v1) +// v2: the syntax of the 4.6 renderers (explicit locations and bindings, #pragma texture / param), the tuning values as constants +// (a uniform can't have a default any more); the blur of the scene and the picture bent by thin snow go to the +// post-processing through the velocity target, as the haze and the drops of rain_windscreen (postfx_taa.frag / +// postfx_motionblur.frag with rain_windscreen_haze.glsl); the colour is written straight +// (not premultiplied) as rain_windscreen of the 4.6 renderers writes the glass; the gloss of the glass from legacy_gloss(); +// no lighting where the glass is clear (no snow, a clear texture). the look and the behaviour of the snow are those of v1. +// +// MaSzyna switches the weather itself (simulationenvironment.cpp): with Overcast > 1 it rains when the air is warmer +// than 1 deg C and it SNOWS at 1 deg C and below, and the .mat block "snow:" is picked. rain_params.x is the +// precipitation intensity (saturate(Overcast - 1)), exactly what rain_windscreen uses for the drops, so the snow +// on the glass follows the snowfall: nothing without snow, and the harder it snows the more the glass gets plastered. +// +// - flakes: every cell of the glass can hold a flake (atlas tiles 0..2: fluffy, wet lump, crumbs). It lands at a random +// moment, stays white for `snow_hold` seconds and then MELTS for `snow_melt` seconds: the snow fades into a water spot +// (tile 3). About `snow_slide_share` of the melting flakes also SLIDE DOWN the glass, stretching into a drip. +// Only the wet, melting spot blurs the scene (water refracts; dry snow does not, see snow_fresh_blur). +// - clumping: flakes land small and GROW as more snow piles onto them. Where flakes land next to each other they run together +// into one bigger patch (a crusty white film), and the more it snows the more flakes land side by side, so the bigger +// the patches get. The patch exists only where flakes really sit close together; when they melt / slide away it breaks +// up and thins out (snow_clump). +// - wipers (wipermask, GetMixFactor) clear all of it; it builds up again after `snow_regen` seconds (faster in heavy snow). +// Nothing depends on the time since the game started. +// +// Atlas / normalmap (blender_snow_atlas.py), 2 x 2 tiles: +// 0 dry fluffy flake 1 wet compact lump 2 crumbs 3 melted spot (water + ice remnants) +// +// .mat: +// +// texture_diffuse: dynamic/pkp/vectron_v1/cab/szyby +// texture_raindropsatlas: textures/fx/raindrops-atlas +// texture_normalmap: textures/fx/raindrops_normalmap +// texture_wipermask: dynamic/pkp/vectron_v1/cab/szyby_wipermask +// shader: rain_windscreen +// param_raindrop_grid_size: 150 +// +// snow: { +// shader: snow_windscreen +// texture_raindropsatlas: textures/fx/snow-atlas +// texture_normalmap: textures/fx/snow_normalmap +// param_raindrop_grid_size: 70 +// } +// +// One cell is about one flake: a grid of ~50-90 gives flakes of ~1-2 cm on a ~1.5 m windscreen. + +layout(location = 0) in vec3 f_normal; +layout(location = 2) in vec2 f_coord; +layout(location = 3) in vec4 f_pos; +layout(location = 4) in vec4 f_clip_pos; +layout(location = 5) in vec4 f_clip_future_pos; +#include "common.glsl" + +layout(location = 0) out vec4 out_color; +layout(location = 1) out vec4 out_motion; + +#pragma texture(diffuse, 0, sRGB_A) +#pragma texture(raindropsatlas, 1, sRGB_A) +#pragma texture(wipermask, 2, sRGB_A) +#pragma texture(normalmap, 3, RGBA) // flakes: rg = normal xy, b = height, a = mask; same 2x2 layout as raindropsatlas (linear) +#pragma param(color, 0, 0, 4, diffuse) +#pragma param(diffuse, 1, 0, 1, diffuse) +#pragma param(specular, 1, 1, 1, specular) +#pragma param(reflection, 1, 2, 1, zero) +#pragma param(glossiness, 1, 3, 1, glossiness) +#pragma param(raindrop_grid_size, 2, 0, 1, one) +// snow_slot: 1 + the slot of the glass in the simulation of the snow (the renderer sets it), 0: none +#pragma param(snow_slot, 2, 2, 1, zero) + +#include "light_common.glsl" +#include "apply_fog.glsl" +#include "tonemapping.glsl" +#include "random.glsl" +#include "water.glsl" + +layout(binding = 0) uniform sampler2D diffuse; +layout(binding = 1) uniform sampler2D raindropsatlas; +layout(binding = 2) uniform sampler2D wipermask; +layout(binding = 3) uniform sampler2D normalmap; + +// --- Tuning ----------------------------------------------------------------- +// Intensity = rain_params.x = saturate(Overcast - 1). The slider range 1.00..2.00 (Overcast) maps to intensity 0..1. The share of flake cells is pow(intensity, 0.8) * snow_gain * snow_density, +// so with the defaults every cell carries a flake from Overcast ~ 1.2 and the film closes the glass at about 1.3 (1.1 = light snow, 1.5+ = blizzard). +const float snow_gain = 1.4; // how fast the glass gets covered when the snowfall gets heavier (higher = already plastered in light snow) +const float snow_density = 0.95; // upper limit of the share of cells that carry a big flake +const float snow_small = 0.80; // same for the layer of small flakes (0 = off) +const float snow_pack = 0.90; // opacity of the patches that form where flakes clump together (0 = no patches) +const float snow_clump = 2.60; // how readily neighbouring flakes run together into one patch (higher = patches form sooner and get bigger) +const float snow_clump_share = 0.55; // share of the flakes that run together into patches; the rest stay separate flakes +const float snow_hold = 40.0; // seconds a flake stays white before it starts to melt (longer in heavy snow) +const float snow_melt = 30.0; // seconds the melting takes (snow fades into a water spot) +const float snow_slide_share = 0.40; // share of the melting flakes that run down the glass +const float snow_slide_len = 2.0; // how far a sliding flake runs, in cells (max 2.4) +const float snow_grow_fast = 5.3; // seconds a patch needs to grow from a clump to a big sheet in the heaviest snowfall +const float snow_grow_slow = 46.7; // same in the lightest snowfall (it still gets there, just much later) +const float snow_haze = 1.0; // blur of the scene behind and around the snow patches (frosted glass), 0 = off, 1 = full (radius: windscreen_view.glsl) +const float snow_distort = 2.0; // picture distortion seen through thin snow (refraction by its relief), 0 = off +const float snow_flake_scale = 2.5; // size of the flakes from the atlas relative to one grid cell (2-3 = two to three times bigger than before; the flakes get fewer) +const float snow_regen = 25.0; // seconds until snow is back on a wiped area (in light snowfall) +const float snow_opacity = 1.0; // overall opacity +const float snow_uv_aspect = 1.0; // glass width / height in the world if the UV is stretched +const float snow_bump = 1.0; // strength of the 3D relief from the normal map, 0 = flat +const float snow_gloss = 0.45; // glints of the sun / headlights on the snow, 0 = matt +const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off +const float snow_melt_blur = 0.8; // blur of the scene around the water spots of melting flakes (0 = off, 1 = full) +const float snow_fresh_blur = 0.0; // blur around fresh dry flakes: physically there is none, a little (0.1-0.2) fakes light scattering + +#ifndef SNOW_FLIP_Y +#define SNOW_FLIP_Y 0 // set to 1 if sliding flakes run UP the glass (the glass UV then has v growing downwards) +#endif +const float SNOW_SIZE_MIN = 0.70; // flake size in grid cells (keep max <= 1.8, the search covers 3x3 cells) +const float SNOW_SIZE_MAX = 1.50; +const float SNOW_SLIDER_MAX = 1.10; // a flake that slides is smaller than this (it gets stretched on its way down) +const float SNOW_HALO_SCALE = 1.5; // blur ring radius = flake half-size * this +const float SNOW_LAND_TIME = 1.5; // seconds a flake takes to land and settle +const float SNOW_REFR_MAXPX = 96.0; // the largest picture shift of thin snow, screen pixels +const float WS_REFR_MAXPX = 96.0; // the largest picture shift the post-processing makes, screen pixels; must match rain_windscreen_haze.glsl +const float WS_BEND_ENC = 60.0; // the bend request in the velocity target; must match rain_windscreen_haze.glsl +const float WS_DROP_BIAS = 192.0; +const float WS_ENC = 64.0; // the haze request in the velocity target; must match rain_windscreen_haze.glsl +const float SNOW_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the bent picture + +#ifndef SNOW_MATCH_RAIN_GLASS +#define SNOW_MATCH_RAIN_GLASS 0 // 4.6: rain_windscreen writes the glass straight, not premultiplied +#endif + +float snHaze = 0.0; // set by snowFilm: 1 inside / next to a snow patch (drives the frosted-glass blur) +float snWipeSince = 1.0e5; // set by GetMixFactor: seconds since the wiper last cleaned this spot +float GetMixFactor(in vec2 co, out float side); + +const float SNOW_MERGE_R = 2.0; // reach of a flake's 'snow mass' in flake half-sizes (flakes closer than this run together) +const float SNOW_CLUMP_THR = 0.80; // summed mass above which the glass is covered + +float snHash(vec2 p) +{ + return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); +} + +float snNoise(vec2 p) +{ + vec2 i = floor(p); + vec2 f = fract(p); + f = f * f * (3.0 - 2.0 * f); + return mix(mix(snHash(i), snHash(i + vec2(1.0, 0.0)), f.x), + mix(snHash(i + vec2(0.0, 1.0)), snHash(i + vec2(1.0, 1.0)), f.x), f.y); +} + +float snFbm(vec2 p) +{ + float a = 0.5; + float v = 0.0; + for (int i = 0; i < 4; ++i) + { + v += a * snNoise(p); + p = p * 2.07 + vec2(17.3, 9.1); + a *= 0.5; + } + return v / 0.9375; +} + +// One flake in one cell. `age` = seconds since it landed. +void snowFlake(vec2 ncell, uint seed, float age, float gridSize, float pixelUV, vec2 aspect, + float sizeMul, float opacityMul, float hold, float meltT, float slideShare, + inout vec3 accRGB, inout float accA, inout float smear, + inout vec3 accN, inout float accTr, inout float accM) +{ + float mt = clamp((age - hold) / meltT, 0.0, 1.0); // 0 = dry, 1 = melted away + float melt = smoothstep(0.0, 1.0, mt); + float fade = 1.0 - smoothstep(0.75, 1.0, mt); // the water spot dries up at the very end + float land = smoothstep(0.0, 0.3, age); // it lands at once (no ghostly fade-in): it just starts small + + float jx = RandF(seed); + float jy = RandF(seed); + vec2 center = (ncell + vec2(jx, jy)) / gridSize; + + float rs = RandF(seed); + float ang = RandF(seed) * 6.2831853; + float flipX = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float kind = RandF(seed); + float tone = mix(0.94, 1.04, RandF(seed)); + bool slider = RandF(seed) < slideShare; + float slideLen = mix(0.8, 1.0, RandF(seed)) * min(snow_slide_len, 2.4) / gridSize; + bool clumper = RandF(seed) < snow_clump_share; // this flake sticks to its neighbours (else it stays on its own) + float aniso = mix(0.62, 1.0, RandF(seed)); // flakes are never round: random squash after rotation + + float szMax = slider ? SNOW_SLIDER_MAX : SNOW_SIZE_MAX; + float size = mix(SNOW_SIZE_MIN, szMax, rs * rs) / gridSize * sizeMul * mix(0.45, 1.0, smoothstep(0.0, max(hold * 0.25, 1.0), age)) * mix(1.0, 0.85, melt); // grows as snow piles onto it + + // a sliding flake runs down while it melts and stretches into a drip + float slideP = slider ? smoothstep(0.05, 1.0, mt) : 0.0; +#if SNOW_FLIP_Y + center.y += slideLen * slideP * slideP; +#else + center.y -= slideLen * slideP * slideP; +#endif + float stretchY = 1.0 + 0.9 * slideP; + + vec2 d = (f_coord - center) * aspect; + d.y /= stretchY; + + // the 'snow mass' of this flake: neighbouring flakes add up, and where the sum is high they have run into one patch + { + float kr = min(size * 0.5 * SNOW_MERGE_R, 1.0 / gridSize); // (1 cell: the search only covers the 3x3 cells around the pixel) + float m = 1.0 - smoothstep(0.0, kr, length(d)); + if (clumper) + accM += m * m * (3.0 - 2.0 * m) * (1.0 - 0.6 * melt) * snow_clump * land; + } + + // blur only around the water of a melting flake (and, optionally, a little around fresh ones) + float haloR = size * 0.5 * SNOW_HALO_SCALE; + float dist = length(d); + if (dist < haloR) + { + float ring = 1.0 - smoothstep(0.35 * haloR, haloR, dist); + smear = max(smear, ring * land * (melt * snow_melt_blur + (1.0 - melt) * snow_fresh_blur)); + } + + float c = cos(ang); + float s = sin(ang); + vec2 r = vec2(c * d.x + s * d.y, -s * d.x + c * d.y); + r.x *= flipX / aniso; + + vec2 local = r / size + 0.5; + if (any(lessThan(local, vec2(0.0))) || any(greaterThan(local, vec2(1.0)))) + return; + + float lod = clamp(log2(max(pixelUV / size * 0.5 * float(textureSize(raindropsatlas, 0).x), 1.0)), 0.0, 4.0); + + // dry flake (tiles 0..2: fluffy, wet lump, crumbs) and, while melting, its water spot (tile 3) + vec2 off0 = (kind < 0.40) ? vec2(0.0, 0.5) : ((kind < 0.72) ? vec2(0.5, 0.5) : vec2(0.0, 0.0)); + vec2 off3 = vec2(0.5, 0.0); + vec4 t0 = textureLod(raindropsatlas, off0 + local * 0.5, lod); + vec4 n0 = textureLod(normalmap, off0 + local * 0.5, lod); + float a0 = t0.a * (1.0 - melt); + float a3 = 0.0; + vec4 t3 = vec4(0.0); + vec4 n3 = vec4(0.5, 0.5, 0.0, 0.0); + if (melt > 0.001) + { + t3 = textureLod(raindropsatlas, off3 + local * 0.5, lod); + n3 = textureLod(normalmap, off3 + local * 0.5, lod); + a3 = t3.a * smoothstep(0.0, 0.5, melt) * fade; + } + + float aSum = a0 + a3; + float a = clamp(aSum * land * snow_opacity * opacityMul, 0.0, 1.0); + if (a <= 0.0) + return; + vec3 col = (t0.rgb * a0 + t3.rgb * a3) / max(aSum, 1e-4); + vec2 nxy = ((n0.rg * 2.0 - 1.0) * a0 + (n3.rg * 2.0 - 1.0) * a3) / max(aSum, 1e-4); + nxy *= snow_bump * land; + nxy.x *= flipX; + vec2 nuv = vec2(c * nxy.x - s * nxy.y, s * nxy.x + c * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + + // thin snow lets light through: the dry part is translucent, the water spot is not + float tr = (a0 / max(aSum, 1e-4)) * (1.0 - t0.a * 0.55); + + accRGB = col * tone * a + accRGB * (1.0 - a); + accN = nT * a + accN * (1.0 - a); + accTr = tr * a + accTr * (1.0 - a); + accA = a + accA * (1.0 - a); +} + +// Adds one layer of flakes to the premultiplied accumulators. Same scheme as the drops of rain_windscreen: +// the cells around the pixel (a few more above it, for the flakes that slide down), the wipers decide per cell whether it +// is clear, the precipitation intensity decides whether the cell carries a flake right now. +void snowLayer(float gridSize, float density, uint layerSeed, float sizeMul, float opacityMul, float slideShare, int rowsUp, + float pixelUV, vec2 aspect, + inout vec3 accRGB, inout float accA, inout float smear, + inout vec3 accN, inout float accTr, inout float accM) +{ + vec2 cell = floor(f_coord * gridSize); + float heavy = clamp(rain_params.x, 0.0, 1.0); + float hold = snow_hold * (1.0 + 1.5 * heavy); // in heavy snow there is no time to melt + float meltT = max(snow_melt, 1.0); + float life = hold + meltT; + float occupancy = mix(0.70, 0.97, heavy); // share of the time a cell holds a flake + float cycBase = life / occupancy; + float share = clamp(pow(rain_params.x, 0.8) * snow_gain, 0.0, 1.0) * density; + + // flakes slide upwards in UV if SNOW_FLIP_Y: search the rows on the other side +#if SNOW_FLIP_Y + int oyMin = -1 - rowsUp; + int oyMax = 1; +#else + int oyMin = -1; + int oyMax = 1 + rowsUp; +#endif + + for (int oy = oyMin; oy <= oyMax; oy++) { + for (int ox = -1; ox <= 1; ox++) { + + vec2 ncell = cell + vec2(float(ox), float(oy)); + uvec2 ucell = uvec2(ivec2(ncell)); + + float side; + float mixFactor = GetMixFactor((ncell + 0.5) / gridSize, side); + + // timing of this cell: the same in every round + uint tseed = Hash(uvec3(ucell, layerSeed + 31u)); + float cyc = cycBase * (1.0 + mix(0.45, 0.03, heavy) * RandF(tseed)); // in heavy snow the cells hardly ever stand empty + float tOff = RandF(tseed) * cyc; + float patchMul = mix(0.7, 1.3, RandF(tseed)); + float tl = time + tOff; + float rnd = floor(tl / cyc); + float age = tl - rnd * cyc; // seconds since this round's flake landed + if (age > life) + continue; + + // a new flake (position, shape, size) every round; the wiper stroke is part of the seed, as in the rain + uint seed = Hash(uvec3(ucell, layerSeed + uint(side) * 7919u + uint(max(rnd, 0.0)) * 2654435u)); + + if (mixFactor < RandF(seed)) + continue; // wiped / still regrowing + + float activate = RandF(seed); + if (activate > share * patchMul) + continue; + + snowFlake(ncell, seed, age, gridSize, pixelUV, aspect, sizeMul, opacityMul, hold, meltT, slideShare, + accRGB, accA, smear, accN, accTr, accM); + } + } +} + +// Snow patches: a crusty white sheet with the structure of real snow (lumps, grain, thin translucent edges, holes). +// WHERE it grows is decided by the flakes: the 'snow mass' of the flakes that stick together (accM) pushes the sheet up, so a patch starts +// where several flakes landed close to each other, spreads from there in an irregular shape and keeps growing while more flakes land +// next to it; when they melt or slide away it breaks up into holes. It is drawn UNDER the flakes. +// Snow patches built from 'pach pach pach' accretion: every big cell carries a patch that is a heap of 22 small clumps (about flake sized). +// The clumps pop up one after another (the ones near the middle first, so the patch spreads outwards) and each lands at once, as a ragged +// piece that merges with the pieces already there. How fast that goes depends on the snowfall intensity (growT); left alone the pieces +// overlap into a closed sheet. Regions of the glass start at different moments. Returns f > 0 inside the snow (f = depth in sheet cells). +float snowSheetField(float gridSize) +{ + float sg = gridSize * 0.19; + vec2 pg = f_coord * sg; + vec2 cell = floor(pg); + float heavy = clamp(rain_params.x, 0.0, 1.0); + float growT = mix(snow_grow_slow, snow_grow_fast, pow(heavy, 0.5)); + float hold = snow_hold * (1.0 + 1.5 * heavy); + float meltT = max(snow_melt, 1.0); + float life = growT + hold + meltT; + float occupancy = mix(0.80, 0.97, heavy); + float cycBase = life / occupancy; + float share = clamp(heavy * 1.6, 0.0, 1.0) * 0.95 + 0.05 * heavy; // share of the cells that carry a patch (1.0 = none, ~1.6 = nearly all) + + // wiper: pixel precise. The sheet at a pixel is no older than the last wipe of that pixel. + float sidePx; + float mixPx = GetMixFactor(f_coord, sidePx); + float wipeAgePx = snWipeSince; + + float acc = 0.0; // summed clump kernels (metaballs): touching clumps merge, no scalloped circles + for (int oy = -1; oy <= 1; oy++) { + for (int ox = -1; ox <= 1; ox++) { + vec2 ncell = cell + vec2(float(ox), float(oy)); + uvec2 ucell = uvec2(ivec2(ncell)); + + uint tseed = Hash(uvec3(ucell, 211u)); + float cyc = cycBase * (1.0 + mix(0.45, 0.03, heavy) * RandF(tseed)); + float tOff = RandF(tseed) * cyc; + float tl = time + tOff; + float rnd = floor(tl / cyc); + float age = tl - rnd * cyc; + if (age > life) + continue; + + uint seed = Hash(uvec3(ucell, 223u + uint(sidePx) * 7919u + uint(max(rnd, 0.0)) * 2654435u)); + if (RandF(seed) > share) + continue; + + vec2 c = ncell + vec2(0.1 + 0.8 * RandF(seed), 0.1 + 0.8 * RandF(seed)); + vec2 dc = pg - c; + if (dot(dc, dc) > 1.2 * 1.2) + continue; // too far from this patch to be touched by any of its clumps + + age = min(age, wipeAgePx); + float delay = snNoise(c * 0.30 + 3.7) * growT * 0.35; // regions of the glass start at different moments + float ga = max(age - delay, 0.0); + float mt = clamp((age - growT - hold) / meltT, 0.0, 1.0); + float shrink = 1.0 - 1.1 * mt * mt; // melting: the clumps shrink and holes open + + for (int i = 0; i < 22; i++) { + uint bs = Hash(uvec3(seed, uint(i), 977u)); + float rho = RandF(bs); + float an = RandF(bs) * 6.2831853; + float rad = 0.85 * sqrt(rho); + vec2 bp = c + rad * vec2(cos(an), sin(an)); + float rb = mix(0.17, 0.30, RandF(bs)); + float ti = growT * (0.03 + 0.97 * pow(rad / 0.85, 0.9) * mix(0.70, 1.0, RandF(bs))); // inner clumps first + // each clump arrives in three small portions (pop, pop, pop): 45% -> 72% -> 100% of its size, no fading + float dT = growT * 0.10; + float stg = step(ti, ga) + step(ti + dT, ga) + step(ti + 2.0 * dT, ga); // 0..3 + if (stg <= 0.0) + continue; + float rr = rb * shrink * (stg < 1.5 ? 0.45 : (stg < 2.5 ? 0.72 : 1.0)); + float kd = max(1.0 - length(pg - bp) / max(rr * 1.35, 1e-3), 0.0); + acc += kd * kd * (3.0 - 2.0 * kd); + } + } + } + // torn, crumbly edge: fine noise (features about a flake wide) decides where the summed clumps stop, so the outline is irregular + // snow and not a ring of circles + float nz = snFbm(pg * 5.5 + 13.0) * 0.45 + snFbm(pg * 13.0 + 7.0) * 0.35 + snFbm(pg * 31.0 + 3.0) * 0.20 - 0.5; + float best = (acc - 0.50) * 0.20 + nz * 0.30; + best -= (1.0 - smoothstep(0.0, 0.12, mixPx)) * 1.0; // swept (or still regrowing) areas + return best; +} + +void snowFilm(float gridSize, inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) +{ +#if SNOW_FLIP_Y + float dir = -1.0; +#else + float dir = 1.0; +#endif + float sf = snowSheetField(gridSize); + snHaze = max(snHaze, smoothstep(-0.045, 0.0, sf)); // the glass next to a patch is frosted a little as well + float cover = smoothstep(0.0, 0.03, sf); + if (cover <= 0.002) + return; + float thick = smoothstep(0.0, 0.11, sf); // 0 at the thin edge, 1 in the thick middle + vec2 p = f_coord * gridSize * 0.17 + vec2(0.0, dir * time * 0.008); + vec2 q = f_coord * gridSize * 2.6; + float h0 = snFbm(p); + + // lumpy surface: big drifts + fine grain + float f1 = snFbm(q); + float e = 0.06; + float ef = 0.05; + vec2 g = vec2(snFbm(p + vec2(e, 0.0)) - h0, snFbm(p + vec2(0.0, e)) - h0) / e; + vec2 gf = vec2(snFbm(q + vec2(ef, 0.0)) - f1, snFbm(q + vec2(0.0, ef)) - f1) / ef; + vec3 nT = normalize(vec3(-(g * 0.55 + gf * 0.20) * snow_bump, 1.0)); + + vec3 thin = vec3(0.66, 0.72, 0.80); // thin snow is greyish-blue and lets the dark background through + vec3 full = vec3(0.93, 0.95, 0.98); + vec3 col = mix(thin, full, thick) * (0.62 + 0.55 * f1) * (0.88 + 0.22 * snNoise(f_coord * gridSize * 9.0)) * (0.85 + 0.3 * h0); + float a = clamp(cover * mix(0.50, 0.96, thick) * snow_pack * snow_opacity, 0.0, 0.97); + float under = 1.0 - accA; + accRGB = accRGB + col * a * under; + accN = accN + nT * a * under; + accTr = accTr + mix(0.60, 0.30, thick) * a * under; + accA = accA + a * under; +} + +// --- The snow of the simulation (water_snow.comp): the map of the glass --------------------------------------------------- +// When the renderer simulates the snow of the glass (the param snow_slot holds 1 + its slot), the snow, the water, how packed the +// snow is and the shape of its flakes come from the map of the glass (water.glsl), which keeps them from frame to frame: the flakes +// land and stay where they landed, pile up into a layer, the blades push it into ridges at the ends of their sweeps and leave a wet +// trace, it melts at the warm glass and slush slides down. Here it's only drawn: +// - a texel of the map with a little snow is a flake (atlas tiles 0..2: fluffy when dry, a wet lump when wet or packed, crumbs), +// the more snow the bigger; with mostly water left it's the water spot (tile 3) +// - where the snow is thicker it's a layer: its edge torn by the grain of the snow, as opaque as it's thick (Beer-Lambert), grey +// and translucent when wet (slush), smoother and denser when packed; its relief from the slopes of the snow of the map +// - the water: wet glass bends the picture behind (the post-processing), the thin snow hazes it +// Without the simulation (an older renderer, no compute) the procedural snow below draws the glass as before. +const float snow_map_flake = 1.15; // size of a flake relative to a texel of the map (the snow of a texel) +const float snow_map_layer = 1.0; // mm of snow above which the flakes run together into a layer +const float snow_map_opaque = 1.8; // mm of fresh snow which lets 1/e of the light through (packed: half of it) +const float snow_map_relief = 0.6; // how much the slopes of the snow tilt its surface +const float snow_map_grain = 0.35; // the fine grain of the layer (its relief) +const float snow_map_wet_bend = 0.6; // how strongly a wet glass bends the picture behind it +const float snow_map_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through: the picture + // behind shows through it, blurred, rather than a dark speck at night) + +int snMapSlot = -1; +uint snMapIndex = 0u; +float snWet = 0.0; // set by snowMapped: the film of water (0 .. 1) +vec2 snWetN = vec2(0.0); // set by snowMapped: the slope of the water, for the bend of the picture + +// the snow of the map at a place of the glass +vec4 snMapAt(vec2 uv) +{ + return water_snow_at(uint(snMapSlot), snMapIndex, uv); +} + +// a flake of the map drawn over the accumulators: Local the place in its sprite (0 .. 1), Tile the corner of its tile in the atlas +void snowMapSprite(vec2 local, vec2 tile, float alpha, float tone, float flip, float c, float s, float lod, + inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) +{ + vec4 t = textureLod(raindropsatlas, tile + local * 0.5, lod); + vec4 n = textureLod(normalmap, tile + local * 0.5, lod); + float a = clamp(t.a * alpha * snow_opacity, 0.0, 1.0); + if (a <= 0.0) + return; + vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump; + nxy.x *= flip; + vec2 nuv = vec2(c * nxy.x - s * nxy.y, s * nxy.x + c * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + float tr = (1.0 - t.a * 0.55); + accRGB = t.rgb * tone * a + accRGB * (1.0 - a); + accN = nT * a + accN * (1.0 - a); + accTr = tr * a + accTr * (1.0 - a); + accA = a + accA * (1.0 - a); +} + +// the flakes of the texels around the pixel +void snowMapFlakes(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) +{ + vec2 p = f_coord * float(WATER_MAP); + ivec2 here = ivec2(floor(p)); + for (int oy = -1; oy <= 1; ++oy) + { + for (int ox = -1; ox <= 1; ++ox) + { + ivec2 texel = here + ivec2(ox, oy); + vec4 q = water_snow_texel(uint(snMapSlot), snMapIndex, texel); + float density = mix(0.1, 0.4, q.z); + float wet = q.y / (q.y + q.x * density + 1e-4); + bool spot = (q.x < 0.05) && (q.y > 0.03); // a flake melted into its water + if ((q.x < 0.05) && (false == spot)) + continue; + uint seed = Hash(uvec3(uvec2(texel), uint(q.w * 65535.0) + 7u * uint(snMapSlot))); + // the water of a texel is a droplet only now and then: the more water the more of them + if (spot && (RandF(seed) > smoothstep(0.03, 0.2, q.y))) + continue; + vec2 center = vec2(texel) + vec2(0.15 + 0.7 * RandF(seed), 0.15 + 0.7 * RandF(seed)); + float ang = RandF(seed) * 6.2831853; + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float kind = RandF(seed); + float tone = mix(0.94, 1.04, RandF(seed)); + float aniso = mix(0.62, 1.0, RandF(seed)); + // the more snow the texel holds the bigger the flake (a lump of a few flakes) + float size = snow_map_flake * mix(0.6, 1.0, RandF(seed)) * (spot ? mix(0.5, 1.1, smoothstep(0.03, 0.3, q.y)) + : mix(0.7, 1.6, smoothstep(0.05, 2.0, q.x))); + vec2 d = (p - center) * aspect; + float c = cos(ang); + float s = sin(ang); + vec2 r = vec2(c * d.x + s * d.y, -s * d.x + c * d.y); + r.x *= flip / aniso; + vec2 local = r / size + 0.5; + if (any(lessThan(local, vec2(0.0))) || any(greaterThan(local, vec2(1.0)))) + continue; + float sizeUV = size / float(WATER_MAP); + float lod = clamp(log2(max(pixelUV / sizeUV * 0.5 * float(textureSize(raindropsatlas, 0).x), 1.0)), 0.0, 4.0); + vec2 tile; + if (spot) + tile = vec2(0.5, 0.0); + else if ((wet > 0.3) || (q.z > 0.5) || (kind < 0.30)) + tile = vec2(0.5, 0.5); // a wet lump + else if (kind < 0.75) + tile = vec2(0.0, 0.5); // fluffy + else + tile = vec2(0.0, 0.0); // crumbs + float alpha = spot ? smoothstep(0.03, 0.1, q.y) : smoothstep(0.05, 0.25, q.x) * mix(snow_map_thin, 1.0, smoothstep(0.3, 2.5, q.x)); + snowMapSprite(local, tile, alpha, tone, flip, c, s, lod, accRGB, accA, accN, accTr); + } + } +} + +// the snow of the map at the pixel: the flakes, the layer of the snow under them, the water, the haze +void snowMapped(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, inout float smear, inout vec3 accN, inout float accTr) +{ + vec4 q = snMapAt(f_coord); + float e = 1.0 / float(WATER_MAP); + vec4 qr = snMapAt(f_coord + vec2(e, 0.0)); + vec4 ql = snMapAt(f_coord - vec2(e, 0.0)); + vec4 qu = snMapAt(f_coord + vec2(0.0, e)); + vec4 qd = snMapAt(f_coord - vec2(0.0, e)); + float around = (q.x + qr.x + ql.x + qu.x + qd.x) * 0.2; + + // the flakes of thin snow and the water spots; the picture behind a flake is blurred (it scatters the light going through) + snowMapFlakes(aspect, pixelUV, accRGB, accA, accN, accTr); + snHaze = max(snHaze, smoothstep(0.0, 0.3, accA)); + + // the water: the film bends the picture behind + snWet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); + snWetN = vec2(qr.y - ql.y, qu.y - qd.y) * 2.0 + (vec2(snNoise(f_coord * 900.0), snNoise(f_coord * 900.0 + 31.0)) - 0.5) * 0.6 * snWet; + smear = max(smear, snWet * snow_melt_blur * 0.6); + // thin snow hazes the picture around it + snHaze = max(snHaze, smoothstep(0.15, 1.0, around)); + + // the layer, where the snow has run together + vec2 gp = f_coord * float(WATER_MAP) * aspect; + float grain = snFbm(gp * 0.9 + 3.0) * 0.55 + snFbm(gp * 2.7 + 11.0) * 0.30 + snFbm(gp * 7.1 + 5.0) * 0.15; + float edge = (q.x - snow_map_layer) / max(snow_map_layer, 1e-3) + (grain - 0.5) * 1.6; + float cover = smoothstep(0.0, 0.35, edge); + if (cover <= 0.002) + return; + float density = mix(0.1, 0.4, q.z); + float wet = q.y / (q.y + q.x * density + 1e-4); + float opaque = snow_map_opaque * mix(1.0, 0.5, q.z); + float thick = 1.0 - exp(-q.x / opaque); + // the relief: the slopes of the snow of the map (ridges, the edges of the swept arcs) and the grain of the fresh snow + vec2 slope = vec2(qr.x - ql.x, qu.x - qd.x) * 0.5 * snow_map_relief; + float f1 = snFbm(gp * 3.3); + float ef = 0.05; + vec2 gf = vec2(snFbm(gp * 3.3 + vec2(ef, 0.0)) - f1, snFbm(gp * 3.3 + vec2(0.0, ef)) - f1) / ef; + vec3 nT = normalize(vec3(-(slope + gf * snow_map_grain * (1.0 - 0.6 * q.z)) * snow_bump, 1.0)); + + vec3 fresh = vec3(0.93, 0.95, 0.98); + vec3 packed = vec3(0.89, 0.91, 0.94); + vec3 slush = vec3(0.60, 0.66, 0.73); + vec3 col = mix(mix(fresh, packed, q.z), slush, smoothstep(0.2, 0.7, wet)); + col *= (0.80 + 0.30 * f1 * (1.0 - 0.5 * q.z)) * (0.92 + 0.12 * grain); + float a = clamp(cover * mix(0.35, 0.97, thick) * mix(1.0, 0.75, smoothstep(0.3, 0.8, wet)) * snow_pack * snow_opacity, 0.0, 0.97); + float under = 1.0 - accA; + accRGB = accRGB + col * a * under; + accN = accN + nT * a * under; + accTr = accTr + mix(0.60, 0.25, thick) * a * under; + accA = accA + a * under; +} + +void main() +{ + // Derivatives first, in uniform control flow (no discard before them). + vec3 Ngl = normalize(f_normal); + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec2 duv1 = dFdx(f_coord); + vec2 duv2 = dFdy(f_coord); + vec3 dp2perp = cross(dp2, Ngl); + vec3 dp1perp = cross(Ngl, dp1); + vec3 Tgl = dp2perp * duv1.x + dp1perp * duv2.x; + vec3 Bgl = dp2perp * duv1.y + dp1perp * duv2.y; + float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); + Tgl *= invmax; + Bgl *= invmax; + + vec4 tex_color = texture(diffuse, f_coord); // no discard: clean glass between faint dirt must still get snow and blur + + float gridSize = max(ceil(param[2].x), 1.0); + float pixelUV = max(length(dFdx(f_coord)), length(dFdy(f_coord))); + snHaze = 0.0; + vec2 aspect = (snow_uv_aspect >= 1.0) ? vec2(snow_uv_aspect, 1.0) : vec2(1.0, 1.0 / max(snow_uv_aspect, 0.01)); + + vec3 snowRGB = vec3(0.0); // premultiplied + float snowA = 0.0; + float smear = 0.0; + vec3 snowN = vec3(0.0); + float snowTr = 0.0; + // the snow of the simulation where the glass has a map of it, else made up as before + snMapSlot = int(param[2].z + 0.5) - 1; + bool mapped = (snMapSlot >= 0) && (snMapSlot < WATER_SLOTS) && water_snow_map(uint(snMapSlot), snMapIndex); + if (mapped) + { + // the texels of the map as they lie on the glass (the uv may be stretched) + ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); + uint axis = (uint(snMapSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; + vec2 span = vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)); + if (min(span.x, span.y) > 1e-6) + aspect = span / max(span.x, span.y); + snowMapped(aspect, pixelUV, snowRGB, snowA, smear, snowN, snowTr); + } + else if (rain_params.x > 0.0) + { + float mass = 0.0; + if (snow_small > 0.0) + snowLayer(gridSize * 2.4 / snow_flake_scale, snow_small, 17u, 0.9, 0.85, 0.0, 0, pixelUV, aspect, snowRGB, snowA, smear, snowN, snowTr, mass); + snowLayer(gridSize / snow_flake_scale, snow_density, 13u, 1.0, 1.0, snow_slide_share, 4, pixelUV, aspect, snowRGB, snowA, smear, snowN, snowTr, mass); + if (snow_pack > 0.0) + snowFilm(gridSize, snowRGB, snowA, snowN, snowTr); // patches where flakes have run together + } + + float glassA = tex_color.a * alpha_mult; + float finalA = snowA + glassA * (1.0 - snowA); + vec3 premult = snowRGB + tex_color.rgb * glassA * (1.0 - snowA); + vec3 albedo = premult / max(finalA, 1e-4); + float glassShare = glassA * (1.0 - snowA) / max(finalA, 1e-4); + + // relief: tilt the glass normal by the slope of the snow (flat where there is none) + vec3 nDir = snowN + vec3(0.0, 0.0, 1.0) * (1.0 - snowA); + vec3 fragnormal = Ngl; + if (snowA > 0.001) + fragnormal = normalize(Ngl * max(nDir.z, 0.05) + Tgl * nDir.x + Bgl * nDir.y); + + vec3 fragcolor = ambient; + float reflectivity = param[1].z * glassShare; + float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5 * glassShare + snow_gloss * snowA; + legacy_gloss(); + + // most of the glass is clear (no snow, a clear glass texture): the lighting of the 4.6 renderers (the clusters of lamps, the + // shadows, the reflections) is skipped there, it would be multiplied by an alpha of ~0 + if (finalA > 0.002) + fragcolor = apply_lights(fragcolor, fragnormal, albedo, reflectivity, specularity, shadow_tone); + + // thin snow glows when you look towards the sun / a lamp + if (finalA > 0.002 && snowA > 0.001 && snow_translucency > 0.0 && lights_count > 0U) + { + vec3 I = normalize(f_pos.xyz); + float shadowSun = 0.0; + if (shadow_tone < 1.0) + shadowSun = (1.0 - shadow_tone) * clamp(calc_shadow(), 0.0, 1.0); + float towards = max(dot(I, normalize(-lights[0].dir)), 0.0); + float glow = pow(towards, 3.0) * (1.0 - shadowSun); + fragcolor += lights[0].color * lights[0].intensity * glow * snow_translucency * snowTr * albedo * snowA; + } + vec3 lit = apply_fog(fragcolor); + +#if SNOW_MATCH_RAIN_GLASS + vec4 color = vec4(lit * finalA, finalA); +#else + vec4 color = vec4(lit, finalA); +#endif + + out_color = POSTFX_ENABLED ? color : tonemap(color); + + // the scene seen through the snow, drawn by the post-processing (rain_windscreen_haze.glsl), asked for in the velocity target as + // rain_windscreen asks: thin snow bends it (its relief refracts; x, y = WS_DROP_BIAS + WS_BEND_ENC * bend), elsewhere it's blurred in + // and around thin snow and around the melting spots (x = WS_ENC * strength, y = 0); the snow itself stays sharp. alpha 0 elsewhere: + // the blending keeps the motion of the scene behind + if (MOTIONBLUR_ENABLED) + { + float thin = smoothstep(0.04, 0.20, snowA) * (1.0 - smoothstep(0.55, 0.90, snowA)); + vec4 req = vec4(0.0); + if ((snWet > 0.25) && (snowA < 0.35) && (glassA < 0.5)) + { + // the water on the glass: its film and its spots bend the picture behind + vec2 bend = clamp(-snWetN * snow_map_wet_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.25, 0.6, snWet); + req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); + } + else if ((snow_distort > 0.0) && (thin > 0.30) && (glassA < 0.5)) + { + vec2 slope = snowN.xy / max(snowA, 1e-3); + vec2 bend = clamp(-slope * snow_distort, vec2(-1.0), vec2(1.0)) * smoothstep(0.30, 0.60, thin) * (SNOW_REFR_MAXPX / WS_REFR_MAXPX); + req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); + } + else + { + float haze = snHaze * snow_haze * (1.0 - smoothstep(0.30, 0.80, snowA)); // frosted glass in and around thin snow + float blurMask = clamp(max(smear * (1.0 - snowA), haze) * (1.0 - smoothstep(0.5, 0.95, glassA)), 0.0, 1.0); + if (blurMask >= 0.01) + req = vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0); + } + out_motion = req; + } +} + +float GetMixFactor(in vec2 co, out float side) { + vec4 movePhase = wiper_pos; + bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); + movePhase = mix(vec4(2.) - movePhase, movePhase, is_out); + + vec4 mask = textureLod(wipermask, co, 0.0); // called from non-uniform flow: no implicit derivatives + + vec4 areaMask = step(.001, mask); + + vec4 maskVal = mix(1. - mask, mask, is_out); + vec4 wipeWidth = smoothstep(1., .9, movePhase) * .25; + vec4 cleaned = smoothstep(movePhase - wipeWidth, movePhase, maskVal) * areaMask; + vec4 side_v = step(maskVal, movePhase); + cleaned *= side_v; + side_v = mix(side_v, vec4(1.) - side_v, is_out); + + // "regeneration", snow gradually returning after a wiper pass (slower than rain, and faster in heavy snowfall): + float regenT = max(mix(snow_regen, snow_regen * 0.6, clamp(rain_params.x, 0.0, 1.0)), 0.5); + vec4 sinceV = vec4(time) - mix(wiper_timer_out, wiper_timer_return, side_v) - vec4(.2); + vec4 regenPhase = clamp(sinceV / vec4(regenT), vec4(0.), vec4(1.)); + + side_v = mix(vec4(0.), vec4(1.) - side_v, areaMask); + + vec4 factor_v = mix(vec4(1.), regenPhase * (vec4(1.) - cleaned), areaMask); + + side = 0.; + float out_factor = 1.; + bool have_side = false; + snWipeSince = 1.0e5; + + // out_factor: the blade that clears the grid cell the most wins (as before). + // side: which wiper stroke the drops of this cell belong to. It is part of the random + // seed of every drop, so it must NOT depend on out_factor. It used to: once the drops had + // fully regrown (out_factor == 1) side fell back to 0 and every drop in the swept area + // jumped to a new position, about one regrow time after each stroke (most visible in + // heavy rain, where regrowth takes ~1 s). + for(int i = 0; i < 4; ++i) + { + out_factor = min(out_factor, factor_v[i]); + if (!have_side && areaMask[i] > 0.) + { + side = side_v[i]; + snWipeSince = max(sinceV[i], 0.0); + have_side = true; + } + } + + return out_factor; +} diff --git a/shaders/ogl46/rain_cells.comp b/shaders/ogl46/rain_cells.comp index 6916c3eab..43ab26a60 100644 --- a/shaders/ogl46/rain_cells.comp +++ b/shaders/ogl46/rain_cells.comp @@ -7,7 +7,7 @@ #include "common.glsl" layout(location = 0) uniform float rain_time; // the time of the block of the scene (scene_ubs.time) -layout(location = 1) uniform float rain_amount; // how hard it rains (scene_ubs.rain_params.x) +layout(location = 1) uniform float rain_amount; // how wet the glass is (scene_ubs.rain_state.y, a little more) layout(location = 2) uniform int rain_pass; // 0 the cells, 1 the reach of the drops #include "random.glsl" @@ -125,6 +125,7 @@ float drop_reach(uint A, uint B, float Spread) uvec4 drop_masks(ivec2 Cell) { uvec4 result = uvec4(0u); + // as many drops as the glass is wet (rain_amount: the wetness of the glass, scene_ubs.rain_state.y) float most = min(rain_amount * drop_density, 0.95); for (int dy = -1; dy <= 1; ++dy) for (int dx = -1; dx <= 1; ++dx) diff --git a/shaders/ogl46/rain_cells.glsl b/shaders/ogl46/rain_cells.glsl index 52e248032..5fa8569dd 100644 --- a/shaders/ogl46/rain_cells.glsl +++ b/shaders/ogl46/rain_cells.glsl @@ -53,7 +53,7 @@ const float drop_life_min = 14.0; // seconds a drop sits on the glass const float drop_life_max = 45.0; const float drop_appear = 0.18; // seconds of the landing "pop" const float drop_fade = 1.5; // seconds a drop takes to vanish at the end of its life -const float wiper_miss = 0.05; // share of the drops a blade goes over without taking them +const float wiper_miss = 0.005; // share of the drops a blade goes over without taking them (a tenth of the 0.05 it was) const float streak_period = 40.0; // seconds a rivulet lives (it runs for ~90% of that and then fades out), average const float wind_streak_period = 18.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) diff --git a/shaders/ogl46/settings.glsl b/shaders/ogl46/settings.glsl index 65c441991..cda2ecf39 100644 --- a/shaders/ogl46/settings.glsl +++ b/shaders/ogl46/settings.glsl @@ -4,7 +4,8 @@ #ifndef SETTINGS_GLSL #define SETTINGS_GLSL -#ifdef GL_SPIRV +// (some drivers, AMD's among them, define GL_SPIRV also when they compile the source: the game always puts the values before it) +#if defined(GL_SPIRV) && !defined(SHADOWMAP_ENABLED_VALUE) layout(constant_id = 0) const bool SHADOWMAP_ENABLED = true; layout(constant_id = 1) const bool ENVMAP_ENABLED = true; layout(constant_id = 2) const bool MOTIONBLUR_ENABLED = true; diff --git a/shaders/ogl46/water.glsl b/shaders/ogl46/water.glsl index 6c3dcbfba..f35fbdf75 100644 --- a/shaders/ogl46/water.glsl +++ b/shaders/ogl46/water.glsl @@ -53,6 +53,45 @@ layout(std430, binding = WATER_SSBO_BINDING) readonly buffer water_ssbo uint water_cells[]; }; +// the snow on a glass of the snow (water_snow.comp, mat_snow_windscreen.frag): two maps of WATER_MAP x WATER_MAP texels after the +// wetted paths in water_cells, two uint a texel (halves: x the snow, mm, y the water, mm, z how packed the snow is 0 .. 1, w random +// 0 .. 1, the shape of its flakes); a step reads one and writes the other, the header of the glass says which one is the latest +// (z 1 when there's a map of the snow, w the map) +uint water_snow_base(uint slot, uint map) +{ + return uint(WATER_SLOTS * WATER_GRID * WATER_GRID * (1 + WATER_CELL_DROPS)) + uint(WATER_SLOTS * WATER_TRAIL * WATER_TRAIL) + (map * uint(WATER_SLOTS) + slot) * uint(WATER_MAP * WATER_MAP * 2); +} + +// a texel of a map of the snow, nothing outside the map +vec4 water_snow_texel(uint slot, uint map, ivec2 texel) +{ + if (any(lessThan(texel, ivec2(0))) || any(greaterThanEqual(texel, ivec2(WATER_MAP)))) + return vec4(0.0); + uint index = water_snow_base(slot, map) + 2u * uint(texel.y * WATER_MAP + texel.x); + return vec4(unpackHalf2x16(water_cells[index]), unpackHalf2x16(water_cells[index + 1u])); +} + +// the latest map of the snow of a glass; false when there's none yet +bool water_snow_map(uint slot, out uint map) +{ + vec4 header = water_header[slot]; + map = (header.w > 0.5) ? 1u : 0u; + return header.z > 0.5; +} + +// the latest map of the snow filtered between the texels at a place of the glass +vec4 water_snow_at(uint slot, uint map, vec2 uv) +{ + vec2 p = uv * float(WATER_MAP) - 0.5; + ivec2 i = ivec2(floor(p)); + vec2 f = p - vec2(i); + vec4 a = water_snow_texel(slot, map, i); + vec4 b = water_snow_texel(slot, map, i + ivec2(1, 0)); + vec4 c = water_snow_texel(slot, map, i + ivec2(0, 1)); + vec4 d = water_snow_texel(slot, map, i + ivec2(1, 1)); + return mix(mix(a, b, f.x), mix(c, d, f.x), f.y); +} + // the radius of the footprint of a drop holding Volume mm3 of water, metres: a cap of a sphere meeting the glass at 40 degrees float water_radius(float volume) { diff --git a/shaders/ogl46/water_sim.glsl b/shaders/ogl46/water_sim.glsl index 75919c9e9..d611b6c0e 100644 --- a/shaders/ogl46/water_sim.glsl +++ b/shaders/ogl46/water_sim.glsl @@ -41,6 +41,11 @@ layout(std140, binding = WATER_UBO_BINDING) uniform water_ubo // every glass: x the landings tried in the step, y 1 / the most metres squared a unit of its uv holds, z 1 when it's simulated, // w the size of its drops (rain_scale of its material) vec4 water_slots[WATER_SLOTS]; + // the snow (water_snow.comp): x the flakes coming to a square metre of the ground in a second, y how much warmer than the air + // the glass is, degrees, z the speed of the vehicle, m/s, w the map of the snow the step reads (0, 1) + vec4 water_snow; + // every glass: 1 when its snow is simulated + vec4 water_snow_slots; }; const float WATER_GRAVITY = 9.81; diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp new file mode 100644 index 000000000..f7f60b28a --- /dev/null +++ b/shaders/ogl46/water_snow.comp @@ -0,0 +1,350 @@ +#version 460 core +#define STAGE_COMPUTE 1 +// the snow on the windscreens (water_sim.glsl, water.glsl): a step of the snow of the glasses of the snow, a thread per texel of +// the map of a glass, a row of groups per glass. the step reads one map of the snow and writes the other (water_snow.w says which +// one it reads), so a texel sees its neighbours as they were before the step +// +// what a texel holds: the snow, mm (as it lies, fluffy or packed), the water, mm (the melted snow, a film on the glass and soaked +// into the snow), how packed the snow is (0 fresh flakes .. 1 snow pressed by a blade) and a random number, the shape of its +// flakes (mat_snow_windscreen.frag). in a step, in this order: +// - the snow and the water move: wet heavy snow (slush) slides down the glass, dry powder is blown along it by the air at speed, +// the water runs down as a film and is pushed by the air; and snow piled higher than its neighbours by more than it holds slips +// onto them (a ridge left by a blade spreads into a wedge). what goes over the edge of the glass falls off +// - the blades: a blade going over a texel in the step takes its snow (a little stays, and a wet trace of the water), and pushes +// it on in front of itself: the texel just ahead of the line of texels the blade went over gets their snow, packed (each texel +// to one texel at most: the snow pushed along is never counted twice). at the end +// of its sweep the blade leaves it there, a ridge; pushed past the edge of the glass, it's gone +// - the flakes land: as many as come to the glass facing the snow coming at it against the cab (and a few in the eddies of the +// air where it doesn't face it), each bringing its snow to the texel; the faster the vehicle the more of the dry ones bounce off +// - the snow melts: the glass is warmer than the air (the cab is heated), the less so the faster the vehicle goes; above zero the +// snow melts at the glass into its water, the water dries slowly + +#include "common.glsl" +#include "water_sim.glsl" + +layout(local_size_x = WATER_GROUP_SIZE) in; + +// how dense the snow is: fresh flakes and snow pressed by a blade (the water in a mm of it, mm) +const float SNOW_FRESH = 0.1; +const float SNOW_PACKED = 0.4; +// the snow of a flake, mm3 of water (0.3 .. 2.5 as the flakes of the water passes, water_spawn.comp) +const float SNOW_FLAKE_LEAST = 0.3; +const float SNOW_FLAKE_MOST = 2.5; +// the speed of the snow coming at the glass in the eddies of the air, m/s: a glass not facing the snow gets a little of it +const float SNOW_EDDIES = 0.25; +// the most snow a texel holds, mm, and the step of the snow to a neighbour it holds without slipping onto it, mm +const float SNOW_MOST = 40.0; +const float SNOW_REPOSE = 3.0; +// the share of the snow over the step slipping onto the neighbour in a second +const float SNOW_SLIP = 6.0; +// the share of the snow a blade leaves (at most SNOW_WIPE_LEFT mm: the snow it pushes along goes with it), of the water, and +// of the water of the snow it takes which it leaves as a wet trace (at most SNOW_WIPE_WET mm) +const float SNOW_WIPE_MISS = 0.03; +const float SNOW_WIPE_LEFT = 0.03; +const float SNOW_WIPE_WATER = 0.1; +const float SNOW_WIPE_TRACE = 0.08; +const float SNOW_WIPE_WET = 0.015; +// the longest line of texels a blade goes over in a step, texels +const int SNOW_WIPE_LINE = 12; +// the water the snow melts into at the glass a second for each degree the glass is above zero, mm +const float SNOW_MELT = 0.003; +// the water drying a second, mm, and the share of a thin film going in a second (it dries and runs off as droplets) +const float SNOW_DRY = 0.0004; +const float SNOW_FILM_DRY = 0.15; +// how fast slush slides down a vertical glass, how fast dry powder goes with the air (a share of the speed of the air along the +// glass), how fast the film of water runs down a vertical glass and goes with the air, m/s +const float SNOW_SLIDE = 0.03; +const float SNOW_BLOW = 0.004; +const float SNOW_RUN = 0.02; +const float SNOW_RUN_AIR = 0.002; + +// the neighbours of a texel +const ivec2 SNOW_AROUND[8] = ivec2[8](ivec2(-1, -1), ivec2(0, -1), ivec2(1, -1), ivec2(-1, 0), ivec2(1, 0), ivec2(-1, 1), ivec2(0, 1), ivec2(1, 1)); + +uint snow_slot; +uint snow_from; +uint snow_axes_base; + +bool snow_on_glass(ivec2 texel) +{ + if (any(lessThan(texel, ivec2(0))) || any(greaterThanEqual(texel, ivec2(WATER_MAP)))) + return false; + return water_axes[(snow_axes_base + uint(texel.y * WATER_MAP + texel.x)) * 2u].w > 0.75; +} + +vec4 snow_get(ivec2 texel) +{ + return snow_on_glass(texel) ? water_snow_texel(snow_slot, snow_from, texel) : vec4(0.0); +} + +float snow_blade(ivec2 texel, int blade) +{ + texel = clamp(texel, ivec2(0), ivec2(WATER_MAP - 1)); + return water_blades[snow_axes_base + uint(texel.y * WATER_MAP + texel.x)][blade]; +} + +// whether the blade went over the texel in the step (it reaches it, and the place of the texel along its sweep is between where +// the blade was and where it is, the place it was at belonging to the step before) +bool snow_crossed(ivec2 texel, int blade) +{ + float before = water_blades_before[blade]; + float now = water_blades_now[blade]; + if ((before < 0.0) || (now < 0.0) || (now == before) || (false == snow_on_glass(texel))) + return false; + float place = snow_blade(texel, blade); + if (place <= 0.001) + return false; + return (now > before) ? ((place > before) && (place <= now)) : ((place < before) && (place >= now)); +} + +// the way the blade goes over the texel, a step of a texel (zero when it can't be told) +ivec2 snow_blade_way(ivec2 texel, int blade) +{ + float here = snow_blade(texel, blade); + float right = snow_blade(texel + ivec2(1, 0), blade); + float left = snow_blade(texel - ivec2(1, 0), blade); + float up = snow_blade(texel + ivec2(0, 1), blade); + float down = snow_blade(texel - ivec2(0, 1), blade); + // one-sided where a neighbour is out of the sweep + right = (right > 0.001) ? right : here; + left = (left > 0.001) ? left : here; + up = (up > 0.001) ? up : here; + down = (down > 0.001) ? down : here; + vec2 gradient = vec2(right - left, up - down); + if (dot(gradient, gradient) < 1e-12) + return ivec2(0); + vec2 way = normalize(gradient) * ((water_blades_now[blade] > water_blades_before[blade]) ? 1.0 : -1.0); + return ivec2(round(way)); +} + +// whether no blade goes over the texel now: the snow piled there may slip onto its neighbours (in a sweep of a working blade +// the snow it pushes would slip behind it, a stripe of snow left on the wiped glass for every step) +bool snow_unswept(ivec2 texel) +{ + for (int blade = 0; blade < 4; ++blade) + { + if ((water_blades_now[blade] >= 0.0) && (water_blades_now[blade] != water_blades_before[blade]) && (snow_blade(texel, blade) > 0.001)) + return false; + } + return true; +} + +// the frame of the glass at a texel, unfiltered +water_frame_s snow_frame(ivec2 texel) +{ + uint index = snow_axes_base + uint(texel.y * WATER_MAP + texel.x); + vec4 a = water_axes[index * 2u]; + vec4 b = water_axes[index * 2u + 1u]; + water_frame_s frame = water_frame_s(a.xyz, b.xyz, vec3(0.0, 0.0, 1.0), a.w); + vec3 n = cross(a.xyz, b.xyz); + if (dot(n, n) > 1e-24) + frame.normal = normalize(n) * ((b.w < 0.0) ? -1.0 : 1.0); + return frame; +} + +// how the snow (xy) and the water (zw) of a texel move, texels a second +vec4 snow_motion(ivec2 texel, vec4 state) +{ + if ((state.x <= 0.001) && (state.y <= 0.001)) + return vec4(0.0); + water_frame_s frame = snow_frame(texel); + vec3 n = frame.normal; + vec3 down = -water_up.xyz; + vec3 slope = down - n * dot(down, n); + vec3 air = water_air.xyz - n * dot(water_air.xyz, n); + float wind = length(air); + float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); + float wet = state.y / (state.y + state.x * density + 1e-4); + // slush: wet and heavy enough to go; dry powder: loose and thin enough to be blown + float slide = SNOW_SLIDE * smoothstep(0.25, 0.7, wet) * smoothstep(2.0, 8.0, state.x); + float blow = SNOW_BLOW * smoothstep(10.0, 25.0, wind) * (1.0 - state.z) * (1.0 - smoothstep(0.1, 0.3, wet)) * (1.0 - smoothstep(1.0, 4.0, state.x)); + vec3 snow = slope * slide + air * blow; + // the film of water runs where there's enough of it, not the water soaked into the snow + float film = (1.0 - smoothstep(0.5, 3.0, state.x)); + vec3 water = (slope * SNOW_RUN * smoothstep(0.03, 0.15, state.y) + air * SNOW_RUN_AIR * smoothstep(0.03, 0.1, state.y)) * film; + return vec4(water_to_uv(frame, snow), water_to_uv(frame, water)) * float(WATER_MAP); +} + +// the shares of a texel going to its neighbours along x and along y in the step, for a motion in texels a second +vec2 snow_out(vec2 motion, float seconds) +{ + return min(abs(motion) * seconds, vec2(0.45)); +} + +// the snow and the water of the texel after they moved in the step: what leaves it, what comes from its neighbours; the +// packing and the shape go with the snow +vec4 snow_move(ivec2 texel, vec4 state, float seconds) +{ + vec4 motion = snow_motion(texel, state); + vec2 snowout = snow_out(motion.xy, seconds); + vec2 waterout = snow_out(motion.zw, seconds); + float snow = state.x * (1.0 - snowout.x - snowout.y); + float water = state.y * (1.0 - waterout.x - waterout.y); + float packed = state.z * snow; + bool unswept = snow_unswept(texel); + float slip = min(SNOW_SLIP * seconds, 0.2); + const ivec2 sides[4] = ivec2[4](ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1)); + for (int k = 0; k < 4; ++k) + { + ivec2 side = sides[k]; + ivec2 other = texel + side; + bool glass = snow_on_glass(other); + vec4 neighbour = glass ? water_snow_texel(snow_slot, snow_from, other) : vec4(0.0); + // slipping onto the neighbour (off the glass: falling off) and from it, where no blade goes over either now + bool slips = unswept && snow_unswept(other); + float away = slips ? slip * max(state.x - neighbour.x - SNOW_REPOSE, 0.0) : 0.0; + snow -= away; + packed -= away * state.z; + if (false == glass) + continue; + float coming = slips ? slip * max(neighbour.x - state.x - SNOW_REPOSE, 0.0) : 0.0; + // what the motion of the neighbour brings: it goes this way along the axis of the side + vec4 itsmotion = snow_motion(other, neighbour); + vec2 itssnow = snow_out(itsmotion.xy, seconds); + vec2 itswater = snow_out(itsmotion.zw, seconds); + if (side.x != 0) + { + coming += (itsmotion.x * float(side.x) < 0.0) ? neighbour.x * itssnow.x : 0.0; + water += (itsmotion.z * float(side.x) < 0.0) ? neighbour.y * itswater.x : 0.0; + } + else + { + coming += (itsmotion.y * float(side.y) < 0.0) ? neighbour.x * itssnow.y : 0.0; + water += (itsmotion.w * float(side.y) < 0.0) ? neighbour.y * itswater.y : 0.0; + } + snow += coming; + packed += coming * neighbour.z; + } + snow = max(snow, 0.0); + return vec4(snow, max(water, 0.0), (snow > 1e-4) ? clamp(packed / snow, 0.0, 1.0) : 0.0, state.w); +} + +// the snow and the water of the line of texels the blade went over in the step, ending at a texel (the blade goes on from it to +// the texel ahead), and the packing of the snow (summed for its snow) +vec3 snow_line(ivec2 last, int blade, ivec2 way) +{ + vec3 line = vec3(0.0); + for (int k = 0; k < SNOW_WIPE_LINE; ++k) + { + ivec2 texel = last - way * k; + if (false == snow_crossed(texel, blade)) + break; + vec4 state = water_snow_texel(snow_slot, snow_from, texel); + line += vec3(state.x, state.y, state.x * state.z); + } + return line; +} + +void main() +{ + snow_slot = gl_WorkGroupID.y; + uint place = gl_GlobalInvocationID.x; + if ((water_snow_slots[snow_slot] < 0.5) || (place >= uint(WATER_MAP * WATER_MAP))) + return; + snow_from = (water_snow.w > 0.5) ? 1u : 0u; + uint to = 1u - snow_from; + snow_axes_base = snow_slot * uint(WATER_MAP * WATER_MAP); + if (place == 0u) + water_header[snow_slot].zw = vec2(1.0, float(to)); + ivec2 texel = ivec2(int(place % uint(WATER_MAP)), int(place / uint(WATER_MAP))); + uint index = water_snow_base(snow_slot, to) + 2u * place; + if (false == snow_on_glass(texel)) + { + water_cells[index] = 0u; + water_cells[index + 1u] = 0u; + return; + } + float seconds = water_step.x; + vec4 before = water_snow_texel(snow_slot, snow_from, texel); + vec4 state = snow_move(texel, before, seconds); + + // the blades: taken where they went over, pushed on in front of them + bool crossed = false; + vec3 pushed = vec3(0.0); + for (int blade = 0; blade < 4; ++blade) + { + if (snow_crossed(texel, blade)) + { + crossed = true; + continue; + } + // every texel the blade went over goes to one texel ahead at most, so the snow it pushes isn't counted twice (it would + // grow at every step): in the sweep the texel takes the line of texels behind itself along the way of the blade, off the + // sweep (the blade pushes the snow out at its edge) the line of one of its neighbours pointing at it + if (snow_blade(texel, blade) > 0.001) + { + ivec2 way = snow_blade_way(texel, blade); + if ((way != ivec2(0)) && snow_crossed(texel - way, blade)) + pushed += snow_line(texel - way, blade, way); + continue; + } + for (int k = 0; k < 8; ++k) + { + ivec2 from = texel + SNOW_AROUND[k]; + if (false == snow_crossed(from, blade)) + continue; + ivec2 way = snow_blade_way(from, blade); + if ((way != ivec2(0)) && (from + way == texel)) + { + pushed += snow_line(from, blade, way); + break; + } + } + } + if (crossed) + { + float left = min(state.x * SNOW_WIPE_MISS, SNOW_WIPE_LEFT); + float taken = state.x - left; + state.x = left; + state.y = state.y * SNOW_WIPE_WATER + min(taken * mix(SNOW_FRESH, SNOW_PACKED, state.z) * SNOW_WIPE_TRACE, SNOW_WIPE_WET); + } + if (pushed.x + pushed.y > 0.0) + { + float snow = state.x + pushed.x; + // pressed by the blade + state.z = (snow > 1e-4) ? clamp((state.z * state.x + max(pushed.z, pushed.x * 0.85)) / snow, 0.0, 1.0) : state.z; + state.x = snow; + state.y += pushed.y * 0.5; + } + + // the flakes landing + water_frame_s frame = snow_frame(texel); + float area = length(cross(frame.tu, frame.tv)) / float(WATER_MAP * WATER_MAP); // m2 + vec3 coming = water_air.xyz - water_up.xyz * water_air.w; // the snow against the cab, m/s + float facing = max(-dot(coming, frame.normal), 0.0) + SNOW_EDDIES; + float speed = water_snow.z; + float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); + float wet = state.y / (state.y + state.x * density + 1e-4); + // the dry flakes bounce off a fast glass, the ones landing on wet snow or water stay + float sticking = 1.0 - 0.6 * smoothstep(15.0, 35.0, speed) * (1.0 - smoothstep(0.1, 0.4, wet)); + float landings = water_snow.x / max(water_air.w, 0.1) * facing * area * seconds * sticking; + vec4 random = water_random(place, snow_slot, water_counts.x, 0x5e0du); + float count = min(floor(landings) + ((random.x < fract(landings)) ? 1.0 : 0.0), 4.0); + if (count > 0.0) + { + float water = count * mix(SNOW_FLAKE_LEAST, SNOW_FLAKE_MOST, random.y * random.y); // mm3 + float added = water / SNOW_FRESH / max(area * 1e6, 1e-3); // mm of fresh snow over the texel + float snow = state.x + added; + state.z = state.z * state.x / snow; + // a flake on the bare glass has a shape of its own + state.w = (state.x < 0.3) ? random.z : state.w; + state.x = snow; + } + + // the melting at the warm glass and the drying + float glass = water_up.w + water_snow.y / (1.0 + speed / 12.0); + float melted = min(SNOW_MELT * max(glass, 0.0) * seconds, state.x * density); + state.x -= melted / max(density, 1e-3); + float film = state.y * (1.0 - smoothstep(0.5, 3.0, state.x)); // the water not soaked into the snow + state.y = max(state.y + melted - (SNOW_DRY + SNOW_FILM_DRY * film) * seconds, 0.0); + + state.x = clamp(state.x, 0.0, SNOW_MOST); + state.y = min(state.y, 4.0); + if (state.x < 0.002) + { + state.x = 0.0; + state.z = 0.0; + } + water_cells[index] = packHalf2x16(state.xy); + water_cells[index + 1u] = packHalf2x16(state.zw); +} diff --git a/shaders/vk14/common.glsl b/shaders/vk14/common.glsl index b2aa5218b..dfc741624 100644 --- a/shaders/vk14/common.glsl +++ b/shaders/vk14/common.glsl @@ -142,6 +142,12 @@ #define CAB_PROBE_SH_GROUP_SIZE 64 #endif +// the places along the sweep of a blade whose rain is kept (gl::WIPER_PASS_BUCKETS): the renderer defines it, an older one doesn't +#ifndef WIPER_PASS_BUCKETS +#define WIPER_PASS_BUCKETS 64 +#endif + + #include "settings.glsl" #if !defined(LAYOUT_UI) && !defined(LAYOUT_COMPUTE) @@ -337,6 +343,10 @@ layout(std140, set = PASS_SET, binding = SCENE_UBO) uniform scene_ubo // the place of the camera of the pass in the world (whole 64 m, the rest), see gl::scene_ubs vec4 camera_hi; vec4 camera_lo; + // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills (mat_rain_windscreen), see gl::scene_ubs + vec4 rain_state; + // the rain fallen when a blade last went over a place of its sweep (the wiper mask / 64), see gl::scene_ubs + vec4 wiper_rain_pass[WIPER_PASS_BUCKETS]; }; #ifndef LAYOUT_COMPUTE diff --git a/shaders/vk14/mat_rain_windscreen.frag b/shaders/vk14/mat_rain_windscreen.frag index 9b8bfb2a8..89f1c263f 100644 --- a/shaders/vk14/mat_rain_windscreen.frag +++ b/shaders/vk14/mat_rain_windscreen.frag @@ -83,20 +83,26 @@ layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler // --- Haze of the wet glass (blur) ------------------------------------------------ // The haze follows the rain and is wiped away by the wipers, as before (fully blurred from a quarter of the haze on). const float blur_amount = 1.0; // strength of the haze: 0 = off, 1 = full -// after the wiper the haze grows with the rain fallen on the glass since (intensity x seconds) from nothing up to its full -// strength, which is the intensity of the rain (cloud cover 1.5 -> 0.5). where no wiper reaches it is as always -const float haze_fill = 12.0; // rain to mist the glass up fully: seconds of the heaviest rain (2x as long at 1.5) +// after the wiper the haze grows with the rain fallen on the glass since (intensity x seconds, more at speed) from nothing up to +// its full strength, in any rain (a lighter rain takes longer). where no wiper reaches it is full +const float haze_fill = 12.0; // rain fallen since the blade to mist the glass up fully: seconds of the heaviest + // rain standing still (2x as long at 1.5; the speed counted in by the game) const float haze_curve = 1.0; // > 1: slow at first, then more and more -const float haze_speed = 1.0; // at speed the haze grows: x (1 + haze_speed) at full speed (see wind_drag_gain) const float WS_BEND_ENC = 60.0; // the drop request in the velocity target; must match rain_windscreen_haze.glsl const float WS_DROP_BIAS = 192.0; const float WS_ENC = 64.0; // the haze request in the velocity target; must match rain_windscreen_haze.glsl +// --- How the water gathers on the glass ------------------------------------------------------------------ +// the game counts the rain the glass meets (rain_state, gl::scene_ubs; more at speed) and how wet the glass is (0 dry .. 1 as full +// of drops as it gets): the glass fills up to the full in any rain, a lighter one only takes longer, and dries when the rain stops. +// the times are in the game (fill_rate, fill_speed, dry_halflife in the setup of the scene block). where a blade went over the glass +// the drops come back with the rain fallen since + // --- Drops (atlas tiles) ------------------------------------------------------ // (how long they live: rain_cells.glsl; the cells of the drops and of the rivulets are worked out once a frame by rain_cells.comp) // --- Micro droplets ------------------------------------------------------------- -const float micro_density = 0.45; // share of micro cells holding a droplet at full rain, 0 = off +const float micro_density = 0.45; // share of micro cells holding a droplet on a full glass, 0 = off const float micro_scale = 3.0; // micro grid = raindrop_grid_size * micro_scale const float micro_size_min = 0.12; // droplet radius in micro cells const float micro_size_max = 0.40; @@ -268,6 +274,14 @@ vec4 wsOver(vec4 over, vec4 under) // =========================================================================== float GetMixFactor(in vec2 co, out float side); +// the rain fallen when each blade last went over the place of its sweep given by the wiper mask (-1: not known), see +// gl::scene_ubs::wiper_rain_pass +vec4 wsWipePass(vec4 mask) +{ + ivec4 b = min(ivec4(max(mask, vec4(0.0)) * float(WIPER_PASS_BUCKETS)), ivec4(WIPER_PASS_BUCKETS - 1)); + return vec4(wiper_rain_pass[b.x].x, wiper_rain_pass[b.y].y, wiper_rain_pass[b.z].z, wiper_rain_pass[b.w].w); +} + uvec2 cellKey(vec2 c); vec2 tileOffset(float choice) @@ -366,7 +380,7 @@ Riv getRiv(vec2 sCell, float sCW, float sCH, float gridSize) { Riv r; uvec4 d = rain_cells[rain_riv_index(wsLayerIndex, ivec2(sCell))]; - r.on = ((float(d.x & 65535u) + 0.5) * (1.0 / 65536.0) < rain_params.x * streak_density * wsLayerDensity); + r.on = ((float(d.x & 65535u) + 0.5) * (1.0 / 65536.0) < streak_density * wsLayerDensity * rain_state.y); // as wet as the glass is r.life = float((d.x >> 16) & 255u) * (1.0 / 255.0); float wr = rain_byte(d.y, 16u); r.width = streak_head * wsLayerHead / gridSize @@ -559,23 +573,16 @@ float wsKept(vec2 cg, float rad, float sCW, float sCH, float gridSize) return kept; } -// seconds since a wiper blade last went over Co (texture UV), from the timers of its strokes as GetMixFactor takes them; -// -1 where no wiper reaches -float wsWipeAge(vec2 co) +// the rain fallen (rain_state.x) since a blade last went over this place (texture UV); -1 where no blade goes or not known +float wsWipeRain(vec2 co) { - vec4 movePhase = wiper_pos; - bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); - movePhase = mix(vec4(2.) - movePhase, movePhase, is_out); vec4 mask = textureLod(wipermask, co, 0.0); - vec4 maskVal = mix(1. - mask, mask, is_out); - vec4 passed = step(maskVal, movePhase); - vec4 sideV = mix(passed, vec4(1.) - passed, is_out); - vec4 ages = vec4(time) - mix(wiper_timer_out, wiper_timer_return, sideV); - float age = -1.0; + vec4 at = wsWipePass(mask); + float fallen = -1.0; for (int i = 0; i < 4; ++i) - if ((mask[i] > 0.001) && ((age < 0.0) || (ages[i] < age))) - age = max(ages[i], 0.0); - return age; + if ((mask[i] > 0.001) && (at[i] >= 0.0)) + fallen = (fallen < 0.0) ? max(rain_state.x - at[i], 0.0) : min(fallen, max(rain_state.x - at[i], 0.0)); + return fallen; } // the tangent frame of the glass (the directions of u and v on it, view space) from the screen-space change of the place and the uv @@ -633,10 +640,6 @@ void main() float wsNight = smoothstep(0.0, drop_dark_lum, sceneLum); // 0 dark night .. 1 daylight dynBright *= wsNight; - // wiper state of this pixel (blur, micro droplets) - float hazeSide; - float wipeVis = GetMixFactor(f_coord, hazeSide); - Hit hit; hit.score = 0.0; hit.cov = 0.0; hit.colA = 0.0; hit.n = vec3(0.0, 0.0, 1.0); hit.offUV = vec2(0.0); hit.radUV = 1.0; hit.isDrop = 1.0; @@ -683,6 +686,10 @@ void main() wsPushT = vec2(dot(wsPush, Tgl), dot(wsPush, Bgl)); wsPushT = (dot(wsPushT, wsPushT) > 1e-10) ? normalize(wsPushT) : vec2(0.0, -1.0); } + + // the wiper state of this pixel (blur, micro droplets) + float hazeSide; + float wipeVis = GetMixFactor(f_coord, hazeSide); // the change of the glass UV (v up) per screen pixel, for the rivulets vec2 wsRd1 = vec2(duv1.x, flipS * duv1.y); vec2 wsRd2 = vec2(duv2.x, flipS * duv2.y); @@ -695,7 +702,7 @@ void main() vec2 sCell = floor(sUVg / vec2(sCW, sCH)); bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0) && (WS_PROFILE != 2); - if ((rain_params.x > 0.001) && (WS_PROFILE != 5)) + if ((rain_state.y > 0.001) && (WS_PROFILE != 5)) { // =================================================================== // 1. drops from the atlas: this cell and its 8 neighbours @@ -713,6 +720,9 @@ void main() reach &= reach - 1u; vec2 nc = cell + vec2(float(bit % 3 - 1), float(bit / 3 - 1)); uvec4 d = rain_cells[rain_drop_index(ivec2(nc))]; + // as many drops as the glass is wet (the cells were sorted out with a little more) + if (rain_byte(d.y, 24u) > min(rain_state.y * drop_density, 0.95)) + continue; float vis = float(d.w >> 24) * (1.0 / 255.0); float spreadF = mix(0.8, 1.0, float((d.y >> 19) & 31u) * (1.0 / 31.0)); // a drop the blades miss: the same drop before and after the stroke, left where it is @@ -786,7 +796,7 @@ void main() float mph = fract(mtt); uint mep = uint(mod(floor(mtt), 65521.0)); uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); - if (RandF(m1) < min(rain_params.x * micro_density, 0.95)) + if (RandF(m1) < min(micro_density * rain_state.y, 0.95)) { uint m2 = Hash(uvec3(mk, mep * 4u + 2u + uint(hazeSide) * 2u)); if (wipeVis >= RandF(m2)) @@ -996,10 +1006,11 @@ void main() // What is seen through the wet glass: the image of the last frame, blurred by the haze, bent by the drops // ----------------------------------------------------------------------- // the haze after the wiper: grows with the rain fallen since, up to the intensity of the rain (as it always was where no wiper reaches) - float wipeAge = wsWipeAge(f_coord); - float hazeBack = (wipeAge < 0.0) ? 1.0 - : min(wipeVis, pow(clamp(wipeAge * rain_params.x / haze_fill, 0.0, 1.0), haze_curve)); - float hazeWeight = min(rain_params.x * hazeBack * (1.0 + haze_speed * wsSpeed), 1.0) * (1.0 - max(alphaOut, coverA)); + float wipeRain = wsWipeRain(f_coord); + float hazeBack = (wipeRain < 0.0) ? rain_state.y + : min(rain_state.y, pow(clamp(wipeRain / haze_fill, 0.0, 1.0), haze_curve)); + // up to the full haze in any rain, as the glass gets wet (a lighter rain only mists it up more slowly), less as it dries + float hazeWeight = hazeBack * (1.0 - max(alphaOut, coverA)); float glassClear = 1.0 - smoothstep(0.5, 0.95, glassA); bool image = ssr_params.x >= 1.0; float background = 0.0; // distance to the scene behind, along the view (0: far / not known) @@ -1099,7 +1110,13 @@ float GetMixFactor(in vec2 co, out float side) { side_v = mix(side_v, vec4(1.) - side_v, is_out); // "regeneration", raindrops gradually returning after wiper pass: - vec4 regenPhase = clamp((vec4(time) - mix(wiper_timer_out, wiper_timer_return, side_v) - vec4(.2)) / vec4(rain_params.y), vec4(0.), vec4(1.)); + // the share of the drops back: the glass fills with the rain fallen since the blade (rain_state), up to as wet as the glass is + // where no blade goes (the drops of a cell are there only up to that share, so the share of those back is the fill over it) + vec4 at = wsWipePass(mask); + vec4 fallen = vec4(rain_state.x) - at; + vec4 known = step(vec4(0.), at); + vec4 filled = mix(vec4(1.), vec4(1.) - exp(-max(fallen, vec4(0.)) * rain_state.z), known); + vec4 regenPhase = clamp(filled / max(rain_state.y, 1e-4), vec4(0.), vec4(1.)); side_v = mix(vec4(0.), vec4(1.) - side_v, areaMask); diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag new file mode 100644 index 000000000..183193b69 --- /dev/null +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -0,0 +1,784 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +#include "common.glsl" +// Windscreen snow: replaces rain_windscreen when it snows - v2 (OpenGL 4.6 / Vulkan 1.4 port of the OpenGL 3.3 v1) +// v2: the syntax of the 4.6 renderers (explicit locations and bindings, #pragma texture / param), the tuning values as constants +// (a uniform can't have a default any more); the blur of the scene and the picture bent by thin snow go to the +// post-processing through the velocity target, as the haze and the drops of rain_windscreen (postfx_taa.frag / +// postfx_motionblur.frag with rain_windscreen_haze.glsl); the colour is written straight +// (not premultiplied) as rain_windscreen of the 4.6 renderers writes the glass; the gloss of the glass from legacy_gloss(); +// no lighting where the glass is clear (no snow, a clear texture). the look and the behaviour of the snow are those of v1. +// +// MaSzyna switches the weather itself (simulationenvironment.cpp): with Overcast > 1 it rains when the air is warmer +// than 1 deg C and it SNOWS at 1 deg C and below, and the .mat block "snow:" is picked. rain_params.x is the +// precipitation intensity (saturate(Overcast - 1)), exactly what rain_windscreen uses for the drops, so the snow +// on the glass follows the snowfall: nothing without snow, and the harder it snows the more the glass gets plastered. +// +// - flakes: every cell of the glass can hold a flake (atlas tiles 0..2: fluffy, wet lump, crumbs). It lands at a random +// moment, stays white for `snow_hold` seconds and then MELTS for `snow_melt` seconds: the snow fades into a water spot +// (tile 3). About `snow_slide_share` of the melting flakes also SLIDE DOWN the glass, stretching into a drip. +// Only the wet, melting spot blurs the scene (water refracts; dry snow does not, see snow_fresh_blur). +// - clumping: flakes land small and GROW as more snow piles onto them. Where flakes land next to each other they run together +// into one bigger patch (a crusty white film), and the more it snows the more flakes land side by side, so the bigger +// the patches get. The patch exists only where flakes really sit close together; when they melt / slide away it breaks +// up and thins out (snow_clump). +// - wipers (wipermask, GetMixFactor) clear all of it; it builds up again after `snow_regen` seconds (faster in heavy snow). +// Nothing depends on the time since the game started. +// +// Atlas / normalmap (blender_snow_atlas.py), 2 x 2 tiles: +// 0 dry fluffy flake 1 wet compact lump 2 crumbs 3 melted spot (water + ice remnants) +// +// .mat: +// +// texture_diffuse: dynamic/pkp/vectron_v1/cab/szyby +// texture_raindropsatlas: textures/fx/raindrops-atlas +// texture_normalmap: textures/fx/raindrops_normalmap +// texture_wipermask: dynamic/pkp/vectron_v1/cab/szyby_wipermask +// shader: rain_windscreen +// param_raindrop_grid_size: 150 +// +// snow: { +// shader: snow_windscreen +// texture_raindropsatlas: textures/fx/snow-atlas +// texture_normalmap: textures/fx/snow_normalmap +// param_raindrop_grid_size: 70 +// } +// +// One cell is about one flake: a grid of ~50-90 gives flakes of ~1-2 cm on a ~1.5 m windscreen. + +layout(location = 0) in vec3 f_normal; +layout(location = 2) in vec2 f_coord; +layout(location = 3) in vec4 f_pos; +layout(location = 4) in vec4 f_clip_pos; +layout(location = 5) in vec4 f_clip_future_pos; + +layout(location = 0) out vec4 out_color; +#ifdef NO_MOTION_OUTPUT +// a pass without the velocity target: the writes go nowhere +vec4 out_motion; +#else +layout(location = 1) out vec4 out_motion; +#endif + +#pragma texture(diffuse, 0, sRGB_A) +#pragma texture(raindropsatlas, 1, sRGB_A) +#pragma texture(wipermask, 2, sRGB_A) +#pragma texture(normalmap, 3, RGBA) // flakes: rg = normal xy, b = height, a = mask; same 2x2 layout as raindropsatlas (linear) +#pragma param(color, 0, 0, 4, diffuse) +#pragma param(diffuse, 1, 0, 1, diffuse) +#pragma param(specular, 1, 1, 1, specular) +#pragma param(reflection, 1, 2, 1, zero) +#pragma param(glossiness, 1, 3, 1, glossiness) +#pragma param(raindrop_grid_size, 2, 0, 1, one) +// snow_slot: 1 + the slot of the glass in the simulation of the snow (the renderer sets it), 0: none +#pragma param(snow_slot, 2, 2, 1, zero) + +#include "light_common.glsl" +#include "apply_fog.glsl" +#include "tonemapping.glsl" +#include "random.glsl" +#include "water.glsl" + +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 0) uniform sampler2D diffuse; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 1) uniform sampler2D raindropsatlas; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler2D wipermask; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D normalmap; + +// --- Tuning ----------------------------------------------------------------- +// Intensity = rain_params.x = saturate(Overcast - 1). The slider range 1.00..2.00 (Overcast) maps to intensity 0..1. The share of flake cells is pow(intensity, 0.8) * snow_gain * snow_density, +// so with the defaults every cell carries a flake from Overcast ~ 1.2 and the film closes the glass at about 1.3 (1.1 = light snow, 1.5+ = blizzard). +const float snow_gain = 1.4; // how fast the glass gets covered when the snowfall gets heavier (higher = already plastered in light snow) +const float snow_density = 0.95; // upper limit of the share of cells that carry a big flake +const float snow_small = 0.80; // same for the layer of small flakes (0 = off) +const float snow_pack = 0.90; // opacity of the patches that form where flakes clump together (0 = no patches) +const float snow_clump = 2.60; // how readily neighbouring flakes run together into one patch (higher = patches form sooner and get bigger) +const float snow_clump_share = 0.55; // share of the flakes that run together into patches; the rest stay separate flakes +const float snow_hold = 40.0; // seconds a flake stays white before it starts to melt (longer in heavy snow) +const float snow_melt = 30.0; // seconds the melting takes (snow fades into a water spot) +const float snow_slide_share = 0.40; // share of the melting flakes that run down the glass +const float snow_slide_len = 2.0; // how far a sliding flake runs, in cells (max 2.4) +const float snow_grow_fast = 5.3; // seconds a patch needs to grow from a clump to a big sheet in the heaviest snowfall +const float snow_grow_slow = 46.7; // same in the lightest snowfall (it still gets there, just much later) +const float snow_haze = 1.0; // blur of the scene behind and around the snow patches (frosted glass), 0 = off, 1 = full (radius: windscreen_view.glsl) +const float snow_distort = 2.0; // picture distortion seen through thin snow (refraction by its relief), 0 = off +const float snow_flake_scale = 2.5; // size of the flakes from the atlas relative to one grid cell (2-3 = two to three times bigger than before; the flakes get fewer) +const float snow_regen = 25.0; // seconds until snow is back on a wiped area (in light snowfall) +const float snow_opacity = 1.0; // overall opacity +const float snow_uv_aspect = 1.0; // glass width / height in the world if the UV is stretched +const float snow_bump = 1.0; // strength of the 3D relief from the normal map, 0 = flat +const float snow_gloss = 0.45; // glints of the sun / headlights on the snow, 0 = matt +const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off +const float snow_melt_blur = 0.8; // blur of the scene around the water spots of melting flakes (0 = off, 1 = full) +const float snow_fresh_blur = 0.0; // blur around fresh dry flakes: physically there is none, a little (0.1-0.2) fakes light scattering + +#ifndef SNOW_FLIP_Y +#define SNOW_FLIP_Y 0 // set to 1 if sliding flakes run UP the glass (the glass UV then has v growing downwards) +#endif +const float SNOW_SIZE_MIN = 0.70; // flake size in grid cells (keep max <= 1.8, the search covers 3x3 cells) +const float SNOW_SIZE_MAX = 1.50; +const float SNOW_SLIDER_MAX = 1.10; // a flake that slides is smaller than this (it gets stretched on its way down) +const float SNOW_HALO_SCALE = 1.5; // blur ring radius = flake half-size * this +const float SNOW_LAND_TIME = 1.5; // seconds a flake takes to land and settle +const float SNOW_REFR_MAXPX = 96.0; // the largest picture shift of thin snow, screen pixels +const float WS_REFR_MAXPX = 96.0; // the largest picture shift the post-processing makes, screen pixels; must match rain_windscreen_haze.glsl +const float WS_BEND_ENC = 60.0; // the bend request in the velocity target; must match rain_windscreen_haze.glsl +const float WS_DROP_BIAS = 192.0; +const float WS_ENC = 64.0; // the haze request in the velocity target; must match rain_windscreen_haze.glsl +const float SNOW_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the bent picture + +#ifndef SNOW_MATCH_RAIN_GLASS +#define SNOW_MATCH_RAIN_GLASS 0 // 4.6: rain_windscreen writes the glass straight, not premultiplied +#endif + +float snHaze = 0.0; // set by snowFilm: 1 inside / next to a snow patch (drives the frosted-glass blur) +float snWipeSince = 1.0e5; // set by GetMixFactor: seconds since the wiper last cleaned this spot +float GetMixFactor(in vec2 co, out float side); + +const float SNOW_MERGE_R = 2.0; // reach of a flake's 'snow mass' in flake half-sizes (flakes closer than this run together) +const float SNOW_CLUMP_THR = 0.80; // summed mass above which the glass is covered + +float snHash(vec2 p) +{ + return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); +} + +float snNoise(vec2 p) +{ + vec2 i = floor(p); + vec2 f = fract(p); + f = f * f * (3.0 - 2.0 * f); + return mix(mix(snHash(i), snHash(i + vec2(1.0, 0.0)), f.x), + mix(snHash(i + vec2(0.0, 1.0)), snHash(i + vec2(1.0, 1.0)), f.x), f.y); +} + +float snFbm(vec2 p) +{ + float a = 0.5; + float v = 0.0; + for (int i = 0; i < 4; ++i) + { + v += a * snNoise(p); + p = p * 2.07 + vec2(17.3, 9.1); + a *= 0.5; + } + return v / 0.9375; +} + +// One flake in one cell. `age` = seconds since it landed. +void snowFlake(vec2 ncell, uint seed, float age, float gridSize, float pixelUV, vec2 aspect, + float sizeMul, float opacityMul, float hold, float meltT, float slideShare, + inout vec3 accRGB, inout float accA, inout float smear, + inout vec3 accN, inout float accTr, inout float accM) +{ + float mt = clamp((age - hold) / meltT, 0.0, 1.0); // 0 = dry, 1 = melted away + float melt = smoothstep(0.0, 1.0, mt); + float fade = 1.0 - smoothstep(0.75, 1.0, mt); // the water spot dries up at the very end + float land = smoothstep(0.0, 0.3, age); // it lands at once (no ghostly fade-in): it just starts small + + float jx = RandF(seed); + float jy = RandF(seed); + vec2 center = (ncell + vec2(jx, jy)) / gridSize; + + float rs = RandF(seed); + float ang = RandF(seed) * 6.2831853; + float flipX = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float kind = RandF(seed); + float tone = mix(0.94, 1.04, RandF(seed)); + bool slider = RandF(seed) < slideShare; + float slideLen = mix(0.8, 1.0, RandF(seed)) * min(snow_slide_len, 2.4) / gridSize; + bool clumper = RandF(seed) < snow_clump_share; // this flake sticks to its neighbours (else it stays on its own) + float aniso = mix(0.62, 1.0, RandF(seed)); // flakes are never round: random squash after rotation + + float szMax = slider ? SNOW_SLIDER_MAX : SNOW_SIZE_MAX; + float size = mix(SNOW_SIZE_MIN, szMax, rs * rs) / gridSize * sizeMul * mix(0.45, 1.0, smoothstep(0.0, max(hold * 0.25, 1.0), age)) * mix(1.0, 0.85, melt); // grows as snow piles onto it + + // a sliding flake runs down while it melts and stretches into a drip + float slideP = slider ? smoothstep(0.05, 1.0, mt) : 0.0; +#if SNOW_FLIP_Y + center.y += slideLen * slideP * slideP; +#else + center.y -= slideLen * slideP * slideP; +#endif + float stretchY = 1.0 + 0.9 * slideP; + + vec2 d = (f_coord - center) * aspect; + d.y /= stretchY; + + // the 'snow mass' of this flake: neighbouring flakes add up, and where the sum is high they have run into one patch + { + float kr = min(size * 0.5 * SNOW_MERGE_R, 1.0 / gridSize); // (1 cell: the search only covers the 3x3 cells around the pixel) + float m = 1.0 - smoothstep(0.0, kr, length(d)); + if (clumper) + accM += m * m * (3.0 - 2.0 * m) * (1.0 - 0.6 * melt) * snow_clump * land; + } + + // blur only around the water of a melting flake (and, optionally, a little around fresh ones) + float haloR = size * 0.5 * SNOW_HALO_SCALE; + float dist = length(d); + if (dist < haloR) + { + float ring = 1.0 - smoothstep(0.35 * haloR, haloR, dist); + smear = max(smear, ring * land * (melt * snow_melt_blur + (1.0 - melt) * snow_fresh_blur)); + } + + float c = cos(ang); + float s = sin(ang); + vec2 r = vec2(c * d.x + s * d.y, -s * d.x + c * d.y); + r.x *= flipX / aniso; + + vec2 local = r / size + 0.5; + if (any(lessThan(local, vec2(0.0))) || any(greaterThan(local, vec2(1.0)))) + return; + + float lod = clamp(log2(max(pixelUV / size * 0.5 * float(textureSize(raindropsatlas, 0).x), 1.0)), 0.0, 4.0); + + // dry flake (tiles 0..2: fluffy, wet lump, crumbs) and, while melting, its water spot (tile 3) + vec2 off0 = (kind < 0.40) ? vec2(0.0, 0.5) : ((kind < 0.72) ? vec2(0.5, 0.5) : vec2(0.0, 0.0)); + vec2 off3 = vec2(0.5, 0.0); + vec4 t0 = textureLod(raindropsatlas, off0 + local * 0.5, lod); + vec4 n0 = textureLod(normalmap, off0 + local * 0.5, lod); + float a0 = t0.a * (1.0 - melt); + float a3 = 0.0; + vec4 t3 = vec4(0.0); + vec4 n3 = vec4(0.5, 0.5, 0.0, 0.0); + if (melt > 0.001) + { + t3 = textureLod(raindropsatlas, off3 + local * 0.5, lod); + n3 = textureLod(normalmap, off3 + local * 0.5, lod); + a3 = t3.a * smoothstep(0.0, 0.5, melt) * fade; + } + + float aSum = a0 + a3; + float a = clamp(aSum * land * snow_opacity * opacityMul, 0.0, 1.0); + if (a <= 0.0) + return; + vec3 col = (t0.rgb * a0 + t3.rgb * a3) / max(aSum, 1e-4); + vec2 nxy = ((n0.rg * 2.0 - 1.0) * a0 + (n3.rg * 2.0 - 1.0) * a3) / max(aSum, 1e-4); + nxy *= snow_bump * land; + nxy.x *= flipX; + vec2 nuv = vec2(c * nxy.x - s * nxy.y, s * nxy.x + c * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + + // thin snow lets light through: the dry part is translucent, the water spot is not + float tr = (a0 / max(aSum, 1e-4)) * (1.0 - t0.a * 0.55); + + accRGB = col * tone * a + accRGB * (1.0 - a); + accN = nT * a + accN * (1.0 - a); + accTr = tr * a + accTr * (1.0 - a); + accA = a + accA * (1.0 - a); +} + +// Adds one layer of flakes to the premultiplied accumulators. Same scheme as the drops of rain_windscreen: +// the cells around the pixel (a few more above it, for the flakes that slide down), the wipers decide per cell whether it +// is clear, the precipitation intensity decides whether the cell carries a flake right now. +void snowLayer(float gridSize, float density, uint layerSeed, float sizeMul, float opacityMul, float slideShare, int rowsUp, + float pixelUV, vec2 aspect, + inout vec3 accRGB, inout float accA, inout float smear, + inout vec3 accN, inout float accTr, inout float accM) +{ + vec2 cell = floor(f_coord * gridSize); + float heavy = clamp(rain_params.x, 0.0, 1.0); + float hold = snow_hold * (1.0 + 1.5 * heavy); // in heavy snow there is no time to melt + float meltT = max(snow_melt, 1.0); + float life = hold + meltT; + float occupancy = mix(0.70, 0.97, heavy); // share of the time a cell holds a flake + float cycBase = life / occupancy; + float share = clamp(pow(rain_params.x, 0.8) * snow_gain, 0.0, 1.0) * density; + + // flakes slide upwards in UV if SNOW_FLIP_Y: search the rows on the other side +#if SNOW_FLIP_Y + int oyMin = -1 - rowsUp; + int oyMax = 1; +#else + int oyMin = -1; + int oyMax = 1 + rowsUp; +#endif + + for (int oy = oyMin; oy <= oyMax; oy++) { + for (int ox = -1; ox <= 1; ox++) { + + vec2 ncell = cell + vec2(float(ox), float(oy)); + uvec2 ucell = uvec2(ivec2(ncell)); + + float side; + float mixFactor = GetMixFactor((ncell + 0.5) / gridSize, side); + + // timing of this cell: the same in every round + uint tseed = Hash(uvec3(ucell, layerSeed + 31u)); + float cyc = cycBase * (1.0 + mix(0.45, 0.03, heavy) * RandF(tseed)); // in heavy snow the cells hardly ever stand empty + float tOff = RandF(tseed) * cyc; + float patchMul = mix(0.7, 1.3, RandF(tseed)); + float tl = time + tOff; + float rnd = floor(tl / cyc); + float age = tl - rnd * cyc; // seconds since this round's flake landed + if (age > life) + continue; + + // a new flake (position, shape, size) every round; the wiper stroke is part of the seed, as in the rain + uint seed = Hash(uvec3(ucell, layerSeed + uint(side) * 7919u + uint(max(rnd, 0.0)) * 2654435u)); + + if (mixFactor < RandF(seed)) + continue; // wiped / still regrowing + + float activate = RandF(seed); + if (activate > share * patchMul) + continue; + + snowFlake(ncell, seed, age, gridSize, pixelUV, aspect, sizeMul, opacityMul, hold, meltT, slideShare, + accRGB, accA, smear, accN, accTr, accM); + } + } +} + +// Snow patches: a crusty white sheet with the structure of real snow (lumps, grain, thin translucent edges, holes). +// WHERE it grows is decided by the flakes: the 'snow mass' of the flakes that stick together (accM) pushes the sheet up, so a patch starts +// where several flakes landed close to each other, spreads from there in an irregular shape and keeps growing while more flakes land +// next to it; when they melt or slide away it breaks up into holes. It is drawn UNDER the flakes. +// Snow patches built from 'pach pach pach' accretion: every big cell carries a patch that is a heap of 22 small clumps (about flake sized). +// The clumps pop up one after another (the ones near the middle first, so the patch spreads outwards) and each lands at once, as a ragged +// piece that merges with the pieces already there. How fast that goes depends on the snowfall intensity (growT); left alone the pieces +// overlap into a closed sheet. Regions of the glass start at different moments. Returns f > 0 inside the snow (f = depth in sheet cells). +float snowSheetField(float gridSize) +{ + float sg = gridSize * 0.19; + vec2 pg = f_coord * sg; + vec2 cell = floor(pg); + float heavy = clamp(rain_params.x, 0.0, 1.0); + float growT = mix(snow_grow_slow, snow_grow_fast, pow(heavy, 0.5)); + float hold = snow_hold * (1.0 + 1.5 * heavy); + float meltT = max(snow_melt, 1.0); + float life = growT + hold + meltT; + float occupancy = mix(0.80, 0.97, heavy); + float cycBase = life / occupancy; + float share = clamp(heavy * 1.6, 0.0, 1.0) * 0.95 + 0.05 * heavy; // share of the cells that carry a patch (1.0 = none, ~1.6 = nearly all) + + // wiper: pixel precise. The sheet at a pixel is no older than the last wipe of that pixel. + float sidePx; + float mixPx = GetMixFactor(f_coord, sidePx); + float wipeAgePx = snWipeSince; + + float acc = 0.0; // summed clump kernels (metaballs): touching clumps merge, no scalloped circles + for (int oy = -1; oy <= 1; oy++) { + for (int ox = -1; ox <= 1; ox++) { + vec2 ncell = cell + vec2(float(ox), float(oy)); + uvec2 ucell = uvec2(ivec2(ncell)); + + uint tseed = Hash(uvec3(ucell, 211u)); + float cyc = cycBase * (1.0 + mix(0.45, 0.03, heavy) * RandF(tseed)); + float tOff = RandF(tseed) * cyc; + float tl = time + tOff; + float rnd = floor(tl / cyc); + float age = tl - rnd * cyc; + if (age > life) + continue; + + uint seed = Hash(uvec3(ucell, 223u + uint(sidePx) * 7919u + uint(max(rnd, 0.0)) * 2654435u)); + if (RandF(seed) > share) + continue; + + vec2 c = ncell + vec2(0.1 + 0.8 * RandF(seed), 0.1 + 0.8 * RandF(seed)); + vec2 dc = pg - c; + if (dot(dc, dc) > 1.2 * 1.2) + continue; // too far from this patch to be touched by any of its clumps + + age = min(age, wipeAgePx); + float delay = snNoise(c * 0.30 + 3.7) * growT * 0.35; // regions of the glass start at different moments + float ga = max(age - delay, 0.0); + float mt = clamp((age - growT - hold) / meltT, 0.0, 1.0); + float shrink = 1.0 - 1.1 * mt * mt; // melting: the clumps shrink and holes open + + for (int i = 0; i < 22; i++) { + uint bs = Hash(uvec3(seed, uint(i), 977u)); + float rho = RandF(bs); + float an = RandF(bs) * 6.2831853; + float rad = 0.85 * sqrt(rho); + vec2 bp = c + rad * vec2(cos(an), sin(an)); + float rb = mix(0.17, 0.30, RandF(bs)); + float ti = growT * (0.03 + 0.97 * pow(rad / 0.85, 0.9) * mix(0.70, 1.0, RandF(bs))); // inner clumps first + // each clump arrives in three small portions (pop, pop, pop): 45% -> 72% -> 100% of its size, no fading + float dT = growT * 0.10; + float stg = step(ti, ga) + step(ti + dT, ga) + step(ti + 2.0 * dT, ga); // 0..3 + if (stg <= 0.0) + continue; + float rr = rb * shrink * (stg < 1.5 ? 0.45 : (stg < 2.5 ? 0.72 : 1.0)); + float kd = max(1.0 - length(pg - bp) / max(rr * 1.35, 1e-3), 0.0); + acc += kd * kd * (3.0 - 2.0 * kd); + } + } + } + // torn, crumbly edge: fine noise (features about a flake wide) decides where the summed clumps stop, so the outline is irregular + // snow and not a ring of circles + float nz = snFbm(pg * 5.5 + 13.0) * 0.45 + snFbm(pg * 13.0 + 7.0) * 0.35 + snFbm(pg * 31.0 + 3.0) * 0.20 - 0.5; + float best = (acc - 0.50) * 0.20 + nz * 0.30; + best -= (1.0 - smoothstep(0.0, 0.12, mixPx)) * 1.0; // swept (or still regrowing) areas + return best; +} + +void snowFilm(float gridSize, inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) +{ +#if SNOW_FLIP_Y + float dir = -1.0; +#else + float dir = 1.0; +#endif + float sf = snowSheetField(gridSize); + snHaze = max(snHaze, smoothstep(-0.045, 0.0, sf)); // the glass next to a patch is frosted a little as well + float cover = smoothstep(0.0, 0.03, sf); + if (cover <= 0.002) + return; + float thick = smoothstep(0.0, 0.11, sf); // 0 at the thin edge, 1 in the thick middle + vec2 p = f_coord * gridSize * 0.17 + vec2(0.0, dir * time * 0.008); + vec2 q = f_coord * gridSize * 2.6; + float h0 = snFbm(p); + + // lumpy surface: big drifts + fine grain + float f1 = snFbm(q); + float e = 0.06; + float ef = 0.05; + vec2 g = vec2(snFbm(p + vec2(e, 0.0)) - h0, snFbm(p + vec2(0.0, e)) - h0) / e; + vec2 gf = vec2(snFbm(q + vec2(ef, 0.0)) - f1, snFbm(q + vec2(0.0, ef)) - f1) / ef; + vec3 nT = normalize(vec3(-(g * 0.55 + gf * 0.20) * snow_bump, 1.0)); + + vec3 thin = vec3(0.66, 0.72, 0.80); // thin snow is greyish-blue and lets the dark background through + vec3 full = vec3(0.93, 0.95, 0.98); + vec3 col = mix(thin, full, thick) * (0.62 + 0.55 * f1) * (0.88 + 0.22 * snNoise(f_coord * gridSize * 9.0)) * (0.85 + 0.3 * h0); + float a = clamp(cover * mix(0.50, 0.96, thick) * snow_pack * snow_opacity, 0.0, 0.97); + float under = 1.0 - accA; + accRGB = accRGB + col * a * under; + accN = accN + nT * a * under; + accTr = accTr + mix(0.60, 0.30, thick) * a * under; + accA = accA + a * under; +} + +// --- The snow of the simulation (water_snow.comp): the map of the glass --------------------------------------------------- +// When the renderer simulates the snow of the glass (the param snow_slot holds 1 + its slot), the snow, the water, how packed the +// snow is and the shape of its flakes come from the map of the glass (water.glsl), which keeps them from frame to frame: the flakes +// land and stay where they landed, pile up into a layer, the blades push it into ridges at the ends of their sweeps and leave a wet +// trace, it melts at the warm glass and slush slides down. Here it's only drawn: +// - a texel of the map with a little snow is a flake (atlas tiles 0..2: fluffy when dry, a wet lump when wet or packed, crumbs), +// the more snow the bigger; with mostly water left it's the water spot (tile 3) +// - where the snow is thicker it's a layer: its edge torn by the grain of the snow, as opaque as it's thick (Beer-Lambert), grey +// and translucent when wet (slush), smoother and denser when packed; its relief from the slopes of the snow of the map +// - the water: wet glass bends the picture behind (the post-processing), the thin snow hazes it +// Without the simulation (an older renderer, no compute) the procedural snow below draws the glass as before. +const float snow_map_flake = 1.15; // size of a flake relative to a texel of the map (the snow of a texel) +const float snow_map_layer = 1.0; // mm of snow above which the flakes run together into a layer +const float snow_map_opaque = 1.8; // mm of fresh snow which lets 1/e of the light through (packed: half of it) +const float snow_map_relief = 0.6; // how much the slopes of the snow tilt its surface +const float snow_map_grain = 0.35; // the fine grain of the layer (its relief) +const float snow_map_wet_bend = 0.6; // how strongly a wet glass bends the picture behind it +const float snow_map_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through: the picture + // behind shows through it, blurred, rather than a dark speck at night) + +int snMapSlot = -1; +uint snMapIndex = 0u; +float snWet = 0.0; // set by snowMapped: the film of water (0 .. 1) +vec2 snWetN = vec2(0.0); // set by snowMapped: the slope of the water, for the bend of the picture + +// the snow of the map at a place of the glass +vec4 snMapAt(vec2 uv) +{ + return water_snow_at(uint(snMapSlot), snMapIndex, uv); +} + +// a flake of the map drawn over the accumulators: Local the place in its sprite (0 .. 1), Tile the corner of its tile in the atlas +void snowMapSprite(vec2 local, vec2 tile, float alpha, float tone, float flip, float c, float s, float lod, + inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) +{ + vec4 t = textureLod(raindropsatlas, tile + local * 0.5, lod); + vec4 n = textureLod(normalmap, tile + local * 0.5, lod); + float a = clamp(t.a * alpha * snow_opacity, 0.0, 1.0); + if (a <= 0.0) + return; + vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump; + nxy.x *= flip; + vec2 nuv = vec2(c * nxy.x - s * nxy.y, s * nxy.x + c * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + float tr = (1.0 - t.a * 0.55); + accRGB = t.rgb * tone * a + accRGB * (1.0 - a); + accN = nT * a + accN * (1.0 - a); + accTr = tr * a + accTr * (1.0 - a); + accA = a + accA * (1.0 - a); +} + +// the flakes of the texels around the pixel +void snowMapFlakes(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) +{ + vec2 p = f_coord * float(WATER_MAP); + ivec2 here = ivec2(floor(p)); + for (int oy = -1; oy <= 1; ++oy) + { + for (int ox = -1; ox <= 1; ++ox) + { + ivec2 texel = here + ivec2(ox, oy); + vec4 q = water_snow_texel(uint(snMapSlot), snMapIndex, texel); + float density = mix(0.1, 0.4, q.z); + float wet = q.y / (q.y + q.x * density + 1e-4); + bool spot = (q.x < 0.05) && (q.y > 0.03); // a flake melted into its water + if ((q.x < 0.05) && (false == spot)) + continue; + uint seed = Hash(uvec3(uvec2(texel), uint(q.w * 65535.0) + 7u * uint(snMapSlot))); + // the water of a texel is a droplet only now and then: the more water the more of them + if (spot && (RandF(seed) > smoothstep(0.03, 0.2, q.y))) + continue; + vec2 center = vec2(texel) + vec2(0.15 + 0.7 * RandF(seed), 0.15 + 0.7 * RandF(seed)); + float ang = RandF(seed) * 6.2831853; + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float kind = RandF(seed); + float tone = mix(0.94, 1.04, RandF(seed)); + float aniso = mix(0.62, 1.0, RandF(seed)); + // the more snow the texel holds the bigger the flake (a lump of a few flakes) + float size = snow_map_flake * mix(0.6, 1.0, RandF(seed)) * (spot ? mix(0.5, 1.1, smoothstep(0.03, 0.3, q.y)) + : mix(0.7, 1.6, smoothstep(0.05, 2.0, q.x))); + vec2 d = (p - center) * aspect; + float c = cos(ang); + float s = sin(ang); + vec2 r = vec2(c * d.x + s * d.y, -s * d.x + c * d.y); + r.x *= flip / aniso; + vec2 local = r / size + 0.5; + if (any(lessThan(local, vec2(0.0))) || any(greaterThan(local, vec2(1.0)))) + continue; + float sizeUV = size / float(WATER_MAP); + float lod = clamp(log2(max(pixelUV / sizeUV * 0.5 * float(textureSize(raindropsatlas, 0).x), 1.0)), 0.0, 4.0); + vec2 tile; + if (spot) + tile = vec2(0.5, 0.0); + else if ((wet > 0.3) || (q.z > 0.5) || (kind < 0.30)) + tile = vec2(0.5, 0.5); // a wet lump + else if (kind < 0.75) + tile = vec2(0.0, 0.5); // fluffy + else + tile = vec2(0.0, 0.0); // crumbs + float alpha = spot ? smoothstep(0.03, 0.1, q.y) : smoothstep(0.05, 0.25, q.x) * mix(snow_map_thin, 1.0, smoothstep(0.3, 2.5, q.x)); + snowMapSprite(local, tile, alpha, tone, flip, c, s, lod, accRGB, accA, accN, accTr); + } + } +} + +// the snow of the map at the pixel: the flakes, the layer of the snow under them, the water, the haze +void snowMapped(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, inout float smear, inout vec3 accN, inout float accTr) +{ + vec4 q = snMapAt(f_coord); + float e = 1.0 / float(WATER_MAP); + vec4 qr = snMapAt(f_coord + vec2(e, 0.0)); + vec4 ql = snMapAt(f_coord - vec2(e, 0.0)); + vec4 qu = snMapAt(f_coord + vec2(0.0, e)); + vec4 qd = snMapAt(f_coord - vec2(0.0, e)); + float around = (q.x + qr.x + ql.x + qu.x + qd.x) * 0.2; + + // the flakes of thin snow and the water spots; the picture behind a flake is blurred (it scatters the light going through) + snowMapFlakes(aspect, pixelUV, accRGB, accA, accN, accTr); + snHaze = max(snHaze, smoothstep(0.0, 0.3, accA)); + + // the water: the film bends the picture behind + snWet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); + snWetN = vec2(qr.y - ql.y, qu.y - qd.y) * 2.0 + (vec2(snNoise(f_coord * 900.0), snNoise(f_coord * 900.0 + 31.0)) - 0.5) * 0.6 * snWet; + smear = max(smear, snWet * snow_melt_blur * 0.6); + // thin snow hazes the picture around it + snHaze = max(snHaze, smoothstep(0.15, 1.0, around)); + + // the layer, where the snow has run together + vec2 gp = f_coord * float(WATER_MAP) * aspect; + float grain = snFbm(gp * 0.9 + 3.0) * 0.55 + snFbm(gp * 2.7 + 11.0) * 0.30 + snFbm(gp * 7.1 + 5.0) * 0.15; + float edge = (q.x - snow_map_layer) / max(snow_map_layer, 1e-3) + (grain - 0.5) * 1.6; + float cover = smoothstep(0.0, 0.35, edge); + if (cover <= 0.002) + return; + float density = mix(0.1, 0.4, q.z); + float wet = q.y / (q.y + q.x * density + 1e-4); + float opaque = snow_map_opaque * mix(1.0, 0.5, q.z); + float thick = 1.0 - exp(-q.x / opaque); + // the relief: the slopes of the snow of the map (ridges, the edges of the swept arcs) and the grain of the fresh snow + vec2 slope = vec2(qr.x - ql.x, qu.x - qd.x) * 0.5 * snow_map_relief; + float f1 = snFbm(gp * 3.3); + float ef = 0.05; + vec2 gf = vec2(snFbm(gp * 3.3 + vec2(ef, 0.0)) - f1, snFbm(gp * 3.3 + vec2(0.0, ef)) - f1) / ef; + vec3 nT = normalize(vec3(-(slope + gf * snow_map_grain * (1.0 - 0.6 * q.z)) * snow_bump, 1.0)); + + vec3 fresh = vec3(0.93, 0.95, 0.98); + vec3 packed = vec3(0.89, 0.91, 0.94); + vec3 slush = vec3(0.60, 0.66, 0.73); + vec3 col = mix(mix(fresh, packed, q.z), slush, smoothstep(0.2, 0.7, wet)); + col *= (0.80 + 0.30 * f1 * (1.0 - 0.5 * q.z)) * (0.92 + 0.12 * grain); + float a = clamp(cover * mix(0.35, 0.97, thick) * mix(1.0, 0.75, smoothstep(0.3, 0.8, wet)) * snow_pack * snow_opacity, 0.0, 0.97); + float under = 1.0 - accA; + accRGB = accRGB + col * a * under; + accN = accN + nT * a * under; + accTr = accTr + mix(0.60, 0.25, thick) * a * under; + accA = accA + a * under; +} + +void main() +{ + // Derivatives first, in uniform control flow (no discard before them). + vec3 Ngl = normalize(f_normal); + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec2 duv1 = dFdx(f_coord); + vec2 duv2 = dFdy(f_coord); + vec3 dp2perp = cross(dp2, Ngl); + vec3 dp1perp = cross(Ngl, dp1); + vec3 Tgl = dp2perp * duv1.x + dp1perp * duv2.x; + vec3 Bgl = dp2perp * duv1.y + dp1perp * duv2.y; + float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); + Tgl *= invmax; + Bgl *= invmax; + + vec4 tex_color = texture(diffuse, f_coord); // no discard: clean glass between faint dirt must still get snow and blur + + float gridSize = max(ceil(param[2].x), 1.0); + float pixelUV = max(length(dFdx(f_coord)), length(dFdy(f_coord))); + snHaze = 0.0; + vec2 aspect = (snow_uv_aspect >= 1.0) ? vec2(snow_uv_aspect, 1.0) : vec2(1.0, 1.0 / max(snow_uv_aspect, 0.01)); + + vec3 snowRGB = vec3(0.0); // premultiplied + float snowA = 0.0; + float smear = 0.0; + vec3 snowN = vec3(0.0); + float snowTr = 0.0; + // the snow of the simulation where the glass has a map of it, else made up as before + snMapSlot = int(param[2].z + 0.5) - 1; + bool mapped = (snMapSlot >= 0) && (snMapSlot < WATER_SLOTS) && water_snow_map(uint(snMapSlot), snMapIndex); + if (mapped) + { + // the texels of the map as they lie on the glass (the uv may be stretched) + ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); + uint axis = (uint(snMapSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; + vec2 span = vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)); + if (min(span.x, span.y) > 1e-6) + aspect = span / max(span.x, span.y); + snowMapped(aspect, pixelUV, snowRGB, snowA, smear, snowN, snowTr); + } + else if (rain_params.x > 0.0) + { + float mass = 0.0; + if (snow_small > 0.0) + snowLayer(gridSize * 2.4 / snow_flake_scale, snow_small, 17u, 0.9, 0.85, 0.0, 0, pixelUV, aspect, snowRGB, snowA, smear, snowN, snowTr, mass); + snowLayer(gridSize / snow_flake_scale, snow_density, 13u, 1.0, 1.0, snow_slide_share, 4, pixelUV, aspect, snowRGB, snowA, smear, snowN, snowTr, mass); + if (snow_pack > 0.0) + snowFilm(gridSize, snowRGB, snowA, snowN, snowTr); // patches where flakes have run together + } + + float glassA = tex_color.a * alpha_mult; + float finalA = snowA + glassA * (1.0 - snowA); + vec3 premult = snowRGB + tex_color.rgb * glassA * (1.0 - snowA); + vec3 albedo = premult / max(finalA, 1e-4); + float glassShare = glassA * (1.0 - snowA) / max(finalA, 1e-4); + + // relief: tilt the glass normal by the slope of the snow (flat where there is none) + vec3 nDir = snowN + vec3(0.0, 0.0, 1.0) * (1.0 - snowA); + vec3 fragnormal = Ngl; + if (snowA > 0.001) + fragnormal = normalize(Ngl * max(nDir.z, 0.05) + Tgl * nDir.x + Bgl * nDir.y); + + vec3 fragcolor = ambient; + float reflectivity = param[1].z * glassShare; + float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5 * glassShare + snow_gloss * snowA; + legacy_gloss(); + + // most of the glass is clear (no snow, a clear glass texture): the lighting of the 4.6 renderers (the clusters of lamps, the + // shadows, the reflections) is skipped there, it would be multiplied by an alpha of ~0 + if (finalA > 0.002) + fragcolor = apply_lights(fragcolor, fragnormal, albedo, reflectivity, specularity, shadow_tone); + + // thin snow glows when you look towards the sun / a lamp + if (finalA > 0.002 && snowA > 0.001 && snow_translucency > 0.0 && lights_count > 0U) + { + vec3 I = normalize(f_pos.xyz); + float shadowSun = 0.0; + if (shadow_tone < 1.0) + shadowSun = (1.0 - shadow_tone) * clamp(calc_shadow(), 0.0, 1.0); + float towards = max(dot(I, normalize(-lights[0].dir)), 0.0); + float glow = pow(towards, 3.0) * (1.0 - shadowSun); + fragcolor += lights[0].color * lights[0].intensity * glow * snow_translucency * snowTr * albedo * snowA; + } + vec3 lit = apply_fog(fragcolor); + +#if SNOW_MATCH_RAIN_GLASS + vec4 color = vec4(lit * finalA, finalA); +#else + vec4 color = vec4(lit, finalA); +#endif + + out_color = POSTFX_ENABLED ? color : tonemap(color); + + // the scene seen through the snow, drawn by the post-processing (rain_windscreen_haze.glsl), asked for in the velocity target as + // rain_windscreen asks: thin snow bends it (its relief refracts; x, y = WS_DROP_BIAS + WS_BEND_ENC * bend), elsewhere it's blurred in + // and around thin snow and around the melting spots (x = WS_ENC * strength, y = 0); the snow itself stays sharp. alpha 0 elsewhere: + // the blending keeps the motion of the scene behind + if (MOTIONBLUR_ENABLED) + { + float thin = smoothstep(0.04, 0.20, snowA) * (1.0 - smoothstep(0.55, 0.90, snowA)); + vec4 req = vec4(0.0); + if ((snWet > 0.25) && (snowA < 0.35) && (glassA < 0.5)) + { + // the water on the glass: its film and its spots bend the picture behind + vec2 bend = clamp(-snWetN * snow_map_wet_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.25, 0.6, snWet); + req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); + } + else if ((snow_distort > 0.0) && (thin > 0.30) && (glassA < 0.5)) + { + vec2 slope = snowN.xy / max(snowA, 1e-3); + vec2 bend = clamp(-slope * snow_distort, vec2(-1.0), vec2(1.0)) * smoothstep(0.30, 0.60, thin) * (SNOW_REFR_MAXPX / WS_REFR_MAXPX); + req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); + } + else + { + float haze = snHaze * snow_haze * (1.0 - smoothstep(0.30, 0.80, snowA)); // frosted glass in and around thin snow + float blurMask = clamp(max(smear * (1.0 - snowA), haze) * (1.0 - smoothstep(0.5, 0.95, glassA)), 0.0, 1.0); + if (blurMask >= 0.01) + req = vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0); + } + out_motion = req; + } +} + +float GetMixFactor(in vec2 co, out float side) { + vec4 movePhase = wiper_pos; + bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); + movePhase = mix(vec4(2.) - movePhase, movePhase, is_out); + + vec4 mask = textureLod(wipermask, co, 0.0); // called from non-uniform flow: no implicit derivatives + + vec4 areaMask = step(.001, mask); + + vec4 maskVal = mix(1. - mask, mask, is_out); + vec4 wipeWidth = smoothstep(1., .9, movePhase) * .25; + vec4 cleaned = smoothstep(movePhase - wipeWidth, movePhase, maskVal) * areaMask; + vec4 side_v = step(maskVal, movePhase); + cleaned *= side_v; + side_v = mix(side_v, vec4(1.) - side_v, is_out); + + // "regeneration", snow gradually returning after a wiper pass (slower than rain, and faster in heavy snowfall): + float regenT = max(mix(snow_regen, snow_regen * 0.6, clamp(rain_params.x, 0.0, 1.0)), 0.5); + vec4 sinceV = vec4(time) - mix(wiper_timer_out, wiper_timer_return, side_v) - vec4(.2); + vec4 regenPhase = clamp(sinceV / vec4(regenT), vec4(0.), vec4(1.)); + + side_v = mix(vec4(0.), vec4(1.) - side_v, areaMask); + + vec4 factor_v = mix(vec4(1.), regenPhase * (vec4(1.) - cleaned), areaMask); + + side = 0.; + float out_factor = 1.; + bool have_side = false; + snWipeSince = 1.0e5; + + // out_factor: the blade that clears the grid cell the most wins (as before). + // side: which wiper stroke the drops of this cell belong to. It is part of the random + // seed of every drop, so it must NOT depend on out_factor. It used to: once the drops had + // fully regrown (out_factor == 1) side fell back to 0 and every drop in the swept area + // jumped to a new position, about one regrow time after each stroke (most visible in + // heavy rain, where regrowth takes ~1 s). + for(int i = 0; i < 4; ++i) + { + out_factor = min(out_factor, factor_v[i]); + if (!have_side && areaMask[i] > 0.) + { + side = side_v[i]; + snWipeSince = max(sinceV[i], 0.0); + have_side = true; + } + } + + return out_factor; +} diff --git a/shaders/vk14/rain_cells.comp b/shaders/vk14/rain_cells.comp index 780addf0e..9b6848a2b 100644 --- a/shaders/vk14/rain_cells.comp +++ b/shaders/vk14/rain_cells.comp @@ -11,7 +11,7 @@ layout(push_constant) uniform kernel_constants { float rain_time; // the time of the block of the scene (scene_ubs.time) - float rain_amount; // how hard it rains (scene_ubs.rain_params.x) + float rain_amount; // how wet the glass is (scene_ubs.rain_state.y, a little more) int rain_pass; // 0 the cells, 1 the reach of the drops }; @@ -130,6 +130,7 @@ float drop_reach(uint A, uint B, float Spread) uvec4 drop_masks(ivec2 Cell) { uvec4 result = uvec4(0u); + // as many drops as the glass is wet (rain_amount: the wetness of the glass, scene_ubs.rain_state.y) float most = min(rain_amount * drop_density, 0.95); for (int dy = -1; dy <= 1; ++dy) for (int dx = -1; dx <= 1; ++dx) diff --git a/shaders/vk14/rain_cells.glsl b/shaders/vk14/rain_cells.glsl index 0629492e2..6a5a69945 100644 --- a/shaders/vk14/rain_cells.glsl +++ b/shaders/vk14/rain_cells.glsl @@ -53,7 +53,7 @@ const float drop_life_min = 14.0; // seconds a drop sits on the glass const float drop_life_max = 45.0; const float drop_appear = 0.18; // seconds of the landing "pop" const float drop_fade = 1.5; // seconds a drop takes to vanish at the end of its life -const float wiper_miss = 0.05; // share of the drops a blade goes over without taking them +const float wiper_miss = 0.005; // share of the drops a blade goes over without taking them (a tenth of the 0.05 it was) const float streak_period = 40.0; // seconds a rivulet lives (it runs for ~90% of that and then fades out), average const float wind_streak_period = 18.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) diff --git a/shaders/vk14/water.glsl b/shaders/vk14/water.glsl index 41d672d60..ed2b1094d 100644 --- a/shaders/vk14/water.glsl +++ b/shaders/vk14/water.glsl @@ -54,6 +54,45 @@ layout(std430, set = PASS_SET, binding = WATER_SSBO) readonly buffer water_ssbo uint water_cells[]; }; +// the snow on a glass of the snow (water_snow.comp, mat_snow_windscreen.frag): two maps of WATER_MAP x WATER_MAP texels after the +// wetted paths in water_cells, two uint a texel (halves: x the snow, mm, y the water, mm, z how packed the snow is 0 .. 1, w random +// 0 .. 1, the shape of its flakes); a step reads one and writes the other, the header of the glass says which one is the latest +// (z 1 when there's a map of the snow, w the map) +uint water_snow_base(uint slot, uint map) +{ + return uint(WATER_SLOTS * WATER_GRID * WATER_GRID * (1 + WATER_CELL_DROPS)) + uint(WATER_SLOTS * WATER_TRAIL * WATER_TRAIL) + (map * uint(WATER_SLOTS) + slot) * uint(WATER_MAP * WATER_MAP * 2); +} + +// a texel of a map of the snow, nothing outside the map +vec4 water_snow_texel(uint slot, uint map, ivec2 texel) +{ + if (any(lessThan(texel, ivec2(0))) || any(greaterThanEqual(texel, ivec2(WATER_MAP)))) + return vec4(0.0); + uint index = water_snow_base(slot, map) + 2u * uint(texel.y * WATER_MAP + texel.x); + return vec4(unpackHalf2x16(water_cells[index]), unpackHalf2x16(water_cells[index + 1u])); +} + +// the latest map of the snow of a glass; false when there's none yet +bool water_snow_map(uint slot, out uint map) +{ + vec4 header = water_header[slot]; + map = (header.w > 0.5) ? 1u : 0u; + return header.z > 0.5; +} + +// the latest map of the snow filtered between the texels at a place of the glass +vec4 water_snow_at(uint slot, uint map, vec2 uv) +{ + vec2 p = uv * float(WATER_MAP) - 0.5; + ivec2 i = ivec2(floor(p)); + vec2 f = p - vec2(i); + vec4 a = water_snow_texel(slot, map, i); + vec4 b = water_snow_texel(slot, map, i + ivec2(1, 0)); + vec4 c = water_snow_texel(slot, map, i + ivec2(0, 1)); + vec4 d = water_snow_texel(slot, map, i + ivec2(1, 1)); + return mix(mix(a, b, f.x), mix(c, d, f.x), f.y); +} + // the radius of the footprint of a drop holding Volume mm3 of water, metres: a cap of a sphere meeting the glass at 40 degrees float water_radius(float volume) { diff --git a/shaders/vk14/water_sim.glsl b/shaders/vk14/water_sim.glsl index 82710150a..d1794ca64 100644 --- a/shaders/vk14/water_sim.glsl +++ b/shaders/vk14/water_sim.glsl @@ -41,6 +41,11 @@ layout(std140, set = COMPUTE_SET, binding = 1) uniform water_ubo // every glass: x the landings tried in the step, y 1 / the most metres squared a unit of its uv holds, z 1 when it's simulated, // w the size of its drops (rain_scale of its material) vec4 water_slots[WATER_SLOTS]; + // the snow (water_snow.comp): x the flakes coming to a square metre of the ground in a second, y how much warmer than the air + // the glass is, degrees, z the speed of the vehicle, m/s, w the map of the snow the step reads (0, 1) + vec4 water_snow; + // every glass: 1 when its snow is simulated + vec4 water_snow_slots; }; const float WATER_GRAVITY = 9.81; diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp new file mode 100644 index 000000000..e4ea47a86 --- /dev/null +++ b/shaders/vk14/water_snow.comp @@ -0,0 +1,353 @@ +#version 460 core +#define STAGE_COMPUTE 1 +// the snow on the windscreens (water_sim.glsl, water.glsl): a step of the snow of the glasses of the snow, a thread per texel of +// the map of a glass, a row of groups per glass. the step reads one map of the snow and writes the other (water_snow.w says which +// one it reads), so a texel sees its neighbours as they were before the step +// +// what a texel holds: the snow, mm (as it lies, fluffy or packed), the water, mm (the melted snow, a film on the glass and soaked +// into the snow), how packed the snow is (0 fresh flakes .. 1 snow pressed by a blade) and a random number, the shape of its +// flakes (mat_snow_windscreen.frag). in a step, in this order: +// - the snow and the water move: wet heavy snow (slush) slides down the glass, dry powder is blown along it by the air at speed, +// the water runs down as a film and is pushed by the air; and snow piled higher than its neighbours by more than it holds slips +// onto them (a ridge left by a blade spreads into a wedge). what goes over the edge of the glass falls off +// - the blades: a blade going over a texel in the step takes its snow (a little stays, and a wet trace of the water), and pushes +// it on in front of itself: the texel just ahead of the line of texels the blade went over gets their snow, packed (each texel +// to one texel at most: the snow pushed along is never counted twice). at the end +// of its sweep the blade leaves it there, a ridge; pushed past the edge of the glass, it's gone +// - the flakes land: as many as come to the glass facing the snow coming at it against the cab (and a few in the eddies of the +// air where it doesn't face it), each bringing its snow to the texel; the faster the vehicle the more of the dry ones bounce off +// - the snow melts: the glass is warmer than the air (the cab is heated), the less so the faster the vehicle goes; above zero the +// snow melts at the glass into its water, the water dries slowly + +// none of the pass set: everything the kernel reads is pushed with its dispatch (set COMPUTE_SET, water_sim.glsl), so it runs +// before the passes of the frame set theirs up +#define LAYOUT_UI 1 +#include "common.glsl" +#include "water_sim.glsl" + +layout(local_size_x = WATER_GROUP_SIZE) in; + +// how dense the snow is: fresh flakes and snow pressed by a blade (the water in a mm of it, mm) +const float SNOW_FRESH = 0.1; +const float SNOW_PACKED = 0.4; +// the snow of a flake, mm3 of water (0.3 .. 2.5 as the flakes of the water passes, water_spawn.comp) +const float SNOW_FLAKE_LEAST = 0.3; +const float SNOW_FLAKE_MOST = 2.5; +// the speed of the snow coming at the glass in the eddies of the air, m/s: a glass not facing the snow gets a little of it +const float SNOW_EDDIES = 0.25; +// the most snow a texel holds, mm, and the step of the snow to a neighbour it holds without slipping onto it, mm +const float SNOW_MOST = 40.0; +const float SNOW_REPOSE = 3.0; +// the share of the snow over the step slipping onto the neighbour in a second +const float SNOW_SLIP = 6.0; +// the share of the snow a blade leaves (at most SNOW_WIPE_LEFT mm: the snow it pushes along goes with it), of the water, and +// of the water of the snow it takes which it leaves as a wet trace (at most SNOW_WIPE_WET mm) +const float SNOW_WIPE_MISS = 0.03; +const float SNOW_WIPE_LEFT = 0.03; +const float SNOW_WIPE_WATER = 0.1; +const float SNOW_WIPE_TRACE = 0.08; +const float SNOW_WIPE_WET = 0.015; +// the longest line of texels a blade goes over in a step, texels +const int SNOW_WIPE_LINE = 12; +// the water the snow melts into at the glass a second for each degree the glass is above zero, mm +const float SNOW_MELT = 0.003; +// the water drying a second, mm, and the share of a thin film going in a second (it dries and runs off as droplets) +const float SNOW_DRY = 0.0004; +const float SNOW_FILM_DRY = 0.15; +// how fast slush slides down a vertical glass, how fast dry powder goes with the air (a share of the speed of the air along the +// glass), how fast the film of water runs down a vertical glass and goes with the air, m/s +const float SNOW_SLIDE = 0.03; +const float SNOW_BLOW = 0.004; +const float SNOW_RUN = 0.02; +const float SNOW_RUN_AIR = 0.002; + +// the neighbours of a texel +const ivec2 SNOW_AROUND[8] = ivec2[8](ivec2(-1, -1), ivec2(0, -1), ivec2(1, -1), ivec2(-1, 0), ivec2(1, 0), ivec2(-1, 1), ivec2(0, 1), ivec2(1, 1)); + +uint snow_slot; +uint snow_from; +uint snow_axes_base; + +bool snow_on_glass(ivec2 texel) +{ + if (any(lessThan(texel, ivec2(0))) || any(greaterThanEqual(texel, ivec2(WATER_MAP)))) + return false; + return water_axes[(snow_axes_base + uint(texel.y * WATER_MAP + texel.x)) * 2u].w > 0.75; +} + +vec4 snow_get(ivec2 texel) +{ + return snow_on_glass(texel) ? water_snow_texel(snow_slot, snow_from, texel) : vec4(0.0); +} + +float snow_blade(ivec2 texel, int blade) +{ + texel = clamp(texel, ivec2(0), ivec2(WATER_MAP - 1)); + return water_blades[snow_axes_base + uint(texel.y * WATER_MAP + texel.x)][blade]; +} + +// whether the blade went over the texel in the step (it reaches it, and the place of the texel along its sweep is between where +// the blade was and where it is, the place it was at belonging to the step before) +bool snow_crossed(ivec2 texel, int blade) +{ + float before = water_blades_before[blade]; + float now = water_blades_now[blade]; + if ((before < 0.0) || (now < 0.0) || (now == before) || (false == snow_on_glass(texel))) + return false; + float place = snow_blade(texel, blade); + if (place <= 0.001) + return false; + return (now > before) ? ((place > before) && (place <= now)) : ((place < before) && (place >= now)); +} + +// the way the blade goes over the texel, a step of a texel (zero when it can't be told) +ivec2 snow_blade_way(ivec2 texel, int blade) +{ + float here = snow_blade(texel, blade); + float right = snow_blade(texel + ivec2(1, 0), blade); + float left = snow_blade(texel - ivec2(1, 0), blade); + float up = snow_blade(texel + ivec2(0, 1), blade); + float down = snow_blade(texel - ivec2(0, 1), blade); + // one-sided where a neighbour is out of the sweep + right = (right > 0.001) ? right : here; + left = (left > 0.001) ? left : here; + up = (up > 0.001) ? up : here; + down = (down > 0.001) ? down : here; + vec2 gradient = vec2(right - left, up - down); + if (dot(gradient, gradient) < 1e-12) + return ivec2(0); + vec2 way = normalize(gradient) * ((water_blades_now[blade] > water_blades_before[blade]) ? 1.0 : -1.0); + return ivec2(round(way)); +} + +// whether no blade goes over the texel now: the snow piled there may slip onto its neighbours (in a sweep of a working blade +// the snow it pushes would slip behind it, a stripe of snow left on the wiped glass for every step) +bool snow_unswept(ivec2 texel) +{ + for (int blade = 0; blade < 4; ++blade) + { + if ((water_blades_now[blade] >= 0.0) && (water_blades_now[blade] != water_blades_before[blade]) && (snow_blade(texel, blade) > 0.001)) + return false; + } + return true; +} + +// the frame of the glass at a texel, unfiltered +water_frame_s snow_frame(ivec2 texel) +{ + uint index = snow_axes_base + uint(texel.y * WATER_MAP + texel.x); + vec4 a = water_axes[index * 2u]; + vec4 b = water_axes[index * 2u + 1u]; + water_frame_s frame = water_frame_s(a.xyz, b.xyz, vec3(0.0, 0.0, 1.0), a.w); + vec3 n = cross(a.xyz, b.xyz); + if (dot(n, n) > 1e-24) + frame.normal = normalize(n) * ((b.w < 0.0) ? -1.0 : 1.0); + return frame; +} + +// how the snow (xy) and the water (zw) of a texel move, texels a second +vec4 snow_motion(ivec2 texel, vec4 state) +{ + if ((state.x <= 0.001) && (state.y <= 0.001)) + return vec4(0.0); + water_frame_s frame = snow_frame(texel); + vec3 n = frame.normal; + vec3 down = -water_up.xyz; + vec3 slope = down - n * dot(down, n); + vec3 air = water_air.xyz - n * dot(water_air.xyz, n); + float wind = length(air); + float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); + float wet = state.y / (state.y + state.x * density + 1e-4); + // slush: wet and heavy enough to go; dry powder: loose and thin enough to be blown + float slide = SNOW_SLIDE * smoothstep(0.25, 0.7, wet) * smoothstep(2.0, 8.0, state.x); + float blow = SNOW_BLOW * smoothstep(10.0, 25.0, wind) * (1.0 - state.z) * (1.0 - smoothstep(0.1, 0.3, wet)) * (1.0 - smoothstep(1.0, 4.0, state.x)); + vec3 snow = slope * slide + air * blow; + // the film of water runs where there's enough of it, not the water soaked into the snow + float film = (1.0 - smoothstep(0.5, 3.0, state.x)); + vec3 water = (slope * SNOW_RUN * smoothstep(0.03, 0.15, state.y) + air * SNOW_RUN_AIR * smoothstep(0.03, 0.1, state.y)) * film; + return vec4(water_to_uv(frame, snow), water_to_uv(frame, water)) * float(WATER_MAP); +} + +// the shares of a texel going to its neighbours along x and along y in the step, for a motion in texels a second +vec2 snow_out(vec2 motion, float seconds) +{ + return min(abs(motion) * seconds, vec2(0.45)); +} + +// the snow and the water of the texel after they moved in the step: what leaves it, what comes from its neighbours; the +// packing and the shape go with the snow +vec4 snow_move(ivec2 texel, vec4 state, float seconds) +{ + vec4 motion = snow_motion(texel, state); + vec2 snowout = snow_out(motion.xy, seconds); + vec2 waterout = snow_out(motion.zw, seconds); + float snow = state.x * (1.0 - snowout.x - snowout.y); + float water = state.y * (1.0 - waterout.x - waterout.y); + float packed = state.z * snow; + bool unswept = snow_unswept(texel); + float slip = min(SNOW_SLIP * seconds, 0.2); + const ivec2 sides[4] = ivec2[4](ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1)); + for (int k = 0; k < 4; ++k) + { + ivec2 side = sides[k]; + ivec2 other = texel + side; + bool glass = snow_on_glass(other); + vec4 neighbour = glass ? water_snow_texel(snow_slot, snow_from, other) : vec4(0.0); + // slipping onto the neighbour (off the glass: falling off) and from it, where no blade goes over either now + bool slips = unswept && snow_unswept(other); + float away = slips ? slip * max(state.x - neighbour.x - SNOW_REPOSE, 0.0) : 0.0; + snow -= away; + packed -= away * state.z; + if (false == glass) + continue; + float coming = slips ? slip * max(neighbour.x - state.x - SNOW_REPOSE, 0.0) : 0.0; + // what the motion of the neighbour brings: it goes this way along the axis of the side + vec4 itsmotion = snow_motion(other, neighbour); + vec2 itssnow = snow_out(itsmotion.xy, seconds); + vec2 itswater = snow_out(itsmotion.zw, seconds); + if (side.x != 0) + { + coming += (itsmotion.x * float(side.x) < 0.0) ? neighbour.x * itssnow.x : 0.0; + water += (itsmotion.z * float(side.x) < 0.0) ? neighbour.y * itswater.x : 0.0; + } + else + { + coming += (itsmotion.y * float(side.y) < 0.0) ? neighbour.x * itssnow.y : 0.0; + water += (itsmotion.w * float(side.y) < 0.0) ? neighbour.y * itswater.y : 0.0; + } + snow += coming; + packed += coming * neighbour.z; + } + snow = max(snow, 0.0); + return vec4(snow, max(water, 0.0), (snow > 1e-4) ? clamp(packed / snow, 0.0, 1.0) : 0.0, state.w); +} + +// the snow and the water of the line of texels the blade went over in the step, ending at a texel (the blade goes on from it to +// the texel ahead), and the packing of the snow (summed for its snow) +vec3 snow_line(ivec2 last, int blade, ivec2 way) +{ + vec3 line = vec3(0.0); + for (int k = 0; k < SNOW_WIPE_LINE; ++k) + { + ivec2 texel = last - way * k; + if (false == snow_crossed(texel, blade)) + break; + vec4 state = water_snow_texel(snow_slot, snow_from, texel); + line += vec3(state.x, state.y, state.x * state.z); + } + return line; +} + +void main() +{ + snow_slot = gl_WorkGroupID.y; + uint place = gl_GlobalInvocationID.x; + if ((water_snow_slots[snow_slot] < 0.5) || (place >= uint(WATER_MAP * WATER_MAP))) + return; + snow_from = (water_snow.w > 0.5) ? 1u : 0u; + uint to = 1u - snow_from; + snow_axes_base = snow_slot * uint(WATER_MAP * WATER_MAP); + if (place == 0u) + water_header[snow_slot].zw = vec2(1.0, float(to)); + ivec2 texel = ivec2(int(place % uint(WATER_MAP)), int(place / uint(WATER_MAP))); + uint index = water_snow_base(snow_slot, to) + 2u * place; + if (false == snow_on_glass(texel)) + { + water_cells[index] = 0u; + water_cells[index + 1u] = 0u; + return; + } + float seconds = water_step.x; + vec4 before = water_snow_texel(snow_slot, snow_from, texel); + vec4 state = snow_move(texel, before, seconds); + + // the blades: taken where they went over, pushed on in front of them + bool crossed = false; + vec3 pushed = vec3(0.0); + for (int blade = 0; blade < 4; ++blade) + { + if (snow_crossed(texel, blade)) + { + crossed = true; + continue; + } + // every texel the blade went over goes to one texel ahead at most, so the snow it pushes isn't counted twice (it would + // grow at every step): in the sweep the texel takes the line of texels behind itself along the way of the blade, off the + // sweep (the blade pushes the snow out at its edge) the line of one of its neighbours pointing at it + if (snow_blade(texel, blade) > 0.001) + { + ivec2 way = snow_blade_way(texel, blade); + if ((way != ivec2(0)) && snow_crossed(texel - way, blade)) + pushed += snow_line(texel - way, blade, way); + continue; + } + for (int k = 0; k < 8; ++k) + { + ivec2 from = texel + SNOW_AROUND[k]; + if (false == snow_crossed(from, blade)) + continue; + ivec2 way = snow_blade_way(from, blade); + if ((way != ivec2(0)) && (from + way == texel)) + { + pushed += snow_line(from, blade, way); + break; + } + } + } + if (crossed) + { + float left = min(state.x * SNOW_WIPE_MISS, SNOW_WIPE_LEFT); + float taken = state.x - left; + state.x = left; + state.y = state.y * SNOW_WIPE_WATER + min(taken * mix(SNOW_FRESH, SNOW_PACKED, state.z) * SNOW_WIPE_TRACE, SNOW_WIPE_WET); + } + if (pushed.x + pushed.y > 0.0) + { + float snow = state.x + pushed.x; + // pressed by the blade + state.z = (snow > 1e-4) ? clamp((state.z * state.x + max(pushed.z, pushed.x * 0.85)) / snow, 0.0, 1.0) : state.z; + state.x = snow; + state.y += pushed.y * 0.5; + } + + // the flakes landing + water_frame_s frame = snow_frame(texel); + float area = length(cross(frame.tu, frame.tv)) / float(WATER_MAP * WATER_MAP); // m2 + vec3 coming = water_air.xyz - water_up.xyz * water_air.w; // the snow against the cab, m/s + float facing = max(-dot(coming, frame.normal), 0.0) + SNOW_EDDIES; + float speed = water_snow.z; + float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); + float wet = state.y / (state.y + state.x * density + 1e-4); + // the dry flakes bounce off a fast glass, the ones landing on wet snow or water stay + float sticking = 1.0 - 0.6 * smoothstep(15.0, 35.0, speed) * (1.0 - smoothstep(0.1, 0.4, wet)); + float landings = water_snow.x / max(water_air.w, 0.1) * facing * area * seconds * sticking; + vec4 random = water_random(place, snow_slot, water_counts.x, 0x5e0du); + float count = min(floor(landings) + ((random.x < fract(landings)) ? 1.0 : 0.0), 4.0); + if (count > 0.0) + { + float water = count * mix(SNOW_FLAKE_LEAST, SNOW_FLAKE_MOST, random.y * random.y); // mm3 + float added = water / SNOW_FRESH / max(area * 1e6, 1e-3); // mm of fresh snow over the texel + float snow = state.x + added; + state.z = state.z * state.x / snow; + // a flake on the bare glass has a shape of its own + state.w = (state.x < 0.3) ? random.z : state.w; + state.x = snow; + } + + // the melting at the warm glass and the drying + float glass = water_up.w + water_snow.y / (1.0 + speed / 12.0); + float melted = min(SNOW_MELT * max(glass, 0.0) * seconds, state.x * density); + state.x -= melted / max(density, 1e-3); + float film = state.y * (1.0 - smoothstep(0.5, 3.0, state.x)); // the water not soaked into the snow + state.y = max(state.y + melted - (SNOW_DRY + SNOW_FILM_DRY * film) * seconds, 0.0); + + state.x = clamp(state.x, 0.0, SNOW_MOST); + state.y = min(state.y, 4.0); + if (state.x < 0.002) + { + state.x = 0.0; + state.z = 0.0; + } + water_cells[index] = packHalf2x16(state.xy); + water_cells[index + 1u] = packHalf2x16(state.zw); +}