Search code examples
pythonblenderverticesplane

Blender Python Script: Place/Connect Vertices by Global Co-ordinance


To extrude vertices, in editmode, you can simply Ctr+RMB and Blender automatically detects the mouse position and places a new connected vertex at that position.

I don't understand why I can't set the mouse position and then use the same function in the info window like this:

bpy.context.scene.cursor.location = (0.0, 0.0, 0.0) bpy.context.scene.cursor.location = (1,1,1) bpy.ops.mesh.dupli_extrude_cursor(rotate_source=True)

When I run that, I get the following error:

RuntimeError: Operator bpy.ops.mesh.dupli_extrude_cursor.poll() expected a view3d region & editmesh

I need it this way because the format of my object is in global co ordinance and I want to avoid interacting with the low-level functions for creating meshes since this is a script for high-level software.

EDIT>>>>

I attempted this with an operator:

import bpy


class MyExtrude(bpy.types.Operator):
    bl_idname = "wm.myextrude"
    bl_label = "Extrude Operator"



    def invoke(self, context, event):
        bpy.context.scene.cursor.location = (1,1,1)
        bpy.ops.mesh.dupli_extrude_cursor(rotate_source=True)
        return {'FINISHED'}


#weird workaround
classes = (MyExtrude,

          )

register, unregister = bpy.utils.register_classes_factory(classes)


if __name__ == "__main__":
    register()


bpy.ops.wm.myextrude('INVOKE_DEFAULT')

However it returns the same error:

RuntimeError: Operator bpy.ops.mesh.dupli_extrude_cursor.poll() expected a view3d region & editmesh


Solution

  • When an operator performs its task, it receives a context property telling it things like selected objects and which 3Dview it is working in. When you run a script in the text editor, the active viewport will be the text editor where 3d modeling operators cannot function.

    It is possible to override the context being sent to an operator, which allows us to run a script that works in the 3dviewport. Also note that the object needs to be in edit mode.

    You could also consider defining an operator and calling other operators from within. When your operator is started from within the 3dview, whether that is from searching for it, attaching it to a shortcut or adding a button in a panel, it will have the correct context to pass onto the other operators.