import bpy

def draw_polygon_with_gpencil(verts):
    # **Grease Pencil オブジェクトの作成**
    #gp_obj = bpy.data.objects.new(name="GP_Object", object_data=None)
    gp_obj = bpy.data.objects.new("GPencil_Object", "GreasePencil")
    print("オブジェクトの作成　gp_obj = ", gp_obj)
    return
    gp_obj.data = bpy.data.grease_pencils.new(name="GP_Data", GreasePencil)
    #gp_obj.data = bpy.data.grease_pencils.new("GPencil_Data")
    print("オブジェクトデータ　gp_obj.data = ", gp_obj.data)

    bpy.context.collection.objects.link(gp_obj)  # シーンに追加
    print("シーンに追加完了")
    # **新しい Grease Pencil レイヤーを作成**
    gp_layer = gp_obj.data.data.layers.get("GP_Layer") or gp_obj.data.data.layers.append()
    print("新しい Grease Pencil レイヤーを作成 gp_layer = ", gp_layer)
    
    # **フレームを作成**
    gp_frame = gp_layer.frames.get(0) or gp_layer.frames.append(0)
    print("フレームを作成 gp_frame = ", gp_frame)
    
    # **ストロークを作成**
    gp_stroke = gp_frame.strokes.append()
    gp_stroke.display_mode = '3DSPACE'  # 3D空間に描画
    gp_stroke.use_cyclic = True  # 線を閉じる
    gp_stroke.line_width = 10  # 線の太さ

    # **頂点を追加**
    gp_stroke.points.add(count=len(verts))
    for i, (x, y, z) in enumerate(verts):
        gp_stroke.points[i].co = (x, y, z)

    print("✅ Grease Pencil でポリゴンが描画されました")

# **テスト用の座標リスト（四角形）**
verts = [
    (-1, -1, 0),
    (1, -1, 0),
    (1, 1, 0),
    (-1, 1, 0)
]

draw_polygon_with_gpencil(verts)
