adze/chop/transform.py

65 lines
2 KiB
Python
Raw Normal View History

2018-03-20 15:10:45 -07:00
import numpy
from numpy import sin, cos
2018-03-28 14:58:38 -07:00
from . import poly_t, plane_t
2018-03-20 15:10:45 -07:00
2018-03-28 14:58:38 -07:00
def rotate(poly: poly_t, theta: float, axis: int) -> poly_t:
'''
Rotate the polyhedron around an axis.
:param poly: Polyhedron to rotate. Changed in-place.
:param theta: Angle to rotate by (radians).
:param axis: Axis to rotate around (0-2).
:return: Rotated polyhedron.
Data is altered in-place but also returned for convenience.
'''
2018-03-20 15:10:45 -07:00
s, c = sin(theta), cos(theta)
v0 = poly['vertices'][:, axis - 2].copy()
v1 = poly['vertices'][:, axis - 1].copy()
poly['vertices'][:, axis - 2] = c * v0 - s * v1
poly['vertices'][:, axis - 1] = s * v1 + c * v0
2018-03-28 14:58:38 -07:00
return poly
2018-03-20 15:10:45 -07:00
2018-03-28 14:58:38 -07:00
def translate(poly: poly_t, shift: numpy.ndarray) -> poly_t:
'''
Translate the polyhedron by a vector.
:param poly: Polyhedron to translate. Changed in-place.
:param shift: Vector to translate by.
:return: Translated polyhedron.
Data is altered in-place but also returned for convenience.
'''
2018-03-20 15:10:45 -07:00
poly['vertices'] += shift
2018-03-28 14:58:38 -07:00
return poly
2018-03-20 15:10:45 -07:00
2018-03-28 14:58:38 -07:00
def scale(poly: poly_t, factor: numpy.ndarray or float) -> poly_t:
'''
Scale the polyhedron.
Can scale by a single value, or scale each axis individually
:param poly: Polyhedron to scale. Changed in-place.
:param factor: Scalar or vector to scale by.
:return: Scaled polyhedron.
Data is altered in-place but also returned for convenience.
'''
2018-03-20 15:10:45 -07:00
poly['vertices'] *= factor
2018-03-28 14:58:38 -07:00
return poly
2018-03-20 15:10:45 -07:00
2018-03-28 14:58:38 -07:00
def affine(poly: poly_t, xform: numpy.ndarray) -> poly_t:
'''
Perform arbitrary affine trasnformation on the polyhedron.
2018-03-20 15:10:45 -07:00
2018-03-28 14:58:38 -07:00
:param poly: Polyhedron to transform. Changed in-place.
:param xform: 4x4 affine transformation matrix.
:return: Transformed polyhedron.
Data is altered in-place but also returned for convenience.
'''
mat4x3 = xform[:, :3]
mat4x1 = xform[:, 3]
2018-03-20 15:10:45 -07:00
vh = mat4x3 @ poly['vertices'].T + mat4x1
2018-03-28 14:58:38 -07:00
poly['vertices'][:] = (vh[:3, :] / vh[3, :]).T
return poly