# Kambi: trivial example of adding a new mesh.
# Minimal changes to circle_producer_25.py, to make it an operator
# with interactive number_of_points, radius controls.

import math
import bpy
from bpy.props import FloatProperty, IntProperty

class AddCircle(bpy.types.Operator):
        '''Add a circle mesh'''
        # Beware: do not add this "mesh.primitive_circle_add", it already exists.
        bl_idname = "mesh.primitive_circle_add_example"
        bl_label = "Add Circle (Example)"
        bl_options = {'REGISTER', 'UNDO'}

        number_of_points = IntProperty(name="Number of points",
            description="Number of points along the circle outline, not counting the middle point",
            default=32, min=2, max=1000)
        radius = FloatProperty(name="Radius",
            description="Circle radius",
            default=1.0, min=0.01, max=100.0)

        def execute(self, context):
                mesh = bpy.data.meshes.new("Circle")
                mesh.vertices.add(self.number_of_points + 1)

                # add side vertexes
                for i in range(0, self.number_of_points):
                        angle = 2 * math.pi * i / self.number_of_points
                        mesh.vertices[i].co = (
                                self.radius * math.cos(angle),
                                self.radius * math.sin(angle),
                                0.0)

                # add a vertex to the center
                mesh.vertices[self.number_of_points].co = (0.0, 0.0, 0.0)

                # connect the vertices to form faces
                mesh.faces.add(self.number_of_points)
                for i in range(0, self.number_of_points):
                        mesh.faces[i].vertices = (i, (i+1) % self.number_of_points, self.number_of_points)

                # necessary to create appropriate edges (implicitly defined by faces).
                # Without this, edges may not appear correctly for some time
                # (e.g. until we enter edit mode).
                mesh.update()

                # create and add an object containing mesh (remember that
                # in Blender, "mesh" is only a data inside a container "object").
                # Note: see add_object_utils helper module for a more fancy way
                # to add an object, honoring standard selection and edit/object
                # mode behavior.
                obj = bpy.data.objects.new("CircleObject", mesh)
                bpy.context.scene.objects.link(obj)

                return {'FINISHED'}

bpy.utils.register_class(AddCircle)
