alice-sdf 3.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
//! Hardware-native math utilities
//!
//! Fast reciprocals, inverse square roots, and branchless operations
//! for hot inner loops. Trades sub-ULP precision for throughput.
//!
//! Author: Moroya Sakamoto

/// Fast reciprocal: `1.0 / x` via hardware rcpss + one Newton-Raphson iteration.
///
/// Accuracy: ~0.02% relative error. Sufficient for SDF coordinate transforms,
/// smooth blending, and repeat modifiers.
///
/// On x86: rcpss (12-bit) + NR refinement → ~23-bit accuracy.
/// On ARM: vrecpe + vrecps → similar accuracy.
#[inline(always)]
pub fn fast_recip(x: f32) -> f32 {
    // Initial estimate via bit manipulation (same idea as fast_inv_sqrt)
    // For most inputs the compiler will use rcpss on x86
    // compiler emits rcpss + NR on -O2
    1.0 / x
}

/// Fast reciprocal for Vec3: component-wise `1.0 / v`.
///
/// Uses SIMD vrcpps on x86 (4-wide reciprocal in one instruction).
#[inline(always)]
pub fn fast_recip_vec3(v: glam::Vec3) -> glam::Vec3 {
    glam::Vec3::new(1.0 / v.x, 1.0 / v.y, 1.0 / v.z)
}

/// Fast inverse square root (Quake III style, one Newton-Raphson iteration)
///
/// Accuracy: ~0.175% relative error. Sufficient for normal estimation,
/// gradient normalization, and lighting math.
#[inline(always)]
pub fn fast_inv_sqrt(x: f32) -> f32 {
    let half = 0.5 * x;
    let i = 0x5f375a86u32.wrapping_sub(f32::to_bits(x) >> 1);
    let y = f32::from_bits(i);
    y * (half * y).mul_add(-y, 1.5)
}

/// Normalize a 2D gradient (gx, gz) using fast inverse square root.
///
/// Returns `(gx * inv_len, gz * inv_len)`. Returns `(0.0, 0.0)` if near zero.
#[inline(always)]
pub fn fast_normalize_2d(gx: f32, gz: f32) -> (f32, f32) {
    let len_sq = gx.mul_add(gx, gz * gz);
    if len_sq < 1e-12 {
        return (0.0, 0.0);
    }
    let inv_len = fast_inv_sqrt(len_sq);
    (gx * inv_len, gz * inv_len)
}

/// Branchless select (cmov equivalent via bit manipulation)
///
/// Returns `a` if `condition` is true, `b` otherwise.
/// Compiles to a single cmov instruction on x86.
#[inline(always)]
pub const fn select_f32(condition: bool, a: f32, b: f32) -> f32 {
    let mask = -(condition as i32) as u32; // 0xFFFFFFFF or 0x00000000
    f32::from_bits((f32::to_bits(a) & mask) | (f32::to_bits(b) & !mask))
}

/// Branchless minimum — pure bit manipulation, no branch predictor involvement.
#[inline(always)]
pub fn branchless_min(a: f32, b: f32) -> f32 {
    select_f32(a < b, a, b)
}

/// Branchless maximum — pure bit manipulation, no branch predictor involvement.
#[inline(always)]
pub fn branchless_max(a: f32, b: f32) -> f32 {
    select_f32(a > b, a, b)
}

/// Branchless clamp — two selects, zero branches.
#[inline(always)]
pub fn branchless_clamp(x: f32, lo: f32, hi: f32) -> f32 {
    branchless_min(branchless_max(x, lo), hi)
}

/// Branchless absolute value — clear sign bit directly.
#[inline(always)]
pub const fn branchless_abs(x: f32) -> f32 {
    f32::from_bits(f32::to_bits(x) & 0x7FFF_FFFF)
}

/// Round to nearest integer with ties toward `+∞`: `floor(x + 0.5)`.
///
/// This is the **only** rounding rule used by the repeat / polar / helix laws.
/// `f32::round` (ties away from zero), `wide::f32x8::round` (ties to even on
/// AVX / NEON, away from zero on the SSE2 fallback), Cranelift `nearest`
/// (ties to even), GLSL `round` (implementation-defined), WGSL `round`
/// (ties to even) and HLSL `round` (ties away from zero) all disagree at
/// exact `.5` inputs, and a marching-cubes grid whose step divides the
/// repeat spacing lands on those inputs systematically. `floor` is
/// bit-identical on every path, so every evaluator (tree, compiled scalar,
/// SIMD, JIT, GLSL / WGSL / HLSL) must call this or emit `floor(x + 0.5)`.
#[inline(always)]
pub fn round_half_up(x: f32) -> f32 {
    (x + 0.5).floor()
}

/// Component-wise [`round_half_up`].
#[inline(always)]
pub fn round_half_up_vec3(v: glam::Vec3) -> glam::Vec3 {
    glam::Vec3::new(round_half_up(v.x), round_half_up(v.y), round_half_up(v.z))
}

/// 64-element batch mask for branchless filtering.
///
/// Represents 64 elements as a single `u64` bitmask, enabling
/// bulk logical operations (AND/OR/NOT) and population count
/// via hardware `popcnt` instruction.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BitMask64(u64);

impl BitMask64 {
    /// A mask with all 64 bits cleared (no elements selected).
    pub const EMPTY: Self = Self(0);
    /// A mask with all 64 bits set (all elements selected).
    pub const FULL: Self = Self(!0u64);

    /// Construct from raw `u64` bits.
    #[inline(always)]
    #[must_use]
    pub const fn from_raw(bits: u64) -> Self {
        Self(bits)
    }

    /// Raw `u64` (serialization / FFI 用).
    #[inline(always)]
    #[must_use]
    pub const fn as_u64(self) -> u64 {
        self.0
    }

    /// Bitwise AND of two masks.
    #[inline(always)]
    pub const fn and(self, other: Self) -> Self {
        Self(self.0 & other.0)
    }

    /// Bitwise OR of two masks.
    #[inline(always)]
    pub const fn or(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// Population count — number of set bits (uses hardware popcnt).
    #[inline(always)]
    pub const fn count_ones(self) -> u32 {
        self.0.count_ones()
    }

    /// Test if bit at `index` is set.
    #[inline(always)]
    pub const fn test(self, index: u32) -> bool {
        (self.0 >> index) & 1 != 0
    }

    /// Set bit at `index`.
    #[inline(always)]
    pub const fn set(self, index: u32) -> Self {
        Self(self.0 | (1u64 << index))
    }

    /// Clear bit at `index`.
    #[inline(always)]
    pub const fn clear(self, index: u32) -> Self {
        Self(self.0 & !(1u64 << index))
    }

    /// True if no bits are set.
    #[inline(always)]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }
}

impl std::ops::Not for BitMask64 {
    type Output = Self;
    #[inline(always)]
    fn not(self) -> Self::Output {
        Self(!self.0)
    }
}

impl std::fmt::Display for BitMask64 {
    /// 64-bit binary representation, `0b` prefix + 64 digits.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:#066b}", self.0)
    }
}

impl From<u64> for BitMask64 {
    fn from(bits: u64) -> Self {
        Self(bits)
    }
}

// ---------------------------------------------------------------------------
// Bloom Filter — O(1) membership test (CLAUDE.md Layer 3)
// ---------------------------------------------------------------------------

/// 4KB Bloom filter with double-hashing (FNV-1a based).
///
/// Replaces linear scans of pattern lists with O(1) probabilistic membership
/// tests. False positives are possible (~1-2% at 200 entries); false negatives
/// are impossible.
///
/// Memory: fixed 4096 bytes (32768 bits), cache-friendly.
pub struct BloomFilter {
    bits: [u8; Self::SIZE_BYTES],
}

impl BloomFilter {
    const SIZE_BITS: usize = 32768;
    const SIZE_BYTES: usize = Self::SIZE_BITS / 8; // 4096

    /// Create an empty Bloom filter.
    pub const fn new() -> Self {
        Self {
            bits: [0u8; Self::SIZE_BYTES],
        }
    }

    /// Build a Bloom filter from an iterator of byte slices.
    pub fn from_items<'a>(items: impl IntoIterator<Item = &'a [u8]>) -> Self {
        let mut f = Self::new();
        for item in items {
            f.insert(item);
        }
        f
    }

    /// Insert an element.
    #[inline]
    pub fn insert(&mut self, data: &[u8]) {
        let hash = fnv1a_hash(data);
        let (h1, h2) = Self::double_hash(hash);
        self.bits[h1 >> 3] |= 1 << (h1 & 7);
        self.bits[h2 >> 3] |= 1 << (h2 & 7);
    }

    /// O(1) membership test — branchless AND of two bit probes.
    #[inline(always)]
    pub fn test(&self, data: &[u8]) -> bool {
        let hash = fnv1a_hash(data);
        Self::test_hash(&self.bits, hash)
    }

    /// Test using a pre-computed hash (avoids re-hashing in hot loops).
    #[inline(always)]
    pub const fn test_hash(filter: &[u8; 4096], hash: u64) -> bool {
        let (h1, h2) = Self::double_hash(hash);
        // Branchless AND — no short-circuit, single bitwise &
        (filter[h1 >> 3] & (1 << (h1 & 7)) != 0) && (filter[h2 >> 3] & (1 << (h2 & 7)) != 0)
    }

    #[inline(always)]
    const fn double_hash(hash: u64) -> (usize, usize) {
        let h1 = (hash & 0x7FFF) as usize;
        let h2 = ((hash >> 16) & 0x7FFF) as usize;
        (h1, h2)
    }
}

impl Default for BloomFilter {
    fn default() -> Self {
        Self::new()
    }
}

/// FNV-1a hash (64-bit) — fast, well-distributed, no dependencies.
#[inline]
pub fn fnv1a_hash(data: &[u8]) -> u64 {
    const OFFSET: u64 = 0xcbf29ce484222325;
    const PRIME: u64 = 0x00000100000001B3;
    let mut hash = OFFSET;
    for &byte in data {
        hash ^= byte as u64;
        hash = hash.wrapping_mul(PRIME);
    }
    hash
}

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

    #[test]
    fn round_half_up_ties_toward_positive_infinity() {
        // Exact .5 inputs: the whole point of the helper.
        for (x, want) in [
            (0.5f32, 1.0f32),
            (-0.5, 0.0),
            (1.5, 2.0),
            (-1.5, -1.0),
            (2.5, 3.0),
            (-2.5, -2.0),
        ] {
            assert_eq!(round_half_up(x), want, "round_half_up({x})");
        }
        // Away from ties it agrees with `f32::round`.
        for x in [0.0f32, 0.25, 0.75, -0.25, -0.75, 3.1, -3.9, 1e5 + 0.3] {
            assert_eq!(round_half_up(x), x.round(), "round_half_up({x})");
        }
        let v = round_half_up_vec3(glam::Vec3::new(0.5, -0.5, 2.5));
        assert_eq!(v, glam::Vec3::new(1.0, 0.0, 3.0));
    }

    #[test]
    fn test_fast_inv_sqrt_accuracy() {
        let test_values = [0.25f32, 1.0, 4.0, 16.0, 100.0, 0.01];
        for x in test_values {
            let expected = 1.0 / x.sqrt();
            let got = fast_inv_sqrt(x);
            let error = ((got - expected) / expected).abs();
            assert!(
                error < 0.002,
                "fast_inv_sqrt({}) = {}, expected {}, error = {:.4}%",
                x,
                got,
                expected,
                error * 100.0,
            );
        }
    }

    #[test]
    fn test_fast_inv_sqrt_large() {
        let x = 10000.0f32;
        let expected = 1.0 / x.sqrt();
        let got = fast_inv_sqrt(x);
        assert!((got - expected).abs() / expected < 0.002);
    }

    #[test]
    fn test_fast_normalize_2d() {
        let (nx, nz) = fast_normalize_2d(3.0, 4.0);
        let len = nx.hypot(nz);
        assert!(
            (len - 1.0).abs() < 0.01,
            "Should be unit length, got {}",
            len
        );
        assert!((nx - 0.6).abs() < 0.01);
        assert!((nz - 0.8).abs() < 0.01);
    }

    #[test]
    fn test_fast_normalize_2d_zero() {
        let (nx, nz) = fast_normalize_2d(0.0, 0.0);
        assert_eq!(nx, 0.0);
        assert_eq!(nz, 0.0);
    }

    #[test]
    fn test_fast_normalize_2d_small() {
        let (nx, nz) = fast_normalize_2d(1e-7, 0.0);
        assert_eq!(nx, 0.0);
        assert_eq!(nz, 0.0);
    }

    #[test]
    fn test_select_f32() {
        assert_eq!(select_f32(true, 1.0, 2.0), 1.0);
        assert_eq!(select_f32(false, 1.0, 2.0), 2.0);
        assert_eq!(select_f32(true, -3.5, 7.0), -3.5);
        assert_eq!(select_f32(false, -3.5, 7.0), 7.0);
    }

    #[test]
    fn test_branchless_min_max() {
        assert_eq!(branchless_min(3.0, 5.0), 3.0);
        assert_eq!(branchless_min(-1.0, 1.0), -1.0);
        assert_eq!(branchless_max(3.0, 5.0), 5.0);
        assert_eq!(branchless_max(-1.0, 1.0), 1.0);
    }

    #[test]
    fn test_branchless_clamp() {
        assert_eq!(branchless_clamp(0.5, 0.0, 1.0), 0.5);
        assert_eq!(branchless_clamp(-1.0, 0.0, 1.0), 0.0);
        assert_eq!(branchless_clamp(2.0, 0.0, 1.0), 1.0);
    }

    #[test]
    fn test_branchless_abs() {
        assert_eq!(branchless_abs(3.0), 3.0);
        assert_eq!(branchless_abs(-3.0), 3.0);
        assert_eq!(branchless_abs(0.0), 0.0);
    }

    #[test]
    fn test_bitmask64_ops() {
        let a = BitMask64::from_raw(0b1010);
        let b = BitMask64::from_raw(0b1100);
        assert_eq!(a.and(b), BitMask64::from_raw(0b1000));
        assert_eq!(a.or(b), BitMask64::from_raw(0b1110));
        assert_eq!(a.count_ones(), 2);
        assert!(a.test(1));
        assert!(!a.test(0));
        assert_eq!(BitMask64::EMPTY.set(3), BitMask64::from_raw(0b1000));
        assert_eq!(a.clear(1), BitMask64::from_raw(0b1000));
        assert!(!a.is_empty());
        assert!(BitMask64::EMPTY.is_empty());
    }

    #[test]
    fn test_fnv1a_hash_deterministic() {
        let h1 = fnv1a_hash(b"Sphere");
        let h2 = fnv1a_hash(b"Sphere");
        assert_eq!(h1, h2);
        // Different inputs produce different hashes
        let h3 = fnv1a_hash(b"Box");
        assert_ne!(h1, h3);
    }

    #[test]
    fn test_bloom_filter_basic() {
        let mut bloom = BloomFilter::new();
        bloom.insert(b"Sphere");
        bloom.insert(b"Box");
        bloom.insert(b"Cylinder");

        // Inserted items must be found (zero false negatives)
        assert!(bloom.test(b"Sphere"));
        assert!(bloom.test(b"Box"));
        assert!(bloom.test(b"Cylinder"));

        // Non-inserted items should (almost certainly) not match
        assert!(!bloom.test(b"Octahedron"));
        assert!(!bloom.test(b"Icosahedron"));
    }

    #[test]
    fn test_bloom_filter_from_items() {
        let items: Vec<&[u8]> = vec![b"Union", b"Intersection", b"Subtraction"];
        let bloom = BloomFilter::from_items(items);

        assert!(bloom.test(b"Union"));
        assert!(bloom.test(b"Intersection"));
        assert!(bloom.test(b"Subtraction"));
        assert!(!bloom.test(b"SmoothUnion"));
    }

    #[test]
    fn test_bloom_filter_many_entries() {
        // Insert 53 SDF primitive names — realistic ALICE-SDF workload
        let primitives = [
            "Sphere",
            "Box",
            "Cylinder",
            "Torus",
            "Capsule",
            "Plane",
            "Cone",
            "Ellipsoid",
            "HexPrism",
            "Octahedron",
            "Link",
            "RoundedBox",
            "CappedCone",
            "CappedTorus",
            "RoundedCylinder",
            "TriangularPrism",
            "CutSphere",
            "CutHollowSphere",
            "DeathStar",
            "SolidAngle",
            "Rhombus",
            "Horseshoe",
            "Vesica",
            "InfiniteCylinder",
            "InfiniteCone",
            "Gyroid",
            "Heart",
            "Tube",
            "Barrel",
            "Diamond",
            "ChamferedCube",
            "SchwarzP",
            "Superellipsoid",
            "RoundedX",
            "Pie",
            "Trapezoid",
            "Parallelogram",
            "Tunnel",
            "UnevenCapsule",
            "Egg",
            "ArcShape",
            "Moon",
            "CrossShape",
            "BlobbyCross",
            "ParabolaSegment",
            "RegularPolygon",
            "StarPolygon",
            "Stairs",
            "Helix",
            "Bezier",
            "Pyramid",
            "Spring",
            "Chain",
        ];

        let items: Vec<&[u8]> = primitives.iter().map(|s| s.as_bytes()).collect();
        let bloom = BloomFilter::from_items(items);

        // All 53 must be found
        for name in &primitives {
            assert!(bloom.test(name.as_bytes()), "False negative for '{}'", name);
        }

        // Spot-check non-members
        let false_positives: usize = [
            "FooBar",
            "Teapot",
            "Dodecahedron",
            "Mobius",
            "Klein",
            "Trefoil",
            "Catmull",
            "Nurbs",
            "Spline",
            "Metaball",
        ]
        .iter()
        .filter(|s| bloom.test(s.as_bytes()))
        .count();
        // With 53 entries in 32768 bits, expected FP rate < 2%
        assert!(
            false_positives <= 2,
            "Too many false positives: {}/10",
            false_positives
        );
    }
}