use std::sync::Arc;
use crate::cameras::Camera;
use crate::renderer::fullscreen::{self, draw, draw_timed, DoubleFbo, Fbo, Load};
use crate::Vector3;
use super::passes::FluidFormats;
use super::PressureSolver;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FluidConfig3d {
pub resolution: u32,
pub dye_resolution: u32,
pub density_dissipation: f32,
pub velocity_dissipation: f32,
pub pressure: f32,
pub pressure_iterations: u32,
pub time_scale: f32,
pub pressure_solver: PressureSolver,
pub multigrid_cycles: u32,
pub multigrid_smooth: u32,
pub multigrid_coarsest: u32,
pub cache_bindings: bool,
pub show_fps: bool,
pub temporal_samples: u32,
pub temporal_clip: f32,
pub empty_space_skip: bool,
pub compact_dye: bool,
pub curl: f32,
pub gradient_scale: f32,
pub splat_radius: f32,
pub splat_force: f32,
pub buoyancy: f32,
pub buoyancy_axis: [f32; 3],
pub march_steps: u32,
pub absorption: f32,
pub emission: f32,
pub exposure: f32,
pub background: [f32; 3],
pub transparent: bool,
pub bounds_min: [f32; 3],
pub bounds_max: [f32; 3],
pub seed: u64,
}
#[derive(Clone, Copy, Debug)]
pub struct FluidQuality3d {
pub name: &'static str,
pub resolution: u32,
pub dye_resolution: u32,
pub pressure_iterations: u32,
pub march_steps: u32,
}
pub const QUALITY_LEVELS_3D: &[FluidQuality3d] = &[
FluidQuality3d {
name: "low",
resolution: 24,
dye_resolution: 48,
pressure_iterations: 16,
march_steps: 48,
},
FluidQuality3d {
name: "medium",
resolution: 40,
dye_resolution: 80,
pressure_iterations: 18,
march_steps: 64,
},
FluidQuality3d {
name: "high",
resolution: 64,
dye_resolution: 128,
pressure_iterations: 20,
march_steps: 96,
},
FluidQuality3d {
name: "ultra",
resolution: 96,
dye_resolution: 192,
pressure_iterations: 24,
march_steps: 128,
},
FluidQuality3d {
name: "extreme",
resolution: 128,
dye_resolution: 256,
pressure_iterations: 28,
march_steps: 192,
},
];
pub fn memory_for(resolution: u32, dye_resolution: u32, formats: FluidFormats) -> u64 {
let texels = |grid: u32| {
let a = Atlas::new(grid);
let (w, h) = a.size();
w as u64 * h as u64
};
let size = |f: wgpu::TextureFormat| crate::renderer::readback::bytes_per_texel(f) as u64;
let (vec3, dye_fmt, scalar) = (
size(formats.dye),
size(formats.volume_dye),
size(formats.scalar),
);
let sim = texels(resolution.max(2));
let dye = texels(dye_resolution.max(2));
let mut total = sim * (2 * vec3 + 2 * scalar + scalar + vec3 + scalar);
total += dye * 2 * dye_fmt;
let mut n = resolution.max(2);
let mut levels = 0;
while n / 2 >= MG_COARSEST_3D && levels < 6 {
n /= 2;
levels += 1;
total += texels(n) * 4 * scalar;
}
total += (texels(dye_resolution / 2) + texels(dye_resolution / 4)) * scalar;
total
}
pub fn within_memory(budget: u64, ratio: u32, formats: FluidFormats) -> (u32, u32) {
let ratio = ratio.max(1);
let mut best = (8u32, 8 * ratio);
for solver in (8..=512).step_by(8) {
let dye = solver * ratio;
if memory_for(solver, dye, formats) > budget {
break;
}
best = (solver, dye);
}
best
}
pub fn quality3d(name: &str) -> Option<&'static FluidQuality3d> {
QUALITY_LEVELS_3D.iter().find(|q| q.name == name)
}
pub fn quality3d_names() -> impl Iterator<Item = &'static str> {
QUALITY_LEVELS_3D.iter().map(|q| q.name)
}
impl FluidConfig3d {
pub fn with_quality(mut self, quality: &FluidQuality3d) -> Self {
self.resolution = quality.resolution;
self.dye_resolution = quality.dye_resolution;
self.pressure_iterations = quality.pressure_iterations;
self.march_steps = quality.march_steps;
self
}
}
impl Default for FluidConfig3d {
fn default() -> Self {
Self {
resolution: 64,
dye_resolution: 128,
density_dissipation: 0.4,
velocity_dissipation: 0.2,
pressure: 1.0,
pressure_iterations: 20,
time_scale: 1.0,
pressure_solver: PressureSolver::Multigrid,
multigrid_cycles: 1,
multigrid_smooth: 2,
multigrid_coarsest: 4,
cache_bindings: true,
show_fps: false,
temporal_samples: 1,
temporal_clip: 0.5,
empty_space_skip: true,
compact_dye: false,
curl: 12.0,
gradient_scale: 1.0,
splat_radius: 0.6,
splat_force: 6.0,
buoyancy: 0.0,
buoyancy_axis: [0.0, 1.0, 0.0],
march_steps: 96,
absorption: 28.0,
emission: 1.2,
exposure: 1.0,
background: [0.015, 0.015, 0.025],
transparent: false,
bounds_min: [-0.5, -0.5, -0.5],
bounds_max: [0.5, 0.5, 0.5],
seed: 0x5EED_F101_D1CE,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Atlas {
pub grid: u32,
pub tiles: (u32, u32),
}
impl Atlas {
pub fn new(grid: u32) -> Self {
let grid = grid.max(2);
let across = (grid as f32).sqrt().ceil() as u32;
let down = grid.div_ceil(across);
Self {
grid,
tiles: (across, down),
}
}
pub fn size(&self) -> (u32, u32) {
(self.grid * self.tiles.0, self.grid * self.tiles.1)
}
pub fn largest_within(mut grid: u32, max: u32) -> Self {
loop {
let a = Self::new(grid);
let (w, h) = a.size();
if (w <= max && h <= max) || grid <= 8 {
return a;
}
grid /= 2;
}
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]
struct GridUniform {
size: [f32; 4],
tiles: [f32; 4],
}
impl From<Atlas> for GridUniform {
fn from(a: Atlas) -> Self {
let n = a.grid as f32;
let (tx, ty) = (a.tiles.0 as f32, a.tiles.1 as f32);
Self {
size: [n, n, n, 1.0 / n],
tiles: [tx, ty, 1.0 / tx, 1.0 / ty],
}
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]
struct Vol {
out_grid: GridUniform,
a_grid: GridUniform,
b_grid: GridUniform,
texel: [f32; 4],
point: [f32; 4],
color: [f32; 4],
params: [f32; 4],
bounds_min: [f32; 4],
bounds_max: [f32; 4],
march: [f32; 4],
background: [f32; 4],
cam_pos: [f32; 4],
inv_view_proj: [f32; 16],
prev_view_proj: [f32; 16],
}
const VOL_SIZE: u64 = std::mem::size_of::<Vol>() as u64;
pub struct FluidSim3d {
device: Arc<wgpu::Device>,
queue: Arc<wgpu::Queue>,
config: FluidConfig3d,
formats: FluidFormats,
sim: Atlas,
dye_atlas: Atlas,
velocity: DoubleFbo,
dye: DoubleFbo,
pressure: DoubleFbo,
divergence: Fbo,
curl: Fbo,
residual: Fbo,
mg: Vec<MgLevel3>,
occupancy: [(Atlas, Fbo); 2],
occupancy_stale: std::cell::Cell<bool>,
bgl: wgpu::BindGroupLayout,
sampler: wgpu::Sampler,
pipes: Pipes,
out: fullscreen::FormatPipelines<wgpu::RenderPipeline>,
accum_march: Option<wgpu::RenderPipeline>,
resolve: fullscreen::FormatPipelines<wgpu::RenderPipeline>,
overlay: fullscreen::FormatPipelines<wgpu::RenderPipeline>,
layout: wgpu::PipelineLayout,
module: wgpu::ShaderModule,
ubos: std::cell::RefCell<Vec<wgpu::Buffer>>,
next_ubo: std::cell::Cell<usize>,
ubo_contents: std::cell::RefCell<Vec<Vol>>,
profiler: Option<crate::renderer::gpu_timer::GpuTimer>,
rate: super::read_out::Rate,
history: super::read_out::History,
current: Option<Fbo>,
depth: Option<Fbo>,
view_proj: [f32; 16],
view_proj_inverse: [f32; 16],
accum: Option<DoubleFbo>,
accum_from: Option<[f32; 16]>,
accum_frame: u32,
passes: std::cell::Cell<u32>,
mark: std::cell::Cell<u32>,
binds: std::cell::RefCell<std::collections::HashMap<(usize, u64, u64), wgpu::BindGroup>>,
rng: super::Rng,
paused: bool,
}
struct Pipes {
fill: wgpu::RenderPipeline,
buoyancy: wgpu::RenderPipeline,
splat_velocity: wgpu::RenderPipeline,
splat_dye: wgpu::RenderPipeline,
advect_velocity: wgpu::RenderPipeline,
advect_dye: wgpu::RenderPipeline,
divergence: wgpu::RenderPipeline,
curl: wgpu::RenderPipeline,
vorticity: wgpu::RenderPipeline,
pressure: wgpu::RenderPipeline,
gradient: wgpu::RenderPipeline,
maxdown: wgpu::RenderPipeline,
residual: wgpu::RenderPipeline,
restrict: wgpu::RenderPipeline,
prolong: wgpu::RenderPipeline,
}
pub const STAGE_NAMES: [&str; 5] = ["curl+vort", "divergence", "solve", "project", "advect"];
const MARKS: u32 = STAGE_NAMES.len() as u32 + 1;
fn occupancy_levels(
device: &wgpu::Device,
dye_grid: u32,
format: wgpu::TextureFormat,
) -> [(Atlas, Fbo); 2] {
let level = |n: u32| {
let atlas = Atlas::new(n.max(2));
let (w, h) = atlas.size();
(atlas, Fbo::new(device, "fluid3d occupancy", w, h, format))
};
[level(dye_grid / 2), level(dye_grid / 4)]
}
fn packed_dye(
device: &wgpu::Device,
config: &FluidConfig3d,
formats: FluidFormats,
) -> wgpu::TextureFormat {
if !config.compact_dye {
return formats.resolve(false).volume_dye;
}
if device
.features()
.contains(wgpu::Features::RG11B10UFLOAT_RENDERABLE)
{
wgpu::TextureFormat::Rg11b10Ufloat
} else {
formats.dye
}
}
struct Ubo {
buffer: wgpu::Buffer,
slot: usize,
}
const MG_COARSEST_3D: u32 = 4;
struct MgLevel3 {
atlas: Atlas,
pressure: DoubleFbo,
rhs: Fbo,
residual: Fbo,
}
fn mg_levels3(
device: &wgpu::Device,
grid: u32,
coarsest: u32,
format: wgpu::TextureFormat,
) -> Vec<MgLevel3> {
let mut levels = Vec::new();
let mut n = grid;
let coarsest = coarsest.max(MG_COARSEST_3D);
while n / 2 >= coarsest && levels.len() < 6 {
n /= 2;
let atlas = Atlas::new(n);
let (w, h) = atlas.size();
levels.push(MgLevel3 {
atlas,
pressure: DoubleFbo::new(device, "fluid3d mg pressure", w, h, format),
rhs: Fbo::new(device, "fluid3d mg rhs", w, h, format),
residual: Fbo::new(device, "fluid3d mg residual", w, h, format),
});
}
levels
}
impl FluidSim3d {
pub fn new(
device: Arc<wgpu::Device>,
queue: Arc<wgpu::Queue>,
config: FluidConfig3d,
) -> Result<Self, String> {
Self::with_formats(device, queue, config, FluidFormats::default())
}
pub fn with_formats(
device: Arc<wgpu::Device>,
queue: Arc<wgpu::Queue>,
config: FluidConfig3d,
formats: FluidFormats,
) -> Result<Self, String> {
if config.pressure_iterations == 0 {
return Err("fluid3d: pressure_iterations must be at least 1".into());
}
let max = device.limits().max_texture_dimension_2d;
let sim = Atlas::largest_within(config.resolution, max);
let dye_atlas = Atlas::largest_within(config.dye_resolution, max);
let formats = FluidFormats {
volume_dye: packed_dye(&device, &config, formats),
..formats
};
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers fluid3d bgl"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: wgpu::BufferSize::new(VOL_SIZE),
},
count: None,
},
tex(1),
tex(2),
tex(4),
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers fluid3d layout"),
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers fluid3d"),
source: wgpu::ShaderSource::Wgsl(
format!(
"{}\n{}\n{}",
fullscreen::VS,
super::read_out::glyphs(),
super::volume_shader::SHADER
)
.into(),
),
});
let vec_fmt = formats.dye;
let dye_fmt = formats.volume_dye;
let scalar = formats.scalar;
let p = |fs: &str, format| build(&device, &layout, &module, fs, format);
let pipes = Pipes {
fill: p("fs_fill3", vec_fmt),
buoyancy: p("fs_buoyancy3", vec_fmt),
splat_velocity: p("fs_splat3", vec_fmt),
splat_dye: p("fs_splat3", dye_fmt),
advect_velocity: p("fs_advect3_self", vec_fmt),
advect_dye: p("fs_advect3", dye_fmt),
divergence: p("fs_divergence3", scalar),
curl: p("fs_curl3", vec_fmt),
vorticity: p("fs_vorticity3", vec_fmt),
pressure: p("fs_pressure3", scalar),
gradient: p("fs_gradient3", vec_fmt),
maxdown: p("fs_maxdown3", scalar),
residual: p("fs_residual3", scalar),
restrict: p("fs_restrict3", scalar),
prolong: p("fs_prolong3", scalar),
};
let (sw, sh) = sim.size();
let (dw, dh) = dye_atlas.size();
Ok(Self {
velocity: DoubleFbo::new(&device, "fluid3d velocity", sw, sh, vec_fmt),
dye: DoubleFbo::new(&device, "fluid3d dye", dw, dh, dye_fmt),
pressure: DoubleFbo::new(&device, "fluid3d pressure", sw, sh, scalar),
divergence: Fbo::new(&device, "fluid3d divergence", sw, sh, scalar),
curl: Fbo::new(&device, "fluid3d curl", sw, sh, vec_fmt),
residual: Fbo::new(&device, "fluid3d residual", sw, sh, scalar),
mg: mg_levels3(&device, sim.grid, config.multigrid_coarsest, scalar),
occupancy: occupancy_levels(&device, dye_atlas.grid, scalar),
occupancy_stale: std::cell::Cell::new(true),
sampler: fullscreen::linear_sampler(&device),
ubos: std::cell::RefCell::new((0..48).map(|_| ubo(&device)).collect()),
next_ubo: std::cell::Cell::new(0),
profiler: None,
rate: Default::default(),
history: Default::default(),
current: None,
depth: None,
view_proj: [0.0; 16],
view_proj_inverse: [0.0; 16],
accum: None,
accum_from: None,
accum_frame: 0,
passes: std::cell::Cell::new(0),
mark: std::cell::Cell::new(0),
ubo_contents: std::cell::RefCell::new(Vec::new()),
binds: std::cell::RefCell::new(std::collections::HashMap::new()),
rng: super::Rng::new(config.seed),
device,
queue,
config,
formats,
sim,
dye_atlas,
bgl,
pipes,
out: fullscreen::FormatPipelines::new(),
accum_march: None,
resolve: fullscreen::FormatPipelines::new(),
overlay: fullscreen::FormatPipelines::new(),
layout,
module,
paused: false,
})
}
pub fn config(&self) -> &FluidConfig3d {
&self.config
}
pub fn set_config(&mut self, config: FluidConfig3d) {
let (solver, dye) = (config.resolution, config.dye_resolution);
let refmt = packed_dye(&self.device, &config, self.formats) != self.formats.volume_dye;
let relevel = config.multigrid_coarsest != self.config.multigrid_coarsest;
self.config = config;
if refmt || relevel {
self.formats.volume_dye = packed_dye(&self.device, &self.config, self.formats);
self.rebuild_fields();
}
self.set_resolution(solver, dye);
self.ubo_contents.borrow_mut().clear();
}
pub fn set_resolution(&mut self, solver: u32, dye: u32) {
let max = self.device.limits().max_texture_dimension_2d;
let sim = Atlas::largest_within(solver.max(2), max);
let dye_atlas = Atlas::largest_within(dye.max(2), max);
self.config.resolution = solver;
self.config.dye_resolution = dye;
if sim.grid == self.sim.grid && dye_atlas.grid == self.dye_atlas.grid {
return;
}
self.sim = sim;
self.dye_atlas = dye_atlas;
self.rebuild_fields();
}
fn rebuild_fields(&mut self) {
let (sw, sh) = self.sim.size();
let (dw, dh) = self.dye_atlas.size();
let vec_fmt = self.formats.dye;
let scalar = self.formats.scalar;
self.velocity = DoubleFbo::new(&self.device, "fluid3d velocity", sw, sh, vec_fmt);
self.dye = DoubleFbo::new(&self.device, "fluid3d dye", dw, dh, self.formats.volume_dye);
self.pressure = DoubleFbo::new(&self.device, "fluid3d pressure", sw, sh, scalar);
self.divergence = Fbo::new(&self.device, "fluid3d divergence", sw, sh, scalar);
self.curl = Fbo::new(&self.device, "fluid3d curl", sw, sh, vec_fmt);
self.residual = Fbo::new(&self.device, "fluid3d residual", sw, sh, scalar);
self.mg = mg_levels3(
&self.device,
self.sim.grid,
self.config.multigrid_coarsest,
scalar,
);
self.occupancy = occupancy_levels(&self.device, self.dye_atlas.grid, scalar);
self.occupancy_stale.set(true);
self.binds.borrow_mut().clear();
self.clear_fields();
}
fn clear_fields(&mut self) {
let mut enc = self.encoder("fluid3d clear");
for target in [
&self.velocity.read.view,
&self.velocity.write.view,
&self.pressure.read.view,
&self.pressure.write.view,
&self.divergence.view,
&self.curl.view,
&self.dye.read.view,
&self.dye.write.view,
] {
fullscreen::begin(&mut enc, target, Load::Clear);
}
self.queue.submit([enc.finish()]);
}
pub fn solver_levels(&self) -> usize {
self.mg.len()
}
pub fn grids(&self) -> (u32, u32) {
(self.sim.grid, self.dye_atlas.grid)
}
pub fn memory_bytes(&self) -> u64 {
let bytes = |f: &Fbo| {
crate::renderer::readback::bytes_per_texel(f.texture.format()) as u64
* f.width as u64
* f.height as u64
};
let double = |f: &DoubleFbo| bytes(&f.read) + bytes(&f.write);
double(&self.velocity)
+ double(&self.dye)
+ double(&self.pressure)
+ bytes(&self.divergence)
+ bytes(&self.curl)
+ bytes(&self.residual)
+ self
.mg
.iter()
.map(|l| double(&l.pressure) + bytes(&l.rhs) + bytes(&l.residual))
.sum::<u64>()
+ self.occupancy.iter().map(|(_, f)| bytes(f)).sum::<u64>()
}
pub fn formats(&self) -> FluidFormats {
self.formats
}
pub fn fps(&self) -> f32 {
self.rate.fps()
}
pub fn profile(&mut self) -> bool {
if self.profiler.is_none() {
self.profiler =
crate::renderer::gpu_timer::GpuTimer::with_marks(&self.device, &self.queue, MARKS);
}
self.profiler.is_some()
}
pub fn stage_ms(&self) -> [f32; STAGE_NAMES.len()] {
let mut out = [0.0; STAGE_NAMES.len()];
if let Some(p) = &self.profiler {
for (i, slot) in out.iter_mut().enumerate() {
*slot = p.span_ms(i);
}
}
out
}
pub fn passes_per_step(&self) -> u32 {
self.passes.get()
}
fn pass(
&self,
enc: &mut wgpu::CommandEncoder,
target: &wgpu::TextureView,
load: Load,
pipeline: &wgpu::RenderPipeline,
bind: &wgpu::BindGroup,
marks: Option<wgpu::RenderPassTimestampWrites<'_>>,
) {
self.passes.set(self.passes.get() + 1);
draw_timed(enc, target, load, pipeline, bind, marks);
}
fn take_mark(&self, stage: u32) -> Option<u32> {
if self.profiler.is_none() || self.mark.get() != stage {
return None;
}
self.mark.set(stage + 1);
Some(stage)
}
fn writes(&self, mark: Option<u32>) -> Option<wgpu::RenderPassTimestampWrites<'_>> {
match (mark, &self.profiler) {
(Some(i), Some(p)) => Some(p.mark(i)),
_ => None,
}
}
fn open(&self, stage: u32) -> Option<wgpu::RenderPassTimestampWrites<'_>> {
let mark = self.take_mark(stage);
self.writes(mark)
}
pub fn paused(&self) -> bool {
self.paused
}
pub fn set_paused(&mut self, paused: bool) {
self.paused = paused;
}
pub fn dye_texture(&self) -> &wgpu::Texture {
&self.dye.read.texture
}
pub fn dye_atlas(&self) -> Atlas {
self.dye_atlas
}
pub fn splat(&mut self, at: [f32; 3], velocity: [f32; 3], color: [f32; 3]) {
self.splat_batch(&[(at, velocity, color)]);
}
pub fn impulse_at_screen(
&mut self,
camera: &dyn Camera,
uv: [f32; 2],
drag: [f32; 2],
strength: f32,
colour: [f32; 3],
) {
let inv = camera
.projection_matrix()
.multiply(&camera.view_matrix())
.invert();
let ray = |uv: [f32; 2]| -> (Vector3, Vector3) {
let ndc =
|z: f32| Vector3::new(uv[0] * 2.0 - 1.0, 1.0 - uv[1] * 2.0, z).apply_matrix4(&inv);
let near = ndc(0.0);
let far = ndc(1.0);
(near, (far - near).normalize())
};
let c = self.config;
let centre = Vector3::new(
0.5 * (c.bounds_min[0] + c.bounds_max[0]),
0.5 * (c.bounds_min[1] + c.bounds_max[1]),
0.5 * (c.bounds_min[2] + c.bounds_max[2]),
);
let eye = camera.position();
let normal = (centre - eye).normalize();
let on_plane = |uv: [f32; 2]| -> Option<Vector3> {
let (origin, dir) = ray(uv);
let denom = dir.dot(normal);
if denom.abs() < 1e-6 {
return None;
}
let t = (centre - origin).dot(normal) / denom;
if t <= 0.0 {
return None;
}
Some(origin + dir * t)
};
let Some(hit) = on_plane(uv) else { return };
let size = Vector3::new(
c.bounds_max[0] - c.bounds_min[0],
c.bounds_max[1] - c.bounds_min[1],
c.bounds_max[2] - c.bounds_min[2],
);
let at = [
(hit.x - c.bounds_min[0]) / size.x,
(hit.y - c.bounds_min[1]) / size.y,
(hit.z - c.bounds_min[2]) / size.z,
];
if at.iter().any(|v| !(0.0..=1.0).contains(v)) {
return;
}
let moved = on_plane([uv[0] + drag[0], uv[1] + drag[1]])
.map(|to| to - hit)
.unwrap_or(Vector3::ZERO);
let scale = strength * self.sim.grid as f32;
self.splat(
at,
[
moved.x / size.x * scale,
moved.y / size.y * scale,
moved.z / size.z * scale,
],
colour,
);
}
pub fn multiple_splats(&mut self, count: u32) {
let mut batch = Vec::with_capacity(count as usize);
for _ in 0..count {
let hue = self.rng.next_f32();
let c = super::hsv_to_rgb(hue, 1.0, 1.0);
let at = [
0.2 + 0.6 * self.rng.next_f32(),
0.2 + 0.6 * self.rng.next_f32(),
0.2 + 0.6 * self.rng.next_f32(),
];
let z = 2.0 * self.rng.next_f32() - 1.0;
let theta = std::f32::consts::TAU * self.rng.next_f32();
let r = (1.0 - z * z).max(0.0).sqrt();
let speed = 120.0 + 180.0 * self.rng.next_f32();
let v = [r * theta.cos() * speed, z * speed, r * theta.sin() * speed];
batch.push((at, v, [c[0] * 1.5, c[1] * 1.5, c[2] * 1.5]));
}
self.splat_batch(&batch);
}
fn splat_batch(&mut self, splats: &[([f32; 3], [f32; 3], [f32; 3])]) {
let radius = self.config.splat_radius / 100.0;
for (at, vel, color) in splats {
let mut enc = self.encoder("fluid3d splat");
self.next_ubo.set(0);
for dye in [false, true] {
let field = if dye { &self.dye } else { &self.velocity };
let atlas = if dye { self.dye_atlas } else { self.sim };
let value = if dye { *color } else { *vel };
let u = self.params(
atlas,
Vol {
point: [at[0], at[1], at[2], radius],
color: [value[0], value[1], value[2], 1.0],
..Default::default()
},
);
let bg = self.bind(&u, &field.read, None);
let pipe = if dye {
&self.pipes.splat_dye
} else {
&self.pipes.splat_velocity
};
draw(&mut enc, &field.write.view, Load::Clear, pipe, &bg);
}
self.queue.submit([enc.finish()]);
self.velocity.swap();
self.dye.swap();
self.occupancy_stale.set(true);
}
}
pub fn set_uniform_velocity(&mut self, v: [f32; 3]) {
let mut enc = self.encoder("fluid3d fill");
self.next_ubo.set(0);
let u = self.params(
self.sim,
Vol {
color: [v[0], v[1], v[2], 0.0],
..Default::default()
},
);
let bg = self.bind(&u, &self.velocity.read, None);
draw(
&mut enc,
&self.velocity.write.view,
Load::Clear,
&self.pipes.fill,
&bg,
);
self.queue.submit([enc.finish()]);
self.velocity.swap();
}
pub fn update(&mut self, dt: f32) {
let dt = dt * self.config.time_scale.max(0.0);
if !self.paused && dt > 0.0 {
self.step(dt);
}
}
pub fn step(&mut self, dt: f32) {
let c = self.config;
let mut enc = self.encoder("fluid3d step");
self.next_ubo.set(0);
self.mark.set(0);
self.passes.set(0);
let axis = {
let a = c.buoyancy_axis;
let len = (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]).sqrt();
if len > 1e-6 {
[a[0] / len, a[1] / len, a[2] / len]
} else {
[0.0; 3]
}
};
if c.buoyancy != 0.0 && axis != [0.0; 3] {
let u = self.params_mixed(
self.sim,
self.sim,
self.dye_atlas,
Vol {
texel: [0.0, 0.0, 0.0, dt],
params: [0.0, c.buoyancy, 0.0, 0.0],
color: [axis[0], axis[1], axis[2], 0.0],
..Default::default()
},
);
let bg = self.bind(&u, &self.velocity.read, Some(&self.dye.read));
self.pass(
&mut enc,
&self.velocity.write.view,
Load::Clear,
&self.pipes.buoyancy,
&bg,
self.open(0),
);
self.velocity.swap();
}
if c.curl != 0.0 {
let u = self.params(self.sim, Vol::default());
let bg = self.bind(&u, &self.velocity.read, None);
self.pass(
&mut enc,
&self.curl.view,
Load::Clear,
&self.pipes.curl,
&bg,
self.open(0),
);
let u = self.params(
self.sim,
Vol {
texel: [0.0, 0.0, 0.0, dt],
params: [0.0, c.curl, 0.0, 0.0],
..Default::default()
},
);
let bg = self.bind(&u, &self.velocity.read, Some(&self.curl));
self.pass(
&mut enc,
&self.velocity.write.view,
Load::Clear,
&self.pipes.vorticity,
&bg,
None,
);
self.velocity.swap();
}
let u = self.params(self.sim, Vol::default());
let bg = self.bind(&u, &self.velocity.read, None);
self.pass(
&mut enc,
&self.divergence.view,
Load::Clear,
&self.pipes.divergence,
&bg,
self.open(1),
);
let open = self.take_mark(2);
match c.pressure_solver {
PressureSolver::Jacobi => {
self.record_jacobi(&mut enc, c.pressure_iterations, c.pressure, open)
}
PressureSolver::Multigrid => self.record_multigrid(&mut enc, open),
}
let u = self.params(
self.sim,
Vol {
params: [0.0, 0.0, c.gradient_scale, 0.0],
..Default::default()
},
);
let bg = self.bind(&u, &self.pressure.read, Some(&self.velocity.read));
self.pass(
&mut enc,
&self.velocity.write.view,
Load::Clear,
&self.pipes.gradient,
&bg,
self.open(3),
);
self.velocity.swap();
let u = self.params(
self.sim,
Vol {
texel: [0.0, 0.0, 0.0, dt],
params: [c.velocity_dissipation, 0.0, 0.0, 0.0],
..Default::default()
},
);
let bg = self.bind(&u, &self.velocity.read, Some(&self.velocity.read));
self.pass(
&mut enc,
&self.velocity.write.view,
Load::Clear,
&self.pipes.advect_velocity,
&bg,
self.open(4),
);
self.velocity.swap();
let u = self.params_mixed(
self.dye_atlas,
self.sim,
self.dye_atlas,
Vol {
texel: [0.0, 0.0, 0.0, dt],
params: [c.density_dissipation, 0.0, 0.0, 0.0],
..Default::default()
},
);
let bg = self.bind(&u, &self.velocity.read, Some(&self.dye.read));
self.pass(
&mut enc,
&self.dye.write.view,
Load::Clear,
&self.pipes.advect_dye,
&bg,
None,
);
self.dye.swap();
self.occupancy_stale.set(true);
self.queue.submit([enc.finish()]);
}
fn record_jacobi(
&mut self,
enc: &mut wgpu::CommandEncoder,
count: u32,
first_scale: f32,
open: Option<u32>,
) {
if count == 0 {
return;
}
let scaled = self.params(
self.sim,
Vol {
params: [0.0, 0.0, first_scale, 0.0],
..Default::default()
},
);
let plain = self.params(
self.sim,
Vol {
params: [0.0, 0.0, 1.0, 0.0],
..Default::default()
},
);
let groups = [
self.bind(&scaled, &self.pressure.read, Some(&self.divergence)),
self.bind(&scaled, &self.pressure.write, Some(&self.divergence)),
self.bind(&plain, &self.pressure.read, Some(&self.divergence)),
self.bind(&plain, &self.pressure.write, Some(&self.divergence)),
];
let mut marks = self.writes(open);
for i in 0..count {
let even = i % 2 == 0;
let bg = &groups[usize::from(i > 0) * 2 + usize::from(!even)];
let target = if even {
&self.pressure.write.view
} else {
&self.pressure.read.view
};
self.pass(
enc,
target,
Load::Clear,
&self.pipes.pressure,
bg,
marks.take(),
);
}
if count % 2 == 1 {
self.pressure.swap();
}
}
fn record_multigrid(&mut self, enc: &mut wgpu::CommandEncoder, open: Option<u32>) {
if self.mg.is_empty() {
let (count, scale) = (self.config.pressure_iterations, self.config.pressure);
self.record_jacobi(enc, count, scale, open);
return;
}
let nu = self.config.multigrid_smooth.max(1);
let coarsest = self.mg.last().map(|l| l.atlas.grid).unwrap_or(4);
let coarse_sweeps = (2 * coarsest).clamp(nu * 2, self.config.pressure_iterations.max(8));
let mut open = open;
for cycle in 0..self.config.multigrid_cycles.max(1) {
let scale = if cycle == 0 {
self.config.pressure
} else {
1.0
};
self.record_jacobi(enc, nu, scale, open.take());
for level in 0..self.mg.len() {
self.record_residual3(enc, level);
self.record_restrict3(enc, level);
let sweeps = if level + 1 == self.mg.len() {
coarse_sweeps
} else {
nu
};
self.record_smooth3(enc, level, sweeps, 0.0);
}
for level in (0..self.mg.len()).rev() {
self.record_prolong3(enc, level);
if level == 0 {
self.record_jacobi(enc, nu, 1.0, None);
} else {
self.record_smooth3(enc, level - 1, nu, 1.0);
}
}
}
}
fn record_smooth3(
&mut self,
enc: &mut wgpu::CommandEncoder,
level: usize,
sweeps: u32,
first_scale: f32,
) {
if sweeps == 0 {
return;
}
let atlas = self.mg[level].atlas;
let scaled = self.params(
atlas,
Vol {
params: [0.0, 0.0, first_scale, 0.0],
..Default::default()
},
);
let plain = self.params(
atlas,
Vol {
params: [0.0, 0.0, 1.0, 0.0],
..Default::default()
},
);
let l = &self.mg[level];
let groups = [
self.bind(&scaled, &l.pressure.read, Some(&l.rhs)),
self.bind(&scaled, &l.pressure.write, Some(&l.rhs)),
self.bind(&plain, &l.pressure.read, Some(&l.rhs)),
self.bind(&plain, &l.pressure.write, Some(&l.rhs)),
];
for i in 0..sweeps {
let even = i % 2 == 0;
let bg = &groups[usize::from(i > 0) * 2 + usize::from(!even)];
let target = if even {
&l.pressure.write.view
} else {
&l.pressure.read.view
};
self.pass(enc, target, Load::Clear, &self.pipes.pressure, bg, None);
}
if sweeps % 2 == 1 {
self.mg[level].pressure.swap();
}
}
fn record_residual3(&mut self, enc: &mut wgpu::CommandEncoder, level: usize) {
let (atlas, pressure, rhs, target) = if level == 0 {
(
self.sim,
&self.pressure.read,
&self.divergence,
&self.residual,
)
} else {
let l = &self.mg[level - 1];
(l.atlas, &l.pressure.read, &l.rhs, &l.residual)
};
let u = self.params(atlas, Vol::default());
let bg = self.bind(&u, pressure, Some(rhs));
self.pass(
enc,
&target.view,
Load::Clear,
&self.pipes.residual,
&bg,
None,
);
}
fn record_restrict3(&mut self, enc: &mut wgpu::CommandEncoder, level: usize) {
let (fine_atlas, residual) = if level == 0 {
(self.sim, &self.residual)
} else {
let l = &self.mg[level - 1];
(l.atlas, &l.residual)
};
let coarse = self.mg[level].atlas;
let u = self.params_mixed(coarse, fine_atlas, fine_atlas, Vol::default());
let bg = self.bind(&u, residual, None);
self.pass(
enc,
&self.mg[level].rhs.view,
Load::Clear,
&self.pipes.restrict,
&bg,
None,
);
}
fn record_prolong3(&mut self, enc: &mut wgpu::CommandEncoder, level: usize) {
let coarse_atlas = self.mg[level].atlas;
let (fine_atlas, fine_read, fine_write) = if level == 0 {
(self.sim, &self.pressure.read, &self.pressure.write)
} else {
let l = &self.mg[level - 1];
(l.atlas, &l.pressure.read, &l.pressure.write)
};
let u = self.params_mixed(fine_atlas, coarse_atlas, fine_atlas, Vol::default());
let bg = self.bind(&u, &self.mg[level].pressure.read, Some(fine_read));
self.pass(
enc,
&fine_write.view,
Load::Clear,
&self.pipes.prolong,
&bg,
None,
);
if level == 0 {
self.pressure.swap();
} else {
self.mg[level - 1].pressure.swap();
}
}
fn record_occupancy(&self, enc: &mut wgpu::CommandEncoder, opening: Option<u32>) {
let mut source = (self.dye_atlas, &self.dye.read);
let mut marks = self.writes(opening);
for level in 0..self.occupancy.len() {
let (atlas, target) = &self.occupancy[level];
let u = self.params_mixed(*atlas, source.0, source.0, Vol::default());
let bg = self.bind(&u, source.1, None);
self.pass(
enc,
&target.view,
Load::Clear,
&self.pipes.maxdown,
&bg,
marks.take(),
);
source = (*atlas, target);
}
}
pub fn render(&mut self, camera: &dyn Camera, target: &wgpu::Texture) {
let view = target.create_view(&wgpu::TextureViewDescriptor::default());
let size = (target.width(), target.height());
self.render_to_view(camera, &view, target.format(), size);
}
pub fn render_to_view(
&mut self,
camera: &dyn Camera,
target: &wgpu::TextureView,
format: wgpu::TextureFormat,
size: (u32, u32),
) {
let c = self.config;
self.next_ubo.set(0);
let accumulating = self.prepare_accum(size);
let view_proj = camera.projection_matrix().multiply(&camera.view_matrix());
let inv = view_proj.invert();
self.view_proj = view_proj.elements;
self.view_proj_inverse = inv.elements;
let pos = camera.position();
let skip_floor = if c.empty_space_skip { 0.0008 } else { 0.0 };
let u = self.params_mixed(
self.dye_atlas,
self.dye_atlas,
self.occupancy[1].0,
Vol {
params: [skip_floor, self.accum_frame as f32, 0.0, 0.0],
bounds_min: [c.bounds_min[0], c.bounds_min[1], c.bounds_min[2], 0.0],
bounds_max: [c.bounds_max[0], c.bounds_max[1], c.bounds_max[2], 0.0],
march: [
c.march_steps.max(1) as f32,
c.absorption,
c.emission,
c.exposure,
],
background: [
c.background[0],
c.background[1],
c.background[2],
if c.transparent { 1.0 } else { 0.0 },
],
cam_pos: [pos.x, pos.y, pos.z, 1.0],
inv_view_proj: inv.elements,
prev_view_proj: self.accum_from.unwrap_or(view_proj.elements),
..Default::default()
},
);
let bg = self.bind(&u, &self.dye.read, Some(&self.occupancy[1].1));
let mut enc = self.encoder("fluid3d render");
if c.empty_space_skip && self.occupancy_stale.get() {
let closing = self.take_mark(STAGE_NAMES.len() as u32);
self.record_occupancy(&mut enc, closing);
self.occupancy_stale.set(false);
}
let mark = self.take_mark(STAGE_NAMES.len() as u32);
if accumulating {
self.record_accumulated_march(&mut enc, target, format, &bg, mark);
} else {
let (device, layout, module) = (&self.device, &self.layout, &self.module);
let pipeline = self.out.get_or_build(format, || {
build(device, layout, module, "fs_raymarch", format)
});
let marks = match (mark, &self.profiler) {
(Some(i), Some(p)) => Some(p.mark(i)),
_ => None,
};
draw_timed(&mut enc, target, Load::Clear, pipeline, &bg, marks);
}
let complete = self.mark.get() == MARKS;
if let Some(p) = &self.profiler {
if complete {
p.resolve(&mut enc);
}
}
if c.show_fps {
self.record_overlay(&mut enc, target, format);
}
self.queue.submit([enc.finish()]);
if let Some(p) = &mut self.profiler {
p.poll(&self.device);
}
if accumulating {
self.accum_frame += 1;
self.accum_from = Some(view_proj.elements);
}
self.rate.tick();
}
fn record_overlay(
&mut self,
enc: &mut wgpu::CommandEncoder,
target: &wgpu::TextureView,
format: wgpu::TextureFormat,
) {
let target_ms = self.rate.target_ms();
let scale_ms = self.rate.scale_ms();
let u = self.params(
self.dye_atlas,
Vol {
params: [self.rate.fps(), scale_ms, target_ms, 0.0],
..Default::default()
},
);
let history = {
let (device, queue) = (self.device.clone(), self.queue.clone());
self.history
.view(&device, &queue, self.rate.frames())
.clone()
};
let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("fluid3d read-out"),
layout: &self.bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: u.buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&history),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(&history),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::Sampler(&self.sampler),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::TextureView(&history),
},
],
});
let (device, layout, module) = (&self.device, &self.layout, &self.module);
let pipeline = self.overlay.get_or_build(format, || {
build_blended(
device,
layout,
module,
"fs_overlay3",
format,
wgpu::BlendState::ALPHA_BLENDING,
)
});
draw(enc, target, Load::Keep, pipeline, &bind);
}
fn prepare_accum(&mut self, size: (u32, u32)) -> bool {
if self.config.temporal_samples <= 1 {
self.accum = None;
self.current = None;
self.depth = None;
self.accum_from = None;
return false;
}
let (w, h) = (size.0.max(1), size.1.max(1));
let resized = !matches!(&self.current, Some(f) if f.width == w && f.height == h);
if resized {
let fmt = self.formats.dye;
self.current = Some(Fbo::new(&self.device, "fluid3d march", w, h, fmt));
self.accum = Some(DoubleFbo::new(&self.device, "fluid3d history", w, h, fmt));
self.depth = Some(Fbo::new(
&self.device,
"fluid3d march depth",
w,
h,
self.formats.scalar,
));
}
if resized {
self.accum_from = None;
self.accum_frame = 0;
}
true
}
fn record_accumulated_march(
&mut self,
enc: &mut wgpu::CommandEncoder,
target: &wgpu::TextureView,
format: wgpu::TextureFormat,
bg: &wgpu::BindGroup,
mark: Option<u32>,
) {
let weight = if self.accum_frame == 0 {
1.0
} else {
1.0 / self.config.temporal_samples.max(2) as f32
};
let accum_format = self.formats.dye;
let depth_format = self.formats.scalar;
if self.accum_march.is_none() {
self.accum_march = Some(build_targets(
&self.device,
&self.layout,
&self.module,
"fs_raymarch_depth",
&[Some(accum_format), Some(depth_format)],
));
}
{
let current = self.current.as_ref().expect("prepare_accum made one");
let depth = self.depth.as_ref().expect("prepare_accum made one");
let marks = match (mark, &self.profiler) {
(Some(i), Some(p)) => Some(p.mark(i)),
_ => None,
};
fn attach(view: &wgpu::TextureView) -> wgpu::RenderPassColorAttachment<'_> {
wgpu::RenderPassColorAttachment {
view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
}
}
let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("fluid3d march"),
color_attachments: &[Some(attach(¤t.view)), Some(attach(&depth.view))],
depth_stencil_attachment: None,
timestamp_writes: marks,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(self.accum_march.as_ref().expect("just built"));
pass.set_bind_group(0, bg, &[]);
pass.draw(0..3, 0..1);
}
let u = self.params(
self.dye_atlas,
Vol {
params: [0.0, 0.0, weight, self.config.temporal_clip],
inv_view_proj: self.view_proj_inverse,
prev_view_proj: self.accum_from.unwrap_or(self.view_proj),
..Default::default()
},
);
let current = self.current.take().expect("prepare_accum made one");
let depth = self.depth.take().expect("prepare_accum made one");
let mut accum = self.accum.take().expect("prepare_accum made one");
let bind = self.bind3(&u, ¤t, &accum.read, &depth);
{
let (device, layout, module) = (&self.device, &self.layout, &self.module);
let pipeline = self.resolve.get_or_build(format, || {
build_targets(
device,
layout,
module,
"fs_resolve3",
&[Some(accum_format), Some(format)],
)
});
let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("fluid3d resolve"),
color_attachments: &[
Some(wgpu::RenderPassColorAttachment {
view: &accum.write.view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
}),
Some(wgpu::RenderPassColorAttachment {
view: target,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
}),
],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(pipeline);
pass.set_bind_group(0, &bind, &[]);
pass.draw(0..3, 0..1);
}
accum.swap();
self.current = Some(current);
self.depth = Some(depth);
self.accum = Some(accum);
}
#[cfg(not(target_arch = "wasm32"))]
pub fn capture_rgba(&mut self, camera: &dyn Camera, width: u32, height: u32) -> Vec<u8> {
let target = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("fluid3d capture"),
size: wgpu::Extent3d {
width: width.max(1),
height: height.max(1),
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
self.render(camera, &target);
crate::renderer::readback::texture_bytes(&self.device, &self.queue, &target)
}
fn encoder(&self, label: &str) -> wgpu::CommandEncoder {
self.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some(label) })
}
fn params(&self, atlas: Atlas, rest: Vol) -> Ubo {
self.params_mixed(atlas, atlas, atlas, rest)
}
fn params_mixed(&self, out: Atlas, a: Atlas, b: Atlas, rest: Vol) -> Ubo {
let v = Vol {
out_grid: out.into(),
a_grid: a.into(),
b_grid: b.into(),
..rest
};
let i = self.next_ubo.get();
self.next_ubo.set(i + 1);
let buffer = {
let mut pool = self.ubos.borrow_mut();
while pool.len() <= i {
pool.push(ubo(&self.device));
}
pool[i].clone()
};
if !self.config.cache_bindings {
self.queue.write_buffer(&buffer, 0, bytemuck::bytes_of(&v));
return Ubo { buffer, slot: i };
}
let mut seen = self.ubo_contents.borrow_mut();
while seen.len() <= i {
seen.push(Vol::default());
}
if bytemuck::bytes_of(&seen[i]) != bytemuck::bytes_of(&v) {
seen[i] = v;
drop(seen);
self.queue.write_buffer(&buffer, 0, bytemuck::bytes_of(&v));
}
Ubo { buffer, slot: i }
}
fn bind(&self, params: &Ubo, a: &Fbo, b: Option<&Fbo>) -> wgpu::BindGroup {
if !self.config.cache_bindings {
return self.build_bind(¶ms.buffer, a, b);
}
let key = (params.slot, a.id, b.map(|f| f.id).unwrap_or(a.id));
if let Some(hit) = self.binds.borrow().get(&key) {
return hit.clone();
}
let group = self.build_bind(¶ms.buffer, a, b);
self.binds.borrow_mut().insert(key, group.clone());
group
}
fn build_bind(&self, params: &wgpu::Buffer, a: &Fbo, b: Option<&Fbo>) -> wgpu::BindGroup {
self.build_bind3(params, a, b, None)
}
fn build_bind3(
&self,
params: &wgpu::Buffer,
a: &Fbo,
b: Option<&Fbo>,
c: Option<&Fbo>,
) -> wgpu::BindGroup {
self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("fluid3d bind"),
layout: &self.bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: params.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&a.view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(
b.map(|f| &f.view).unwrap_or(&a.view),
),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::Sampler(&self.sampler),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::TextureView(
c.map(|f| &f.view).unwrap_or(&a.view),
),
},
],
})
}
fn bind3(&self, params: &Ubo, a: &Fbo, b: &Fbo, c: &Fbo) -> wgpu::BindGroup {
self.build_bind3(¶ms.buffer, a, Some(b), Some(c))
}
}
fn tex(binding: u32) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
}
}
fn ubo(device: &wgpu::Device) -> wgpu::Buffer {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("fluid3d params"),
size: VOL_SIZE,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
}
fn build(
device: &wgpu::Device,
layout: &wgpu::PipelineLayout,
module: &wgpu::ShaderModule,
fs: &str,
format: wgpu::TextureFormat,
) -> wgpu::RenderPipeline {
build_targets(device, layout, module, fs, &[Some(format)])
}
fn build_targets(
device: &wgpu::Device,
layout: &wgpu::PipelineLayout,
module: &wgpu::ShaderModule,
fs: &str,
formats: &[Option<wgpu::TextureFormat>],
) -> wgpu::RenderPipeline {
let targets: Vec<_> = formats
.iter()
.map(|f| {
f.map(|format| wgpu::ColorTargetState {
format,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})
})
.collect();
build_with(device, layout, module, fs, &targets)
}
fn build_blended(
device: &wgpu::Device,
layout: &wgpu::PipelineLayout,
module: &wgpu::ShaderModule,
fs: &str,
format: wgpu::TextureFormat,
blend: wgpu::BlendState,
) -> wgpu::RenderPipeline {
build_with(
device,
layout,
module,
fs,
&[Some(wgpu::ColorTargetState {
format,
blend: Some(blend),
write_mask: wgpu::ColorWrites::ALL,
})],
)
}
fn build_with(
device: &wgpu::Device,
layout: &wgpu::PipelineLayout,
module: &wgpu::ShaderModule,
fs: &str,
targets: &[Option<wgpu::ColorTargetState>],
) -> wgpu::RenderPipeline {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(fs),
layout: Some(layout),
vertex: wgpu::VertexState {
module,
entry_point: Some(fullscreen::VS_ENTRY),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module,
entry_point: Some(fs),
targets,
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
}
#[cfg(test)]
#[path = "volume_tests.rs"]
mod tests;