1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! Fluid Flow Visualization
//!
//! Generates visualization data from fluid particle simulations:
//!
//! - **Flow Arrows**: Grid-sampled velocity arrows for vector field display
//! - **Streamlines**: Particle traces through the velocity field
//!
//! All computations use deterministic 128-bit fixed-point arithmetic.
use crate::math::{Fix128, Vec3Fix};
#[cfg(not(feature = "std"))]
use alloc::vec;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
// ============================================================================
// Flow Visualization Types
// ============================================================================
/// A velocity arrow for flow visualization.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FlowArrow {
/// Arrow base position
pub position: Vec3Fix,
/// Velocity direction (normalized)
pub direction: Vec3Fix,
/// Velocity magnitude
pub magnitude: Fix128,
}
/// Collection of streamlines stored as a flat buffer with per-line lengths.
///
/// `points[offsets[i]..offsets[i+1]]` gives the polyline for streamline `i`.
#[derive(Clone, Debug)]
pub struct Streamlines {
/// All polyline points packed contiguously.
pub points: Vec<Vec3Fix>,
/// Start index in `points` for each line; length = num_lines + 1.
pub offsets: Vec<usize>,
}
impl Streamlines {
/// Number of streamlines.
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.offsets.len().saturating_sub(1)
}
/// Returns `true` if there are no streamlines.
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Get the polyline for streamline `i`.
#[inline]
#[must_use]
pub fn line(&self, i: usize) -> &[Vec3Fix] {
let s = self.offsets[i];
let e = self.offsets[i + 1];
&self.points[s..e]
}
}
/// Configuration for flow visualization.
#[derive(Clone, Debug)]
pub struct FlowVizConfig {
/// Grid resolution (cells per axis)
pub grid_resolution: usize,
/// Minimum corner of the visualization volume
pub bounds_min: Vec3Fix,
/// Maximum corner of the visualization volume
pub bounds_max: Vec3Fix,
/// Scale factor for arrow lengths
pub arrow_scale: Fix128,
}
// ============================================================================
// Flow Arrow Generation
// ============================================================================
/// Generate flow arrows from fluid particle data.
///
/// Samples velocity on a regular 3D grid by averaging nearby fluid particle
/// velocities using a radial kernel. Each grid cell with non-zero velocity
/// produces a flow arrow.
///
/// # Arguments
///
/// - `fluid_positions`: Fluid particle positions
/// - `fluid_velocities`: Fluid particle velocities
/// - `config`: Visualization configuration
#[must_use]
pub fn generate_flow_arrows(
fluid_positions: &[Vec3Fix],
fluid_velocities: &[Vec3Fix],
config: &FlowVizConfig,
) -> Vec<FlowArrow> {
if fluid_positions.is_empty() {
return Vec::new();
}
let res = config.grid_resolution.max(1);
let min = config.bounds_min;
let max = config.bounds_max;
let dx = (max.x - min.x) / Fix128::from_int(res as i64);
let dy = (max.y - min.y) / Fix128::from_int(res as i64);
let dz = (max.z - min.z) / Fix128::from_int(res as i64);
// Cell size determines the search radius for averaging
let cell_size = dx;
let radius_sq = cell_size * cell_size;
let mut arrows = Vec::new();
for iz in 0..res {
for iy in 0..res {
for ix in 0..res {
// Cell center
let center = Vec3Fix::new(
min.x + dx * Fix128::from_int(ix as i64) + dx.half(),
min.y + dy * Fix128::from_int(iy as i64) + dy.half(),
min.z + dz * Fix128::from_int(iz as i64) + dz.half(),
);
// Average velocity of nearby particles
let mut avg_vel = Vec3Fix::ZERO;
let mut count = Fix128::ZERO;
for (pi, pos) in fluid_positions.iter().enumerate() {
let diff = *pos - center;
let dist_sq = diff.dot(diff);
if dist_sq < radius_sq {
if pi < fluid_velocities.len() {
avg_vel = avg_vel + fluid_velocities[pi];
}
count = count + Fix128::ONE;
}
}
if count.is_zero() {
continue;
}
avg_vel = avg_vel / count;
let magnitude = avg_vel.length();
if magnitude.is_zero() {
continue;
}
let direction = avg_vel / magnitude;
arrows.push(FlowArrow {
position: center,
direction,
magnitude: magnitude * config.arrow_scale,
});
}
}
}
arrows
}
// ============================================================================
// Streamline Generation
// ============================================================================
/// Generate streamlines by tracing particles through a velocity field.
///
/// Starting from each seed point, advances forward through the velocity
/// field (interpolated from nearby fluid particles) for the given number
/// of steps. Returns a [`Streamlines`] struct with all polylines in a
/// single flat buffer.
///
/// # Arguments
///
/// - `fluid_positions`: Fluid particle positions
/// - `fluid_velocities`: Fluid particle velocities
/// - `seed_points`: Starting positions for streamlines
/// - `steps`: Number of integration steps per streamline
/// - `dt`: Time step for Euler integration
#[must_use]
pub fn generate_streamlines(
fluid_positions: &[Vec3Fix],
fluid_velocities: &[Vec3Fix],
seed_points: &[Vec3Fix],
steps: usize,
dt: Fix128,
) -> Streamlines {
let num_seeds = seed_points.len();
let mut points: Vec<Vec3Fix> = Vec::with_capacity(num_seeds * (steps + 1));
let mut offsets: Vec<usize> = Vec::with_capacity(num_seeds + 1);
if fluid_positions.is_empty() || dt.is_zero() {
for &s in seed_points {
offsets.push(points.len());
points.push(s);
}
offsets.push(points.len());
return Streamlines { points, offsets };
}
let influence_radius = Fix128::ONE;
let radius_sq = influence_radius * influence_radius;
for &seed in seed_points {
offsets.push(points.len());
let mut pos = seed;
points.push(pos);
for _ in 0..steps {
let vel = interpolate_velocity(
pos,
fluid_positions,
fluid_velocities,
radius_sq,
influence_radius,
);
if vel.length_squared().is_zero() {
break;
}
pos = pos + vel * dt;
points.push(pos);
}
}
offsets.push(points.len());
Streamlines { points, offsets }
}
/// Interpolate velocity at a point using inverse-distance weighting.
fn interpolate_velocity(
pos: Vec3Fix,
fluid_positions: &[Vec3Fix],
fluid_velocities: &[Vec3Fix],
radius_sq: Fix128,
radius: Fix128,
) -> Vec3Fix {
let mut weighted_vel = Vec3Fix::ZERO;
let mut total_weight = Fix128::ZERO;
for (i, fp) in fluid_positions.iter().enumerate() {
let diff = pos - *fp;
let dist_sq = diff.dot(diff);
if dist_sq >= radius_sq || i >= fluid_velocities.len() {
continue;
}
// Linear weight: 1 - dist/radius
let dist = dist_sq.sqrt();
let weight = Fix128::ONE - dist / radius;
if weight > Fix128::ZERO {
weighted_vel = weighted_vel + fluid_velocities[i] * weight;
total_weight = total_weight + weight;
}
}
if total_weight.is_zero() {
Vec3Fix::ZERO
} else {
weighted_vel / total_weight
}
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
fn basic_config() -> FlowVizConfig {
FlowVizConfig {
grid_resolution: 2,
bounds_min: Vec3Fix::from_int(-2, -2, -2),
bounds_max: Vec3Fix::from_int(2, 2, 2),
arrow_scale: Fix128::ONE,
}
}
#[test]
fn test_flow_arrows_empty_fluid() {
let config = basic_config();
let arrows = generate_flow_arrows(&[], &[], &config);
assert!(arrows.is_empty());
}
#[test]
fn test_flow_arrows_uniform_field() {
let config = FlowVizConfig {
grid_resolution: 2,
bounds_min: Vec3Fix::from_int(-1, -1, -1),
bounds_max: Vec3Fix::from_int(1, 1, 1),
arrow_scale: Fix128::ONE,
};
// Particles everywhere moving in +X
let mut positions = Vec::new();
let mut velocities = Vec::new();
for ix in -1..=1 {
for iy in -1..=1 {
for iz in -1..=1 {
positions.push(Vec3Fix::from_int(ix, iy, iz));
velocities.push(Vec3Fix::from_int(1, 0, 0));
}
}
}
let arrows = generate_flow_arrows(&positions, &velocities, &config);
// Should produce some arrows
assert!(!arrows.is_empty());
// All arrows should point in +X direction
for arrow in &arrows {
assert!(arrow.direction.x > Fix128::ZERO);
assert!(arrow.magnitude > Fix128::ZERO);
}
}
#[test]
fn test_flow_arrows_magnitude_scaled() {
let config = FlowVizConfig {
grid_resolution: 1,
bounds_min: Vec3Fix::from_int(-1, -1, -1),
bounds_max: Vec3Fix::from_int(1, 1, 1),
arrow_scale: Fix128::from_int(2),
};
let positions = vec![Vec3Fix::ZERO];
let velocities = vec![Vec3Fix::from_int(3, 0, 0)];
let arrows = generate_flow_arrows(&positions, &velocities, &config);
if !arrows.is_empty() {
// Magnitude should be velocity * scale
assert!(arrows[0].magnitude > Fix128::from_int(5));
}
}
#[test]
fn test_streamlines_empty_fluid() {
let seeds = vec![Vec3Fix::ZERO];
let lines = generate_streamlines(&[], &[], &seeds, 10, Fix128::from_ratio(1, 60));
assert_eq!(lines.len(), 1);
assert_eq!(lines.line(0).len(), 1); // Only seed point
}
#[test]
fn test_streamlines_single_particle() {
let positions = vec![Vec3Fix::ZERO];
let velocities = vec![Vec3Fix::from_int(1, 0, 0)];
let seeds = vec![Vec3Fix::ZERO];
let lines = generate_streamlines(
&positions,
&velocities,
&seeds,
5,
Fix128::from_ratio(1, 10),
);
assert_eq!(lines.len(), 1);
// Should have seed + some trace points
assert!(lines.line(0).len() > 1);
// Should have moved in +X direction
let last = lines.line(0).last().unwrap();
assert!(last.x > Fix128::ZERO);
}
#[test]
fn test_streamlines_zero_dt() {
let positions = vec![Vec3Fix::ZERO];
let velocities = vec![Vec3Fix::from_int(1, 0, 0)];
let seeds = vec![Vec3Fix::ZERO];
let lines = generate_streamlines(&positions, &velocities, &seeds, 10, Fix128::ZERO);
assert_eq!(lines.line(0).len(), 1); // Only seed
}
#[test]
fn test_streamlines_multiple_seeds() {
let positions = vec![Vec3Fix::ZERO, Vec3Fix::from_int(1, 0, 0)];
let velocities = vec![Vec3Fix::UNIT_X, Vec3Fix::UNIT_X];
let seeds = vec![
Vec3Fix::from_int(-1, 0, 0),
Vec3Fix::from_int(0, 1, 0),
Vec3Fix::from_int(0, 0, -1),
];
let lines = generate_streamlines(
&positions,
&velocities,
&seeds,
3,
Fix128::from_ratio(1, 10),
);
assert_eq!(lines.len(), 3);
}
#[test]
fn test_interpolate_velocity_no_neighbors() {
let vel = interpolate_velocity(
Vec3Fix::from_int(100, 100, 100),
&[Vec3Fix::ZERO],
&[Vec3Fix::from_int(1, 0, 0)],
Fix128::ONE,
Fix128::ONE,
);
assert!(vel.length_squared().is_zero());
}
#[test]
fn test_flow_arrow_direction_normalized() {
let config = FlowVizConfig {
grid_resolution: 1,
bounds_min: Vec3Fix::from_int(-1, -1, -1),
bounds_max: Vec3Fix::from_int(1, 1, 1),
arrow_scale: Fix128::ONE,
};
let positions = vec![Vec3Fix::ZERO];
let velocities = vec![Vec3Fix::from_int(3, 4, 0)];
let arrows = generate_flow_arrows(&positions, &velocities, &config);
if !arrows.is_empty() {
let len = arrows[0].direction.length();
let eps = Fix128::from_ratio(1, 100);
let diff = (len - Fix128::ONE).abs();
assert!(diff < eps, "Direction should be normalized");
}
}
}