mirror of
https://github.com/Theaninova/Bampy.git
synced 2026-01-21 01:12:54 +00:00
Compare commits
3 Commits
dependabot
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
f57e6c3f4e
|
|||
|
8c353107d8
|
|||
|
0e8479af91
|
177
;
Normal file
177
;
Normal 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
|
||||
}
|
||||
}
|
||||
674
LICENSE
674
LICENSE
@@ -1,674 +0,0 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -20,7 +20,7 @@ wasm-bindgen = "0.2.84"
|
||||
# code size when deploying.
|
||||
console_error_panic_hook = { version = "0.1.7", optional = true }
|
||||
bvh = "0.9.0"
|
||||
nalgebra = "0.33.0"
|
||||
nalgebra = "0.32.4"
|
||||
num = "0.4.1"
|
||||
approx = "0.5.1"
|
||||
serde = "1.0.197"
|
||||
|
||||
215
bampy/src/lib.rs
215
bampy/src/lib.rs
@@ -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
39
bampy/src/result.rs
Normal 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
30
bampy/src/slicer/axis.rs
Normal 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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
253
bampy/src/slicer/sdf.rs
Normal 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 {}
|
||||
183
bampy/src/slicer/slice_path.rs
Normal file
183
bampy/src/slicer/slice_path.rs
Normal 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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
122
flake.nix
@@ -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
|
||||
'';
|
||||
};
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -37,4 +37,3 @@
|
||||
"vite-plugin-wasm": "^3.3.0"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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}
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ export interface SliceArguments {
|
||||
maxNonPlanarAngle: number;
|
||||
tolerance: number;
|
||||
layerHeight: number;
|
||||
nozzleDiameter: number;
|
||||
minSurfacePathLength: number;
|
||||
}
|
||||
|
||||
export interface SliceEvent {
|
||||
|
||||
@@ -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
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user