Skip to content

Instantly share code, notes, and snippets.

@blender8r
Created November 9, 2023 12:50
Show Gist options
  • Select an option

  • Save blender8r/2ca1ded6496eb084ac76838348abf5fd to your computer and use it in GitHub Desktop.

Select an option

Save blender8r/2ca1ded6496eb084ac76838348abf5fd to your computer and use it in GitHub Desktop.
Finds the intersection point between two grease pencil strokes in Blender
import bpy
from math import pi, sin, cos
def ellipse(gp_frame, center, radius_x, radius_z, num_points):
gp_stroke = gp_frame.strokes.new()
gp_stroke.line_width = 30
gp_stroke.use_cyclic = True
gp_stroke.points.add(count=num_points)
step = (2 * pi) / num_points
for i in range(num_points):
angle = i * step
x = center[0] + (radius_x * cos(angle))
y = 0
z = center[2] + (radius_z* sin(angle))
gp_stroke.points[i].co = (x, y, z)
return gp_stroke
def find_line_intersection(a1_pos, a2_pos, b1_pos, b2_pos, bounded=True):
a1x, a1z = a1_pos[0], a1_pos[2]
a2x, a2z = a2_pos[0], a2_pos[2]
b1x, b1z = b1_pos[0], b1_pos[2]
b2x, b2z = b2_pos[0], b2_pos[2]
denom = (a1x-a2x)*(b1z-b2z)-(a1z-a2z)*(b1x-b2x)
if denom == 0:
return None
numerator_x = ((b1x-b2x)*(a1x*a2z-a1z*a2x)-(a1x-a2x)*(b1x*b2z-b1z*b2x))
numerator_z = ((b1z-b2z)*(a1x*a2z-a1z*a2x)-(a1z-a2z)*(b1x*b2z-b1z*b2x))
xi = numerator_x / denom
zi = numerator_z / denom
if bounded:
if xi < min(a1x, a2x) or xi > max(a1x, a2x):
return None
if zi < min(a1z, a2z) or zi > max(a1z, a2z):
return None
if xi < min(b1x, b2x) or xi > max(b1x, b2x):
return None
if zi < min(b1z, b2z) or zi > max(b1z, b2z):
return None
return (xi, 0, zi)
def find_stroke_intersections(stroke1, stroke2, bounded=True):
intersections = []
for i in range(len(stroke1.points)):
p1 = stroke1.points[i].co
if i == (len(stroke1.points)-1):
if stroke1.use_cyclic:
p2 = stroke1.points[0].co
else:
break
else:
p2 = stroke1.points[i+1].co
for j in range(len(stroke2.points)):
p3 = stroke2.points[j].co
if j == (len(stroke2.points)-1):
if stroke2.use_cyclic:
p4 = stroke2.points[0].co
else:
break
else:
p4 = stroke2.points[j+1].co
intersection = find_line_intersection(p1, p2, p3, p4, bounded)
if intersection:
intersections.append(intersection)
return intersections
sel_obj = None
sel_objs = bpy.context.selected_objects
if sel_objs:
sel_obj = sel_objs[0]
if sel_obj is not None and sel_obj.type == 'GPENCIL':
gpencil = sel_obj.data
gp_layer = gpencil.layers.active
gp_frame = gp_layer.frames[0]
stroke1, stroke2 = gp_frame.strokes[0], gp_frame.strokes[1]
# a1 = stroke1.points[0].co
# a2 = stroke1.points[1].co
# b1 = stroke2.points[0].co
# b2 = stroke2.points[1].co
intersections = find_stroke_intersections(stroke1, stroke2, True)
for intersection in intersections:
ellipse(gp_frame, intersection, 0.1, 0.1, 24)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment