Created
August 3, 2022 17:02
-
-
Save jkulhanek/2d07aae5937371b26ecfe391139cc780 to your computer and use it in GitHub Desktop.
Numpy computing 2D SDF function of a polygon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def compute_sdf_polygon(vertices, points): | |
vertices = vertices[:, None, ...] | |
points = points[None, :, ...] | |
d = np.sum((points[0] - vertices[0]) * (points[0] - vertices[0]), -1) | |
vert_offset = np.concatenate([vertices[-1:], vertices[:-1]], 0) | |
e = vert_offset - vertices | |
w = points - vertices | |
b = w - e * np.clip(np.sum(w * e, -1) / np.sum(e * e, -1), 0., 1.)[..., None] | |
b_dot = np.sum(b * b, -1) | |
d = np.minimum(d, np.min(b_dot, 0)) | |
c = np.stack([ | |
points[..., 1] > vertices[..., 1], | |
points[..., 1] <= vert_offset[..., 1], | |
e[..., 0] * w[..., 1] > e[...,1] * w[...,0]], -1) | |
s = np.where(np.logical_or(np.all(c, -1), np.all(np.logical_not(c), -1)), -1, 1) | |
s = np.prod(s, 0) | |
return s * np.sqrt(d) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment