alice-sdf 5.0.0

ALICE-SDF: 3D/Spatial Data Specialist — Store laws, not polygons. GLSL/WGSL/HLSL transpile, SVO, GPU marching cubes, texture-fit, procedural CSG. Optional bridges to alice-physics / alice-codec / libasp / alice-cache behind features.
Documentation
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//! Mesh to SDF conversion (Deep Fried Edition v2)
//!
//! Converts polygon meshes to SDF representations with multiple strategies:
//! - **BVH-Accelerated Exact**: O(log n) queries using BVH
//! - **Capsule Approximation**: Fast but approximate (legacy mode)
//! - **Hybrid**: BVH for distance, capsule tree for SdfNode
//!
//! # Deep Fried Optimizations
//! - **Edge Deduplication**: Uses HashSet to eliminate duplicate capsules.
//! - **BVH Acceleration**: O(log n) distance queries for exact SDF.
//! - **Parallel Batch Evaluation**: Rayon-powered batch queries.
//! - **Forced Inlining**: `#[inline(always)]` on hot-path helpers.
//!
//! Author: Moroya Sakamoto

use crate::mesh::bvh::MeshBvh;
use crate::mesh::mesh_sign::{ExteriorField, MeshSignMode};
use crate::mesh::MeshInputError;
use crate::types::SdfNode;
use glam::Vec3;
use rayon::prelude::*;
use std::collections::HashSet;
use std::sync::Arc;

/// Cells along the longest bounding box axis used by
/// [`MeshSignMode::ExteriorFloodFill`] unless the caller overrides it.
pub const DEFAULT_SIGN_FLOOD_FILL_RESOLUTION: u32 = 64;

/// Conversion strategy for mesh_to_sdf
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MeshToSdfStrategy {
    /// Use capsule approximation (fast, creates SdfNode tree)
    #[default]
    Capsule,
    /// Use BVH for exact distance (accurate, returns MeshSdf wrapper)
    BvhExact,
    /// Hybrid: create capsule tree but use BVH for evaluation
    Hybrid,
}

/// Configuration for mesh to SDF conversion
#[derive(Debug, Clone)]
pub struct MeshToSdfConfig {
    /// Conversion strategy
    pub strategy: MeshToSdfStrategy,
    /// Whether to use bounding volumes for acceleration
    pub use_bvh: bool,
    /// Maximum triangles per leaf node (if using BVH)
    pub max_triangles_per_leaf: usize,
    /// Capsule radius factor (multiplied by average edge length)
    pub capsule_radius_factor: f32,
    /// Whether to compute vertex normals for sign determination
    pub compute_normals: bool,
    /// How the sign of the resulting field is decided.
    ///
    /// Defaults to [`MeshSignMode::NearestFaceNormal`], which needs a closed,
    /// consistently wound mesh. Use [`MeshSignMode::ExteriorFloodFill`] for
    /// meshes you did not author — open surfaces, mixed winding and separate
    /// components all come out right.
    pub sign_mode: MeshSignMode,
    /// Cells along the longest bounding box axis for
    /// [`MeshSignMode::ExteriorFloodFill`]. Ignored by the other modes.
    ///
    /// The thinnest feature that keeps its interior spans a few cells, so raise
    /// this for thin-walled meshes.
    pub sign_flood_fill_resolution: u32,
}

impl Default for MeshToSdfConfig {
    fn default() -> Self {
        Self {
            strategy: MeshToSdfStrategy::Capsule,
            use_bvh: true,
            max_triangles_per_leaf: 4,
            capsule_radius_factor: 0.05,
            compute_normals: true,
            sign_mode: MeshSignMode::NearestFaceNormal,
            sign_flood_fill_resolution: DEFAULT_SIGN_FLOOD_FILL_RESOLUTION,
        }
    }
}

impl MeshToSdfConfig {
    /// Create config for fast capsule approximation
    pub fn fast() -> Self {
        Self {
            strategy: MeshToSdfStrategy::Capsule,
            use_bvh: false,
            ..Default::default()
        }
    }

    /// Create config for accurate BVH-based SDF.
    ///
    /// Uses [`MeshSignMode::ExteriorFloodFill`], so the sign is a function of the
    /// geometry rather than of the triangle winding: an open surface reports no
    /// interior, reversing the winding changes nothing, and each closed component
    /// gets its own interior. Pair with [`Self::sign_flood_fill_resolution`] when
    /// the mesh has features thinner than a few grid cells.
    ///
    /// For the pre-4.0 behaviour, set `sign_mode` back to
    /// [`MeshSignMode::NearestFaceNormal`].
    pub fn accurate() -> Self {
        Self {
            strategy: MeshToSdfStrategy::BvhExact,
            use_bvh: true,
            max_triangles_per_leaf: 4,
            sign_mode: MeshSignMode::ExteriorFloodFill,
            ..Default::default()
        }
    }

    /// Create config for hybrid approach
    pub fn hybrid() -> Self {
        Self {
            strategy: MeshToSdfStrategy::Hybrid,
            use_bvh: true,
            max_triangles_per_leaf: 4,
            ..Default::default()
        }
    }

    /// Exact BVH distance with a sign that does not depend on triangle winding.
    ///
    /// Identical to [`Self::accurate`] — delegates to it so the two cannot
    /// drift — and spelled out for call sites where the reason for the choice is
    /// the mesh's provenance rather than the accuracy: scans, generative models,
    /// assemblies of independently wound parts. See
    /// [`MeshSignMode::ExteriorFloodFill`] for the resolution caveat.
    pub fn topology_robust() -> Self {
        Self::accurate()
    }
}

/// BVH-accelerated mesh SDF
///
/// Provides exact signed distance queries using BVH acceleration.
/// This is more accurate than the capsule approximation but cannot be
/// converted to shader code directly.
pub struct MeshSdf {
    bvh: Arc<MeshBvh>,
    bounds: crate::types::Aabb,
    sign_mode: MeshSignMode,
    /// `Some` exactly when `sign_mode` is [`MeshSignMode::ExteriorFloodFill`];
    /// construction fails rather than silently falling back to the winding rule.
    exterior: Option<Arc<ExteriorField>>,
}

impl MeshSdf {
    /// Create MeshSdf from vertices and indices.
    ///
    /// Returns `None` on the errors [`MeshSdf::try_new`] reports; use that form
    /// when you need to know which one.
    pub fn new(vertices: &[Vec3], indices: &[u32], config: &MeshToSdfConfig) -> Option<Self> {
        Self::try_new(vertices, indices, config).ok()
    }

    /// Create MeshSdf from vertices and indices.
    ///
    /// # Errors
    ///
    /// Empty input, a mesh with no bounding box, or — for
    /// [`MeshSignMode::ExteriorFloodFill`] — a degenerate extent or a
    /// `sign_flood_fill_resolution` over the cell budget.
    pub fn try_new(
        vertices: &[Vec3],
        indices: &[u32],
        config: &MeshToSdfConfig,
    ) -> Result<Self, MeshInputError> {
        if vertices.is_empty() || indices.is_empty() {
            return Err(MeshInputError {
                reason: "mesh_to_sdf needs at least one triangle",
            });
        }

        let bvh = MeshBvh::build(vertices, indices, config.max_triangles_per_leaf);
        let bounds = bvh.bounds().ok_or(MeshInputError {
            reason: "mesh has no bounding box",
        })?;

        let exterior = match config.sign_mode {
            MeshSignMode::ExteriorFloodFill => Some(Arc::new(ExteriorField::build(
                &bvh,
                config.sign_flood_fill_resolution,
            )?)),
            _ => None,
        };

        Ok(Self {
            bvh: Arc::new(bvh),
            bounds,
            sign_mode: config.sign_mode,
            exterior,
        })
    }

    /// Which rule decides the sign of [`Self::eval`].
    #[inline]
    pub const fn sign_mode(&self) -> MeshSignMode {
        self.sign_mode
    }

    /// Evaluate signed distance at a point
    #[inline]
    pub fn eval(&self, point: Vec3) -> f32 {
        self.exterior.as_ref().map_or_else(
            || self.bvh.signed_distance(point),
            |field| field.signed_distance(&self.bvh, point),
        )
    }

    /// Evaluate unsigned distance at a point
    #[inline]
    pub fn eval_unsigned(&self, point: Vec3) -> f32 {
        self.bvh.unsigned_distance(point)
    }

    /// Batch evaluate signed distances (parallel)
    pub fn eval_batch(&self, points: &[Vec3]) -> Vec<f32> {
        self.exterior.as_ref().map_or_else(
            || self.bvh.signed_distance_batch(points),
            |field| {
                points
                    .par_iter()
                    .map(|&p| field.signed_distance(&self.bvh, p))
                    .collect()
            },
        )
    }

