Skip to content

Instantly share code, notes, and snippets.

@paulhayes
Last active July 17, 2022 10:55
Show Gist options
  • Save paulhayes/92a96ac9cbe87839c0f6d090ea62dcb5 to your computer and use it in GitHub Desktop.
Save paulhayes/92a96ac9cbe87839c0f6d090ea62dcb5 to your computer and use it in GitHub Desktop.
OpenScad Polygon utilities. Includes smooth_corners and truncate_corners modules.
function normalize(v) = norm(v)==0 ? 0 : v/norm(v);
function wrap(i,l) = ((i%l)+l)%l;
function lerp(start, end, bias) = (end * bias + start * (1 - bias));
function truncate_corners(points,size) = [
for(i=[0:len(points)-1])
for(j=[-1,1]) points[i]+size*normalize(points[wrap(i+j,len(points))]-points[i])
];
function n_lerp(start, end, bias)=
normalize(lerp(start, end, bias));
function n_lerp_origin(p1,p2,p,size)=
(p+1.41*size*normalize((p1-p)/2+(p2-p)/2));
function n_lerp_corner(p1,p2,p,size,t)=
size*n_lerp(
p1-n_lerp_origin(p1,p2,p,size),
p2-n_lerp_origin(p1,p2,p,size),
t
)+n_lerp_origin(p1,p2,p,size) ;
function move_towards(from,to,distance)=
from+(distance*normalize(to-from));
function smooth_corners(points,size,steps=10) = [
for(i=[0:len(points)-1])
for(j=[0:1/steps:1])
n_lerp_corner(
move_towards(points[i],points[wrap(i-1,len(points))],size),
move_towards(points[i],points[wrap(i+1,len(points))],size),
points[i],
size,
j
)
];
module round_rect(width,length,corner_size){
points = [
[width,0],
[width,length],
[0,length],
[0,0]
];
polygon( smooth_corners(points,corner_size));
}
@paulhayes
Copy link
Author

I got the idea of using a normalised magnitude lerp ( nLerp ) rather than slerp from this article.
https://keithmaggio.wordpress.com/2011/02/15/math-magician-lerp-slerp-and-nlerp/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment