diff --git a/shaders/ogl46/mat_rain_windscreen.frag b/shaders/ogl46/mat_rain_windscreen.frag index 91ed0ad96..06a221f89 100644 --- a/shaders/ogl46/mat_rain_windscreen.frag +++ b/shaders/ogl46/mat_rain_windscreen.frag @@ -1,29 +1,44 @@ #version 460 core #define STAGE_FRAGMENT 1 -// Windshield rain and snow -// by @lcddisplay; wiper movement @MichauSto; water on the glass rewritten as a model of drops lying on it +// Windshield rain effects - v3 (rewrite) +// by @lcddisplay; wiper movement @MichauSto; rain v3: drop layers, drop life, rivulets that sweep drops // -// the material: the textures diffuse (the glass) and wipermask (a blade per channel, r g b a: 0 where it doesn't reach, elsewhere -// the place of the blade over its sweep, 0 at rest .. 1 at the far end, at which it goes over the place). raindropsatlas and -// raindrop_grid_size aren't used any more, they stay so the materials which name them still load. rain_scale (1 when not given) -// scales the drops and the flakes. water_slot is given by the renderer (1 + the glass of the simulation, 0 none), not by the -// material. the block of the scene: rain_params (x: how heavy the rain or snow is, z: 1 for snow, w: temperature of the air), -// wiper_pos, wiper_timer_out, wiper_timer_return (the blades of the vehicle of the camera) and rain_wind (the air against it). +// What is on the glass: +// 1. Micro droplets: a dense grid of tiny, static droplets. Procedural (no texture reads): a spherical cap +// per droplet. They make the glass look wet between the bigger drops. +// 2. Drops: one per grid cell (raindrop_grid_size), shape from the 2x2 drop tiles of the atlas +// (normalmap: rg = normal xy, b = height, a = mask). A drop lands (quick pop), sits still for +// drop_life_min..drop_life_max seconds, then makes room for a new one. Drops do NOT slide: all motion is +// done by the rivulets (a sliding drop used to leave its 3x3 neighbourhood and got cut off). +// Sizes are skewed (many medium, few big) and the tiles are randomly mirrored (8 shapes instead of 4). +// Where drops overlap, the higher one wins (no averaged "ghost" normals). +// 3. Rivulets: a drop runs down in stick-slip fashion and leaves a wet trail (4 sprites in the right half +// of the atlas, 256 x 1024: head in the bottom STREAK_HEAD_FRAC, trail above). The head sweeps up every +// drop and droplet on its way: the trail band is clean until the rivulet fades out. +// The trail right above the head is taken from the sprite part that touches the head, then it blends +// into the trail pattern that is fixed to the glass (beads stay where they were left). // -// the glasses of the cab of the train are simulated (gfx::windscreen_water, water_*.comp, water.glsl): the raindrops land as often -// as the rain hits the glass, splashing; the drops lie held by surface tension until gravity and the drag of the air pull them -// harder, then slide in stops and goes, wetting their paths (the next ones follow them into rivulets) and leaving droplets behind; -// the drops which touch flow together; the blades take the water along, gather it into a bead and leave it at the ends of their -// sweep, where it runs down; the flakes stick and melt. here the drops of the simulation are drawn where the fragment is, and the -// wetted paths as a thin film. elsewhere (the windows of other vehicles, a glass the simulation has no room for) the water is made -// up from the time alone: drops landing, growing and sliding along tracks, the blades pushing a ridge and leaving the water at the -// edge of their sweep. +// Shading: the grey atlas (bright rim, dark middle) is read once per pixel, only for the drop that wins the +// pixel (it used to be read for all 9 neighbours). Micro droplets are shaded analytically. // -// the water is a field of soft kernels (metaballs): drops coming close flow together, and a drop is a few kernels, so the drops -// are of many shapes. a drop is a lens holding a sharp picture of the place around it turned over (the image of the last frame -// where the screen holds it, the sky and the ground elsewhere), its edge shows the light of the sky reflected inside it; the lamps -// and the headlights light the water up; the film the blades leave breaks up behind them and the lights seen through it are drawn -// into lines towards their pivot; the wet glass is a little milky +// Refraction / blur (OpenGL 4.6, the renderer with the screen space reflections): the glass reads the image of the last +// frame the renderer keeps for the reflections (ssr_history, with mipmaps) and the depth of the scene (scene_depth): +// - drops act as small lenses: the pixel shows the scene on the opposite side of the drop centre, so every drop holds a +// small, flipped picture (drop_lens); rivulets bend the view by Snell's law from their normal, +// - bright lights near a drop (signals, lamps, headlights) show up in it, +// Works standing still, with the motion blur off and with taa. Needs gfx.ssr (default: medium); without it the drops show +// the sky / ground only, faintly. +// The haze of the wet glass is blurred by the post-processing, from the picture of this frame: the glass writes a request +// into the velocity target (x = 64 * strength, y = 0) and postfx_taa.frag (with gfx.antialiasing taa: every frame) or +// postfx_motionblur.frag (without it: only while something moves) blur the picture there (rain_windscreen_haze.glsl). +// +// Speed: the air against the vehicle (rain_wind) drives the water: at speed a second layer of rivulets runs along its push +// (up a front glass, back along a side window) and sweeps the drops up on its way, the drops are stretched along the push, +// the haze grows. Standing still the rain is as it always was. +// +// OpenGL 4.6 renderer (feat/gl46-migration): headlights and lamps are clustered, calc_headlights takes the +// screen-space derivatives of f_pos, the sun glint follows the cloud shadow. Lamps (cab lamp, scenery) light up +// the drops too (drop_lamp_scatter). layout(location = 0) in vec3 f_normal; layout(location = 2) in vec2 f_coord; @@ -37,1176 +52,1020 @@ 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) // rg = normal xy, b = height, a = mask; 2048 x 1024 (drops left, rivulets right), 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) -#pragma param(rain_scale, 2, 1, 1, one) #include "light_common.glsl" #include "apply_fog.glsl" #include "tonemapping.glsl" -#include "water.glsl" +#include "random.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; -const float RW_PI = 3.14159265; -// refractive index of water -const float RW_IOR = 1.333; -// the falling particles (particles_precipitation.comp, rendering/common/gpuparticles.cpp): the diameters of the flakes, metres, -// and how fast the rain and the snow fall, m/s -const vec2 RW_SNOW_DIAMETER = vec2(0.004, 0.012); -const float RW_RAIN_FALL = 7.0; -const float RW_SNOW_FALL = 1.1; -// a drop is a lens: it holds a sharp picture of the place around it, turned over through its middle, RW_LENS times as far out -// as the fragment is from the middle (and as much smaller), with this share of the bending of the view by the surface on top -const float RW_LENS = 2.0; -const float RW_LENS_BEND = 0.15; -// the drag of the air going along the glass: the speed at which it equals the weight of a drop, m/s; and the share of the air -// meeting the glass head on which turns up along it. so the water goes up a glass the sooner the more it leans back: on a -// vertical glass at about 250 km/h, leaning 20 degrees at about 130 km/h, 45 degrees at about 80 km/h -const float RW_DRAG_SPEED = 24.0; -const float RW_HEAD_ON = 0.35; -// the water is a field summed from soft kernels (metaballs) and its surface is where the field is RW_SURFACE: drops which come -// close flow together the way surface tension pulls them. a kernel alone reaches the surface at RW_EDGE of its radius -const float RW_SURFACE = 0.25; -const float RW_EDGE = 0.61; +// --- 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) +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 -// the glass at the fragment: the view space steps along it for a step of the coordinates of the glass (metres along the axes -// of the model, see main()), and the size of a pixel on it, metres -vec3 rw_tu; -vec3 rw_tv; -float rw_pixel; +// --- Drops (atlas tiles) ------------------------------------------------------ +const float drop_density = 0.6; // share of grid cells holding a drop at full rain (scaled by rain intensity) +const float drop_size_min = 0.45; // drop size in grid cells +const float drop_size_max = 1.15; +const float drop_size_bias = 1.8; // >1 = more small/medium drops, fewer big ones +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 drop_sag = 0.12; // max vertical stretch of a resting drop (gravity) -// how the water on the glass behaves here, set by main() -float rw_scale; // size of the drops (param rain_scale) -float rw_since; // seconds since a blade last cleaned the place -float rw_period; // seconds between the small drops landing on a place of one -float rw_grow; // seconds the drops need after a wipe to grow big enough to slide -float rw_rate; // how fast the glass gathers the rain against a standing vertical glass in the heaviest rain -float rw_push; // the force on a drop along the glass, in units of its weight -vec2 rw_down; // the way gravity pulls along the glass (coordinates of the glass, unit) -vec2 rw_flow; // the way the air goes along the glass (unit, 0 in still air) +// --- Micro droplets ------------------------------------------------------------- +const float micro_density = 0.45; // share of micro cells holding a droplet at full rain, 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; +const float micro_bulge = 0.80; // slope of the droplet dome at its rim (0..0.95) +const float micro_life = 60.0; // average seconds a droplet lives -// the field of the water: the sum of the kernels, its gradient along the glass (view space) and the sums for the mean radius of -// the drops it is made of -float rw_field = 0.0; -vec3 rw_fgrad = vec3(0.0); -float rw_fsize = 0.0; -float rw_fweight = 0.0; +// --- Look of the drops (grey atlas for drops / rivulets, the same look computed for micro droplets) --------- +const float drop_rim_start = 0.30; // micro droplets: dome slope (1 - nz) where the bright rim starts +const float drop_rim_end = 0.80; // ... and where it is fully bright +const float drop_light_side = 0.25; // micro droplets: brighter on the upper-left side +const float drop_center_alpha = 0.25; // how much the dark middle of a drop covers the scene +const float drop_rim_alpha = 0.85; // how much the bright rim covers the scene +const float drop_shade_alpha = 0.30; // faint alpha over the whole dome (carries the glints) -// the water at the fragment: the thickness of the highest water there (metres), its gradient (view space), the radius of the -// curvature of its surface (metres: how much it bends the view across a pixel) and how much of the pixel it covers -float rw_height = 0.0; -vec3 rw_slope = vec3(0.0); -float rw_curve = 1.0; -float rw_cover = 0.0; -// from the middle of the drop which gives the water to the fragment (view space, metres), 0 for spread water -vec3 rw_offset = vec3(0.0); -// the last time the water a blade pushes went over the fragment, taking the drops lying there with it -float rw_cleared = -1.0e9; +// --- Light on the drops -------------------------------------------------------- +const float drop_ior = 1.33; // refraction index of water +const float drop_refract = 0.5; // rivulets: strength of the picture shift (Snell; 1 = physical) +const float drop_lens = 2.0; // drops: lens field, the drop shows (1 + drop_lens) x its own size, flipped +const float drop_lens_mix = 0.7; // drops: 1 = lens picture, 0 = Snell shift like the rivulets +const float drop_env = 0.6; // reflection of the environment on the dome (0 = off) +const float drop_glint_strength = 5.0; // sun / moon glint brightness +const float drop_glint_sharpness = 40.0; // sun / moon glint size (lower = a wider lobe, so more drops catch it) +const float drop_sheen = 0.3; // wide, soft sun sheen on the domes around the sharp glint +const float drop_headlight_scatter = 3.0; // how much drops light up in headlight beams +const float drop_lamp_scatter = 1.0; // GL 4.6: how much drops light up from lamps (station lamps, signals), 0 = off +const float drop_light_near = 4.0; // lights nearer than this (metres; the own vehicle) don't light the drops, full from 2x +const float drop_light_max = 3.0; +const float drop_dark_lum = 0.25; // average brightness of the screen (scene units) below which the drops darken with it // the most the lamps and headlights add to a drop (scene units, before tonemapping) -uvec4 rw_pcg4d(uvec4 v) +// --- Rivulets (drops that run down and leave a wet trail) --------------------------------- +// Sizes are in "drop cells" (1 cell = 1 / raindrop_grid_size of the glass UV). +const float streak_density = 1.00; // share of cells carrying a rivulet (scaled by the rain intensity), 0 = off +const float streak_cell = 6.0; // width of a rivulet cell in drop cells +const float streak_run = 20.0; // height of a rivulet cell in drop cells = the longest run of one rivulet +const float streak_head = 1.7; // mean width of the drop head, in drop cells (randomised 0.75x .. 1.25x) +const float streak_period = 40.0; // seconds a rivulet lives (it runs for ~90% of that and then fades out), average +const float streak_wiggle = 0.35; // how far the path swings sideways, in head widths (0 = straight) +const float streak_wiggle_speed = 0.5; // speed of the little waves that flow down the trail +const float streak_flow = 0.15; // ripples flowing down inside the trail (shows in refraction and glints), 0 = off +const float streak_uv_aspect = 1.0; // glass width / height in UV terms (1 = same stretch as the drops) +const float streak_sweep = 1.0; // 1 = the head sweeps up drops on its way (clean band behind it), 0 = off +const float streak_sweep_width = 0.9; // width of the swept band, in head widths +const float streak_link = 1.5; // head widths above the head where the trail is taken from the sprite part + // that touches the head (so the trail always leaves the head cleanly) + +// --- Speed: the air against the vehicle (rain_wind) drives the water on the glass -------------------- +// The force on the water along the glass: its weight (gravity) and the drag of the air going along the glass (and of the +// share of the air meeting it head on which turns up along it), as in the stock shader of the renderer. Standing still +// (or in a light wind) nothing of it shows: the rain lands, grows and runs down as it always did. +const float wind_drag_gain = 4.0; // how strongly the air drives the water (1 = the drag of the stock shader: on a + // vertical front glass the water would go up only at ~250 km/h) +const float wind_streaks = 3.0; // density of the rivulets driven by the air, at full drag (x streak_density) +const float wind_cell_scale = 0.36; // the rivulets of the air: their cells this much narrower ... +const float wind_run_scale = 0.28; // ... and shorter than those of gravity: many small drops with short trails +const float wind_head_scale = 0.55; // their heads this much smaller +const int wind_layers = 4; // layers of them, each with drops of its own (1 .. 4) +const float wind_long_run = 1.6; // the last layer: its trails this much longer than those of gravity (the long ones, a part of all) +const float wind_streak_period = 14.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) +const float drop_wind_stretch = 0.4; // drops are stretched up to this much along the push of the air (0 = off) +const float WS_DRAG_SPEED = 24.0; // speed of the air along the glass at which its drag equals the weight of a drop, m/s +const float WS_HEAD_ON = 0.35; // share of the air meeting the glass head on which turns up along it +const float WS_WIND_STEP = 0.1309; // the direction of the rivulets of the air in steps of 7.5 degrees (no seams on a + // curved glass, where every triangle would turn them a little) + +#ifndef STREAK_FLIP_Y +#define STREAK_FLIP_Y 0 // set to 1 if the rivulets run UP the glass (head on top) +#endif +const float STREAK_TAIL_SCALE = 1.5; // the trail pattern of the sprite is drawn this much longer than native +const float STREAK_HEAD_FRAC = 0.22; // part of the sprite height used by the drop head (= HEAD_FRAC of the atlas generator) + +const float WS_INSIDE = 0.3; // metres beyond the glass nearer than which the image is taken for the inside of the cab + // (in the rain the cab isn't in the depth: the nose of the own vehicle is outside) +const float WS_REFR_MAXPX = 96.0; // largest picture shift of a drop, screen pixels +const float WS_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the refracted picture +const float WS_LIGHT_GAIN = 1.0; // brightness of the lights near a drop shown in it (0 = off) +const float WS_LIGHT_CONTRAST = 3.0; // a light: this many times brighter than the place around it + +const vec3 DROP_LIGHT = vec3(-0.5527, 0.6532, 0.5226); // same light as the atlas generator (upper left) + +// the surroundings in a view space direction where the image doesn't hold them: the environment map above the horizon, +// the ground below it, blurred by Lod (as in the stock mat_rain_windscreen.frag) +vec3 wsSurroundings(vec3 direction, float lod) { - v = v * 1664525u + 1013904223u; - v.x += v.y * v.w; - v.y += v.z * v.x; - v.z += v.x * v.y; - v.w += v.y * v.z; - v ^= v >> 16u; - v.x += v.y * v.w; - v.y += v.z * v.x; - v.z += v.x * v.y; - v.w += v.y * v.z; - return v; + vec3 world = mat3(inv_view) * direction; + vec3 sky = envmap_sample_rough(normalize(vec3(world.x, max(world.y, 0.0), world.z)), clamp(lod / 8.0, 0.0, 1.0)); + float below = smoothstep(-0.03 - 0.05 * lod, 0.25 + 0.05 * lod, -world.y); + if ((below <= 0.0) || (false == ENVMAP_ENABLED)) + return sky; + return mix(sky, reflection_ground(), below); } -// four numbers 0 .. 1 of a cell of a layer -vec4 rw_random(ivec2 cell, uint layer, uint index) +// what is seen through the glass in a view space direction: the image of the last frame where it holds the place, Distance +// away along the direction (0: far), blurred by Lod; Share: how much of it the image gave. Fade: towards the edges of the +// image the surroundings take over. The inside of the cab (near the camera in the depth) is never taken: the surroundings +// stand for it (else the drops would show the dark walls of the cab) +vec3 wsBehind(vec3 direction, float lod, float distance, out float share, bool fade) { - return vec4(rw_pcg4d(uvec4(uvec2(cell), layer, index))) * (1.0 / 4294967296.0); + share = 0.0; + vec3 around = wsSurroundings(direction, lod); + if (ssr_params.x < 1.0) + return around; + vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); + if (previous.w <= 1e-5) + return around; + vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; + vec2 edges = min(coords, 1.0 - coords); + share = fade ? smoothstep(0.0, 0.04, min(edges.x, edges.y)) : step(-0.02, min(edges.x, edges.y)); + coords = clamp(coords, vec2(0.0), vec2(1.0)); + if (share <= 0.0) + return around; + ivec2 size = textureSize(scene_depth, 0); + float depth = texelFetch(scene_depth, clamp(ivec2(coords * vec2(size)), ivec2(0), size - 1), 0).r; + float near = projection[3][2]; + if ((depth > 0.0) && (near / depth < -f_pos.z + WS_INSIDE)) + { + share = 0.0; + return around; + } + vec3 color = textureLod(ssr_history, coords, clamp(lod, 0.0, ssr_params2.x)).rgb; + if (any(isnan(color)) || any(isinf(color))) + { + share = 0.0; + return around; + } + return mix(around, max(color, vec3(0.0)), share); } -float rw_noise(float x, uint layer) +float wsLum(vec3 c) { - float i = floor(x); - float f = x - i; - float a = rw_random(ivec2(int(i), 0), layer, 7u).x; - float b = rw_random(ivec2(int(i) + 1, 0), layer, 7u).x; - return mix(a, b, f * f * (3.0 - 2.0 * f)); + return dot(c, vec3(0.2126, 0.7152, 0.0722)); } -// value noise 0 .. 1 (x) with its gradient (yz) -vec3 rw_noise2(vec2 p, uint layer) +// bright lights near a drop (signals, lamps, headlights): a drop is a wide-angle lens and picks them up. A light is where a +// fine mip level of the image (~11 px around) is much brighter than a coarse one (~90 px around) +vec3 wsLightGlow(vec3 direction, float distance) { - vec2 i = floor(p); - vec2 f = p - i; - vec2 u = f * f * (3.0 - 2.0 * f); - vec2 du = 6.0 * f * (1.0 - f); - ivec2 c = ivec2(i); - float a = rw_random(c, layer, 8u).x; - float b = rw_random(c + ivec2(1, 0), layer, 8u).x; - float d = rw_random(c + ivec2(0, 1), layer, 8u).x; - float e = rw_random(c + ivec2(1, 1), layer, 8u).x; - float k1 = b - a; - float k2 = d - a; - float k4 = a - b - d + e; - return vec3(a + k1 * u.x + k2 * u.y + k4 * u.x * u.y, du * vec2(k1 + k4 * u.y, k2 + k4 * u.x)); -} - -// P turned by A (radians). every set of drops is laid on its own grid, turned and shifted against the others, so the drops line -// up neither with each other nor along the glass -vec2 rw_turn(vec2 p, float a) -{ - float c = cos(a); - float s = sin(a); - return vec2(c * p.x - s * p.y, s * p.x + c * p.y); -} - -// a gradient given along the coordinates of the glass, view space -vec3 rw_along(vec2 gradient) -{ - return rw_tu * (gradient.x / dot(rw_tu, rw_tu)) + rw_tv * (gradient.y / dot(rw_tv, rw_tv)); -} - -// the gradient along the glass (view space) of a value of the fragments, from how it changes from pixel to pixel; Dpdx, Dpdy: -// the steps of the position, Normal: of the glass -vec3 rw_gradient(float value, vec3 dpdx, vec3 dpdy, vec3 normal) -{ - vec3 r1 = cross(dpdy, normal); - vec3 r2 = cross(normal, dpdx); - float det = dot(dpdx, r1); - float dx = dFdx(value); - float dy = dFdy(value); - return (abs(det) > 1e-14) ? (dx * r1 + dy * r2) / det : vec3(0.0); -} - -// a kernel of the water, Offset (view space) from its centre to the fragment: alone it makes water of the radius Visible, -// Weight 1 .. 0 as it goes. water smaller than a pixel would only flicker, it is left to the haze of the wet glass -void rw_kernel(vec3 offset, float visible, float weight) -{ - if ((weight <= 0.0) || (visible < 0.5 * rw_pixel)) - return; - // a drop a pixel or two across is grain rather than a lens: it fades into the haze of the wet glass - weight *= smoothstep(0.5 * rw_pixel, 2.0 * rw_pixel, visible); - float support = visible / RW_EDGE; - float q = dot(offset, offset) / (support * support); - if (q >= 1.0) - return; - float k = 1.0 - q; - float k3 = weight * k * k * k; - rw_field += k3; - rw_fgrad += offset * (-6.0 * weight * k * k / (support * support)); - rw_fsize += k3 * visible; - rw_fweight += k3; -} - -// a kernel at the Offset in the coordinates of the glass -void rw_blob(vec2 offset, float visible, float weight) -{ - rw_kernel(offset.x * rw_tu + offset.y * rw_tv, visible, weight); -} - -// a drop lying on the glass: a few kernels, sagging down the glass and lopsided as Shape (random 0 .. 1) says -void rw_drop(vec2 offset, float visible, float weight, vec4 shape) -{ - rw_blob(offset, visible, weight); - if (visible < 1.5 * rw_pixel) - return; - vec2 side = vec2(-rw_down.y, rw_down.x); - vec2 sag = (rw_down * (0.2 + 0.35 * shape.x) + side * ((shape.y - 0.5) * 0.7)) * visible; - rw_blob(offset - sag, visible * mix(0.6, 0.85, shape.z), weight); - if (shape.w > 0.4) - { - float angle = shape.w * 40.0; - rw_blob(offset - vec2(cos(angle), sin(angle)) * (0.6 * visible), visible * mix(0.4, 0.6, shape.x), weight); - } -} - -// water spread over the glass (a film, a ridge): its thickness, the gradient of it (view space), the radius of the curvature of -// its surface and how much of the pixel it covers -void rw_sheet(float thickness, vec3 slope, float curve, float cover) -{ - if (cover <= 0.0) - return; - rw_cover = max(rw_cover, cover); - if (thickness > rw_height) - { - rw_height = thickness; - rw_slope = slope; - rw_curve = curve; - rw_offset = vec3(0.0); - } -} - -// the surface of the water of the field: a drop is a cap of a sphere, flat lens of the contact angle Contact (radians) the water -// makes with the glass. how far across a drop the fragment is follows from the field (inverting the kernel), the height and -// the slope of the cap from that: the slope rises slowly from the middle and steeply only close to the edge, where it reaches -// the contact angle; where drops flowed together the field is above that of a drop alone and the water is flat. the edge is -// antialiased by how fast the field changes across a pixel -void rw_settle(float contact) -{ - if (rw_field <= 0.5 * RW_SURFACE) - return; - float gradient = length(rw_fgrad); - float cover = clamp((rw_field - RW_SURFACE) / max(gradient * rw_pixel, 1e-3) + 0.5, 0.0, 1.0); - if (cover <= 0.0) - return; - float mean = rw_fsize / max(rw_fweight, 1e-12); - // 0 in the middle of a drop, 1 at its edge - float across = min(sqrt(max(1.0 - pow(min(rw_field, 1.0), 1.0 / 3.0), 0.0)) / RW_EDGE, 1.0); - float s = sin(contact); - float rs = across * s; - float root = sqrt(max(1.0 - rs * rs, 1e-4)); - float sphere = mean / s; - vec3 slope = (gradient > 1e-9) ? rw_fgrad * ((rs / root) / gradient) : vec3(0.0); - float height = max(sphere * (root - cos(contact)), 0.0); - bool top = height > rw_height; - rw_sheet(height, slope, sphere, cover); - // the field rises towards the middle of the drop - if (top && (gradient > 1e-9)) - rw_offset = rw_fgrad * (-across * mean / gradient); -} - -// the blades. a channel of the mask of the wipers is a blade: 0 where it doesn't reach, elsewhere the place of the blade over its -// sweep (0 at rest .. 1 at the far end) at which it goes over the place. wiper_pos: where the blade is (0 .. 1 on its way out, -// 1 + where it is on its way back), wiper_timer_out / _return: the last time it lay at its start / was at its far end -struct rw_wipe_s -{ - float since; // seconds since a blade last went over the place (large where none reaches) - float ahead; // 0 .. 1, how close in front of a moving blade the place is (the water the blade pushes) - float front; // how far in front of the nearest moving blade the place is, units of the mask (1 where none) - float swept; // 0 .. 1, how much of its way the blade in front did, the water it gathered on the way - float working; // 0 .. 1, the blades went lately -}; - -rw_wipe_s rw_wipe(vec4 mask) -{ - rw_wipe_s wipe = rw_wipe_s(1.0e4, 0.0, 1.0, 0.0, 0.0); - for (int i = 0; i < 4; ++i) - { - float m = mask[i]; - if (m < 0.001) - continue; - float pos = wiper_pos[i]; - bool back = pos > 1.0; - float blade = back ? pos - 1.0 : pos; - float t0 = wiper_timer_out[i]; - float t1 = wiper_timer_return[i]; - // when the blade went over the place last: on this stroke, the blade moving at an even pace from its end, or on the - // stroke before, which took as long as the time between the ends (if the blade lay at its end longer, two seconds) - float pass; - float front; // how far in front of the blade the place is (units of the mask), below 0 behind it - if (back) - { - pass = (m >= blade) ? t1 + (time - t1) * ((1.0 - m) / max(1.0 - blade, 1e-3)) : t0 + m * clamp(t1 - t0, 0.0, 2.0); - front = blade - m; - } - else - { - pass = (m <= blade) ? t0 + (time - t0) * (m / max(blade, 1e-3)) : t1 + (1.0 - m) * clamp(t0 - t1, 0.0, 2.0); - front = m - blade; - } - wipe.since = min(wipe.since, max(time - pass, 0.0)); - float moving = smoothstep(0.0, 0.03, blade) * smoothstep(1.0, 0.97, blade); - float ahead = (front > 0.0) ? (1.0 - smoothstep(0.0, 0.035, front)) * moving : 0.0; - wipe.ahead = max(wipe.ahead, ahead); - if ((front > 0.0) && (moving > 0.5)) - wipe.front = min(wipe.front, front); - wipe.swept = max(wipe.swept, ahead * (back ? 1.0 - blade : blade)); - float working = 1.0 - smoothstep(4.0, 30.0, time - t1); - wipe.working = max(wipe.working, working); - } - return wipe; -} - -// a place of the glass a blade reaches -bool rw_reached(vec2 coords) -{ - return any(greaterThanEqual(textureLod(wipermask, clamp(coords, vec2(0.0), vec2(1.0)), 0.0), vec4(0.001))); -} - -// the edge of the sweep of the blades, where they push the water out to: 0 where a blade reaches, else the share of the places -// around at Reach (metres along the glass) which a blade reaches. found from where the blades reach and not from the values of -// the mask, which may stay at the end of the sweep over a wide part of the glass. Maskstep: the coordinates of the mask for a -// step along the glass -float rw_rim(vec2 coords, float reach, mat2 maskstep) -{ - if (rw_reached(coords)) - return 0.0; - float inside = 0.0; - for (int k = 0; k < 6; ++k) - { - float angle = float(k) * (RW_PI / 3.0); - inside += rw_reached(coords + maskstep * (vec2(cos(angle), sin(angle)) * reach)) ? 1.0 : 0.0; - } - return inside / 6.0; -} - -// whether the edge of the sweep of the blades is within Reach of the place -bool rw_border(vec2 coords, float reach, mat2 maskstep) -{ - bool here = rw_reached(coords); - for (int k = 0; k < 6; ++k) - { - float angle = float(k) * (RW_PI / 3.0); - if (rw_reached(coords + maskstep * (vec2(cos(angle), sin(angle)) * reach)) != here) - return true; - } - return false; -} - -// how far along its way a sliding drop is at the share T of the time it takes: it stops and goes, the more smoothly the harder -// it is pushed -float rw_stickslip(float t, float seed) -{ - t = clamp(t, 0.0, 1.0); - float s = t * 3.0; - float i = floor(s); - float stuck = (i + smoothstep(0.25 + 0.4 * seed, 1.0, s - i)) / 3.0; - return mix(stuck, t, smoothstep(0.8, 2.0, rw_push)); -} - -// the track of the water down a column of the glass (Column: its index, Width: of a column, Y: metres up the way): where it -// is across, metres. the water keeps to the way wetted before, so every drop of a column goes the same way, wavy, with kinks -// where the glass held it -float rw_path(int column, float y, float width, uint layer) -{ - float slow = rw_noise(y / (0.05 * rw_scale) + float(column) * 7.31, layer) - 0.5; - float k = y / (0.008 * rw_scale); - float i = floor(k); - float a = rw_random(ivec2(column, int(i)), layer + 500u, 3u).x; - float b = rw_random(ivec2(column, int(i) + 1), layer + 500u, 3u).x; - float kinks = mix(a, b, smoothstep(0.15, 0.85, k - i)) - 0.5; - return (float(column) + 0.5 + 0.4 * slow + 0.2 * kinks) * width; -} - -// the drops which grew big enough to slide, and the streams they leave: Q the place across and up the way they go (Side, Down: -// those directions in the coordinates of the glass), Share of them going this way. a column of the glass carries the water of -// a track; a drop starts somewhere in a cell of the column now and then, slides down with stops, thinning, and leaves a stream -// which drains into beads and dries -void rw_sliders(vec2 q, vec2 side, vec2 down, uint layer, float share) -{ - float width = 0.04 * rw_scale; - float height = 0.15 * rw_scale; - int column = int(floor(q.x / width)); - int row = int(floor(q.y / height)); - vec4 a = rw_random(ivec2(column, 7), layer, 0u); - if (a.x > share * mix(0.35, 0.9, clamp(rw_rate / 3.0, 0.0, 1.0))) - return; - float speed = clamp(0.035 + 0.06 * (rw_push - 0.4) + 0.3 * max(rw_push - 1.5, 0.0), 0.01, 0.8); - float period = clamp(25.0 / rw_rate, 3.0, 60.0); - float trail = 0.0; - for (int r = 0; r < 3; ++r) - { - ivec2 cell = ivec2(column, row + r); - vec4 b = rw_random(cell, layer, 1u); - float span = period * mix(0.7, 1.3, b.x); - float now = floor(time / span + b.y); - for (int k = 0; k < 2; ++k) - { - float cycle = now - float(k); - float start = (cycle - b.y) * span; - float t = time - start; - // the drop gathered from the drops landed since the last wipe - if ((t < 0.0) || (rw_since - t < rw_grow)) - continue; - vec4 c = rw_random(cell, layer + 1000u, uint(int(cycle) + 1000000)); - float top = (float(cell.y) + 0.8 - 0.6 * c.x) * height; - float travel = mix(0.06, 0.28, c.y) * rw_scale; - float v = speed * mix(0.7, 1.3, c.z); - float gather = 0.6; - float moved = travel * rw_stickslip((t - gather) * v / travel, c.w); - float y = top - moved; - float radius = mix(0.003, 0.0042, c.w) * rw_scale * (1.0 - 0.35 * moved / travel) * mix(0.6, 1.0, smoothstep(0.0, gather, t)); - // at the end of its way what is left of it stays and flows out into the stream - float body = 1.0 - smoothstep(0.0, 1.5, t - gather - travel / v); - if ((body > 0.0) && (abs(q.y - y) < 3.5 * radius)) - { - vec2 o = vec2(q.x - rw_path(column, y, width, layer), q.y - y); - rw_blob(side * o.x - down * o.y, radius, body); - // its rear up the stream: a corner, drawn out into a cusp the faster it goes (the front stays round) - float drawn = clamp(v * 5.0, 0.0, 1.5); - for (int k = 1; k <= 2; ++k) - { - float yt = y + radius * (0.45 + 0.5 * drawn) * float(k); - vec2 ot = vec2(q.x - rw_path(column, yt, width, layer), q.y - yt); - rw_blob(side * ot.x - down * ot.y, radius * ((k == 1) ? 0.7 : 0.42), body); - } - } - if ((moved > 0.0) && (q.y > y) && (q.y < top)) - { - float age = t - gather - (top - q.y) / v; - if ((age >= 0.0) && (age < rw_since)) - { - // fresh, the stream is whole; draining, it breaks into beads, which dry - float beads = rw_noise(q.y / (0.004 * rw_scale), layer + 9u); - float wet = mix(1.15, 0.2 + 1.0 * beads, smoothstep(0.0, 15.0, age)) * (1.0 - smoothstep(30.0, 60.0, age)); - trail = max(trail, wet); - } - } - } - } - if (trail > 0.0) - { - float across = q.x - rw_path(column, q.y, width, layer); - float half_width = mix(0.0005, 0.0011, a.y) * rw_scale * (0.6 + 0.8 * rw_noise(q.y / (0.006 * rw_scale), layer + 11u)); - rw_blob(side * across, half_width, trail); - } -} - -// a drop lying on the glass, as rw_drop() with the directions along the glass given in the view space (Down: the way gravity -// pulls along the glass, Side across it) -void rw_drop_view(vec3 offset, float visible, float weight, vec4 shape, vec3 down, vec3 side) -{ - rw_kernel(offset, visible, weight); - if (visible < 1.5 * rw_pixel) - return; - vec3 sag = (down * (0.2 + 0.35 * shape.x) + side * ((shape.y - 0.5) * 0.7)) * visible; - rw_kernel(offset - sag, visible * mix(0.6, 0.85, shape.z), weight); - if (shape.w > 0.4) - { - float angle = shape.w * 40.0; - rw_kernel(offset - (cos(angle) * side + sin(angle) * down) * (0.6 * visible), visible * mix(0.4, 0.6, shape.x), weight); - } -} - -// the water the simulation keeps on the glass (gfx::windscreen_water, water.glsl), where the material is a glass of the cab of the -// train: the drops listed by the cell of the grid the fragment is in. Slot: of the glass, Uv: the coordinates of the fragment, -// Puv: the view space step along the glass for a step of the uv; Down, Side: along the glass. a sliding drop is drawn out behind -// itself into a cusp, the faster the longer; one lying is lopsided and sags down the glass; a flake of snow is lace, grey and -// clear as it melts (Snowcover, Wet: as the flakes of rw_snow()) -void rw_simulated(uint slot, vec2 uv, mat2x3 puv, vec3 down, vec3 side, inout float snowcover, inout float wet) -{ - uint base = water_grid_base(slot); - uint cell = water_cell(uv); - uint count = min(water_cells[base + cell], uint(WATER_CELL_DROPS)); - for (uint k = 0u; k < count; ++k) - { - uint place = water_cells[base + uint(WATER_GRID * WATER_GRID) + cell * uint(WATER_CELL_DROPS) + k]; - water_drop_s drop = water_drops[slot * uint(WATER_DROPS) + place]; - float volume = drop.place.z; - if (volume <= 0.0) - continue; - vec3 offset = puv * (uv - drop.place.xy); - vec4 shape = vec4(rw_pcg4d(uvec4(place, slot, 41u, 0u))) * (1.0 / 4294967296.0); - if (drop.motion.w < 1.0) - { - // a flake: lobed lace, shrinking, grey and clear as it melts - float m = drop.motion.w; - vec2 flat2 = vec2(dot(offset, side), dot(offset, down)); - float radius = 0.5 * water_flake(volume); - float dist = length(flat2); - if (dist < radius + rw_pixel) - { - float angle = atan(flat2.y, flat2.x); - float lobes = 0.55 + 0.45 * (0.6 * rw_noise(angle * 1.9 + shape.z * 40.0, 13u) + 0.4 * abs(cos(3.0 * angle + shape.w * 6.2831853))); - float rim = radius * lobes * (1.0 - 0.45 * m); - float body = smoothstep(rim + rw_pixel, 0.55 * rim - rw_pixel, dist); - float lace = rw_noise2(flat2 / 0.0007 + shape.zw * 100.0, 14u).x; - float flake = body * mix(0.55, 1.0, lace) * (1.0 - 0.7 * m * m); - snowcover = 1.0 - (1.0 - snowcover) * (1.0 - flake); - wet = max(wet, m * body); - } - continue; - } - float radius = water_radius(volume); - vec3 velocity = puv * drop.motion.xy; - float speed = length(velocity); - if (speed > 0.002) - { - // its rear up the way it came: a corner, drawn out into a cusp the faster it goes (the front stays round) - vec3 way = velocity / speed; - rw_kernel(offset, radius, 1.0); - float drawn = clamp(speed * 5.0, 0.0, 1.5); - for (int t = 1; t <= 2; ++t) - rw_kernel(offset + way * (radius * (0.45 + 0.5 * drawn) * float(t)), radius * ((t == 1) ? 0.7 : 0.42), 1.0); - } - else - { - rw_drop_view(offset, radius, 1.0, shape, down, side); - } - } -} - -// how fresh the wetted paths of the simulation are at a place of the glass (x) and how that changes along u and v (yz): the -// texels of their map filtered by a cubic b-spline over 4 x 4 of them, so the edges of a path are smooth curves and its slopes -// change smoothly (a bilinear filter would leave steps at every texel in the bending of the view) -vec3 rw_trail(uint slot, vec2 uv, float now) -{ - // a path stays wet (and seen) longer than the drops keep to it - float lasting = 25.0; - vec2 p = uv * float(WATER_TRAIL) - 0.5; - vec2 i = floor(p); - vec2 f = p - i; - // the weights of the b-spline and their derivatives, for the texels i - 1 .. i + 2 - vec2 g = 1.0 - f; - vec4 wx = vec4(g.x * g.x * g.x, 3.0 * f.x * f.x * f.x - 6.0 * f.x * f.x + 4.0, -3.0 * f.x * f.x * f.x + 3.0 * f.x * f.x + 3.0 * f.x + 1.0, f.x * f.x * f.x) / 6.0; - vec4 wy = vec4(g.y * g.y * g.y, 3.0 * f.y * f.y * f.y - 6.0 * f.y * f.y + 4.0, -3.0 * f.y * f.y * f.y + 3.0 * f.y * f.y + 3.0 * f.y + 1.0, f.y * f.y * f.y) / 6.0; - vec4 dx = vec4(-g.x * g.x, 3.0 * f.x * f.x - 4.0 * f.x, -3.0 * f.x * f.x + 2.0 * f.x + 1.0, f.x * f.x) * 0.5; - vec4 dy = vec4(-g.y * g.y, 3.0 * f.y * f.y - 4.0 * f.y, -3.0 * f.y * f.y + 2.0 * f.y + 1.0, f.y * f.y) * 0.5; - vec3 result = vec3(0.0); - ivec2 base = ivec2(i) - 1; - for (int y = 0; y < 4; ++y) - { - for (int x = 0; x < 4; ++x) - { - float value = water_wetted(slot, base + ivec2(x, y), now, lasting); - result += value * vec3(wx[x] * wy[y], dx[x] * wy[y], wx[x] * dy[y]); - } - } - result.yz *= float(WATER_TRAIL); - return result; -} - -// the surroundings in a view space direction where the screen doesn't hold them: the environment map above the horizon (the sky -// and the clouds), the ground below it, blurred by Lod -vec3 rw_surroundings(vec3 direction, float lod) -{ - vec3 world = mat3(inv_view) * direction; - vec3 sky = envmap_sample_rough(normalize(vec3(world.x, max(world.y, 0.0), world.z)), clamp(lod / 8.0, 0.0, 1.0)); - // the horizon as blurred as the view is - float below = smoothstep(-0.03 - 0.05 * lod, 0.25 + 0.05 * lod, -world.y); - if ((below <= 0.0) || (false == ENVMAP_ENABLED)) - return sky; - return mix(sky, reflection_ground(), below); -} - -// what is seen through the glass in a view space direction: the image of the last frame (the screen space reflections keep it) -// where it holds the place, Distance away along the direction (0: far), blurred by Lod; Share: how much of it the image gave. -// Fade: towards the edges of the image the surroundings take over (else the edges are stretched) -vec3 rw_behind_edges(vec3 direction, float lod, float distance, out float share, bool fade) -{ - share = 0.0; - vec3 around = rw_surroundings(direction, lod); - if (ssr_params.x < 1.0) - return around; - vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); - if (previous.w <= 1e-5) - return around; - vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; - vec2 edges = min(coords, 1.0 - coords); - share = fade ? smoothstep(0.0, 0.04, min(edges.x, edges.y)) : step(-0.02, min(edges.x, edges.y)); - coords = clamp(coords, vec2(0.0), vec2(1.0)); - if (share <= 0.0) - return around; - // the view out through the water goes on outside, where the image shows the inside of the cab around the windows the - // surroundings stand for it (else the drops show the dark walls and roof of the cab) - ivec2 size = textureSize(scene_depth, 0); - float depth = texelFetch(scene_depth, clamp(ivec2(coords * vec2(size)), ivec2(0), size - 1), 0).r; - float near = projection[3][2]; - if ((depth > 0.0) && (near / depth < -f_pos.z + 2.5)) - { - share = 0.0; - return around; - } - vec3 color = textureLod(ssr_history, coords, clamp(lod, 0.0, ssr_params2.x)).rgb; - if (any(isnan(color)) || any(isinf(color))) - { - share = 0.0; - return around; - } - return mix(around, max(color, vec3(0.0)), share); -} - -vec3 rw_behind(vec3 direction, float lod, float distance, out float share) -{ - return rw_behind_edges(direction, lod, distance, share, true); + vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); + if (previous.w <= 1e-5) + return vec3(0.0); + vec2 coords = clamp((previous.xy / previous.w) * 0.5 + 0.5, vec2(0.0), vec2(1.0)); + vec3 near = textureLod(ssr_history, coords, min(3.5, ssr_params2.x)).rgb; + vec3 wide = textureLod(ssr_history, coords, min(6.5, ssr_params2.x)).rgb; + if (any(isnan(near)) || any(isinf(near)) || any(isnan(wide)) || any(isinf(wide))) + return vec3(0.0); + vec3 excess = max(near - wide * WS_LIGHT_CONTRAST, vec3(0.0)); + return min(excess, vec3(30.0)) * (2.0 * WS_LIGHT_GAIN); } // a layer Over put over Under, the colours not premultiplied -vec4 rw_over(vec4 over, vec4 under) +vec4 wsOver(vec4 over, vec4 under) { - float alpha = over.a + under.a * (1.0 - over.a); - if (alpha <= 1e-5) - return vec4(0.0); - return vec4((over.rgb * over.a + under.rgb * under.a * (1.0 - over.a)) / alpha, alpha); + float alpha = over.a + under.a * (1.0 - over.a); + if (alpha <= 1e-5) + return vec4(0.0); + return vec4((over.rgb * over.a + under.rgb * under.a * (1.0 - over.a)) / alpha, alpha); +} + +// =========================================================================== +float GetMixFactor(in vec2 co, out float side); + +uvec2 cellKey(vec2 c); + +vec2 tileOffset(float choice) +{ + if (choice < 0.25) return vec2(0.0, 0.0); + else if (choice < 0.5) return vec2(0.5, 0.0); + else if (choice < 0.75) return vec2(0.0, 0.5); + return vec2(0.5, 0.5); +} + +// the 2x2 drop tiles live in the left half of the atlas: a tile is 0.25 wide and 0.5 high in atlas UV +vec2 dropAtlasUV(float choice, vec2 uv) +{ + vec2 off = tileOffset(choice); + return vec2((off.x + uv.x * 0.5) * 0.5, off.y + uv.y * 0.5); +} + +uvec2 cellKey(vec2 c) +{ + return uvec2(ivec2(c) + ivec2(65536)); +} + +// --- one rivulet cell ------------------------------------------------------------ +struct Riv +{ + bool on; + float life; // 0..1 (fade in / out) + float width; // sprite width = head width (glass UV) + float headH; // head height (glass UV) + float topY; // where the trail starts (fixed on the glass) + float bottom; // bottom of the head now + float left; // left edge of the sprite + float flip; + float col; // which of the 4 sprites + float wipe; + float wavK, wavPh, wavSp; +}; + +// the layer of rivulets being worked on: the one of gravity (the rivulets as they always were, coordinates = glass UV with v +// up) or the one of the air (its own cells and seeds, turned so that its rivulets run along the push of the air) +float wsLayerDensity = 1.0; // x rain x streak_density: share of the cells holding a rivulet +float wsLayerPeriod = streak_period; +uint wsLayerSalt = 91u; +float wsLayerHead = 1.0; // x streak_head +float wsLayerCos = 1.0; // the layer is turned by this angle (its "down" is the way its water runs on the glass) +float wsLayerSin = 0.0; + +// glass UV (v up) -> coordinates of the layer, where the rivulets run down (-v) +vec2 wsToLayerDir(vec2 v) +{ + return vec2(wsLayerCos * v.x + wsLayerSin * v.y, -wsLayerSin * v.x + wsLayerCos * v.y); +} +vec2 wsToLayer(vec2 g) +{ + return wsToLayerDir(g - 0.5) + 0.5; +} +vec2 wsFromLayerDir(vec2 v) +{ + return vec2(wsLayerCos * v.x - wsLayerSin * v.y, wsLayerSin * v.x + wsLayerCos * v.y); +} +vec2 wsFromLayer(vec2 p) +{ + return wsFromLayerDir(p - 0.5) + 0.5; +} + +// the layers: 0 gravity, 1 air. WindShare: how much the air drives the water (0 standing still), WindCos / WindSin: the turn +// of the layer of the air +float wsWindShare = 0.0; +float wsWindCos = 1.0; +float wsWindSin = 0.0; +void wsSetLayer(int layer) +{ + if (layer == 0) + { + wsLayerDensity = 1.0 - wsWindShare; + wsLayerPeriod = streak_period; + wsLayerSalt = 91u; + wsLayerHead = 1.0; + wsLayerCos = 1.0; + wsLayerSin = 0.0; + } + else + { + wsLayerDensity = wsWindShare * wind_streaks; + wsLayerPeriod = wind_streak_period; + wsLayerSalt = 91u + 2u * uint(layer); + wsLayerHead = wind_head_scale; + wsLayerCos = wsWindCos; + wsLayerSin = wsWindSin; + } +} + +Riv getRiv(vec2 sCell, float sCW, float sCH, float gridSize) +{ + Riv r; + uint sSeed = Hash(uvec3(cellKey(sCell), wsLayerSalt)); + r.on = (RandF(sSeed) < rain_params.x * streak_density * wsLayerDensity); + float sPeriod = wsLayerPeriod * mix(0.6, 1.6, RandF(sSeed)); + float sPhase = fract(time / sPeriod + RandF(sSeed)); + r.life = smoothstep(0.0, 0.05, sPhase) * (1.0 - smoothstep(0.86, 1.0, sPhase)); + r.width = streak_head * wsLayerHead / gridSize * mix(0.75, 1.25, RandF(sSeed)); + r.headH = r.width * 0.88 * streak_uv_aspect; + float sSpan = max(sCH * mix(0.35, 0.70, RandF(sSeed)), r.headH * 3.0); + // stick-slip: the drop waits, then lurches forward; N waits on the way down + float sSteps = floor(mix(3.0, 8.0, RandF(sSeed))); + float sXs = clamp(sPhase / 0.88, 0.0, 1.0) * sSteps; + float sRun = clamp((floor(sXs) + smoothstep(0.55, 1.0, fract(sXs))) / sSteps, 0.0, 1.0); + r.topY = sCell.y * sCH + sSpan + RandF(sSeed) * max(sCH - sSpan, 0.0); + r.bottom = r.topY - r.headH * 1.2 - sRun * (sSpan - r.headH * 1.2); + const float sMargin = 0.8; + r.left = sCell.x * sCW + sMargin * r.width + RandF(sSeed) * max(sCW - r.width * (1.0 + 2.0 * sMargin), 0.0); + r.flip = (RandF(sSeed) < 0.5) ? 1.0 : 0.0; + r.col = floor(RandF(sSeed) * 4.0); + r.wipe = RandF(sSeed); + r.wavK = 6.2831853 / mix(2.5, 5.0, RandF(sSeed)); + r.wavPh = RandF(sSeed) * 6.2831853; + r.wavSp = streak_wiggle_speed * mix(0.6, 1.4, RandF(sSeed)); + return r; +} + +// sideways offset of the path (in head widths) at distance dW (head widths) down from the start of the trail +float rivWob(Riv r, float dW, out float ramp, out float wobD) +{ + float rampT = clamp(dW / 2.5, 0.0, 1.0); + ramp = rampT * rampT * (3.0 - 2.0 * rampT); + float rampD = 3.0 * rampT * (1.0 - rampT) / 2.5; + float a1 = dW * r.wavK + r.wavPh; + float a2 = dW * r.wavK * 1.7 - time * r.wavSp * 1.0472 + r.wavPh * 2.0; // the wave runs DOWN + float w1 = 0.7 * sin(a1) + 0.3 * sin(a2); + float w1D = 0.7 * cos(a1) * r.wavK + 0.3 * cos(a2) * r.wavK * 1.7; + wobD = -streak_wiggle * (rampD * w1 + ramp * w1D); + return streak_wiggle * ramp * w1; +} + +// how much a drop centred at p (glass UV, v up) with radius rad has been swept up by rivulet r (0..1) +float rivSwept(Riv r, vec2 p, float rad) +{ + if (!r.on || r.life <= 0.001) return 0.0; + if (p.y > r.topY || p.y < r.bottom - rad) return 0.0; + bool inHead = p.y < r.bottom + r.headH; + float dW = (r.topY - (inHead ? r.bottom + 0.5 * r.headH : p.y)) / r.width; + float ramp, wobD; + float wob = rivWob(r, dW, ramp, wobD); + float cx = r.left + (0.5 + wob) * r.width; + float halfW = 0.5 * streak_sweep_width * r.width; + return (1.0 - smoothstep(halfW, halfW + rad, abs(p.x - cx))) * r.life; +} + +// candidate on the glass that wins the pixel (the highest dome) +struct Hit +{ + float score; + float cov; // coverage of the dome (normal map alpha) + float colA; // coverage of the drawn drop (sharper) + vec3 n; // dome normal, tangent space of the glass + vec2 offUV; // pixel - centre (glass UV), for the lens + float radUV; // radius (glass UV) + float isDrop; // 1 = drop / droplet (lens), 0 = rivulet (Snell) + float vis; // life / sweep visibility + vec2 auv; // grey atlas lookup of the winner (drops, rivulets) + vec2 agx, agy; + float atlas; // 1 = shade from the grey atlas, 0 = analytic (micro droplets: shade in colA's place) + float shade; // analytic shade (micro droplets) +}; + +void consider(inout Hit h, float score, float cov, float colA, vec3 n, vec2 offUV, float radUV, float isDrop, + float vis, vec2 auv, vec2 agx, vec2 agy, float atlas, float shade) +{ + if (score > h.score) + { + h.score = score; h.cov = cov; h.colA = colA; h.n = n; + h.offUV = offUV; h.radUV = radUV; h.isDrop = isDrop; + h.vis = vis; h.auv = auv; h.agx = agx; h.agy = agy; h.atlas = atlas; h.shade = shade; + } +} + +// the rivulet R of the layer set (wsSetLayer) at the pixel, at SUVr in the coordinates of the layer; Rd1 / Rd2: their change +// per screen pixel +void drawRivulet(inout Hit hit, Riv r, vec2 sUVr, vec2 rd1, vec2 rd2) +{ + if (!(r.on && r.life > 0.001)) + return; + const float sMargin = 0.8; + float sLen = r.topY - r.bottom; + float sx = (sUVr.x - r.left) / r.width; + float sy = sUVr.y - r.bottom; + if (sx >= -sMargin && sx <= 1.0 + sMargin && sy >= 0.0 && sy <= sLen) + { + bool inHead = sy < r.headH; + float dW = (r.topY - (inHead ? r.bottom + 0.5 * r.headH : sUVr.y)) / r.width; + float ramp, wobD; + float wob = rivWob(r, dW, ramp, wobD); + if (inHead) wobD = 0.0; + float sxw = sx - wob; + if (sxw >= 0.0 && sxw <= 1.0) + { + float sSide; + vec2 sWipeUV = f_coord; + if (inHead) + { + sWipeUV = wsFromLayer(vec2(r.left + 0.5 * r.width, r.bottom + 0.5 * r.headH)); + if (STREAK_FLIP_Y != 0) sWipeUV.y = 1.0 - sWipeUV.y; + } + if (GetMixFactor(sWipeUV, sSide) >= mix(0.5, 1.0, r.wipe)) + { + float sNative = 3.125 * r.width * streak_uv_aspect * STREAK_TAIL_SCALE; + float sxs = mix(sxw, 1.0 - sxw, r.flip); + float su = 0.5 + (r.col + sxs) * 0.125; + vec2 sgx = vec2(0.125 / r.width * rd1.x, 0.0); + vec2 sgy = vec2(0.125 / r.width * rd2.x, 0.0); + vec4 sNm; + vec2 sAuv; + float vtSign = 1.0; + if (inHead) + { + float kv = STREAK_HEAD_FRAC / r.headH; + sgx.y = kv * rd1.y; sgy.y = kv * rd2.y; + sAuv = vec2(su, sy / r.headH * STREAK_HEAD_FRAC); + sNm = textureGrad(normalmap, sAuv, sgx, sgy); + } + else + { + float kv = (1.0 - STREAK_HEAD_FRAC) / sNative; + sgx.y = kv * rd1.y; sgy.y = kv * rd2.y; + // a) trail pattern fixed to the glass, tiled by mirroring (beads stay where they were left) + float dd = max(r.topY - sUVr.y, 0.0) / sNative; + float vt = abs(mod(dd, 2.0) - 1.0); + vtSign = (mod(dd, 2.0) < 1.0) ? 1.0 : -1.0; + // b) right above the head: the sprite part that touches the head + float above = (sy - r.headH) / r.width; // head widths above the head + float link = 1.0 - smoothstep(0.5 * streak_link, streak_link, above); + vec4 nGlass = vec4(0.0); + vec4 nLink = vec4(0.0); + vec2 uvGlass = vec2(su, STREAK_HEAD_FRAC + vt * (1.0 - STREAK_HEAD_FRAC)); + vec2 uvLink = vec2(su, STREAK_HEAD_FRAC + min((sy - r.headH) / sNative, 1.0) * (1.0 - STREAK_HEAD_FRAC)); + if (link < 0.999) + nGlass = textureGrad(normalmap, uvGlass, sgx, sgy); + if (link > 0.001) + nLink = textureGrad(normalmap, uvLink, sgx, sgy); + sAuv = (link > 0.5) ? uvLink : uvGlass; + sNm = mix(nGlass, nLink, link); + vtSign = mix(vtSign, 1.0, link); + } + + float sFade = inHead ? 1.0 : smoothstep(0.0, 1.5, dW); // the start of the trail melts into the glass + float sVis = r.life * sFade; + float sCov = smoothstep(0.1, 0.6, sNm.a) * sVis; + if (sCov > 0.001) + { + vec2 nxy = sNm.rg * 2.0 - 1.0; + if (r.flip > 0.5) nxy.x = -nxy.x; + if (STREAK_FLIP_Y != 0) nxy.y = -nxy.y; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec2 slope = -nxy / max(nz, 0.08); + if (!inHead) + slope.y = slope.y * vtSign / STREAK_TAIL_SCALE - slope.x * wobD + + streak_flow * ramp * sin(dW * 4.8 - time * 4.0); + // the slope of the layer to the one of the glass + if (STREAK_FLIP_Y != 0) slope.y = -slope.y; + slope = wsFromLayerDir(slope); + if (STREAK_FLIP_Y != 0) slope.y = -slope.y; + vec3 n = normalize(vec3(-slope, 1.0)); + float h = sNm.b * r.width * 0.5; + consider(hit, sCov * (h + 1e-5), sCov, 0.0, n, vec2(0.0), r.width * 0.5, 0.0, + sVis, sAuv, sgx, sgy, 1.0, 0.0); + } + } + } + } +} + +// how much of a drop centred at Cg (glass UV, v up) with radius Rad the rivulets of both layers have swept up (0..1 kept) +float wsKept(vec2 cg, float rad, Riv rivP, vec2 sCell, float sCW, float sCH, float gridSize) +{ + wsSetLayer(0); + vec2 rc = floor(cg / vec2(sCW, sCH)); + Riv rv = rivP; + if (rc != sCell) rv = getRiv(rc, sCW, sCH, gridSize); + float kept = 1.0 - streak_sweep * rivSwept(rv, cg, rad); + if (wsWindShare > 0.001) + { + wsSetLayer(1); + vec2 cw = wsToLayer(cg); + vec2 wc = vec2(sCW * wind_cell_scale, sCH * wind_run_scale); + Riv rw = getRiv(floor(cw / wc), wc.x, wc.y, gridSize); + kept *= 1.0 - streak_sweep * rivSwept(rw, cw, rad); + wsSetLayer(0); + } + 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) +{ + 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; + 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; } void main() { - vec4 tex_color = texture(diffuse, f_coord); - vec4 mask = texture(wipermask, f_coord); + // ---- screen-space derivatives (before any non-uniform flow) ---- + float uvPerPx = max(length(dFdx(f_coord)), length(dFdy(f_coord))); + vec2 sxy = f_pos.xy / max(-f_pos.z, 1e-3); + float pxPerSlope = 1.0 / max(max(length(dFdx(sxy)), length(dFdy(sxy))), 1e-6); + vec3 Ngl = normalize(f_normal); + vec3 wsView = normalize(f_pos.xyz); // the view through the glass and its change per pixel (for the bent view) + vec3 wsDvx = dFdx(wsView); + vec3 wsDvy = dFdy(wsView); + 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; + // glass UV offset -> screen pixels (inverse of the UV Jacobian), for the drop lens + mat2 Juv = mat2(duv1, duv2); + float detJ = determinant(Juv); + mat2 Jinv = (abs(detJ) > 1e-20) ? inverse(Juv) : mat2(0.0); - // the coordinates of the glass: metres along the axes of the model, so the water stays where it lies on the glass whatever the - // vehicle and the camera do. the axis of the model nearest to the vertical is up, the glass is projected along the - // horizontal one it faces most (along the vertical one if it lies flat) - mat3 linear = mat3(modelview); - mat3 rot = mat3(normalize(linear[0]), normalize(linear[1]), normalize(linear[2])); - mat3 unrot = transpose(rot); - vec3 local = unrot * (f_pos.xyz - modelview[3].xyz); - vec3 viewnormal = normalize(f_normal); - // the water is on the side away from the camera, the outside of the cab - vec3 outward = (dot(viewnormal, f_pos.xyz) < 0.0) ? -viewnormal : viewnormal; - vec3 normal = unrot * outward; - vec3 up = unrot * (vec3(0.0, 1.0, 0.0) * mat3(inv_view)); - vec3 aup = abs(up); - int iu = (aup.x > aup.y) ? ((aup.x > aup.z) ? 0 : 2) : ((aup.y > aup.z) ? 1 : 2); - int ia = (iu + 1) % 3; - int ib = (iu + 2) % 3; - vec3 axis_up = vec3(0.0); - axis_up[iu] = (up[iu] < 0.0) ? -1.0 : 1.0; - vec3 axis_a = vec3(0.0); - axis_a[ia] = 1.0; - vec3 axis_b = vec3(0.0); - axis_b[ib] = 1.0; - vec3 an = abs(normal); - vec3 axis_u, axis_v, axis_n; - if (an[iu] > max(an[ia], an[ib])) - { - axis_n = axis_up; - axis_u = axis_a; - axis_v = axis_b; - } - else if (an[ia] >= an[ib]) - { - axis_n = axis_a; - axis_u = axis_b; - axis_v = axis_up; - } - else - { - axis_n = axis_b; - axis_u = axis_a; - axis_v = axis_up; - } - vec2 glass = vec2(dot(local, axis_u), dot(local, axis_v)); - float facing = dot(normal, axis_n); - facing = ((facing < 0.0) ? -1.0 : 1.0) * max(abs(facing), 0.35); - // a step of the coordinates is a step along the glass - rw_tu = rot * (axis_u - axis_n * (dot(normal, axis_u) / facing)); - rw_tv = rot * (axis_v - axis_n * (dot(normal, axis_v) / facing)); + vec4 tex_color = texture(diffuse, f_coord); + float glassA = tex_color.a * alpha_mult; - // the derivatives, before anything is discarded: the size of a pixel on the glass and in the view, and how the coordinates of - // the mask follow the ones of the glass - vec3 view = normalize(f_pos.xyz); - vec3 dpdx = dFdx(f_pos.xyz); - vec3 dpdy = dFdy(f_pos.xyz); - rw_pixel = max(max(length(dpdx), length(dpdy)), 1e-6); - float pixelangle = max(max(length(dFdx(view)), length(dFdy(view))), 1e-6); - vec2 gdx = dFdx(glass); - vec2 gdy = dFdy(glass); - mat2 steps = mat2(gdx, gdy); - float det = determinant(steps); - mat2 maskstep = (abs(det) > 1e-14) ? mat2(dFdx(f_coord), dFdy(f_coord)) * inverse(steps) : mat2(0.0); + float gridSize = ceil(param[2].x); + vec2 rainCoord = f_coord; - // the water the simulation keeps, where the material is a glass of the cab of the train (the param water_slot, given by the - // renderer: 1 + the glass): the view space step along the glass for a step of the uv, and how fresh the wetted path the water - // went along is, with how that changes along the glass (before anything is discarded) - int slot = int(param[2].z + 0.5) - 1; - mat2 uvsteps = mat2(dFdx(f_coord), dFdy(f_coord)); - float uvdet = determinant(uvsteps); - bool simulated = (slot >= 0) && (slot < WATER_SLOTS) && (abs(uvdet) > 1e-24); - simulated = simulated && (water_header[clamp(slot, 0, WATER_SLOTS - 1)].x > 0.5); - mat2x3 puv = (abs(uvdet) > 1e-24) ? mat2x3(dpdx, dpdy) * inverse(uvsteps) : mat2x3(0.0); - vec3 trailfield = simulated ? rw_trail(uint(slot), f_coord, water_header[clamp(slot, 0, WATER_SLOTS - 1)].y) : vec3(0.0); - float trail = trailfield.x; - // its gradient along the glass, view space: the uv gradient taken through the steps of the uv along the glass - vec3 trailslope = vec3(0.0); - { - mat2 metric = transpose(puv) * puv; - if (abs(determinant(metric)) > 1e-30) - trailslope = puv * (inverse(metric) * trailfield.yz); - } + float ambLum = clamp(dot(ambient, vec3(0.2126, 0.7152, 0.0722)), 0.0, 1.0); + float dynBright = pow(clamp(ambLum * 6.0, 0.0, 1.0), 0.5); + // GL 4.6: the ambient light isn't a level of 0..1 any more (it is in the units of the scene, the light of the sky added), so + // at night the drops came out as bright as by day. how bright the picture around really is says it: the coarsest level of + // the image of the last frame, the average of the screen + float sceneLum = (ssr_params.x >= 1.0) ? wsLum(textureLod(ssr_history, vec2(0.5), ssr_params2.x).rgb) : 1.0; + float wsNight = smoothstep(0.0, drop_dark_lum, sceneLum); // 0 dark night .. 1 daylight + dynBright *= wsNight; - if (tex_color.a < 0.01) - discard; + // wiper state of this pixel (blur, micro droplets) + float hazeSide; + float wipeVis = GetMixFactor(f_coord, hazeSide); - vec4 layer = vec4(0.0); - float heavy = clamp(rain_params.x, 0.0, 1.0); - bool snow = rain_params.z > 0.5; - if ((heavy > 0.0) || simulated) - { - rw_scale = max(param[2].y, 0.05); + 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; + hit.vis = 0.0; hit.auv = vec2(0.0); hit.agx = vec2(0.0); hit.agy = vec2(0.0); hit.atlas = 0.0; hit.shade = 0.0; - // what meets the glass. the air against the vehicle (rain_wind) drags the drops along the glass with what of it goes - // along the glass and with the share of what meets it head on which turns up it: the more the glass leans back the more - // of the air goes along it, and the less of their weight pulls the drops down it - vec3 air = unrot * (rain_wind.xyz * mat3(inv_view)); - float fall = snow ? RW_SNOW_FALL : RW_RAIN_FALL; - float hits = max(-dot(air - up * fall, normal), 0.0); - rw_rate = heavy * clamp(0.7 + hits / fall, 0.7, 6.0); - rw_period = clamp((snow ? 10.0 : 5.0) / rw_rate, 0.4, 300.0); - rw_grow = 2.0 * rw_period; - vec3 gravity = -up - normal * dot(-up, normal); - vec3 rise = up - normal * dot(up, normal); - rise = (length(rise) > 0.1) ? normalize(rise) : vec3(0.0); - vec3 flow = air - normal * dot(air, normal) + rise * (max(-dot(air, normal), 0.0) * RW_HEAD_ON); - vec3 push = gravity + flow * (length(flow) / (RW_DRAG_SPEED * RW_DRAG_SPEED)); - vec2 force = vec2(dot(push, axis_u), dot(push, axis_v)); - rw_push = length(force); - vec2 fallway = vec2(dot(gravity, axis_u), dot(gravity, axis_v)); - rw_down = (length(fallway) > 0.1) ? normalize(fallway) : vec2(0.0, -1.0); - vec2 flowway = vec2(dot(flow, axis_u), dot(flow, axis_v)); - rw_flow = (length(flowway) > 1.0) ? normalize(flowway) : vec2(0.0); + // ---- the air against the vehicle on the glass (uniform flow: the derivatives of the glass above) ---- + float flipS = (STREAK_FLIP_Y != 0) ? -1.0 : 1.0; // texture v -> glass v (up) + vec3 wsUp = vec3(0.0, 1.0, 0.0) * mat3(inv_view); // world up, view space + vec3 wsAir = rain_wind.xyz * mat3(inv_view); // the air against the vehicle, view space, m/s + vec3 wsN = (dot(Ngl, f_pos.xyz) < 0.0) ? -Ngl : Ngl; // the outside of the glass + vec3 wsGrav = -wsUp - wsN * dot(-wsUp, wsN); // the weight along the glass + vec3 wsRise = wsUp - wsN * dot(wsUp, wsN); + wsRise = (length(wsRise) > 0.1) ? normalize(wsRise) : vec3(0.0); + vec3 wsFlow = wsAir - wsN * dot(wsAir, wsN) + wsRise * (max(-dot(wsAir, wsN), 0.0) * WS_HEAD_ON); + float wsDrag = dot(wsFlow, wsFlow) / (WS_DRAG_SPEED * WS_DRAG_SPEED) * wind_drag_gain; // in units of the weight + vec3 wsFlowDir = (length(wsFlow) > 1e-3) ? normalize(wsFlow) : vec3(0.0); + vec3 wsPush = wsGrav + wsFlowDir * wsDrag; + // to the glass UV (v up) through the tangent frame of the texture + vec2 gravG = vec2(dot(wsGrav, Tgl), dot(wsGrav, Bgl) * flipS); + vec2 flowG = vec2(dot(wsFlowDir, Tgl), dot(wsFlowDir, Bgl) * flipS); + float wsSpeed = smoothstep(0.3, 1.2, wsDrag); // 0 standing still .. 1 at speed (haze, drops) + wsWindShare = smoothstep(0.5, 1.3, wsDrag); // how much the air drives the rivulets + if (wsWindShare > 0.0) + { + // the rivulets of the air run along the push of the air at twice the weight: the same way at any speed (they don't swing + // round as the train speeds up), up a front glass, back and down a side window + vec2 way = gravG + flowG * 2.0; + if (dot(way, way) > 1e-8) + { + way = normalize(way); + float turn = round(atan(way.x, -way.y) / WS_WIND_STEP) * WS_WIND_STEP; + wsWindCos = cos(turn); + wsWindSin = sin(turn); + } + else + wsWindShare = 0.0; + } + // the push of the air on the drops, texture UV (for stretching them) + vec2 wsPushT = vec2(dot(wsPush, Tgl), dot(wsPush, Bgl)); + wsPushT = (dot(wsPushT, wsPushT) > 1e-10) ? normalize(wsPushT) : vec2(0.0, -1.0); + // 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); - rw_wipe_s wipe = rw_wipe(mask); - rw_since = wipe.since; - // the blades went lately (any of them, also where none of them reaches) - float working = 0.0; - for (int i = 0; i < 4; ++i) - working = max(working, 1.0 - smoothstep(4.0, 30.0, time - wiper_timer_return[i])); - // how much of the water the place gathers it has - float gathered = 1.0 - exp(-rw_since / (6.0 * rw_period)); - // the film a blade leaves is drawn into fine streaks along its arcs, each a thin cylindrical lens which draws a light seen - // through it into a line across the streaks, towards the pivot of the blade: the way across the streaks on the screen - vec2 streakway = vec2(0.0); - if ((working > 0.0) && (false == snow) && (abs(det) > 1e-14)) - { - int blade = 0; - for (int i = 1; i < 4; ++i) - blade = (mask[i] > mask[blade]) ? i : blade; - if (mask[blade] >= 0.001) - { - // the mask grows along the arcs; a step of a centimetre, so the steps of its values don't matter - float mu = textureLod(wipermask, f_coord + maskstep * vec2(0.01, 0.0), 0.0)[blade]; - float mv = textureLod(wipermask, f_coord + maskstep * vec2(0.0, 0.01), 0.0)[blade]; - vec2 arc = vec2(mu, mv) - mask[blade]; - vec2 onscreen = inverse(steps) * vec2(-arc.y, arc.x); - if ((length(arc) > 1e-4) && (length(onscreen) > 1e-9)) - streakway = normalize(onscreen); - } - } - vec3 ripple = rw_noise2(glass / (0.006 * rw_scale), 5u); + // ---- rivulet cell of this pixel (also used to sweep the drops) ---- + wsSetLayer(0); + float sCW = streak_cell / gridSize; + float sCH = streak_run / gridSize; + vec2 sUVg = vec2(f_coord.x, (STREAK_FLIP_Y != 0) ? 1.0 - f_coord.y : f_coord.y); // glass UV, v up + vec2 sCell = floor(sUVg / vec2(sCW, sCH)); + Riv rivP = getRiv(sCell, sCW, sCH, gridSize); + bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0); - // the water a blade pushes: a bead in front of it while it moves, as wide as the water it gathered on its way, with a steep - // lumpy front (its edge shows dark, the view can't get out there). the drops the bead reaches flow into it - vec3 lumps = rw_noise2(glass / (0.009 * rw_scale), 7u); - float gatheredwater = snow ? 0.0 : min(gathered * 1.5, 1.0) * (0.35 + 0.65 * min(wipe.swept * 2.5, 1.0)); - float reach = 0.004 + 0.018 * gatheredwater + 0.008 * (ripple.x - 0.5); - float ridge = gatheredwater * smoothstep(0.0, 0.003, wipe.front) * (1.0 - smoothstep(reach - 0.004, reach, wipe.front)); - // the smooth shape from how it changes from pixel to pixel, the lumps on it as they are - float pooledbase = 0.004 * ridge; - float pooled = pooledbase * (0.75 + 0.5 * lumps.x); - vec3 pooledslope = rw_gradient(pooledbase, dpdx, dpdy, outward) * (0.75 + 0.5 * lumps.x) + rw_along(lumps.yz * (0.5 * pooledbase / (0.009 * rw_scale))); - if ((pooled > 0.0) && (false == simulated)) - { - rw_sheet(pooled, pooledslope, 0.03, smoothstep(0.0, 0.1, ridge)); - if (ridge > 0.05) - rw_cleared = time; - } + if (rain_params.x > 0.001) + { + // =================================================================== + // 1. drops from the atlas: this cell and its 8 neighbours + // =================================================================== + vec2 cell = floor(rainCoord * gridSize); + for (int oy = -1; oy <= 1; oy++) + for (int ox = -1; ox <= 1; ox++) + { + vec2 nc = cell + vec2(ox, oy); + uvec2 key = cellKey(nc); + // life cycle of this cell: a new drop every lifeLen seconds + uint s0 = Hash(uvec3(key, 23u)); + float lifeLen = mix(drop_life_min, drop_life_max, RandF(s0)); + float tt = time / lifeLen + RandF(s0); + float epoch = floor(tt); + float ph = tt - epoch; + uint ep = uint(mod(epoch, 65521.0)); + // activation first (cheap), the wiper texture only for live drops + uint s1 = Hash(uvec3(key, ep * 4u + 1u)); + if (RandF(s1) > rain_params.x * drop_density) + continue; + float side; + float mixF = GetMixFactor((nc + 0.5) / gridSize, side); + uint s2 = Hash(uvec3(key, ep * 4u + 2u + uint(side) * 2u)); + if (mixF < RandF(s2)) + continue; - float snowcover = 0.0; - float wet = 0.0; - if (simulated) - { - // the directions along the glass, view space - vec3 upview = vec3(0.0, 1.0, 0.0) * mat3(inv_view); - vec3 downview = -(upview - outward * dot(upview, outward)); - downview = (length(downview) > 0.05) ? normalize(downview) : normalize(cross(outward, normalize(rw_tu))); - vec3 sideview = cross(outward, downview); - rw_simulated(uint(slot), f_coord, puv, downview, sideview, snowcover, wet); - // the paths the water went along lately: a rivulet, a band of water rounded across (a cylinder lens: it holds a picture of - // the place around it turned over across the band, its edges dark as the edges of drops), thicker the fresher. the - // smoothed freshness falls off from the middle of a path to its edges - if (trail > 0.08) - { - float p = clamp((trail - 0.08) / 0.5, 0.0, 1.0); - float thickness = 0.0005 * (1.0 - (1.0 - p) * (1.0 - p)); - vec3 rise = trailslope * (0.0005 * 2.0 * (1.0 - p) / 0.5); - float steep = length(rise); - if (steep > 0.7) - rise *= 0.7 / steep; - bool top = thickness > rw_height; - rw_sheet(thickness, rise, 0.004, smoothstep(0.0, 0.15, p) * 0.95); - // from the middle of the band to the fragment - float across = length(trailslope) / 0.5; - if (top && (across > 1.0)) - rw_offset = -trailslope * ((1.0 - p) / (across * length(trailslope))); - } - } - else if (false == snow) - { - // the drops which grew big enough slide off, with gravity and the air: a set of tracks for each of the directions of the - // push nearest to the one now, each laid along its own way, so none of them moves when the push turns - float sliding = smoothstep(0.25, 0.6, rw_push); - if (sliding > 0.0) - { - float bin = atan(force.y, force.x) / (RW_PI / 6.0); - float lower = floor(bin); - for (int k = 0; k < 2; ++k) - { - float share = ((k == 0) ? 1.0 - (bin - lower) : bin - lower) * sliding; - if (share < 0.02) - continue; - float angle = (lower + float(k)) * (RW_PI / 6.0); - vec2 down = vec2(cos(angle), sin(angle)); - vec2 side = vec2(-down.y, down.x); - rw_sliders(vec2(dot(glass, side), -dot(glass, down)), side, down, uint(int(lower) + k + 64) * 2u + 16u, share); - } - } + vec2 center = (nc + vec2(RandF(s2), RandF(s2))) / gridSize; + float size = mix(drop_size_min, drop_size_max, pow(RandF(s2), drop_size_bias)) / gridSize; + float sag = 1.0 + drop_sag * RandF(s2); + float flipX = (RandF(s2) < 0.5) ? 1.0 : 0.0; + float choice = RandF(s2); + // at speed the air stretches the drop along its push (1 standing still: the drop as it always was) + float stretch = 1.0 + drop_wind_stretch * wsSpeed * RandF(s2); + mat2 shapeM = mat2(1.0, 0.0, 0.0, 1.0 / sag) + * (mat2(1.0) + (1.0 / stretch - 1.0) * outerProduct(wsPushT, wsPushT)); - // the drops as they land, each time somewhere else in its cell, as often as the rain hits the glass: the drops of the - // rain spread on the glass, thrown with a fine splash which runs back into them - // each drop anywhere in its cell, the cell as large as a drop with its splash reaches - float cell = 0.007 * rw_scale; - vec2 laid = rw_turn(glass, 0.61) + vec2(0.31, 0.17); - ivec2 home = ivec2(floor(laid / cell)); - float density = mix(0.08, 0.3, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 1u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 1u, 1u); - float span = rw_period * mix(0.7, 1.3, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.5, 0.9, b.y); - if ((age > life) || (age > rw_since) || (time - age < rw_cleared)) - continue; - vec4 p = rw_random(c, 2u, uint(cycle)); - vec2 offset = rw_turn(laid - (vec2(c) + p.xy) * cell, -0.61); - float visible = mix(0.0011, 0.0019, b.z) * rw_scale; - // a raindrop hits the glass far above the speed at which it splashes (Weber number in the hundreds and thousands): - // it spreads, throws a spray of droplets which stay on the glass around it, and draws back - float splash = exp(-age / 0.06); - float fade = 1.0 - smoothstep(life - min(0.4, 0.3 * life), life, age); - if (visible * 0.3 > 0.5 * rw_pixel) - { - int spray = 3 + int(p.z * 4.0); - for (int s = 0; s < spray; ++s) - { - vec4 e = rw_random(c, 3u, uint(cycle) * 8u + uint(s)); - vec2 way = normalize(vec2(cos(e.x * 6.2831853), sin(e.x * 6.2831853)) + rw_flow * 0.9); - rw_blob(offset - way * (visible * (1.4 + 1.6 * e.y)), visible * mix(0.18, 0.35, e.z), fade * (0.55 + 0.45 * splash)); - } - } - rw_drop(offset, visible * (1.0 + 0.3 * splash), fade, p.wzyx); - } - } - // the drops the landing ones gathered into, growing until they are big enough to slide (the air blows them off sooner) - cell = 0.011 * rw_scale; - laid = rw_turn(glass, 1.07) + vec2(0.53, 0.29); - home = ivec2(floor(laid / cell)); - density = mix(0.55, 1.0, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 4u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 4u, 1u); - float span = rw_period * mix(2.5, 4.0, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.75, 0.98, b.y) / (1.0 + 2.0 * max(rw_push - 1.0, 0.0)); - if ((age > life) || (age > rw_since) || (time - age < rw_cleared)) - continue; - vec4 p = rw_random(c, 5u, uint(cycle)); - // the big drops are much alike: they grow as they gather the small ones (the radius in step with the time) up to the - // size at which they slide off (on a vertical glass a footprint of about 9 mm, larger on a glass leaning back, smaller - // in a strong air flow), and go - float slides = min(0.0045 / sqrt(max(rw_push, 0.3)), 0.005); - float visible = slides * mix(0.6, 1.0, b.z) * rw_scale * mix(0.35, 1.0, clamp(age / (0.6 * life), 0.0, 1.0)); - rw_drop(rw_turn(laid - (vec2(c) + p.xy) * cell, -1.07), visible, 1.0 - smoothstep(life - min(0.5, 0.3 * life), life, age), p.zwxy); - } - } + float appearF = drop_appear / lifeLen; + float fadeF = drop_fade / lifeLen; + float vis = smoothstep(0.0, appearF, ph) * (1.0 - smoothstep(1.0 - fadeF, 1.0, ph)); + float sq = size * mix(0.8, 1.0, smoothstep(0.0, 2.0 * appearF, ph)); // spreads out as it lands - // the water the blades push out of their sweep: a broken row of drops flowed together along its edge, just outside it - float leave = working * min(heavy * 1.5, 1.0); - if ((leave > 0.0) && rw_border(f_coord, 0.009 * rw_scale, maskstep)) - { - cell = 0.0065 * rw_scale; - laid = rw_turn(glass, 0.29) + vec2(0.11, 0.43); - home = ivec2(floor(laid / cell)); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 20u, 0u); - if (a.x > 0.85) - continue; - // from the fragment to the middle of the drop, along the glass - vec2 centre = rw_turn((vec2(c) + a.yz) * cell - laid, -0.29); - float rim = rw_rim(f_coord + maskstep * centre, 0.004 * rw_scale, maskstep) * leave; - if (rim <= 0.05) - continue; - rw_drop(-centre, mix(0.0016, 0.003, a.w) * rw_scale * mix(0.6, 1.0, rim), smoothstep(0.05, 0.35, rim), rw_random(c, 21u, 0u)); - } - } - } + vec2 diff = rainCoord - center; + vec2 dl = shapeM * diff; + if (max(abs(dl.x), abs(dl.y)) >= sq * 0.5) + continue; - // the streams running down from the water the blades leave at the ends of their sweep: a stream in some of the columns - // along the way down, where up the glass there is such water, as far down as the water had time to run since the blade - // went over the place - if ((working > 0.0) && (length(fallway) > 0.3)) - { - vec2 side = vec2(-rw_down.y, rw_down.x); - float width = 0.035 * rw_scale; - float across = dot(glass, side); - float along = -dot(glass, rw_down); - int column = int(floor(across / width)); - vec4 a = rw_random(ivec2(column, 0), 30u, 0u); - if (a.x < 0.6 * heavy * working) - { - float lateral = across - rw_path(column, along, width, 31u); - float half_width = mix(0.0006, 0.0012, a.z) * rw_scale * (0.6 + 0.8 * rw_noise(along / (0.006 * rw_scale), 32u)); - if (abs(lateral) < 2.0 * half_width + rw_pixel) - { - // up the glass, the first place where the reach of the blades begins or ends - const float reach[6] = float[](0.01, 0.025, 0.05, 0.1, 0.18, 0.3); - bool here = rw_reached(f_coord); - float source = -1.0; - for (int s = 0; s < 6; ++s) - { - if (rw_reached(f_coord + maskstep * (-rw_down * reach[s])) != here) - { - source = reach[s]; - break; - } - } - if ((source > 0.0) && (source < max(rw_since - 0.1, 0.0) * 0.2)) - { - float beads = rw_noise(along / (0.004 * rw_scale), 33u); - float flowing = working * (1.0 - 0.5 * smoothstep(0.15, 0.3, source)); - rw_blob(side * lateral, half_width, flowing * mix(0.6, 1.2, beads)); - } - } - } - } - } - else - { - // the flakes stick where they land and melt into drops: the glass is warmed by the cab, faster in the air above zero - float warm = rain_params.w; - float cell = 0.016 * rw_scale; - vec2 laid = rw_turn(glass, 0.83) + vec2(0.07, 0.61); - ivec2 home = ivec2(floor(laid / cell)); - float density = mix(0.5, 0.9, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 11u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 11u, 1u); - float span = rw_period * mix(0.7, 1.3, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.6, 0.95, b.y); - if ((age > life) || (age > rw_since)) - continue; - vec4 p = rw_random(c, 12u, uint(cycle)); - vec2 offset = rw_turn(laid - (vec2(c) + p.xy) * cell, -0.83); - float diameter = mix(RW_SNOW_DIAMETER.x, RW_SNOW_DIAMETER.y, b.z) * rw_scale; - float melt = ((warm > 0.5) ? mix(3.0, 10.0, b.w) / (1.0 + 0.25 * warm) : mix(15.0, 45.0, b.w)); - if (age < melt) - { - float m = age / melt; - float dist = length(offset.x * rw_tu + offset.y * rw_tv); - float radius = 0.5 * diameter; - if (dist < radius + rw_pixel) - { - float angle = atan(offset.y, offset.x); - float lobes = 0.55 + 0.45 * (0.6 * rw_noise(angle * 1.9 + p.z * 40.0, 13u) + 0.4 * abs(cos(3.0 * angle + p.w * 6.2831853))); - float rim = radius * lobes * (1.0 - 0.45 * m); - float body = smoothstep(rim + rw_pixel, 0.55 * rim - rw_pixel, dist); - float lace = rw_noise2(glass / (0.0007 * rw_scale) + p.zw * 100.0, 14u).x; - float flake = body * mix(0.55, 1.0, lace) * (1.0 - 0.7 * m * m); - snowcover = 1.0 - (1.0 - snowcover) * (1.0 - flake); - wet = max(wet, m * body); - } - } - else - { - // the water of the flake - rw_drop(offset, 0.0018 * pow(diameter / 0.008, 0.667) * rw_scale, 1.0 - smoothstep(life - min(0.5, 0.3 * life), life, age), p.wzyx); - } - } - } - // the snow the blades push in front of them and leave at the ends of their sweep - float pile = max(wipe.ahead * min(gathered * 2.0, 1.0) * (0.4 + 0.6 * min(wipe.swept * 2.5, 1.0)), rw_rim(f_coord, 0.006 * rw_scale, maskstep) * working * heavy); - float packed = rw_noise2(glass / (0.0015 * rw_scale), 15u).x; - snowcover = max(snowcover, smoothstep(0.15, 0.5, pile * 1.2 + 0.4 * (ripple.x - 0.5)) * mix(0.7, 1.0, packed)); - } - // untreated glass, weathered and a little dirty: flat drops (a rain repellent coating would give beads above 90 degrees) - rw_settle(radians(mix(30.0, 48.0, rw_noise2(glass / (0.005 * rw_scale), 16u).x))); + if (sweepOn) + { + vec2 cg = vec2(center.x, (STREAK_FLIP_Y != 0) ? 1.0 - center.y : center.y); + vis *= wsKept(cg, 0.35 * sq, rivP, sCell, sCW, sCH, gridSize); + } + if (vis <= 0.001) + continue; - // the lamps (of the cab, of the scenery) and the headlights light the water up, from both sides of the glass (worked out - // here, where the fragments of a quad go together) - vec3 lamps = vec3(0.0); - vec3 lampgloss = vec3(0.0); - add_local_lights(outward, lamps, lampgloss); - add_local_lights(-outward, lamps, lampgloss); + vec2 luv = dl / sq + 0.5; + if (flipX > 0.5) luv.x = 1.0 - luv.x; + float atlasTexels = float(textureSize(normalmap, 0).x); + float quadPx = sq / max(uvPerPx, 1e-6); + float nlod = clamp(log2(max(0.25 * atlasTexels / max(quadPx, 1.0), 1.0)), 0.0, 6.0); + vec4 nm = textureLod(normalmap, dropAtlasUV(choice, luv), nlod); + float cov = smoothstep(0.1, 0.6, nm.a) * vis; + if (cov <= 0.001) + continue; + vec2 nxy = nm.rg * 2.0 - 1.0; + if (flipX > 0.5) nxy.x = -nxy.x; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec2 slope = transpose(shapeM) * (-nxy / max(nz, 0.08)); + vec3 n = normalize(vec3(-slope, 1.0)); + // gradients of the tile UV (for the one atlas read after the loop) + vec2 gx = (shapeM * duv1) / sq * vec2(0.25, 0.5); + vec2 gy = (shapeM * duv2) / sq * vec2(0.25, 0.5); + consider(hit, cov * (nm.b * sq * sag + 1e-5), cov, 0.0, n, diff, 0.5 * sq, 1.0, + vis, dropAtlasUV(choice, luv), gx, gy, 1.0, 0.0); + } - // the film just behind a blade, breaking up - float film = snow ? 0.0 : heavy * exp(-rw_since / 0.8) * smoothstep(0.02, 0.08, rw_since); - if (film > 0.01) - { - vec3 fine = rw_noise2(glass / (0.0021 * rw_scale), 6u); - vec2 tilt = fine.yz * (0.004 * film); - rw_sheet(0.00005 * film, rw_along(tilt), 0.3, 0.8 * film); - } + // =================================================================== + // 2. micro droplets: procedural, one per micro cell, fully inside it + // =================================================================== + if (micro_density > 0.0) + { + float mg = gridSize * micro_scale; + vec2 mc = floor(rainCoord * mg); + uvec2 mk = cellKey(mc); + uint m0 = Hash(uvec3(mk, 51u)); + float mLife = micro_life * mix(0.6, 1.6, RandF(m0)); + float mtt = time / mLife + RandF(m0); + float mph = fract(mtt); + uint mep = uint(mod(floor(mtt), 65521.0)); + uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); + if (RandF(m1) < rain_params.x * micro_density) + { + uint m2 = Hash(uvec3(mk, mep * 4u + 2u + uint(hazeSide) * 2u)); + if (wipeVis >= RandF(m2)) + { + float r = mix(micro_size_min, micro_size_max, pow(RandF(m2), 1.5)); + vec2 c = mc + vec2(r) + vec2(RandF(m2), RandF(m2)) * max(1.0 - 2.0 * r, 0.0); + float ell = mix(0.85, 1.15, RandF(m2)); + vec2 p = (rainCoord * mg - c) / r; + p.x *= ell; + float d2 = dot(p, p); + if (d2 < 1.0) + { + float vis = smoothstep(0.0, 0.01, mph) * (1.0 - smoothstep(0.97, 1.0, mph)); + if (sweepOn) + { + vec2 cu = c / mg; + vec2 cg = vec2(cu.x, (STREAK_FLIP_Y != 0) ? 1.0 - cu.y : cu.y); + vis *= wsKept(cg, r / mg, rivP, sCell, sCW, sCH, gridSize); + } + float d = sqrt(d2); + float cov = smoothstep(1.0, 0.8, d) * vis; + if (cov > 0.001) + { + vec2 nxy = p * micro_bulge; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec3 n = normalize(vec3(nxy, nz)); + float h = sqrt(1.0 - d2) * micro_bulge * (r / mg); + float rim = smoothstep(drop_rim_start, drop_rim_end, 1.0 - n.z); + float lt = dot(n, DROP_LIGHT) * drop_light_side * 0.5 + (1.0 - drop_light_side * 0.5); + consider(hit, cov * (h + 1e-6), cov, smoothstep(1.0, 0.9, d) * vis, n, + rainCoord - c / mg, r / mg, 1.0, + vis, vec2(0.0), vec2(0.0), vec2(0.0), 0.0, clamp(rim * lt, 0.0, 1.0)); + } + } + } + } + } - // what the water shows: the view goes through the glass (a plate: only the way from the air into the water counts) and out - // through the surface of the water, bent as much as it is curved. it is the world turned upside down in a drop, and the - // edges of a drop, where the view can't get out (total internal reflection), show the inside of the cab - float background = 0.0; - bool image = ssr_params.x >= 1.0; - if (image) - { - ivec2 size = textureSize(scene_depth, 0); - float depth = texelFetch(scene_depth, clamp(ivec2(gl_FragCoord.xy), ivec2(0), size - 1), 0).r; - if (depth > 0.0) - background = (projection[3][2] / depth) / max(-view.z, 0.05); - } - vec3 inside = ambient * (AMBIENT_SCALE * 0.5); - vec4 water = vec4(0.0); - if (rw_cover > 0.0) - { - vec3 surface = normalize(outward - rw_slope); - vec3 inwater = refract(view, -outward, 1.0 / RW_IOR); - vec3 through = refract(inwater, -surface, RW_IOR); - // what the surface reflects back inside the water: the light which came in at the other side of the drop, from the sky, - // and the inside of the cab. where the view can't get out (the edge of a drop) that is all it shows: a bright edge - vec3 bounced = reflect(inwater, surface); - if (dot(bounced, outward) < 0.0) - bounced = reflect(bounced, outward); - vec3 inner = mix(inside, rw_surroundings(normalize(bounced), 5.0), 0.3); - vec3 color = inner; - if (dot(through, through) > 0.5) - { - float fresnel = 0.02 + 0.98 * pow(1.0 - abs(dot(through, surface)), 5.0); - // the view through the water spreads over this much of the world across a pixel (radians) - float spread = (RW_IOR - 1.0) * rw_pixel / max(rw_curve, 1e-4); - // the picture the drop holds as a lens, and a share of the bending by the surface - vec3 lens = normalize(f_pos.xyz - (1.0 + RW_LENS) * rw_offset) + (through - view) * RW_LENS_BEND; - float lod = mix(log2(1.0 + RW_LENS) - 0.5, log2(max(spread / pixelangle, 1.0)), RW_LENS_BEND); - // a drop a few pixels across would hold a picture of single pixels, a grain: blurred more the smaller it looks - lod += clamp(2.5 - log2(max(rw_curve / rw_pixel, 1.0)), 0.0, 1.5); - float share; - vec3 seen = rw_behind(normalize(lens), lod, background, share); - // the sun through the drop, where the image doesn't hold it: as bright as the drop gathers its light. in heavier rain - // the sun is behind the clouds, its disc is not there to be focused - float sunshare = (1.0 - heavy) * (1.0 - heavy); - if ((lights_count > 0U) && (share < 1.0) && (sunshare > 0.01)) - { - vec3 sun = normalize(-lights[0].dir); - float width = max(spread, 0.03); - float off = acos(clamp(dot(through, sun), -1.0, 1.0)); - if (off < 4.0 * width) - { - float lit = 1.0 - clamp(calc_shadow(), 0.0, 1.0); - vec3 sunlight = lights[0].color * (SUN_DIFFUSE_SCALE * lights[0].intensity * cloud_shadow(mat3(inv_view) * f_pos.xyz)); - // the light of the sun over the spread of the view: a pixel shows pi * irradiance * the share of a steradian - seen += sunlight * (sunshare * lit * (1.0 - share) * exp(-0.5 * off * off / (width * width)) / (2.0 * width * width)); - } - } - color = mix(seen, inner, fresnel); - } - color += lamps * 0.6; - // without the image of the last frame the surroundings stand for what the water bends the view to; nearly flat water - // would show them in place of the scene behind it, so it is left mostly clear - float opaque = image ? 1.0 : mix(0.3, 1.0, smoothstep(0.02, 0.15, 1.0 - dot(through, view))); - water = vec4(color, rw_cover * opaque); - } - // the wet glass where the rain gathers is a little hazy: the tiniest drops spread the light - if (image && (false == snow)) - { - float mist = heavy * gathered * (simulated ? 0.18 : 0.3); - if (mist > 0.01) - { - float share; - vec3 hazy = rw_behind_edges(view, 3.5, background, share, false); - // the tiniest drops spread the light of the sky coming through the glass - hazy = mix(hazy, rw_surroundings(outward, 7.0), 0.1); - layer = vec4(hazy, mist * max(share, 0.5)); - } - } - layer = rw_over(water, layer); - // the lights seen through the streaks of the film the blades leave, drawn into lines towards their pivot - if (image && (length(streakway) > 0.5)) - { - vec4 previous = ssr_reprojection * ((background > 0.0) ? vec4(view * background, 1.0) : vec4(view, 0.0)); - if (previous.w > 1e-5) - { - vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; - vec2 texel = 1.0 / vec2(textureSize(ssr_history, 0)); - ivec2 size = textureSize(scene_depth, 0); - float near = projection[3][2]; - // a light: much brighter than the place around it (the bright sky is not) - vec3 around = textureLod(ssr_history, clamp(coords, vec2(0.0), vec2(1.0)), 6.0).rgb; - float threshold = max(1.0, 3.0 * max(around.r, max(around.g, around.b))); - vec3 glare = vec3(0.0); - float total = 0.0; - for (int k = -8; k <= 8; ++k) - { - if (k == 0) - continue; - float w = 1.0 - abs(float(k)) / 9.0; - total += w; - vec2 tap = coords + streakway * texel * (float(k) * 5.0); - if (any(lessThan(tap, vec2(0.0))) || any(greaterThan(tap, vec2(1.0)))) - continue; - // only what is outside: the lamps of the cab are not behind the glass - float depth = texelFetch(scene_depth, clamp(ivec2(tap * vec2(size)), ivec2(0), size - 1), 0).r; - if ((depth > 0.0) && (near / depth < -f_pos.z + 2.5)) - continue; - vec3 c = textureLod(ssr_history, tap, 1.5).rgb; - if (any(isnan(c)) || any(isinf(c))) - continue; - glare += max(c - vec3(threshold), vec3(0.0)) * w; - } - glare *= 0.6 * heavy * working / total; - if (any(greaterThan(glare, vec3(1e-4)))) - { - // the scene itself under the water carries the light added (it changes nothing seen) - vec3 scene = textureLod(ssr_history, clamp(coords, vec2(0.0), vec2(1.0)), 0.0).rgb; - layer = rw_over(layer, vec4(max(scene, vec3(0.0)), 0.2)); - layer.rgb += glare / layer.a; - } - } - } - if (snowcover > 0.0) - { - // the flakes are lit through from the outside, by the sky and the sun, and from the inside of the cab; melting they turn - // grey and clear - vec3 outside = rw_surroundings(outward, 6.0); - if (lights_count > 0U) - { - vec3 sun = normalize(-lights[0].dir); - outside += lights[0].color * (SUN_DIFFUSE_SCALE * lights[0].intensity * max(dot(outward, sun), 0.0) * (1.0 - clamp(calc_shadow(), 0.0, 1.0))); - } - vec3 flake = mix(vec3(0.92), vec3(0.62, 0.66, 0.7), wet); - vec3 color = flake * (outside * (0.35 * (1.0 - 0.5 * wet)) + ambient * (AMBIENT_SCALE * 0.7)); - layer = rw_over(vec4(color, snowcover * mix(0.97, 0.6, wet)), layer); - } - } - out_color = layer; + // =================================================================== + // 3. rivulets of this pixel's cells: the layer of gravity and, at speed, the one of the air + // =================================================================== + wsSetLayer(0); + drawRivulet(hit, rivP, sUVg, wsRd1, wsRd2); + if (wsWindShare > 0.001) + { + for (int wl = 1; wl <= wind_layers; ++wl) + { + vec2 wc = vec2(sCW * wind_cell_scale, sCH * ((wl == wind_layers) && (wl > 1) ? wind_long_run : wind_run_scale)); + wsSetLayer(wl); + // every further layer: its cells shifted aside, drops of its own + vec2 sUVw = wsToLayer(sUVg) + fract(vec2(0.5, 0.618) * float(wl - 1)) * wc; + Riv rivW = getRiv(floor(sUVw / wc), wc.x, wc.y, gridSize); + drawRivulet(hit, rivW, sUVw, wsToLayerDir(wsRd1), wsToLayerDir(wsRd2)); + } + wsSetLayer(0); + } + } - { // Overlay windshield texture with alpha - vec3 fragcolor = ambient; - vec3 fragnormal = normalize(f_normal); - float reflectivity = param[1].z; - float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5; - legacy_gloss(); + // ----------------------------------------------------------------------- + // Shading of the winning dome + // ----------------------------------------------------------------------- + float coverA = clamp(hit.cov, 0.0, 1.0); + vec3 dropLayer = vec3(0.0); + float alphaOut = 0.0; + vec3 dropGlint = vec3(0.0); + vec2 lensBend = vec2(0.0); + float lensK = 0.0; // drops: how much the lens shrinks the picture + float lensRadPx = 1.0e4; // drops: radius on screen, pixels + if (coverA > 0.001) + { + vec3 Nt = hit.n; + // look of the drop: grey atlas (bright rim, dark middle) for drops and rivulets, analytic for droplets + vec3 rgb; + float colA; + if (hit.atlas > 0.5) + { + vec4 at = textureGrad(raindropsatlas, hit.auv, hit.agx, hit.agy); + rgb = at.rgb; + colA = smoothstep(0.3, 0.9, at.a) * hit.vis; + } + else + { + rgb = vec3(hit.shade); + colA = hit.colA; + } + float a = colA * mix(drop_center_alpha, drop_rim_alpha, smoothstep(0.1, 0.3, length(rgb))); + dropLayer = rgb * dynBright * a; + alphaOut = clamp(a, 0.0, 1.0); - fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(fragcolor, tex_color.a * alpha_mult); + // refraction: Snell for rivulets (and as a fallback), lens picture for drops + vec3 I = normalize(f_pos.xyz); + vec3 No = (dot(Ngl, I) > 0.0) ? Ngl : -Ngl; + vec3 Nd = normalize(Tgl * Nt.x + Bgl * Nt.y + No * Nt.z); + vec3 R = refract(I, -Nd, drop_ior); + if (dot(R, R) < 1e-4) + R = refract(I, -Nd, 1.0 + 0.5 * (drop_ior - 1.0)); + vec2 dSlope = vec2(0.0); + if (dot(R, R) > 1e-4 && R.z < -0.05) + dSlope = R.xy / (-R.z) - I.xy / (-I.z); + vec2 snellBend = clamp(-(dSlope * pxPerSlope * drop_refract) / WS_REFR_MAXPX, vec2(-1.0), vec2(1.0)); + lensBend = snellBend; + if (hit.isDrop > 0.5 && drop_lens_mix > 0.0) + { + vec2 offPx = Jinv * hit.offUV; // pixel - drop centre, in screen pixels + float radPx = hit.radUV / max(uvPerPx, 1e-6); + float k = clamp(min(drop_lens, 0.95 * WS_REFR_MAXPX / max(radPx, 1.0) - 1.0), 0.0, drop_lens); + vec2 lb = clamp((1.0 + k) * offPx / WS_REFR_MAXPX, vec2(-1.0), vec2(1.0)); + lensBend = mix(snellBend, lb, drop_lens_mix); + lensK = k; + lensRadPx = radPx; + } - out_color.xyz = apply_fog(mix(out_color.xyz, color.xyz, color.a)); - out_color.a = mix(out_color.a, 1., color.a); - } - if (false == POSTFX_ENABLED) - { - out_color = tonemap(out_color); - } + vec3 Rd = (dot(R, R) > 1e-4) ? normalize(R) : I; + vec3 glint = vec3(0.0); + if (lights_count > 0U) + { + float cosS = max(dot(Rd, normalize(-lights[0].dir)), 0.0); + float lobe = pow(cosS, drop_glint_sharpness) * drop_glint_strength + + pow(cosS, 0.2 * drop_glint_sharpness) * drop_sheen; + // the shadow (shadow map + GL 4.6 contact shadow ray) only where the sun shows in the drop at all + if (lobe > 1e-4) + { + float shadowSun = 0.0; + if (shadow_tone < 1.0) + shadowSun = (1.0 - shadow_tone) * clamp(calc_shadow(), 0.0, 1.0); + // GL 4.6: the clouds hold the sun back where their shadow falls (as in apply_lights) + float cloudSun = cloud_shadow(mat3(inv_view) * f_pos.xyz); + glint += lights[0].color * lights[0].intensity * lobe * (1.0 - shadowSun) * cloudSun * wsNight; + } + } + // GL 4.6: headlights and lamps come from the light cluster of the fragment (lights_clustered), or are the + // first lights_count - 1 headlights otherwise. calc_headlights takes the screen-space change of f_pos + // (worked out at the top of main, in uniform flow). The drop scatters light from both sides of the glass, + // so the glass normal is turned towards the light. + // only the lights outside the glass and a few metres away light the drops up (signals, lamps of the station, the + // headlights of other trains): the lamps and the headlights of the own vehicle, a metre or two from the glass, would + // make every drop glow white + vec3 lamps = vec3(0.0); + if (lights_clustered != 0U) + { + cluster_range_s range = cluster_ranges[fragment_cluster()]; + for (uint i = 0U; i < range.count; i++) + { + light_s lt = lights[cluster_light_indices[range.offset + i]]; + vec3 toL = lt.pos - f_pos.xyz; + float away = smoothstep(0.0, 0.2, dot(toL, wsN) / max(length(toL), 1e-4)) + * smoothstep(drop_light_near, 2.0 * drop_light_near, length(toL)); + if (away <= 0.0) + continue; + vec3 nl = (dot(Ngl, toL) > 0.0) ? Ngl : -Ngl; + if (lt.type == LIGHT_HEADLIGHTS) + lamps += lt.color * calc_headlights(lt, nl, dp1, dp2).x * lt.intensity * drop_headlight_scatter * away; + else if (drop_lamp_scatter > 0.0) + lamps += lt.color * calc_local_light(lt, nl).x * lt.intensity * drop_lamp_scatter * away; + } + } + else + { + for (uint i = 1U; i < lights_count; i++) + { + light_s lt = lights[i]; + vec3 toL = lt.pos - f_pos.xyz; + float away = smoothstep(0.0, 0.2, dot(toL, wsN) / max(length(toL), 1e-4)) + * smoothstep(drop_light_near, 2.0 * drop_light_near, length(toL)); + if (away <= 0.0) + continue; + vec3 nl = (dot(Ngl, toL) > 0.0) ? Ngl : -Ngl; + lamps += lt.color * calc_headlights(lt, nl, dp1, dp2).x * lt.intensity * drop_headlight_scatter * away; + } + } + glint += min(lamps, vec3(drop_light_max)); + // reflection of the surroundings on the dome: straight from the environment map. (It used to go through a + // second apply_lights, which in GL 4.6 also runs the shadow map, the contact shadows and the whole light + // cluster again for every drop pixel; the sun and the lamps are done above already.) + if (drop_env > 0.0) + { + vec3 Nv = -Nd; // dome normal towards the viewer + float NoV = clamp(dot(Nv, -I), 0.0, 1.0); + glint += envmap_color_lod(Nv, 0.8) * EnvBRDFApprox(vec3(0.04), 0.1, NoV) * drop_env * wsNight; + } + dropGlint = glint; + if (!POSTFX_ENABLED) + dropGlint = min(dropGlint, vec3(1.0)); // this path is not tonemapped + } - if (MOTIONBLUR_ENABLED) - { - out_motion = vec4(0.0); - } + // ----------------------------------------------------------------------- + // 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 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) + if (image) + { + ivec2 size = textureSize(scene_depth, 0); + float depth = texelFetch(scene_depth, clamp(ivec2(gl_FragCoord.xy), ivec2(0), size - 1), 0).r; + if (depth > 0.0) + background = (projection[3][2] / depth) / max(-wsView.z, 0.05); + } + vec4 under = vec4(0.0); // the blurred view under the drops (not premultiplied) + vec4 bent = vec4(0.0); // the view bent by the drops, laid over everything (as the old postfx did) + + // the haze is blurred by the post-processing (postfx_taa.frag / postfx_motionblur.frag, rain_windscreen_haze.glsl): the + // picture of this frame can't be read here, and one of the last frame laid over it only shows a milky ghost of the scene + float blurAmt = clamp(hazeWeight * blur_amount, 0.0, 1.0); + + // the drops: the view bent (the picture shift worked out above), and the lights near them. with the motion vectors the + // post-processing bends the picture of this frame (postfx_taa.frag / postfx_motionblur.frag, rain_windscreen_haze.glsl): it has + // the depth of the cab and never pulls the dashboard or the roof into a drop. the image of the last frame is only the fallback + float refrA = smoothstep(0.05, 0.35, coverA) * glassClear * step(glassA, 0.5); + if ((false == MOTIONBLUR_ENABLED) && (refrA > 0.001)) + { + vec2 shiftPx = -lensBend * WS_REFR_MAXPX; // where the drop looks, screen pixels + vec3 dir = normalize(wsView + shiftPx.x * wsDvx + shiftPx.y * wsDvy); + // a drop shows a minified picture: read it from a coarser level (no grain); tiny drops a little blurrier still + float lod = clamp(log2(1.0 + lensK * drop_lens_mix) - 0.5, 0.0, 3.0) + + clamp(2.5 - log2(max(lensRadPx, 1.0)), 0.0, 1.5); + float share; + vec3 seen = wsBehind(dir, lod, background, share, true); + if (image && (WS_LIGHT_GAIN > 0.0)) + seen += wsLightGlow(wsView, background); + // without the image the surroundings stand in: only faintly, they aren't the scene behind + bent = vec4(seen, refrA * WS_REFR_MIX * (image ? 1.0 : 0.3)); + } + + // the drop shading over it + float shadeA = coverA * drop_shade_alpha; + float outA = alphaOut + shadeA * (1.0 - alphaOut); + vec4 drops = vec4(dropLayer, outA); + drops.rgb += dropGlint * coverA / max(outA, 0.05); // the blend multiplies by alpha once more + out_color = wsOver(drops, under); + + { // windshield texture over the rain + vec3 fragcolor = ambient; + // where the glass texture is clear, its lighting is multiplied by ~0 below: skip apply_lights there + if (glassA > 0.002) + { + vec3 fragnormal = normalize(f_normal); + float reflectivity = param[1].z; + float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5; + legacy_gloss(); + fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); + } + vec4 color = vec4(fragcolor, glassA); + out_color.xyz = apply_fog(mix(out_color.xyz, color.xyz, color.a)); + out_color.a = mix(out_color.a, 1., color.a); + } + // the picture in the drops goes over the drop shading and the glass, as the old postfx replaced the pixel with it: the dark + // middle of the atlas only shows through faintly, the rim and the glints a little more + out_color = wsOver(bent, out_color); + if (!POSTFX_ENABLED) + out_color = tonemap(out_color); + + // the velocity target: on the drops the picture shift (x, y = WS_DROP_BIAS + WS_BEND_ENC * bend), on the hazy glass the request + // for the haze (x = WS_ENC * strength, y = 0); elsewhere the velocity of the scene behind the glass stays as it is (alpha 0) + if (MOTIONBLUR_ENABLED) + { + vec4 req = vec4(0.0); + bool drop = (coverA > 0.05 || alphaOut > 0.05) && (glassA < 0.5); + float blurMask = blurAmt * glassClear; + if (drop) + { + vec2 bend = lensBend * smoothstep(0.05, 0.35, coverA); + req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); + } + else 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", 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.)); + + 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; + // out_factor: the blade that clears the cell the most wins. side: which wiper stroke the drops of this + // cell belong to (part of their random seed, so it must not depend on out_factor). + 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]; + have_side = true; + } + } + return out_factor; } diff --git a/shaders/ogl46/postfx_motionblur.frag b/shaders/ogl46/postfx_motionblur.frag index e28953ebb..41e080ce6 100644 --- a/shaders/ogl46/postfx_motionblur.frag +++ b/shaders/ogl46/postfx_motionblur.frag @@ -13,13 +13,34 @@ layout(binding = 1) uniform sampler2D velocity_tex; layout(binding = 2) uniform sampler2D depth_tex; #include "common.glsl" +#include "rain_windscreen_haze.glsl" void main() { + // the hazy wet windscreen (mat_rain_windscreen.frag): blurred here without the taa, left as it is when the taa blurred it + vec2 rawv = texture(velocity_tex, f_coords).xy; + if (wsIsDrop(rawv)) + { + vec4 picture = texture(color_tex, f_coords); + out_color = vec4((picture.a > 0.5 * (1.0 + WS_HAZED)) ? picture.rgb + : wsDropRefraction(color_tex, velocity_tex, depth_tex, f_coords, rawv), 1.0); + return; + } + float blurAmt = wsBlur(rawv); + if (blurAmt > 0.0) + { + vec4 picture = texture(color_tex, f_coords); + out_color = vec4((picture.a > 0.5 * (1.0 + WS_HAZED)) ? picture.rgb : wsHaze(color_tex, velocity_tex, f_coords, blurAmt), 1.0); + return; + } + float ori_depth = texture(depth_tex, f_coords).x; vec2 texelSize = 1.0 / vec2(textureSize(color_tex, 0)); - vec2 velocity = texture(velocity_tex, f_coords).xy * param[0].x; + vec2 velocity = rawv * param[0].x; + // edge pixels of the windscreen can carry a fraction of a blur request: never use that as motion + if (any(greaterThan(abs(rawv), vec2(WS_FLOOR * WS_ENC)))) + velocity = vec2(0.0); float speed = length(velocity / texelSize); int nSamples = clamp(int(speed), 1, 32); diff --git a/shaders/ogl46/postfx_taa.frag b/shaders/ogl46/postfx_taa.frag index 294325e71..a4e9566d4 100644 --- a/shaders/ogl46/postfx_taa.frag +++ b/shaders/ogl46/postfx_taa.frag @@ -22,4 +22,53 @@ layout(binding = 3) uniform sampler2D history_tex; #define TAA_HISTORY_VALID (param[0].x > 0.5) #define TAA_REPROJECTION future #define TAA_NEAR param[0].y +#include "rain_windscreen_haze.glsl" + +// the resolve of the taa under another name: main() below gives the hazy windscreen its blur first +#define main taa_resolve_main #include "taa_resolve.glsl" +#undef main + +// the drops and the haze are made from the frame alone (the history of the taa would smear them over the frames): drawn with the +// offsets of the taa they shimmer from frame to frame. they stay where they are on the screen, so the result of the last frame at +// the same pixel is blended in: fully while the view stands still, half while it moves, kept near this frame's result (no ghosts +// of a wiper or of drops gone) +const float WS_TEMPORAL_SHARE = 0.2; // the share of this frame while the view stands still +const float WS_TEMPORAL_MOVING = 0.5; // ... and while it moves +const float WS_TEMPORAL_RANGE = 0.12; // the last frame kept within this of this frame (colours squeezed into 0..1) + +vec3 wsStabilize(vec3 current, ivec2 pixel) +{ + if (false == TAA_HISTORY_VALID) + return current; + vec4 last = texelFetch(history_tex, pixel, 0); + if (any(isnan(last)) || (last.a < 0.5 * (1.0 + WS_HAZED))) // not a drop or haze pixel in the last frame + return current; + vec2 size = vec2(textureSize(color_tex, 0)); + float depth = texelFetch(depth_tex, pixel, 0).r; + vec4 world = TAA_REPROJECTION * vec4(f_coords * 2.0 - 1.0, depth, 1.0); + bool still = (world.w > 0.0) && (length((world.xy / world.w * 0.5 + 0.5 - f_coords) * size) < 0.5); + vec3 c = taa_compress(current); + vec3 h = clamp(taa_compress(taa_clean(last.rgb)), c - WS_TEMPORAL_RANGE, c + WS_TEMPORAL_RANGE); + return taa_decompress(clamp(mix(h, c, still ? WS_TEMPORAL_SHARE : WS_TEMPORAL_MOVING), vec3(0.0), vec3(1.0 - 1.0 / TAA_HALF_MAX))); +} + +void main() +{ + // the hazy wet windscreen (mat_rain_windscreen.frag): the picture of this frame blurred over the hazy glass, without the + // history (else it would blur on frame after frame); marked for the motion blur after + ivec2 pixel = ivec2(f_coords * vec2(textureSize(velocity_tex, 0))); + vec2 raw = texelFetch(velocity_tex, pixel, 0).xy; + if (wsIsDrop(raw)) + { + out_color = vec4(wsStabilize(taa_clean(wsDropRefraction(color_tex, velocity_tex, depth_tex, f_coords, raw)), pixel), WS_HAZED); + return; + } + float blurAmt = wsBlur(raw); + if (blurAmt > 0.0) + { + out_color = vec4(wsStabilize(taa_clean(wsHaze(color_tex, velocity_tex, f_coords, blurAmt)), pixel), WS_HAZED); + return; + } + taa_resolve_main(); +} diff --git a/shaders/ogl46/rain_windscreen_haze.glsl b/shaders/ogl46/rain_windscreen_haze.glsl new file mode 100644 index 000000000..6dd9a4cde --- /dev/null +++ b/shaders/ogl46/rain_windscreen_haze.glsl @@ -0,0 +1,233 @@ +// the haze of the wet windscreen (mat_rain_windscreen.frag), drawn by the post-processing: the glass asks for it in the velocity +// target (x = WS_ENC * strength, y = 0, see mat_rain_windscreen.frag), and the picture there is blurred over the hazy glass only. +// postfx_taa.frag does it with the temporal anti-aliasing (every frame, also standing still), postfx_motionblur.frag without it +// (it runs only while something moves). the picture blurred by the taa is marked in its alpha (WS_HAZED), so the motion blur +// after it leaves it as it is. +// +// real motion vectors are tiny (<< 0.25 per frame), so the large values can only come from the windscreen +#ifndef RAIN_WINDSCREEN_HAZE_GLSL +#define RAIN_WINDSCREEN_HAZE_GLSL + +const float WS_ENC = 64.0; // must match mat_rain_windscreen.frag +const float WS_FLOOR = 0.004; // = 0.256 in raw velocity units: everything below is real motion +const float WS_HAZED = 2.0; // alpha of the picture the taa already blurred + +// blur of hazy glass +const float WS_RADIUS = 0.014; // max blur radius, fraction of screen height +const int WS_TAPS = 16; +const float WS_HAZE_LIGHT_CAP = 12.0; // the most a light adds to the haze around it (brightness, scene units) + +// strength of the blur request, 0 for pixels that are not blur pixels +float wsBlur(vec2 raw) +{ + if (raw.x > 100.0 || raw.y > 100.0) // a blended edge with something else: not a blur pixel + return 0.0; + float m = clamp(raw.x / WS_ENC, 0.0, 1.0); + return clamp((m - WS_FLOOR) / (1.0 - WS_FLOOR), 0.0, 1.0); +} + +// a colour of the picture made safe: a very bright light can be an infinity in the half float image (and a broken pixel a nan); +// in an average that gave nan for the whole result, which the taa turns black: black dotted blobs around the lights +vec3 wsSafe(vec3 c) +{ + return any(isnan(c)) ? vec3(0.0) : clamp(c, vec3(0.0), vec3(65000.0)); +} + +vec3 wsFetch(sampler2D tex, vec2 uv) +{ + return wsSafe(textureLod(tex, uv, 0.0).rgb); +} + +// the weight of a colour in an average that a single very bright pixel must not take over +float wsKaris(vec3 c) +{ + return 1.0 / (1.0 + dot(c, vec3(0.2126, 0.7152, 0.0722))); +} + +// the picture at Uv blurred over the hazy glass, for a request of BlurAmt (> 0) +vec3 wsHaze(sampler2D colortex, sampler2D velocitytex, vec2 uv, float blurAmt) +{ + vec2 texelSize = 1.0 / vec2(textureSize(colortex, 0)); + float aspect = texelSize.x / texelSize.y; // height / width + vec3 sharp = wsFetch(colortex, uv); + + float radius = WS_RADIUS * blurAmt; + + // interleaved gradient noise rotates the disc per pixel -> no banding + float rot = 6.2831853 * fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))); + + float wsum = wsKaris(sharp); + vec3 sum = sharp * wsum; + float psum_w = 1.0; // the plain average beside it + vec3 psum = sharp; + + for (int i = 0; i < WS_TAPS; ++i) + { + float r = sqrt((float(i) + 0.5) / float(WS_TAPS)); + float a = float(i) * 2.3999632 + rot; // golden angle + vec2 o = vec2(cos(a), sin(a)) * r * radius; + o.x *= aspect; + + vec2 tap = uv + o; + + // take only hazy-glass pixels (not the cab frame, not clear glass, not drops) + // weighed by 1 / (1 + brightness) (karis average): an ordinary picture blurs the same, but a very bright light + // (a lamp close by, headlights) is not smeared over the whole disc at full strength, which the bloom then turned + // into a large flat blob shaped like a clover + float w = step(0.01, wsBlur(textureLod(velocitytex, tap, 0.0).xy)); + vec3 c = wsFetch(colortex, tap); + psum += c * w; + psum_w += w; + w *= wsKaris(c); + sum += c * w; + wsum += w; + } + + // the karis average alone almost wipes small bright lights out of the haze (signals at night went faint): the light the + // plain average has above it comes back, up to WS_HAZE_LIGHT_CAP, so a light stays a soft glow of its colour and only a + // very bright one (a lamp close by) isn't smeared at full strength + vec3 blurred = sum / wsum; + vec3 extra = max(psum / psum_w - blurred, vec3(0.0)); + float extraL = dot(extra, vec3(0.2126, 0.7152, 0.0722)); + blurred += extra * min(1.0, WS_HAZE_LIGHT_CAP / max(extraL, 1e-4)); + return mix(sharp, blurred, min(blurAmt * 4.0, 1.0)); +} + +// --------------------------------------------------------------------------------------------------------------------------- +// refraction in the drops: the glass sends the picture shift of the drop (x, y = WS_DROP_BIAS + WS_BEND_ENC * bend, bend -1..1 +// = WS_REFR_MAXPX pixels), and the picture of this frame is bent here. the depth of the whole frame (with the cab) is known here, +// so the dashboard, the frame and the roof of the cab are never pulled into a drop (the image of the last frame used by the +// glass shader can't tell them apart: white drops at night at the edges and under the wipers) +// --------------------------------------------------------------------------------------------------------------------------- +const float WS_BEND_ENC = 60.0; // must match mat_rain_windscreen.frag +const float WS_DROP_BIAS = 192.0; // must match mat_rain_windscreen.frag +const float WS_REFR_MAXPX = 96.0; // must match mat_rain_windscreen.frag +const float WS_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the refracted picture +const float WS_LENS_AA = 0.75; // above this spread of the picture between neighbouring pixels, a 4x4 footprint is averaged + +// the lights in the drops: a drop is a wide-angle lens and lights up near a bright light (signals, lamps, headlights). taken from +// the mipmaps of the image the screen reflections keep (ssr_history: the last frame, or this one in the motion blur), so the glow +// is smooth: point samples of the full image caught a headlight of one pixel only at fixed offsets and drew it as grids of dots +const float WS_LIGHT_GAIN = 1.0; // brightness of the lights in the drops (0 = off) +const float WS_LIGHT_CAP = 8.0; // the most the glow adds to a drop (brightness, scene units) +const float WS_LIGHT_MIN_LUM = 1.0; // a light: the fine level at least this bright (scene units) above the place around it ... +const float WS_LIGHT_CONTRAST = 3.0; // ... and this many times brighter than it +const float WS_LIGHT_FINE = 3.5; // mip levels: the drop's own neighbourhood (~11 px), a wider one (~32 px), the place around +const float WS_LIGHT_MID = 5.0; +const float WS_LIGHT_WIDE = 7.0; +const float WS_LIGHT_MID_SHARE = 0.5; // how much the lights a little further away count + +// the vulkan renderer gives the post-processing only its own images (LAYOUT_POST): no history of the reflections, no glow there +#ifndef LAYOUT_POST +layout(binding = SSR_HISTORY_TEX) uniform sampler2D ws_light_history; +#endif + +// reverse z, infinite far: depth = znear / distance. a sample is "the cab" when it is much nearer than the centre and closer than ~5 m +const float WS_NEAR_RATIO = 1.6; +const float WS_NEAR_DEPTH = 0.02; + +bool wsSameLayer(float d, float d0) +{ + return d <= max(d0 * WS_NEAR_RATIO, WS_NEAR_DEPTH); +} + +float wsLum(vec3 c) +{ + return dot(c, vec3(0.2126, 0.7152, 0.0722)); +} + +// a drop pixel (drop, rivulet): both values in 132..252 +bool wsIsDrop(vec2 raw) +{ + return raw.x > 120.0 && raw.y > 120.0; +} + +vec2 wsBend(vec2 raw) +{ + return clamp((raw - WS_DROP_BIAS) / WS_BEND_ENC, -1.0, 1.0); +} + +#ifndef LAYOUT_POST +vec3 wsLightExcess(vec2 uv, float lod, vec3 wide) +{ + vec3 c = wsSafe(textureLod(ws_light_history, uv, min(lod, ssr_params2.x)).rgb); + vec3 excess = max(c - wide * WS_LIGHT_CONTRAST, vec3(0.0)); + return excess * smoothstep(0.5 * WS_LIGHT_MIN_LUM, WS_LIGHT_MIN_LUM, wsLum(excess)); +} + +vec3 wsLightGlow(vec2 uv) +{ + if ((ssr_params.x < 1.0) || (textureSize(ws_light_history, 0).x < 16)) + return vec3(0.0); + vec3 wide = wsSafe(textureLod(ws_light_history, uv, min(WS_LIGHT_WIDE, ssr_params2.x)).rgb); + vec3 glow = wsLightExcess(uv, WS_LIGHT_FINE, wide) + WS_LIGHT_MID_SHARE * wsLightExcess(uv, WS_LIGHT_MID, wide); + glow *= WS_LIGHT_GAIN; + // a light close by is kept to the brightness of one light + return glow * min(1.0, WS_LIGHT_CAP / max(wsLum(glow), 1e-4)); +} +#else +vec3 wsLightGlow(vec2 uv) +{ + return vec3(0.0); +} +#endif + +// the picture at Uv seen through the drop, for a drop pixel with the request Raw +vec3 wsDropRefraction(sampler2D colortex, sampler2D velocitytex, sampler2D depthtex, vec2 uv, vec2 raw) +{ + vec2 texelSize = 1.0 / vec2(textureSize(colortex, 0)); + float aspect = texelSize.x / texelSize.y; // height / width + vec3 center = wsFetch(colortex, uv); + + vec2 bend = wsBend(raw); + vec2 uv2 = uv - bend * WS_REFR_MAXPX * texelSize; + + // the spread of the picture between neighbouring pixels (the jacobian of the shift): a drop shows a minified, flipped copy + // of the scene, single samples would alias into a hatch there + vec2 rx = textureLod(velocitytex, uv + vec2(texelSize.x, 0.0), 0.0).xy; + vec2 ry = textureLod(velocitytex, uv + vec2(0.0, texelSize.y), 0.0).xy; + vec2 jx = (wsIsDrop(rx) ? wsBend(rx) - bend : vec2(0.0)) * WS_REFR_MAXPX; + vec2 jy = (wsIsDrop(ry) ? wsBend(ry) - bend : vec2(0.0)) * WS_REFR_MAXPX; + float lens = length(jx) + length(jy); + + // never pull in what is much nearer than the scene behind the glass (the cab) + vec3 refr = center; + float d0 = textureLod(depthtex, uv, 0.0).x; + float d1 = textureLod(depthtex, uv2, 0.0).x; + if (wsSameLayer(d1, d0)) + { + if (lens < WS_LENS_AA) + { + refr = wsFetch(colortex, uv2); + } + else + { + vec2 fx = clamp(vec2(1.0, 0.0) - jx, vec2(-10.0), vec2(10.0)); + vec2 fy = clamp(vec2(0.0, 1.0) - jy, vec2(-10.0), vec2(10.0)); + vec3 acc = vec3(0.0); + float wacc = 0.0; + for (int j = 0; j < 4; ++j) + { + for (int i = 0; i < 4; ++i) + { + vec2 t = (vec2(float(i), float(j)) + 0.5) / 4.0 - 0.5; + vec3 c = wsFetch(colortex, uv2 + (fx * t.x + fy * t.y) * texelSize); + float w = wsKaris(c); + acc += c * w; + wacc += w; + } + } + refr = acc / wacc; + } + } + + vec3 outc = mix(center, refr, WS_REFR_MIX); + // the glow only in the drops themselves, strongest in their middle, where the lens bends most: the water film and the + // rivulets between them (no bend) would show it as flat squares around the headlights of an oncoming train + float glowW = smoothstep(0.03, 0.2, length(bend)); + if ((WS_LIGHT_GAIN > 0.0) && (glowW > 0.0)) + outc += wsLightGlow(uv) * glowW; + return outc; +} + +#endif diff --git a/shaders/vk14/mat_rain_windscreen.frag b/shaders/vk14/mat_rain_windscreen.frag index 4cc783f2a..fa76bc95e 100644 --- a/shaders/vk14/mat_rain_windscreen.frag +++ b/shaders/vk14/mat_rain_windscreen.frag @@ -1,30 +1,45 @@ #version 460 core #define STAGE_FRAGMENT 1 #include "common.glsl" -// Windshield rain and snow -// by @lcddisplay; wiper movement @MichauSto; water on the glass rewritten as a model of drops lying on it +// Windshield rain effects - v3 (rewrite) +// by @lcddisplay; wiper movement @MichauSto; rain v3: drop layers, drop life, rivulets that sweep drops // -// the material: the textures diffuse (the glass) and wipermask (a blade per channel, r g b a: 0 where it doesn't reach, elsewhere -// the place of the blade over its sweep, 0 at rest .. 1 at the far end, at which it goes over the place). raindropsatlas and -// raindrop_grid_size aren't used any more, they stay so the materials which name them still load. rain_scale (1 when not given) -// scales the drops and the flakes. water_slot is given by the renderer (1 + the glass of the simulation, 0 none), not by the -// material. the block of the scene: rain_params (x: how heavy the rain or snow is, z: 1 for snow, w: temperature of the air), -// wiper_pos, wiper_timer_out, wiper_timer_return (the blades of the vehicle of the camera) and rain_wind (the air against it). +// What is on the glass: +// 1. Micro droplets: a dense grid of tiny, static droplets. Procedural (no texture reads): a spherical cap +// per droplet. They make the glass look wet between the bigger drops. +// 2. Drops: one per grid cell (raindrop_grid_size), shape from the 2x2 drop tiles of the atlas +// (normalmap: rg = normal xy, b = height, a = mask). A drop lands (quick pop), sits still for +// drop_life_min..drop_life_max seconds, then makes room for a new one. Drops do NOT slide: all motion is +// done by the rivulets (a sliding drop used to leave its 3x3 neighbourhood and got cut off). +// Sizes are skewed (many medium, few big) and the tiles are randomly mirrored (8 shapes instead of 4). +// Where drops overlap, the higher one wins (no averaged "ghost" normals). +// 3. Rivulets: a drop runs down in stick-slip fashion and leaves a wet trail (4 sprites in the right half +// of the atlas, 256 x 1024: head in the bottom STREAK_HEAD_FRAC, trail above). The head sweeps up every +// drop and droplet on its way: the trail band is clean until the rivulet fades out. +// The trail right above the head is taken from the sprite part that touches the head, then it blends +// into the trail pattern that is fixed to the glass (beads stay where they were left). // -// the glasses of the cab of the train are simulated (gfx::windscreen_water, water_*.comp, water.glsl): the raindrops land as often -// as the rain hits the glass, splashing; the drops lie held by surface tension until gravity and the drag of the air pull them -// harder, then slide in stops and goes, wetting their paths (the next ones follow them into rivulets) and leaving droplets behind; -// the drops which touch flow together; the blades take the water along, gather it into a bead and leave it at the ends of their -// sweep, where it runs down; the flakes stick and melt. here the drops of the simulation are drawn where the fragment is, and the -// wetted paths as a thin film. elsewhere (the windows of other vehicles, a glass the simulation has no room for) the water is made -// up from the time alone: drops landing, growing and sliding along tracks, the blades pushing a ridge and leaving the water at the -// edge of their sweep. +// Shading: the grey atlas (bright rim, dark middle) is read once per pixel, only for the drop that wins the +// pixel (it used to be read for all 9 neighbours). Micro droplets are shaded analytically. // -// the water is a field of soft kernels (metaballs): drops coming close flow together, and a drop is a few kernels, so the drops -// are of many shapes. a drop is a lens holding a sharp picture of the place around it turned over (the image of the last frame -// where the screen holds it, the sky and the ground elsewhere), its edge shows the light of the sky reflected inside it; the lamps -// and the headlights light the water up; the film the blades leave breaks up behind them and the lights seen through it are drawn -// into lines towards their pivot; the wet glass is a little milky +// Refraction / blur (OpenGL 4.6, the renderer with the screen space reflections): the glass reads the image of the last +// frame the renderer keeps for the reflections (ssr_history, with mipmaps) and the depth of the scene (scene_depth): +// - drops act as small lenses: the pixel shows the scene on the opposite side of the drop centre, so every drop holds a +// small, flipped picture (drop_lens); rivulets bend the view by Snell's law from their normal, +// - bright lights near a drop (signals, lamps, headlights) show up in it, +// Works standing still, with the motion blur off and with taa. Needs gfx.ssr (default: medium); without it the drops show +// the sky / ground only, faintly. +// The haze of the wet glass is blurred by the post-processing, from the picture of this frame: the glass writes a request +// into the velocity target (x = 64 * strength, y = 0) and postfx_taa.frag (with gfx.antialiasing taa: every frame) or +// postfx_motionblur.frag (without it: only while something moves) blur the picture there (rain_windscreen_haze.glsl). +// +// Speed: the air against the vehicle (rain_wind) drives the water: at speed a second layer of rivulets runs along its push +// (up a front glass, back along a side window) and sweeps the drops up on its way, the drops are stretched along the push, +// the haze grows. Standing still the rain is as it always was. +// +// OpenGL 4.6 renderer (feat/gl46-migration): headlights and lamps are clustered, calc_headlights takes the +// screen-space derivatives of f_pos, the sun glint follows the cloud shadow. Lamps (cab lamp, scenery) light up +// the drops too (drop_lamp_scatter). layout(location = 0) in vec3 f_normal; layout(location = 2) in vec2 f_coord; @@ -42,1176 +57,1020 @@ 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) // rg = normal xy, b = height, a = mask; 2048 x 1024 (drops left, rivulets right), 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) -#pragma param(rain_scale, 2, 1, 1, one) #include "light_common.glsl" #include "apply_fog.glsl" #include "tonemapping.glsl" -#include "water.glsl" +#include "random.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; -const float RW_PI = 3.14159265; -// refractive index of water -const float RW_IOR = 1.333; -// the falling particles (particles_precipitation.comp, rendering/common/gpuparticles.cpp): the diameters of the flakes, metres, -// and how fast the rain and the snow fall, m/s -const vec2 RW_SNOW_DIAMETER = vec2(0.004, 0.012); -const float RW_RAIN_FALL = 7.0; -const float RW_SNOW_FALL = 1.1; -// a drop is a lens: it holds a sharp picture of the place around it, turned over through its middle, RW_LENS times as far out -// as the fragment is from the middle (and as much smaller), with this share of the bending of the view by the surface on top -const float RW_LENS = 2.0; -const float RW_LENS_BEND = 0.15; -// the drag of the air going along the glass: the speed at which it equals the weight of a drop, m/s; and the share of the air -// meeting the glass head on which turns up along it. so the water goes up a glass the sooner the more it leans back: on a -// vertical glass at about 250 km/h, leaning 20 degrees at about 130 km/h, 45 degrees at about 80 km/h -const float RW_DRAG_SPEED = 24.0; -const float RW_HEAD_ON = 0.35; -// the water is a field summed from soft kernels (metaballs) and its surface is where the field is RW_SURFACE: drops which come -// close flow together the way surface tension pulls them. a kernel alone reaches the surface at RW_EDGE of its radius -const float RW_SURFACE = 0.25; -const float RW_EDGE = 0.61; +// --- 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) +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 -// the glass at the fragment: the view space steps along it for a step of the coordinates of the glass (metres along the axes -// of the model, see main()), and the size of a pixel on it, metres -vec3 rw_tu; -vec3 rw_tv; -float rw_pixel; +// --- Drops (atlas tiles) ------------------------------------------------------ +const float drop_density = 0.6; // share of grid cells holding a drop at full rain (scaled by rain intensity) +const float drop_size_min = 0.45; // drop size in grid cells +const float drop_size_max = 1.15; +const float drop_size_bias = 1.8; // >1 = more small/medium drops, fewer big ones +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 drop_sag = 0.12; // max vertical stretch of a resting drop (gravity) -// how the water on the glass behaves here, set by main() -float rw_scale; // size of the drops (param rain_scale) -float rw_since; // seconds since a blade last cleaned the place -float rw_period; // seconds between the small drops landing on a place of one -float rw_grow; // seconds the drops need after a wipe to grow big enough to slide -float rw_rate; // how fast the glass gathers the rain against a standing vertical glass in the heaviest rain -float rw_push; // the force on a drop along the glass, in units of its weight -vec2 rw_down; // the way gravity pulls along the glass (coordinates of the glass, unit) -vec2 rw_flow; // the way the air goes along the glass (unit, 0 in still air) +// --- Micro droplets ------------------------------------------------------------- +const float micro_density = 0.45; // share of micro cells holding a droplet at full rain, 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; +const float micro_bulge = 0.80; // slope of the droplet dome at its rim (0..0.95) +const float micro_life = 60.0; // average seconds a droplet lives -// the field of the water: the sum of the kernels, its gradient along the glass (view space) and the sums for the mean radius of -// the drops it is made of -float rw_field = 0.0; -vec3 rw_fgrad = vec3(0.0); -float rw_fsize = 0.0; -float rw_fweight = 0.0; +// --- Look of the drops (grey atlas for drops / rivulets, the same look computed for micro droplets) --------- +const float drop_rim_start = 0.30; // micro droplets: dome slope (1 - nz) where the bright rim starts +const float drop_rim_end = 0.80; // ... and where it is fully bright +const float drop_light_side = 0.25; // micro droplets: brighter on the upper-left side +const float drop_center_alpha = 0.25; // how much the dark middle of a drop covers the scene +const float drop_rim_alpha = 0.85; // how much the bright rim covers the scene +const float drop_shade_alpha = 0.30; // faint alpha over the whole dome (carries the glints) -// the water at the fragment: the thickness of the highest water there (metres), its gradient (view space), the radius of the -// curvature of its surface (metres: how much it bends the view across a pixel) and how much of the pixel it covers -float rw_height = 0.0; -vec3 rw_slope = vec3(0.0); -float rw_curve = 1.0; -float rw_cover = 0.0; -// from the middle of the drop which gives the water to the fragment (view space, metres), 0 for spread water -vec3 rw_offset = vec3(0.0); -// the last time the water a blade pushes went over the fragment, taking the drops lying there with it -float rw_cleared = -1.0e9; +// --- Light on the drops -------------------------------------------------------- +const float drop_ior = 1.33; // refraction index of water +const float drop_refract = 0.5; // rivulets: strength of the picture shift (Snell; 1 = physical) +const float drop_lens = 2.0; // drops: lens field, the drop shows (1 + drop_lens) x its own size, flipped +const float drop_lens_mix = 0.7; // drops: 1 = lens picture, 0 = Snell shift like the rivulets +const float drop_env = 0.6; // reflection of the environment on the dome (0 = off) +const float drop_glint_strength = 5.0; // sun / moon glint brightness +const float drop_glint_sharpness = 40.0; // sun / moon glint size (lower = a wider lobe, so more drops catch it) +const float drop_sheen = 0.3; // wide, soft sun sheen on the domes around the sharp glint +const float drop_headlight_scatter = 3.0; // how much drops light up in headlight beams +const float drop_lamp_scatter = 1.0; // GL 4.6: how much drops light up from lamps (station lamps, signals), 0 = off +const float drop_light_near = 4.0; // lights nearer than this (metres; the own vehicle) don't light the drops, full from 2x +const float drop_light_max = 3.0; +const float drop_dark_lum = 0.25; // average brightness of the screen (scene units) below which the drops darken with it // the most the lamps and headlights add to a drop (scene units, before tonemapping) -uvec4 rw_pcg4d(uvec4 v) +// --- Rivulets (drops that run down and leave a wet trail) --------------------------------- +// Sizes are in "drop cells" (1 cell = 1 / raindrop_grid_size of the glass UV). +const float streak_density = 1.00; // share of cells carrying a rivulet (scaled by the rain intensity), 0 = off +const float streak_cell = 6.0; // width of a rivulet cell in drop cells +const float streak_run = 20.0; // height of a rivulet cell in drop cells = the longest run of one rivulet +const float streak_head = 1.7; // mean width of the drop head, in drop cells (randomised 0.75x .. 1.25x) +const float streak_period = 40.0; // seconds a rivulet lives (it runs for ~90% of that and then fades out), average +const float streak_wiggle = 0.35; // how far the path swings sideways, in head widths (0 = straight) +const float streak_wiggle_speed = 0.5; // speed of the little waves that flow down the trail +const float streak_flow = 0.15; // ripples flowing down inside the trail (shows in refraction and glints), 0 = off +const float streak_uv_aspect = 1.0; // glass width / height in UV terms (1 = same stretch as the drops) +const float streak_sweep = 1.0; // 1 = the head sweeps up drops on its way (clean band behind it), 0 = off +const float streak_sweep_width = 0.9; // width of the swept band, in head widths +const float streak_link = 1.5; // head widths above the head where the trail is taken from the sprite part + // that touches the head (so the trail always leaves the head cleanly) + +// --- Speed: the air against the vehicle (rain_wind) drives the water on the glass -------------------- +// The force on the water along the glass: its weight (gravity) and the drag of the air going along the glass (and of the +// share of the air meeting it head on which turns up along it), as in the stock shader of the renderer. Standing still +// (or in a light wind) nothing of it shows: the rain lands, grows and runs down as it always did. +const float wind_drag_gain = 4.0; // how strongly the air drives the water (1 = the drag of the stock shader: on a + // vertical front glass the water would go up only at ~250 km/h) +const float wind_streaks = 3.0; // density of the rivulets driven by the air, at full drag (x streak_density) +const float wind_cell_scale = 0.36; // the rivulets of the air: their cells this much narrower ... +const float wind_run_scale = 0.28; // ... and shorter than those of gravity: many small drops with short trails +const float wind_head_scale = 0.55; // their heads this much smaller +const int wind_layers = 4; // layers of them, each with drops of its own (1 .. 4) +const float wind_long_run = 1.6; // the last layer: its trails this much longer than those of gravity (the long ones, a part of all) +const float wind_streak_period = 14.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) +const float drop_wind_stretch = 0.4; // drops are stretched up to this much along the push of the air (0 = off) +const float WS_DRAG_SPEED = 24.0; // speed of the air along the glass at which its drag equals the weight of a drop, m/s +const float WS_HEAD_ON = 0.35; // share of the air meeting the glass head on which turns up along it +const float WS_WIND_STEP = 0.1309; // the direction of the rivulets of the air in steps of 7.5 degrees (no seams on a + // curved glass, where every triangle would turn them a little) + +#ifndef STREAK_FLIP_Y +#define STREAK_FLIP_Y 0 // set to 1 if the rivulets run UP the glass (head on top) +#endif +const float STREAK_TAIL_SCALE = 1.5; // the trail pattern of the sprite is drawn this much longer than native +const float STREAK_HEAD_FRAC = 0.22; // part of the sprite height used by the drop head (= HEAD_FRAC of the atlas generator) + +const float WS_INSIDE = 0.3; // metres beyond the glass nearer than which the image is taken for the inside of the cab + // (in the rain the cab isn't in the depth: the nose of the own vehicle is outside) +const float WS_REFR_MAXPX = 96.0; // largest picture shift of a drop, screen pixels +const float WS_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the refracted picture +const float WS_LIGHT_GAIN = 1.0; // brightness of the lights near a drop shown in it (0 = off) +const float WS_LIGHT_CONTRAST = 3.0; // a light: this many times brighter than the place around it + +const vec3 DROP_LIGHT = vec3(-0.5527, 0.6532, 0.5226); // same light as the atlas generator (upper left) + +// the surroundings in a view space direction where the image doesn't hold them: the environment map above the horizon, +// the ground below it, blurred by Lod (as in the stock mat_rain_windscreen.frag) +vec3 wsSurroundings(vec3 direction, float lod) { - v = v * 1664525u + 1013904223u; - v.x += v.y * v.w; - v.y += v.z * v.x; - v.z += v.x * v.y; - v.w += v.y * v.z; - v ^= v >> 16u; - v.x += v.y * v.w; - v.y += v.z * v.x; - v.z += v.x * v.y; - v.w += v.y * v.z; - return v; + vec3 world = mat3(inv_view) * direction; + vec3 sky = envmap_sample_rough(normalize(vec3(world.x, max(world.y, 0.0), world.z)), clamp(lod / 8.0, 0.0, 1.0)); + float below = smoothstep(-0.03 - 0.05 * lod, 0.25 + 0.05 * lod, -world.y); + if ((below <= 0.0) || (false == ENVMAP_ENABLED)) + return sky; + return mix(sky, reflection_ground(), below); } -// four numbers 0 .. 1 of a cell of a layer -vec4 rw_random(ivec2 cell, uint layer, uint index) +// what is seen through the glass in a view space direction: the image of the last frame where it holds the place, Distance +// away along the direction (0: far), blurred by Lod; Share: how much of it the image gave. Fade: towards the edges of the +// image the surroundings take over. The inside of the cab (near the camera in the depth) is never taken: the surroundings +// stand for it (else the drops would show the dark walls of the cab) +vec3 wsBehind(vec3 direction, float lod, float distance, out float share, bool fade) { - return vec4(rw_pcg4d(uvec4(uvec2(cell), layer, index))) * (1.0 / 4294967296.0); + share = 0.0; + vec3 around = wsSurroundings(direction, lod); + if (ssr_params.x < 1.0) + return around; + vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); + if (previous.w <= 1e-5) + return around; + vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; + vec2 edges = min(coords, 1.0 - coords); + share = fade ? smoothstep(0.0, 0.04, min(edges.x, edges.y)) : step(-0.02, min(edges.x, edges.y)); + coords = clamp(coords, vec2(0.0), vec2(1.0)); + if (share <= 0.0) + return around; + ivec2 size = textureSize(scene_depth, 0); + float depth = texelFetch(scene_depth, clamp(ivec2(coords * vec2(size)), ivec2(0), size - 1), 0).r; + float near = projection[3][2]; + if ((depth > 0.0) && (near / depth < -f_pos.z + WS_INSIDE)) + { + share = 0.0; + return around; + } + vec3 color = textureLod(ssr_history, coords, clamp(lod, 0.0, ssr_params2.x)).rgb; + if (any(isnan(color)) || any(isinf(color))) + { + share = 0.0; + return around; + } + return mix(around, max(color, vec3(0.0)), share); } -float rw_noise(float x, uint layer) +float wsLum(vec3 c) { - float i = floor(x); - float f = x - i; - float a = rw_random(ivec2(int(i), 0), layer, 7u).x; - float b = rw_random(ivec2(int(i) + 1, 0), layer, 7u).x; - return mix(a, b, f * f * (3.0 - 2.0 * f)); + return dot(c, vec3(0.2126, 0.7152, 0.0722)); } -// value noise 0 .. 1 (x) with its gradient (yz) -vec3 rw_noise2(vec2 p, uint layer) +// bright lights near a drop (signals, lamps, headlights): a drop is a wide-angle lens and picks them up. A light is where a +// fine mip level of the image (~11 px around) is much brighter than a coarse one (~90 px around) +vec3 wsLightGlow(vec3 direction, float distance) { - vec2 i = floor(p); - vec2 f = p - i; - vec2 u = f * f * (3.0 - 2.0 * f); - vec2 du = 6.0 * f * (1.0 - f); - ivec2 c = ivec2(i); - float a = rw_random(c, layer, 8u).x; - float b = rw_random(c + ivec2(1, 0), layer, 8u).x; - float d = rw_random(c + ivec2(0, 1), layer, 8u).x; - float e = rw_random(c + ivec2(1, 1), layer, 8u).x; - float k1 = b - a; - float k2 = d - a; - float k4 = a - b - d + e; - return vec3(a + k1 * u.x + k2 * u.y + k4 * u.x * u.y, du * vec2(k1 + k4 * u.y, k2 + k4 * u.x)); -} - -// P turned by A (radians). every set of drops is laid on its own grid, turned and shifted against the others, so the drops line -// up neither with each other nor along the glass -vec2 rw_turn(vec2 p, float a) -{ - float c = cos(a); - float s = sin(a); - return vec2(c * p.x - s * p.y, s * p.x + c * p.y); -} - -// a gradient given along the coordinates of the glass, view space -vec3 rw_along(vec2 gradient) -{ - return rw_tu * (gradient.x / dot(rw_tu, rw_tu)) + rw_tv * (gradient.y / dot(rw_tv, rw_tv)); -} - -// the gradient along the glass (view space) of a value of the fragments, from how it changes from pixel to pixel; Dpdx, Dpdy: -// the steps of the position, Normal: of the glass -vec3 rw_gradient(float value, vec3 dpdx, vec3 dpdy, vec3 normal) -{ - vec3 r1 = cross(dpdy, normal); - vec3 r2 = cross(normal, dpdx); - float det = dot(dpdx, r1); - float dx = dFdx(value); - float dy = dFdy(value); - return (abs(det) > 1e-14) ? (dx * r1 + dy * r2) / det : vec3(0.0); -} - -// a kernel of the water, Offset (view space) from its centre to the fragment: alone it makes water of the radius Visible, -// Weight 1 .. 0 as it goes. water smaller than a pixel would only flicker, it is left to the haze of the wet glass -void rw_kernel(vec3 offset, float visible, float weight) -{ - if ((weight <= 0.0) || (visible < 0.5 * rw_pixel)) - return; - // a drop a pixel or two across is grain rather than a lens: it fades into the haze of the wet glass - weight *= smoothstep(0.5 * rw_pixel, 2.0 * rw_pixel, visible); - float support = visible / RW_EDGE; - float q = dot(offset, offset) / (support * support); - if (q >= 1.0) - return; - float k = 1.0 - q; - float k3 = weight * k * k * k; - rw_field += k3; - rw_fgrad += offset * (-6.0 * weight * k * k / (support * support)); - rw_fsize += k3 * visible; - rw_fweight += k3; -} - -// a kernel at the Offset in the coordinates of the glass -void rw_blob(vec2 offset, float visible, float weight) -{ - rw_kernel(offset.x * rw_tu + offset.y * rw_tv, visible, weight); -} - -// a drop lying on the glass: a few kernels, sagging down the glass and lopsided as Shape (random 0 .. 1) says -void rw_drop(vec2 offset, float visible, float weight, vec4 shape) -{ - rw_blob(offset, visible, weight); - if (visible < 1.5 * rw_pixel) - return; - vec2 side = vec2(-rw_down.y, rw_down.x); - vec2 sag = (rw_down * (0.2 + 0.35 * shape.x) + side * ((shape.y - 0.5) * 0.7)) * visible; - rw_blob(offset - sag, visible * mix(0.6, 0.85, shape.z), weight); - if (shape.w > 0.4) - { - float angle = shape.w * 40.0; - rw_blob(offset - vec2(cos(angle), sin(angle)) * (0.6 * visible), visible * mix(0.4, 0.6, shape.x), weight); - } -} - -// water spread over the glass (a film, a ridge): its thickness, the gradient of it (view space), the radius of the curvature of -// its surface and how much of the pixel it covers -void rw_sheet(float thickness, vec3 slope, float curve, float cover) -{ - if (cover <= 0.0) - return; - rw_cover = max(rw_cover, cover); - if (thickness > rw_height) - { - rw_height = thickness; - rw_slope = slope; - rw_curve = curve; - rw_offset = vec3(0.0); - } -} - -// the surface of the water of the field: a drop is a cap of a sphere, flat lens of the contact angle Contact (radians) the water -// makes with the glass. how far across a drop the fragment is follows from the field (inverting the kernel), the height and -// the slope of the cap from that: the slope rises slowly from the middle and steeply only close to the edge, where it reaches -// the contact angle; where drops flowed together the field is above that of a drop alone and the water is flat. the edge is -// antialiased by how fast the field changes across a pixel -void rw_settle(float contact) -{ - if (rw_field <= 0.5 * RW_SURFACE) - return; - float gradient = length(rw_fgrad); - float cover = clamp((rw_field - RW_SURFACE) / max(gradient * rw_pixel, 1e-3) + 0.5, 0.0, 1.0); - if (cover <= 0.0) - return; - float mean = rw_fsize / max(rw_fweight, 1e-12); - // 0 in the middle of a drop, 1 at its edge - float across = min(sqrt(max(1.0 - pow(min(rw_field, 1.0), 1.0 / 3.0), 0.0)) / RW_EDGE, 1.0); - float s = sin(contact); - float rs = across * s; - float root = sqrt(max(1.0 - rs * rs, 1e-4)); - float sphere = mean / s; - vec3 slope = (gradient > 1e-9) ? rw_fgrad * ((rs / root) / gradient) : vec3(0.0); - float height = max(sphere * (root - cos(contact)), 0.0); - bool top = height > rw_height; - rw_sheet(height, slope, sphere, cover); - // the field rises towards the middle of the drop - if (top && (gradient > 1e-9)) - rw_offset = rw_fgrad * (-across * mean / gradient); -} - -// the blades. a channel of the mask of the wipers is a blade: 0 where it doesn't reach, elsewhere the place of the blade over its -// sweep (0 at rest .. 1 at the far end) at which it goes over the place. wiper_pos: where the blade is (0 .. 1 on its way out, -// 1 + where it is on its way back), wiper_timer_out / _return: the last time it lay at its start / was at its far end -struct rw_wipe_s -{ - float since; // seconds since a blade last went over the place (large where none reaches) - float ahead; // 0 .. 1, how close in front of a moving blade the place is (the water the blade pushes) - float front; // how far in front of the nearest moving blade the place is, units of the mask (1 where none) - float swept; // 0 .. 1, how much of its way the blade in front did, the water it gathered on the way - float working; // 0 .. 1, the blades went lately -}; - -rw_wipe_s rw_wipe(vec4 mask) -{ - rw_wipe_s wipe = rw_wipe_s(1.0e4, 0.0, 1.0, 0.0, 0.0); - for (int i = 0; i < 4; ++i) - { - float m = mask[i]; - if (m < 0.001) - continue; - float pos = wiper_pos[i]; - bool back = pos > 1.0; - float blade = back ? pos - 1.0 : pos; - float t0 = wiper_timer_out[i]; - float t1 = wiper_timer_return[i]; - // when the blade went over the place last: on this stroke, the blade moving at an even pace from its end, or on the - // stroke before, which took as long as the time between the ends (if the blade lay at its end longer, two seconds) - float pass; - float front; // how far in front of the blade the place is (units of the mask), below 0 behind it - if (back) - { - pass = (m >= blade) ? t1 + (time - t1) * ((1.0 - m) / max(1.0 - blade, 1e-3)) : t0 + m * clamp(t1 - t0, 0.0, 2.0); - front = blade - m; - } - else - { - pass = (m <= blade) ? t0 + (time - t0) * (m / max(blade, 1e-3)) : t1 + (1.0 - m) * clamp(t0 - t1, 0.0, 2.0); - front = m - blade; - } - wipe.since = min(wipe.since, max(time - pass, 0.0)); - float moving = smoothstep(0.0, 0.03, blade) * smoothstep(1.0, 0.97, blade); - float ahead = (front > 0.0) ? (1.0 - smoothstep(0.0, 0.035, front)) * moving : 0.0; - wipe.ahead = max(wipe.ahead, ahead); - if ((front > 0.0) && (moving > 0.5)) - wipe.front = min(wipe.front, front); - wipe.swept = max(wipe.swept, ahead * (back ? 1.0 - blade : blade)); - float working = 1.0 - smoothstep(4.0, 30.0, time - t1); - wipe.working = max(wipe.working, working); - } - return wipe; -} - -// a place of the glass a blade reaches -bool rw_reached(vec2 coords) -{ - return any(greaterThanEqual(textureLod(wipermask, clamp(coords, vec2(0.0), vec2(1.0)), 0.0), vec4(0.001))); -} - -// the edge of the sweep of the blades, where they push the water out to: 0 where a blade reaches, else the share of the places -// around at Reach (metres along the glass) which a blade reaches. found from where the blades reach and not from the values of -// the mask, which may stay at the end of the sweep over a wide part of the glass. Maskstep: the coordinates of the mask for a -// step along the glass -float rw_rim(vec2 coords, float reach, mat2 maskstep) -{ - if (rw_reached(coords)) - return 0.0; - float inside = 0.0; - for (int k = 0; k < 6; ++k) - { - float angle = float(k) * (RW_PI / 3.0); - inside += rw_reached(coords + maskstep * (vec2(cos(angle), sin(angle)) * reach)) ? 1.0 : 0.0; - } - return inside / 6.0; -} - -// whether the edge of the sweep of the blades is within Reach of the place -bool rw_border(vec2 coords, float reach, mat2 maskstep) -{ - bool here = rw_reached(coords); - for (int k = 0; k < 6; ++k) - { - float angle = float(k) * (RW_PI / 3.0); - if (rw_reached(coords + maskstep * (vec2(cos(angle), sin(angle)) * reach)) != here) - return true; - } - return false; -} - -// how far along its way a sliding drop is at the share T of the time it takes: it stops and goes, the more smoothly the harder -// it is pushed -float rw_stickslip(float t, float seed) -{ - t = clamp(t, 0.0, 1.0); - float s = t * 3.0; - float i = floor(s); - float stuck = (i + smoothstep(0.25 + 0.4 * seed, 1.0, s - i)) / 3.0; - return mix(stuck, t, smoothstep(0.8, 2.0, rw_push)); -} - -// the track of the water down a column of the glass (Column: its index, Width: of a column, Y: metres up the way): where it -// is across, metres. the water keeps to the way wetted before, so every drop of a column goes the same way, wavy, with kinks -// where the glass held it -float rw_path(int column, float y, float width, uint layer) -{ - float slow = rw_noise(y / (0.05 * rw_scale) + float(column) * 7.31, layer) - 0.5; - float k = y / (0.008 * rw_scale); - float i = floor(k); - float a = rw_random(ivec2(column, int(i)), layer + 500u, 3u).x; - float b = rw_random(ivec2(column, int(i) + 1), layer + 500u, 3u).x; - float kinks = mix(a, b, smoothstep(0.15, 0.85, k - i)) - 0.5; - return (float(column) + 0.5 + 0.4 * slow + 0.2 * kinks) * width; -} - -// the drops which grew big enough to slide, and the streams they leave: Q the place across and up the way they go (Side, Down: -// those directions in the coordinates of the glass), Share of them going this way. a column of the glass carries the water of -// a track; a drop starts somewhere in a cell of the column now and then, slides down with stops, thinning, and leaves a stream -// which drains into beads and dries -void rw_sliders(vec2 q, vec2 side, vec2 down, uint layer, float share) -{ - float width = 0.04 * rw_scale; - float height = 0.15 * rw_scale; - int column = int(floor(q.x / width)); - int row = int(floor(q.y / height)); - vec4 a = rw_random(ivec2(column, 7), layer, 0u); - if (a.x > share * mix(0.35, 0.9, clamp(rw_rate / 3.0, 0.0, 1.0))) - return; - float speed = clamp(0.035 + 0.06 * (rw_push - 0.4) + 0.3 * max(rw_push - 1.5, 0.0), 0.01, 0.8); - float period = clamp(25.0 / rw_rate, 3.0, 60.0); - float trail = 0.0; - for (int r = 0; r < 3; ++r) - { - ivec2 cell = ivec2(column, row + r); - vec4 b = rw_random(cell, layer, 1u); - float span = period * mix(0.7, 1.3, b.x); - float now = floor(time / span + b.y); - for (int k = 0; k < 2; ++k) - { - float cycle = now - float(k); - float start = (cycle - b.y) * span; - float t = time - start; - // the drop gathered from the drops landed since the last wipe - if ((t < 0.0) || (rw_since - t < rw_grow)) - continue; - vec4 c = rw_random(cell, layer + 1000u, uint(int(cycle) + 1000000)); - float top = (float(cell.y) + 0.8 - 0.6 * c.x) * height; - float travel = mix(0.06, 0.28, c.y) * rw_scale; - float v = speed * mix(0.7, 1.3, c.z); - float gather = 0.6; - float moved = travel * rw_stickslip((t - gather) * v / travel, c.w); - float y = top - moved; - float radius = mix(0.003, 0.0042, c.w) * rw_scale * (1.0 - 0.35 * moved / travel) * mix(0.6, 1.0, smoothstep(0.0, gather, t)); - // at the end of its way what is left of it stays and flows out into the stream - float body = 1.0 - smoothstep(0.0, 1.5, t - gather - travel / v); - if ((body > 0.0) && (abs(q.y - y) < 3.5 * radius)) - { - vec2 o = vec2(q.x - rw_path(column, y, width, layer), q.y - y); - rw_blob(side * o.x - down * o.y, radius, body); - // its rear up the stream: a corner, drawn out into a cusp the faster it goes (the front stays round) - float drawn = clamp(v * 5.0, 0.0, 1.5); - for (int k = 1; k <= 2; ++k) - { - float yt = y + radius * (0.45 + 0.5 * drawn) * float(k); - vec2 ot = vec2(q.x - rw_path(column, yt, width, layer), q.y - yt); - rw_blob(side * ot.x - down * ot.y, radius * ((k == 1) ? 0.7 : 0.42), body); - } - } - if ((moved > 0.0) && (q.y > y) && (q.y < top)) - { - float age = t - gather - (top - q.y) / v; - if ((age >= 0.0) && (age < rw_since)) - { - // fresh, the stream is whole; draining, it breaks into beads, which dry - float beads = rw_noise(q.y / (0.004 * rw_scale), layer + 9u); - float wet = mix(1.15, 0.2 + 1.0 * beads, smoothstep(0.0, 15.0, age)) * (1.0 - smoothstep(30.0, 60.0, age)); - trail = max(trail, wet); - } - } - } - } - if (trail > 0.0) - { - float across = q.x - rw_path(column, q.y, width, layer); - float half_width = mix(0.0005, 0.0011, a.y) * rw_scale * (0.6 + 0.8 * rw_noise(q.y / (0.006 * rw_scale), layer + 11u)); - rw_blob(side * across, half_width, trail); - } -} - -// a drop lying on the glass, as rw_drop() with the directions along the glass given in the view space (Down: the way gravity -// pulls along the glass, Side across it) -void rw_drop_view(vec3 offset, float visible, float weight, vec4 shape, vec3 down, vec3 side) -{ - rw_kernel(offset, visible, weight); - if (visible < 1.5 * rw_pixel) - return; - vec3 sag = (down * (0.2 + 0.35 * shape.x) + side * ((shape.y - 0.5) * 0.7)) * visible; - rw_kernel(offset - sag, visible * mix(0.6, 0.85, shape.z), weight); - if (shape.w > 0.4) - { - float angle = shape.w * 40.0; - rw_kernel(offset - (cos(angle) * side + sin(angle) * down) * (0.6 * visible), visible * mix(0.4, 0.6, shape.x), weight); - } -} - -// the water the simulation keeps on the glass (gfx::windscreen_water, water.glsl), where the material is a glass of the cab of the -// train: the drops listed by the cell of the grid the fragment is in. Slot: of the glass, Uv: the coordinates of the fragment, -// Puv: the view space step along the glass for a step of the uv; Down, Side: along the glass. a sliding drop is drawn out behind -// itself into a cusp, the faster the longer; one lying is lopsided and sags down the glass; a flake of snow is lace, grey and -// clear as it melts (Snowcover, Wet: as the flakes of rw_snow()) -void rw_simulated(uint slot, vec2 uv, mat2x3 puv, vec3 down, vec3 side, inout float snowcover, inout float wet) -{ - uint base = water_grid_base(slot); - uint cell = water_cell(uv); - uint count = min(water_cells[base + cell], uint(WATER_CELL_DROPS)); - for (uint k = 0u; k < count; ++k) - { - uint place = water_cells[base + uint(WATER_GRID * WATER_GRID) + cell * uint(WATER_CELL_DROPS) + k]; - water_drop_s drop = water_drops[slot * uint(WATER_DROPS) + place]; - float volume = drop.place.z; - if (volume <= 0.0) - continue; - vec3 offset = puv * (uv - drop.place.xy); - vec4 shape = vec4(rw_pcg4d(uvec4(place, slot, 41u, 0u))) * (1.0 / 4294967296.0); - if (drop.motion.w < 1.0) - { - // a flake: lobed lace, shrinking, grey and clear as it melts - float m = drop.motion.w; - vec2 flat2 = vec2(dot(offset, side), dot(offset, down)); - float radius = 0.5 * water_flake(volume); - float dist = length(flat2); - if (dist < radius + rw_pixel) - { - float angle = atan(flat2.y, flat2.x); - float lobes = 0.55 + 0.45 * (0.6 * rw_noise(angle * 1.9 + shape.z * 40.0, 13u) + 0.4 * abs(cos(3.0 * angle + shape.w * 6.2831853))); - float rim = radius * lobes * (1.0 - 0.45 * m); - float body = smoothstep(rim + rw_pixel, 0.55 * rim - rw_pixel, dist); - float lace = rw_noise2(flat2 / 0.0007 + shape.zw * 100.0, 14u).x; - float flake = body * mix(0.55, 1.0, lace) * (1.0 - 0.7 * m * m); - snowcover = 1.0 - (1.0 - snowcover) * (1.0 - flake); - wet = max(wet, m * body); - } - continue; - } - float radius = water_radius(volume); - vec3 velocity = puv * drop.motion.xy; - float speed = length(velocity); - if (speed > 0.002) - { - // its rear up the way it came: a corner, drawn out into a cusp the faster it goes (the front stays round) - vec3 way = velocity / speed; - rw_kernel(offset, radius, 1.0); - float drawn = clamp(speed * 5.0, 0.0, 1.5); - for (int t = 1; t <= 2; ++t) - rw_kernel(offset + way * (radius * (0.45 + 0.5 * drawn) * float(t)), radius * ((t == 1) ? 0.7 : 0.42), 1.0); - } - else - { - rw_drop_view(offset, radius, 1.0, shape, down, side); - } - } -} - -// how fresh the wetted paths of the simulation are at a place of the glass (x) and how that changes along u and v (yz): the -// texels of their map filtered by a cubic b-spline over 4 x 4 of them, so the edges of a path are smooth curves and its slopes -// change smoothly (a bilinear filter would leave steps at every texel in the bending of the view) -vec3 rw_trail(uint slot, vec2 uv, float now) -{ - // a path stays wet (and seen) longer than the drops keep to it - float lasting = 25.0; - vec2 p = uv * float(WATER_TRAIL) - 0.5; - vec2 i = floor(p); - vec2 f = p - i; - // the weights of the b-spline and their derivatives, for the texels i - 1 .. i + 2 - vec2 g = 1.0 - f; - vec4 wx = vec4(g.x * g.x * g.x, 3.0 * f.x * f.x * f.x - 6.0 * f.x * f.x + 4.0, -3.0 * f.x * f.x * f.x + 3.0 * f.x * f.x + 3.0 * f.x + 1.0, f.x * f.x * f.x) / 6.0; - vec4 wy = vec4(g.y * g.y * g.y, 3.0 * f.y * f.y * f.y - 6.0 * f.y * f.y + 4.0, -3.0 * f.y * f.y * f.y + 3.0 * f.y * f.y + 3.0 * f.y + 1.0, f.y * f.y * f.y) / 6.0; - vec4 dx = vec4(-g.x * g.x, 3.0 * f.x * f.x - 4.0 * f.x, -3.0 * f.x * f.x + 2.0 * f.x + 1.0, f.x * f.x) * 0.5; - vec4 dy = vec4(-g.y * g.y, 3.0 * f.y * f.y - 4.0 * f.y, -3.0 * f.y * f.y + 2.0 * f.y + 1.0, f.y * f.y) * 0.5; - vec3 result = vec3(0.0); - ivec2 base = ivec2(i) - 1; - for (int y = 0; y < 4; ++y) - { - for (int x = 0; x < 4; ++x) - { - float value = water_wetted(slot, base + ivec2(x, y), now, lasting); - result += value * vec3(wx[x] * wy[y], dx[x] * wy[y], wx[x] * dy[y]); - } - } - result.yz *= float(WATER_TRAIL); - return result; -} - -// the surroundings in a view space direction where the screen doesn't hold them: the environment map above the horizon (the sky -// and the clouds), the ground below it, blurred by Lod -vec3 rw_surroundings(vec3 direction, float lod) -{ - vec3 world = mat3(inv_view) * direction; - vec3 sky = envmap_sample_rough(normalize(vec3(world.x, max(world.y, 0.0), world.z)), clamp(lod / 8.0, 0.0, 1.0)); - // the horizon as blurred as the view is - float below = smoothstep(-0.03 - 0.05 * lod, 0.25 + 0.05 * lod, -world.y); - if ((below <= 0.0) || (false == ENVMAP_ENABLED)) - return sky; - return mix(sky, reflection_ground(), below); -} - -// what is seen through the glass in a view space direction: the image of the last frame (the screen space reflections keep it) -// where it holds the place, Distance away along the direction (0: far), blurred by Lod; Share: how much of it the image gave. -// Fade: towards the edges of the image the surroundings take over (else the edges are stretched) -vec3 rw_behind_edges(vec3 direction, float lod, float distance, out float share, bool fade) -{ - share = 0.0; - vec3 around = rw_surroundings(direction, lod); - if (ssr_params.x < 1.0) - return around; - vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); - if (previous.w <= 1e-5) - return around; - vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; - vec2 edges = min(coords, 1.0 - coords); - share = fade ? smoothstep(0.0, 0.04, min(edges.x, edges.y)) : step(-0.02, min(edges.x, edges.y)); - coords = clamp(coords, vec2(0.0), vec2(1.0)); - if (share <= 0.0) - return around; - // the view out through the water goes on outside, where the image shows the inside of the cab around the windows the - // surroundings stand for it (else the drops show the dark walls and roof of the cab) - ivec2 size = textureSize(scene_depth, 0); - float depth = texelFetch(scene_depth, clamp(ivec2(coords * vec2(size)), ivec2(0), size - 1), 0).r; - float near = projection[3][2]; - if ((depth > 0.0) && (near / depth < -f_pos.z + 2.5)) - { - share = 0.0; - return around; - } - vec3 color = textureLod(ssr_history, coords, clamp(lod, 0.0, ssr_params2.x)).rgb; - if (any(isnan(color)) || any(isinf(color))) - { - share = 0.0; - return around; - } - return mix(around, max(color, vec3(0.0)), share); -} - -vec3 rw_behind(vec3 direction, float lod, float distance, out float share) -{ - return rw_behind_edges(direction, lod, distance, share, true); + vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); + if (previous.w <= 1e-5) + return vec3(0.0); + vec2 coords = clamp((previous.xy / previous.w) * 0.5 + 0.5, vec2(0.0), vec2(1.0)); + vec3 near = textureLod(ssr_history, coords, min(3.5, ssr_params2.x)).rgb; + vec3 wide = textureLod(ssr_history, coords, min(6.5, ssr_params2.x)).rgb; + if (any(isnan(near)) || any(isinf(near)) || any(isnan(wide)) || any(isinf(wide))) + return vec3(0.0); + vec3 excess = max(near - wide * WS_LIGHT_CONTRAST, vec3(0.0)); + return min(excess, vec3(30.0)) * (2.0 * WS_LIGHT_GAIN); } // a layer Over put over Under, the colours not premultiplied -vec4 rw_over(vec4 over, vec4 under) +vec4 wsOver(vec4 over, vec4 under) { - float alpha = over.a + under.a * (1.0 - over.a); - if (alpha <= 1e-5) - return vec4(0.0); - return vec4((over.rgb * over.a + under.rgb * under.a * (1.0 - over.a)) / alpha, alpha); + float alpha = over.a + under.a * (1.0 - over.a); + if (alpha <= 1e-5) + return vec4(0.0); + return vec4((over.rgb * over.a + under.rgb * under.a * (1.0 - over.a)) / alpha, alpha); +} + +// =========================================================================== +float GetMixFactor(in vec2 co, out float side); + +uvec2 cellKey(vec2 c); + +vec2 tileOffset(float choice) +{ + if (choice < 0.25) return vec2(0.0, 0.0); + else if (choice < 0.5) return vec2(0.5, 0.0); + else if (choice < 0.75) return vec2(0.0, 0.5); + return vec2(0.5, 0.5); +} + +// the 2x2 drop tiles live in the left half of the atlas: a tile is 0.25 wide and 0.5 high in atlas UV +vec2 dropAtlasUV(float choice, vec2 uv) +{ + vec2 off = tileOffset(choice); + return vec2((off.x + uv.x * 0.5) * 0.5, off.y + uv.y * 0.5); +} + +uvec2 cellKey(vec2 c) +{ + return uvec2(ivec2(c) + ivec2(65536)); +} + +// --- one rivulet cell ------------------------------------------------------------ +struct Riv +{ + bool on; + float life; // 0..1 (fade in / out) + float width; // sprite width = head width (glass UV) + float headH; // head height (glass UV) + float topY; // where the trail starts (fixed on the glass) + float bottom; // bottom of the head now + float left; // left edge of the sprite + float flip; + float col; // which of the 4 sprites + float wipe; + float wavK, wavPh, wavSp; +}; + +// the layer of rivulets being worked on: the one of gravity (the rivulets as they always were, coordinates = glass UV with v +// up) or the one of the air (its own cells and seeds, turned so that its rivulets run along the push of the air) +float wsLayerDensity = 1.0; // x rain x streak_density: share of the cells holding a rivulet +float wsLayerPeriod = streak_period; +uint wsLayerSalt = 91u; +float wsLayerHead = 1.0; // x streak_head +float wsLayerCos = 1.0; // the layer is turned by this angle (its "down" is the way its water runs on the glass) +float wsLayerSin = 0.0; + +// glass UV (v up) -> coordinates of the layer, where the rivulets run down (-v) +vec2 wsToLayerDir(vec2 v) +{ + return vec2(wsLayerCos * v.x + wsLayerSin * v.y, -wsLayerSin * v.x + wsLayerCos * v.y); +} +vec2 wsToLayer(vec2 g) +{ + return wsToLayerDir(g - 0.5) + 0.5; +} +vec2 wsFromLayerDir(vec2 v) +{ + return vec2(wsLayerCos * v.x - wsLayerSin * v.y, wsLayerSin * v.x + wsLayerCos * v.y); +} +vec2 wsFromLayer(vec2 p) +{ + return wsFromLayerDir(p - 0.5) + 0.5; +} + +// the layers: 0 gravity, 1 air. WindShare: how much the air drives the water (0 standing still), WindCos / WindSin: the turn +// of the layer of the air +float wsWindShare = 0.0; +float wsWindCos = 1.0; +float wsWindSin = 0.0; +void wsSetLayer(int layer) +{ + if (layer == 0) + { + wsLayerDensity = 1.0 - wsWindShare; + wsLayerPeriod = streak_period; + wsLayerSalt = 91u; + wsLayerHead = 1.0; + wsLayerCos = 1.0; + wsLayerSin = 0.0; + } + else + { + wsLayerDensity = wsWindShare * wind_streaks; + wsLayerPeriod = wind_streak_period; + wsLayerSalt = 91u + 2u * uint(layer); + wsLayerHead = wind_head_scale; + wsLayerCos = wsWindCos; + wsLayerSin = wsWindSin; + } +} + +Riv getRiv(vec2 sCell, float sCW, float sCH, float gridSize) +{ + Riv r; + uint sSeed = Hash(uvec3(cellKey(sCell), wsLayerSalt)); + r.on = (RandF(sSeed) < rain_params.x * streak_density * wsLayerDensity); + float sPeriod = wsLayerPeriod * mix(0.6, 1.6, RandF(sSeed)); + float sPhase = fract(time / sPeriod + RandF(sSeed)); + r.life = smoothstep(0.0, 0.05, sPhase) * (1.0 - smoothstep(0.86, 1.0, sPhase)); + r.width = streak_head * wsLayerHead / gridSize * mix(0.75, 1.25, RandF(sSeed)); + r.headH = r.width * 0.88 * streak_uv_aspect; + float sSpan = max(sCH * mix(0.35, 0.70, RandF(sSeed)), r.headH * 3.0); + // stick-slip: the drop waits, then lurches forward; N waits on the way down + float sSteps = floor(mix(3.0, 8.0, RandF(sSeed))); + float sXs = clamp(sPhase / 0.88, 0.0, 1.0) * sSteps; + float sRun = clamp((floor(sXs) + smoothstep(0.55, 1.0, fract(sXs))) / sSteps, 0.0, 1.0); + r.topY = sCell.y * sCH + sSpan + RandF(sSeed) * max(sCH - sSpan, 0.0); + r.bottom = r.topY - r.headH * 1.2 - sRun * (sSpan - r.headH * 1.2); + const float sMargin = 0.8; + r.left = sCell.x * sCW + sMargin * r.width + RandF(sSeed) * max(sCW - r.width * (1.0 + 2.0 * sMargin), 0.0); + r.flip = (RandF(sSeed) < 0.5) ? 1.0 : 0.0; + r.col = floor(RandF(sSeed) * 4.0); + r.wipe = RandF(sSeed); + r.wavK = 6.2831853 / mix(2.5, 5.0, RandF(sSeed)); + r.wavPh = RandF(sSeed) * 6.2831853; + r.wavSp = streak_wiggle_speed * mix(0.6, 1.4, RandF(sSeed)); + return r; +} + +// sideways offset of the path (in head widths) at distance dW (head widths) down from the start of the trail +float rivWob(Riv r, float dW, out float ramp, out float wobD) +{ + float rampT = clamp(dW / 2.5, 0.0, 1.0); + ramp = rampT * rampT * (3.0 - 2.0 * rampT); + float rampD = 3.0 * rampT * (1.0 - rampT) / 2.5; + float a1 = dW * r.wavK + r.wavPh; + float a2 = dW * r.wavK * 1.7 - time * r.wavSp * 1.0472 + r.wavPh * 2.0; // the wave runs DOWN + float w1 = 0.7 * sin(a1) + 0.3 * sin(a2); + float w1D = 0.7 * cos(a1) * r.wavK + 0.3 * cos(a2) * r.wavK * 1.7; + wobD = -streak_wiggle * (rampD * w1 + ramp * w1D); + return streak_wiggle * ramp * w1; +} + +// how much a drop centred at p (glass UV, v up) with radius rad has been swept up by rivulet r (0..1) +float rivSwept(Riv r, vec2 p, float rad) +{ + if (!r.on || r.life <= 0.001) return 0.0; + if (p.y > r.topY || p.y < r.bottom - rad) return 0.0; + bool inHead = p.y < r.bottom + r.headH; + float dW = (r.topY - (inHead ? r.bottom + 0.5 * r.headH : p.y)) / r.width; + float ramp, wobD; + float wob = rivWob(r, dW, ramp, wobD); + float cx = r.left + (0.5 + wob) * r.width; + float halfW = 0.5 * streak_sweep_width * r.width; + return (1.0 - smoothstep(halfW, halfW + rad, abs(p.x - cx))) * r.life; +} + +// candidate on the glass that wins the pixel (the highest dome) +struct Hit +{ + float score; + float cov; // coverage of the dome (normal map alpha) + float colA; // coverage of the drawn drop (sharper) + vec3 n; // dome normal, tangent space of the glass + vec2 offUV; // pixel - centre (glass UV), for the lens + float radUV; // radius (glass UV) + float isDrop; // 1 = drop / droplet (lens), 0 = rivulet (Snell) + float vis; // life / sweep visibility + vec2 auv; // grey atlas lookup of the winner (drops, rivulets) + vec2 agx, agy; + float atlas; // 1 = shade from the grey atlas, 0 = analytic (micro droplets: shade in colA's place) + float shade; // analytic shade (micro droplets) +}; + +void consider(inout Hit h, float score, float cov, float colA, vec3 n, vec2 offUV, float radUV, float isDrop, + float vis, vec2 auv, vec2 agx, vec2 agy, float atlas, float shade) +{ + if (score > h.score) + { + h.score = score; h.cov = cov; h.colA = colA; h.n = n; + h.offUV = offUV; h.radUV = radUV; h.isDrop = isDrop; + h.vis = vis; h.auv = auv; h.agx = agx; h.agy = agy; h.atlas = atlas; h.shade = shade; + } +} + +// the rivulet R of the layer set (wsSetLayer) at the pixel, at SUVr in the coordinates of the layer; Rd1 / Rd2: their change +// per screen pixel +void drawRivulet(inout Hit hit, Riv r, vec2 sUVr, vec2 rd1, vec2 rd2) +{ + if (!(r.on && r.life > 0.001)) + return; + const float sMargin = 0.8; + float sLen = r.topY - r.bottom; + float sx = (sUVr.x - r.left) / r.width; + float sy = sUVr.y - r.bottom; + if (sx >= -sMargin && sx <= 1.0 + sMargin && sy >= 0.0 && sy <= sLen) + { + bool inHead = sy < r.headH; + float dW = (r.topY - (inHead ? r.bottom + 0.5 * r.headH : sUVr.y)) / r.width; + float ramp, wobD; + float wob = rivWob(r, dW, ramp, wobD); + if (inHead) wobD = 0.0; + float sxw = sx - wob; + if (sxw >= 0.0 && sxw <= 1.0) + { + float sSide; + vec2 sWipeUV = f_coord; + if (inHead) + { + sWipeUV = wsFromLayer(vec2(r.left + 0.5 * r.width, r.bottom + 0.5 * r.headH)); + if (STREAK_FLIP_Y != 0) sWipeUV.y = 1.0 - sWipeUV.y; + } + if (GetMixFactor(sWipeUV, sSide) >= mix(0.5, 1.0, r.wipe)) + { + float sNative = 3.125 * r.width * streak_uv_aspect * STREAK_TAIL_SCALE; + float sxs = mix(sxw, 1.0 - sxw, r.flip); + float su = 0.5 + (r.col + sxs) * 0.125; + vec2 sgx = vec2(0.125 / r.width * rd1.x, 0.0); + vec2 sgy = vec2(0.125 / r.width * rd2.x, 0.0); + vec4 sNm; + vec2 sAuv; + float vtSign = 1.0; + if (inHead) + { + float kv = STREAK_HEAD_FRAC / r.headH; + sgx.y = kv * rd1.y; sgy.y = kv * rd2.y; + sAuv = vec2(su, sy / r.headH * STREAK_HEAD_FRAC); + sNm = textureGrad(normalmap, sAuv, sgx, sgy); + } + else + { + float kv = (1.0 - STREAK_HEAD_FRAC) / sNative; + sgx.y = kv * rd1.y; sgy.y = kv * rd2.y; + // a) trail pattern fixed to the glass, tiled by mirroring (beads stay where they were left) + float dd = max(r.topY - sUVr.y, 0.0) / sNative; + float vt = abs(mod(dd, 2.0) - 1.0); + vtSign = (mod(dd, 2.0) < 1.0) ? 1.0 : -1.0; + // b) right above the head: the sprite part that touches the head + float above = (sy - r.headH) / r.width; // head widths above the head + float link = 1.0 - smoothstep(0.5 * streak_link, streak_link, above); + vec4 nGlass = vec4(0.0); + vec4 nLink = vec4(0.0); + vec2 uvGlass = vec2(su, STREAK_HEAD_FRAC + vt * (1.0 - STREAK_HEAD_FRAC)); + vec2 uvLink = vec2(su, STREAK_HEAD_FRAC + min((sy - r.headH) / sNative, 1.0) * (1.0 - STREAK_HEAD_FRAC)); + if (link < 0.999) + nGlass = textureGrad(normalmap, uvGlass, sgx, sgy); + if (link > 0.001) + nLink = textureGrad(normalmap, uvLink, sgx, sgy); + sAuv = (link > 0.5) ? uvLink : uvGlass; + sNm = mix(nGlass, nLink, link); + vtSign = mix(vtSign, 1.0, link); + } + + float sFade = inHead ? 1.0 : smoothstep(0.0, 1.5, dW); // the start of the trail melts into the glass + float sVis = r.life * sFade; + float sCov = smoothstep(0.1, 0.6, sNm.a) * sVis; + if (sCov > 0.001) + { + vec2 nxy = sNm.rg * 2.0 - 1.0; + if (r.flip > 0.5) nxy.x = -nxy.x; + if (STREAK_FLIP_Y != 0) nxy.y = -nxy.y; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec2 slope = -nxy / max(nz, 0.08); + if (!inHead) + slope.y = slope.y * vtSign / STREAK_TAIL_SCALE - slope.x * wobD + + streak_flow * ramp * sin(dW * 4.8 - time * 4.0); + // the slope of the layer to the one of the glass + if (STREAK_FLIP_Y != 0) slope.y = -slope.y; + slope = wsFromLayerDir(slope); + if (STREAK_FLIP_Y != 0) slope.y = -slope.y; + vec3 n = normalize(vec3(-slope, 1.0)); + float h = sNm.b * r.width * 0.5; + consider(hit, sCov * (h + 1e-5), sCov, 0.0, n, vec2(0.0), r.width * 0.5, 0.0, + sVis, sAuv, sgx, sgy, 1.0, 0.0); + } + } + } + } +} + +// how much of a drop centred at Cg (glass UV, v up) with radius Rad the rivulets of both layers have swept up (0..1 kept) +float wsKept(vec2 cg, float rad, Riv rivP, vec2 sCell, float sCW, float sCH, float gridSize) +{ + wsSetLayer(0); + vec2 rc = floor(cg / vec2(sCW, sCH)); + Riv rv = rivP; + if (rc != sCell) rv = getRiv(rc, sCW, sCH, gridSize); + float kept = 1.0 - streak_sweep * rivSwept(rv, cg, rad); + if (wsWindShare > 0.001) + { + wsSetLayer(1); + vec2 cw = wsToLayer(cg); + vec2 wc = vec2(sCW * wind_cell_scale, sCH * wind_run_scale); + Riv rw = getRiv(floor(cw / wc), wc.x, wc.y, gridSize); + kept *= 1.0 - streak_sweep * rivSwept(rw, cw, rad); + wsSetLayer(0); + } + 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) +{ + 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; + 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; } void main() { - vec4 tex_color = texture(diffuse, f_coord); - vec4 mask = texture(wipermask, f_coord); + // ---- screen-space derivatives (before any non-uniform flow) ---- + float uvPerPx = max(length(dFdx(f_coord)), length(dFdy(f_coord))); + vec2 sxy = f_pos.xy / max(-f_pos.z, 1e-3); + float pxPerSlope = 1.0 / max(max(length(dFdx(sxy)), length(dFdy(sxy))), 1e-6); + vec3 Ngl = normalize(f_normal); + vec3 wsView = normalize(f_pos.xyz); // the view through the glass and its change per pixel (for the bent view) + vec3 wsDvx = dFdx(wsView); + vec3 wsDvy = dFdy(wsView); + 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; + // glass UV offset -> screen pixels (inverse of the UV Jacobian), for the drop lens + mat2 Juv = mat2(duv1, duv2); + float detJ = determinant(Juv); + mat2 Jinv = (abs(detJ) > 1e-20) ? inverse(Juv) : mat2(0.0); - // the coordinates of the glass: metres along the axes of the model, so the water stays where it lies on the glass whatever the - // vehicle and the camera do. the axis of the model nearest to the vertical is up, the glass is projected along the - // horizontal one it faces most (along the vertical one if it lies flat) - mat3 linear = mat3(modelview); - mat3 rot = mat3(normalize(linear[0]), normalize(linear[1]), normalize(linear[2])); - mat3 unrot = transpose(rot); - vec3 local = unrot * (f_pos.xyz - modelview[3].xyz); - vec3 viewnormal = normalize(f_normal); - // the water is on the side away from the camera, the outside of the cab - vec3 outward = (dot(viewnormal, f_pos.xyz) < 0.0) ? -viewnormal : viewnormal; - vec3 normal = unrot * outward; - vec3 up = unrot * (vec3(0.0, 1.0, 0.0) * mat3(inv_view)); - vec3 aup = abs(up); - int iu = (aup.x > aup.y) ? ((aup.x > aup.z) ? 0 : 2) : ((aup.y > aup.z) ? 1 : 2); - int ia = (iu + 1) % 3; - int ib = (iu + 2) % 3; - vec3 axis_up = vec3(0.0); - axis_up[iu] = (up[iu] < 0.0) ? -1.0 : 1.0; - vec3 axis_a = vec3(0.0); - axis_a[ia] = 1.0; - vec3 axis_b = vec3(0.0); - axis_b[ib] = 1.0; - vec3 an = abs(normal); - vec3 axis_u, axis_v, axis_n; - if (an[iu] > max(an[ia], an[ib])) - { - axis_n = axis_up; - axis_u = axis_a; - axis_v = axis_b; - } - else if (an[ia] >= an[ib]) - { - axis_n = axis_a; - axis_u = axis_b; - axis_v = axis_up; - } - else - { - axis_n = axis_b; - axis_u = axis_a; - axis_v = axis_up; - } - vec2 glass = vec2(dot(local, axis_u), dot(local, axis_v)); - float facing = dot(normal, axis_n); - facing = ((facing < 0.0) ? -1.0 : 1.0) * max(abs(facing), 0.35); - // a step of the coordinates is a step along the glass - rw_tu = rot * (axis_u - axis_n * (dot(normal, axis_u) / facing)); - rw_tv = rot * (axis_v - axis_n * (dot(normal, axis_v) / facing)); + vec4 tex_color = texture(diffuse, f_coord); + float glassA = tex_color.a * alpha_mult; - // the derivatives, before anything is discarded: the size of a pixel on the glass and in the view, and how the coordinates of - // the mask follow the ones of the glass - vec3 view = normalize(f_pos.xyz); - vec3 dpdx = dFdx(f_pos.xyz); - vec3 dpdy = dFdy(f_pos.xyz); - rw_pixel = max(max(length(dpdx), length(dpdy)), 1e-6); - float pixelangle = max(max(length(dFdx(view)), length(dFdy(view))), 1e-6); - vec2 gdx = dFdx(glass); - vec2 gdy = dFdy(glass); - mat2 steps = mat2(gdx, gdy); - float det = determinant(steps); - mat2 maskstep = (abs(det) > 1e-14) ? mat2(dFdx(f_coord), dFdy(f_coord)) * inverse(steps) : mat2(0.0); + float gridSize = ceil(param[2].x); + vec2 rainCoord = f_coord; - // the water the simulation keeps, where the material is a glass of the cab of the train (the param water_slot, given by the - // renderer: 1 + the glass): the view space step along the glass for a step of the uv, and how fresh the wetted path the water - // went along is, with how that changes along the glass (before anything is discarded) - int slot = int(param[2].z + 0.5) - 1; - mat2 uvsteps = mat2(dFdx(f_coord), dFdy(f_coord)); - float uvdet = determinant(uvsteps); - bool simulated = (slot >= 0) && (slot < WATER_SLOTS) && (abs(uvdet) > 1e-24); - simulated = simulated && (water_header[clamp(slot, 0, WATER_SLOTS - 1)].x > 0.5); - mat2x3 puv = (abs(uvdet) > 1e-24) ? mat2x3(dpdx, dpdy) * inverse(uvsteps) : mat2x3(0.0); - vec3 trailfield = simulated ? rw_trail(uint(slot), f_coord, water_header[clamp(slot, 0, WATER_SLOTS - 1)].y) : vec3(0.0); - float trail = trailfield.x; - // its gradient along the glass, view space: the uv gradient taken through the steps of the uv along the glass - vec3 trailslope = vec3(0.0); - { - mat2 metric = transpose(puv) * puv; - if (abs(determinant(metric)) > 1e-30) - trailslope = puv * (inverse(metric) * trailfield.yz); - } + float ambLum = clamp(dot(ambient, vec3(0.2126, 0.7152, 0.0722)), 0.0, 1.0); + float dynBright = pow(clamp(ambLum * 6.0, 0.0, 1.0), 0.5); + // GL 4.6: the ambient light isn't a level of 0..1 any more (it is in the units of the scene, the light of the sky added), so + // at night the drops came out as bright as by day. how bright the picture around really is says it: the coarsest level of + // the image of the last frame, the average of the screen + float sceneLum = (ssr_params.x >= 1.0) ? wsLum(textureLod(ssr_history, vec2(0.5), ssr_params2.x).rgb) : 1.0; + float wsNight = smoothstep(0.0, drop_dark_lum, sceneLum); // 0 dark night .. 1 daylight + dynBright *= wsNight; - if (tex_color.a < 0.01) - discard; + // wiper state of this pixel (blur, micro droplets) + float hazeSide; + float wipeVis = GetMixFactor(f_coord, hazeSide); - vec4 layer = vec4(0.0); - float heavy = clamp(rain_params.x, 0.0, 1.0); - bool snow = rain_params.z > 0.5; - if ((heavy > 0.0) || simulated) - { - rw_scale = max(param[2].y, 0.05); + 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; + hit.vis = 0.0; hit.auv = vec2(0.0); hit.agx = vec2(0.0); hit.agy = vec2(0.0); hit.atlas = 0.0; hit.shade = 0.0; - // what meets the glass. the air against the vehicle (rain_wind) drags the drops along the glass with what of it goes - // along the glass and with the share of what meets it head on which turns up it: the more the glass leans back the more - // of the air goes along it, and the less of their weight pulls the drops down it - vec3 air = unrot * (rain_wind.xyz * mat3(inv_view)); - float fall = snow ? RW_SNOW_FALL : RW_RAIN_FALL; - float hits = max(-dot(air - up * fall, normal), 0.0); - rw_rate = heavy * clamp(0.7 + hits / fall, 0.7, 6.0); - rw_period = clamp((snow ? 10.0 : 5.0) / rw_rate, 0.4, 300.0); - rw_grow = 2.0 * rw_period; - vec3 gravity = -up - normal * dot(-up, normal); - vec3 rise = up - normal * dot(up, normal); - rise = (length(rise) > 0.1) ? normalize(rise) : vec3(0.0); - vec3 flow = air - normal * dot(air, normal) + rise * (max(-dot(air, normal), 0.0) * RW_HEAD_ON); - vec3 push = gravity + flow * (length(flow) / (RW_DRAG_SPEED * RW_DRAG_SPEED)); - vec2 force = vec2(dot(push, axis_u), dot(push, axis_v)); - rw_push = length(force); - vec2 fallway = vec2(dot(gravity, axis_u), dot(gravity, axis_v)); - rw_down = (length(fallway) > 0.1) ? normalize(fallway) : vec2(0.0, -1.0); - vec2 flowway = vec2(dot(flow, axis_u), dot(flow, axis_v)); - rw_flow = (length(flowway) > 1.0) ? normalize(flowway) : vec2(0.0); + // ---- the air against the vehicle on the glass (uniform flow: the derivatives of the glass above) ---- + float flipS = (STREAK_FLIP_Y != 0) ? -1.0 : 1.0; // texture v -> glass v (up) + vec3 wsUp = vec3(0.0, 1.0, 0.0) * mat3(inv_view); // world up, view space + vec3 wsAir = rain_wind.xyz * mat3(inv_view); // the air against the vehicle, view space, m/s + vec3 wsN = (dot(Ngl, f_pos.xyz) < 0.0) ? -Ngl : Ngl; // the outside of the glass + vec3 wsGrav = -wsUp - wsN * dot(-wsUp, wsN); // the weight along the glass + vec3 wsRise = wsUp - wsN * dot(wsUp, wsN); + wsRise = (length(wsRise) > 0.1) ? normalize(wsRise) : vec3(0.0); + vec3 wsFlow = wsAir - wsN * dot(wsAir, wsN) + wsRise * (max(-dot(wsAir, wsN), 0.0) * WS_HEAD_ON); + float wsDrag = dot(wsFlow, wsFlow) / (WS_DRAG_SPEED * WS_DRAG_SPEED) * wind_drag_gain; // in units of the weight + vec3 wsFlowDir = (length(wsFlow) > 1e-3) ? normalize(wsFlow) : vec3(0.0); + vec3 wsPush = wsGrav + wsFlowDir * wsDrag; + // to the glass UV (v up) through the tangent frame of the texture + vec2 gravG = vec2(dot(wsGrav, Tgl), dot(wsGrav, Bgl) * flipS); + vec2 flowG = vec2(dot(wsFlowDir, Tgl), dot(wsFlowDir, Bgl) * flipS); + float wsSpeed = smoothstep(0.3, 1.2, wsDrag); // 0 standing still .. 1 at speed (haze, drops) + wsWindShare = smoothstep(0.5, 1.3, wsDrag); // how much the air drives the rivulets + if (wsWindShare > 0.0) + { + // the rivulets of the air run along the push of the air at twice the weight: the same way at any speed (they don't swing + // round as the train speeds up), up a front glass, back and down a side window + vec2 way = gravG + flowG * 2.0; + if (dot(way, way) > 1e-8) + { + way = normalize(way); + float turn = round(atan(way.x, -way.y) / WS_WIND_STEP) * WS_WIND_STEP; + wsWindCos = cos(turn); + wsWindSin = sin(turn); + } + else + wsWindShare = 0.0; + } + // the push of the air on the drops, texture UV (for stretching them) + vec2 wsPushT = vec2(dot(wsPush, Tgl), dot(wsPush, Bgl)); + wsPushT = (dot(wsPushT, wsPushT) > 1e-10) ? normalize(wsPushT) : vec2(0.0, -1.0); + // 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); - rw_wipe_s wipe = rw_wipe(mask); - rw_since = wipe.since; - // the blades went lately (any of them, also where none of them reaches) - float working = 0.0; - for (int i = 0; i < 4; ++i) - working = max(working, 1.0 - smoothstep(4.0, 30.0, time - wiper_timer_return[i])); - // how much of the water the place gathers it has - float gathered = 1.0 - exp(-rw_since / (6.0 * rw_period)); - // the film a blade leaves is drawn into fine streaks along its arcs, each a thin cylindrical lens which draws a light seen - // through it into a line across the streaks, towards the pivot of the blade: the way across the streaks on the screen - vec2 streakway = vec2(0.0); - if ((working > 0.0) && (false == snow) && (abs(det) > 1e-14)) - { - int blade = 0; - for (int i = 1; i < 4; ++i) - blade = (mask[i] > mask[blade]) ? i : blade; - if (mask[blade] >= 0.001) - { - // the mask grows along the arcs; a step of a centimetre, so the steps of its values don't matter - float mu = textureLod(wipermask, f_coord + maskstep * vec2(0.01, 0.0), 0.0)[blade]; - float mv = textureLod(wipermask, f_coord + maskstep * vec2(0.0, 0.01), 0.0)[blade]; - vec2 arc = vec2(mu, mv) - mask[blade]; - vec2 onscreen = inverse(steps) * vec2(-arc.y, arc.x); - if ((length(arc) > 1e-4) && (length(onscreen) > 1e-9)) - streakway = normalize(onscreen); - } - } - vec3 ripple = rw_noise2(glass / (0.006 * rw_scale), 5u); + // ---- rivulet cell of this pixel (also used to sweep the drops) ---- + wsSetLayer(0); + float sCW = streak_cell / gridSize; + float sCH = streak_run / gridSize; + vec2 sUVg = vec2(f_coord.x, (STREAK_FLIP_Y != 0) ? 1.0 - f_coord.y : f_coord.y); // glass UV, v up + vec2 sCell = floor(sUVg / vec2(sCW, sCH)); + Riv rivP = getRiv(sCell, sCW, sCH, gridSize); + bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0); - // the water a blade pushes: a bead in front of it while it moves, as wide as the water it gathered on its way, with a steep - // lumpy front (its edge shows dark, the view can't get out there). the drops the bead reaches flow into it - vec3 lumps = rw_noise2(glass / (0.009 * rw_scale), 7u); - float gatheredwater = snow ? 0.0 : min(gathered * 1.5, 1.0) * (0.35 + 0.65 * min(wipe.swept * 2.5, 1.0)); - float reach = 0.004 + 0.018 * gatheredwater + 0.008 * (ripple.x - 0.5); - float ridge = gatheredwater * smoothstep(0.0, 0.003, wipe.front) * (1.0 - smoothstep(reach - 0.004, reach, wipe.front)); - // the smooth shape from how it changes from pixel to pixel, the lumps on it as they are - float pooledbase = 0.004 * ridge; - float pooled = pooledbase * (0.75 + 0.5 * lumps.x); - vec3 pooledslope = rw_gradient(pooledbase, dpdx, dpdy, outward) * (0.75 + 0.5 * lumps.x) + rw_along(lumps.yz * (0.5 * pooledbase / (0.009 * rw_scale))); - if ((pooled > 0.0) && (false == simulated)) - { - rw_sheet(pooled, pooledslope, 0.03, smoothstep(0.0, 0.1, ridge)); - if (ridge > 0.05) - rw_cleared = time; - } + if (rain_params.x > 0.001) + { + // =================================================================== + // 1. drops from the atlas: this cell and its 8 neighbours + // =================================================================== + vec2 cell = floor(rainCoord * gridSize); + for (int oy = -1; oy <= 1; oy++) + for (int ox = -1; ox <= 1; ox++) + { + vec2 nc = cell + vec2(ox, oy); + uvec2 key = cellKey(nc); + // life cycle of this cell: a new drop every lifeLen seconds + uint s0 = Hash(uvec3(key, 23u)); + float lifeLen = mix(drop_life_min, drop_life_max, RandF(s0)); + float tt = time / lifeLen + RandF(s0); + float epoch = floor(tt); + float ph = tt - epoch; + uint ep = uint(mod(epoch, 65521.0)); + // activation first (cheap), the wiper texture only for live drops + uint s1 = Hash(uvec3(key, ep * 4u + 1u)); + if (RandF(s1) > rain_params.x * drop_density) + continue; + float side; + float mixF = GetMixFactor((nc + 0.5) / gridSize, side); + uint s2 = Hash(uvec3(key, ep * 4u + 2u + uint(side) * 2u)); + if (mixF < RandF(s2)) + continue; - float snowcover = 0.0; - float wet = 0.0; - if (simulated) - { - // the directions along the glass, view space - vec3 upview = vec3(0.0, 1.0, 0.0) * mat3(inv_view); - vec3 downview = -(upview - outward * dot(upview, outward)); - downview = (length(downview) > 0.05) ? normalize(downview) : normalize(cross(outward, normalize(rw_tu))); - vec3 sideview = cross(outward, downview); - rw_simulated(uint(slot), f_coord, puv, downview, sideview, snowcover, wet); - // the paths the water went along lately: a rivulet, a band of water rounded across (a cylinder lens: it holds a picture of - // the place around it turned over across the band, its edges dark as the edges of drops), thicker the fresher. the - // smoothed freshness falls off from the middle of a path to its edges - if (trail > 0.08) - { - float p = clamp((trail - 0.08) / 0.5, 0.0, 1.0); - float thickness = 0.0005 * (1.0 - (1.0 - p) * (1.0 - p)); - vec3 rise = trailslope * (0.0005 * 2.0 * (1.0 - p) / 0.5); - float steep = length(rise); - if (steep > 0.7) - rise *= 0.7 / steep; - bool top = thickness > rw_height; - rw_sheet(thickness, rise, 0.004, smoothstep(0.0, 0.15, p) * 0.95); - // from the middle of the band to the fragment - float across = length(trailslope) / 0.5; - if (top && (across > 1.0)) - rw_offset = -trailslope * ((1.0 - p) / (across * length(trailslope))); - } - } - else if (false == snow) - { - // the drops which grew big enough slide off, with gravity and the air: a set of tracks for each of the directions of the - // push nearest to the one now, each laid along its own way, so none of them moves when the push turns - float sliding = smoothstep(0.25, 0.6, rw_push); - if (sliding > 0.0) - { - float bin = atan(force.y, force.x) / (RW_PI / 6.0); - float lower = floor(bin); - for (int k = 0; k < 2; ++k) - { - float share = ((k == 0) ? 1.0 - (bin - lower) : bin - lower) * sliding; - if (share < 0.02) - continue; - float angle = (lower + float(k)) * (RW_PI / 6.0); - vec2 down = vec2(cos(angle), sin(angle)); - vec2 side = vec2(-down.y, down.x); - rw_sliders(vec2(dot(glass, side), -dot(glass, down)), side, down, uint(int(lower) + k + 64) * 2u + 16u, share); - } - } + vec2 center = (nc + vec2(RandF(s2), RandF(s2))) / gridSize; + float size = mix(drop_size_min, drop_size_max, pow(RandF(s2), drop_size_bias)) / gridSize; + float sag = 1.0 + drop_sag * RandF(s2); + float flipX = (RandF(s2) < 0.5) ? 1.0 : 0.0; + float choice = RandF(s2); + // at speed the air stretches the drop along its push (1 standing still: the drop as it always was) + float stretch = 1.0 + drop_wind_stretch * wsSpeed * RandF(s2); + mat2 shapeM = mat2(1.0, 0.0, 0.0, 1.0 / sag) + * (mat2(1.0) + (1.0 / stretch - 1.0) * outerProduct(wsPushT, wsPushT)); - // the drops as they land, each time somewhere else in its cell, as often as the rain hits the glass: the drops of the - // rain spread on the glass, thrown with a fine splash which runs back into them - // each drop anywhere in its cell, the cell as large as a drop with its splash reaches - float cell = 0.007 * rw_scale; - vec2 laid = rw_turn(glass, 0.61) + vec2(0.31, 0.17); - ivec2 home = ivec2(floor(laid / cell)); - float density = mix(0.08, 0.3, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 1u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 1u, 1u); - float span = rw_period * mix(0.7, 1.3, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.5, 0.9, b.y); - if ((age > life) || (age > rw_since) || (time - age < rw_cleared)) - continue; - vec4 p = rw_random(c, 2u, uint(cycle)); - vec2 offset = rw_turn(laid - (vec2(c) + p.xy) * cell, -0.61); - float visible = mix(0.0011, 0.0019, b.z) * rw_scale; - // a raindrop hits the glass far above the speed at which it splashes (Weber number in the hundreds and thousands): - // it spreads, throws a spray of droplets which stay on the glass around it, and draws back - float splash = exp(-age / 0.06); - float fade = 1.0 - smoothstep(life - min(0.4, 0.3 * life), life, age); - if (visible * 0.3 > 0.5 * rw_pixel) - { - int spray = 3 + int(p.z * 4.0); - for (int s = 0; s < spray; ++s) - { - vec4 e = rw_random(c, 3u, uint(cycle) * 8u + uint(s)); - vec2 way = normalize(vec2(cos(e.x * 6.2831853), sin(e.x * 6.2831853)) + rw_flow * 0.9); - rw_blob(offset - way * (visible * (1.4 + 1.6 * e.y)), visible * mix(0.18, 0.35, e.z), fade * (0.55 + 0.45 * splash)); - } - } - rw_drop(offset, visible * (1.0 + 0.3 * splash), fade, p.wzyx); - } - } - // the drops the landing ones gathered into, growing until they are big enough to slide (the air blows them off sooner) - cell = 0.011 * rw_scale; - laid = rw_turn(glass, 1.07) + vec2(0.53, 0.29); - home = ivec2(floor(laid / cell)); - density = mix(0.55, 1.0, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 4u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 4u, 1u); - float span = rw_period * mix(2.5, 4.0, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.75, 0.98, b.y) / (1.0 + 2.0 * max(rw_push - 1.0, 0.0)); - if ((age > life) || (age > rw_since) || (time - age < rw_cleared)) - continue; - vec4 p = rw_random(c, 5u, uint(cycle)); - // the big drops are much alike: they grow as they gather the small ones (the radius in step with the time) up to the - // size at which they slide off (on a vertical glass a footprint of about 9 mm, larger on a glass leaning back, smaller - // in a strong air flow), and go - float slides = min(0.0045 / sqrt(max(rw_push, 0.3)), 0.005); - float visible = slides * mix(0.6, 1.0, b.z) * rw_scale * mix(0.35, 1.0, clamp(age / (0.6 * life), 0.0, 1.0)); - rw_drop(rw_turn(laid - (vec2(c) + p.xy) * cell, -1.07), visible, 1.0 - smoothstep(life - min(0.5, 0.3 * life), life, age), p.zwxy); - } - } + float appearF = drop_appear / lifeLen; + float fadeF = drop_fade / lifeLen; + float vis = smoothstep(0.0, appearF, ph) * (1.0 - smoothstep(1.0 - fadeF, 1.0, ph)); + float sq = size * mix(0.8, 1.0, smoothstep(0.0, 2.0 * appearF, ph)); // spreads out as it lands - // the water the blades push out of their sweep: a broken row of drops flowed together along its edge, just outside it - float leave = working * min(heavy * 1.5, 1.0); - if ((leave > 0.0) && rw_border(f_coord, 0.009 * rw_scale, maskstep)) - { - cell = 0.0065 * rw_scale; - laid = rw_turn(glass, 0.29) + vec2(0.11, 0.43); - home = ivec2(floor(laid / cell)); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 20u, 0u); - if (a.x > 0.85) - continue; - // from the fragment to the middle of the drop, along the glass - vec2 centre = rw_turn((vec2(c) + a.yz) * cell - laid, -0.29); - float rim = rw_rim(f_coord + maskstep * centre, 0.004 * rw_scale, maskstep) * leave; - if (rim <= 0.05) - continue; - rw_drop(-centre, mix(0.0016, 0.003, a.w) * rw_scale * mix(0.6, 1.0, rim), smoothstep(0.05, 0.35, rim), rw_random(c, 21u, 0u)); - } - } - } + vec2 diff = rainCoord - center; + vec2 dl = shapeM * diff; + if (max(abs(dl.x), abs(dl.y)) >= sq * 0.5) + continue; - // the streams running down from the water the blades leave at the ends of their sweep: a stream in some of the columns - // along the way down, where up the glass there is such water, as far down as the water had time to run since the blade - // went over the place - if ((working > 0.0) && (length(fallway) > 0.3)) - { - vec2 side = vec2(-rw_down.y, rw_down.x); - float width = 0.035 * rw_scale; - float across = dot(glass, side); - float along = -dot(glass, rw_down); - int column = int(floor(across / width)); - vec4 a = rw_random(ivec2(column, 0), 30u, 0u); - if (a.x < 0.6 * heavy * working) - { - float lateral = across - rw_path(column, along, width, 31u); - float half_width = mix(0.0006, 0.0012, a.z) * rw_scale * (0.6 + 0.8 * rw_noise(along / (0.006 * rw_scale), 32u)); - if (abs(lateral) < 2.0 * half_width + rw_pixel) - { - // up the glass, the first place where the reach of the blades begins or ends - const float reach[6] = float[](0.01, 0.025, 0.05, 0.1, 0.18, 0.3); - bool here = rw_reached(f_coord); - float source = -1.0; - for (int s = 0; s < 6; ++s) - { - if (rw_reached(f_coord + maskstep * (-rw_down * reach[s])) != here) - { - source = reach[s]; - break; - } - } - if ((source > 0.0) && (source < max(rw_since - 0.1, 0.0) * 0.2)) - { - float beads = rw_noise(along / (0.004 * rw_scale), 33u); - float flowing = working * (1.0 - 0.5 * smoothstep(0.15, 0.3, source)); - rw_blob(side * lateral, half_width, flowing * mix(0.6, 1.2, beads)); - } - } - } - } - } - else - { - // the flakes stick where they land and melt into drops: the glass is warmed by the cab, faster in the air above zero - float warm = rain_params.w; - float cell = 0.016 * rw_scale; - vec2 laid = rw_turn(glass, 0.83) + vec2(0.07, 0.61); - ivec2 home = ivec2(floor(laid / cell)); - float density = mix(0.5, 0.9, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 11u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 11u, 1u); - float span = rw_period * mix(0.7, 1.3, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.6, 0.95, b.y); - if ((age > life) || (age > rw_since)) - continue; - vec4 p = rw_random(c, 12u, uint(cycle)); - vec2 offset = rw_turn(laid - (vec2(c) + p.xy) * cell, -0.83); - float diameter = mix(RW_SNOW_DIAMETER.x, RW_SNOW_DIAMETER.y, b.z) * rw_scale; - float melt = ((warm > 0.5) ? mix(3.0, 10.0, b.w) / (1.0 + 0.25 * warm) : mix(15.0, 45.0, b.w)); - if (age < melt) - { - float m = age / melt; - float dist = length(offset.x * rw_tu + offset.y * rw_tv); - float radius = 0.5 * diameter; - if (dist < radius + rw_pixel) - { - float angle = atan(offset.y, offset.x); - float lobes = 0.55 + 0.45 * (0.6 * rw_noise(angle * 1.9 + p.z * 40.0, 13u) + 0.4 * abs(cos(3.0 * angle + p.w * 6.2831853))); - float rim = radius * lobes * (1.0 - 0.45 * m); - float body = smoothstep(rim + rw_pixel, 0.55 * rim - rw_pixel, dist); - float lace = rw_noise2(glass / (0.0007 * rw_scale) + p.zw * 100.0, 14u).x; - float flake = body * mix(0.55, 1.0, lace) * (1.0 - 0.7 * m * m); - snowcover = 1.0 - (1.0 - snowcover) * (1.0 - flake); - wet = max(wet, m * body); - } - } - else - { - // the water of the flake - rw_drop(offset, 0.0018 * pow(diameter / 0.008, 0.667) * rw_scale, 1.0 - smoothstep(life - min(0.5, 0.3 * life), life, age), p.wzyx); - } - } - } - // the snow the blades push in front of them and leave at the ends of their sweep - float pile = max(wipe.ahead * min(gathered * 2.0, 1.0) * (0.4 + 0.6 * min(wipe.swept * 2.5, 1.0)), rw_rim(f_coord, 0.006 * rw_scale, maskstep) * working * heavy); - float packed = rw_noise2(glass / (0.0015 * rw_scale), 15u).x; - snowcover = max(snowcover, smoothstep(0.15, 0.5, pile * 1.2 + 0.4 * (ripple.x - 0.5)) * mix(0.7, 1.0, packed)); - } - // untreated glass, weathered and a little dirty: flat drops (a rain repellent coating would give beads above 90 degrees) - rw_settle(radians(mix(30.0, 48.0, rw_noise2(glass / (0.005 * rw_scale), 16u).x))); + if (sweepOn) + { + vec2 cg = vec2(center.x, (STREAK_FLIP_Y != 0) ? 1.0 - center.y : center.y); + vis *= wsKept(cg, 0.35 * sq, rivP, sCell, sCW, sCH, gridSize); + } + if (vis <= 0.001) + continue; - // the lamps (of the cab, of the scenery) and the headlights light the water up, from both sides of the glass (worked out - // here, where the fragments of a quad go together) - vec3 lamps = vec3(0.0); - vec3 lampgloss = vec3(0.0); - add_local_lights(outward, lamps, lampgloss); - add_local_lights(-outward, lamps, lampgloss); + vec2 luv = dl / sq + 0.5; + if (flipX > 0.5) luv.x = 1.0 - luv.x; + float atlasTexels = float(textureSize(normalmap, 0).x); + float quadPx = sq / max(uvPerPx, 1e-6); + float nlod = clamp(log2(max(0.25 * atlasTexels / max(quadPx, 1.0), 1.0)), 0.0, 6.0); + vec4 nm = textureLod(normalmap, dropAtlasUV(choice, luv), nlod); + float cov = smoothstep(0.1, 0.6, nm.a) * vis; + if (cov <= 0.001) + continue; + vec2 nxy = nm.rg * 2.0 - 1.0; + if (flipX > 0.5) nxy.x = -nxy.x; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec2 slope = transpose(shapeM) * (-nxy / max(nz, 0.08)); + vec3 n = normalize(vec3(-slope, 1.0)); + // gradients of the tile UV (for the one atlas read after the loop) + vec2 gx = (shapeM * duv1) / sq * vec2(0.25, 0.5); + vec2 gy = (shapeM * duv2) / sq * vec2(0.25, 0.5); + consider(hit, cov * (nm.b * sq * sag + 1e-5), cov, 0.0, n, diff, 0.5 * sq, 1.0, + vis, dropAtlasUV(choice, luv), gx, gy, 1.0, 0.0); + } - // the film just behind a blade, breaking up - float film = snow ? 0.0 : heavy * exp(-rw_since / 0.8) * smoothstep(0.02, 0.08, rw_since); - if (film > 0.01) - { - vec3 fine = rw_noise2(glass / (0.0021 * rw_scale), 6u); - vec2 tilt = fine.yz * (0.004 * film); - rw_sheet(0.00005 * film, rw_along(tilt), 0.3, 0.8 * film); - } + // =================================================================== + // 2. micro droplets: procedural, one per micro cell, fully inside it + // =================================================================== + if (micro_density > 0.0) + { + float mg = gridSize * micro_scale; + vec2 mc = floor(rainCoord * mg); + uvec2 mk = cellKey(mc); + uint m0 = Hash(uvec3(mk, 51u)); + float mLife = micro_life * mix(0.6, 1.6, RandF(m0)); + float mtt = time / mLife + RandF(m0); + float mph = fract(mtt); + uint mep = uint(mod(floor(mtt), 65521.0)); + uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); + if (RandF(m1) < rain_params.x * micro_density) + { + uint m2 = Hash(uvec3(mk, mep * 4u + 2u + uint(hazeSide) * 2u)); + if (wipeVis >= RandF(m2)) + { + float r = mix(micro_size_min, micro_size_max, pow(RandF(m2), 1.5)); + vec2 c = mc + vec2(r) + vec2(RandF(m2), RandF(m2)) * max(1.0 - 2.0 * r, 0.0); + float ell = mix(0.85, 1.15, RandF(m2)); + vec2 p = (rainCoord * mg - c) / r; + p.x *= ell; + float d2 = dot(p, p); + if (d2 < 1.0) + { + float vis = smoothstep(0.0, 0.01, mph) * (1.0 - smoothstep(0.97, 1.0, mph)); + if (sweepOn) + { + vec2 cu = c / mg; + vec2 cg = vec2(cu.x, (STREAK_FLIP_Y != 0) ? 1.0 - cu.y : cu.y); + vis *= wsKept(cg, r / mg, rivP, sCell, sCW, sCH, gridSize); + } + float d = sqrt(d2); + float cov = smoothstep(1.0, 0.8, d) * vis; + if (cov > 0.001) + { + vec2 nxy = p * micro_bulge; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec3 n = normalize(vec3(nxy, nz)); + float h = sqrt(1.0 - d2) * micro_bulge * (r / mg); + float rim = smoothstep(drop_rim_start, drop_rim_end, 1.0 - n.z); + float lt = dot(n, DROP_LIGHT) * drop_light_side * 0.5 + (1.0 - drop_light_side * 0.5); + consider(hit, cov * (h + 1e-6), cov, smoothstep(1.0, 0.9, d) * vis, n, + rainCoord - c / mg, r / mg, 1.0, + vis, vec2(0.0), vec2(0.0), vec2(0.0), 0.0, clamp(rim * lt, 0.0, 1.0)); + } + } + } + } + } - // what the water shows: the view goes through the glass (a plate: only the way from the air into the water counts) and out - // through the surface of the water, bent as much as it is curved. it is the world turned upside down in a drop, and the - // edges of a drop, where the view can't get out (total internal reflection), show the inside of the cab - float background = 0.0; - bool image = ssr_params.x >= 1.0; - if (image) - { - ivec2 size = textureSize(scene_depth, 0); - float depth = texelFetch(scene_depth, clamp(ivec2(gl_FragCoord.xy), ivec2(0), size - 1), 0).r; - if (depth > 0.0) - background = (projection[3][2] / depth) / max(-view.z, 0.05); - } - vec3 inside = ambient * (AMBIENT_SCALE * 0.5); - vec4 water = vec4(0.0); - if (rw_cover > 0.0) - { - vec3 surface = normalize(outward - rw_slope); - vec3 inwater = refract(view, -outward, 1.0 / RW_IOR); - vec3 through = refract(inwater, -surface, RW_IOR); - // what the surface reflects back inside the water: the light which came in at the other side of the drop, from the sky, - // and the inside of the cab. where the view can't get out (the edge of a drop) that is all it shows: a bright edge - vec3 bounced = reflect(inwater, surface); - if (dot(bounced, outward) < 0.0) - bounced = reflect(bounced, outward); - vec3 inner = mix(inside, rw_surroundings(normalize(bounced), 5.0), 0.3); - vec3 color = inner; - if (dot(through, through) > 0.5) - { - float fresnel = 0.02 + 0.98 * pow(1.0 - abs(dot(through, surface)), 5.0); - // the view through the water spreads over this much of the world across a pixel (radians) - float spread = (RW_IOR - 1.0) * rw_pixel / max(rw_curve, 1e-4); - // the picture the drop holds as a lens, and a share of the bending by the surface - vec3 lens = normalize(f_pos.xyz - (1.0 + RW_LENS) * rw_offset) + (through - view) * RW_LENS_BEND; - float lod = mix(log2(1.0 + RW_LENS) - 0.5, log2(max(spread / pixelangle, 1.0)), RW_LENS_BEND); - // a drop a few pixels across would hold a picture of single pixels, a grain: blurred more the smaller it looks - lod += clamp(2.5 - log2(max(rw_curve / rw_pixel, 1.0)), 0.0, 1.5); - float share; - vec3 seen = rw_behind(normalize(lens), lod, background, share); - // the sun through the drop, where the image doesn't hold it: as bright as the drop gathers its light. in heavier rain - // the sun is behind the clouds, its disc is not there to be focused - float sunshare = (1.0 - heavy) * (1.0 - heavy); - if ((lights_count > 0U) && (share < 1.0) && (sunshare > 0.01)) - { - vec3 sun = normalize(-lights[0].dir); - float width = max(spread, 0.03); - float off = acos(clamp(dot(through, sun), -1.0, 1.0)); - if (off < 4.0 * width) - { - float lit = 1.0 - clamp(calc_shadow(), 0.0, 1.0); - vec3 sunlight = lights[0].color * (SUN_DIFFUSE_SCALE * lights[0].intensity * cloud_shadow(mat3(inv_view) * f_pos.xyz)); - // the light of the sun over the spread of the view: a pixel shows pi * irradiance * the share of a steradian - seen += sunlight * (sunshare * lit * (1.0 - share) * exp(-0.5 * off * off / (width * width)) / (2.0 * width * width)); - } - } - color = mix(seen, inner, fresnel); - } - color += lamps * 0.6; - // without the image of the last frame the surroundings stand for what the water bends the view to; nearly flat water - // would show them in place of the scene behind it, so it is left mostly clear - float opaque = image ? 1.0 : mix(0.3, 1.0, smoothstep(0.02, 0.15, 1.0 - dot(through, view))); - water = vec4(color, rw_cover * opaque); - } - // the wet glass where the rain gathers is a little hazy: the tiniest drops spread the light - if (image && (false == snow)) - { - float mist = heavy * gathered * (simulated ? 0.18 : 0.3); - if (mist > 0.01) - { - float share; - vec3 hazy = rw_behind_edges(view, 3.5, background, share, false); - // the tiniest drops spread the light of the sky coming through the glass - hazy = mix(hazy, rw_surroundings(outward, 7.0), 0.1); - layer = vec4(hazy, mist * max(share, 0.5)); - } - } - layer = rw_over(water, layer); - // the lights seen through the streaks of the film the blades leave, drawn into lines towards their pivot - if (image && (length(streakway) > 0.5)) - { - vec4 previous = ssr_reprojection * ((background > 0.0) ? vec4(view * background, 1.0) : vec4(view, 0.0)); - if (previous.w > 1e-5) - { - vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; - vec2 texel = 1.0 / vec2(textureSize(ssr_history, 0)); - ivec2 size = textureSize(scene_depth, 0); - float near = projection[3][2]; - // a light: much brighter than the place around it (the bright sky is not) - vec3 around = textureLod(ssr_history, clamp(coords, vec2(0.0), vec2(1.0)), 6.0).rgb; - float threshold = max(1.0, 3.0 * max(around.r, max(around.g, around.b))); - vec3 glare = vec3(0.0); - float total = 0.0; - for (int k = -8; k <= 8; ++k) - { - if (k == 0) - continue; - float w = 1.0 - abs(float(k)) / 9.0; - total += w; - vec2 tap = coords + streakway * texel * (float(k) * 5.0); - if (any(lessThan(tap, vec2(0.0))) || any(greaterThan(tap, vec2(1.0)))) - continue; - // only what is outside: the lamps of the cab are not behind the glass - float depth = texelFetch(scene_depth, clamp(ivec2(tap * vec2(size)), ivec2(0), size - 1), 0).r; - if ((depth > 0.0) && (near / depth < -f_pos.z + 2.5)) - continue; - vec3 c = textureLod(ssr_history, tap, 1.5).rgb; - if (any(isnan(c)) || any(isinf(c))) - continue; - glare += max(c - vec3(threshold), vec3(0.0)) * w; - } - glare *= 0.6 * heavy * working / total; - if (any(greaterThan(glare, vec3(1e-4)))) - { - // the scene itself under the water carries the light added (it changes nothing seen) - vec3 scene = textureLod(ssr_history, clamp(coords, vec2(0.0), vec2(1.0)), 0.0).rgb; - layer = rw_over(layer, vec4(max(scene, vec3(0.0)), 0.2)); - layer.rgb += glare / layer.a; - } - } - } - if (snowcover > 0.0) - { - // the flakes are lit through from the outside, by the sky and the sun, and from the inside of the cab; melting they turn - // grey and clear - vec3 outside = rw_surroundings(outward, 6.0); - if (lights_count > 0U) - { - vec3 sun = normalize(-lights[0].dir); - outside += lights[0].color * (SUN_DIFFUSE_SCALE * lights[0].intensity * max(dot(outward, sun), 0.0) * (1.0 - clamp(calc_shadow(), 0.0, 1.0))); - } - vec3 flake = mix(vec3(0.92), vec3(0.62, 0.66, 0.7), wet); - vec3 color = flake * (outside * (0.35 * (1.0 - 0.5 * wet)) + ambient * (AMBIENT_SCALE * 0.7)); - layer = rw_over(vec4(color, snowcover * mix(0.97, 0.6, wet)), layer); - } - } - out_color = layer; + // =================================================================== + // 3. rivulets of this pixel's cells: the layer of gravity and, at speed, the one of the air + // =================================================================== + wsSetLayer(0); + drawRivulet(hit, rivP, sUVg, wsRd1, wsRd2); + if (wsWindShare > 0.001) + { + for (int wl = 1; wl <= wind_layers; ++wl) + { + vec2 wc = vec2(sCW * wind_cell_scale, sCH * ((wl == wind_layers) && (wl > 1) ? wind_long_run : wind_run_scale)); + wsSetLayer(wl); + // every further layer: its cells shifted aside, drops of its own + vec2 sUVw = wsToLayer(sUVg) + fract(vec2(0.5, 0.618) * float(wl - 1)) * wc; + Riv rivW = getRiv(floor(sUVw / wc), wc.x, wc.y, gridSize); + drawRivulet(hit, rivW, sUVw, wsToLayerDir(wsRd1), wsToLayerDir(wsRd2)); + } + wsSetLayer(0); + } + } - { // Overlay windshield texture with alpha - vec3 fragcolor = ambient; - vec3 fragnormal = normalize(f_normal); - float reflectivity = param[1].z; - float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5; - legacy_gloss(); + // ----------------------------------------------------------------------- + // Shading of the winning dome + // ----------------------------------------------------------------------- + float coverA = clamp(hit.cov, 0.0, 1.0); + vec3 dropLayer = vec3(0.0); + float alphaOut = 0.0; + vec3 dropGlint = vec3(0.0); + vec2 lensBend = vec2(0.0); + float lensK = 0.0; // drops: how much the lens shrinks the picture + float lensRadPx = 1.0e4; // drops: radius on screen, pixels + if (coverA > 0.001) + { + vec3 Nt = hit.n; + // look of the drop: grey atlas (bright rim, dark middle) for drops and rivulets, analytic for droplets + vec3 rgb; + float colA; + if (hit.atlas > 0.5) + { + vec4 at = textureGrad(raindropsatlas, hit.auv, hit.agx, hit.agy); + rgb = at.rgb; + colA = smoothstep(0.3, 0.9, at.a) * hit.vis; + } + else + { + rgb = vec3(hit.shade); + colA = hit.colA; + } + float a = colA * mix(drop_center_alpha, drop_rim_alpha, smoothstep(0.1, 0.3, length(rgb))); + dropLayer = rgb * dynBright * a; + alphaOut = clamp(a, 0.0, 1.0); - fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(fragcolor, tex_color.a * alpha_mult); + // refraction: Snell for rivulets (and as a fallback), lens picture for drops + vec3 I = normalize(f_pos.xyz); + vec3 No = (dot(Ngl, I) > 0.0) ? Ngl : -Ngl; + vec3 Nd = normalize(Tgl * Nt.x + Bgl * Nt.y + No * Nt.z); + vec3 R = refract(I, -Nd, drop_ior); + if (dot(R, R) < 1e-4) + R = refract(I, -Nd, 1.0 + 0.5 * (drop_ior - 1.0)); + vec2 dSlope = vec2(0.0); + if (dot(R, R) > 1e-4 && R.z < -0.05) + dSlope = R.xy / (-R.z) - I.xy / (-I.z); + vec2 snellBend = clamp(-(dSlope * pxPerSlope * drop_refract) / WS_REFR_MAXPX, vec2(-1.0), vec2(1.0)); + lensBend = snellBend; + if (hit.isDrop > 0.5 && drop_lens_mix > 0.0) + { + vec2 offPx = Jinv * hit.offUV; // pixel - drop centre, in screen pixels + float radPx = hit.radUV / max(uvPerPx, 1e-6); + float k = clamp(min(drop_lens, 0.95 * WS_REFR_MAXPX / max(radPx, 1.0) - 1.0), 0.0, drop_lens); + vec2 lb = clamp((1.0 + k) * offPx / WS_REFR_MAXPX, vec2(-1.0), vec2(1.0)); + lensBend = mix(snellBend, lb, drop_lens_mix); + lensK = k; + lensRadPx = radPx; + } - out_color.xyz = apply_fog(mix(out_color.xyz, color.xyz, color.a)); - out_color.a = mix(out_color.a, 1., color.a); - } - if (false == POSTFX_ENABLED) - { - out_color = tonemap(out_color); - } + vec3 Rd = (dot(R, R) > 1e-4) ? normalize(R) : I; + vec3 glint = vec3(0.0); + if (lights_count > 0U) + { + float cosS = max(dot(Rd, normalize(-lights[0].dir)), 0.0); + float lobe = pow(cosS, drop_glint_sharpness) * drop_glint_strength + + pow(cosS, 0.2 * drop_glint_sharpness) * drop_sheen; + // the shadow (shadow map + GL 4.6 contact shadow ray) only where the sun shows in the drop at all + if (lobe > 1e-4) + { + float shadowSun = 0.0; + if (shadow_tone < 1.0) + shadowSun = (1.0 - shadow_tone) * clamp(calc_shadow(), 0.0, 1.0); + // GL 4.6: the clouds hold the sun back where their shadow falls (as in apply_lights) + float cloudSun = cloud_shadow(mat3(inv_view) * f_pos.xyz); + glint += lights[0].color * lights[0].intensity * lobe * (1.0 - shadowSun) * cloudSun * wsNight; + } + } + // GL 4.6: headlights and lamps come from the light cluster of the fragment (lights_clustered), or are the + // first lights_count - 1 headlights otherwise. calc_headlights takes the screen-space change of f_pos + // (worked out at the top of main, in uniform flow). The drop scatters light from both sides of the glass, + // so the glass normal is turned towards the light. + // only the lights outside the glass and a few metres away light the drops up (signals, lamps of the station, the + // headlights of other trains): the lamps and the headlights of the own vehicle, a metre or two from the glass, would + // make every drop glow white + vec3 lamps = vec3(0.0); + if (lights_clustered != 0U) + { + cluster_range_s range = cluster_ranges[fragment_cluster()]; + for (uint i = 0U; i < range.count; i++) + { + light_s lt = lights[cluster_light_indices[range.offset + i]]; + vec3 toL = lt.pos - f_pos.xyz; + float away = smoothstep(0.0, 0.2, dot(toL, wsN) / max(length(toL), 1e-4)) + * smoothstep(drop_light_near, 2.0 * drop_light_near, length(toL)); + if (away <= 0.0) + continue; + vec3 nl = (dot(Ngl, toL) > 0.0) ? Ngl : -Ngl; + if (lt.type == LIGHT_HEADLIGHTS) + lamps += lt.color * calc_headlights(lt, nl, dp1, dp2).x * lt.intensity * drop_headlight_scatter * away; + else if (drop_lamp_scatter > 0.0) + lamps += lt.color * calc_local_light(lt, nl).x * lt.intensity * drop_lamp_scatter * away; + } + } + else + { + for (uint i = 1U; i < lights_count; i++) + { + light_s lt = lights[i]; + vec3 toL = lt.pos - f_pos.xyz; + float away = smoothstep(0.0, 0.2, dot(toL, wsN) / max(length(toL), 1e-4)) + * smoothstep(drop_light_near, 2.0 * drop_light_near, length(toL)); + if (away <= 0.0) + continue; + vec3 nl = (dot(Ngl, toL) > 0.0) ? Ngl : -Ngl; + lamps += lt.color * calc_headlights(lt, nl, dp1, dp2).x * lt.intensity * drop_headlight_scatter * away; + } + } + glint += min(lamps, vec3(drop_light_max)); + // reflection of the surroundings on the dome: straight from the environment map. (It used to go through a + // second apply_lights, which in GL 4.6 also runs the shadow map, the contact shadows and the whole light + // cluster again for every drop pixel; the sun and the lamps are done above already.) + if (drop_env > 0.0) + { + vec3 Nv = -Nd; // dome normal towards the viewer + float NoV = clamp(dot(Nv, -I), 0.0, 1.0); + glint += envmap_color_lod(Nv, 0.8) * EnvBRDFApprox(vec3(0.04), 0.1, NoV) * drop_env * wsNight; + } + dropGlint = glint; + if (!POSTFX_ENABLED) + dropGlint = min(dropGlint, vec3(1.0)); // this path is not tonemapped + } - if (MOTIONBLUR_ENABLED) - { - out_motion = vec4(0.0); - } + // ----------------------------------------------------------------------- + // 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 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) + if (image) + { + ivec2 size = textureSize(scene_depth, 0); + float depth = texelFetch(scene_depth, clamp(ivec2(gl_FragCoord.xy), ivec2(0), size - 1), 0).r; + if (depth > 0.0) + background = (projection[3][2] / depth) / max(-wsView.z, 0.05); + } + vec4 under = vec4(0.0); // the blurred view under the drops (not premultiplied) + vec4 bent = vec4(0.0); // the view bent by the drops, laid over everything (as the old postfx did) + + // the haze is blurred by the post-processing (postfx_taa.frag / postfx_motionblur.frag, rain_windscreen_haze.glsl): the + // picture of this frame can't be read here, and one of the last frame laid over it only shows a milky ghost of the scene + float blurAmt = clamp(hazeWeight * blur_amount, 0.0, 1.0); + + // the drops: the view bent (the picture shift worked out above), and the lights near them. with the motion vectors the + // post-processing bends the picture of this frame (postfx_taa.frag / postfx_motionblur.frag, rain_windscreen_haze.glsl): it has + // the depth of the cab and never pulls the dashboard or the roof into a drop. the image of the last frame is only the fallback + float refrA = smoothstep(0.05, 0.35, coverA) * glassClear * step(glassA, 0.5); + if ((false == MOTIONBLUR_ENABLED) && (refrA > 0.001)) + { + vec2 shiftPx = -lensBend * WS_REFR_MAXPX; // where the drop looks, screen pixels + vec3 dir = normalize(wsView + shiftPx.x * wsDvx + shiftPx.y * wsDvy); + // a drop shows a minified picture: read it from a coarser level (no grain); tiny drops a little blurrier still + float lod = clamp(log2(1.0 + lensK * drop_lens_mix) - 0.5, 0.0, 3.0) + + clamp(2.5 - log2(max(lensRadPx, 1.0)), 0.0, 1.5); + float share; + vec3 seen = wsBehind(dir, lod, background, share, true); + if (image && (WS_LIGHT_GAIN > 0.0)) + seen += wsLightGlow(wsView, background); + // without the image the surroundings stand in: only faintly, they aren't the scene behind + bent = vec4(seen, refrA * WS_REFR_MIX * (image ? 1.0 : 0.3)); + } + + // the drop shading over it + float shadeA = coverA * drop_shade_alpha; + float outA = alphaOut + shadeA * (1.0 - alphaOut); + vec4 drops = vec4(dropLayer, outA); + drops.rgb += dropGlint * coverA / max(outA, 0.05); // the blend multiplies by alpha once more + out_color = wsOver(drops, under); + + { // windshield texture over the rain + vec3 fragcolor = ambient; + // where the glass texture is clear, its lighting is multiplied by ~0 below: skip apply_lights there + if (glassA > 0.002) + { + vec3 fragnormal = normalize(f_normal); + float reflectivity = param[1].z; + float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5; + legacy_gloss(); + fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); + } + vec4 color = vec4(fragcolor, glassA); + out_color.xyz = apply_fog(mix(out_color.xyz, color.xyz, color.a)); + out_color.a = mix(out_color.a, 1., color.a); + } + // the picture in the drops goes over the drop shading and the glass, as the old postfx replaced the pixel with it: the dark + // middle of the atlas only shows through faintly, the rim and the glints a little more + out_color = wsOver(bent, out_color); + if (!POSTFX_ENABLED) + out_color = tonemap(out_color); + + // the velocity target: on the drops the picture shift (x, y = WS_DROP_BIAS + WS_BEND_ENC * bend), on the hazy glass the request + // for the haze (x = WS_ENC * strength, y = 0); elsewhere the velocity of the scene behind the glass stays as it is (alpha 0) + if (MOTIONBLUR_ENABLED) + { + vec4 req = vec4(0.0); + bool drop = (coverA > 0.05 || alphaOut > 0.05) && (glassA < 0.5); + float blurMask = blurAmt * glassClear; + if (drop) + { + vec2 bend = lensBend * smoothstep(0.05, 0.35, coverA); + req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); + } + else 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", 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.)); + + 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; + // out_factor: the blade that clears the cell the most wins. side: which wiper stroke the drops of this + // cell belong to (part of their random seed, so it must not depend on out_factor). + 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]; + have_side = true; + } + } + return out_factor; } diff --git a/shaders/vk14/postfx_motionblur.frag b/shaders/vk14/postfx_motionblur.frag index 12d788008..2bc7d938b 100644 --- a/shaders/vk14/postfx_motionblur.frag +++ b/shaders/vk14/postfx_motionblur.frag @@ -16,12 +16,35 @@ layout(set = POST_SET, binding = POST_TEXTURE_FIRST + 1) uniform sampler2D veloc layout(set = POST_SET, binding = POST_TEXTURE_FIRST + 2) uniform sampler2D depth_tex; +#include "rain_windscreen_haze.glsl" + void main() { + // the wet windscreen (mat_rain_windscreen.frag): its drops and haze done here without the taa, left as they are when the taa + // did them (marked in the alpha) + vec2 rawv = texture(velocity_tex, f_coords).xy; + if (wsIsDrop(rawv)) + { + vec4 picture = texture(color_tex, f_coords); + out_color = vec4((picture.a > 0.5 * (1.0 + WS_HAZED)) ? picture.rgb + : wsDropRefraction(color_tex, velocity_tex, depth_tex, f_coords, rawv), 1.0); + return; + } + float blurAmt = wsBlur(rawv); + if (blurAmt > 0.0) + { + vec4 picture = texture(color_tex, f_coords); + out_color = vec4((picture.a > 0.5 * (1.0 + WS_HAZED)) ? picture.rgb : wsHaze(color_tex, velocity_tex, f_coords, blurAmt), 1.0); + return; + } + float ori_depth = texture(depth_tex, f_coords).x; vec2 texelSize = 1.0 / vec2(textureSize(color_tex, 0)); - vec2 velocity = texture(velocity_tex, f_coords).xy * param[0].x; + vec2 velocity = rawv * param[0].x; + // edge pixels of the windscreen can carry a fraction of a request: never use that as motion + if (any(greaterThan(abs(rawv), vec2(WS_FLOOR * WS_ENC)))) + velocity = vec2(0.0); float speed = length(velocity / texelSize); int nSamples = clamp(int(speed), 1, 32); diff --git a/shaders/vk14/postfx_taa.frag b/shaders/vk14/postfx_taa.frag index dd48c0203..6e01a3b25 100644 --- a/shaders/vk14/postfx_taa.frag +++ b/shaders/vk14/postfx_taa.frag @@ -23,4 +23,54 @@ layout(set = POST_SET, binding = POST_TEXTURE_FIRST + 3) uniform sampler2D histo #define TAA_HISTORY_VALID (param[0].x > 0.5) #define TAA_REPROJECTION mat4(param[2], param[3], param[4], param[5]) #define TAA_NEAR param[0].y +#include "rain_windscreen_haze.glsl" + +// the resolve of the taa under another name: main() below gives the wet windscreen (mat_rain_windscreen.frag) its haze and the +// picture in its drops first +#define main taa_resolve_main #include "taa_resolve.glsl" +#undef main + +// the drops and the haze are made from the frame alone (the history of the taa would smear them over the frames): drawn with the +// offsets of the taa they shimmer from frame to frame. they stay where they are on the screen, so the result of the last frame at +// the same pixel is blended in: fully while the view stands still, half while it moves, kept near this frame's result (no ghosts +// of a wiper or of drops gone) +const float WS_TEMPORAL_SHARE = 0.2; // the share of this frame while the view stands still +const float WS_TEMPORAL_MOVING = 0.5; // ... and while it moves +const float WS_TEMPORAL_RANGE = 0.12; // the last frame kept within this of this frame (colours squeezed into 0..1) + +vec3 wsStabilize(vec3 current, ivec2 pixel) +{ + if (false == TAA_HISTORY_VALID) + return current; + vec4 last = texelFetch(history_tex, pixel, 0); + if (any(isnan(last)) || (last.a < 0.5 * (1.0 + WS_HAZED))) // not a drop or haze pixel in the last frame + return current; + vec2 size = vec2(textureSize(color_tex, 0)); + float depth = texelFetch(depth_tex, pixel, 0).r; + vec4 world = TAA_REPROJECTION * vec4(f_coords * 2.0 - 1.0, depth, 1.0); + bool still = (world.w > 0.0) && (length((world.xy / world.w * 0.5 + 0.5 - f_coords) * size) < 0.5); + vec3 c = taa_compress(current); + vec3 h = clamp(taa_compress(taa_clean(last.rgb)), c - WS_TEMPORAL_RANGE, c + WS_TEMPORAL_RANGE); + return taa_decompress(clamp(mix(h, c, still ? WS_TEMPORAL_SHARE : WS_TEMPORAL_MOVING), vec3(0.0), vec3(1.0 - 1.0 / TAA_HALF_MAX))); +} + +void main() +{ + // the drops: the picture of this frame bent by them; the hazy glass: the picture of this frame blurred over it. both without + // the history (else they would smear on frame after frame), marked for the motion blur after + ivec2 pixel = ivec2(f_coords * vec2(textureSize(velocity_tex, 0))); + vec2 raw = texelFetch(velocity_tex, pixel, 0).xy; + if (wsIsDrop(raw)) + { + out_color = vec4(wsStabilize(taa_clean(wsDropRefraction(color_tex, velocity_tex, depth_tex, f_coords, raw)), pixel), WS_HAZED); + return; + } + float blurAmt = wsBlur(raw); + if (blurAmt > 0.0) + { + out_color = vec4(wsStabilize(taa_clean(wsHaze(color_tex, velocity_tex, f_coords, blurAmt)), pixel), WS_HAZED); + return; + } + taa_resolve_main(); +} diff --git a/shaders/vk14/rain_windscreen_haze.glsl b/shaders/vk14/rain_windscreen_haze.glsl new file mode 100644 index 000000000..6dd9a4cde --- /dev/null +++ b/shaders/vk14/rain_windscreen_haze.glsl @@ -0,0 +1,233 @@ +// the haze of the wet windscreen (mat_rain_windscreen.frag), drawn by the post-processing: the glass asks for it in the velocity +// target (x = WS_ENC * strength, y = 0, see mat_rain_windscreen.frag), and the picture there is blurred over the hazy glass only. +// postfx_taa.frag does it with the temporal anti-aliasing (every frame, also standing still), postfx_motionblur.frag without it +// (it runs only while something moves). the picture blurred by the taa is marked in its alpha (WS_HAZED), so the motion blur +// after it leaves it as it is. +// +// real motion vectors are tiny (<< 0.25 per frame), so the large values can only come from the windscreen +#ifndef RAIN_WINDSCREEN_HAZE_GLSL +#define RAIN_WINDSCREEN_HAZE_GLSL + +const float WS_ENC = 64.0; // must match mat_rain_windscreen.frag +const float WS_FLOOR = 0.004; // = 0.256 in raw velocity units: everything below is real motion +const float WS_HAZED = 2.0; // alpha of the picture the taa already blurred + +// blur of hazy glass +const float WS_RADIUS = 0.014; // max blur radius, fraction of screen height +const int WS_TAPS = 16; +const float WS_HAZE_LIGHT_CAP = 12.0; // the most a light adds to the haze around it (brightness, scene units) + +// strength of the blur request, 0 for pixels that are not blur pixels +float wsBlur(vec2 raw) +{ + if (raw.x > 100.0 || raw.y > 100.0) // a blended edge with something else: not a blur pixel + return 0.0; + float m = clamp(raw.x / WS_ENC, 0.0, 1.0); + return clamp((m - WS_FLOOR) / (1.0 - WS_FLOOR), 0.0, 1.0); +} + +// a colour of the picture made safe: a very bright light can be an infinity in the half float image (and a broken pixel a nan); +// in an average that gave nan for the whole result, which the taa turns black: black dotted blobs around the lights +vec3 wsSafe(vec3 c) +{ + return any(isnan(c)) ? vec3(0.0) : clamp(c, vec3(0.0), vec3(65000.0)); +} + +vec3 wsFetch(sampler2D tex, vec2 uv) +{ + return wsSafe(textureLod(tex, uv, 0.0).rgb); +} + +// the weight of a colour in an average that a single very bright pixel must not take over +float wsKaris(vec3 c) +{ + return 1.0 / (1.0 + dot(c, vec3(0.2126, 0.7152, 0.0722))); +} + +// the picture at Uv blurred over the hazy glass, for a request of BlurAmt (> 0) +vec3 wsHaze(sampler2D colortex, sampler2D velocitytex, vec2 uv, float blurAmt) +{ + vec2 texelSize = 1.0 / vec2(textureSize(colortex, 0)); + float aspect = texelSize.x / texelSize.y; // height / width + vec3 sharp = wsFetch(colortex, uv); + + float radius = WS_RADIUS * blurAmt; + + // interleaved gradient noise rotates the disc per pixel -> no banding + float rot = 6.2831853 * fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))); + + float wsum = wsKaris(sharp); + vec3 sum = sharp * wsum; + float psum_w = 1.0; // the plain average beside it + vec3 psum = sharp; + + for (int i = 0; i < WS_TAPS; ++i) + { + float r = sqrt((float(i) + 0.5) / float(WS_TAPS)); + float a = float(i) * 2.3999632 + rot; // golden angle + vec2 o = vec2(cos(a), sin(a)) * r * radius; + o.x *= aspect; + + vec2 tap = uv + o; + + // take only hazy-glass pixels (not the cab frame, not clear glass, not drops) + // weighed by 1 / (1 + brightness) (karis average): an ordinary picture blurs the same, but a very bright light + // (a lamp close by, headlights) is not smeared over the whole disc at full strength, which the bloom then turned + // into a large flat blob shaped like a clover + float w = step(0.01, wsBlur(textureLod(velocitytex, tap, 0.0).xy)); + vec3 c = wsFetch(colortex, tap); + psum += c * w; + psum_w += w; + w *= wsKaris(c); + sum += c * w; + wsum += w; + } + + // the karis average alone almost wipes small bright lights out of the haze (signals at night went faint): the light the + // plain average has above it comes back, up to WS_HAZE_LIGHT_CAP, so a light stays a soft glow of its colour and only a + // very bright one (a lamp close by) isn't smeared at full strength + vec3 blurred = sum / wsum; + vec3 extra = max(psum / psum_w - blurred, vec3(0.0)); + float extraL = dot(extra, vec3(0.2126, 0.7152, 0.0722)); + blurred += extra * min(1.0, WS_HAZE_LIGHT_CAP / max(extraL, 1e-4)); + return mix(sharp, blurred, min(blurAmt * 4.0, 1.0)); +} + +// --------------------------------------------------------------------------------------------------------------------------- +// refraction in the drops: the glass sends the picture shift of the drop (x, y = WS_DROP_BIAS + WS_BEND_ENC * bend, bend -1..1 +// = WS_REFR_MAXPX pixels), and the picture of this frame is bent here. the depth of the whole frame (with the cab) is known here, +// so the dashboard, the frame and the roof of the cab are never pulled into a drop (the image of the last frame used by the +// glass shader can't tell them apart: white drops at night at the edges and under the wipers) +// --------------------------------------------------------------------------------------------------------------------------- +const float WS_BEND_ENC = 60.0; // must match mat_rain_windscreen.frag +const float WS_DROP_BIAS = 192.0; // must match mat_rain_windscreen.frag +const float WS_REFR_MAXPX = 96.0; // must match mat_rain_windscreen.frag +const float WS_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the refracted picture +const float WS_LENS_AA = 0.75; // above this spread of the picture between neighbouring pixels, a 4x4 footprint is averaged + +// the lights in the drops: a drop is a wide-angle lens and lights up near a bright light (signals, lamps, headlights). taken from +// the mipmaps of the image the screen reflections keep (ssr_history: the last frame, or this one in the motion blur), so the glow +// is smooth: point samples of the full image caught a headlight of one pixel only at fixed offsets and drew it as grids of dots +const float WS_LIGHT_GAIN = 1.0; // brightness of the lights in the drops (0 = off) +const float WS_LIGHT_CAP = 8.0; // the most the glow adds to a drop (brightness, scene units) +const float WS_LIGHT_MIN_LUM = 1.0; // a light: the fine level at least this bright (scene units) above the place around it ... +const float WS_LIGHT_CONTRAST = 3.0; // ... and this many times brighter than it +const float WS_LIGHT_FINE = 3.5; // mip levels: the drop's own neighbourhood (~11 px), a wider one (~32 px), the place around +const float WS_LIGHT_MID = 5.0; +const float WS_LIGHT_WIDE = 7.0; +const float WS_LIGHT_MID_SHARE = 0.5; // how much the lights a little further away count + +// the vulkan renderer gives the post-processing only its own images (LAYOUT_POST): no history of the reflections, no glow there +#ifndef LAYOUT_POST +layout(binding = SSR_HISTORY_TEX) uniform sampler2D ws_light_history; +#endif + +// reverse z, infinite far: depth = znear / distance. a sample is "the cab" when it is much nearer than the centre and closer than ~5 m +const float WS_NEAR_RATIO = 1.6; +const float WS_NEAR_DEPTH = 0.02; + +bool wsSameLayer(float d, float d0) +{ + return d <= max(d0 * WS_NEAR_RATIO, WS_NEAR_DEPTH); +} + +float wsLum(vec3 c) +{ + return dot(c, vec3(0.2126, 0.7152, 0.0722)); +} + +// a drop pixel (drop, rivulet): both values in 132..252 +bool wsIsDrop(vec2 raw) +{ + return raw.x > 120.0 && raw.y > 120.0; +} + +vec2 wsBend(vec2 raw) +{ + return clamp((raw - WS_DROP_BIAS) / WS_BEND_ENC, -1.0, 1.0); +} + +#ifndef LAYOUT_POST +vec3 wsLightExcess(vec2 uv, float lod, vec3 wide) +{ + vec3 c = wsSafe(textureLod(ws_light_history, uv, min(lod, ssr_params2.x)).rgb); + vec3 excess = max(c - wide * WS_LIGHT_CONTRAST, vec3(0.0)); + return excess * smoothstep(0.5 * WS_LIGHT_MIN_LUM, WS_LIGHT_MIN_LUM, wsLum(excess)); +} + +vec3 wsLightGlow(vec2 uv) +{ + if ((ssr_params.x < 1.0) || (textureSize(ws_light_history, 0).x < 16)) + return vec3(0.0); + vec3 wide = wsSafe(textureLod(ws_light_history, uv, min(WS_LIGHT_WIDE, ssr_params2.x)).rgb); + vec3 glow = wsLightExcess(uv, WS_LIGHT_FINE, wide) + WS_LIGHT_MID_SHARE * wsLightExcess(uv, WS_LIGHT_MID, wide); + glow *= WS_LIGHT_GAIN; + // a light close by is kept to the brightness of one light + return glow * min(1.0, WS_LIGHT_CAP / max(wsLum(glow), 1e-4)); +} +#else +vec3 wsLightGlow(vec2 uv) +{ + return vec3(0.0); +} +#endif + +// the picture at Uv seen through the drop, for a drop pixel with the request Raw +vec3 wsDropRefraction(sampler2D colortex, sampler2D velocitytex, sampler2D depthtex, vec2 uv, vec2 raw) +{ + vec2 texelSize = 1.0 / vec2(textureSize(colortex, 0)); + float aspect = texelSize.x / texelSize.y; // height / width + vec3 center = wsFetch(colortex, uv); + + vec2 bend = wsBend(raw); + vec2 uv2 = uv - bend * WS_REFR_MAXPX * texelSize; + + // the spread of the picture between neighbouring pixels (the jacobian of the shift): a drop shows a minified, flipped copy + // of the scene, single samples would alias into a hatch there + vec2 rx = textureLod(velocitytex, uv + vec2(texelSize.x, 0.0), 0.0).xy; + vec2 ry = textureLod(velocitytex, uv + vec2(0.0, texelSize.y), 0.0).xy; + vec2 jx = (wsIsDrop(rx) ? wsBend(rx) - bend : vec2(0.0)) * WS_REFR_MAXPX; + vec2 jy = (wsIsDrop(ry) ? wsBend(ry) - bend : vec2(0.0)) * WS_REFR_MAXPX; + float lens = length(jx) + length(jy); + + // never pull in what is much nearer than the scene behind the glass (the cab) + vec3 refr = center; + float d0 = textureLod(depthtex, uv, 0.0).x; + float d1 = textureLod(depthtex, uv2, 0.0).x; + if (wsSameLayer(d1, d0)) + { + if (lens < WS_LENS_AA) + { + refr = wsFetch(colortex, uv2); + } + else + { + vec2 fx = clamp(vec2(1.0, 0.0) - jx, vec2(-10.0), vec2(10.0)); + vec2 fy = clamp(vec2(0.0, 1.0) - jy, vec2(-10.0), vec2(10.0)); + vec3 acc = vec3(0.0); + float wacc = 0.0; + for (int j = 0; j < 4; ++j) + { + for (int i = 0; i < 4; ++i) + { + vec2 t = (vec2(float(i), float(j)) + 0.5) / 4.0 - 0.5; + vec3 c = wsFetch(colortex, uv2 + (fx * t.x + fy * t.y) * texelSize); + float w = wsKaris(c); + acc += c * w; + wacc += w; + } + } + refr = acc / wacc; + } + } + + vec3 outc = mix(center, refr, WS_REFR_MIX); + // the glow only in the drops themselves, strongest in their middle, where the lens bends most: the water film and the + // rivulets between them (no bend) would show it as flat squares around the headlights of an oncoming train + float glowW = smoothstep(0.03, 0.2, length(bend)); + if ((WS_LIGHT_GAIN > 0.0) && (glowW > 0.0)) + outc += wsLightGlow(uv) * glowW; + return outc; +} + +#endif