    /// Batch evaluate unsigned distances (parallel)
    pub fn eval_unsigned_batch(&self, points: &[Vec3]) -> Vec<f32> {
        self.bvh.unsigned_distance_batch(points)
    }

    /// Compute gradient (approximate normal) at a point
    pub fn gradient(&self, point: Vec3, epsilon: f32) -> Vec3 {
        let dx = self.eval(point + Vec3::X * epsilon) - self.eval(point - Vec3::X * epsilon);
        let dy = self.eval(point + Vec3::Y * epsilon) - self.eval(point - Vec3::Y * epsilon);
        let dz = self.eval(point + Vec3::Z * epsilon) - self.eval(point - Vec3::Z * epsilon);
        Vec3::new(dx, dy, dz).normalize_or_zero()
    }

    /// Get mesh bounds
    pub const fn bounds(&self) -> (Vec3, Vec3) {
        (self.bounds.min, self.bounds.max)
    }

    /// Get triangle count
    pub fn triangle_count(&self) -> usize {
        self.bvh.triangle_count()
    }

    /// Get reference to underlying BVH
    pub fn bvh(&self) -> &MeshBvh {
        &self.bvh
    }

    /// Convert to approximate SdfNode tree using capsule method
    ///
    /// This allows the MeshSdf to be used where SdfNode is required,
    /// but with reduced accuracy.
    pub fn to_sdf_node(&self, radius_factor: f32) -> SdfNode {
        // Extract vertices and edges from triangles
        let mut vertices: Vec<Vec3> = Vec::new();
        let mut vertex_map: std::collections::HashMap<[u32; 3], usize> =
            std::collections::HashMap::new();
        let mut unique_edges: HashSet<(usize, usize)> = HashSet::new();

        for tri in &self.bvh.triangles {
            let mut get_or_add = |v: Vec3| -> usize {
                let key = [v.x.to_bits(), v.y.to_bits(), v.z.to_bits()];
                if let Some(&idx) = vertex_map.get(&key) {
                    idx
                } else {
                    let idx = vertices.len();
                    vertices.push(v);
                    vertex_map.insert(key, idx);
                    idx
                }
            };

            let i0 = get_or_add(tri.v0);
            let i1 = get_or_add(tri.v1);
            let i2 = get_or_add(tri.v2);

            unique_edges.insert(edge_key_usize(i0, i1));
            unique_edges.insert(edge_key_usize(i1, i2));
            unique_edges.insert(edge_key_usize(i2, i0));
        }

        // Compute average edge length
        let avg_edge_len: f32 = if unique_edges.is_empty() {
            0.1
        } else {
            let total: f32 = unique_edges
                .iter()
                .map(|&(i0, i1)| (vertices[i1] - vertices[i0]).length())
                .sum();
            total / unique_edges.len() as f32
        };

        let radius = avg_edge_len * radius_factor;

        // Build capsule nodes
        let nodes: Vec<SdfNode> = unique_edges
            .into_iter()
            .map(|(i0, i1)| SdfNode::capsule(vertices[i0], vertices[i1], radius))
            .collect();

        reduce_to_union(nodes)
    }
}

/// Convert a polygon mesh to an SDF representation
///
/// Returns an SdfNode tree that approximates the mesh using capsules.
/// For more accurate SDF evaluation, use `mesh_to_sdf_exact` instead.
///
/// # Arguments
/// * `vertices` - Mesh vertex positions
/// * `indices` - Triangle indices (3 per triangle)
/// * `config` - Conversion configuration
///
/// # Returns
/// SDF tree approximating the mesh
pub fn mesh_to_sdf(vertices: &[Vec3], indices: &[u32], config: &MeshToSdfConfig) -> SdfNode {
    if vertices.is_empty() || indices.is_empty() {
        return SdfNode::sphere(0.001); // Degenerate case
    }

    // Compute average edge length for capsule radius
    let mut total_edge_len = 0.0;
    let mut edge_count = 0;

    for chunk in indices.chunks(3) {
        if chunk.len() == 3 {
            let v0 = vertices[chunk[0] as usize];
            let v1 = vertices[chunk[1] as usize];
            let v2 = vertices[chunk[2] as usize];

            total_edge_len += (v1 - v0).length();
            total_edge_len += (v2 - v1).length();
            total_edge_len += (v0 - v2).length();
            edge_count += 3;
        }
    }

    let avg_edge_len = if edge_count > 0 {
        total_edge_len / edge_count as f32
    } else {
        0.1
    };

    // Use configured fraction of edge length as capsule radius
    let radius = avg_edge_len * config.capsule_radius_factor;

    // Edge deduplication using HashSet
    // Key: (min_idx, max_idx) ensures (a, b) == (b, a)
    let mut unique_edges: HashSet<(u32, u32)> = HashSet::new();

    for chunk in indices.chunks(3) {
        if chunk.len() == 3 {
            let i0 = chunk[0];
            let i1 = chunk[1];
            let i2 = chunk[2];

            // Insert edges with canonical ordering (min, max)
            unique_edges.insert(edge_key(i0, i1));
            unique_edges.insert(edge_key(i1, i2));
            unique_edges.insert(edge_key(i2, i0));
        }
    }

    // Build SDF from unique edges only
    let nodes: Vec<SdfNode> = unique_edges
        .into_iter()
        .map(|(i0, i1)| {
            let v0 = vertices[i0 as usize];
            let v1 = vertices[i1 as usize];
            SdfNode::capsule(v0, v1, radius)
        })
        .collect();

    // Build balanced binary tree of unions
    reduce_to_union(nodes)
}

