Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add align_z argument to pack() Method. #632

Merged
merged 5 commits into from
May 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/tips.rst
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,14 @@ padding (right):
:align: right


By default, the original Z value of all objects packed using the :meth:`pack.pack` function is preserved.
If you want to align all objects so that they are "placed" on the zero Z coordinate, the :meth:`pack`
function has an `align_z` argument. When set to `True`, this will align all objects.

This can be useful, for example, when preparing print setups for 3D printing, giving you full control
over this alignment so you don't have to leave it to the slicer.


.. _are_glob_imports_bad_practice:

***********************************************
Expand Down
18 changes: 14 additions & 4 deletions src/build123d/pack.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from dataclasses import dataclass
from typing import Callable, Collection, Optional, cast

from build123d import Location, Shape
from build123d import Location, Shape, Pos


def _pack2d(
Expand Down Expand Up @@ -119,16 +119,26 @@ def grow_down(w, h):
return [(t[1], t[2]) for t in sorted(translations, key=lambda t: t[0])]


def pack(objects: Collection[Shape], padding: float) -> Collection[Shape]:
"""Pack objects in a squarish area in Plane.XY."""
def pack(objects: Collection[Shape], padding: float, align_z: bool = False) -> Collection[Shape]:
"""Pack objects in a squarish area in Plane.XY.

Args:
objects (Collection[Shape]): objects to arrange
padding (float): space between objects
align_z (bool, optional): align shape bottoms to Plane.XY. Defaults to False.

Returns:
Collection[Shape]: rearranged objects
"""

bounding_boxes = {o: o.bounding_box().size + (padding, padding) for o in objects}
translations = _pack2d(
objects,
width_fn=lambda o: bounding_boxes[cast(Shape, o)].X,
length_fn=lambda o: bounding_boxes[cast(Shape, o)].Y,
)
translated = [
Location((t[0] - o.bounding_box().min.X, t[1] - o.bounding_box().min.Y, 0)) * o
Location((t[0] - o.bounding_box().min.X, t[1] - o.bounding_box().min.Y, 0)) * Pos((0, 0, -o.bounding_box().min.Z if align_z else 0)) * o
for (o, t) in zip(objects, translations)
]

Expand Down
Loading