alice-sdf 5.1.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
//! Volume Export: Raw Binary and DDS 3D Texture Formats
//!
//! Export Volume3D to formats consumable by game engines and GPU APIs.
//!
//! - **Raw**: Flat binary dump (f32 or f16), importable by UE5/Unity
//! - **DDS 3D**: DirectX DDS container with 3D texture header, loadable
//!   by DirectX, Vulkan (via KTX conversion), and most game engines
//!
//! Author: Moroya Sakamoto

use std::io::{self, Write};
use std::path::Path;

use super::Volume3D;

/// Export volume as raw binary file (f32 per voxel)
///
/// Layout: Z-major flat array of f32, same as `Volume3D::data`.
/// A companion `.meta` JSON file is written with resolution and bounds.
///
/// # Arguments
/// * `volume` - The volume to export
/// * `path` - Output file path (e.g., "volume.raw")
pub fn export_raw(volume: &Volume3D<f32>, path: &str) -> io::Result<()> {
    let path = Path::new(path);

    // Write raw data
    let mut file = std::fs::File::create(path)?;
    // SAFETY: `volume.data` is a contiguous Vec<f32>. f32 is POD with no padding,
    // so reinterpreting as &[u8] with byte length = len * 4 is sound.
    // The resulting slice borrows `volume.data` and is valid for its lifetime.
    let bytes: &[u8] = unsafe {
        std::slice::from_raw_parts(
            volume.data.as_ptr() as *const u8,
            volume.data.len() * std::mem::size_of::<f32>(),
        )
    };
    file.write_all(bytes)?;

    // Write metadata JSON
    let meta_path = path.with_extension("raw.meta.json");
    let meta = format!(
        r#"{{
  "format": "float32",
  "resolution": [{}, {}, {}],
  "world_min": [{}, {}, {}],
  "world_max": [{}, {}, {}],
  "voxel_count": {},
  "byte_size": {},
  "mip_levels": {}
}}"#,
        volume.resolution[0],
        volume.resolution[1],
        volume.resolution[2],
        volume.world_min.x,
        volume.world_min.y,
        volume.world_min.z,
        volume.world_max.x,
        volume.world_max.y,
        volume.world_max.z,
        volume.voxel_count(),
        volume.data.len() * 4,
        volume.mip_count(),
    );
    std::fs::write(meta_path, meta)?;

    Ok(())
}

/// Export volume as raw binary with mip chain
///
/// Layout: [mip0_data][mip1_data][mip2_data]...
/// Metadata includes byte offsets for each mip level.
pub fn export_raw_with_mips(volume: &Volume3D<f32>, path: &str) -> io::Result<()> {
    let path = Path::new(path);
    let mut file = std::fs::File::create(path)?;

    // Write mip 0 (base level)
    // SAFETY: `volume.data` is a contiguous Vec<f32>. f32 is POD with no padding,
    // so reinterpreting as &[u8] with byte length = len * 4 is sound.
    let bytes: &[u8] = unsafe {
        std::slice::from_raw_parts(
            volume.data.as_ptr() as *const u8,
            volume.data.len() * std::mem::size_of::<f32>(),
        )
    };
    file.write_all(bytes)?;

    // Write each mip level
    let mut mip_offsets = vec![0u64];
    let mut offset = volume.data.len() as u64 * 4;

    for mip in &volume.mips {
        mip_offsets.push(offset);
        // SAFETY: Each mip level is a contiguous Vec<f32>. f32 is POD,
        // so reinterpreting as &[u8] with byte length = len * 4 is sound.
        let mip_bytes: &[u8] = unsafe {
            std::slice::from_raw_parts(
                mip.as_ptr() as *const u8,
                mip.len() * std::mem::size_of::<f32>(),
            )
        };
        file.write_all(mip_bytes)?;
        offset += mip.len() as u64 * 4;
    }

    // Write metadata JSON with mip offsets
    let meta_path = path.with_extension("raw.meta.json");
    let offsets_str = mip_offsets
        .iter()
        .map(|o| o.to_string())
        .collect::<Vec<_>>()
        .join(", ");

    let meta = format!(
        r#"{{
  "format": "float32",
  "resolution": [{}, {}, {}],
  "world_min": [{}, {}, {}],
  "world_max": [{}, {}, {}],
  "voxel_count": {},
  "byte_size": {},
  "mip_levels": {},
  "mip_byte_offsets": [{}]
}}"#,
        volume.resolution[0],
        volume.resolution[1],
        volume.resolution[2],
        volume.world_min.x,
        volume.world_min.y,
        volume.world_min.z,
        volume.world_max.x,
        volume.world_max.y,
        volume.world_max.z,
        volume.voxel_count(),
        offset,
        volume.mip_count(),
        offsets_str,
    );
    std::fs::write(meta_path, meta)?;

    Ok(())
}

