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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
#![doc(
    html_logo_url = "https://raw.githubusercontent.com/virtualritz/libfive-rs/HEAD/libfive/libfive-logo.png"
)]
//! A high level wrapper around [`libfive`](https://libfive.com/) -- a set of
//! tools for solid modeling based on
//! [functional representation](https://en.wikipedia.org/wiki/Function_representation).
//!
//! Particularly suited for parametric- and procedural modeling. An
//! infrastructure for generative design, mass customization, and
//! domain-specific CAD tools.
//!
//! ## Example
//!
//! ```ignore
//! # use libfive::*;
//! # fn example() -> Result<()> {
//! let f_rep_shape = Tree::sphere(1.0.into(), TreeVec3::default())
//!     .difference_multi(vec![
//!         Tree::sphere(0.6.into(), TreeVec3::default()),
//!         Tree::cylinder_z(
//!             0.6.into(),
//!             2.0.into(),
//!             TreeVec3::new(0.0, 0.0, -1.0),
//!         ),
//!         Tree::cylinder_z(
//!             0.6.into(),
//!             2.0.into(),
//!             TreeVec3::new(0.0, 0.0, -1.0),
//!         )
//!         .reflect_xz(),
//!         Tree::cylinder_z(
//!             0.6.into(),
//!             2.0.into(),
//!             TreeVec3::new(0.0, 0.0, -1.0),
//!         )
//!         .reflect_yz(),
//!     ]);
//!
//! f_rep_shape.write_stl(
//!     "f-rep-shape.stl",
//!     &Region3::new(-2.0, 2.0, -2.0, 2.0, -2.0, 2.0),
//!     // Subdivisions
//!     10.0,
//! )?;
//! # }
//! ```
//! The STL file generated from this code is show below.
//!
//! ## Features
//!
//! <img src="https://raw.githubusercontent.com/virtualritz/libfive-rs/HEAD/libfive/f-rep-shape.png" alt="Generated CSG Shape" width="38%" padding-left="15%" align="right" align="top">
//!
//! * [`ahash`](https://crates.io/crates/ahash) -- On by default. Use [`AHashMap`](https://docs.rs/ahash/latest/ahash/struct.AHashMap.html)
//!   for hashing when resolving variable names. Disabling this will fall back
//!   to the slower [`HashMap`](std::collections::HashMap).
//!
//! * `stdlib` -- On by default. Add an extensive list of higher level
//!   operations -- the [`libfive stdlib`](Tree#standard-library).
//!
//!   To disable either/both of the above features unset default features in
//!   `Cargo.toml`:
//!
//!   ```toml
//!   [dependencies.libfive]
//!   default-features = false
//!   ```
//!
//! * `packed_opcodes` -- Tightly pack opcodes. This breaks compatibility with
//!   older saved f-rep files.
//!
//!   See [`Tree::save()`](Tree::save)/[`load()`](Tree::load).
use core::{
    ffi::c_void,
    ops::{Add, Div, Mul, Neg, Rem, Sub},
    ptr, result, slice,
};
use libfive_sys as sys;
use std::{ffi::CString, path::Path};
use derive_more::{Display, Error, From};

#[cfg(feature = "ahash")]
type HashMap<K, V> = ahash::AHashMap<K, V>;
#[cfg(not(feature = "ahash"))]
type HashMap<K, V> = std::collections::HashMap<K, V>;

#[cfg(feature = "stdlib")]
mod stdlib;
#[cfg(feature = "stdlib")]
pub use stdlib::*;

/// A specialized [`Result`] type for `libfive` operations.
///
/// This type is broadly used across `libvive` for any operation which may
/// produce an error.
///
/// This type is generally used to avoid writing out [`enum@Error`] directly and
/// is otherwise a direct mapping to [`Result`].
pub type Result<T> = result::Result<T, Error>;

