Compare commits

..

4 Commits

Author SHA1 Message Date
dependabot[bot]
5af73ed39a Merge 3400093fcd into f57e6c3f4e 2024-09-02 14:31:37 +05:30
f57e6c3f4e feat: testing 2024-07-22 13:33:06 +02:00
8c353107d8 feat: test stuff 2024-07-21 22:32:15 +02:00
0e8479af91 feat: testing some stuff 2024-07-17 01:08:23 +02:00
20 changed files with 1263 additions and 416 deletions

177
; Normal file
View File

@@ -0,0 +1,177 @@
use super::{
axis::Axis,
base_slices::BaseSlice,
line::Line3,
slice_path::{SlicePath, SurfacePathIterator},
triangle::Triangle,
FloatValue,
};
use bvh::{
aabb::Aabb,
bvh::{Bvh, BvhNode},
};
#[derive(Debug)]
pub struct Mesh {
pub aabb: Aabb<FloatValue, 3>,
pub bvh: Bvh<FloatValue, 3>,
pub triangles: Vec<Triangle>,
}
impl From<Vec<Triangle>> for Mesh {
fn from(mut triangles: Vec<Triangle>) -> Self {
Self {
aabb: triangles
.get(0)
.map(|triangle| {
let mut aabb = triangle.aabb;
for triangle in triangles.iter().skip(1) {
aabb.join_mut(&triangle.aabb);
}
aabb
})
.unwrap_or_else(|| Aabb::empty()),
bvh: Bvh::build(&mut triangles),
triangles,
}
}
}
impl Mesh {
pub fn slice_paths<'a>(
self: &'a Mesh,
axis: Axis,
slice_height: FloatValue,
) -> impl Iterator<Item = Vec<SlicePath>> + 'a {
self.slice_base_slices(axis, slice_height)
.map(|slice| slice.find_paths())
.filter(|paths| !paths.is_empty())
}
pub fn slice_surface(&self, axis: Axis, nozzle_width: FloatValue) -> SurfacePathIterator {
SurfacePathIterator::new(self, axis, nozzle_width)
}
pub fn slice_base_slices<'a>(
self: &'a Mesh,
axis: Axis,
slice_height: FloatValue,
) -> impl Iterator<Item = BaseSlice> + 'a {
let layer_count = ((self.aabb.max[axis as usize] - self.aabb.min[axis as usize])
/ slice_height)
.floor() as usize;
(0..layer_count).map(move |i| {
let layer = i as FloatValue * slice_height + self.aabb.min[axis as usize];
let mut base_slice = BaseSlice {
i,
d: layer,
axis,
lines: vec![],
};
let mut stack = Vec::<usize>::with_capacity(self.bvh.nodes.len());
stack.push(0);
while let Some(i) = stack.pop() {
match self.bvh.nodes[i] {
BvhNode::Node {
parent_index: _,
child_l_index,
child_l_aabb,
child_r_index,
child_r_aabb,
} => {
assert!(child_l_aabb.min[axis as usize] <= child_l_aabb.max[axis as usize]);
assert!(child_r_aabb.min[axis as usize] <= child_r_aabb.max[axis as usize]);
if layer >= child_l_aabb.min[axis as usize]
&& layer <= child_l_aabb.max[axis as usize]
{
stack.push(child_l_index);
}
if layer >= child_r_aabb.min[axis as usize]
&& layer <= child_r_aabb.max[axis as usize]
{
stack.push(child_r_index);
}
}
BvhNode::Leaf {
parent_index: _,
shape_index,
} => {
for line in self.triangles[shape_index].intersect(layer, axis as usize) {
base_slice.lines.push(line);
}
}
}
}
base_slice
})
}
pub fn outline_base_slice(&self, axis: Axis) -> BaseSlice {
let mut base_slice = BaseSlice {
i: 0,
d: 0.0,
axis,
lines: vec![],
};
'triangle: for (i, triangle) in self.triangles.iter().enumerate() {
let mut stack = Vec::<usize>::with_capacity(self.bvh.nodes.len());
stack.push(0);
let mut ab = false;
let mut ac = false;
let mut bc = false;
while let Some(i) = stack.pop() {
match self.bvh.nodes[i] {
BvhNode::Node {
parent_index: _,
child_l_index,
child_l_aabb,
child_r_index,
child_r_aabb,
} => {
let coords = [triangle.a, triangle.b, triangle.c];
macro_rules! match_aabb {
($side:expr) => {
coords
.iter()
.map(|point| {
$side.approx_contains_eps(point, FloatValue::EPSILON) as i32
})
.sum::<i32>()
>= 2
};
}
if match_aabb!(child_l_aabb) {
stack.push(child_l_index);
}
if match_aabb!(child_r_aabb) {
stack.push(child_r_index);
}
}
BvhNode::Leaf {
parent_index: _,
shape_index,
} => {
if i == shape_index {
continue;
}
let other = &self.triangles[shape_index];
let a = triangle.has_point(other.a);
let b = triangle.has_point(other.b);
let c = triangle.has_point(other.c);
ab = ab || (a && b);
ac = ac || (a && c);
bc = bc || (b && c);
if ab && ac && bc {
continue 'triangle;
}
}
}
}
}
base_slice
}
}

View File

