Created
February 3, 2025 18:51
-
-
Save joshbodily/2905b3bad34e7c0e89ab818b01844efb to your computer and use it in GitHub Desktop.
Convex Hulls from Blender to Lua
This file contains 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 bpy | |
import bmesh | |
import itertools | |
# Usage, assign material slots to each unique coplanar plane in each convex hull of the mesh (leaving the first material slot for unassigned faces) | |
obj = bpy.data.objects['Model'] | |
me = obj.data | |
vertices = me.vertices | |
# See https://docs.blender.org/api/current/bpy.types.Mesh.html#bpy.types.Mesh.polygons | |
faces = [] | |
for poly in me.polygons: | |
if poly.material_index == 0: | |
continue | |
faces.append( [poly.material_index, poly, None, None] ) | |
def update_min_max(min, max, current): | |
if current[0] < min[0]: min[0] = current[0] | |
if current[1] < min[1]: min[1] = current[1] | |
if current[2] < min[2]: min[2] = current[2] | |
if current[0] > max[0]: max[0] = current[0] | |
if current[1] > max[1]: max[1] = current[1] | |
if current[2] > max[2]: max[2] = current[2] | |
gmin = [float('inf'), float('inf'), float('inf')] | |
gmax = [float('-inf'), float('-inf'), float('-inf')] | |
faces = sorted(faces, key=lambda x: x[0]) | |
for key, group in itertools.groupby(faces, lambda x: x[0]): | |
min = [float('inf'), float('inf'), float('inf')] | |
max = [float('-inf'), float('-inf'), float('-inf')] | |
for thing in group: | |
poly = thing[1] | |
for loop_index in range(poly.loop_start, poly.loop_start + poly.loop_total): | |
vi = me.loops[loop_index].vertex_index | |
print( vertices[vi] ) | |
update_min_max(min, max, vertices[vi].co.to_tuple()) | |
update_min_max(gmin, gmax, vertices[vi].co.to_tuple()) | |
thing[2] = min | |
thing[3] = max | |
print("{") | |
print(" min = {%f, %f, %f}," % tuple(gmin)) | |
print(" max = {%f, %f, %f}," % tuple(gmax)) | |
for key, group in itertools.groupby(faces, lambda x: x[0]): | |
print(" {") | |
for thing in group: | |
poly = thing[1] | |
min = thing[2] | |
max = thing[3] | |
print(" { center={%f, %f, %f}, normal={%f, %f, %f} }," % (poly.center.to_tuple() + poly.normal.to_tuple())) | |
print(" min = {%f, %f, %f}," % tuple(min)) | |
print(" max = {%f, %f, %f}," % tuple(max)) | |
print(" },") | |
print("}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment