5

I have a list of points, and want to add a Bezier-spline using these points.

Following is my code:

import bpy

name = "MyCurve"
numPoints = 4
points = [ [1,1,1], [-1,1,1], [-1,-1,1], [1,-1,-1] ]

curvedata = bpy.data.curves.new(name=name,type='CURVE')
curvedata.dimensions = '3D'
curvedata.fill_mode = 'FULL'
curvedata.bevel_depth = 0.045     

ob = bpy.data.objects.new(name+"Obj", curvedata)
bpy.context.scene.objects.link(ob)

polyline = curvedata.splines.new('BEZIER')
polyline.bezier_points.add(numPoints)
for num in range(numPoints):
    polyline.bezier_points[num].co = points[num]
polyline.resolution_u = 1

print( len(polyline.bezier_points))

Now my problem is, that this code adds another point. The printed value will be 5 not as I expected 4. The added point is after the other points and is the point (0, 0, 0). This is unwanted behavior.

What is wrong with my code?

My Blender version is 2.70 built 2014-03-19.

CodeManX
  • 29,298
  • 3
  • 89
  • 128
Dragonseel
  • 311
  • 3
  • 13

1 Answers1

12

A new splines starts with a single point, it is not empty:

import bpy

curvedata = bpy.data.curves.new(name="Curve", type='CURVE')
ob = bpy.data.objects.new("CurveObj", curvedata)
bpy.context.scene.objects.link(ob)

spline = curvedata.splines.new('BEZIER')
print(len(spline.bezier_points))
# Output: 1

The bezier spline has already a point, so you need to
.add() number of points you want to add minus 1.

polyline.bezier_points.add(len(points)-1)

By the way - you can assign the coordinates more efficiently like this:

from bpy_extras.io_utils import unpack_list
# ...
polyline.bezier_points.foreach_set("co", unpack_list(points))
Garrett
  • 6,596
  • 6
  • 47
  • 75
CodeManX
  • 29,298
  • 3
  • 89
  • 128
  • Thanks. Worked perfectly. Do you have a quick reference/tutorial for the suggested assignment method for me? – Dragonseel Jun 13 '14 at 15:45
  • foreach_set(): http://www.blender.org/documentation/blender_python_api_2_70a_release/bpy.types.bpy_prop_collection.html?highlight=foreach_set#bpy.types.bpy_prop_collection.foreach_set and for unpack_list() see the actual python script in Blender/2.xx/scripts/modules/bpy_extras/io_utils.py. – CodeManX Jun 13 '14 at 16:13