/// DDS 3D texture pixel format
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DdsFormat {
    /// 32-bit float per voxel (R32_FLOAT, DXGI_FORMAT_R32_FLOAT = 41)
    R32Float,
    /// 16-bit float per voxel (R16_FLOAT, DXGI_FORMAT_R16_FLOAT = 54)
    R16Float,
    /// 4-channel 32-bit float (R32G32B32A32_FLOAT = 2) for dist+gradient
    R32G32B32A32Float,
}

/// Export volume as DDS 3D texture
///
/// Creates a DirectX DDS file with DX10 header extension for 3D textures.
/// Compatible with DirectX 11/12, Vulkan (via conversion), and most engines.
///
/// # Arguments
/// * `volume` - The volume to export
/// * `path` - Output file path (e.g., "volume.dds")
/// * `format` - Pixel format
pub fn export_dds_3d(volume: &Volume3D<f32>, path: &str, format: DdsFormat) -> io::Result<()> {
    let path = Path::new(path);
    let mut file = std::fs::File::create(path)?;

    let (dxgi_format, bytes_per_pixel) = match format {
        DdsFormat::R32Float => (41u32, 4u32),
        DdsFormat::R16Float => (54, 2),
        DdsFormat::R32G32B32A32Float => (2, 16),
    };

    // DDS magic number
    file.write_all(&0x20534444u32.to_le_bytes())?; // "DDS "

    // DDS_HEADER (124 bytes)
    let pitch_or_linear = volume.resolution[0] * bytes_per_pixel;
    let header = DdsHeader {
        size: 124,
        flags: dds_header_flags(volume.mip_count()),
        height: volume.resolution[1],
        width: volume.resolution[0],
        pitch_or_linear_size: pitch_or_linear,
        depth: volume.resolution[2],
        mip_map_count: volume.mip_count() as u32,
        reserved1: [0u32; 11],
        // DDS_PIXELFORMAT (32 bytes)
        pf_size: 32,
        pf_flags: 0x00000004, // DDPF_FOURCC
        pf_four_cc: u32::from_le_bytes(*b"DX10"),
        pf_rgb_bit_count: 0,
        pf_r_bitmask: 0,
        pf_g_bitmask: 0,
        pf_b_bitmask: 0,
        pf_a_bitmask: 0,
        // DDS_HEADER caps
        caps: dds_caps(volume.mip_count()),
        caps2: DDSCAPS2_VOLUME,
        caps3: 0,
        caps4: 0,
        reserved2: 0,
    };

    write_dds_header(&mut file, &header)?;

    // DDS_HEADER_DXT10 (20 bytes)
    let dxt10 = DdsHeaderDxt10 {
        dxgi_format,
        resource_dimension: 4, // D3D10_RESOURCE_DIMENSION_TEXTURE3D
        misc_flag: 0,
        array_size: 1,
        misc_flags2: 0,
    };
    write_dds_header_dxt10(&mut file, &dxt10)?;

    // Write pixel data
    match format {
        DdsFormat::R32Float => {
            // SAFETY: `volume.data` is a contiguous Vec<f32>. f32 is POD,
            // so reinterpreting as &[u8] with byte length = len * 4 is sound.
            let bytes: &[u8] = unsafe {
                std::slice::from_raw_parts(volume.data.as_ptr() as *const u8, volume.data.len() * 4)
            };
            file.write_all(bytes)?;

            // Write mip levels
            for mip in &volume.mips {
                // SAFETY: Each mip is a contiguous Vec<f32>. f32 is POD,
                // so reinterpreting as &[u8] with byte length = len * 4 is sound.
                let mip_bytes: &[u8] =
                    unsafe { std::slice::from_raw_parts(mip.as_ptr() as *const u8, mip.len() * 4) };
                file.write_all(mip_bytes)?;
            }
        }
        DdsFormat::R16Float => {
            // Convert f32 -> f16
            for &val in &volume.data {
                let h = f32_to_f16(val);
                file.write_all(&h.to_le_bytes())?;
            }
            for mip in &volume.mips {
                for &val in mip {
                    let h = f32_to_f16(val);
                    file.write_all(&h.to_le_bytes())?;
                }
            }
        }
        DdsFormat::R32G32B32A32Float => {
            // Pad distance to RGBA (dist, 0, 0, 0)
            for &val in &volume.data {
                file.write_all(&val.to_le_bytes())?;
                file.write_all(&0.0f32.to_le_bytes())?;
                file.write_all(&0.0f32.to_le_bytes())?;
                file.write_all(&0.0f32.to_le_bytes())?;
            }
            for mip in &volume.mips {
                for &val in mip {
                    file.write_all(&val.to_le_bytes())?;
                    file.write_all(&0.0f32.to_le_bytes())?;
                    file.write_all(&0.0f32.to_le_bytes())?;
                    file.write_all(&0.0f32.to_le_bytes())?;
                }
            }
        }
    }

    Ok(())
}

/// Export distance+gradient volume as DDS 3D (RGBA32F)
pub fn export_dds_3d_distgrad(
    volume: &Volume3D<super::VoxelDistGrad>,
    path: &str,
) -> io::Result<()> {
    let path = Path::new(path);
    let mut file = std::fs::File::create(path)?;

    let dxgi_format = 2u32; // R32G32B32A32_FLOAT
    let bytes_per_pixel = 16u32;

    // DDS magic
    file.write_all(&0x20534444u32.to_le_bytes())?;

    let header = DdsHeader {
        size: 124,
        flags: dds_header_flags(volume.mip_count()),
        height: volume.resolution[1],
        width: volume.resolution[0],
        pitch_or_linear_size: volume.resolution[0] * bytes_per_pixel,
        depth: volume.resolution[2],
        mip_map_count: volume.mip_count() as u32,
        reserved1: [0u32; 11],
        pf_size: 32,
        pf_flags: 0x00000004,
        pf_four_cc: u32::from_le_bytes(*b"DX10"),
        pf_rgb_bit_count: 0,
        pf_r_bitmask: 0,
        pf_g_bitmask: 0,
        pf_b_bitmask: 0,
        pf_a_bitmask: 0,
        caps: dds_caps(volume.mip_count()),
        caps2: DDSCAPS2_VOLUME,
        caps3: 0,
        caps4: 0,
        reserved2: 0,
    };
    write_dds_header(&mut file, &header)?;

    let dxt10 = DdsHeaderDxt10 {
        dxgi_format,
        resource_dimension: 4,
        misc_flag: 0,
        array_size: 1,
        misc_flags2: 0,
    };
    write_dds_header_dxt10(&mut file, &dxt10)?;

    // Write RGBA32F data (dist, nx, ny, nz)
    for voxel in &volume.data {
        file.write_all(&voxel.distance.to_le_bytes())?;
        file.write_all(&voxel.nx.to_le_bytes())?;
        file.write_all(&voxel.ny.to_le_bytes())?;
        file.write_all(&voxel.nz.to_le_bytes())?;
    }

    for mip in &volume.mips {
        for voxel in mip {
            file.write_all(&voxel.distance.to_le_bytes())?;
            file.write_all(&voxel.nx.to_le_bytes())?;
            file.write_all(&voxel.ny.to_le_bytes())?;
            file.write_all(&voxel.nz.to_le_bytes())?;
        }
    }

    Ok(())
}

// --- Internal helpers ---

// DDS header helper used by export_dds()
#[allow(dead_code)]
struct DdsHeader {
    size: u32,
    flags: u32,
    height: u32,
    width: u32,
    pitch_or_linear_size: u32,
    depth: u32,
    mip_map_count: u32,
    reserved1: [u32; 11],
    pf_size: u32,
    pf_flags: u32,
    pf_four_cc: u32,
    pf_rgb_bit_count: u32,
    pf_r_bitmask: u32,
    pf_g_bitmask: u32,
    pf_b_bitmask: u32,
    pf_a_bitmask: u32,
    caps: u32,
    caps2: u32,
    caps3: u32,
    caps4: u32,
    reserved2: u32,
}

fn write_dds_header(w: &mut impl Write, h: &DdsHeader) -> io::Result<()> {
    w.write_all(&h.size.to_le_bytes())?;
    w.write_all(&h.flags.to_le_bytes())?;
    w.write_all(&h.height.to_le_bytes())?;
    w.write_all(&h.width.to_le_bytes())?;
    w.write_all(&h.pitch_or_linear_size.to_le_bytes())?;
    w.write_all(&h.depth.to_le_bytes())?;
    w.write_all(&h.mip_map_count.to_le_bytes())?;
    for r in &h.reserved1 {
        w.write_all(&r.to_le_bytes())?;
    }
    w.write_all(&h.pf_size.to_le_bytes())?;
    w.write_all(&h.pf_flags.to_le_bytes())?;
    w.write_all(&h.pf_four_cc.to_le_bytes())?;
    w.write_all(&h.pf_rgb_bit_count.to_le_bytes())?;
    w.write_all(&h.pf_r_bitmask.to_le_bytes())?;
    w.write_all(&h.pf_g_bitmask.to_le_bytes())?;
    w.write_all(&h.pf_b_bitmask.to_le_bytes())?;
    w.write_all(&h.pf_a_bitmask.to_le_bytes())?;
    w.write_all(&h.caps.to_le_bytes())?;
    w.write_all(&h.caps2.to_le_bytes())?;
    w.write_all(&h.caps3.to_le_bytes())?;
    w.write_all(&h.caps4.to_le_bytes())?;
    w.write_all(&h.reserved2.to_le_bytes())?;
    Ok(())
}

struct DdsHeaderDxt10 {
    dxgi_format: u32,
    resource_dimension: u32,
    misc_flag: u32,
    array_size: u32,
    misc_flags2: u32,
}

fn write_dds_header_dxt10(w: &mut impl Write, h: &DdsHeaderDxt10) -> io::Result<()> {
    w.write_all(&h.dxgi_format.to_le_bytes())?;
    w.write_all(&h.resource_dimension.to_le_bytes())?;
    w.write_all(&h.misc_flag.to_le_bytes())?;
    w.write_all(&h.array_size.to_le_bytes())?;
    w.write_all(&h.misc_flags2.to_le_bytes())?;
    Ok(())
}

// DDS_HEADER.dwFlags / dwCaps / dwCaps2 bits (Microsoft "DDS_HEADER structure").
const DDSD_CAPS: u32 = 0x1;
const DDSD_HEIGHT: u32 = 0x2;
const DDSD_WIDTH: u32 = 0x4;
const DDSD_PITCH: u32 = 0x8;
const DDSD_PIXELFORMAT: u32 = 0x1000;
const DDSD_MIPMAPCOUNT: u32 = 0x2_0000;
const DDSD_DEPTH: u32 = 0x80_0000;
const DDSCAPS_COMPLEX: u32 = 0x8;
const DDSCAPS_TEXTURE: u32 = 0x1000;
const DDSCAPS_MIPMAP: u32 = 0x40_0000;
const DDSCAPS2_VOLUME: u32 = 0x20_0000;

/// `dwFlags` for an uncompressed volume texture with `mip_count` levels.
///
/// The pitch field holds the bytes per scan line of an uncompressed texture,
/// so the flag is `DDSD_PITCH`; `DDSD_LINEARSIZE` is the compressed-texture
/// variant and must not be set with it. `DDSD_MIPMAPCOUNT` marks a mipmapped
/// texture. Until 4.1.0 the header set both pitch flags and never set
/// `DDSD_MIPMAPCOUNT` (its comment named `0x8` "PIXELFORMAT"), pinned by
/// `tests/test_volume_api_oracle.rs`.
const fn dds_header_flags(mip_count: usize) -> u32 {
    let base = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PITCH | DDSD_PIXELFORMAT | DDSD_DEPTH;
    if mip_count > 1 {
        base | DDSD_MIPMAPCOUNT
    } else {
        base
    }
}

/// `dwCaps`: `DDSCAPS_COMPLEX | DDSCAPS_MIPMAP` only when the file holds more
/// than one surface, i.e. a mip chain.
const fn dds_caps(mip_count: usize) -> u32 {
    if mip_count > 1 {
        DDSCAPS_TEXTURE | DDSCAPS_COMPLEX | DDSCAPS_MIPMAP
    } else {
        DDSCAPS_TEXTURE
    }
}

/// Convert f32 to IEEE 754 binary16, rounding to nearest, ties to even
///
/// Delegates to [`crate::mesh::quantization::half_encode`]. The previous local
/// conversion truncated the mantissa (rounding toward zero), so an R16 DDS
/// volume stored up to one half-ulp more error than the format allows.
const fn f32_to_f16(value: f32) -> u16 {
    crate::mesh::quantization::half_encode(value)
}

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

    #[test]
    fn test_export_raw() {
        let vol = Volume3D::<f32>::new([4, 4, 4], Vec3::splat(-1.0), Vec3::splat(1.0));

        let dir = std::env::temp_dir();
        let path = dir.join("alice_test_volume.raw");
        let path_str = path.to_str().unwrap();

        export_raw(&vol, path_str).unwrap();

        // Check file exists and has correct size
        let bytes = std::fs::read(&path).unwrap();
        assert_eq!(bytes.len(), 4 * 4 * 4 * 4); // 64 voxels * 4 bytes

        // Check metadata exists
        let meta_path = path.with_extension("raw.meta.json");
        assert!(meta_path.exists());

        // Cleanup
        std::fs::remove_file(&path).ok();
        std::fs::remove_file(&meta_path).ok();
    }

    #[test]
    fn test_export_dds_3d() {
        let vol = Volume3D::<f32>::new([4, 4, 4], Vec3::splat(-1.0), Vec3::splat(1.0));

        let dir = std::env::temp_dir();
        let path = dir.join("alice_test_volume.dds");
        let path_str = path.to_str().unwrap();

        export_dds_3d(&vol, path_str, DdsFormat::R32Float).unwrap();

        let bytes = std::fs::read(&path).unwrap();
        // DDS magic + header (124) + DXT10 (20) + pixel data
        assert!(bytes.len() > 4 + 124 + 20);
        assert_eq!(&bytes[0..4], &0x20534444u32.to_le_bytes()); // "DDS "

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn test_f32_to_f16() {
        // Zero
        assert_eq!(f32_to_f16(0.0), 0x0000);

        // One
        assert_eq!(f32_to_f16(1.0), 0x3C00);

        // Negative one
        assert_eq!(f32_to_f16(-1.0), 0xBC00);

        // Infinity
        assert_eq!(f32_to_f16(f32::INFINITY), 0x7C00);
        assert_eq!(f32_to_f16(f32::NEG_INFINITY), 0xFC00);
    }
}