@@ -1,56 +1,29 @@
#![feature(extract_if)]
use std::collections::VecDeque;
use approx::relative_eq;
use nalgebra::{vector, Vector3};
use serde::{Deserialize, Serialize};
use tsify::Tsify;
use nalgebra::{point, vector, Vector3};
use num::Float;
use result::{Slice, SliceOptions, SliceResult};
use slicer::{axis::Axis, slice_path::SlicePath, trace_surface::trace_surface};
use wasm_bindgen::prelude::wasm_bindgen;
use crate::slicer::{
base_slices::create_slices, mesh::Mesh, split_surface::split_surface,
trace_surface::trace_surface, triangle::Triangle, FloatValue, SlicerOptions,
};
use crate::slicer::{mesh::Mesh, split_surface::split_surface, triangle::Triangle, FloatValue};
mod result;
mod slicer;
mod util;
const BED_NORMAL: Vector3<f64> = vector![0f64, 0f64, 1f64];
#[derive(Tsify, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[tsify(from_wasm_abi)]
pub struct SliceOptions {
#[tsify(type = "Float32Array")]
positions: Vec<f32>,
layer_height: f64,
max_angle: f64,
}
#[derive(Tsify, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "type")]
#[tsify(into_wasm_abi)]
pub enum Slice {
Surface {
#[tsify(type = "Float32Array")]
position: Vec<f32>,
},
Ring {
#[tsify(type = "Float32Array")]
position: Vec<f32>,
},
}
#[derive(Tsify, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[tsify(into_wasm_abi)]
pub struct SliceResult {
slices: Vec<Slice>,
}
#[wasm_bindgen]
pub fn slice(
SliceOptions {
positions,
layer_height,
max_angle,
min_surface_path_length,
nozzle_diameter,
}: SliceOptions,
) -> SliceResult {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
@@ -61,17 +34,17 @@ pub fn slice(
let mut slicable_triangles = Vec::<Triangle>::with_capacity(positions.len() / 9);
for i in (0..positions.len()).step_by(9) {
let triangle = Triangle::new(
vector![
point![
positions[i] as FloatValue,
positions[i + 1] as FloatValue,
positions[i + 2] as FloatValue
],
vector![
point![
positions[i + 3] as FloatValue,
positions[i + 4] as FloatValue,
positions[i + 5] as FloatValue
],
vector![
point![
positions[i + 6] as FloatValue,
positions[i + 7] as FloatValue,
positions[i + 8] as FloatValue
@@ -79,71 +52,149 @@ pub fn slice(
);
slicable_triangles.push(triangle);
let angle = triangle.normal.angle(&BED_NORMAL);
let opposite_angle = std::f64::consts::PI - angle;
if angle <= max_angle
|| relative_eq!(angle, max_angle)
|| opposite_angle <= max_angle
|| relative_eq!(opposite_angle, max_angle)
{
let mut normal = triangle.normal.clone();
normal.z = normal.z.abs();
let angle = normal.angle(&BED_NORMAL);
if angle <= max_angle || relative_eq!(angle, max_angle) {
surface_triangles.push(triangle);
}
}
slicable_triangles.shrink_to_fit();
surface_triangles.shrink_to_fit();
let slicer_options = SlicerOptions { layer_height };
console_log!("Creating Surfaces");
let surfaces = split_surface(surface_triangles);
let min_surface_area = std::f64::consts::PI * (nozzle_diameter / 2.0).powi(2);
let mut surfaces = split_surface(surface_triangles)
.into_iter()
.filter(|mesh| {
let mut surface_area = 0.0;
for triangle in &mesh.triangles {
surface_area += triangle.area();
if surface_area >= min_surface_area {
return true;
}
}
return false;
})
.map(|mesh| {
let outline = mesh
.outline_base_slice(Axis::Z)
.find_paths()
.into_iter()
.filter(|path| path.closed)
.collect::<Vec<_>>();
let surface = mesh
.slice_surface(Axis::X, nozzle_diameter)
.filter(|path| {
let mut length = 0.0;
for pair in path.path.windows(2) {
length += (pair[0].coords - pair[1].coords).norm();
if length >= min_surface_path_length {
return true;
}
}
return false;
})
.collect::<Vec<_>>();
(mesh, outline, surface)
})
.collect::<Vec<_>>();
surfaces
.sort_unstable_by(|(a, _, _), (b, _, _)| a.aabb.min.z.partial_cmp(&b.aabb.min.z).unwrap());
console_log!("Computing BVH");
let slicable = Mesh::from(slicable_triangles);
console_log!("Creating Slices");
let mut slices = create_slices(&slicer_options, &slicable);
console_log!("Creating Walls");
let wallMesh = Mesh::from(slicable_triangles);
let mut walls = wallMesh
.slice_paths(Axis::Z, layer_height)
.flat_map(|paths| paths.into_iter().filter(|path| path.closed))
.collect::<VecDeque<_>>();
let mut active_surfaces = Vec::new();
let mut out = Vec::new();
/*console_log!("Tracing Surfaces");
let a = max_angle.tan();
for slice in &mut slices {
for surface in &surfaces {
if surface.aabb.min.z <= slice.z && surface.aabb.max.z > slice.z {
trace_surface(slice, surface, a);
console_log!("Resolving dependencies");
while let Some(mut wall) = walls.pop_front() {
active_surfaces.extend(
surfaces
.extract_if(|surface| surface.0.aabb.min.z <= wall.aabb.max.z)
.map(|surface| (surface, Vec::new())),
);
let deactivate =
active_surfaces.extract_if(|element| element.0 .0.aabb.max.z < wall.aabb.min.z);
for (surface, surface_walls) in deactivate {
for ring in surface.1 {
out.push(ring.points);
}
for path in surface.2 {
out.push(path.path);
}
for wall in surface_walls {
walls.push_front(wall);
}
}
}*/
for surface in active_surfaces.iter_mut() {
let held = wall
.points
.extract_if(|point| !trace_surface(&point, &surface.0 .0, max_angle))
.collect::<Vec<_>>();
if !held.is_empty() {
surface.1.push(SlicePath {
points: held,
..wall
});
}
}
if !wall.points.is_empty() {
out.push(wall.points);
}
}
console_log!("Done");
SliceResult {
slices: slices
slices: out
.into_iter()
.map(|slice| Slice::Ring {
position: slice
.points
.into_iter()
.flat_map(|point| [point.x as f32, point.y as f32, point.z as f32])
.collect(),
})
.chain(surfaces.into_iter().map(|surface| {
Slice::Surface {
position: surface
.triangles
.collect(),
}
/*SliceResult {
slices: surfaces
.into_iter()
.flat_map(|(_, outlines, slices)| {
outlines
.into_iter()
.map(|slice| Slice::Ring {
position: slice
.points
.into_iter()
.flat_map(|point| [point.x as f32, point.y as f32, point.z as f32])
.collect(),
})
.chain(slices.into_iter().map(|slice| {
Slice::Ring {
position: slice
.path
.into_iter()
.flat_map(|point| [point.x as f32, point.y as f32, point.z as f32])
.collect(),
}
}))
})
.chain(walls.flatten().map(|slice| {
Slice::Ring {
position: slice
.points
.into_iter()
.flat_map(|triangle| {
[
triangle.a.x as f32,
triangle.a.y as f32,
triangle.a.z as f32,
triangle.b.x as f32,
triangle.b.y as f32,
triangle.b.z as f32,
triangle.c.x as f32,
triangle.c.y as f32,
triangle.c.z as f32,
]
})
.flat_map(|point| [point.x as f32, point.y as f32, point.z as f32])
.collect(),
}
}))
.collect(),
}
}*/
}

39
bampy/src/result.rs Normal file
View File

@@ -0,0 +1,39 @@
use serde::{Deserialize, Serialize};
use tsify::Tsify;
#[derive(Tsify, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[tsify(from_wasm_abi)]
pub struct SliceOptions {
#[tsify(type = "Float32Array")]
pub positions: Vec<f32>,
pub layer_height: f64,
pub nozzle_diameter: f64,
pub max_angle: f64,
pub min_surface_path_length: f64,
}
#[derive(Tsify, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "type")]
#[tsify(into_wasm_abi)]
pub enum Slice {
Surface {
#[tsify(type = "Float32Array")]
position: Vec<f32>,
},
Ring {
#[tsify(type = "Float32Array")]
position: Vec<f32>,
},
Path {
#[tsify(type = "Float32Array")]
position: Vec<f32>,
},
}
#[derive(Tsify, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[tsify(into_wasm_abi)]
pub struct SliceResult {
pub slices: Vec<Slice>,
}

30
bampy/src/slicer/axis.rs Normal file
View File

@@ -0,0 +1,30 @@
use nalgebra::Vector3;
use super::FloatValue;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[repr(usize)]
pub enum Axis {
#[default]
X = 0,
Y = 1,
Z = 2,
}
impl Axis {
pub fn other(&self) -> (Self, Self) {
match self {
Axis::X => (Axis::Y, Axis::Z),
Axis::Y => (Axis::X, Axis::Z),
Axis::Z => (Axis::X, Axis::Y),
}
}
pub fn normal(&self) -> Vector3<FloatValue> {
match self {
Axis::X => Vector3::x(),
Axis::Y => Vector3::y(),
Axis::Z => Vector3::z(),
}
}
}

View File

@@ -1,66 +1,82 @@
use super::{
line::Line3,
mesh::Mesh,
slice_rings::{find_slice_rings, SliceRing},
FloatValue, SlicerOptions,
};
use bvh::bvh::BvhNode;
use super::{aabb_from_points, axis::Axis, line::Line3, slice_path::SlicePath, FloatValue};
use approx::relative_eq;
use nalgebra::Point3;
#[derive(Debug)]
pub struct BaseSlice {
pub z: FloatValue,
pub i: usize,
pub d: FloatValue,
pub axis: Axis,
pub lines: Vec<Line3>,
}
/// Creates base slices from the geometry, excluding surfaces.
/// The slicse are not sorted or separated into rings.
pub fn create_slices(options: &SlicerOptions, slicable: &Mesh) -> Vec<SliceRing> {
let layer_count = (slicable.aabb.max.z / options.layer_height).floor() as usize;
let mut rings = vec![];
let mut layer_index = 0;
for i in 0..layer_count {
let layer = i as FloatValue * options.layer_height;
let mut base_slice = BaseSlice {
z: layer,
lines: vec![],
};
let mut stack = Vec::<usize>::with_capacity(slicable.bvh.nodes.len());
stack.push(0);
while let Some(i) = stack.pop() {
match slicable.bvh.nodes[i] {
BvhNode::Node {
parent_index: _,
child_l_index,
child_l_aabb,
child_r_index,
child_r_aabb,
} => {
assert!(child_l_aabb.min.z <= child_l_aabb.max.z);
assert!(child_r_aabb.min.z <= child_r_aabb.max.z);
if layer >= child_l_aabb.min.z && layer <= child_l_aabb.max.z {
stack.push(child_l_index);
}
if layer >= child_r_aabb.min.z && layer <= child_r_aabb.max.z {
stack.push(child_r_index);
}
}
BvhNode::Leaf {
parent_index: _,
shape_index,
} => {
slicable.triangles[shape_index]
.intersect_z(layer)
.map(|line| {
base_slice.lines.push(line);
});
}
impl BaseSlice {
pub fn find_paths(mut self) -> Vec<SlicePath> {
let (axis_a, axis_b) = self.axis.other();
let mut rings = vec![];
while let Some(line) = self.lines.pop() {
if relative_eq!(line.start, line.end) {
continue;
}
let mut right = vec![line.end];
let mut left = vec![line.start];
let mut previous_len = usize::MAX;
let mut closed = false;
while !closed {
if previous_len == self.lines.len() {
break;
}
previous_len = self.lines.len();
self.lines.retain_mut(|line| {
if closed {
return true;
}
let test = |side: &mut Vec<Point3<FloatValue>>| {
let last = side.last().unwrap();
let s = relative_eq!(line.start, last);
let e = relative_eq!(line.end, last);
if s && !e {
side.push(line.end);
} else if !s && e {
side.push(line.start);
}
s || e
};
if test(&mut left) || test(&mut right) {
closed = relative_eq!(left.last().unwrap(), right.last().unwrap());
false
} else {
true
}
})
}
left.reverse();
left.extend(right);
let mut ring = SlicePath {
d: self.d,
i: self.i,
axis: self.axis,
closed,
aabb: aabb_from_points(left.iter()),
points: left,
};
if ring.points.windows(2).fold(0.0, |acc, curr| {
acc + (curr[1][axis_a as usize] - curr[0][axis_a as usize])
* (curr[1][axis_b as usize] + curr[0][axis_b as usize])
}) < 0.0
{
ring.points.reverse();
}
rings.push(ring);
}
rings.append(&mut find_slice_rings(base_slice, &mut layer_index));
rings
}
rings
}

View File

@@ -1,4 +1,4 @@
use nalgebra::Vector3;
use nalgebra::{Point3, Vector3};
use super::FloatValue;
@@ -8,6 +8,20 @@ use super::FloatValue;
/// meaning the inside is on the right hand side of the line.
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct Line3 {
pub start: Vector3<FloatValue>,
pub end: Vector3<FloatValue>,
pub start: Point3<FloatValue>,
pub end: Point3<FloatValue>,
}
impl Line3 {
pub fn new(start: Point3<FloatValue>, end: Point3<FloatValue>) -> Self {
Self { start, end }
}
pub fn norm(&self) -> FloatValue {
(self.end - self.start).norm()
}
pub fn normal(&self) -> Vector3<FloatValue> {
(self.end - self.start).normalize()
}
}

View File

@@ -1,5 +1,15 @@
use super::{triangle::Triangle, FloatValue};
use bvh::{aabb::Aabb, bvh::Bvh};
use super::{
axis::Axis,
base_slices::BaseSlice,
line::Line3,
slice_path::{SlicePath, SurfacePathIterator},
triangle::Triangle,
FloatValue,
};
use bvh::{
aabb::Aabb,
bvh::{Bvh, BvhNode},
};
#[derive(Debug)]
pub struct Mesh {
@@ -26,3 +36,151 @@ impl From<Vec<Triangle>> for Mesh {
}
}
}
impl Mesh {
pub fn slice_paths<'a>(
self: &'a Mesh,
axis: Axis,
slice_height: FloatValue,
) -> impl Iterator<Item = Vec<SlicePath>> + 'a {
self.slice_base_slices(axis, slice_height)
.map(|slice| slice.find_paths())
.filter(|paths| !paths.is_empty())
}
pub fn slice_surface(&self, axis: Axis, nozzle_width: FloatValue) -> SurfacePathIterator {
SurfacePathIterator::new(self, axis, nozzle_width)
}
pub fn slice_base_slices<'a>(
self: &'a Mesh,
axis: Axis,
slice_height: FloatValue,
) -> impl Iterator<Item = BaseSlice> + 'a {
let layer_count = ((self.aabb.max[axis as usize] - self.aabb.min[axis as usize])
/ slice_height)
.floor() as usize;
(0..=layer_count).map(move |i| {
let layer = i as FloatValue * slice_height + self.aabb.min[axis as usize];
let mut base_slice = BaseSlice {
i,
d: layer,
axis,
lines: vec![],
};
let mut stack = Vec::<usize>::with_capacity(self.bvh.nodes.len());
stack.push(0);
while let Some(i) = stack.pop() {
match self.bvh.nodes[i] {
BvhNode::Node {
parent_index: _,
child_l_index,
child_l_aabb,
child_r_index,
child_r_aabb,
} => {
assert!(child_l_aabb.min[axis as usize] <= child_l_aabb.max[axis as usize]);
assert!(child_r_aabb.min[axis as usize] <= child_r_aabb.max[axis as usize]);
if layer >= child_l_aabb.min[axis as usize]
&& layer <= child_l_aabb.max[axis as usize]
{
stack.push(child_l_index);
}
if layer >= child_r_aabb.min[axis as usize]
&& layer <= child_r_aabb.max[axis as usize]
{
stack.push(child_r_index);
}
}
BvhNode::Leaf {
parent_index: _,
shape_index,
} => {
for line in self.triangles[shape_index].intersect(layer, axis as usize) {
base_slice.lines.push(line);
}
}
}
}
base_slice
})
}
pub fn outline_base_slice(&self, axis: Axis) -> BaseSlice {
let mut base_slice = BaseSlice {
i: 0,
d: 0.0,
axis,
lines: vec![],
};
'triangle: for (triangle_index, triangle) in self.triangles.iter().enumerate() {
let mut stack = Vec::<usize>::with_capacity(self.bvh.nodes.len());
stack.push(0);
let mut ab = false;
let mut ac = false;
let mut bc = false;
while let Some(i) = stack.pop() {
match self.bvh.nodes[i] {
BvhNode::Node {
parent_index: _,
child_l_index,
child_l_aabb,
child_r_index,
child_r_aabb,
} => {
let coords = [triangle.a, triangle.b, triangle.c];
macro_rules! match_aabb {
($side:expr) => {
coords
.iter()
.map(|point| {
$side.approx_contains_eps(point, FloatValue::EPSILON) as i32
})
.sum::<i32>()
>= 2
};
}
if match_aabb!(child_l_aabb) {
stack.push(child_l_index);
}
if match_aabb!(child_r_aabb) {
stack.push(child_r_index);
}
}
BvhNode::Leaf {
parent_index: _,
shape_index,
} => {
if triangle_index == shape_index {
continue;
}
let other = &self.triangles[shape_index];
let a = other.has_point(triangle.a);
let b = other.has_point(triangle.b);
let c = other.has_point(triangle.c);
ab = ab || (a && b);
ac = ac || (a && c);
bc = bc || (b && c);
if ab && ac && bc {
continue 'triangle;
}
}
}
}
if !ab {
base_slice.lines.push(Line3::new(triangle.a, triangle.b));
}
if !ac {
base_slice.lines.push(Line3::new(triangle.a, triangle.c));
}
if !bc {
base_slice.lines.push(Line3::new(triangle.b, triangle.c));
}
}
base_slice
}
}

View File

@@ -1,9 +1,13 @@
use std::fmt::Debug;
use bvh::aabb::{Aabb, Bounded};
use bvh::bounding_hierarchy::BHValue;
use nalgebra::Point;
pub mod axis;
pub mod base_slices;
pub mod line;
pub mod mesh;
pub mod slice_rings;
pub mod sdf;
pub mod slice_path;
pub mod split_surface;
pub mod trace_surface;
pub mod triangle;
@@ -11,7 +15,17 @@ pub mod z_projection;
pub type FloatValue = f64;
#[derive(Debug)]
pub struct SlicerOptions {
pub layer_height: FloatValue,
pub fn aabb_from_points<'a, I, T: BHValue, const D: usize>(mut points: I) -> Aabb<T, D>
where
I: Iterator<Item = &'a Point<T, D>>,
{
if let Some(point) = points.next() {
let mut aabb = point.aabb();
for point in points {
aabb.grow_mut(point);
}
aabb
} else {
Aabb::empty()
}
}

253
bampy/src/slicer/sdf.rs Normal file
View File

@@ -0,0 +1,253 @@
/// https://iquilezles.org/articles/distfunctions/
use nalgebra::{vector, Point, TAffine, Transform, Vector2, Vector3};
use super::FloatValue;
pub trait Sdf<const D: usize> {
fn sdf(&self, p: &Point<FloatValue, D>) -> FloatValue;
}
#[derive(Debug, Clone, Copy)]
pub struct SdfSphere {
radius: FloatValue,
}
impl SdfSphere {
pub fn new(radius: FloatValue) -> Self {
Self { radius }
}
}
impl Sdf<3> for SdfSphere {
fn sdf(&self, p: &Point<FloatValue, 3>) -> FloatValue {
p.coords.norm() - self.radius
}
}
#[derive(Debug, Clone, Copy)]
pub struct SdfBox {
size: Point<FloatValue, 3>,
}
impl SdfBox {
pub fn new(size: Point<FloatValue, 3>) -> Self {
Self { size }
}
}
impl Sdf<3> for SdfBox {
fn sdf(&self, p: &Point<FloatValue, 3>) -> FloatValue {
let q = p.coords.abs() - self.size.coords;
q.sup(&Vector3::zeros()).add_scalar(q.max().min(0.0)).norm()
}
}
#[derive(Debug, Clone, Copy)]
pub struct SdfInfiniteCone {
angle: Vector2<FloatValue>,
}
impl SdfInfiniteCone {
pub fn new(angle: FloatValue) -> Self {
Self {
angle: vector![angle.sin(), angle.cos()],
}
}
}
impl Sdf<3> for SdfInfiniteCone {
fn sdf(&self, p: &Point<FloatValue, 3>) -> FloatValue {
let q = vector![p.coords.xy().norm(), p.z];
let d = (q - self.angle.scale(q.dot(&self.angle).max(0.0))).norm();
if q.x * self.angle.y - q.y * self.angle.x > 0.0 {
d
} else {
-d
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct SdfTransform<T: Sdf<3>> {
sdf: T,
transform: Transform<FloatValue, TAffine, 3>,
}
impl<T: Sdf<3>> SdfTransform<T> {
fn new(sdf: T, transform: Transform<FloatValue, TAffine, 3>) -> Self {
Self { sdf, transform }
}
}
impl<T: Sdf<3>> Sdf<3> for SdfTransform<T> {
fn sdf(&self, p: &Point<FloatValue, 3>) -> FloatValue {
self.sdf.sdf(&self.transform.inverse_transform_point(p))
}
}
#[derive(Debug, Clone, Copy)]
pub struct SdfScale<const D: usize, T: Sdf<D>> {
sdf: T,
scale: FloatValue,
}
impl<const D: usize, T: Sdf<D>> SdfScale<D, T> {
fn new(sdf: T, scale: FloatValue) -> Self {
Self { sdf, scale }
}
}
impl<const D: usize, T: Sdf<D>> Sdf<D> for SdfScale<D, T> {
fn sdf(&self, p: &Point<FloatValue, D>) -> FloatValue {
self.sdf.sdf(&(p / self.scale)) * self.scale
}
}
#[derive(Debug, Clone, Copy)]
pub struct SdfOnion<T: Sdf<3>> {
sdf: T,
thickness: FloatValue,
}
impl<T: Sdf<3>> SdfOnion<T> {
fn new(sdf: T, thickness: FloatValue) -> Self {
Self { sdf, thickness }
}
}
impl<T: Sdf<3>> Sdf<3> for SdfOnion<T> {
fn sdf(&self, p: &Point<FloatValue, 3>) -> FloatValue {
self.sdf.sdf(p).abs() - self.thickness
}
}
#[derive(Debug, Clone, Copy)]
pub struct SdfUnion<const D: usize, T: Sdf<D>, U: Sdf<D>> {
sdf_a: T,
sdf_b: U,
}
impl<const D: usize, T: Sdf<D>, U: Sdf<D>> SdfUnion<D, T, U> {
fn new(sdf_a: T, sdf_b: U) -> Self {
Self { sdf_a, sdf_b }
}
}
impl<const D: usize, T: Sdf<D>, U: Sdf<D>> Sdf<D> for SdfUnion<D, T, U> {
fn sdf(&self, p: &Point<FloatValue, D>) -> FloatValue {
self.sdf_a.sdf(p).min(self.sdf_b.sdf(p))
}
}
#[derive(Debug, Clone, Copy)]
pub struct SdfIntersection<const D: usize, T: Sdf<D>, U: Sdf<D>> {
sdf_a: T,
sdf_b: U,
}
impl<const D: usize, T: Sdf<D>, U: Sdf<D>> SdfIntersection<D, T, U> {
fn new(sdf_a: T, sdf_b: U) -> Self {
Self { sdf_a, sdf_b }
}
}
impl<const D: usize, T: Sdf<D>, U: Sdf<D>> Sdf<D> for SdfIntersection<D, T, U> {
fn sdf(&self, p: &Point<FloatValue, D>) -> FloatValue {
self.sdf_a.sdf(p).max(self.sdf_b.sdf(p))
}
}
#[derive(Debug, Clone, Copy)]
pub struct SdfDifference<const D: usize, T: Sdf<D>, U: Sdf<D>> {
sdf_a: T,
sdf_b: U,
}
impl<const D: usize, T: Sdf<D>, U: Sdf<D>> SdfDifference<D, T, U> {
fn new(sdf_a: T, sdf_b: U) -> Self {
Self { sdf_a, sdf_b }
}
}
impl<const D: usize, T: Sdf<D>, U: Sdf<D>> Sdf<D> for SdfDifference<D, T, U> {
fn sdf(&self, p: &Point<FloatValue, D>) -> FloatValue {
self.sdf_a.sdf(p).max(-self.sdf_b.sdf(p))
}
}
pub trait SdfOperators<const D: usize>: Sdf<D> {
fn union(self, other: Self) -> SdfUnion<D, Self, Self>
where
Self: Sized,
{
SdfUnion::new(self, other)
}
fn intersection(self, other: Self) -> SdfIntersection<D, Self, Self>
where
Self: Sized,
{
SdfIntersection::new(self, other)
}
fn difference(self, other: Self) -> SdfDifference<D, Self, Self>
where
Self: Sized,
{
SdfDifference::new(self, other)
}
}
impl<const D: usize, T: Sdf<D>> SdfOperators<D> for T {}
pub trait Sdf3dModifiers: Sdf<3> {
/// exact
fn transform(self, transform: Transform<FloatValue, TAffine, 3>) -> SdfTransform<Self>
where
Self: Sized,
{
SdfTransform::new(self, transform)
}
/// exact
fn translate(self, translation: Point<FloatValue, 3>) -> SdfTransform<Self>
where
Self: Sized,
{
self.transform(Transform::from_matrix_unchecked(
nalgebra::Matrix4::new_translation(&translation.coords),
))
}
/// exact
fn rotate(self, rotation: nalgebra::UnitQuaternion<FloatValue>) -> SdfTransform<Self>
where
Self: Sized,
{
self.transform(Transform::from_matrix_unchecked(rotation.to_homogeneous()))
}
/// exact
fn scale(self, scale: FloatValue) -> SdfScale<3, Self>
where
Self: Sized,
{
SdfScale::new(self, scale)
}
/// exact
///
/// For carving interiors or giving thickness to primitives,
/// without performing expensive boolean operations
/// and without distorting the distance field into a bound,
/// one can use "onioning".
/// You can use it multiple times to create concentric layers in your SDF.
fn onion(self, thickness: FloatValue) -> SdfOnion<Self>
where
Self: Sized,
{
SdfOnion::new(self, thickness)
}
}
impl<T: Sdf<3>> Sdf3dModifiers for T {}

View File

@@ -0,0 +1,183 @@
use std::{collections::VecDeque, ops::RangeInclusive};
use approx::relative_eq;
use bvh::aabb::Aabb;
use nalgebra::Point3;
use super::{axis::Axis, mesh::Mesh, FloatValue};
#[derive(Debug, Default)]
pub struct SlicePath {
pub i: usize,
pub d: FloatValue,
pub axis: Axis,
/// The points of the ring, in clockwise order.
pub points: Vec<Point3<FloatValue>>,
pub closed: bool,
pub aabb: Aabb<FloatValue, 3>,
}
pub struct SurfacePath {
pub i: RangeInclusive<usize>,
pub d: RangeInclusive<FloatValue>,
pub axis: Axis,
pub path: Vec<Point3<FloatValue>>,
pub aabb: Aabb<FloatValue, 3>,
}
pub struct SurfacePathIterator {
slices: Vec<Vec<SlicePath>>,
axis: Axis,
nozzle_width: FloatValue,
}
impl SurfacePathIterator {
pub fn new(mesh: &Mesh, axis: Axis, nozzle_width: FloatValue) -> Self {
let (h_axis, _) = axis.other();
Self {
slices: mesh
.slice_paths(axis, nozzle_width)
.map(|mut slice| {
for ring in &mut slice {
ring.points.sort_unstable_by(|a, b| {
a.coords[h_axis as usize]
.partial_cmp(&b.coords[h_axis as usize])
.unwrap()
})
}
slice.sort_unstable_by(|a, b| {
a.points.first().unwrap().coords[h_axis as usize]
.partial_cmp(&b.points.first().unwrap().coords[h_axis as usize])
.unwrap()
});
let mut iter = slice.into_iter();
let mut out = vec![iter.next().unwrap()];
for ring in iter {
if relative_eq!(
out.last().unwrap().points.last().unwrap(),
ring.points.first().unwrap(),
epsilon = nozzle_width
) {
let element = out.last_mut().unwrap();
element.points.extend(ring.points);
element.aabb.join_mut(&ring.aabb);
} else {
out.push(ring);
}
}
out
})
.collect(),
axis,
nozzle_width,
}
}
}
fn squish(points: &mut Vec<Point3<FloatValue>>, axis: Axis, d: FloatValue) {
macro_rules! ax {
($p: expr) => {
$p.coords[axis as usize]
};
}
let first = ax!(points.first().unwrap());
let left = points.iter().position(|p| first - ax!(p) > d);
let last = ax!(points.last().unwrap());
let right = points.iter().rposition(|p| ax!(p) - last > d);
if let (Some(left), Some(right)) = (left, right) {
if left > right {
// TODO
return;
}
let total = ax!(points[left + 1]) - first;
let delta = ax!(points[left]) - ax!(points[left + 1]);
points.splice(
0..left,
vec![points[left].lerp(&points[left + 1], (d - total) / delta)],
);
let total = last - ax!(points[right + 1]);
let delta = ax!(points[right + 1]) - ax!(points[right]);
}
}
impl Iterator for SurfacePathIterator {
type Item = SurfacePath;
fn next(&mut self) -> Option<Self::Item> {
self.slices.retain_mut(|slice| !slice.is_empty());
let (h_axis, _) = self.axis.other();
let mut iter = self.slices.iter_mut();
let mut ring = iter.next()?.pop()?;
// TODO: squish(&mut ring.points, h_axis, self.nozzle_width);
let mut item = Self::Item {
i: ring.i..=ring.i,
d: ring.d..=ring.d,
axis: ring.axis,
aabb: ring.aabb,
path: ring.points,
};
for slice in iter {
if *item.i.end() != slice[0].i - 1 {
break;
}
let last = item.path.last().unwrap();
let mut d = FloatValue::MAX;
let mut needs_reverse = false;
let mut index = None;
for (i, ring) in slice.iter().enumerate() {
macro_rules! item {
($a:ident, $metric: ident) => {
$a.aabb.$metric[h_axis as usize]
};
}
let a = item!(ring, max);
let b = item!(item, min);
if !(a > b || relative_eq!(a, b, epsilon = 0.1)) {
continue;
}
let a = item!(ring, min);
let b = item!(item, max);
if !(a < b || relative_eq!(a, b, epsilon = 0.1)) {
continue;
}
let d_left = last
.coords
.metric_distance(&ring.points.first().unwrap().coords);
let d_right = last
.coords
.metric_distance(&ring.points.last().unwrap().coords);
let d_min = d_left.min(d_right);
if d_min < d {
d = d_min;
needs_reverse = d_left > d_right;
index = Some(i);
}
}
if let Some(mut ring) = index.map(|i| slice.remove(i)) {
// TODO: squish(&mut ring.points, h_axis, self.nozzle_width);
if needs_reverse {
ring.points.reverse();
}
item.i = *item.i.start()..=ring.i;
item.d = *item.d.start()..=ring.d;
item.path.append(&mut ring.points);
item.aabb.join_mut(&ring.aabb)
}
}
Some(item)
}
}

View File

@@ -1,84 +0,0 @@
use approx::relative_eq;
use nalgebra::Vector3;
use crate::console_log;
use super::{base_slices::BaseSlice, FloatValue};
#[derive(Debug)]
pub struct SliceRing {
pub z: FloatValue,
/// The points of the ring, in clockwise order.
pub points: Vec<Vector3<FloatValue>>,
}
pub fn find_slice_rings(mut slice: BaseSlice, layer_index: &mut u32) -> Vec<SliceRing> {
let mut rings = vec![];
while let Some(line) = slice.lines.pop() {
if relative_eq!(line.start, line.end) {
continue;
}
let mut ring = SliceRing {
z: slice.z,
points: vec![line.start, line.end],
};
let mut right_start = ring.points[0];
let mut right = ring.points[1];
let mut sum_of_edges = (right.x - right_start.x) * (right.y + right_start.y);
let mut previous_len = usize::MAX;
let mut done = false;
while !done {
if previous_len == slice.lines.len() {
console_log!(
"Error: Could not close ring {}, d = {}, {} items left.",
layer_index,
ring.points[0].metric_distance(&right),
slice.lines.len()
);
break;
}
previous_len = slice.lines.len();
slice.lines.retain_mut(|line| {
if done {
return true;
}
macro_rules! add {
( $point:expr ) => {
if !relative_eq!($point, right_start) {
right_start = right;
right = $point;
ring.points.push(right);
sum_of_edges = (right.x - right_start.x) * (right.y + right_start.y);
done = relative_eq!(ring.points[0], right);
}
};
}
let s = relative_eq!(line.start, right);
let e = relative_eq!(line.end, right);
if s && !e {
add!(line.end);
false
} else if e && !s {
add!(line.start);
false
} else {
true
}
})
}
// The end point is duplicate, so not part of the winding order calculation.
if sum_of_edges < 0.0 {
ring.points.reverse();
}
rings.push(ring);
*layer_index += 1;
}
rings
}

View File

@@ -2,6 +2,7 @@ use super::{mesh::Mesh, triangle::Triangle};
use bvh::bvh::{Bvh, BvhNode};
/// Splits a surface into connected surfaces.
/// TODO: self intersections
pub fn split_surface(mut triangles: Vec<Triangle>) -> Vec<Mesh> {
let mut surfaces = vec![];
while let Some(triangle) = triangles.pop() {

View File

@@ -1,47 +1,48 @@
use bvh::bvh::BvhNode;
use nalgebra::Point3;
use super::{mesh::Mesh, slice_rings::SliceRing, z_projection::ToolpathIntersects, FloatValue};
use crate::slicer::sdf::Sdf3dModifiers;
pub fn trace_surface(slice: &mut SliceRing, surface: &Mesh, a: FloatValue) {
slice.points.retain_mut(|point| {
let mut stack = Vec::<usize>::new();
stack.push(0);
while let Some(i) = stack.pop() {
match surface.bvh.nodes[i] {
BvhNode::Node {
parent_index: _,
child_l_index,
child_l_aabb,
child_r_index,
child_r_aabb,
} => {
if child_l_aabb.toolpath_intersects(point, a) {
stack.push(child_l_index);
}
if child_r_aabb.toolpath_intersects(point, a) {
stack.push(child_r_index);
}
use super::{
mesh::Mesh,
sdf::{Sdf, SdfInfiniteCone},
z_projection::ToolpathIntersects,
FloatValue,
};
pub fn trace_surface(point: &Point3<FloatValue>, surface: &Mesh, a: FloatValue) -> bool {
let sdf = SdfInfiniteCone::new(a);
let mut stack = Vec::<usize>::new();
stack.push(0);
while let Some(i) = stack.pop() {
match surface.bvh.nodes[i] {
BvhNode::Node {
parent_index: _,
child_l_index,
child_l_aabb,
child_r_index,
child_r_aabb,
} => {
if child_l_aabb.toolpath_intersects(point, a) {
stack.push(child_l_index);
}
BvhNode::Leaf {
parent_index: _,
shape_index,
} => {
let triangle = &surface.triangles[shape_index];
macro_rules! check {
( $var:ident ) => {{
let x = point.x - triangle.$var.x;
let y = point.y - triangle.$var.y;
(point.z > triangle.aabb.min.z
&& FloatValue::sqrt(x * x + y * y)
< (triangle.$var.z - point.z).abs() * a)
}};
}
if check!(a) || check!(b) || check!(c) {
return false;
}
if child_r_aabb.toolpath_intersects(point, a) {
stack.push(child_r_index);
}
}
BvhNode::Leaf {
parent_index: _,
shape_index,
} => {
let triangle = &surface.triangles[shape_index];
if sdf.translate(triangle.a).sdf(point) < 0.0
|| sdf.translate(triangle.b).sdf(point) < 0.0
|| sdf.translate(triangle.c).sdf(point) < 0.0
{
return false;
}
}
}
true
});
}
return true;
}

View File

@@ -9,90 +9,59 @@ use super::{line::Line3, FloatValue};
#[derive(Debug, Clone, Copy)]
pub struct Triangle {
pub a: Vector3<FloatValue>,
pub b: Vector3<FloatValue>,
pub c: Vector3<FloatValue>,
pub a: Point3<FloatValue>,
pub b: Point3<FloatValue>,
pub c: Point3<FloatValue>,
pub normal: Vector3<FloatValue>,
node_index: usize,
pub aabb: Aabb<FloatValue, 3>,
}
#[inline(always)]
fn vec_inside_aabb(vec: &Vector3<FloatValue>, aabb: &Aabb<FloatValue, 3>) -> bool {
macro_rules! within {
($axis:ident) => {
((vec.$axis >= aabb.min.$axis && vec.$axis <= aabb.max.$axis)
|| relative_eq!(vec.$axis, aabb.min.$axis)
|| relative_eq!(vec.$axis, aabb.max.$axis))
};
}
within!(x) && within!(y) && within!(z)
}
impl Triangle {
pub fn new(a: Vector3<FloatValue>, b: Vector3<FloatValue>, c: Vector3<FloatValue>) -> Self {
pub fn new(a: Point3<FloatValue>, b: Point3<FloatValue>, c: Point3<FloatValue>) -> Self {
let mut aabb = a.aabb();
aabb.grow_mut(&b);
aabb.grow_mut(&c);
Self {
a,
b,
c,
normal: (b - a).cross(&(c - a)).into(),
normal: (b - a).cross(&(c - a)).normalize(),
node_index: 0,
aabb: Aabb::with_bounds(
Point3::new(
FloatValue::min(FloatValue::max(a.x, b.x), c.x),
FloatValue::min(FloatValue::min(a.y, b.y), c.y),
FloatValue::min(FloatValue::min(a.z, b.z), c.z),
),
Point3::new(
FloatValue::max(FloatValue::max(a.x, b.x), c.x),
FloatValue::max(FloatValue::max(a.y, b.y), c.y),
FloatValue::max(FloatValue::max(a.z, b.z), c.z),
),
),
aabb,
}
}
pub fn has_point_in_aabb(&self, aabb: &Aabb<FloatValue, 3>) -> bool {
vec_inside_aabb(&self.a, aabb)
|| vec_inside_aabb(&self.b, aabb)
|| vec_inside_aabb(&self.c, aabb)
aabb.contains(&self.a) || aabb.contains(&self.b) || aabb.contains(&self.c)
}
pub fn has_vec(&self, vec: Vector3<FloatValue>) -> bool {
pub fn has_point(&self, vec: Point3<FloatValue>) -> bool {
relative_eq!(self.a, vec) || relative_eq!(self.b, vec) || relative_eq!(self.c, vec)
}
pub fn shares_point_with_triangle(&self, other: Triangle) -> bool {
self.has_vec(other.a) || self.has_vec(other.b) || self.has_vec(other.c)
self.has_point(other.a) || self.has_point(other.b) || self.has_point(other.c)
}
pub fn shares_edge_with_triangle(&self, other: Triangle) -> bool {
let a = self.has_vec(other.a);
let b = self.has_vec(other.b);
let c = self.has_vec(other.c);
a && b || a && c || b && c
}
pub fn intersect_z(&self, z: FloatValue) -> Option<Line3> {
let mut intersection = Vec::<Vector3<FloatValue>>::with_capacity(3);
pub fn intersect(&self, value: FloatValue, axis: usize) -> Option<Line3> {
let mut intersection = Vec::<Point3<FloatValue>>::with_capacity(3);
let mut last = &self.c;
for point in [self.a, self.b, self.c].iter() {
if relative_eq!(point.z, z) {
intersection.push(Vector3::new(point.x, point.y, z));
} else if last.z < z && point.z > z {
let ratio = (z - last.z) / (point.z - last.z);
intersection.push(Vector3::new(
last.x + (point.x - last.x) * ratio,
last.y + (point.y - last.y) * ratio,
z,
))
} else if last.z > z && point.z < z {
let ratio = (z - point.z) / (last.z - point.z);
intersection.push(Vector3::new(
point.x + (last.x - point.x) * ratio,
point.y + (last.y - point.y) * ratio,
z,
))
if relative_eq!(point[axis], value) {
let mut new_point = *point;
new_point[axis] = value;
intersection.push(new_point);
} else if last[axis] < value && point[axis] > value {
let ratio = (value - last[axis]) / (point[axis] - last[axis]);
let mut new_point = last + (point - last) * ratio;
new_point[axis] = value;
intersection.push(new_point);
} else if last[axis] > value && point[axis] < value {
let ratio = (value - point[axis]) / (last[axis] - point[axis]);
let mut new_point = point + (last - point) * ratio;
new_point[axis] = value;
intersection.push(new_point);
}
last = point;
}
@@ -105,6 +74,12 @@ impl Triangle {
None
}
}
pub fn area(&self) -> FloatValue {
let ab = self.b - self.a;
let ac = self.c - self.a;
0.5 * ab.cross(&ac).norm()
}
}
impl Bounded<FloatValue, 3> for Triangle {

View File

@@ -1,5 +1,5 @@
use bvh::aabb::Aabb;
use nalgebra::{Point2, Vector2, Vector3};
use nalgebra::{Point2, Point3};
use super::{triangle::Triangle, FloatValue};
@@ -11,7 +11,7 @@ pub trait ProjectToolpath<T> {
pub trait ToolpathIntersects<T>: ProjectToolpath<T> {
/// Checks if a hypothetical toolpath that draws the object could intersect
/// with the given point, given the tangent of the angle of the toolhead
fn toolpath_intersects(&self, point: &Vector3<FloatValue>, a: FloatValue) -> bool;
fn toolpath_intersects(&self, point: &Point3<FloatValue>, a: FloatValue) -> bool;
}
pub trait ToolpathIntersection {
@@ -38,7 +38,7 @@ impl ProjectToolpath<Aabb<FloatValue, 2>> for Aabb<FloatValue, 3> {
}
impl ToolpathIntersects<Aabb<FloatValue, 2>> for Aabb<FloatValue, 3> {
fn toolpath_intersects(&self, point: &Vector3<FloatValue>, a: FloatValue) -> bool {
fn toolpath_intersects(&self, point: &Point3<FloatValue>, a: FloatValue) -> bool {
if let Some(aabb) = self.project_toolpath_onto_z(point.z, a) {
aabb.approx_contains_eps(&Point2::new(point.x, point.y), FloatValue::EPSILON)
} else {
@@ -100,7 +100,7 @@ impl ProjectToolpath<Triangle2D> for Triangle {
mod tests {
use approx::assert_relative_eq;
use bvh::aabb::Aabb;
use nalgebra::{Point3, Vector2, Vector3};
use nalgebra::{point, Point3};
use crate::slicer::{triangle::Triangle, z_projection::ProjectToolpath, FloatValue};
@@ -129,9 +129,9 @@ mod tests {
#[test]
fn test_project_triangle_toolpath() {
let triangle = Triangle::new(
Vector3::new(0.0, 0.0, 0.0),
Vector3::new(0.0, 1.5, 1.0),
Vector3::new(-0.6, -1.4, 0.2),
point![0.0, 0.0, 0.0],
point![0.0, 1.5, 1.0],
point![-0.6, -1.4, 0.2],
);
let a = FloatValue::to_radians(30.0).tan();

122
flake.nix
View File

@@ -4,59 +4,77 @@
rust-overlay.url = "github:oxalica/rust-overlay";
flake-utils.url = "github:numtide/flake-utils";
};
outputs = {
self,
nixpkgs,
flake-utils,
rust-overlay,
}:
flake-utils.lib.eachDefaultSystem (system: let
overlays = [(import rust-overlay)];
pkgs = import nixpkgs {inherit system overlays;};
rust-bin = pkgs.rust-bin.stable.latest.default.override {
targets = [ "wasm32-unknown-unknown" ];
extensions = ["rust-src" "rust-std" "clippy" "rust-analyzer"];
};
fontMin = pkgs.python311.withPackages (ps: with ps; [brotli fonttools] ++ (with fonttools.optional-dependencies; [woff]));
tauriPkgs = nixpkgs.legacyPackages.${system};
libraries = with tauriPkgs; [
webkitgtk
gtk3
cairo
gdk-pixbuf
glib
dbus
openssl_3
librsvg
];
packages =
(with pkgs; [
nodejs_18
nodePackages.pnpm
rust-bin
fontMin
wasm-pack
])
++ (with tauriPkgs; [
curl
wget
pkg-config
outputs =
{
self,
nixpkgs,
flake-utils,
rust-overlay,
}:
flake-utils.lib.eachDefaultSystem (
system:
let
overlays = [ (import rust-overlay) ];
pkgs = import nixpkgs { inherit system overlays; };
rust-bin = pkgs.rust-bin.nightly.latest.default.override {
targets = [ "wasm32-unknown-unknown" ];
extensions = [
"rust-src"
"rust-std"
"clippy"
"rust-analyzer"
];
};
fontMin = pkgs.python311.withPackages (
ps:
with ps;
[
brotli
fonttools
]
++ (with fonttools.optional-dependencies; [ woff ])
);
tauriPkgs = nixpkgs.legacyPackages.${system};
libraries = with tauriPkgs; [
webkitgtk
gtk3
cairo
gdk-pixbuf
glib
dbus
openssl_3
glib
gtk3
libsoup
webkitgtk
librsvg
# serial plugin
udev
]);
in {
devShell = pkgs.mkShell {
buildInputs = packages;
shellHook = ''
export LD_LIBRARY_PATH=${pkgs.lib.makeLibraryPath libraries}:$LD_LIBRARY_PATH
'';
};
});
];
packages =
(with pkgs; [
nodejs_18
nodePackages.pnpm
rust-bin
fontMin
wasm-pack
])
++ (with tauriPkgs; [
curl
wget
pkg-config
dbus
openssl_3
glib
gtk3
libsoup
webkitgtk
librsvg
# serial plugin
udev
]);
in
{
devShell = pkgs.mkShell {
buildInputs = packages;
shellHook = ''
export LD_LIBRARY_PATH=${pkgs.lib.makeLibraryPath libraries}:$LD_LIBRARY_PATH
'';
};
}
);
}

View File

@@ -37,4 +37,3 @@
"vite-plugin-wasm": "^3.3.0"
}
}

View File

@@ -1,6 +1,6 @@
<script lang="ts">
import { T, type AsyncWritable } from '@threlte/core';
import { Gizmo, Grid, MeshLineGeometry, MeshLineMaterial, OrbitControls } from '@threlte/extras';
import { Gizmo, Grid, OrbitControls, MeshLineGeometry, MeshLineMaterial } from '@threlte/extras';
import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js';
import { useLoader } from '@threlte/core';
import {
@@ -9,9 +9,7 @@
Vector3,
DoubleSide,
Color,
BufferGeometryLoader,
TubeGeometry,
CatmullRomCurve3
BufferGeometryLoader
} from 'three';
import { writable } from 'svelte/store';
import { onDestroy, onMount } from 'svelte';
@@ -35,19 +33,17 @@
progressLayer.set(event.data.layer);
break;
}
case 'layer': {
case 'result': {
layers.update((layers) => {
const layer = event.data.data;
if (layer.type === 'ring') {
const curve = new CatmullRomCurve3(
Array.from({ length: layer.position.length / 3 }, (_, i) =>
new Vector3().fromArray(layer.position, i * 3)
)
);
const geometry = new TubeGeometry(curve, undefined, 0.1);
layers.push(geometry);
} else if (layer.type === 'surface') {
for (const layer of event.data.data.slices) {
if (layer.type === 'ring' || layer.type === 'path') {
layers.push(
Array.from({ length: layer.position.length / 3 }, (_, i) =>
new Vector3().fromArray(layer.position, i * 3)
)
);
} else if (layer.type === 'surface') {
}
}
return layers;
});
@@ -63,6 +59,7 @@
export let buildSurface = [300, 300, 300];
export let layerHeight = 0.2;
export let nozzleDiameter = 0.4;
export let tolerance = 0.005;
export let progress = writable<number | undefined>(undefined);
export let progressLayer = writable(0);
@@ -72,7 +69,7 @@
export let maxNonPlanarAngle = MathUtils.degToRad(20);
export let bedNormal = new Vector3(0, 0, 1);
let layers = writable<Layer[]>([]);
let layers = writable<Vector3[][]>([]);
const stl: AsyncWritable<BufferGeometry> = useLoader(STLLoader).load('/benchy.stl');
@@ -84,6 +81,8 @@
layerHeight,
tolerance,
maxNonPlanarAngle,
nozzleDiameter,
minSurfacePathLength: nozzleDiameter * 2,
bedNormal: bedNormal.toArray()
}
} satisfies SliceEvent);
@@ -107,12 +106,13 @@
gridSize={[buildSurface[0], buildSurface[1]]}
/>
{#each $layers as geometry, i}
{#each $layers as points, i}
{@const visible = maxZ !== 0 ? i === maxZ : showSlices >= i / $layers.length}
{@const color = new Color(Math.random() * 0xffffff)}
<!---{@const color = new Color(0, i / $layers.length, 0.2)}-->
<T.Mesh {geometry} {visible}>
<T.MeshMatcapMaterial {color} side={DoubleSide} />
<T.Mesh {visible}>
<MeshLineGeometry {points} />
<MeshLineMaterial width={nozzleDiameter * 0.25} {color} />
</T.Mesh>
{/each}

View File

@@ -6,6 +6,8 @@ export interface SliceArguments {
maxNonPlanarAngle: number;
tolerance: number;
layerHeight: number;
nozzleDiameter: number;
minSurfacePathLength: number;
}
export interface SliceEvent {

View File

@@ -18,13 +18,13 @@ addEventListener('message', async (event: MessageEvent<WorkerEvent>) => {
const result = slice({
positions: geometry.attributes.position.array as Float32Array,
layerHeight: event.data.data.layerHeight,
maxAngle: event.data.data.maxNonPlanarAngle
maxAngle: event.data.data.maxNonPlanarAngle,
nozzleDiameter: event.data.data.nozzleDiameter,
minSurfacePathLength: event.data.data.minSurfacePathLength
});
self.postMessage({
type: 'result',
data: result
});
for (const layer of result.slices) {
self.postMessage({
type: 'layer',
data: layer
});
}
}
});