/// Convert a polygon mesh to an exact BVH-accelerated SDF
///
/// Returns a MeshSdf that provides accurate signed distance queries.
/// This cannot be converted to shader code directly, but is useful for:
/// - Accurate distance queries
/// - Mesh processing algorithms
/// - Ray marching on CPU
///
/// # Arguments
/// * `vertices` - Mesh vertex positions
/// * `indices` - Triangle indices (3 per triangle)
/// * `config` - Conversion configuration
///
/// # Returns
/// `Option<MeshSdf>` - None if mesh is empty
pub fn mesh_to_sdf_exact(
    vertices: &[Vec3],
    indices: &[u32],
    config: &MeshToSdfConfig,
) -> Option<MeshSdf> {
    MeshSdf::new(vertices, indices, config)
}

/// Create canonical edge key (min, max) for HashSet deduplication
#[inline(always)]
const fn edge_key(a: u32, b: u32) -> (u32, u32) {
    if a < b {
        (a, b)
    } else {
        (b, a)
    }
}

/// Create canonical edge key for usize indices
#[inline(always)]
const fn edge_key_usize(a: usize, b: usize) -> (usize, usize) {
    if a < b {
        (a, b)
    } else {
        (b, a)
    }
}

/// Reduce a list of nodes to a single union using binary tree structure (Deep Fried)
#[inline(always)]
fn reduce_to_union(mut nodes: Vec<SdfNode>) -> SdfNode {
    if nodes.is_empty() {
        return SdfNode::sphere(0.001);
    }

    while nodes.len() > 1 {
        let mut next = Vec::with_capacity(nodes.len().div_ceil(2));

        for chunk in nodes.chunks(2) {
            if chunk.len() == 2 {
                next.push(chunk[0].clone().union(chunk[1].clone()));
            } else {
                next.push(chunk[0].clone());
            }
        }

        nodes = next;
    }

    nodes.pop().unwrap()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_mesh_to_sdf_single_triangle() {
        let vertices = vec![
            Vec3::new(0.0, 0.0, 0.0),
            Vec3::new(1.0, 0.0, 0.0),
            Vec3::new(0.5, 1.0, 0.0),
        ];
        let indices = vec![0, 1, 2];

        let sdf = mesh_to_sdf(&vertices, &indices, &MeshToSdfConfig::default());

        // Should be a valid SDF tree
        assert!(sdf.node_count() > 0);
    }

    #[test]
    fn test_mesh_to_sdf_cube() {
        // Simple cube mesh
        let vertices = vec![
            Vec3::new(-1.0, -1.0, -1.0),
            Vec3::new(1.0, -1.0, -1.0),
            Vec3::new(1.0, 1.0, -1.0),
            Vec3::new(-1.0, 1.0, -1.0),
            Vec3::new(-1.0, -1.0, 1.0),
            Vec3::new(1.0, -1.0, 1.0),
            Vec3::new(1.0, 1.0, 1.0),
            Vec3::new(-1.0, 1.0, 1.0),
        ];
        // Front face, back face (simplified - just 2 triangles for test)
        let indices = vec![
            0, 1, 2, 0, 2, 3, // Front
            4, 6, 5, 4, 7, 6, // Back
        ];

        let sdf = mesh_to_sdf(&vertices, &indices, &MeshToSdfConfig::default());
        assert!(sdf.node_count() > 0);
    }

    #[test]
    fn test_mesh_to_sdf_empty() {
        let vertices: Vec<Vec3> = vec![];
        let indices: Vec<u32> = vec![];

        let sdf = mesh_to_sdf(&vertices, &indices, &MeshToSdfConfig::default());
        // Should return degenerate sphere
        assert_eq!(sdf.node_count(), 1);
    }

    #[test]
    fn test_reduce_to_union() {
        let nodes = vec![
            SdfNode::sphere(1.0),
            SdfNode::sphere(1.0),
            SdfNode::sphere(1.0),
            SdfNode::sphere(1.0),
        ];

        let union = reduce_to_union(nodes);
        // 4 spheres + 2 unions at level 1 + 1 union at root = 7
        assert_eq!(union.node_count(), 7);
    }

    #[test]
    fn test_mesh_sdf_exact() {
        let vertices = vec![
            Vec3::new(-1.0, -1.0, 0.0),
            Vec3::new(1.0, -1.0, 0.0),
            Vec3::new(1.0, 1.0, 0.0),
            Vec3::new(-1.0, 1.0, 0.0),
        ];
        let indices = vec![0, 1, 2, 0, 2, 3];

        let mesh_sdf = mesh_to_sdf_exact(&vertices, &indices, &MeshToSdfConfig::accurate())
            .expect("Should create MeshSdf");

        // Point on surface
        let d_surface = mesh_sdf.eval(Vec3::ZERO);
        assert!(d_surface.abs() < 0.01, "Expected ~0, got {}", d_surface);

        // Point above. The quad is an open sheet, so it encloses nothing and the
        // signed distance is +1 on *both* sides — this used to be asserted on
        // `.abs()` because the winding rule made the sign arbitrary.
        let d_above = mesh_sdf.eval(Vec3::new(0.0, 0.0, 1.0));
        assert!(
            (d_above - 1.0).abs() < 0.01,
            "Expected ~+1 above an open sheet, got {}",
            d_above
        );
        let d_below = mesh_sdf.eval(Vec3::new(0.0, 0.0, -1.0));
        assert!(
            (d_below - 1.0).abs() < 0.01,
            "Expected ~+1 below an open sheet too, got {}",
            d_below
        );

        // Batch evaluation
        let points = vec![
            Vec3::ZERO,
            Vec3::new(0.0, 0.0, 1.0),
            Vec3::new(0.0, 0.0, -1.0),
        ];
        let distances = mesh_sdf.eval_batch(&points);
        assert_eq!(distances.len(), 3);
    }

    #[test]
    fn test_mesh_sdf_to_node() {
        let vertices = vec![
            Vec3::new(0.0, 0.0, 0.0),
            Vec3::new(1.0, 0.0, 0.0),
            Vec3::new(0.5, 1.0, 0.0),
        ];
        let indices = vec![0, 1, 2];

        let mesh_sdf = mesh_to_sdf_exact(&vertices, &indices, &MeshToSdfConfig::accurate())
            .expect("Should create MeshSdf");

        let node = mesh_sdf.to_sdf_node(0.05);
        assert!(node.node_count() > 0);
    }

    #[test]
    fn test_config_presets() {
        let fast = MeshToSdfConfig::fast();
        assert_eq!(fast.strategy, MeshToSdfStrategy::Capsule);
        assert!(!fast.use_bvh);

        let accurate = MeshToSdfConfig::accurate();
        assert_eq!(accurate.strategy, MeshToSdfStrategy::BvhExact);
        assert!(accurate.use_bvh);
        assert_eq!(accurate.sign_mode, MeshSignMode::ExteriorFloodFill);

        // documented as an alias, so pin that rather than repeating the fields
        assert_eq!(
            MeshToSdfConfig::topology_robust().sign_mode,
            accurate.sign_mode
        );
        assert_eq!(
            MeshToSdfConfig::topology_robust().strategy,
            accurate.strategy
        );

        // the default stays on the winding rule so existing callers are unaffected
        assert_eq!(
            MeshToSdfConfig::default().sign_mode,
            MeshSignMode::NearestFaceNormal
        );

        let hybrid = MeshToSdfConfig::hybrid();
        assert_eq!(hybrid.strategy, MeshToSdfStrategy::Hybrid);
        assert!(hybrid.use_bvh);
    }
}