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
//! AMF file format support for Mesh objects
//!
//! This module provides export functionality for AMF (Additive Manufacturing File Format),
//! an XML-based format specifically designed for 3D printing and additive manufacturing.
use crate::float_types::Real;
use crate::mesh::Mesh;
use crate::sketch::Sketch;
use geo::CoordsIter;
use nalgebra::Point3;
use std::fmt::Debug;
use std::io::Write;
impl<S: Clone + Debug + Send + Sync> Mesh<S> {
/// Export this Mesh to AMF format as a string
///
/// Creates an AMF (Additive Manufacturing File Format) file containing:
/// 1. All 3D polygons from Mesh (tessellated to triangles)
///
/// AMF is an XML-based format designed for 3D printing with support for:
/// - Complex 3D geometries
/// - Multiple materials and colors
/// - Metadata and manufacturing information
///
/// # Arguments
/// * `object_name` - Name for the object in the AMF file
/// * `units` - Units for the geometry (e.g., "millimeter", "inch")
///
/// # Example
/// ```
/// use csgrs::mesh::Mesh;
/// let csg: Mesh<()> = Mesh::cube(10.0, None);
/// let amf_content = csg.to_amf("my_cube", "millimeter");
/// println!("{}", amf_content);
/// ```
pub fn to_amf(&self, object_name: &str, units: &str) -> String {
let mut amf_content = String::new();
// AMF XML header
amf_content.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
amf_content.push_str("<amf unit=\"");
amf_content.push_str(units);
amf_content.push_str("\" version=\"1.1\">\n");
// Metadata
amf_content.push_str(" <metadata type=\"producer\">csgrs library</metadata>\n");
amf_content
.push_str(" <metadata type=\"cad\">Constructive Solid Geometry</metadata>\n");
amf_content.push_str(&format!(
" <metadata type=\"description\">{object_name}</metadata>\n"
));
let mut vertices = Vec::new();
let mut triangles = Vec::new();
// Process 3D polygons
for poly in &self.polygons {
// Tessellate polygon to triangles
let poly_triangles = poly.triangulate();
for triangle in poly_triangles {
let mut triangle_indices = Vec::new();
for vertex in triangle {
let vertex_idx = add_unique_vertex_amf(&mut vertices, vertex.pos);
triangle_indices.push(vertex_idx);
}
if triangle_indices.len() == 3 {
triangles.push(triangle_indices);
}
}
}
// Start object definition
amf_content.push_str(&format!(" <object id=\"{object_name}\">\n"));
amf_content.push_str(" <mesh>\n");
// Write vertices
amf_content.push_str(" <vertices>\n");
for (i, vertex) in vertices.iter().enumerate() {
amf_content.push_str(&format!(" <vertex id=\"{i}\">\n"));
amf_content.push_str(" <coordinates>\n");
amf_content.push_str(&format!(" <x>{:.6}</x>\n", vertex.x));
amf_content.push_str(&format!(" <y>{:.6}</y>\n", vertex.y));
amf_content.push_str(&format!(" <z>{:.6}</z>\n", vertex.z));
amf_content.push_str(" </coordinates>\n");
amf_content.push_str(" </vertex>\n");
}
amf_content.push_str(" </vertices>\n");
// Write triangles (volume definition)
amf_content.push_str(" <volume>\n");
for (i, triangle) in triangles.iter().enumerate() {
amf_content.push_str(&format!(" <triangle id=\"{i}\">\n"));
amf_content.push_str(&format!(" <v1>{}</v1>\n", triangle[0]));
amf_content.push_str(&format!(" <v2>{}</v2>\n", triangle[1]));
amf_content.push_str(&format!(" <v3>{}</v3>\n", triangle[2]));
amf_content.push_str(" </triangle>\n");
}
amf_content.push_str(" </volume>\n");
// Close mesh and object
amf_content.push_str(" </mesh>\n");
amf_content.push_str(" </object>\n");
// Close AMF
amf_content.push_str("</amf>\n");
amf_content
}
/// Export this Mesh to an AMF file
///
/// # Arguments
/// * `writer` - Where to write the AMF data
/// * `object_name` - Name for the object in the AMF file
/// * `units` - Units for the geometry (e.g., "millimeter", "inch")
///
/// # Example
/// ```
/// use csgrs::mesh::Mesh;
/// use std::fs::File;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let csg: Mesh<()> = Mesh::cube(10.0, None);
/// let mut file = File::create("stl/output.amf")?;
/// csg.write_amf(&mut file, "my_cube", "millimeter")?;
/// # Ok(())
/// # }
/// ```
pub fn write_amf<W: Write>(
&self,
writer: &mut W,
object_name: &str,
units: &str,
) -> std::io::Result<()> {
let amf_content = self.to_amf(object_name, units);
writer.write_all(amf_content.as_bytes())
}
/// Export this Mesh to AMF format with color information
///
/// Creates an AMF file with color/material information for enhanced 3D printing.
///
/// # Arguments
/// * `object_name` - Name for the object in the AMF file
/// * `units` - Units for the geometry (e.g., "millimeter", "inch")
/// * `color` - RGB color as (red, green, blue) where each component is 0.0-1.0
///
/// # Example
/// ```
/// use csgrs::mesh::Mesh;
/// let csg: Mesh<()> = Mesh::cube(10.0, None);
/// let amf_content = csg.to_amf_with_color("red_cube", "millimeter", (1.0, 0.0, 0.0));
/// println!("{}", amf_content);
/// ```
pub fn to_amf_with_color(
&self,
object_name: &str,
units: &str,
color: (Real, Real, Real),
) -> String {
let mut amf_content = String::new();
// AMF XML header
amf_content.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
amf_content.push_str("<amf unit=\"");
amf_content.push_str(units);
amf_content.push_str("\" version=\"1.1\">\n");
// Metadata
amf_content.push_str(" <metadata type=\"producer\">csgrs library</metadata>\n");
amf_content
.push_str(" <metadata type=\"cad\">Constructive Solid Geometry</metadata>\n");
amf_content.push_str(&format!(
" <metadata type=\"description\">{object_name}</metadata>\n"
));
// Material definition with color
amf_content.push_str(" <material id=\"material1\">\n");
amf_content.push_str(" <metadata type=\"name\">Default Material</metadata>\n");
amf_content.push_str(" <color>\n");
amf_content.push_str(&format!(" <r>{:.3}</r>\n", color.0));
amf_content.push_str(&format!(" <g>{:.3}</g>\n", color.1));
amf_content.push_str(&format!(" <b>{:.3}</b>\n", color.2));
amf_content.push_str(" <a>1.0</a>\n"); // Alpha (opacity)
amf_content.push_str(" </color>\n");
amf_content.push_str(" </material>\n");
let mut vertices = Vec::new();
let mut triangles = Vec::new();
// Process 3D polygons
for poly in &self.polygons {
let poly_triangles = poly.triangulate();
for triangle in poly_triangles {
let mut triangle_indices = Vec::new();
for vertex in triangle {
let vertex_idx = add_unique_vertex_amf(&mut vertices, vertex.pos);
triangle_indices.push(vertex_idx);
}
if triangle_indices.len() == 3 {
triangles.push(triangle_indices);
}
}
}
// Start object definition
amf_content.push_str(&format!(" <object id=\"{object_name}\">\n"));
amf_content.push_str(" <mesh>\n");
// Write vertices
amf_content.push_str(" <vertices>\n");
for (i, vertex) in vertices.iter().enumerate() {
amf_content.push_str(&format!(" <vertex id=\"{i}\">\n"));
amf_content.push_str(" <coordinates>\n");
amf_content.push_str(&format!(" <x>{:.6}</x>\n", vertex.x));
amf_content.push_str(&format!(" <y>{:.6}</y>\n", vertex.y));
amf_content.push_str(&format!(" <z>{:.6}</z>\n", vertex.z));
amf_content.push_str(" </coordinates>\n");
amf_content.push_str(" </vertex>\n");
}
amf_content.push_str(" </vertices>\n");
// Write triangles with material reference
amf_content.push_str(" <volume materialid=\"material1\">\n");
for (i, triangle) in triangles.iter().enumerate() {
amf_content.push_str(&format!(" <triangle id=\"{i}\">\n"));
amf_content.push_str(&format!(" <v1>{}</v1>\n", triangle[0]));
amf_content.push_str(&format!(" <v2>{}</v2>\n", triangle[1]));
amf_content.push_str(&format!(" <v3>{}</v3>\n", triangle[2]));
amf_content.push_str(" </triangle>\n");
}
amf_content.push_str(" </volume>\n");
// Close mesh and object
amf_content.push_str(" </mesh>\n");
amf_content.push_str(" </object>\n");
// Close AMF
amf_content.push_str("</amf>\n");
amf_content
}
}
impl<S: Clone + Debug + Send + Sync> Sketch<S> {
/// Export this Mesh to AMF format as a string
///
/// Creates an AMF (Additive Manufacturing File Format) file containing:
/// 2. Any 2D geometry from Sketch (extruded/projected to 3D)
///
/// AMF is an XML-based format designed for 3D printing with support for:
/// - Complex 3D geometries
/// - Multiple materials and colors
/// - Metadata and manufacturing information
///
/// # Arguments
/// * `object_name` - Name for the object in the AMF file
/// * `units` - Units for the geometry (e.g., "millimeter", "inch")
///
/// # Example
/// ```
/// use csgrs::mesh::Mesh;
/// let csg: Mesh<()> = Mesh::cube(10.0, None);
/// let amf_content = csg.to_amf("my_cube", "millimeter");
/// println!("{}", amf_content);
/// ```
pub fn to_amf(&self, object_name: &str, units: &str) -> String {
let mut amf_content = String::new();
// AMF XML header
amf_content.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
amf_content.push_str("<amf unit=\"");
amf_content.push_str(units);
amf_content.push_str("\" version=\"1.1\">\n");
// Metadata
amf_content.push_str(" <metadata type=\"producer\">csgrs library</metadata>\n");
amf_content
.push_str(" <metadata type=\"cad\">Constructive Solid Geometry</metadata>\n");
amf_content.push_str(&format!(
" <metadata type=\"description\">{object_name}</metadata>\n"
));
let mut vertices = Vec::new();
let mut triangles = Vec::new();
// Process 2D geometry (project to XY plane at Z=0)
for geom in &self.geometry.0 {
match geom {
geo::Geometry::Polygon(poly2d) => {
self.add_2d_polygon_to_amf(poly2d, &mut vertices, &mut triangles);
},
geo::Geometry::MultiPolygon(mp) => {
for poly2d in &mp.0 {
self.add_2d_polygon_to_amf(poly2d, &mut vertices, &mut triangles);
}
},
_ => {}, // Skip other geometry types
}
}
// Start object definition
amf_content.push_str(&format!(" <object id=\"{object_name}\">\n"));
amf_content.push_str(" <mesh>\n");
// Write vertices
amf_content.push_str(" <vertices>\n");
for (i, vertex) in vertices.iter().enumerate() {
amf_content.push_str(&format!(" <vertex id=\"{i}\">\n"));
amf_content.push_str(" <coordinates>\n");
amf_content.push_str(&format!(" <x>{:.6}</x>\n", vertex.x));
amf_content.push_str(&format!(" <y>{:.6}</y>\n", vertex.y));
amf_content.push_str(&format!(" <z>{:.6}</z>\n", vertex.z));
amf_content.push_str(" </coordinates>\n");
amf_content.push_str(" </vertex>\n");
}
amf_content.push_str(" </vertices>\n");
// Write triangles (volume definition)
amf_content.push_str(" <volume>\n");
for (i, triangle) in triangles.iter().enumerate() {
amf_content.push_str(&format!(" <triangle id=\"{i}\">\n"));
amf_content.push_str(&format!(" <v1>{}</v1>\n", triangle[0]));
amf_content.push_str(&format!(" <v2>{}</v2>\n", triangle[1]));
amf_content.push_str(&format!(" <v3>{}</v3>\n", triangle[2]));
amf_content.push_str(" </triangle>\n");
}
amf_content.push_str(" </volume>\n");
// Close mesh and object
amf_content.push_str(" </mesh>\n");
amf_content.push_str(" </object>\n");
// Close AMF
amf_content.push_str("</amf>\n");
amf_content
}
/// Export this Mesh to AMF format with color information
///
/// Creates an AMF file with color/material information for enhanced 3D printing.
///
/// # Arguments
/// * `object_name` - Name for the object in the AMF file
/// * `units` - Units for the geometry (e.g., "millimeter", "inch")
/// * `color` - RGB color as (red, green, blue) where each component is 0.0-1.0
///
/// # Example
/// ```
/// use csgrs::mesh::Mesh;
/// let csg: Mesh<()> = Mesh::cube(10.0, None);
/// let amf_content = csg.to_amf_with_color("red_cube", "millimeter", (1.0, 0.0, 0.0));
/// println!("{}", amf_content);
/// ```
pub fn to_amf_with_color(
&self,
object_name: &str,
units: &str,
color: (Real, Real, Real),
) -> String {
let mut amf_content = String::new();
// AMF XML header
amf_content.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
amf_content.push_str("<amf unit=\"");
amf_content.push_str(units);
amf_content.push_str("\" version=\"1.1\">\n");
// Metadata
amf_content.push_str(" <metadata type=\"producer\">csgrs library</metadata>\n");
amf_content
.push_str(" <metadata type=\"cad\">Constructive Solid Geometry</metadata>\n");
amf_content.push_str(&format!(
" <metadata type=\"description\">{object_name}</metadata>\n"
));
// Material definition with color
amf_content.push_str(" <material id=\"material1\">\n");
amf_content.push_str(" <metadata type=\"name\">Default Material</metadata>\n");
amf_content.push_str(" <color>\n");
amf_content.push_str(&format!(" <r>{:.3}</r>\n", color.0));
amf_content.push_str(&format!(" <g>{:.3}</g>\n", color.1));
amf_content.push_str(&format!(" <b>{:.3}</b>\n", color.2));
amf_content.push_str(" <a>1.0</a>\n"); // Alpha (opacity)
amf_content.push_str(" </color>\n");
amf_content.push_str(" </material>\n");
let mut vertices = Vec::new();
let mut triangles = Vec::new();
// Process 2D geometry
for geom in &self.geometry.0 {
match geom {
geo::Geometry::Polygon(poly2d) => {
self.add_2d_polygon_to_amf(poly2d, &mut vertices, &mut triangles);
},
geo::Geometry::MultiPolygon(mp) => {
for poly2d in &mp.0 {
self.add_2d_polygon_to_amf(poly2d, &mut vertices, &mut triangles);
}
},
_ => {},
}
}
// Start object definition
amf_content.push_str(&format!(" <object id=\"{object_name}\">\n"));
amf_content.push_str(" <mesh>\n");
// Write vertices
amf_content.push_str(" <vertices>\n");
for (i, vertex) in vertices.iter().enumerate() {
amf_content.push_str(&format!(" <vertex id=\"{i}\">\n"));
amf_content.push_str(" <coordinates>\n");
amf_content.push_str(&format!(" <x>{:.6}</x>\n", vertex.x));
amf_content.push_str(&format!(" <y>{:.6}</y>\n", vertex.y));
amf_content.push_str(&format!(" <z>{:.6}</z>\n", vertex.z));
amf_content.push_str(" </coordinates>\n");
amf_content.push_str(" </vertex>\n");
}
amf_content.push_str(" </vertices>\n");
// Write triangles with material reference
amf_content.push_str(" <volume materialid=\"material1\">\n");
for (i, triangle) in triangles.iter().enumerate() {
amf_content.push_str(&format!(" <triangle id=\"{i}\">\n"));
amf_content.push_str(&format!(" <v1>{}</v1>\n", triangle[0]));
amf_content.push_str(&format!(" <v2>{}</v2>\n", triangle[1]));
amf_content.push_str(&format!(" <v3>{}</v3>\n", triangle[2]));
amf_content.push_str(" </triangle>\n");
}
amf_content.push_str(" </volume>\n");
// Close mesh and object
amf_content.push_str(" </mesh>\n");
amf_content.push_str(" </object>\n");
// Close AMF
amf_content.push_str("</amf>\n");
amf_content
}
// Helper function to add 2D polygon to AMF data
fn add_2d_polygon_to_amf(
&self,
poly2d: &geo::Polygon<Real>,
vertices: &mut Vec<Point3<Real>>,
triangles: &mut Vec<Vec<usize>>,
) {
// Get the exterior ring
let exterior: Vec<[Real; 2]> =
poly2d.exterior().coords_iter().map(|c| [c.x, c.y]).collect();
// Get holes
let holes_vec: Vec<Vec<[Real; 2]>> = poly2d
.interiors()
.iter()
.map(|ring| ring.coords_iter().map(|c| [c.x, c.y]).collect())
.collect();
let hole_refs: Vec<&[[Real; 2]]> = holes_vec.iter().map(|h| &h[..]).collect();
// Tessellate the 2D polygon
let triangles_2d = Self::triangulate_2d(&exterior, &hole_refs);
for triangle in triangles_2d {
let mut triangle_indices = Vec::new();
for point in triangle {
let vertex_3d = Point3::new(point.x, point.y, point.z);
let vertex_idx = add_unique_vertex_amf(vertices, vertex_3d);
triangle_indices.push(vertex_idx);
}
if triangle_indices.len() == 3 {
triangles.push(triangle_indices);
}
}
}
/// Export this Mesh to an AMF file
///
/// # Arguments
/// * `writer` - Where to write the AMF data
/// * `object_name` - Name for the object in the AMF file
/// * `units` - Units for the geometry (e.g., "millimeter", "inch")
///
/// # Example
/// ```
/// use csgrs::mesh::Mesh;
/// use std::fs::File;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let csg: Mesh<()> = Mesh::cube(10.0, None);
/// let mut file = File::create("stl/output.amf")?;
/// csg.write_amf(&mut file, "my_cube", "millimeter")?;
/// # Ok(())
/// # }
/// ```
pub fn write_amf<W: Write>(
&self,
writer: &mut W,
object_name: &str,
units: &str,
) -> std::io::Result<()> {
let amf_content = self.to_amf(object_name, units);
writer.write_all(amf_content.as_bytes())
}
}
// Helper function to add unique vertex and return its index for AMF
fn add_unique_vertex_amf(vertices: &mut Vec<Point3<Real>>, vertex: Point3<Real>) -> usize {
const EPSILON: Real = 1e-6;
// Check if vertex already exists (within tolerance)
for (i, existing) in vertices.iter().enumerate() {
if (existing.coords - vertex.coords).norm() < EPSILON {
return i;
}
}
// Add new vertex
vertices.push(vertex);
vertices.len() - 1
}