/// A list specifying general categories of errors.
///
/// This list is intended to grow over time and it is not recommended to
/// exhaustively match against it.
///
/// [`libfive::Error`]: Error
#[derive(Clone, Copy, Debug, Display, Eq, Error, From, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum Error {
    /// The specified variable could not be updated.
    VariablesCouldNotBeUpdated,
    /// The requested variable could not be found.
    VariableNotFound,
    /// The variable with this name was already added.
    VariableAlreadyAdded,
    /// The resp. file could not be opened for writing.
    FileWriteFailed,
    /// The resp. file could not be opened for reading.
    FileReadFailed,
    /// The queried tree is not a constant.
    TreeIsNotConstant,
}

/// Trait to aid with using arbitrary 2D point types on a [`Contour`].
pub trait Point2 {
    fn new(x: f32, y: f32) -> Self;
    fn x(&self) -> f32;
    fn y(&self) -> f32;
}

/// Trait to aid with using arbitrary 3D point types on a [`TriangleMesh`].
pub trait Point3 {
    fn new(x: f32, y: f32, z: f32) -> Self;
    fn x(&self) -> f32;
    fn y(&self) -> f32;
    fn z(&self) -> f32;
}

/// Series of 2D or 3D points forming a
/// [polygonal chain](https://en.wikipedia.org/wiki/Polygonal_chain).
pub type Contour<T> = Vec<T>;

/// Bitmap representing occupancy in a slice of a [`Tree`].
///
/// It contains `width()` * `height()` pixels, in row-major order.
pub struct Bitmap(*mut sys::libfive_pixels);

impl Bitmap {
    /// Returns the bitmap pixel buffer as a flat `[bool]` slice.
    ///
    /// The length is `width()` × `height()`.
    pub fn as_slice(&self) -> &[bool] {
        let bitmap = unsafe { self.0.as_ref() }.unwrap();
        unsafe {
            slice::from_raw_parts(
                bitmap.pixels,
                (bitmap.width * bitmap.height) as _,
            )
        }
    }

    /// Returns the bitmap pixel buffer as a flat, mutable `[bool]` slice.
    ///
    /// The length is `width()` × `height()`.
    pub fn as_slice_mut(&mut self) -> &mut [bool] {
        let bitmap = unsafe { self.0.as_mut() }.unwrap();
        unsafe {
            slice::from_raw_parts_mut(
                bitmap.pixels,
                (bitmap.width * bitmap.height) as _,
            )
        }
    }

    /// Returns the value of the pixel `x`, `y`.
    pub fn pixel(&self, x: u32, y: u32) -> bool {
        assert!(x < self.width() && y < self.height());
        self.as_slice()[(y * self.height() + x) as usize]
    }

    /// Returns the width of the bitmap.
    pub fn width(&self) -> u32 {
        unsafe { self.0.as_ref() }.unwrap().width
    }

    /// Returns the height of the bitmap.
    pub fn height(&self) -> u32 {
        unsafe { self.0.as_ref() }.unwrap().height
    }
}

impl Drop for Bitmap {
    fn drop(&mut self) {
        unsafe { sys::libfive_pixels_delete(&mut self.0 as *mut _ as _) };
    }
}

/// Triangle mesh.
///
/// The `positions` type is generic. You can use whatever type you like. Just
/// implement the [`Point3`] trait on it.
///
/// The `triangles` are a list of indices into the `positions`.
pub struct TriangleMesh<T: Point3> {
    pub positions: Vec<T>,
    pub triangles: Vec<[u32; 3]>,
}

/// Flat triangle mesh.
///
/// The `positions` list has layout `[x0, y0, z0, x1, y1, z1, ...]`.
///
/// The `triangles` list has layout `[t0.v0, t0.v1, t0.v2, t1.v0, t1.v1, t1.v2,
/// ...]` where `t`*n* is triangle *n* and `v`*m* is vertex index *m*.
pub struct FlatTriangleMesh {
    pub positions: Vec<f32>,
    pub triangles: Vec<u32>,
}

impl<T: Point3> From<TriangleMesh<T>> for FlatTriangleMesh {
    fn from(mesh: TriangleMesh<T>) -> FlatTriangleMesh {
        FlatTriangleMesh {
            positions: mesh
                .positions
                .into_iter()
                .flat_map(|point| [point.x(), point.y(), point.z()])
                .collect(),
            triangles: mesh.triangles.into_iter().flatten().collect(),
        }
    }
}

/// Set of variables to parameterize a [`Tree`].
pub struct Variables {
    map: HashMap<String, usize>,
    variables: Vec<*const c_void>,
    values: Vec<f32>,
    sys_variables: sys::libfive_vars,
}

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

impl Variables {
    /// Creates a new, empty set of variables.
    pub fn new() -> Self {
        Self {
            map: HashMap::new(),
            variables: Vec::new(),
            values: Vec::new(),
            sys_variables: sys::libfive_vars {
                vars: ptr::null(),
                values: ptr::null_mut(),
                size: 0,
            },
        }
    }

    /// Adds the variable `name` to the set.
    ///
    /// # Errors
    ///
    /// Returns [`Error::VariableAlreadyAdded`] if the variable already exists
    /// in the set.
    pub fn add(&mut self, name: &str, value: f32) -> Result<Tree> {
        let name = name.to_string();
        if self.map.contains_key(&name) {
            Err(Error::VariableAlreadyAdded)
        } else {
            let tree = unsafe { sys::libfive_tree_var() };
            let id = unsafe { sys::libfive_tree_id(tree) };

            self.map.insert(name, self.variables.len());
            self.variables.push(id);
            self.values.push(value);
            // Update struct.
            self.sys_variables.vars = self.variables.as_ptr() as *const _ as _;
            self.sys_variables.values = self.values.as_ptr() as *const _ as _;
            self.sys_variables.size = self.variables.len().try_into().unwrap();

            Ok(Tree(tree))
        }
    }

    /// Sets the variable `name` to `value`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::VariableNotFound`] if the variable does not exist in
    /// the set.
    pub fn set(&mut self, name: &str, value: f32) -> Result<()> {
        if let Some(&index) = self.map.get(name) {
            self.values[index] = value;
            Ok(())
        } else {
            Err(Error::VariableNotFound)
        }
    }
}

impl Drop for Variables {
    fn drop(&mut self) {
        unsafe {
            sys::libfive_vars_delete(&mut self.sys_variables as *mut _ as _)
        };
    }
}

/// Helper for controlling evaluation of [`Variables`] on a [`Tree`].
pub struct Evaluator(sys::libfive_evaluator);

impl Evaluator {
    pub fn new(tree: &Tree, variables: &Variables) -> Self {
        Self(unsafe {
            sys::libfive_tree_evaluator(tree.0, variables.sys_variables)
        })
    }

    pub fn update(&mut self, variables: &Variables) -> Result<()> {
        if unsafe {
            sys::libfive_evaluator_update_vars(self.0, variables.sys_variables)
        } {
            Err(Error::VariablesCouldNotBeUpdated)
        } else {
            Ok(())
        }
    }

    /// Computes a mesh and saves it to `path` in
    /// [`STL`](https://en.wikipedia.org/wiki/STL_(file_format)) format.
    pub fn write_stl(
        &self,
        path: impl AsRef<Path>,
        region: &Region3,
    ) -> Result<()> {
        let path = c_string_from_path(path);

        if unsafe {
            sys::libfive_evaluator_save_mesh(self.0, region.0, path.as_ptr())
        } {
            Ok(())
        } else {
            Err(Error::FileWriteFailed)
        }
    }
}

impl Drop for Evaluator {
    fn drop(&mut self) {
        unsafe { sys::libfive_evaluator_delete(self.0) };
    }
}

/// 2D bounding region.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Region2(sys::libfive_region2);

impl Region2 {
    pub fn new(x_min: f32, x_max: f32, y_min: f32, y_max: f32) -> Self {
        Self(sys::libfive_region2 {
            X: sys::libfive_interval {
                lower: x_min,
                upper: x_max,
            },
            Y: sys::libfive_interval {
                lower: y_min,
                upper: y_max,
            },
        })
    }
}

/// 3D bounding region.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Region3(sys::libfive_region3);

impl Region3 {
    pub fn new(
        x_min: f32,
        x_max: f32,
        y_min: f32,
        y_max: f32,
        z_min: f32,
        z_max: f32,
    ) -> Self {
        Self(sys::libfive_region3 {
            X: sys::libfive_interval {
                lower: x_min,
                upper: x_max,
            },
            Y: sys::libfive_interval {
                lower: y_min,
                upper: y_max,
            },
            Z: sys::libfive_interval {
                lower: z_min,
                upper: z_max,
            },
        })
    }
}

#[allow(dead_code)]
#[repr(i32)]
enum Op {
    Invalid = 0,

    Constant = 1,
    VarX = 2,
    VarY = 3,
    VarZ = 4,
    VarFree = 5,
    ConstVar = 6,

    Square = 7,
    Sqrt = 8,
    Neg = 9,
    Sin = 10,
    Cos = 11,
    Tan = 12,
    Asin = 13,
    Acos = 14,
    Atan = 15,
    Exp = 16,
    Abs = 28,
    Log = 30,
    Recip = 29,

    Add = 17,
    Mul = 18,
    Min = 19,
    Max = 20,
    Sub = 21,
    Div = 22,
    Atan2 = 23,
    Pow = 24,
    NthRoot = 25,
    Mod = 26,
    NanFill = 27,
    Compare = 31,

    Oracle = 32,
}

macro_rules! fn_unary {
    ($func_name:ident, $op_code:ident) => {
        #[inline]
        pub fn $func_name(&self) -> Self {
            Self(unsafe { sys::libfive_tree_unary(Op::$op_code as _, self.0) })
        }
    };
}

macro_rules! fn_binary {
    ($func_name:ident, $op_code:ident, $other:ident) => {
        #[inline]
        pub fn $func_name(self, $other: Self) -> Self {
            Self(unsafe {
                sys::libfive_tree_binary(Op::$op_code as _, self.0, $other.0)
            })
        }
    };
}

macro_rules! op_binary {
    ($func_name:ident, $op_code:ident) => {
        impl $op_code for Tree {
            type Output = Tree;
            #[inline]
            fn $func_name(self, rhs: Tree) -> Self::Output {
                self.$func_name(rhs)
            }
        }
    };
}

/// Tree of operations.
///
/// # Core
///
/// * [Constant][`TreeFloat::from::<f32>()`]
/// * [Bases](#bases)
/// * [Functions](#functions)
/// * [Evaluation, import & export](#eval)
///
/// # Standard Library
///
/// These features are dependent on the `stdlib` feature being enabled.
///
/// * [Shapes](#shapes)
/// * [Generators](#generators)
/// * [Constructive solid geometry](#csg)
/// * [Transformations](#transforms)
/// * [Text](#text)
#[derive(Eq, PartialEq)]
pub struct Tree(sys::libfive_tree);

/// An alias for [`Tree`].
///
/// Used to make the kind of sensible input more obvious for some operators.
pub type TreeFloat = Tree;

/// # Constants <a name="constant"></a>
impl From<f32> for Tree {
    /// Creates a constant [`Tree`].
    fn from(constant: f32) -> Self {
        Self(unsafe { sys::libfive_tree_const(constant) })
    }
}

/// # Bases <a name="bases"></a>
impl Tree {
    #[inline]
    pub fn x() -> Self {
        Self(unsafe { sys::libfive_tree_x() })
    }

    #[inline]
    pub fn y() -> Self {
        Self(unsafe { sys::libfive_tree_y() })
    }

    #[inline]
    pub fn z() -> Self {
        Self(unsafe { sys::libfive_tree_z() })
    }

    //pub fn variable() -> Self {}
}

/// # Functions <a name="functions"></a>
impl Tree {
    fn_unary!(square, Square);
    fn_unary!(sqrt, Sqrt);
    fn_unary!(neg, Neg);
    fn_unary!(sin, Sin);
    fn_unary!(cos, Cos);
    fn_unary!(tan, Tan);
    fn_unary!(asin, Asin);
    fn_unary!(acos, Acos);
    fn_unary!(atan, Atan);
    fn_unary!(exp, Exp);
    fn_unary!(abs, Abs);
    fn_unary!(log, Log);
    fn_unary!(recip, Recip);

    fn_binary!(add, Add, rhs);
    fn_binary!(mul, Mul, rhs);
    fn_binary!(min, Min, rhs);
    fn_binary!(max, Max, rhs);
    fn_binary!(sub, Sub, rhs);
    fn_binary!(div, Div, rhs);
    fn_binary!(atan2, Atan2, other);
    fn_binary!(pow, Pow, exp);
    fn_binary!(nth_root, NthRoot, n);
    fn_binary!(rem, Mod, rhs);
    fn_binary!(nan_fill, NanFill, rhs);
    fn_binary!(compare, Compare, rhs);

    /// Checks if the tree is a variable.
    pub fn is_variable(&self) -> bool {
        unsafe { sys::libfive_tree_is_var(self.0) }
    }

    /// Returns the value of the tree if it is constant.
    ///
    /// I.e. if it was created from an [`f32`] value.
    ///
    /// # Errors
    ///
    /// Returns [`TreeIsNotConstant`](Error::TreeIsNotConstant) if the tree is
    /// not constant.
    pub fn as_f32(&self) -> Result<f32> {
        let mut success = false;
        let value = unsafe {
            sys::libfive_tree_get_const(self.0, &mut success as *mut _)
        };

        if success {
            Ok(value)
        } else {
            Err(Error::TreeIsNotConstant)
        }
    }
}

/// # Evaluation, Import & Export <a name="eval"></a>
///
/// ## Common Arguments
///
/// * `region` -- A bounding box that will be subdivided into an
///   quadtree/octree. For clean lines/triangles, it should be near-cubical.
///   But this is not a hard requirement.
///
/// * `resolution` -- The resolution used for meshing. Make this larger to get a
///   higher-resolution model.
///
///   To not loose any detail this should be approximately one over half the
///   model's smallest feature size.
///
///   For methods generating 3D data another way to think of resolution is as
///   the number of subdivision, per unit length, on each axis.
impl Tree {
    /// Renders a 2D slice of `region` at the given `z` height into a
    /// [`Bitmap`].
    #[inline]
    pub fn to_bitmap(
        &self,
        region: &Region2,
        z: f32,
        resolution: f32,
    ) -> Bitmap {
        Bitmap(unsafe {
            sys::libfive_tree_render_pixels(self.0, region.0, z, resolution)
        })
    }

    /// Renders `region` to a [`TriangleMesh`].
    pub fn to_triangle_mesh<T: Point3>(
        &self,
        region: &Region3,
        resolution: f32,
    ) -> Option<TriangleMesh<T>> {
        match unsafe {
            sys::libfive_tree_render_mesh(self.0, region.0, resolution).as_mut()
        } {
            Some(raw_mesh) => {
                let mesh = TriangleMesh::<T> {
                    positions: (0..raw_mesh.vert_count)
                        .map(|index| {
                            let vertex =
                                &unsafe { *raw_mesh.verts.add(index as _) };
                            T::new(vertex.x, vertex.y, vertex.z)
                        })
                        .collect(),
                    triangles: (0..raw_mesh.tri_count)
                        .map(|index| {
                            let triangle =
                                &unsafe { *raw_mesh.tris.add(index as _) };
                            [triangle.a, triangle.b, triangle.c]
                        })
                        .collect(),
                };

                unsafe {
                    sys::libfive_mesh_delete(raw_mesh as *mut _ as _);
                }

                Some(mesh)
            }
            None => None,
        }
    }

    /// Renders a 2D slice of `region` at the given `z` height to a set of 2D
    /// contours.
    pub fn to_contour_2d<T: Point2>(
        &self,
        region: Region2,
        z: f32,
        resolution: f32,
    ) -> Option<Vec<Contour<T>>> {
        match unsafe {
            sys::libfive_tree_render_slice(self.0, region.0, z, resolution)
                .as_mut()
        } {
            Some(raw_contours) => {
                let contours = (0..raw_contours.count)
                    .map(|index| {
                        let contour =
                            unsafe { raw_contours.cs.add(index as _).as_ref() }
                                .unwrap();
                        (0..contour.count)
                            .map(|index| {
                                let point = unsafe {
                                    contour.pts.add(index as _).as_ref()
                                }
                                .unwrap();
                                T::new(point.x, point.y)
                            })
                            .collect()
                    })
                    .collect();

                unsafe {
                    sys::libfive_contours_delete(raw_contours as *mut _ as _);
                }

                Some(contours)
            }
            None => None,
        }
    }

    /// Renders `region` to a set of 3D contours.
    pub fn to_contour_3d<T: Point3>(
        &self,
        region: Region2,
        z: f32,
        resolution: f32,
    ) -> Option<Vec<Contour<T>>> {
        let raw_contours = unsafe {
            sys::libfive_tree_render_slice3(self.0, region.0, z, resolution)
                .as_ref()
        };

        if let Some(raw_contours) = raw_contours {
            let contours = (0..raw_contours.count)
                .map(|index| {
                    let contour =
                        unsafe { raw_contours.cs.add(index as _).as_ref() }
                            .unwrap();

                    (0..contour.count)
                        .map(|index| {
                            let point =
                                unsafe { contour.pts.add(index as _).as_ref() }
                                    .unwrap();
                            T::new(point.x, point.y, point.z)
                        })
                        .collect()
                })
                .collect();

            unsafe {
                sys::libfive_contours_delete(&raw_contours as *const _ as _);
            }

            Some(contours)
        } else {
            None
        }
    }

    /// Computes a 2D slice of `region` at the given `z` height and saves it to
    /// `path` in [`SVG`](https://en.wikipedia.org/wiki/Scalable_Vector_Graphics)
    /// format.
    pub fn write_svg(
        &self,
        path: impl AsRef<Path>,
        region: &Region2,
        z: f32,
        resolution: f32,
    ) {
        let path = c_string_from_path(path);

        unsafe {
            sys::libfive_tree_save_slice(
                self.0,
                region.0,
                z,
                resolution,
                path.as_ptr(),
            );
        }
    }

    /// Computes a mesh of `region` and saves it to `path` in
    /// [`STL`](https://en.wikipedia.org/wiki/STL_(file_format)) format.
    pub fn write_stl(
        &self,
        path: impl AsRef<Path>,
        region: &Region3,
        resolution: f32,
    ) -> Result<()> {
        let path = c_string_from_path(path);

            println!("Foobar! {:?}", path);

        if unsafe {
            sys::libfive_tree_save_mesh(
                self.0,
                region.0,
                resolution,
                path.as_ptr(),
            )
        } {
            Ok(())
        } else {
            Err(Error::FileWriteFailed)
        }
    }

    /// Serializes the tree to a file.
    ///
    /// <div class="warning">
    ///
    /// The file format is not archival and may change without notice.
    ///
    /// Saved files may fail to load with older versions of `libfive` if the
    /// `packed_opcodes` feature is enabled.
    ///
    /// </div>
    pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
        let path = c_string_from_path(path);

        if unsafe { sys::libfive_tree_save(self.0, path.as_ptr()) } {
            Ok(())
        } else {
            Err(Error::FileWriteFailed)
        }
    }

    /// Deserializes a tree from a file.
    ///
    /// <div class="warning">
    ///
    /// Old files may fail to load if the `packed_opcodes` feature is enabled.
    ///
    /// </div>
    pub fn load(&self, path: impl AsRef<Path>) -> Result<Tree> {
        let path = c_string_from_path(path);

        match unsafe { sys::libfive_tree_load(path.as_ptr()).as_mut() } {
            Some(tree) => Ok(Self(tree as _)),
            None => Err(Error::FileReadFailed),
        }
    }
}

impl Drop for Tree {
    fn drop(&mut self) {
        unsafe { sys::libfive_tree_delete(self.0) };
    }
}

op_binary!(add, Add);
op_binary!(div, Div);
op_binary!(mul, Mul);
op_binary!(rem, Rem);
op_binary!(sub, Sub);

impl Neg for Tree {
    type Output = Tree;

    fn neg(self) -> Self::Output {
        Self(unsafe { sys::libfive_tree_unary(Op::Neg as _, self.0) })
    }
}

fn c_string_from_path<P: AsRef<Path>>(path: P) -> CString {
    CString::new(path.as_ref().as_os_str().as_encoded_bytes()).unwrap()
}

#[test]
fn test_2d() -> Result<()> {
    let circle = Tree::x().square() + Tree::y().square() - 1.0.into();

    circle.write_svg(
        "circle.svg",
        &Region2::new(-2.0, 2.0, -2.0, 2.0),
        0.0,
        10.0,
    );

    Ok(())
}

#[test]
#[cfg(feature = "stdlib")]
fn test_3d() -> Result<()> {
    let f_rep_shape = Tree::sphere(1.0.into(), TreeVec3::default())
        .difference_multi(vec![
            Tree::sphere(0.6.into(), TreeVec3::default()),
            Tree::cylinder_z(
                0.6.into(),
                2.0.into(),
                TreeVec3::new(0.0, 0.0, -1.0),
            ),
            Tree::cylinder_z(
                0.6.into(),
                2.0.into(),
                TreeVec3::new(0.0, 0.0, -1.0),
            )
            .reflect_xz(),
            Tree::cylinder_z(
                0.6.into(),
                2.0.into(),
                TreeVec3::new(0.0, 0.0, -1.0),
            )
            .reflect_yz(),
        ]);

    f_rep_shape.write_stl(
        "f-rep-shape.stl",
        &Region3::new(-2.0, 2.0, -2.0, 2.0, -2.0, 2.0),
        // Subdivisions
        10.0,
    )?;

    Ok(())
}

/*
#[test]
#[cfg(feature = "stdlib")]
fn test_eval_3d() -> Result<()> {
    //let mut variables = Variables::new();

    //let inner_radius = variables.add("inner_radius", 0.6)?;

    let csg_shape = Tree::sphere(1.0.into(), TreeVec3::default())
        .difference_multi(vec![
            Tree::sphere(0.6.into(), TreeVec3::default()),
            Tree::cylinder_z(
                0.6.into(),
                2.0.into(),
                TreeVec3::new(0.0, 0.0, -1.0),
            ),
            Tree::cylinder_z(
                0.6.into(),
                2.0.into(),
                TreeVec3::new(0.0, 0.0, -1.0),
            )
            .reflect_xz(),
            Tree::cylinder_z(
                0.6.into(),
                2.0.into(),
                TreeVec3::new(0.0, 0.0, -1.0),
            )
            .reflect_yz(),
        ]);

    //let mut evaluator = Evaluator::new(&csg_shape, &variables);
    //evaluator.update(&variables);

    csg_shape.write_stl(
        "csg_shape.stl",
        &Region3::new(-2.0, 2.0, -2.0, 2.0, -2.0, 2.0),
        10.0,
    )?;
    /*
    variables.set("inner_radius", 0.4);
    evaluator.update(&variables);

    csg_shape.write_stl(
        "csg_shape_0_4.stl",
        &Region3::new(-2.0, 2.0, -2.0, 2.0, -2.0, 2.0),
        10.0,
    )?;*/

    Ok(())
}*/