1
$\begingroup$

I'm trying to write an export script to output vertices and vertex colors in a simple format. The script I've created appears to work fine when run during "Object" or "Vertex Paint" mode, but when I try running it during "Edit Mode" it crashes and doesn't work.

Here is the relevant code:

def do_export(context, filepath):
    obj = context.object
    mesh = obj.data
    mesh.calc_normals_split()

    with open(filepath, 'w') as f:
        for poly in mesh.polygons:
            for loop_index in poly.loop_indices:
                loop = mesh.loops[loop_index]
                vert = mesh.vertices[loop.vertex_index]

                f.write("v %.4f %.4f %.4f\n" % vert.co[:])
                f.write("c %i " % (mesh.vertex_colors.active.data[loop_index].color[0] * 255))
                f.write("%i " % (mesh.vertex_colors.active.data[loop_index].color[1] * 255))
                f.write("%i\n" % (mesh.vertex_colors.active.data[loop_index].color[2] * 255))
                f.write("\n")

And the error I get:

location: <unknown location>:-1

Traceback (most recent call last):
  File "/home/pubby/.config/blender/2.78/scripts/addons/export.py", line 62, in execute
    exported = do_export(context,  filepath)
  File "/home/pubby/.config/blender/2.78/scripts/addons/export.py", line 39, in do_export
    f.write("c %i " % (mesh.vertex_colors.active.data[loop_index].color[0] * 255))
IndexError: bpy_prop_collection[index]: index 0 out of range, size 0

location: <unknown location>:-1

Any idea how to fix this?

$\endgroup$

1 Answer 1

1
$\begingroup$

Set it to Object mode before you begin:

bpy.ops.object.mode_set(mode='OBJECT')

...
I tried running your code. It doesn't do anything over here in any mode.

import bpy
def export(filepath):
  obj = bpy.context.object
  mesh = bpy.data.objects[obj.name]
  obj.data.calc_normals_split()

  with open(filepath, 'w') as f:
    for poly in obj.data.polygons:
      for loop_index in poly.loop_indices:
        loop = poly.loop_indices[loop_index]
        vert = mesh.data.vertices[loop]

        f.write("v %.4f %.4f %.4f\n" % vert.co[:])
        f.write("c %i " % (mesh.data.vertex_colors.active.data[loop_index].color[0] * 255))
        f.write("%i " % (mesh.data.vertex_colors.active.data[loop_index].color[1] * 255))
        f.write("%i\n" % (mesh.data.vertex_colors.active.data[loop_index].color[2] * 255))
        f.write("\n")

It throws: IndexError: range object index out of range
I don't think mesh.data.vertices is pointing to the right number though.

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .