Convert selected mesh to Grease Pencil object

Just a quick little script I made that converts a selected mesh to GP strokes on a new GP object. Mostly just an update to other older scripts from 2.7 that no longer work. Figured I’d post it here in case anyone else has the same problem and googles the sam

import bpy
from mathutils import Vector


obj = bpy.context.object
mesh = obj.data


gpencil = bpy.data.grease_pencil.new('gpencil')

layer = gpencil.layers.new("alayer", set_active=True)
frame = layer.frames.new(bpy.context.scene.frame_current)
stroke = frame.strokes.new()
stroke.line_width = 100
stroke.display_mode = '3DSPACE'
# assign material
stroke.material_index = 0


for edge in mesh.edges:

    #edge.vertices[0] and [1] are indices inside
    #mesh.vertices
        
    points = [
        obj.matrix_world @ mesh.vertices[edge.vertices[0]].co,
        obj.matrix_world @ mesh.vertices[edge.vertices[1]].co,
        
        ]

    for point in points:
        print(point) #should be each point's obj data?
        stroke.points.add(1)
        stroke.points[-1].co.x = point[0]
        stroke.points[-1].co.y = point[1]  
        stroke.points[-1].co.z = point[2]  
obj = bpy.data.objects.new('agobject', gpencil)
bpy.context.scene.collection.objects.link(obj)

# create material
mat = bpy.data.materials.new('mymaterial')
obj.data.materials.append(mat)
4 Likes