Compare commits

...

1 Commits

3 changed files with 288 additions and 5 deletions
+50 -5
View File
@@ -1,10 +1,13 @@
//! Rain and retained liquid wetness for world units and their explicitly owned worn rigs.
//! Facing law adapted from pkuzic/benilla-everwood_graphics `wet_hook.wgsl` (MIT OR Apache-2.0).
mod drips;
use std::collections::HashMap;
use std::sync::Arc;
use benilla_world::liquid::LiquidClaim;
use benilla_world::mesh_tag::MAX_RIG_SLOTS;
use benilla_world::particles::buffer::{begin_effect_frame, EffectFog, WorldEffectDraw};
use benilla_world::rig_palette::RigSkin;
use benilla_world::rig_rider::WornRigOwner;
use benilla_world::schedule::WorldLive;
@@ -13,6 +16,7 @@ use benilla_world::wmo_portal::WmoPvsSet;
use benilla_world::world_map::CurrentMap;
use benilla_world::world_point::UnitLiquid;
use benilla_world::world_unit::WorldUnit;
use bevy::asset::AssetId;
use bevy::prelude::*;
use crate::frame::{row, GfxFrame};
@@ -125,6 +129,8 @@ pub(crate) fn register(app: &mut App) {
publish
.after(crate::wet_terrain::publish)
.after(bevy::transform::TransformSystems::Propagate)
.after(bevy::camera::visibility::VisibilitySystems::VisibilityPropagate)
.after(begin_effect_frame)
.after(WmoPvsSet),
);
}
@@ -135,18 +141,20 @@ fn publish(
live: Option<Res<WorldLive>>,
map: Option<Res<CurrentMap>>,
time: Res<Time<Real>>,
camera: Query<(&Camera, &GlobalTransform), With<WorldCamera>>,
camera: Query<(Entity, &Camera, &GlobalTransform), With<WorldCamera>>,
units: Query<(
Entity,
&WorldUnit,
&GlobalTransform,
Option<&RigSkin>,
Has<benilla_world::world_unit::ViewerUnit>,
Option<&InheritedVisibility>,
)>,
worn: Query<(&WornRigOwner, &RigSkin)>,
liquid: UnitLiquid,
mut frame: ResMut<GfxFrame>,
mut state: Local<State>,
mut effects: WorldEffectDraw,
) {
frame.rows[row::WET_BODY] = [0.0; 4];
let map_id = map.as_deref().map(|m| m.0);
@@ -159,18 +167,22 @@ fn publish(
state.units.clear();
state.map = map_id;
}
let Ok((camera_entity, camera, eye)) = camera.single() else {
state.units.clear();
return;
};
if !settings.weather.wet_character
|| strength <= 0.0
|| !live.is_some_and(|l| l.0)
|| map_id.is_none()
|| !camera.single().is_ok_and(|(c, _)| c.is_active)
|| !camera.is_active
{
state.units.clear();
return;
}
state.clear_rows();
state.units.retain(|entity, _| {
units.get(*entity).is_ok_and(|(_, unit, t, _, _)| {
units.get(*entity).is_ok_and(|(_, unit, t, _, _, _)| {
unit.wades
&& unit.height.is_finite()
&& unit.height > 0.0
@@ -180,7 +192,13 @@ fn publish(
let mut used = 0usize;
let mut example = None;
let rain_on = frame.rows[row::WET][0] > 0.0 && frame.rows[row::WET][3] > 0.0;
for (entity, unit, transform, skin, viewer) in &units {
let now = time.elapsed_secs_f64();
let mut drops = effects
.batch(camera_entity, AssetId::default())
.fog(EffectFog::Scene)
.anchored(eye.translation());
let mut drop_count = 0;
for (entity, unit, transform, skin, viewer, visible) in &units {
let at = transform.translation();
if !unit.wades || !at.is_finite() || !unit.height.is_finite() || unit.height <= 0.0 {
continue;
@@ -204,6 +222,32 @@ fn publish(
if !needs_row(wet, rain_on, outdoors) {
continue;
}
let drop_limit = drips::MAX_VISIBLE - usize::from(!viewer);
if drop_count < drop_limit && skin.is_some() && visible.is_none_or(|v| v.get()) {
let to_eye = eye.translation() - at;
let fade = drips::distance_fade(to_eye, height, viewer);
if fade > 0.0 && to_eye.dot(eye.forward().as_vec3()) < 0.0 {
let rain = if rain_on && outdoors {
crate::wet_terrain::rain_on_body(&frame, at + Vec3::Y * (height * 0.75))
} else {
0.0
};
if let Some(drop) = drips::sample(
wet,
strength,
rain,
height,
depth,
now,
entity.to_bits() as u32,
) {
if let Some(vertices) = drop.vertices(unit, transform, eye, fade) {
drops.extend(vertices);
drop_count += 1;
}
}
}
}
let payload = wet.row(at.y, outdoors);
if viewer || example.is_none() {
example = Some((entity, skin.map(|s| s.slot), payload, viewer));
@@ -217,6 +261,7 @@ fn publish(
}
}
}
drops.tris();
for (owner, skin) in &worn {
let slot = skin.slot as usize;
if slot == 0 || slot >= MAX_RIG_SLOTS {
@@ -228,13 +273,13 @@ fn publish(
}
}
publish_snapshot(&mut frame, &state.rows, used);
let now = time.elapsed_secs_f64();
if now - state.last_log >= 1.0 {
debug!(
?example,
affected = state.owners.len(),
slots = used,
rain = frame.rows[row::WET][0],
drops = drop_count,
strength,
"world unit wetness"
);
+203
View File
@@ -0,0 +1,203 @@
//! Sparse runoff along a wet world unit's outline.
use benilla_world::{particles::buffer::EffectVertex, world_unit::WorldUnit};
use bevy::prelude::*;
use super::Wetness;
use crate::fog::smoothstep;
pub(super) const MAX_VISIBLE: usize = 24;
const PERIOD: f64 = 0.75;
const LIFE: f32 = 0.32;
fn random(seed: u32) -> f32 {
let x = (seed ^ (seed >> 16)).wrapping_mul(0x7feb_352d);
let x = (x ^ (x >> 15)).wrapping_mul(0x846c_a68b);
((x ^ (x >> 16)) >> 8) as f32 / 16_777_216.0
}
pub(super) fn distance_fade(to_eye: Vec3, height: f32, viewer: bool) -> f32 {
let distance = to_eye.length();
let near = if viewer {
let horizontal = Vec2::new(to_eye.x, to_eye.z).length();
smoothstep(0.27 * height, 0.65 * height, horizontal)
} else {
smoothstep(0.65, 1.2, distance)
};
near * (1.0 - smoothstep(7.0, 13.0, distance))
}
#[derive(Debug)]
pub(super) struct Drop {
height: f32,
alpha: f32,
/// Local radial direction from the body towards the drop.
side: Vec2,
}
pub(super) fn sample(
wet: Wetness,
scale: f32,
rain: f32,
height: f32,
depth: Option<f32>,
now: f64,
entity_seed: u32,
) -> Option<Drop> {
let upper = (wet.whole * scale).max(rain);
let lower = wet.lower * scale;
let surface = depth.filter(|d| d.is_finite()).unwrap_or(0.0).max(0.0);
let floor = surface + 0.08;
if upper.max(lower) <= 0.08 || height * 0.77 <= floor {
return None;
}
// A fixed cadence keeps the motion continuous during drying. Fewer cycles pass as water fades.
let clock = now + f64::from(random(entity_seed)) * PERIOD;
let age = clock.rem_euclid(PERIOD) as f32;
if age >= LIFE {
return None;
}
let cycle = (clock / PERIOD) as u32;
let seed = entity_seed.wrapping_mul(0x9e37_79b9).wrapping_add(cycle);
let chance = random(seed);
let upper_height = height * (0.69 + 0.08 * random(seed ^ 0xa9a9_3829));
let lower_height = (wet.line * 0.88).min(upper_height);
let (source, amount) = if upper >= lower || lower_height <= floor {
(upper_height, upper)
} else {
(lower_height, lower)
};
if amount <= 0.08 || chance >= smoothstep(0.08, 0.72, amount) {
return None;
}
let height = source - age * (0.32 + 2.6 * age);
if height <= floor {
return None;
}
let fade = smoothstep(0.0, 0.06, age) * (1.0 - smoothstep(0.19, LIFE, age));
let angle = random(seed ^ 0x8d47_3361) * std::f32::consts::TAU;
Some(Drop {
height,
alpha: 0.56 * fade * amount.sqrt(),
side: Vec2::from_angle(angle),
})
}
impl Drop {
pub(super) fn vertices(
&self,
unit: &WorldUnit,
body: &GlobalTransform,
eye: &GlobalTransform,
fade: f32,
) -> Option<[EffectVertex; 12]> {
let bounds = unit.bound?;
let at = body.translation();
let local_eye = body
.affine()
.inverse()
.transform_vector3(eye.translation() - at);
let near = Vec2::new(local_eye.x, local_eye.z).normalize_or_zero();
// Mirror the hidden half around the body so a thin drop reads against the visible outline.
let side =
(self.side + near * (0.3 - 2.0 * self.side.dot(near).min(0.0))).normalize_or_zero();
let center = Vec2::new(bounds.center.x, bounds.center.z);
let half = Vec2::new(bounds.half_extents.x, bounds.half_extents.z);
let offset = center + side * half * 0.95;
let end = body.transform_point(Vec3::new(offset.x, 0.0, offset.y));
// Keep authored hands, tails and unusually wide poses from moving the drop off the body.
let lateral = Vec2::new(end.x - at.x, end.z - at.z).clamp_length_max(unit.height * 0.29);
let center = at + Vec3::new(lateral.x, self.height, lateral.y);
if !center.is_finite() {
return None;
}
let right = eye.right().as_vec3() * 0.019;
let rim = [
center + Vec3::Y * 0.082,
center - right,
center - Vec3::Y * 0.037,
center + right,
];
let vertex = |position: Vec3, alpha| EffectVertex {
pos: position.to_array(),
uv: [0.5; 2],
color: [0.62, 0.77, 0.85, alpha],
};
Some(std::array::from_fn(|i| match i % 3 {
0 => vertex(center, self.alpha * fade),
1 => vertex(rim[i / 3], 0.0),
_ => vertex(rim[(i / 3 + 1) % 4], 0.0),
}))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn runoff_falls_and_leaves_a_gap_between_drops() {
let wet = Wetness {
whole: 1.0,
lower: 1.0,
line: 2.0,
};
let at = |time| sample(wet, 1.0, 0.0, 2.0, None, time, 0);
let early = at(0.08).unwrap();
let late = at(0.23).unwrap();
assert!(late.height < early.height && late.alpha < early.alpha);
assert!(at(0.40).is_none());
assert!(at(0.83).is_some());
}
#[test]
fn runoff_respects_the_wet_part_of_the_body_and_water_surface() {
let wet = Wetness {
whole: 0.0,
lower: 1.0,
line: 0.45,
};
let at = |depth| sample(wet, 1.0, 0.0, 2.0, depth, 0.10, 0);
let drop = at(None).unwrap();
assert!(drop.height < wet.line && drop.height > 0.08);
assert!(at(Some(0.45)).is_none());
let wet = Wetness { whole: 1.0, ..wet };
assert!(sample(wet, 1.0, 1.0, 2.0, Some(2.0), 0.1, 0).is_none());
}
#[test]
fn dry_bodies_and_first_person_stay_clear() {
let dry = Wetness::default();
assert!(sample(dry, 1.0, 0.0, 2.0, None, 0.08, 0).is_none());
assert!(sample(dry, 1.0, 1.0, 2.0, None, 0.08, 0).is_some());
assert_eq!(distance_fade(Vec3::new(0.05, 1.8, 0.0), 2.0, true), 0.0);
assert_eq!(distance_fade(Vec3::Z * 5.0, 2.0, true), 1.0);
assert_eq!(distance_fade(Vec3::Z * 14.0, 2.0, false), 0.0);
}
#[test]
fn runoff_reads_on_the_visible_side_of_the_body() {
let unit = WorldUnit {
wades: true,
scale: 1.0,
height: 2.0,
bound: Some(bevy::camera::primitives::Aabb::from_min_max(
Vec3::new(-0.4, 0.0, -0.3),
Vec3::new(0.4, 2.0, 0.3),
)),
};
let drop = Drop {
height: 1.3,
alpha: 0.3,
side: -Vec2::Y,
};
let body = GlobalTransform::IDENTITY;
let eye = GlobalTransform::from_translation(Vec3::Z * 5.0);
let vertices = drop.vertices(&unit, &body, &eye, 1.0).unwrap();
assert!(vertices[0].pos[2] > 0.2);
assert_eq!(vertices[0].color[3], 0.3);
assert_eq!(vertices[1].color[3], 0.0);
}
}
+35
View File
@@ -272,6 +272,29 @@ pub(crate) fn publish(
frame.shelter.copy_from_slice(rows);
}
/// Rain at an upright body's sample height, using the same roof grid as its wet surface.
pub(super) fn rain_on_body(frame: &GfxFrame, at: Vec3) -> f32 {
let [strength, x, z, spacing] = frame.rows[row::WET];
if strength <= 0.0 || spacing <= 0.0 {
return 0.0;
}
let grid = (Vec2::new(at.x, at.z) - Vec2::new(x, z)) / spacing;
if !grid.is_finite() {
return 0.0;
}
if grid.min_element() < 0.0 || grid.max_element() >= (SIDE - 1) as f32 {
return strength;
}
let cell = grid.floor();
let fraction = grid - cell;
let first = cell.y as usize * SIDE + cell.x as usize;
let cover = |i: usize| crate::fog::smoothstep(0.35, 1.2, frame.shelter[i / 4][i % 4] - at.y);
let top = cover(first) * (1.0 - fraction.x) + cover(first + 1) * fraction.x;
let bottom = cover(first + SIDE) * (1.0 - fraction.x) + cover(first + SIDE + 1) * fraction.x;
let cover = top * (1.0 - fraction.y) + bottom * fraction.y;
strength * (1.0 - ((cover - 0.25) / 0.75).clamp(0.0, 1.0))
}
const SHELTER_WGSL: &str = r#"
// Compare the receiver's height with each sampled roof before blending the corners.
fn mw_wet_exposure(world: vec3<f32>, normal: vec3<f32>) -> f32 {
@@ -391,6 +414,18 @@ pub(crate) fn static_gx_edits(binding: &'static str) -> Vec<Edit> {
mod tests {
use super::*;
#[test]
fn body_rain_respects_shelter_height() {
let mut frame = GfxFrame::default();
frame.rows[row::WET] = [0.65, 0.0, 0.0, SPACING];
let point = Vec3::new(SPACING * 0.5, 2.0, SPACING * 0.5);
assert_eq!(rain_on_body(&frame, point), 0.65);
frame.shelter[0][..2].fill(4.0);
frame.shelter[SIDE / 4][SIDE % 4..SIDE % 4 + 2].fill(4.0);
assert_eq!(rain_on_body(&frame, point), 0.0);
assert_eq!(rain_on_body(&frame, point + Vec3::Y * 3.0), 0.65);
}
#[test]
fn envelope_uses_elapsed_time() {
let mut wet = 0.0;