Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
FogVolume: soft edges and a taper, for steam and smoke that don't read as boxes
shinyobjectzb8e2a3d6d2a4
diff --git a/runtime/scene3d/src/light.rs b/runtime/scene3d/src/light.rsindex 16987f7a..ae9a3b43 100644--- a/runtime/scene3d/src/light.rs+++ b/runtime/scene3d/src/light.rs@@ -1,5 +1,5 @@use super::*;-use super::froxel::{FogRank, FogThinning};+use super::froxel::{FogRank, FogShape};/// Whether a light casts shadows when it's lit (its row's `shadows`, or `volumetric`), kept apart from its/// `shadow_maps_enabled`, which sync_lights clears while the light is dark.@@ -198,7 +198,11 @@ pub fn fog_volume(world: &mut World, e: Entity, id: &str, vals: &BTreeMap<StringErr(err) => eprintln!("raea: FogVolume density_texture {p}: {err}"),}}- world.entity_mut(e).insert((fv, fog_transform(vals), FogRank(id.to_string()), FogThinning(num(vals, "falloff", 0.0).max(0.0))));+ world.entity_mut(e).insert((fv, fog_transform(vals), FogRank(id.to_string()), FogShape {+ falloff: num(vals, "falloff", 0.0).max(0.0),+ soft: num(vals, "soft", 0.0).clamp(0.0, 1.0),+ taper: num(vals, "taper", 0.0).clamp(0.0, 1.0),+ }));}/// The render world's fog volumes, by rank (filled each extraction).diff --git a/sdk/render/src/3d/volumetric.tsx b/sdk/render/src/3d/volumetric.tsxindex 9a076daa..1b7d513a 100644--- a/sdk/render/src/3d/volumetric.tsx+++ b/sdk/render/src/3d/volumetric.tsx@@ -82,6 +82,12 @@ export interface FogVolumeProps {* fog that's a third as thick two metres up. A box wide and tall with a falloff is height fog. Only* <VolumetricFog mode="froxel"> draws it; the march draws the box evenly */falloff?: number;+ /** how far in from each face its density ramps up, as a share of the box's half-size, 0 to 1 (0 by default: a hard+ * box): 0.5 and up hides a small volume's edges (steam, a smoke column). Only <VolumetricFog mode="froxel"> */+ soft?: number;+ /** how much narrower its floor is than its top, 0 to 1 (0 by default: a box): 0.7 is a plume rising off a tank,+ * widening as it climbs. Only <VolumetricFog mode="froxel"> */+ taper?: number;/** Bevy's density_texture: a 3D .ktx2 image in the media folder whose values scale the density through the box (a* cloud, a bunny of smoke); the box draws evenly without one. Only the march draws it */density_texture?: string;@@ -98,5 +104,6 @@ export function FogVolume(props: FogVolumeProps) {const tex = props.density_texture;if (tex !== undefined && !(typeof tex === "string" && /\.ktx2$/i.test(tex))) throw new TypeError(`FogVolume: density_texture is a 3D .ktx2 image, got ${JSON.stringify(tex)}`);if (props.falloff !== undefined && !(props.falloff >= 0 && Number.isFinite(props.falloff))) throw new RangeError(`FogVolume: falloff must be 0 or more, got ${props.falloff}`);+ for (const k of ["soft", "taper"] as const) if (props[k] !== undefined && !(props[k]! >= 0 && props[k]! <= 1)) throw new RangeError(`FogVolume: ${k} must be between 0 and 1, got ${props[k]}`);return node3d("FogVolume", colours("FogVolume", (tex === undefined ? props : { ...props, density_texture: assetPath(tex) }) as Record<string, unknown>, ["color"]));}diff --git a/systems/fog/src/froxel.rs b/systems/fog/src/froxel.rsindex 1b5c6641..81b9cd12 100644--- a/systems/fog/src/froxel.rs+++ b/systems/fog/src/froxel.rs@@ -82,6 +82,7 @@ pub fn insert(world: &mut World, e: Entity, fog: FroxelFog) {}pub fn install(app: &mut App) {+ bevy::shader::load_shader_library!(app, "froxel_volume.wesl");bevy::asset::embedded_asset!(app, "froxel_light.wesl");bevy::asset::embedded_asset!(app, "froxel_grid.wesl");bevy::asset::embedded_asset!(app, "froxel_hero.wesl");@@ -108,7 +109,8 @@ struct GpuVolume {scatter: Vec4,/// rgb: what of the ambient light it scatters per metre (fog colour x scattering x density); a: anisotropyambient: Vec4,- /// x: falloff per metre up from the box's floor; y: the box's height in metres+ /// x: falloff per metre up from the box's floor; y: the box's height in metres; z: the feathered share of the+ /// half-size at each face (`soft`); w: how much narrower the floor is than the top (`taper`); froxel_volume.weslshape: Vec4,}@@ -121,9 +123,9 @@ pub struct Volumes {buffer: StorageBuffer<Vec<GpuVolume>>,}-fn extract_volumes(mut volumes: ResMut<Volumes>, q: Extract<Query<(&FogVolume, &GlobalTransform, Option<&FogRank>, Option<&FogThinning>)>>) {+fn extract_volumes(mut volumes: ResMut<Volumes>, q: Extract<Query<(&FogVolume, &GlobalTransform, Option<&FogRank>, Option<&FogShape>)>>) {let mut found: Vec<(String, GpuVolume, [Vec3; 8])> = Vec::new();- for (fv, t, rank, falloff) in &q {+ for (fv, t, rank, shape) in &q {let affine = t.affine();// a hidden volume is shrunk to nothing (scene3d::fog_transform) and has no densityif fv.density_factor <= 0.0 || affine.matrix3.determinant().abs() < 1e-9 {@@ -147,7 +149,7 @@ fn extract_volumes(mut volumes: ResMut<Volumes>, q: Extract<Query<(&FogVolume, &local_from_world: Mat4::from(local_from_world),scatter: light.extend(extinction),ambient: (colour * fv.scattering * fv.density_factor).extend(fv.scattering_asymmetry),- shape: Vec4::new(falloff.map_or(0.0, |f| f.0), height, 0.0, 0.0),+ shape: shape.map_or(Vec4::new(0.0, height, 0.0, 0.0), |s| Vec4::new(s.falloff, height, s.soft, s.taper)),},corners,));@@ -396,10 +398,16 @@ fn draw(ctx.command_encoder().pop_debug_group();}-/// How fast a fog volume thins going up, per metre from its box's floor (`falloff`; 0: even). Only the froxel grid-/// draws it (froxel.rs); Bevy's march fills the box evenly.-#[derive(Component, Clone, Copy)]-pub struct FogThinning(pub f32);+/// A fog volume's shape inside its box (froxel_volume.wesl): how fast it thins going up, per metre from the box's+/// floor (`falloff`; 0: even); the share of the box's half-size over which its density ramps in from every face+/// (`soft`, 0 to 1; 0: a hard box); how much narrower its floor is than its top (`taper`, 0 to 1; a plume). Only the+/// froxel grid draws it (froxel.rs); Bevy's march fills the box evenly.+#[derive(Component, Clone, Copy, Default)]+pub struct FogShape {+ pub falloff: f32,+ pub soft: f32,+ pub taper: f32,+}/// Where a fog volume comes in the order Bevy composites them (its row's id). Overlapping volumes blend in the order/// Bevy's render world iterates them, which is the order their render entities first got a FogVolume: a render ofdiff --git a/systems/fog/src/froxel_hero.wesl b/systems/fog/src/froxel_hero.weslindex d260a9af..b986ca00 100644--- a/systems/fog/src/froxel_hero.wesl+++ b/systems/fog/src/froxel_hero.wesl@@ -39,6 +39,7 @@ import bevy_pbr::render::mesh_view_types::POINT_LIGHT_FLAGS_SPOT_LIGHT_Y_NEGATIVimport bevy_pbr::render::view_transformations::frag_coord_to_ndc;import bevy_pbr::render::view_transformations::position_ndc_to_view;import bevy_render::maths::orthonormalize;+import raea_sys_fog::froxel_volume::volume_weight;struct Params {view_from_clip: mat4x4<f32>,@@ -219,10 +220,10 @@ fn medium(hero: Hero, p: vec3<f32>) -> vec3<f32> {for (var v = 0u; v < params.counts.x; v += 1u) {let vol = &volumes[v];let local = ((*vol).local_from_world * vec4(p, 1.0)).xyz;- if (any(abs(local) > vec3(0.5))) {+ let w = volume_weight((*vol).shape, local);+ if (w <= 0.0) {continue;}- let w = exp(-(*vol).shape.x * (local.y + 0.5) * (*vol).shape.y);var phase = 1.0;if (hero.kind == 1u) {phase = henyey_greenstein((*vol).ambient.a, hero.cos_view);diff --git a/systems/fog/src/froxel_light.wesl b/systems/fog/src/froxel_light.weslindex 27cb6d30..7f83d681 100644--- a/systems/fog/src/froxel_light.wesl+++ b/systems/fog/src/froxel_light.wesl@@ -23,6 +23,7 @@ import bevy_pbr::render::view_transformations::position_ndc_to_view;import bevy_render::maths::orthonormalize;import bevy_pbr::render::clustered_forward as clustering;import bevy_pbr::render::pbr_lighting::getDistanceAttenuation;+import raea_sys_fog::froxel_volume::volume_weight;struct Params {view_from_clip: mat4x4<f32>,@@ -86,11 +87,11 @@ fn medium_light(P_view: vec3<f32>, pixel: vec2<f32>) -> vec4<f32> {for (var v = 0u; v < params.counts.x; v += 1u) {let vol = &volumes[v];let local = ((*vol).local_from_world * vec4(P_world, 1.0)).xyz;- if (any(abs(local) > vec3(0.5))) {+ // thinning going up, the taper and the feathered faces (froxel_volume.wesl)+ let w = volume_weight((*vol).shape, local);+ if (w <= 0.0) {continue;}- // thinning going up from the box's floor- let w = exp(-(*vol).shape.x * (local.y + 0.5) * (*vol).shape.y);sigma_t += (*vol).scatter.a * w;k += (*vol).scatter.rgb * w;amb += (*vol).ambient.rgb * w;diff --git a/systems/fog/src/froxel_solari.wesl b/systems/fog/src/froxel_solari.weslindex 362b0041..b84b5b3a 100644--- a/systems/fog/src/froxel_solari.wesl+++ b/systems/fog/src/froxel_solari.wesl@@ -15,6 +15,7 @@ import bevy_render::maths::{PI_2, orthonormalize};import bevy_pbr::render::utils::{rand_f, rand_vec2f};import bevy_solari::scene::bindings::{trace_ray, light_sources, RAY_T_MIN, RAY_T_MAX};import bevy_solari::scene::sampling::{generate_random_light_sample, trace_visibility, sample_environment_map_light, ResolvedLightSample};+import raea_sys_fog::froxel_volume::volume_weight;enable wgpu_ray_query;@@ -113,10 +114,11 @@ fn medium(P: vec3<f32>) -> vec4<f32> {for (var v = 0u; v < params.counts.x; v += 1u) {let vol = &volumes[v];let local = ((*vol).local_from_world * vec4(P, 1.0)).xyz;- if (any(abs(local) > vec3(0.5))) {+ let w = volume_weight((*vol).shape, local);+ if (w <= 0.0) {continue;}- let s = (*vol).ambient.rgb * exp(-(*vol).shape.x * (local.y + 0.5) * (*vol).shape.y);+ let s = (*vol).ambient.rgb * w;sigma_s += s;g += (*vol).ambient.a * dot(s, LUMA);share += dot(s, LUMA);diff --git a/systems/fog/src/froxel_volume.wesl b/systems/fog/src/froxel_volume.weslnew file mode 100644index 00000000..997ebd9b--- /dev/null+++ b/systems/fog/src/froxel_volume.wesl@@ -0,0 +1,25 @@+// A fog volume's shape as the froxel passes read it (froxel_light, froxel_hero, froxel_solari): how much of its density+// a point in its box has. froxel.rs packs `shape`: x the thinning per metre going up (`falloff`), y the box's height in+// metres, z the feathered share of the box's half-size at every face (`soft`), w how much narrower its floor is than+// its top (`taper`).++// The density at `local` (the box's own coordinates, -0.5 to 0.5) over the volume's density: 0 outside its shape.+// Thinning is exp(-falloff x metres above the floor). Taper narrows the box's width and depth linearly toward the floor,+// to 1 - taper of the top's (a plume rising off a tank). Soft ramps the density in from each face (the tapered sides+// too) over that share of the half-size with a smoothstep, so the box's edges don't show (0: a hard box).+fn volume_weight(shape: vec4<f32>, local: vec3<f32>) -> f32 {+ let up = local.y + 0.5;+ let wide = max(1.0 - shape.w * (1.0 - up), 1e-3);+ let across = abs(local.xz) / wide;+ if (any(across > vec2(0.5)) || abs(local.y) > 0.5) {+ return 0.0;+ }+ var w = exp(-shape.x * up * shape.y);+ if (shape.z > 0.0) {+ let inside = (vec3(0.5) - vec3(across.x, abs(local.y), across.y)) * 2.0 / shape.z;+ let e = clamp(inside, vec3(0.0), vec3(1.0));+ let s = e * e * (3.0 - 2.0 * e);+ w *= s.x * s.y * s.z;+ }+ return w;+}